diff --git a/.github/workflows/ark-turn.yml b/.github/workflows/ark-turn.yml index 5a6cfc6295..bef2e62448 100644 --- a/.github/workflows/ark-turn.yml +++ b/.github/workflows/ark-turn.yml @@ -29,7 +29,7 @@ concurrency: jobs: adapter-contract: runs-on: ubuntu-latest - timeout-minutes: 10 + timeout-minutes: 15 strategy: matrix: python: ["3.11", "3.13"] diff --git a/.github/workflows/frontstage-pages.yml b/.github/workflows/frontstage-pages.yml index 80e1783366..0ef56a9f1d 100644 --- a/.github/workflows/frontstage-pages.yml +++ b/.github/workflows/frontstage-pages.yml @@ -12,6 +12,7 @@ on: - ".github/workflows/frontstage-pages.yml" - "README.md" - "README.zh-CN.md" + - "README.ja.md" - "apps/presentation/dashboard/**" - "scripts/chat_bundle.py" - "scripts/chat_bundle_launcher.mjs" @@ -56,6 +57,7 @@ on: - ".github/workflows/frontstage-pages.yml" - "README.md" - "README.zh-CN.md" + - "README.ja.md" - "apps/presentation/dashboard/**" - "scripts/chat_bundle.py" - "scripts/chat_bundle_launcher.mjs" diff --git a/.github/workflows/python-tests.yml b/.github/workflows/python-tests.yml index 2e9f6beac0..f6329b30dc 100644 --- a/.github/workflows/python-tests.yml +++ b/.github/workflows/python-tests.yml @@ -192,6 +192,7 @@ jobs: npm run smoke:chat-upgrade npm run smoke:delegation-search npm run smoke:task-inspector-route + npm run smoke:conversation-find - name: Qualify packaged team evidence and feedback recovery if: matrix.shard == 2 working-directory: apps/presentation/dashboard @@ -466,9 +467,11 @@ jobs: run: node scripts/check-css-custom-properties.mjs dashboard # The coverage merger consumes the unit report from shard 1 only. - - name: Measure Dashboard unit coverage once + - name: Check Dashboard startup ownership and measure unit coverage once if: matrix.shard == 1 - run: npm run test:dashboard:coverage + run: | + node --test examples/personal-workspace-browser/server-startup.test.mjs + npm run test:dashboard:coverage - name: Measure Dashboard browser interactions env: @@ -952,7 +955,7 @@ jobs: --basetemp "${{ runner.temp }}/lxb-${{ github.run_id }}-${{ github.run_attempt }}" tests/control_plane/test_cli_output_budget.py tests/control_plane/test_cli_output_differential.py - -k "stable_budget_fixture or long_path_budget or probe_process_failure_preserves_utf8_diagnostics" + -k "stable_budget_fixture or long_path_budget or probe_process_failure_preserves_utf8_diagnostics or pinned_reader_follows" - name: Qualify the native Windows CLI output differential timeout-minutes: 12 diff --git a/.github/workflows/runtime-snapshots.yml b/.github/workflows/runtime-snapshots.yml index 88c7948c24..bcfecbf17b 100644 --- a/.github/workflows/runtime-snapshots.yml +++ b/.github/workflows/runtime-snapshots.yml @@ -89,7 +89,39 @@ jobs: shell: bash run: | set -euo pipefail - revision="$(python -c 'import json; print(json.load(open("runtime/loopx-runtime.json"))["source_revision"])')" + # Validate the downloaded qualification before any remote mutation. + # Successful installation alone does not qualify outcome/cost claims. + revision="$(python - <<'PY' + import hashlib + import json + from pathlib import Path + import re + root = Path("runtime") + manifest_bytes = (root / "loopx-runtime.json").read_bytes() + manifest = json.loads(manifest_bytes) + revision = manifest["source_revision"] + if not isinstance(revision, str) or not re.fullmatch(r"[0-9a-f]{40}", revision): + raise SystemExit("Invalid runtime source revision") + qualification = json.loads((root / f"qualification-{revision}.json").read_bytes()) + checks = ("ok", "clean_install", "upgrade", "doctor", "skills", "frontend_bundle_contract", + "frontend_http", "no_frontend_build_tools", "license_notices", "activation_failure_restored") + if any(qualification.get(check) is not True for check in checks): + raise SystemExit("Runtime installation qualification is missing or failed") + if manifest["channel"] != "main" or any(qualification.get(key) != manifest[key] + for key in ("source_revision", "channel", "sha256")): + raise SystemExit("Runtime qualification does not match the candidate") + archive = root / f"loopx-runtime-{revision}.tar.gz" + with archive.open("rb") as stream: + digest = hashlib.file_digest(stream, "sha256").hexdigest() + if type(manifest["size"]) is not int or type(qualification.get("bytes")) is not int or ( + archive.stat().st_size != manifest["size"] or qualification["bytes"] != manifest["size"] + or digest != manifest["sha256"]): + raise SystemExit("Qualified runtime bytes differ from the candidate") + if (root / f"loopx-runtime-{revision}.json").read_bytes() != manifest_bytes: + raise SystemExit("Immutable runtime metadata differs from the channel candidate") + print(revision) + PY + )" # Keep each immutable snapshot below GitHub's per-release asset cap. # The existing channel release retains its historical assets and URL. tag="runtime-main-${revision}" diff --git a/README.ja.md b/README.ja.md new file mode 100644 index 0000000000..16fd08cfba --- /dev/null +++ b/README.ja.md @@ -0,0 +1,978 @@ +
+ +

LoopX 2.0

+ +LoopX — Trendshift が記録した GitHub Trending #1 + +**1 つのゴールから始めましょう。長時間にわたるエージェントの作業を検証可能に保ちます。** + +すでに使っている Agent に、やってほしいことを伝えるだけです。LoopX はゴール、 +進捗、意思決定、検証可能な結果を保持するため、セッションをまたいで作業を続けられます。
+Codex、Claude Code、DeepSeek Harness などのランタイムにまたがる 24 時間 365 日常駐エージェントのための、オープンでハーネス非依存のコントロールプレーンです。ローカルの SQLite ワークフローからマルチエージェントチームまでスケールします。 + +[![Release](https://img.shields.io/github/v/release/loopx-project/loopx?color=brightgreen)](https://github.com/loopx-project/loopx/releases/latest) [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE) [![TypeScript core](https://img.shields.io/badge/core-TypeScript-3178C6?logo=typescript&logoColor=white)](docs/architecture/rfcs/typescript-control-plane-migration-v0.md) [![Python](https://img.shields.io/badge/python-3.11%2B-blue.svg)](pyproject.toml) + +[![Local-first state](https://img.shields.io/badge/local--first-state-brightgreen.svg)](docs/public-private-boundary.md) [![Loop Agents](https://img.shields.io/badge/status-loop%20agents%20supported-brightgreen.svg)](docs/product/release-readiness.md) [![GitHub contributors](https://img.shields.io/github/contributors-anon/loopx-project/loopx?color=blue)](https://github.com/loopx-project/loopx/graphs/contributors) [![Discord](https://img.shields.io/badge/Discord-Join-5865F2?logo=discord&logoColor=white)](https://discord.gg/XmGgQyCFZd) [![Listed on dsh-plugin.org](https://dsh-plugin.org/badges/listed.svg)](https://dsh-plugin.org/plugins/loopx-project/loopx) + +[はじめる](#quick-start) · [なぜ LoopX なのか](#なぜ-loopx-なのか) · [24/7 常駐](#always-on-agents) · [動作を見る](#loopx-の動作を見る) · [エビデンス](#エビデンス) · [コントリビュート](#contributing) · [ドキュメント](https://loopx-project.github.io/loopx/docs/) · [English](README.md) · [简体中文](README.zh-CN.md) + +
+ +--- + + + +## 1 つのゴールから始める + +**1. LoopX を一度インストールします。** Python 3.11 以降と +Node.js 22.22.3 以降(24 LTS を推奨)が必要です。 + +```bash +python3 -m pip install --upgrade loopx && loopx workflow-skills --install +``` + +[インストールオプションとアップグレード](docs/guides/installing-loopx.md) + +**2. Agent に望む成果を伝えます。** Agent ホストを再起動してプロジェクトを開き、 +自然言語のゴールを 1 つ送ります: + +```text +$loopx speed up this project's slowest workflow; compare approaches and verify the gains +``` + +LoopX はそれを、目に見える計画、あなたの判断が必要な意思決定、そして必要に応じた検証へと変換します。 +Claude Code では `/loopx ` を使います。その他のランタイムについては +[ホストのセットアップ](#使っている-agent-から始める)をご覧ください。ガイド付きで最初の +実行を試したい場合は、[下のタスクから選んでください](#loopx-を試す)。 + +## 📰 ニュース + + + +- **2026-11-01 · 📘 [24/7 エージェントのための段階的コンテキスト配信](https://loopx-project.github.io/loopx/blog/context-delivery/)** — コンパクションサイクル単位の構造化差分と段階的ビューにより、モデル向けの 213 回の起床にわたってコントロールプレーンのバイト数を削減しました(単層の段階的ビューで `32.5%`、サイクル内の 112 回の継続にわたる積み重ね型の初回読み取りエントリで本文 `3.0%` / CLI `5.0%`)。同時に、ロスレスなベースライン復元も維持しています。 +- **2026-10-25 · 🤝 [長期タスク向けエージェント研究:共同研究者を募集中](https://loopx-project.github.io/loopx/blog/edgebench-feedback-and-memory/)** — EdgeBench と実世界のタスクにおけるフィードバック、再計画、再現可能な評価を通じて、**同一予算下での長期的な成果のブレークスルー**を探求しています。学術研究室や企業のチームとの共同研究を歓迎し、成果と総コストを比較していきます。[共同研究について話し合う](https://github.com/loopx-project/loopx/discussions)。 +- **2026-10-20 · 🚀 [LoopX 2.0](https://github.com/loopx-project/loopx/releases/tag/v2.0.0)** — 共有の TypeScript 状態レイヤーと、長期研究用ワークベンチ。[移行ガイド](docs/product/releases/v2.0.0.md) · [エンジニアリングの舞台裏](https://loopx-project.github.io/loopx/blog/typescript-control-plane-refactor/)。 +- **2026-10-14 · 🤖 [エージェント型ソフトウェア](https://loopx-project.github.io/loopx/blog/semantic-software-development/)** — ゴール、エビデンス、人間のフィードバックをエンジニアリングの成果物につなげます。 +- **2026-10-02 · 🧠 [長期ブートストラップと RSI](https://loopx-project.github.io/loopx/blog/long-horizon-rsi/)** — LoopX を使って LoopX を開発した 4 か月間:公開されているプロジェクトの歴史と、システムレベルの自己改善に関する設計上の視点。 +- **2026-09-18 · 🧪 [LoopX × LHTB](https://loopx-project.github.io/loopx/benchmarks/lhtb/)** — 同一モデルによる 46 タスクの研究が、**より多くの計算資源をより良い成果に変える**ことを実証的に裏付けました。LoopX 1.0.3 Heartbeat による継続実行の平均報酬は、Plain Codex より 17.3%、ネイティブ Goal より 10.6% 高くなりました。 +- **2026-09-06 · 🎉 [LoopX 1.0](https://github.com/loopx-project/loopx/releases/tag/v1.0.0)** — セッションをまたいでエージェントの作業を追跡し、意思決定に対応し、納品された結果を確認できる Personal Agent Workspace。[Workspace ガイド](https://github.com/loopx-project/loopx/blob/v1.0.0/docs/guides/personal-workspace-user-guide.md)。 +- **2026-08-02 · ⏱️ [200 時間超のトラジェクトリを X で公開](https://x.com/huangruiteng/status/2083904257494024425)** — 経過時間 200 時間超にわたるオーナー実行の初期事例が X で大きな注目を集め、実行、待機、人間の判断、復旧にまたがる作業を示しました。[トラジェクトリとその限界](#オープンソースの-issue-修正)。 + +[すべてのリリース](https://github.com/loopx-project/loopx/releases) + + + +## なぜ LoopX なのか + +最初の有用なアクションの前に、LoopX の内部を学ぶ必要はありません。 +デフォルトの進め方はゴールファーストです。望む成果を記述し、Agent に計画を +準備させ、意思決定やデバッグが必要になったときにだけ内部の仕組みを確認します。 + +エージェントは 1 つのセッションでタスクを完了できます。しかし長時間にわたる作業はもっと難しくなります。 +目的は変わり、オーナーの判断が必要になり、エビデンスは古くなり、エージェントは +作業を仲間に引き継ぎます。タイマーはループを動かし続けられますが、それだけでは有用になりません。 + +- **最初からやり直さずに続けられます。** ゴール、受け入れ済みの要件、 + 意思決定、エビデンスを、セッションや再起動をまたいで保持します。 +- **[コンテキストを失わずに連携できます。](https://loopx-project.github.io/loopx/blog/agent-facing-kanban/#walkthrough)** 委任された作業、依存する + 成果物、レビュー、返された結果を、責任の所在を明確にしたまま結び付けます。 +- **何が変わったかで進捗を判断できます。** 単なる活動量ではなく、成果物、裏付けとなる + エビデンスと反証となるエビデンス、コスト、次の意思決定を確認します。 + +モデルとツールは Agent ランタイムが提供します。LoopX の永続的な状態レイヤーは、 +エンジニアリング、研究、運用のために、ゴール、受け入れ基準、意思決定、オーナーシップ、エビデンスを +セッションやランタイムをまたいで保持します。エージェントと人間はそれらの事実を使って、 +次に何をすべきかを見直します。保護されたアクションは、引き続き人間の承認によって統制されます。 + + + +| やりたいこと | ここから始める | +| --- | --- | +| コーディングや研究のエージェントをセッションをまたいで働かせ続ける | [インストールして始める](#quick-start) | +| 個人のプロジェクト、スケジュール、意思決定を 1 か所で管理する | [Personal Agent Workspace](#personal-agent-workspace-の紹介) | +| インフラを自作せずに 24/7 常駐エージェントを構築する | [24/7 常駐エージェントのコントロールプレーン](#always-on-agents) | +| エージェント同士を連携させ、検証可能な結果を納品させる | [エージェント連携ガイド](docs/product/use-cases/cross-runtime/README.md) | + +LoopX は、永続的な作業状態を 1 つのコンパクトなレイヤーに保持します: + + + + ハーネスがターンを実行し、LoopX が作業を引き継ぎます。 + + +作業を実行するのは Agent ランタイムです。LoopX は、エンジニアリング、研究、探索、 +運用のループが実行をまたいで継続できるようにするための状態を保持します。これは +新たなエージェントフレームワークでも、特定プロバイダー向けのオーケストレーションランタイムでもありません。 + +
+詳細:コントロールレイヤーの仕組みと位置付け + + + + 単なるタイマーではなく、統制された状態遷移の詳細ビュー。 + + +わかりやすいメンタルモデルは、 +**[長時間作業のためのエージェントネイティブなカンバン](docs/development/control-plane-course/00-concept-primer.md)** です。 +カードはアイデンティティ、権限、エビデンス、継続情報を持ちます。カードの移動は、claim、gate、monitor、 +writeback などの検証済みオペレーターです。ボードは投影(プロジェクション)であり、 +信頼できる唯一の情報源は LoopX の状態です。 + +登録されたエージェントは対等な仲間です。claim、リース、タスク境界、ケイパビリティ、 +型付きの継続によって次に誰が動くかが決まり、永続的なリーダーのアイデンティティは +必要ありません。 + +LoopX は、次のようなものを実行するときに役立ちます: + +- 複数日にわたるエンジニアリング、研究、ベンチマーク、実験の目標 +- スコープ、エビデンス、レビュー状態を保持しなければならない Issue や PR のループ +- 定期的な heartbeat や監視の作業 +- オーナー、安全性、公開、プライベートデータのゲートがあるプロジェクト +- オーナーシップ、リース、引き継ぎが重要になる対等なエージェントのチーム +- 進捗がエンジニアではないオペレーターにも理解できる状態でなければならない、 + クリエイター、研究、運用のワークフロー + +LoopX は自律的な本番コントローラーではありません。危険な権限、 +公開、本番環境への書き込み、最終的なオーナーシップは人間に残ります。 + +
+ + + +### 5 つのサブシステムを自作せずに 24/7 常駐エージェントを構築する + +[Anthropic の *Building always-on agents*](https://claude.com/resources/articles/building-always-on-agents) +では、効果的な常駐エージェントは実時間のほとんどをトークン消費ゼロで +スリープして過ごし、周囲の 5 つのサブシステム(**Event Inbox**、**Timers**、**Memory**、**Permissions**、 +**Outbox**)にまたがる限定的な実行のために起床すると指摘しています。実際には、チームはエージェントホストごとに、 +cron スクリプト、JSON キュー、プロンプトのコンパクション、場当たり的な承認チェックといった壊れやすい +つなぎのコードを作り直しがちで、2 週目には気付かないうちの陳腐化、重複書き込み、ノイズの多いステータス通知に +悩まされることになります。 + +LoopX はそのオープンでハーネス非依存のコントロールレイヤーをパッケージ化しているため、 +すでに使っているランタイム(Codex CLI、Claude Code、DeepSeek Harness、カスタムランナー)を、 +明示的な永続性と人間によるゲートを備えた状態で 24 時間 365 日運用できます: + +| 常駐のためのプリミティブ | LoopX コントロールプレーンのサブシステム | 数週間にわたる実行で防げること | +| --- | --- | --- | +| **Event Inbox** | シングルフライトの **Goal / Todo / Hard Lease** キュー、非同期のアプリ受信箱、接続済みの Lark / GitHub リスナー | 同じリポジトリの状態を重複したワーカーが変更すること、実行中に人間の入力が失われること | +| **Timers & Wakeups** | **Guarded Heartbeat** と安全な定期プリセット(`daily-triage`、`changelog-draft`、`pr-watch`。`loopx preset list` で確認) | 何も変わっていない、またはゲートがまだ人間を待っているのに、やみくもな cron ループがトークンを浪費すること | +| **Memory & Compaction** | [`Decision Context`](loopx/capabilities/decision_context/README.md) によるソース追跡、コンパクションサイクル単位の **Progressive + Delta** [`context_delivery`](https://loopx-project.github.io/loopx/blog/context-delivery/)(213 回の起床にわたるビューで `32.5%`、サイクル内の 112 回の起床にわたる初回読み取りエントリで `3.0% / 5.0%`)、およびオプションの [`Reward Memory`](loopx/capabilities/reward_memory/README.md) | 気付かないうちのソースの陳腐化、コンパクションをまたいだプロンプトの再送の累積や差分の破損 | +| **Permissions & Deferred Calls** | 明示的な**オーナー、安全性、公開、プライベートデータのゲート**、分離されたワークツリー、レビュー可能な引き継ぎ | 自律的な cron 実行による外部への公開、強制マージ、プライベートなコンテキストの漏洩 | +| **Outbox** | 本当の完了、ブロッカー、未解決のゲートを示す、共有 Workspace と Lark の Goal/Decision/Evidence ビュー | 断片化したターミナルログや、人間に実行の子守りを強いるノイズの多い通知 | + +**個人のローカル利用からチーム・組織規模まで、1 つの契約セットで:** + +| 規模 | LoopX の動かし方 | 権限、連携、ガバナンスの姿勢 | +| --- | --- | --- | +| **個人開発者とローカルエージェント** | 外部インフラなしで `python3 -m pip install --upgrade loopx`。既存の CLI/デスクトップのランタイムを接続します | ハードリースを備えた正規のローカル **SQLite** ストア(既存の File セットアップも利用可)。アイドル時のトークン消費ゼロで、再起動やコンパクションを乗り越えます | +| **エンジニアリングチームとエンタープライズへの道筋** | 対等なワーカーが todo を claim し、Desktop Workspace、GitHub、Lark を通じて共有ゴール上でレビュー済みの成果物を返します([3 エージェントのデモ](examples/collaboration-delivery/README.md)) | ワーカーのオーナーシップと人間の承認ゲートを維持します。段階的な **PostgreSQL** リモート権限([プロバイダー](loopx/control_plane/coordination/postgresql_authority_store.ts))や、計画中の組織ガバナンス(RBAC、SSO、クォータ、署名付き監査)へと拡張できます。詳しくは[導入と SaaS のロードマップ](docs/product/roadmaps/saas-opportunity-assessment.md)をご覧ください | + +## LoopX の動作を見る + +企業のチーム、研究組織、個人開発者のための長期研究ワークベンチである LoopX 2.0。記録された研究履歴と、縮尺どおりに描き直したカウントリボンを、ラベル付きのアプリフレーム内に表示
+研究ワークベンチの動画を見る · 86 秒 · 文字起こし、字幕、出典。録画したアプリの抜粋、合成例、イラストにはラベルを付けています。 + + + +### 継続できる研究 + +ゴールを開くと、その作業、担当の Agent、記録された Explore の履歴を確認できます。 +**Deep analysis** を使うと、登録されたトラジェクトリ、その引用、ネイティブな +結果の読み戻し、個別に計測されたコストを確認できます。研究画面では、出典に紐付いた +[人間の注意](docs/reference/trajectory-assessment.md#human-attention-in-research-optional)も、 +記録された入力、タイミングのカバレッジ、確認可能な最適化ポイントとともに表示されます。ソースは Agent が準備します。 +ページを開いたり結果を読んだりしても、モデル呼び出しは始まりません。明示的な分析では、 +設定されたホストとアカウントが使われます。 + +裏付けられた発見、反証された発見、不明な発見を見える状態に保ちます。アプローチが +変更された理由や継続された理由を確認し、そのエビデンスを次の試行に持ち込みます。 + +### Personal Agent Workspace の紹介 + +長期的なゴールを 1 つのローカルファーストなワークスペースに保持します。ゴール、注意、 +会話、タスク、ファイル、スケジュール、復旧は、日をまたいでも、再起動しても、 +ハーネスが変わっても失われません。プロジェクトを再び開き、前のターンの状態と +エビデンスを確認して、次に許可されたアクションを続けます。 + +新しいデフォルトの Codex ゴールでは、タスクとワークスペースの権限を確認してから +**Create Goal and start first run** を確定します。元のタスクは、独立したチェックと実行枠の準備が整うと +元の会話の中で続行されます。通常のメッセージは読み取り専用のままです。待機、結果の読み戻し、 +復旧については[ワークスペースガイド](docs/guides/personal-workspace-user-guide.md#在原对话执行已检查的任务--run-the-checked-original-task)に +従ってください。 + +LoopX は、こうした長期的なコントロール状態を Personal Workspace にまとめます。1 か所で次のことができます: + +- 何があなたを必要としているか、何が実行中か、何が監視中か、何が + スケジュール済みまたは停止中かを確認する +- ゴールのケイパビリティを設定し、マシンのデフォルトとゴールごとの上書きを区別し、 + 適用前に変更をプレビューする +- 実行中のターンを誘導したり、メッセージをキューに入れたり、接続済みの Lark 会話から + 明示的な Goal/Agent/セッションのルーティングで非同期受信箱を使ったりする +- 納品されたファイル、定期レポート、それらを裏付けるエビデンスを確認する +- Codex、Claude Code、モデル直接利用、その他の登録済み Agent セッションをまたいで、 + ゴールの状態やエビデンスを失わずに作業を続ける +- 型付きのプレビュー、明示的な確認、受領記録を通じて保護された変更をレビューする。 + その間も、権威を持つのはブラウザーではなく LoopX の状態です + +Manager のグループ会話では、LoopX はメッセージの可視性とターンの権限を分けて +扱います。バイリンガルの [Lark Manager のコンテキストと権限の +契約](docs/reference/protocols/lark-manager-context-authority-v0.md)をご覧ください。 + +```bash +loopx dashboard +``` + +`loopx dashboard` がサポートされているブラウザー/PWA の起動方法です。ネイティブのデスクトップ版 +プレビューを[現在のリリース](https://github.com/loopx-project/loopx/releases/latest)からダウンロードすることもできます。 +これらは同じループバックサービスとゴールの状態を再利用します。Apple Silicon の macOS では、 +シェルと同梱のランタイムを組み合わせる署名付きのアプリ更新に加え、修復と +復旧にも対応しています。Python 3.11 以降が必要です。アプリは ad-hoc 署名のみで、公証はされていません。 +Windows の NSIS プレビューインストーラーは main チャネルで同じ署名付きの更新フローに対応しており、 +CLI は別途インストールします。stable チャネルと MSI でのインストールは +手動のままで、アプリのロールバックと修復は利用できず、インストーラーには +Authenticode 証明書がありません(Windows で SmartScreen の確認が表示される場合があります)。 +[デスクトップ版のインストール、更新、ソースからの開発](apps/desktop/loopx-control-plane/README.md)。 + +実際の Workspace の録画:子タスクの容量と、許可された責任範囲を設定する + +
+ケイパビリティ設定と再現可能なワークスペースのシナリオ + +ソースをチェックアウトした状態で `python -m demo.workspace serve` を実行すると、コミュニティ +イベント、家庭のエネルギー比較、地域の Web サイト公開の 3 つを試せます。それぞれに 4 つの +作業ロール、18 個のタスク、2 つの意思決定、2 つの監視があります。上のスクリーンショットは +この再現可能なワークスペースのものです。[シナリオとリプレイの手順](demo/workspace/README.md)。 + +
+ +[32 秒のウォークスルー全編を見る](docs/assets/personal-workspace/loopx-dashboard-launch.mp4) +· [ワークスペースガイドを読む](docs/guides/personal-workspace-user-guide.md) +· [5 分間のツアーを試す](docs/guides/personal-workspace-trial-guide.md) + +## LoopX を試す + +確認できる結果が得られるウォークスルーを選んでください: + +| 始めるもの | やること | +| --- | --- | +| [初めてのバグ修正ループ](docs/guides/first-bugfix-loop.md) | 小さな Python プロジェクトで 2 つのバグを再現し、Agent に修正させてから、テストとパッチを確認します。 | +| [長時間のコーディング作業](docs/guides/long-running-coding-agents.md) | Issue を修正したり、自分のリポジトリを改善し続けたりします。レビュー、エビデンス、復旧はセッションをまたいで引き継がれます。 | +| [Personal Agent Workspace(中国語)](docs/guides/personal-workspace-user-guide.md) | 図解ガイドに沿って、アプリでプロジェクト、会話、タスク、納品された結果を管理します。 | + +### 使っている Agent から始める + +[2 ステップのセットアップ](#quick-start)の後、プロジェクトで開いたセッションで +お使いのホスト用のエントリを使います: + +| ホスト | 開始と継続の確認 | +| --- | --- | +| Codex App | `$loopx `。[heartbeat オートメーションが保存されていること](docs/guides/first-bugfix-loop.md#confirm-that-it-actually-started)を確認します。 | +| Codex CLI | `$loopx `。生成された[ネイティブの `/goal`](docs/product/runtimes/codex-cli/codex-cli-packaged-install.md#current-user-path) を同じセッションで有効化します。 | +| Claude Code | `/loopx `。定期的な作業には[ループドライバーのセットアップ](docs/guides/newcomer-command-path.md#choose-the-loop-driver)に従います。 | +| DeepSeek Harness | [ネイティブの DSH プラグイン](packages/dsh-loopx-plugin/README.md)をインストールし、`loopx` スキルを選択してから、タスクを記述します | + +LoopX は既存のプロジェクト状態を再利用するか、プロジェクトを接続し、作業を +Todo として計画して、ホストの有効化をガイドします。アクティブなゴール、 +次の Todo、継続の仕組みを Agent に確認してもらってください。セットアップパケットだけではアクティブなループになりません。 +作業を続けるあいだは、ホストを利用可能な状態にしておいてください。`loopx status` はゴール、 +あなたを待っている意思決定、次の Todo を表示します。`loopx doctor` はインストールを診断します。 + +[LoopX のインストール](docs/guides/installing-loopx.md)では、ネイティブの Windows、`pipx`、 +アップグレード、ロールバック、アンインストールについて説明しています。 + +**1.x からアップグレードする場合は?** 既存のゴールを続ける前に、[2.0 の移行と復旧のガイド](docs/product/releases/v2.0.0.md)をお読みください。 + +
+その他のホスト、ループドライバー、カスタムランナー + +| ホスト | 推奨される開始方法 | ループドライバー | +| --- | --- | --- | +| Codex App | プロジェクトで開いたスレッドで `$loopx ` を実行するか、`/skills` から `loopx` を選びます。 | Codex App の heartbeat オートメーション。`quota should-run.scheduler_hint` から更新されます | +| Codex App over SSH | `loopx agent-onboard --agent-type codex-app-ssh --project .` | 返される可視の `/goal ` | +| Codex CLI | プロジェクトで `codex` を起動し、`$loopx ` または `/skills` を使います。 | 可視の `/goal `。デフォルトでは隠れたヘッドレス実行はありません | +| Claude Code | オプトインのアダプターをインストールし、`/loopx ` に続けて `/loop` を実行します。 | LoopX によってゲートされた、Claude Code ネイティブの `/loop` | +| KunlunCode | `loopx-kunluncode connect --project . --goal-id --agent-id ` を実行し、範囲を限定した todo を追加してから、`loopx-kunluncode run --project .` を実行します。 | app-server を介したネイティブの Goal Pro。LoopX は厳密な検証の後にのみ、完了とクォータを書き込みます | +| OpenCode | 静的なコマンドファサードをインストールし、定期的なゴールには `--with-goal-bridge` でオプトインします。 | OpenCode のコマンドファサードと明示的なゴールブリッジ | +| Pi | `loopx slash-commands --install --surface pi` でオプトインのゴール拡張をインストールし、信頼できる Pi セッションから `/loopx ` を使います。 | LoopX のクォータによってゲートされた可視の Pi ゴール拡張(`loopx_goal_activate` + `agent_settled` による継続) | +| ZCode | `loopx slash-commands --install --surface zcode` でスキルファサードをインストールし、プロジェクトの ZCode セッションから `$loopx` スキル(または `/loopx `)を呼び出します。 | ZCode セッション自身のターンループ。すべての継続は `quota should-run` を経由します | +| Antigravity CLI (agy) | `loopx slash-commands --install --surface agy` でスキルファサードをインストールし、プロジェクトの `agy` セッションから `loopx` スキル(または `/loopx `)を呼び出します。 | セッションのネイティブな `/goal` ループ(`` まで監査されます)と、セッションが生きている間の `schedule` による自己起床。ファサードは各ターン/起床で `quota should-run` を経由して再入するよう指示します。これは助言的なペース配分であり、ホストが強制するゲートではありません | +| Kiro CLI | `loopx slash-commands --install --surface kiro-cli` でスキルファサードをインストールし、プロジェクトの `kiro-cli` セッションから `/loopx ` を実行します。 | セッションのネイティブな `/goal --max Done when: ` ループ。ホストがゴール文から受け入れ基準を導出するため、基準はゴール文の中に記述します。ホスト自身の反復予算(デフォルトは 5)で制限され、組み込みの `goal` 完了契約によって確定されます。ファサードは各ターンと反復で `quota should-run` を経由して再入するよう指示します。これは助言的なペース配分であり、ホストが強制するゲートではありません | +| DeepSeek Harness (dsh) | [ネイティブの DSH プラグイン](packages/dsh-loopx-plugin/README.md)をインストールし、`loopx` スキルを選択して、タスクを記述します。ヘッドレスなターンには、引き続き [dsh goal-mode アダプター](loopx/dsh_goal_mode/README.md)を利用できます。 | ネイティブな同一セッション内での継続と GoalBar、またはヘッドレスな dsh セグメント。どちらも LoopX の権限によってゲートされます | +| Cursor、シェル、カスタムランナー | `loopx start-goal --guided --project . --goal-text ""` を実行するか、ランナーから LoopX を呼び出します。 | お使いのシェル、スケジューラー、ランナー | + +そのままコピーできるセットアップメッセージとホストの復旧手順は、 +[Getting Started](docs/guides/getting-started.md) にあります。ホスト連携では、 +[Codex App のホストコマンドレジストリ契約](docs/reference/protocols/codex-app-host-command-registry-v0.md)、 +[Codex CLI のパッケージインストール手順](docs/product/runtimes/codex-cli/codex-cli-packaged-install.md)、 +[Claude Code アダプター](loopx/claude_goal_mode/README.md)、 +[KunlunCode のネイティブ Goal アダプター](loopx/kunluncode_goal_mode/README.md)、 +[Kiro CLI の goal-mode アダプター](loopx/kiro_cli_goal_mode/README.md)、または +[DeepSeek Harness のターンアダプター](loopx/dsh_goal_mode/README.md)を確認できます。 + +ネイティブな手順については、[60 秒の DSH × LoopX Replan の録画と再現可能な +フィクスチャ](docs/showcases/cases/dsh-loopx-replan-demo.md)をご覧ください: +プラグインをインストールし、スキルを 1 つ選択し、重要な制約を変更して、 +保持された意思決定の記録を確認します。 + +カスタムランナーの場合は、まず +[最小限のカスタムランタイムの例](docs/guides/minimal-custom-runtime-example.md) +(`python3 examples/custom-runtime-minimal-cli-turn-smoke.py`)から始め、次に完全な +[Embed LoopX in Your Agent Runner](docs/guides/custom-agent-runner-integration.md) +ガイドと[ワーカーブリッジのインストール契約](docs/integrations/worker-bridge-install-contract.md)をご覧ください。 +コアとなる 1 回の tick は、意図的に小さくしています: + +```text +loopx quota should-run # should this registered agent act now? +loopx todo claim # who owns this slice? +loopx todo update # what changed? +loopx refresh-state # what should the next turn see? +loopx quota spend-slot # account for a completed, validated slice +``` + +クローンによるインストールは、ライブの canary ラッパーを使いたいコントリビューター向けです: + +```bash +git clone https://github.com/loopx-project/loopx ~/loopx +~/loopx/scripts/install-local.sh +loopx doctor +``` + +
+ +### 初回実行のフィードバック + +LoopX がうまく動いたら、1 分で書ける公開 Issue が、実際の初回実行がどのようなものかを +知る助けになります。これは任意で、テレメトリは含まれません。ログ、パス、認証情報、 +社内のプロジェクト名、ゴールの内容は含めないでください: + +- [初回実行のフィードバック](https://github.com/loopx-project/loopx/issues/new?template=first_run.yml) +- [長時間の実行についての利用事例](https://github.com/loopx-project/loopx/issues/new?template=usage_story.yml) + +`loopx first-run-report` は、何も送信せずに、同じ入力済みのリンクをローカルで +表示します。 + +基本的な利用統計は、初回利用時の告知の後、デフォルトで有効になります。プラットフォームのサポート状況と継続利用を把握するための、 +ランダム ID による 1 日 1 回の heartbeat と、それとは別の ID なしの CLI 利用回数です。 +コンテンツは収集しません。どちらも Settings → Capability Center、 +または `loopx usage-ping disable` / `LOOPX_USAGE_PING=0` で無効化できます。送信内容は +`loopx usage-ping status` で確認できます。[基本的な利用統計](docs/reference/usage-ping.md)をご覧ください。 + + + +## エビデンス + + + +### LHTB:同じモデルでより高い平均報酬 + +**LoopX 1.0.3 Heartbeat は、対応する 46 タスクで平均報酬 0.4948 を達成しました:** +**Plain Codex を 17.3% 上回り**、**ネイティブの Codex Goal を 10.6% 上回っています**。 +3 つとも GPT-5.6 Sol、最大の推論努力、Web Search 無効の条件で実行しています。 +[Long-Horizon Terminal-Bench](https://zli12321.github.io/LHTB/index.html) はコーディングにとどまりません。これらのタスクは、研究の +再現、科学シミュレーション、マルチモーダル分析、専門的な +ワークフロー、ゲーム、システム関連の作業にまたがります。 + +| 実行モード | 平均報酬 ↑ | 厳格な合格率(≥0.95) | 合格率(≥0.80) | +| --- | ---: | ---: | ---: | +| Plain Codex | 0.4218 | 7/46 (15.2%) | 12/46 (26.1%) | +| ネイティブの Codex Goal | 0.4475 | 4/46 (8.7%) | 14/46 (30.4%) | +| **LoopX 1.0.3 Heartbeat** | **0.4948** | **7/46 (15.2%)** | **15/46 (32.6%)** | + +≥0.80 のしきい値は補足的な事後の見方です。ベンチマークの厳格な解決しきい値は +引き続き ≥0.95 です。この研究にはちょうど 0.80 のスコアがないため、 +これらの件数は研究概要の >0.80 の見方とも一致します。 + +ネイティブの Goal と比べると、タスク単位の報酬は **23** タスクで改善、**13** タスクで同等、 +**10** タスクで悪化しました。厳格な解決数は Plain Codex と同じであるため、平均の向上は、 +すべてのタスクが改善したことや、Plain より多くのタスクが完全に解決されたことを +主張するものではありません。平均報酬は部分的な進捗も評価に含めます。 + +タスクとモードごとに有効な試行は 1 回です。指定された代替試行があり、 +ランタイムや予算は均等ではありません(一部の Heartbeat の代替試行にはより長い予算を含みます)。 +これらは観測されたシステムとしての結果であり、同一予算での効率の結果でも、 +LoopX の効果を単独で推定した因果的な推定値でもありません。 + +[インタラクティブな結果、タスクの比較、方法論](https://loopx-project.github.io/loopx/benchmarks/lhtb/) +· [5 アームの研究とその限界](benchmark/LHTB/studies/five-arm-gpt56sol-max/README.md) +· [公開されているタスク単位のスコア](benchmark/LHTB/studies/five-arm-gpt56sol-max/data.json) + +ベンチマーク以外にも、LoopX には確認可能な長期プロジェクトのエビデンスがあります。 +公開されている OpenViking へのコントリビューションの流れは、 +**ループの経過時間で 200 時間超**にわたり、 +範囲を限定したターン、意思決定、エビデンスの更新を保持しています。これはプロジェクトの実時間を +計測したものであり、連続したモデルの実行時間や無人での本番自律運用を示すものではありません。 +図を開くと、公開しても安全なタスクグラフ、エビデンスの分岐、 +ターンをまたいだ意思決定を確認できます。この事例には、出典と再現性の範囲が記載されています。 + +### オープンソースの Issue 修正 + +**200 時間超の公開コントリビューションの軌跡:PR の納品と再利用可能な修正知識が +ともに進化します。** + + + 焦点を絞った PR の納品と、再利用可能な LoopX のケイパビリティを結び付けた、オープンソースの Issue 修正のトラジェクトリ + + +
+コントリビューションの出典とエビデンスの範囲 + +LoopX の作者は、この手順を +[OpenViking のコントリビューター](https://github.com/volcengine/OpenViking/pulls?q=is%3Apr+author%3Ahuangruiteng)として使っています。 +示されている公開コントリビューションの流れは、最初の PR の作成から、示されている最新の +レビューまたは更新まで、経過時間で 200 時間を超えています。 +[Issue-Fix ケイパビリティ](loopx/capabilities/issue_fix/README.md)は、継続的に更新される +リポジトリのコンテキスト、リビジョンが刻まれた修正知識、レビュアー向けの +好みを分けて保持します。権威を持つのは、リンクされた PR と、現在のチェックアウトのソースおよびテストです。 + +
+ +### 実際のプロジェクトでの利用 + +- **独立したユーザー · `>13h` の C++ 精度改善の実行。** ユーザーの報告によると、 + 複数段階のタスクが一貫性を保ち、公開情報の調査を行い、 + [公開されているコードメモリツール](https://github.com/DeusData/codebase-memory-mcp)を採用し、 + 最終的な精度が向上しました。[エビデンスの範囲を読む](docs/showcases/cases/independent-cpp-accuracy-long-run.md)。 +- **独立したユーザー · `4d` の無人実行。** ユーザーの報告によると、4 日間 + 人間の介入なしに有用な作業が続き、定期レポートの画面も + 機能しました。[マスキング済みの事例を読む](docs/showcases/cases/independent-four-day-unattended-agent.md)。 +- **独立したユーザー · `7` 件のマージ済み PR。** LoopX によるものとされる Engine のリファクタリングが、 + [公開 Issue](https://github.com/zilliztech/mfs/issues/166) と + 7 件のマージ済み PR で確認できます。LoopX によるものという帰属と、報告された `1B+` トークンという規模は、ユーザーの + 報告に基づくものです。[事例を確認する](docs/showcases/cases/independent-public-engine-refactor.md)。 +- **独立したユーザー · vLLM の最適化がアップストリームにマージ。** + [Zheng Cai](https://x.com/zigzagcai/status/2109952174822408443) は、プロファイリング、調査、実験、 + 正確性チェックのワークフローエンジンとして LoopX を使ったと報告しています。[vLLM PR #54951](https://github.com/vllm-project/vllm/pull/54951) + では sparse-indexer の最適化がマージされました。報告されている総トークンスループットの **32.59%** の向上は、 + GLM-5.3-Flash、入力 1M トークン、4×H200、TP4、C1 の条件でのものです。 + [ワークフロー、すべての条件、エビデンスの範囲を確認する](docs/showcases/cases/independent-vllm-long-context-optimization.md)。 + +これらは注目の独立ユーザー事例 4 件であり、すべてではありません。コントリビューターの事例、 +作者自身によるドッグフーディング、再現可能なデモ、明示的なエビデンスの強度ラベルについては、 +[Showcase の完全なカタログ](docs/showcases/README.md)をご覧ください。 + +### 探索的なベンチマーク研究 + +- **[SWE-Marathon](https://loopx-project.github.io/loopx/benchmarks/swe-marathon/):** + 対応する 15 タスクで 5 つの実行モードを比較し、自己検証、スコア、 + コストを比べています。自己検証を増やしても、一貫して高いスコアにはなりませんでした。 +- **[LHTB × LoopX](https://loopx-project.github.io/loopx/benchmarks/lhtb/):** + [上記の結果](#lhtb-results)から、5 つの実行メカニズム、 + タスク単位の比較、悪化した事例、探索的なタスクタイプ分析へと続きます。 +- **[DeepSWE の行動分析](https://loopx-project.github.io/loopx/benchmarks/deepswe/behavior-discovery/)**(中国語): + 選ばれた事例をもとに、ドメインのヒントが要件の保持や + 検証の選択とどう関係するかを調べ、さらなる検証のためのメカニズムの仮説を示しています。 + +SWE-Marathon と LHTB は、タスクとモードごとに有効な試行が 1 回です。DeepSWE は +選ばれた事例と事後分析を用いています。 + +その他の確認できる情報: + +- 製品のストーリー、クイックスタート、長期実行のエビデンスについては + [公開ホームページ](https://loopx-project.github.io/loopx/) +- [Showcase の完全なカタログ](docs/showcases/README.md)と、その + [バイリンガルのホスト版インデックス](docs/showcases/index.html) +- 依存する成果物、独立したレビュー、返された結果については[エージェント連携ガイド](docs/product/use-cases/cross-runtime/README.md) +- 公開されている[ユーザーマニュアル](https://my.feishu.cn/wiki/CaL5wMk9ui17ngkWzeUcMlAYnZg) + + + +## ケイパビリティ + +必要な成果から始めましょう。オプションのケイパビリティは、同じゴール、 +作業のオーナーシップ、エビデンスを再利用します。それぞれのサポート状況と権限の範囲を確認してください。 + +### 製品ケイパビリティの進め方 + +ケイパビリティは、汎用的なプリミティブを、成果に責任を持つ作業レーンに変えます。 +成果から始め、現在登録されている実装とその書き込み範囲を +確認してください: + +| やりたいこと | ケイパビリティ | 始め方 | +| --- | --- | --- | +| 公開 Issue を、レビュー可能でエビデンスに裏付けられた変更にする | [Issue Fix](loopx/capabilities/issue_fix/README.md) | `loopx capability show issue-fix --format json` | +| 納品前に、最終的な差分そのものを適格性確認する | [Change Quality](loopx/capabilities/change_quality/README.md) | `loopx capability show change-quality-qualification --format json` | +| 定期レビューの前に、忙しいのにゴールから外れている作業ラウンドに気付く | [Progress-Review Sentinel](loopx/capabilities/progress_review/README.md) | `loopx capability show progress-review-sentinel --format json` | +| すでにレビュー済みのブランチの、変化し続けるスタックを保持する | [Integration Branch](loopx/capabilities/integration_branch/README.md) | `loopx capability show integration-branch-reconcile --format json` | +| 仮説や発見を失わずに、不確実な研究を探索する | [Explore](loopx/capabilities/explore/README.md) | `loopx capability show explore --format json` | +| 現在のエビデンスと検証済みの結果に基づいて意思決定を見直す | [Decision Context](loopx/capabilities/decision_context/README.md) | `loopx capability show decision-context --format json` | +| 受領記録付きで、定期的または進捗をきっかけにしたレポートを作成する | [Periodic Report](loopx/capabilities/periodic_report/README.md) | `loopx capability show periodic-report --format json` | + +インストール済みのリリースにおける正式なカタログは、`loopx capability list --format json` を実行すると確認できます。 +ケイパビリティの詳細には、ユーザーにとっての価値、成熟度、 +プロバイダーの準備状況、エントリコマンド、書き込み範囲、プロトコル、永続的な +検証が含まれます。成果から選ぶには[人が読めるケイパビリティのインデックス](loopx/capabilities/README.md)を参照し、 +プロバイダーをインストールまたは構築するときは [Extensions and Capabilities](docs/reference/extensions.md) を +使ってください。 + +### コントロールプレーンの中核となる約束 + +Kernel は、その仕組みを 5 つの問いにまとめています。それぞれの問いが、あらゆるエージェントハーネスの上で +1 つの製品上の約束を果たします:目的 → 長期的な状態、 +次 → 意味的な意思決定、人間の判断 → 人間とエージェントの協働、 +エビデンス → 復旧、継続 → ガバナンス。 + +| 問い | LoopX が見える状態に保つもの | +| --- | --- | +| 目的は何か? | アクティブなゴール、明示的なスコープ、現在の権限。 | +| 次に何が起こるか? | 順序付けられたユーザーとエージェントの todo、オーナーシップ、claim、リース。 | +| 人間の判断が必要なものは何か? | 曖昧な「オーナー待ち」ではなく、具体的なユーザーゲート。 | +| どのエビデンスが変わったか? | コンパクトな実行履歴、検証、ブロッカー、受け入れられた writeback。 | +| ループを続けてよいか? | クォータ、ケイパビリティ、安全なフォールバック、スケジューラーのヒント、停止条件。 | + +Goal の停止は `loopx goal-lifecycle --goal-id --operation stop` でプレビューできます。 +資格を元に戻すには `--operation resume` を使います。遷移を適用するには +`--actor-kind owner --execute` を使い、Goal のアクションビューから提供された場合は最新の `--expected-state-fingerprint` を付けたままにします。 +通常の CLI とスタンドアロンの +[`loopx-core`](packages/loopx-core/README.md) CLI は、同じライフサイクルオーナーを使います。 + +
+アーキテクチャ、コントロールプレーンの画面、ランタイムの責任 + +LoopX はアーキテクチャを明示的に保つことで、エージェントハーネスや外部プロバイダーが +変わっても、同じ統制された成果が生き残れるようにしています。以下の用語は、交換可能な +プラグインの種類ではなく、異なる境界を表しています: + +| 境界 | 意味 | 詳しく見る | +| --- | --- | --- | +| **Kernel** | 永続的なゴール、todo、ゲート、エビデンス、クォータ、復旧、スケジューリングの真実を管理します。 | [アーキテクチャ](docs/architecture.md) | +| **Capability** | LoopX の状態から、範囲が限定され検証可能な呼び出し元の成果を 1 つ生み出すための、安定したプロバイダー非依存の契約を定義します。 | [ケイパビリティのカタログ](loopx/capabilities/README.md) | +| **Provider** | 外部システムやローカルの実装を呼び出し、範囲が限定された観測、効果の結果、読み戻しを返します。 | [プロバイダーの責任](docs/reference/extensions.md#runtime-responsibilities) | +| **Extension** | 明示的なインストール、準備状況、有効化、アップグレード、無効化、ロールバックのライフサイクルを通じて、オプションのプロバイダーをパッケージ化して運用します。 | [Extension のライフサイクル](docs/reference/extensions.md#runtime-lifecycle) | + +`--available-capability shell` のようなホストの宣言は、観測された +実行サポートを表します。この製品マップでは、これらはランタイムの能力であり、製品の +ケイパビリティでも権限の付与でもありません。有効なケイパビリティは、遷移を提案する前に、 +引き続き独自のポリシーと権限のチェックを適用します。 + +### コントロールプレーンの画面 + +| 画面 | 役割 | 始め方 | +| --- | --- | --- | +| ゴールの状態とステータス | アクティブな状態、todo、claim、ゲート、エビデンス、実行履歴、最初の画面で注意すべき点を追跡します。 | `loopx status`、`loopx diagnose`、`loopx review-packet` | +| クォータとインタラクションの契約 | ターンで納品するか、尋ねるか、待つか、自己修復するか、静かにしているかを決定します。 | `loopx quota should-run`、[クォータの割り当て](docs/quota-allocation.md) | +| Agent ランタイムのブリッジ | Codex App、Codex CLI、Claude Code、汎用ワーカーを同じガードにそろえます。 | `loopx heartbeat-prompt`、`loopx codex-cli-bootstrap-message`、`loopx worker-bridge` | +| オペレーター向け画面 | ブラウザーを状態の権威にすることなく、コンパクトなステータスを表示します。 | `loopx serve-status`、[ダッシュボード](apps/presentation/dashboard/README.md) | +| セッションダッシュ | セッション、そのゴール、各ゴールのステータス/todo の進捗といったフリート全体の進捗を、結果の統計とともに追跡するライブの単一ページパネルを起動します。その場で自動更新されます。 | `loopx dash`、[セッションダッシュの設計](docs/product/surfaces/session-dash-panel-design.md) | +| 外部への投影 | LoopX を権威として保ったまま、todo とゲートをコラボレーション画面に投影します。 | `loopx lark-kanban`、[Lark Kanban アダプター](docs/integrations/lark-kanban-control-plane-adapter.md) | +| ドメインケイパビリティ | Issue 修正、コンテンツ運用、価値コネクターの計画、ML 実験のアドバイス、ベンチマークのエビデンス、Explore など、繰り返し可能な作業レーンをパッケージ化します。 | `loopx issue-fix`、`loopx content-ops`、`loopx value-connectors`、`loopx ml-experiment`、`loopx benchmark`、[Explore](loopx/capabilities/explore/README.md) | +| 実験的なコンテキスト学習 | 名前付きの登録済みエージェントが、無視される・デフォルトでオフのプロジェクト設定を通じて、プロバイダー非依存の Reward Memory を試せるようにします。OpenViking はプロバイダーの選択肢の 1 つであり、グローバルな依存関係ではありません。 | `loopx reward-memory experiment-status`、[Reward Memory のアーキテクチャ](loopx/capabilities/reward_memory/README.md) | +| ガバナンスのパターン | 再利用可能なルーティング、ゲート、エビデンス、投影、計画の形を記録します。 | [インタラクションパターン](docs/concepts/interaction-pattern-catalog.md)、[状態モデル](docs/state-interaction-model.md) | + +提供済みのプリミティブには、ライフタイムゴール、具体的なユーザーゲート、監査済みの安全な +フォールバック、対等な todo のオーナーシップ、クォータとステアリング、コンパクトな実行履歴、 +エビデンスに裏付けられた引き継ぎ、読み取り優先の管理画面、プロジェクトレベルの価値 +シグナル、公開/非公開の境界チェックが含まれます。 + +### ランタイムの責任 + +| 役割 | 責任 | +| --- | --- | +| **Agent** | ホスト/ランタイムを通じて、計画、分析、ツールの使用を行い、範囲を限定したアクションを 1 つ実行します。 | +| **Provider** | 外部システムを呼び出し、観測、効果の結果、読み戻しを返します。 | +| **Capability** | 呼び出し元の成果を定義し、プロバイダーの出力を正規化して検証し、型付きの遷移を提案します。 | +| **Kernel** | 永続的な todo、ゲート、監視、受け入れられた writeback、クォータ、復旧、スケジューリングを管理します。 | + +実行の経路は `Agent -> Capability -> Provider` で、制御の経路は +`Provider readback -> Capability transition -> Kernel` と戻ってきます。Extension は、 +オプションのプロバイダーをパッケージ化して管理する方法であり、コントロールプレーンの別の +オーナーではありません。[アーキテクチャ](docs/architecture.md)と +[Extensions and Capabilities](docs/reference/extensions.md) をご覧ください。 + +
+ +
+パーソナルエージェント、チーム、自己改善するワークフロー + +### パーソナルエージェント、チーム、自己改善するワークフロー + +[Meta Muse](https://about.fb.com/news/2026/09/introducing-muse-personal-ai-agent/)、 +[Grok Bot](https://x.ai/news/introducing-grok-bot)、そして +[Anthropic の *Building always-on agents*](https://claude.com/resources/articles/building-always-on-agents) +によって、常駐するパーソナルエージェントや、スリープ/起床によるイベント駆動の実行は、おなじみの製品 +およびアーキテクチャのモデルになっています。LoopX はこの領域に、すでに実行しているエージェントのための、オープンでプロバイダー非依存の +[24/7 コントロールプレーン](#always-on-agents)としてアプローチします。いずれかの製品を +置き換えるホスト型サービスではありません。 + +- **パーソナルエージェント:** 提供済みの Workspace と接続済みの Lark の画面を使って、 + ゴールを確認し、作業を誘導し、意思決定を解決します。 + [常駐スチュワードと意味的な引き継ぎの RFC](docs/architecture/rfcs/capable-manager-semantic-handoff-v0.md) + は、これをチームのための有能な 1 つの窓口へと拡張するものです。完全な体験は + まだ適格性確認中です。 +- **エージェントチーム:** ワーカーのオーナーシップを消すことなくゴールを共有します。claim、エビデンス、 + 明示的な返却によって、実装とレビューがつながった状態に保たれます。修正と 2 回のレビューラウンドを含む + 範囲を限定した例については、[3 エージェントの連携デモ](examples/collaboration-delivery/README.md)を + ご覧ください。 +- **自己改善するワークフロー:** [Reward Memory](loopx/capabilities/reward_memory/README.md) を通じて + フィードバックを次の試行につなげ、[Explore](loopx/capabilities/explore/README.md) を通じて + 変更候補を評価します。どちらもオプションです。**再帰的自己改善(RSI)** とのつながりは + 提案、テスト、レビュー、保持というエンジニアリングのループであり、LoopX が + 自律的なモデルの改善や複利的な能力向上を実証したと主張するものではありません。 + +パーソナルスチュワードはインタラクション上の役割であり、2 つ目の権威の源ではありません。 +バックグラウンドでの実行には、引き続き利用可能なホストと設定済みのランタイムが必要です。 +[全体のロードマップ](docs/architecture/rfcs/loopx-overall-roadmap-v0.md)では、 +提供済みの基盤と、次のエンドツーエンドの受け入れマイルストーンを分けて示しています。 + +
+ + + + +
+2.0 の背景と移行 + +| 共有のコントロールプレーン | 長期研究用ワークベンチ | +| --- | --- | +| 移行済みのトランザクション、権限、復旧のルールは TypeScript が担います。Python は実際のホスト/プロバイダーの IO と特殊な計算を引き続き担当します。 | 委任された作業、Explore の履歴、成果物、トラジェクトリ分析、次の意思決定を通じて、研究上の問いを追跡します。 | +| [2 か月間のエンジニアリング、ソースの履歴、主要な統計](https://loopx-project.github.io/loopx/blog/typescript-control-plane-refactor/) | [86 秒の動画を見る](https://github.com/user-attachments/assets/543af0b1-c3d4-4cfb-aedd-a68563a20601) · [分析の契約を読む](docs/reference/trajectory-assessment.md) | + +**1.x からアップグレードする場合は?** 2.0 では、昇格されていない Markdown のゴールへの通常の書き込みを廃止しています。 +それらのゴールを続ける前に、[移行と復旧のガイド](docs/product/releases/v2.0.0.md)を +確認してください。インストールによって既存の状態が黙って変換されることはありません。 + +
+ +## 高度な使い方 + +最初の有用なループには、すべてのオプション機能が必要なわけではありません。これらは作業で +必要になったときにだけ追加してください。 + +高度な機能を有効にする前に、現在のゴールの読み取り専用のケイパビリティカタログを +確認してください: + +```bash +loopx configure-goal --goal-id +``` + +`--execute` を付けなければ、このコマンドはプロジェクトの状態を変更せずに、現在/デフォルトの状態、適合性、範囲、 +コピーできるコマンドを報告します。 + +### 定期作業のプリセット + +安全なプリセットは、日次のトリアージ、changelog の下書き、PR の監視をカバーしています。まずは +[初心者向けプリセットガイド](docs/product/foundations/beginner-loop-presets.md)から始めてください。 + +```bash +loopx preset list +loopx preset show daily-triage +``` + +プリセットの確認は読み取り専用です。接続済みの定期的なゴールについては、 +`loopx ready-score --goal-id --agent-id ` が、 +ループを繰り返し実行する準備ができているかどうかを報告します。 + +### 統制されたターン + +LoopX は、検証済みの受領記録、最新のクォータ状態、プロバイダー非依存の予算から、 +純粋で範囲が限定されたターンの決定を 1 つ生成できます。現在の Codex CLI の +クイックスタートと有効化の契約は、 +[LoopX Turn for Codex CLI](docs/product/runtimes/codex-cli/loopx-turn-codex-cli-quickstart.md) に記載されています。 + +### Explore のグラフとハーネス + +Explore はサポートされているオプション機能で、デフォルトではオフです。タスクに +測定可能なオフライン評価、ベースライン、施策、ガードレールがある場合に最も効果を発揮します。 +本番環境の承認の代わりにはなりません。まずは +[Explore ケイパビリティ](loopx/capabilities/explore/README.md)と、その +[Lark での表示のマッピング](loopx/capabilities/explore/README.md#presentation-sink-lark-mapping)から始めてください。 + +### エージェントの作業をレビューする + +意思決定、エビデンス、検証、未解決のゲートを、オーナー向けにコンパクトに確認するには +`loopx review-packet` を使います。 +[インテリジェントな管理画面](docs/product/surfaces/intelligent-management-surface.md) +ではオペレーターのモデルを説明しており、 +[プロジェクトレベルの報酬モデル](docs/product/foundations/project-level-reward-model.md) +では、出力の量、品質、トークン +コスト、ユーザーの注意のコストにまたがる、控えめな価値シグナルを説明しています。 + +具体的な対等ワークフローについては、まず +[エージェント連携ガイド](docs/product/use-cases/cross-runtime/README.md)をご覧ください: +ビルダーがアナリストの成果物を使い、独立したレビューを受け、 +オーナーからの修正に対応して、確認済みの結果を返します。このガイドでは、 +実行可能な同一ホストの例と、以前のクロスランタイムの設計スケッチを区別しています。 + +### アプリと投影の使い方 + +- ローカルの読み取り優先 UI:[ダッシュボードガイド](apps/presentation/dashboard/README.md) +- 公開されている製品概要:[公開ホームページ](https://loopx-project.github.io/loopx/) +- ドキュメントポータル:[ホスト版ドキュメント](https://loopx-project.github.io/loopx/docs/) +- Feishu/Lark への投影:[Lark Kanban アダプター](docs/integrations/lark-kanban-control-plane-adapter.md) +- 汎用的なホスト連携:[連携ガイド](docs/integration.md) +- カスタムのマルチエージェントランナー: + [最小限のカスタムランタイムの例](docs/guides/minimal-custom-runtime-example.md)、 + 次に[カスタムランナーの連携](docs/guides/custom-agent-runner-integration.md) + +オプションの投影は状態を確認しやすくしますが、信頼できる情報源に +なるわけではありません。 + +### 運用と復旧 + +日々の確認は次のコマンドから始めます: + +```bash +loopx status +loopx history --goal-id your-project-goal +loopx quota should-run --goal-id your-project-goal +``` + +自動のターンは、まずクォータを確認し、検証済みの writeback の後にのみ消費を記録しなければなりません。 +静かなスキップ、事前チェックの失敗、ドライランのプレビューでは消費しません。 +ユーザーゲートが 1 つのレーンをブロックしている場合、別途監査された安全なフォールバックで +続行できることがありますが、ゲートを迂回してはいけません。 + +対等なエージェントは、納品の前に `loopx todo claim` を、検証の後に `loopx todo update` を使い、 +オーナーシップとエビデンスが見える状態を保ちます。 + +スケジューラーの周期は `quota should-run.scheduler_hint` に従います。インストール済みの Codex +App のオートメーションは、返された `ack_hint.cli_args` を通じて現在のヒントを確認応答します。 +衝突からの復旧、監視のセマンティクス、自己修復、 +正確なオペレーターコマンドは、 +[Getting Started](docs/guides/getting-started.md)、 +[Quota Allocation](docs/quota-allocation.md)、 +[Long-Task Cadence Policy](docs/operations/long-task-cadence-policy.md) で管理されています。 + +公開ドキュメントや例を公開する前に: + +```bash +loopx check \ + --scan-path README.md \ + --scan-path docs/ \ + --scan-path examples/ +``` + +## 現在の技術的方向性 + +LoopX には、3 つの進行中の戦略プログラムと、アーキテクチャおよび研究の +インキュベーターがあります。これらは方向性を示すものであり、納品の約束ではありません。提供済みの事実の情報源は、引き続き `main`、リリース済みの +成果物、安定したリファレンス契約です。 + +- **長期ベンチマークとエビデンス:** 相補的なベンチマーク環境にまたがる、 + 再現可能な能力のエビデンスと、制御されたメカニズムの研究。[方向性トラッカー](https://github.com/loopx-project/loopx/issues/3243) +- **オペレーター画面と IM 連携:** オペレーターのワークスペース、セッションの + 記録、範囲を限定したコラボレーション画面。Personal Workspace は + 提供済みで、統合されたスチュワード、実行、復旧の体験はまだ適格性確認中です。 + 実装リードは `@maxliux5` です。 + [方向性トラッカー](https://github.com/loopx-project/loopx/issues/3244) +- **共有ゴールの権限とクロスホストの連携:** 明示的に共有されたゴールのための、プロバイダー非依存の + 連携。NoKV は、新たなコントロールプレーンの権威ではなく、昇格前の + プロバイダー候補です。 + [方向性トラッカー](https://github.com/loopx-project/loopx/issues/3245) +- **アーキテクチャと研究のインキュベーター:** Effect Program の堅牢化、 + TypeScript への同等性を保った移行、階層的なストライド、研究の探索、 + 人間の注意、成果物のライフサイクル、メモリの有用性に関する作業。それぞれ成熟度は明示的に + 異なります。 + [方向性トラッカー](https://github.com/loopx-project/loopx/issues/3246) + +ステージ、昇格のゲート、コントリビューターが安全に取り組める切り口、オーナーシップの範囲については、正式な +[Technical Directions マップ](docs/project/technical-directions.md)をお読みください。コミュニティでの議論には、 +ピン留めされた [GitHub Discussion](https://github.com/loopx-project/loopx/discussions/2851) +を使ってください。コアとなるコントロールプレーンの信頼性は、これらのプログラムを支える +共通の基盤として継続されます。 + +## 高度なドキュメント + +[製品 Web サイト](https://loopx-project.github.io/loopx/) · [ブログ](https://loopx-project.github.io/loopx/blog/) · [Developer Book](https://loopx-project.github.io/loopx/docs/book/en/) + +現在のタスクに合った道筋から始めてください。公開されているドキュメントサイトには、ホスト版の +[ドキュメントポータル](https://loopx-project.github.io/loopx/docs/)を使ってください。 +[ドキュメントのインデックス](docs/README.md)は、引き続き完全なソースマップです。この一覧は +厳選したものです。より詳しいドキュメントやバージョン管理されたプロトコルは、各カテゴリのインデックスが管理しています。 + +### 使う・運用する + +- [Getting Started](docs/guides/getting-started.md):インストール、接続、 + 診断、日々のワークフロー、heartbeat、ダッシュボード、開発、コマンド。 +- [ユーザーマニュアル](https://my.feishu.cn/wiki/CaL5wMk9ui17ngkWzeUcMlAYnZg): + 公開されているオンボーディング、概念、FAQ、厳選した事例。 +- [運用](docs/operations/README.md):ゴールの継続、todo、周期、 + 注意、権限のワークフロー。 +- [Quota Allocation](docs/quota-allocation.md) と + [Heartbeat Automation Prompt](docs/heartbeat-automation-prompt.md):スケジューラーの + 実行可否、消費、スケジュールされた継続。 +- [ダッシュボード](apps/presentation/dashboard/README.md)と + [Status Data Contract](docs/status-data-contract.md):オペレーター向けの状態 + と投影の契約。 +- [Release Readiness](docs/product/release-readiness.md):インストール/更新の手順、 + 互換性のゲート、リリースノート、安心して依存できる画面。 + +### コントロールプレーンを理解する + +- [アーキテクチャ](docs/architecture.md):ライフタイムゴールの不変条件とカーネル。 +- [State Interaction Model](docs/state-interaction-model.md):アクター、ストア、 + インタラクションの契約、writeback。 +- [概念](docs/concepts/README.md):再利用可能なルーティング、ゲート、エビデンス、 + 投影、計画のパターン。 +- [Product Foundations](docs/product/foundations/README.md):Loop Engineering の + 原則、プロジェクトレベルの報酬、報酬スタイルの再計画。 +- [Product Vision](docs/product/vision.md):より広い Loop Agent の方向性。 + +### 連携する・拡張する + +- [連携ガイド](docs/integration.md) +- [最小限のカスタムランタイムの例](docs/guides/minimal-custom-runtime-example.md) +- [カスタムエージェントランナーの連携](docs/guides/custom-agent-runner-integration.md) +- [Integrations](docs/integrations/README.md):ワーカーブリッジや Lark を含む、ランタイム、ホスト、コラボレーション、 + 外部システムのアダプター。 +- [Extensions and Capabilities](docs/reference/extensions.md) + +### LoopX をビルドする・レビューする + +- [開発者ガイド](docs/development/README.md):コントリビューターのワークフロー、 + ベンチマークの開発、ドキュメントの構成、品質のゲート。 +- [リファレンスとプロトコル](docs/reference/README.md):ホストコマンドや Reward Memory の + アーキテクチャを含む、安定した契約とバージョン管理された実装プロトコル。 +- [コントロールプレーン開発者コース](docs/development/control-plane-course/README.md): + コードを中心とした中国語の講義 9 回。 +- [テストと品質](docs/development/testing-and-quality.md):検証の + レイヤーとリスクに基づくチェック。 +- [公開/非公開の境界](docs/public-private-boundary.md):安全なフィクスチャ、 + 例、エビデンス、公開。 + +### 成果を確認する + +- [Showcase カタログ](docs/showcases/README.md):公開しても安全な事例とエビデンスの + ラベル。 +- [研究とエビデンス](docs/research/README.md):ベンチマークの調査 + と出典に裏付けられた発見。 +- [Update Notes](docs/update-notes/README.md):公開しても安全な進捗メモ。 + +### プロジェクトとコミュニティ + +- [現在の技術的方向性](docs/project/technical-directions.md) +- [プロジェクトのガバナンス](.github/GOVERNANCE.md) +- [コントリビューション](CONTRIBUTING.md)と[コントリビューター向けタスク](docs/development/contributor-tasks.md) +- [作者とコントリビューター](docs/project/authors.md) +- [プロジェクトの歴史](docs/project/history.md) +- [名称と商標](docs/project/trademarks.md) +- [外部利用のためのブランドガイド](docs/project/brand-guide.md):プロジェクトや企業が LoopX、その連携、アートワークに言及する方法 +- [ADOPTERS](ADOPTERS.md):任意の自己申告による導入事例ディレクトリ +- [エコシステムでの導入](docs/community/ecosystem-adoption.md) - 私たちが観測・追跡している連携、 + サンプリング、派生プロジェクト + +## パートナープロジェクト + +LoopX は、長時間稼働するエージェントのエコシステムを築くために、他のオープンソースプロジェクトとの +協力を歓迎しています。確定しているパートナーは次のとおりです: + +- [OpenViking](https://github.com/volcengine/OpenViking) - AI エージェントのための + 自己進化するコンテキストデータベース +- [NoKV](https://github.com/NoKV-Lab/NoKV) - AI ネイティブな分散ファイルシステム + +## 現在のステータス + +LoopX は、長時間にわたるエージェントの作業のための実用的なローカルコントロールプレーンであり、 +より広い導入の段階に入りつつあります。完全なエージェントプラットフォーム、エージェントランタイム、 +自律的な本番コントローラーではありません。 + +現在の LoopX は、ゴール、型付きの todo と意思決定の +スコープ、対等な claim とリース、エビデンスと writeback、クォータを考慮したスケジューリング、 +ターンをまたいだ継続のための永続的な状態カーネルを提供しています。ガイド付きの開始、定期的な heartbeat、分離された Codex +CLI のターン、エビデンスに裏付けられた Issue-Fix の受け入れ、オプションの Explore と自動 +研究の手順、公開検証用の canary、複数プロジェクトの Personal +Workspace は、いずれもその共有のコントロール状態の上に構築されています。 + +サポートレベルは引き続き明示されています。状態と CLI の契約が安定した +中心であり、いくつかのホスト連携や高度な使い方は、オプション、デフォルトでオフ、 +または実験的なものです。LoopX は、認証情報を付与したり、破壊的な操作や +本番環境での操作を承認したり、承認なしにユーザーに代わって公開したり、 +検証されていない実行を成功のエビデンスに変えたりはしません。 + +現在の投資は、 +[Technical Directions マップ](docs/project/technical-directions.md)を通じて整理されています:長期 +ベンチマークのエビデンス、オペレーター画面と IM 連携、共有ゴールのクロスホスト +連携、そして明示的に段階分けされたアーキテクチャおよび研究のインキュベーターです。 + + + + +## コミュニティとコントリビューション + +長期的な Agent チームの働き方を一緒に形作りましょう。ワークフローを共有したり、 +バグを再現したり、連携を構築したり、Agent が成し遂げたことを紹介したりしてください。コード、 +ドキュメント、例、レビュー、慎重に範囲を限定したエビデンスの研究は、 +いずれも歓迎します。 + +- **学ぶ:** [ドキュメント](https://loopx-project.github.io/loopx/docs/) · + [ブログ](https://loopx-project.github.io/loopx/blog/) · + [技術的方向性](docs/project/technical-directions.md)。 +- **議論・共有する:** [GitHub Discussions](https://github.com/loopx-project/loopx/discussions) で、 + 質問したり、ワークフローを比較したり、プロジェクトを共有したりしてください。 +- **バグを報告する・機能を提案する:** バージョン、ホスト/ランタイム、期待される動作、公開しても安全な再現手順を添えて、 + [GitHub Issue](https://github.com/loopx-project/loopx/issues/new/choose) を + 作成してください。 +- **最初のコントリビューションをする:** [コントリビューター向けタスク](docs/development/contributor-tasks.md)から + 公開タスクを選ぶか、自己完結した修正を持ち込んでください。[コントリビューションガイド](CONTRIBUTING.md)では、セットアップ、 + 検証、PR のプロセスを説明しています。大きな変更は議論から始めてください。 +- **会話に参加する:** [Discord](https://discord.gg/XmGgQyCFZd) · + [Lark](docs/assets/loopx-lark-developer-group.png) · + [WeChat](docs/assets/loopx-wechat-contact.png)。 + +チャネルの使い分けと公式の情報源については [Support](.github/SUPPORT.md) を、コミュニティへの参加については +[行動規範](CODE_OF_CONDUCT.md)をご覧ください。 + +
+コード、ログ、例を共有する前に + +`.loopx/`、レガシーの `.codex/goals/`、ライブの `ACTIVE_GOAL_STATE.md`、生の Agent +セッションやベンチマークのトレース、認証情報、非公開のログ、社内リンク、 +機密性の高いユーザー/チームのデータ、オペレーターの成果物は、公開のコントリビューションに含めないでください。 + +
+ +### コントリビューター + +コード、ドキュメント、バグ報告、レビュー、実際の利用に基づくフィードバックで +貢献してくださっているすべての方に感謝します。皆さんのおかげで、長期的な Agent の作業は、より実行しやすく、 +確認しやすく、信頼しやすいものになっています。 + +[![LoopX GitHub contributors](https://contrib.rocks/image?repo=loopx-project/loopx&columns=12&max=120)](https://github.com/loopx-project/loopx/graphs/contributors) + +[すべての GitHub コントリビューター](https://github.com/loopx-project/loopx/graphs/contributors) · +[作者とコントリビューションの記録](docs/project/authors.md) · +[ガバナンス](.github/GOVERNANCE.md) · [プロジェクトの歴史](docs/project/history.md) · +[名称と商標](docs/project/trademarks.md)。 + +### コミュニティチャット + +

+ LoopX の Lark 開発者グループの QR コード + LoopX の WeChat 連絡先の QR コード +

+

+ Lark:スキャンして直接参加できます
WeChat:huangrt00 · 友だち申請の際に LoopX と書き添えてください
+

+ +## Star の推移 + +

+ 検証済みのスナップショットに基づく LoopX の GitHub スター数の推移
+ リポジトリで承認されたワークフローを使い、GitHub 公式の stargazer のタイムスタンプから 6 時間ごとに生成しています。スナップショットは、取得した行数が GitHub の現在のスター数と一致した場合にのみ公開されます。GitHub の画像キャッシュにより、更新が遅れることがあります。 +

+ +## ライセンス + +Copyright 2026 LoopX contributors. 作者は +[`@huangruiteng`](https://github.com/huangruiteng) です。公開されている +[作者とコントリビューターの記録](docs/project/authors.md)をご覧ください。 + +`v0.4.8` 以降は Apache License 2.0 です。[LICENSE](LICENSE) と +[NOTICE](NOTICE) をご覧ください。`v0.4.7` までのリリースは、元の MIT の +条件のままです。その歴史的なテキストと告知は +[LICENSE-MIT](LICENSE-MIT) に保存されています。[ライセンスポリシー](docs/project/licensing.md)では、 +バージョン、コントリビューション、特許許諾、オープンコアの範囲について説明しています。 + +AI による生成、コードの書き換え、言語間の翻訳、 +プロジェクト名の変更を根拠に、適用されるライセンスの下での著作権、帰属表示、 +NOTICE の保持の要件を削除したり回避したりしてはなりません。配布される +素材が LoopX の派生物である場合、それらの義務は引き続き適用されます。この +説明は、適用されるライセンスで許可されている改変や再配布を制限するものではありません。[再利用と帰属表示](docs/project/licensing.md#reuse-ports-and-attribution) +と[名称と商標のガイダンス](docs/project/trademarks.md)をご覧ください。派生物の +配布物を LoopX の公式リリースとして提示してはなりません。 + +[osai-verify: eb42dd9cf910399988f0]: # diff --git a/README.md b/README.md index 95aea82cc4..7c74e0c5f7 100644 --- a/README.md +++ b/README.md @@ -6,16 +6,15 @@ **Start with one goal. Keep long-running agent work verifiable.** -Tell the Agent you already use what you want done. LoopX keeps the goal, work, -needed decisions and verifiable results durable behind the scenes, so the next -session can continue without making you learn LoopX internals first.
-Work with Codex, Claude Code, DeepSeek Harness and other runtimes. Advanced docs still expose the local-first architecture, ownership model and research workbench. +Tell your agent what you want to accomplish. LoopX preserves goals, +progress, decisions and verifiable results so work can continue across sessions.
+An open, harness-neutral control plane for 24/7 always-on agents across Codex, Claude Code, DeepSeek Harness and other runtimes—scaling from local SQLite workflows to multi-agent teams. [![Release](https://img.shields.io/github/v/release/loopx-project/loopx?color=brightgreen)](https://github.com/loopx-project/loopx/releases/latest) [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE) [![TypeScript core](https://img.shields.io/badge/core-TypeScript-3178C6?logo=typescript&logoColor=white)](docs/architecture/rfcs/typescript-control-plane-migration-v0.md) [![Python](https://img.shields.io/badge/python-3.11%2B-blue.svg)](pyproject.toml) [![Local-first state](https://img.shields.io/badge/local--first-state-brightgreen.svg)](docs/public-private-boundary.md) [![Loop Agents](https://img.shields.io/badge/status-loop%20agents%20supported-brightgreen.svg)](docs/product/release-readiness.md) [![GitHub contributors](https://img.shields.io/github/contributors-anon/loopx-project/loopx?color=blue)](https://github.com/loopx-project/loopx/graphs/contributors) [![Discord](https://img.shields.io/badge/Discord-Join-5865F2?logo=discord&logoColor=white)](https://discord.gg/XmGgQyCFZd) [![Listed on dsh-plugin.org](https://dsh-plugin.org/badges/listed.svg)](https://dsh-plugin.org/plugins/loopx-project/loopx) -[Get started](#quick-start) · [Why LoopX](#why-loopx) · [See it in action](#see-loopx-in-action) · [Evidence](#evidence) · [Contribute](#contributing) · [Docs](https://loopx-project.github.io/loopx/docs/) · [简体中文](README.zh-CN.md) +[Get started](#quick-start) · [Why LoopX](#why-loopx) · [24/7 Always-On](#always-on-agents) · [See it in action](#see-loopx-in-action) · [Evidence](#evidence) · [Contribute](#contributing) · [Docs](https://loopx-project.github.io/loopx/docs/) · [简体中文](README.zh-CN.md) · [日本語](README.ja.md) @@ -54,6 +53,7 @@ run? [Choose a task below](#try-loopx). not news. Keep both languages aligned, newest first, using verified publication dates (UTC). --> +- **2026-11-01 · 📘 [Progressive context delivery for 24/7 agents](https://loopx-project.github.io/loopx/blog/context-delivery/)** — Compaction-cycle structured deltas and progressive views cut control-plane bytes across 213 model-facing wakes (`32.5%` single-layer progressive view; `3.0%` body / `5.0%` CLI stacked first-read entry across 112 in-cycle continuations) while preserving lossless baseline recovery. - **2026-10-25 · 🤝 [Long-horizon agent research: collaborators welcome](https://loopx-project.github.io/loopx/blog/edgebench-feedback-and-memory/)** — Exploring **breakthroughs in long-horizon outcomes under equal budgets**, through feedback, replanning and reproducible evaluation on EdgeBench and real-world tasks. Academic labs and industry teams are welcome to collaborate, comparing outcomes and total cost. [Discuss collaboration](https://github.com/loopx-project/loopx/discussions). - **2026-10-20 · 🚀 [LoopX 2.0](https://github.com/loopx-project/loopx/releases/tag/v2.0.0)** — A shared TypeScript state layer and long-horizon research workbench. [Migration guide](docs/product/releases/v2.0.0.md) · [Engineering story](https://loopx-project.github.io/loopx/blog/typescript-control-plane-refactor/). - **2026-10-14 · 🤖 [Agentic software](https://loopx-project.github.io/loopx/blog/semantic-software-development/)** — Connecting goals, evidence and human feedback to engineering delivery. @@ -96,6 +96,7 @@ protected actions. | --- | --- | | Keep a coding or research agent working across sessions | [Install and start](#quick-start) | | Manage personal projects, schedules and decisions in one place | [Personal Agent Workspace](#meet-the-personal-agent-workspace) | +| Wire up a 24/7 always-on agent without hand-rolling infra | [24/7 Always-On Agent Control Plane](#always-on-agents) | | Let agents collaborate and deliver verifiable results | [Agent collaboration guide](docs/product/use-cases/cross-runtime/README.md) | LoopX keeps the durable work state in one compact layer: @@ -142,6 +143,37 @@ publishing, production writes, and final ownership stay with the human. + + +### Building 24/7 Always-On Agents Without Hand-Rolling the 5 Subsystems + +[Anthropic's *Building always-on agents*](https://claude.com/resources/articles/building-always-on-agents) +notes that effective persistent agents spend most of their wall-clock life +asleep at zero tokens and wake for bounded runs across five surrounding +subsystems: **Event Inbox**, **Timers**, **Memory**, **Permissions**, and an +**Outbox**. In practice, teams often re-build fragile glue—cron scripts, JSON +queues, prompt compaction, and ad-hoc approval checks—for every agent host, only +to hit silent staleness, duplicate writes, or noisy status spam by week two. + +LoopX packages that open, harness-neutral control layer so the runtimes you +already use (Codex CLI, Claude Code, DeepSeek Harness, or custom runners) can +operate 24/7 with explicit durability and human gates: + +| Always-on primitive | LoopX control-plane subsystem | What it prevents in multi-week runs | +| --- | --- | --- | +| **Event Inbox** | Single-flight **Goal / Todo / Hard Lease** queue, async app inbox, and connected Lark / GitHub listeners | Duplicate workers mutating the same repo state; dropped human inputs mid-run | +| **Timers & Wakeups** | **Guarded Heartbeat** and safe recurring presets (`daily-triage`, `changelog-draft`, `pr-watch`; inspect via `loopx preset list`) | Blind cron loops burning tokens when nothing changed or a gate is still waiting on a human | +| **Memory & Compaction** | [`Decision Context`](loopx/capabilities/decision_context/README.md) source tracking, compaction-cycle **Progressive + Delta** [`context_delivery`](https://loopx-project.github.io/loopx/blog/context-delivery/) (`32.5%` view across 213 wakes; `3.0% / 5.0%` first-read entry across 112 in-cycle wakes), and optional [`Reward Memory`](loopx/capabilities/reward_memory/README.md) | Silent source staleness; compounding prompt replay or broken deltas across compaction | +| **Permissions & Deferred Calls** | Explicit **owner, safety, publication, and private-data gates**, isolated worktrees, and review-ready handoffs | Autonomous cron runs publishing externally, forcing merges, or leaking private context | +| **Outbox** | Shared Workspace & Lark Goal/Decision/Evidence views surfacing genuine completions, blockers, and open gates | Fragmented terminal logs and high-noise pings that force humans to babysit runs | + +**Solo local to team & organizational scale—on one set of contracts:** + +| Scale | How LoopX runs | Authority, collaboration & governance posture | +| --- | --- | --- | +| **Solo developer & local agent** | `python3 -m pip install --upgrade loopx` with zero external infrastructure; connect your existing CLI/Desktop runtime | Canonical local **SQLite** store with hard leases (plus existing File setups), surviving restarts and compaction at zero idle tokens | +| **Engineering team & enterprise path** | Peer workers claim todos and return reviewed artifacts on shared Goals via Desktop Workspace, GitHub, and Lark ([three-agent demo](examples/collaboration-delivery/README.md)) | Preserves worker ownership and human approval gates; extends to staged **PostgreSQL** remote authority ([provider](loopx/control_plane/coordination/postgresql_authority_store.ts)) and planned org governance—RBAC, SSO, quotas, signed audit—in the [adoption & SaaS roadmap](docs/product/roadmaps/saas-opportunity-assessment.md) | + ## See LoopX in Action LoopX 2.0, the long-horizon research workbench for enterprise teams, research organizations and independent builders; recorded research history with count ribbons redrawn to scale in a labelled App frame
@@ -153,7 +185,9 @@ publishing, production writes, and final ownership stay with the human. Open a Goal to inspect its work, responsible Agents and recorded Explore history. Use **Deep analysis** to inspect a registered trajectory, its citations, native -outcome readback and separately measured costs. An Agent prepares the source; +outcome readback and separately measured costs. Research also shows source-bound +[human attention](docs/reference/trajectory-assessment.md#human-attention-in-research-optional), +with recorded inputs, timing coverage and inspectable optimization points. An Agent prepares the source; opening a page or reading a result does not start a model call. Explicit analysis uses the configured host and account. @@ -167,6 +201,12 @@ conversations, tasks, files, schedules, and recovery stay durable across days, restarts, and harnesses. Reopen a project, inspect the previous turn’s state and evidence, and continue the next permitted action. +For a new default Codex Goal, review the task and workspace permission before +confirming **Create Goal and start first run**. The original task continues in +its original conversation when independent checks and allowance are ready; +ordinary messages remain read-only. Follow the [workspace guide](docs/guides/personal-workspace-user-guide.md#在原对话执行已检查的任务--run-the-checked-original-task) +for waiting, result readback and recovery. + LoopX brings these long-horizon control states into the Personal Workspace. It gives you one place to: - see what needs you, what is running, what is being watched, and what is @@ -488,6 +528,12 @@ evidence → recovery; continuation → governance. | What evidence changed? | Compact run history, validation, blockers, and accepted writeback. | | May the loop continue? | Quota, capabilities, safe fallback, scheduler hints, and stop conditions. | +Preview a Goal stop with `loopx goal-lifecycle --goal-id --operation stop`; +use `--operation resume` to restore eligibility. Apply the transition with +`--actor-kind owner --execute`, retaining a fresh `--expected-state-fingerprint` +when supplied by the Goal actions view. The ordinary and standalone +[`loopx-core`](packages/loopx-core/README.md) CLI use the same lifecycle owner. +
Architecture, control-plane surfaces and runtime responsibilities @@ -548,11 +594,13 @@ owner. See [Architecture](docs/architecture.md) and ### Personal Agents, Teams, and Self-Improving Workflows -[Meta Muse](https://about.fb.com/news/2026/09/introducing-muse-personal-ai-agent/) -and [Grok Bot](https://x.ai/news/introducing-grok-bot) make persistent personal -agents and delegated work a familiar product idea. LoopX approaches that space -as an open, provider-neutral control plane for agents you already run—not as a -hosted replacement for either product. +[Meta Muse](https://about.fb.com/news/2026/09/introducing-muse-personal-ai-agent/), +[Grok Bot](https://x.ai/news/introducing-grok-bot), and +[Anthropic's *Building always-on agents*](https://claude.com/resources/articles/building-always-on-agents) +make persistent personal agents and sleep/wake event-driven runs a familiar product +and architecture model. LoopX approaches that space as an open, provider-neutral +[24/7 control plane](#always-on-agents) for agents you already run—not as a hosted +replacement for either product. - **Personal agent:** use the shipped Workspace and connected Lark surfaces to inspect goals, steer work and resolve decisions. The diff --git a/README.zh-CN.md b/README.zh-CN.md index e658f8f251..0bfad065b2 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -6,15 +6,15 @@ **从一个目标开始,让长程 Agent 工作可验证。** -告诉你已经在用的 Agent 想完成什么。LoopX 在幕后持久保留目标、 -工作、审批与证据,让下一轮会话可以继续,而不要求你先学会 LoopX 内部机制。
-连接 Codex、Claude Code、DeepSeek Harness 等运行时。高级文档仍会展开本地优先语义内核、ownership 模型与研究工作台。 +告诉你已经在用的 Agent 想完成什么。LoopX 保存目标、进展、决策与可验证成果, +让工作在不同会话间持续推进。
+面向 7×24 常驻在线 Agent 的开源、Harness 中立控制面——连接 Codex、Claude Code、DeepSeek Harness 等运行时,从个人本地 SQLite 平滑延伸到多 Agent 团队协作。 [![Release](https://img.shields.io/github/v/release/loopx-project/loopx?color=brightgreen)](https://github.com/loopx-project/loopx/releases/latest) [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE) [![TypeScript core](https://img.shields.io/badge/core-TypeScript-3178C6?logo=typescript&logoColor=white)](docs/architecture/rfcs/typescript-control-plane-migration-v0.zh-CN.md) [![Python](https://img.shields.io/badge/python-3.11%2B-blue.svg)](pyproject.toml) [![Local first](https://img.shields.io/badge/control--plane-local--first-brightgreen.svg)](docs/public-private-boundary.md) [![Loop Agents](https://img.shields.io/badge/status-loop%20agents%20supported-brightgreen.svg)](docs/product/release-readiness.md) [![GitHub contributors](https://img.shields.io/github/contributors-anon/loopx-project/loopx?color=blue)](https://github.com/loopx-project/loopx/graphs/contributors) [![Discord](https://img.shields.io/badge/Discord-Join-5865F2?logo=discord&logoColor=white)](https://discord.gg/XmGgQyCFZd) [![Listed on dsh-plugin.org](https://dsh-plugin.org/badges/listed.svg)](https://dsh-plugin.org/plugins/loopx-project/loopx) -[快速上手](#快速开始) · [为什么需要 LoopX](#为什么需要-loopx) · [看看实际使用](#看看-loopx-如何工作) · [证据与案例](#证据) · [参与贡献](#贡献) · [文档](https://loopx-project.github.io/loopx/docs/) · [English](README.md) +[快速上手](#快速开始) · [为什么需要 LoopX](#为什么需要-loopx) · [7×24 常驻架构](#always-on-agents) · [看看实际使用](#看看-loopx-如何工作) · [证据与案例](#证据) · [参与贡献](#贡献) · [文档](https://loopx-project.github.io/loopx/docs/) · [English](README.md) · [日本語](README.ja.md) @@ -50,6 +50,7 @@ LoopX 会按需把它变成可见的任务、决策门和证据。Claude Code not news. Keep both languages aligned, newest first, using verified publication dates (UTC). --> +- **2026-11-01 · 📘 [面向 7×24 Agent 的渐进式上下文交付](https://loopx-project.github.io/loopx/blog/zh/context-delivery/)** — 受 Compaction 周期约束的结构化差分与按需视图在 213 次模型唤醒中将单层渐进载荷降至原文 `32.5%`,112 次同周期续跑的叠加首读入口降至 `3.0%` 正文 / `5.0%` 含封装,同时保留压缩失配时原子回切完整基线的能力。 - **2026-10-25 · 🤝 [长程 Agent 研究:欢迎学术与企业合作者](https://loopx-project.github.io/loopx/blog/zh/edgebench-feedback-and-memory/)** — 探索**等预算下的长期效果突破**:围绕 EdgeBench 和真实长程任务,研究反馈、重规划与可复现评测,同时核对效果与完整成本。欢迎学术与企业团队合作。[交流合作](https://github.com/loopx-project/loopx/discussions)。 - **2026-10-20 · 🚀 [LoopX 2.0](https://github.com/loopx-project/loopx/releases/tag/v2.0.0)** — 共享 TypeScript 控制面与长程研究工作台。[迁移指南](docs/product/releases/v2.0.0.md#中文指南) · [重构历程](https://loopx-project.github.io/loopx/blog/zh/typescript-control-plane-refactor/)。 - **2026-10-14 · 🤖 [Agentic Software](https://loopx-project.github.io/loopx/blog/zh/semantic-software-development/)** — 连接目标、证据、人的反馈与工程交付。 @@ -82,6 +83,7 @@ LoopX 会按需把它变成可见的任务、决策门和证据。Claude Code | --- | --- | | 让编程或研究 Agent 跨会话持续干活 | [安装并开始](#快速开始) | | 在一个入口管理个人项目、定时任务与待决事项 | [个人 Agent 工作区](#认识个人-agent-工作区) | +| 不从零手搓基础设施,直接搭建 7×24 常驻在线 Agent | [7×24 常驻 Agent 控制面](#always-on-agents) | | 让多个 Agent 分工协作,交付可验收的结果 | [Agent 协作指南](docs/product/use-cases/cross-runtime/README.md#中文指南) | LoopX 把长期控制状态留在同一层紧凑状态里: @@ -126,6 +128,29 @@ LoopX 不是生产自动化控制器。危险权限、生产写入、公开发
+ + +### 搭建 7×24 常驻在线 Agent:无需从零手搓 5 大底层组件 + +[Anthropic 在《Building always-on agents》中指出](https://claude.com/resources/articles/building-always-on-agents),真正能长期稳定运行的常驻 Agent 大部分时间其实在**零 Token 休眠**,只在事件到来时被唤醒执行一轮有界工作,围绕 **Event Inbox、Timers、Memory、Permissions、Outbox** 五个底层原语运转。现实工程中,团队常常为每个宿主机重复手搓 cron 脚本、JSON 队列、Prompt 压缩和临时审批检查,运行几周后还是会在状态过期、重复写入或消息刷屏中翻车。 + +LoopX 把这套**开源、Harness 中立**的控制面直接做成可运行基础设施,让 Codex CLI、Claude Code、DeepSeek Harness 或自研运行时共享持久状态与人工决策门: + +| 常驻 Agent 原语 | LoopX 对应控制面子系统 | 解决跨周运行中的哪类故障 | +| --- | --- | --- | +| **Event Inbox(事件收件箱)** | Single-flight **Goal / Todo / Hard Lease** 队列、异步对话收件箱,以及飞书 / GitHub 事件监听 | 多 Worker 并发踩踏同一份仓库状态;运行中途用户消息丢失 | +| **Timers(定时与唤醒)** | **Guarded Heartbeat** 与安全周期预设(`daily-triage`、`changelog-draft`、`pr-watch`,可用 `loopx preset list` 只读查看) | 盲目 cron 在零增量或人门尚未批准时反复唤醒模型白烧 Token | +| **Memory(记忆与压缩恢复)** | [`Decision Context`](loopx/capabilities/decision_context/README.md) 来源追踪、受 Compaction 周期约束的 **Progressive + Delta** [`context_delivery`](https://loopx-project.github.io/loopx/blog/zh/context-delivery/)(213 次唤醒中单层渐进降至原文 `32.5%`,112 次同周期续跑首读降至原文 `3.0% / 5.0%`),以及可选 [`Reward Memory`](loopx/capabilities/reward_memory/README.md) | 数据源过期却一路亮绿灯;上下文压缩后全量重放或差分悬空 | +| **Permissions(权限与延后批准)** | 显式 **Owner / 安全 / 公开发布 / 私有数据 Gate**、隔离 Worktree 与可评审交付交接 | 定时任务在无人确认时私自对外发布、强行合并或越界读写 | +| **Outbox(低噪成果回传)** | 本地工作区与飞书共享同一份 Goal / 决策 / 证据视图,仅在真正完成、阻塞或待决时打扰人类 | 碎片化终端日志与各端高频无效推送,避免人肉盯盘 | + +**个人开发者本地运行 → 工程团队与组织级扩展,同一套协议无缝衔接:** + +| 使用形态 | LoopX 运行方式 | 权威存储、协作与治理形态 | +| --- | --- | --- | +| **个人开发者 & 本地 Agent** | `python3 -m pip install --upgrade loopx` 零外部依赖直接运行,接入已有 CLI / 桌面端 | 默认本地权威 **SQLite** + hard lease(兼顾既有 File 配置),跨重启、跨压缩保留现场且闲置零 Token | +| **工程团队 & 组织级扩展** | 多 Agent 认领 Todo、基于同一 Goal 经工作区 / GitHub / 飞书协同交付与互审([三 Agent 协作示例](examples/collaboration-delivery/README.md)) | 保留各自责任边界与人工审批门;支持向预置的 **PostgreSQL** 远程共享权威([源码实现](loopx/control_plane/coordination/postgresql_authority_store.ts))以及[组织治理路线图](docs/product/roadmaps/saas-opportunity-assessment.zh-CN.md)中的 RBAC、SSO 与审计能力平滑演进 | + ## 看看 LoopX 如何工作 LoopX 2.0,面向企业、研究机构与超级个体的长程研究工作台;应用画框内保留真实研究历史与来源范围,状态条按原计数校正比例
@@ -136,7 +161,9 @@ LoopX 不是生产自动化控制器。危险权限、生产写入、公开发 ### 让研究接得下去 打开 Goal 查看任务归属、Agent 与已记录的 Explore 历史。通过 **深度分析 / Deep analysis** -检查已登记轨迹的引用、原生结果读回,以及单独测量的成本。Agent 准备来源; +检查已登记轨迹的引用、原生结果读回,以及单独测量的成本。研究页还可展示有来源的 +[人工注意力投入](docs/reference/trajectory-assessment.md#human-attention-in-research-optional), +包括介入次数、时间覆盖和可核查的优化点。Agent 准备来源; 打开页面、刷新和读取结果不会启动模型,执行分析需要显式操作及已配置的宿主和账号。 保留支持、反驳与未知,核对新证据为什么改变了路线,或为什么值得继续,再进入下一轮。 @@ -147,6 +174,10 @@ LoopX 不是生产自动化控制器。危险权限、生产写入、公开发 文件、定时计划与恢复状态跨天数、跨重启、跨 harness 保持持久。重新打开项目时, 可以检查上一轮的状态与证据,再继续下一项允许执行的工作。 +新建默认 Codex Goal 时,先核对任务和工作区权限,再确认**创建 Goal 并开始首轮**。 +原任务在独立检查和额度就绪后沿原对话继续执行,普通消息保持只读。 +等待、结果核对和恢复见[工作区指南](docs/guides/personal-workspace-user-guide.md#在原对话执行已检查的任务--run-the-checked-original-task)。 + LoopX 将这些长程控制状态汇入 Personal Workspace。你可以在一个页面中: - 看清哪些事项正在等你、执行中、观察中、已安排或已停止; @@ -432,6 +463,12 @@ Kernel 把控制面归结为五个用户可以直接行动的问题。每个问 | 证据发生了什么变化? | 紧凑 run history、验证、blocker 和已接受 writeback。 | | Loop 是否可以继续? | Quota、capability、安全侧路、scheduler hint 和停止条件。 | +用 `loopx goal-lifecycle --goal-id --operation stop` 预览 Goal 停止; +改用 `--operation resume` 可恢复资格。加入 `--actor-kind owner --execute` +执行变更;Goal actions 视图提供了新鲜指纹时,保留 +`--expected-state-fingerprint`。普通 CLI 与独立 +[`loopx-core`](packages/loopx-core/README.md) CLI 使用同一个生命周期 owner。 +
架构、控制面能力与运行责任 @@ -488,10 +525,12 @@ provider 的打包和生命周期,不是另一个控制面 owner。详见 ### 个人 Agent、数字团队与自我改进 -[Meta Muse](https://about.fb.com/news/2026/09/introducing-muse-personal-ai-agent/) -与 [Grok Bot](https://x.ai/news/introducing-grok-bot) 正在让“把工作交给常驻的个人 Agent” -变得更容易理解。LoopX 选择的是开放、Provider-neutral 的控制面路线, -连接你已经在用的 Agent,而不是提供这两款托管产品的等价替代。 +[Meta Muse](https://about.fb.com/news/2026/09/introducing-muse-personal-ai-agent/)、 +[Grok Bot](https://x.ai/news/introducing-grok-bot) 以及 +[Anthropic《Building always-on agents》](https://claude.com/resources/articles/building-always-on-agents) +正在让“把工作交给 7×24 常驻个人 Agent”与“休眠—事件唤醒”成为越来越清晰的产品与架构共识。LoopX +选择的是开放、Provider-neutral 的[7×24 控制面](#always-on-agents)路线,连接你已经在用的 Agent, +而不是提供这两款托管产品的等价替代。 - **个人 Agent:**通过已发布的工作区与关联飞书入口查看目标、调整方向、处理决策。 [常驻管家与语义交接 RFC](docs/architecture/rfcs/capable-manager-semantic-handoff-v0.zh-CN.md) diff --git a/apps/desktop/loopx-control-plane/README.md b/apps/desktop/loopx-control-plane/README.md index 9e6bef1537..deac5411c4 100644 --- a/apps/desktop/loopx-control-plane/README.md +++ b/apps/desktop/loopx-control-plane/README.md @@ -14,9 +14,12 @@ desktop release workflow succeeds: On Apple Silicon macOS, the App opens its qualified local runtime first, then checks its current official channel and downloads a newer App in the background. -It verifies the updater signature and prepares the archive locally. The next -normal open verifies that archive again and installs it before starting services; -ordinary background preparation never replaces or restarts an active workspace. +It verifies the updater signature and prepares the archive locally. Ordinary +opening never installs a cached App or restarts the workspace. Use the existing +update panel or `loopx upgrade` to install and restart; those explicit operations +verify the archive again before replacement. Background preparation cannot +replace or restart an active workspace. This replaces the earlier next-open +automatic installation policy on macOS so ordinary launches stay local and fast. Windows NSIS installs follow the signed-update journey on the main channel: the App checks on launch, verifies the minisign signature, runs the installer passively and restarts automatically. On Windows the stable channel, MSI @@ -47,23 +50,49 @@ readback. A permission-restricted prepared installation stays on the verified current App; use the existing explicit update action for native authorization. The disposable cache is not an update authority: its signed bytes, channel, version order and sealed bundle version are checked again before replacement. -Rejected cached signatures and verified-safe replacement failures keep local -startup moving, with the failure retained in diagnostics. They do not display -a stopped-startup state while services are connecting. An incomplete target, -failed journal retirement or unknown installation failure still requires recovery. +Rejected signatures and replacement failures remain visible on the explicit +update transaction. An incomplete target, failed journal retirement or unknown +installation failure still requires recovery. Ordinary opening does not enter +that installation transaction. ## Updates And Recovery From a terminal, `loopx upgrade` coordinates the owning CLI installer and this -App's signed updater, restarts the App and waits for native service readiness. +App's signed updater. On writable macOS installations that advertise native +preparation support, the CLI first runs the installed App's windowless updater. +The existing workspace stays open while the native owner checks, downloads and +verifies the signed archive. A matching verified background cache is reused. +Preparation failure leaves the current window running. Only after preparation +succeeds does the CLI quit/reopen the App and wait for qualified services. + +The handoff pins that prepared version in a request-scoped disposable cache. +Restart verifies its bytes again and binds the version to the sealed App bundle; +it never downloads or chases a moving channel feed. Missing, mismatched or corrupt +bytes fail explicitly. The replacement process acknowledges the frozen target, +then reports both service identities. A failed check cannot become success just +because the workspace is healthy. Older Apps and administrator-protected install +locations retain the existing interactive native update/authorization path until +an App with preparation support is installed or the installation is writable. + Archive users can select Main with `loopx upgrade --ref main`; `--dry-run` is -read-only. The terminal passes only a bounded request id and an official channel -to the App. A private request receipt contains versions, source revisions, -update phase and the qualified service runtime identity; it contains no Goal -content or credentials. An update check failure remains a failed terminal -upgrade even when the workspace can still open. Normal launches without that -request perform their network check after local services are ready; an explicit -terminal upgrade retains its thirty-second interactive check budget. +read-only. The terminal passes a bounded request id, official channel and prepared +version, never an arbitrary download URL or installation path. Receipts contain +versions, source revisions, phase and qualified runtime identity, without Goal +content or credentials. Normal launch/background behavior is unchanged. + +macOS 可写安装目录下,`loopx upgrade` 先通过已安装 App 的无窗口原生更新器检查、 +下载并验签,保持原工作区可用;已有匹配的验签缓存会复用。准备成功后才退出、重开 +App,并核验服务身份。准备失败不关闭窗口。切换阶段固定本次版本、重新验签并核对 +密封包版本,不在启动时追逐更新源;缓存丢失、损坏或版本不符明确失败。旧 App 及 +需要管理员授权的目录保留原交互式升级路径。普通启动与后台更新行为不变。 + +This separates usable-workspace time from transfer time, following the same +preparation-before-restart principle visible in +[VS Code's Downloaded/Ready and quit-and-install transitions](https://github.com/microsoft/vscode/blob/4ebcba98631cbacfbf469338653b5d98f9c392b1/src/vs/platform/update/electron-main/updateService.darwin.ts#L177) +and [Zed's asynchronous download/install and restart-path preparation](https://github.com/zed-industries/zed/blob/48741fd17d0dec28be6ad664b0a06dc7202086be/crates/auto_update/src/auto_update.rs#L785). +Their packaging differs from LoopX's independently owned CLI runtime; this does +not combine package owners, remove integrity checks, or claim faster networks. + The existing update panel shows the same native maintenance phases and recovery actions. Main is the latest complete signed build, which can lag Git HEAD. @@ -98,8 +127,16 @@ restart a running workspace. 校验失败,只展示可操作的原因与重试入口,不暴露传输地址或签名内部错误。 无法分类的失败仍保留通用提示,失败不会被显示为已安装。 -Startup automatically uses the newest qualified local runtime it can establish. -It compares package versions; equal versions with source revisions use ancestry +Ordinary startup first reuses its last successful runtime when both existing +local services are healthy and expose that exact qualified identity. Opening a +workspace then requires no source-ancestry network check or service migration. +A newer terminal CLI alone cannot force an account/provider handoff on launch. +Explicit terminal upgrades still require their frozen target; developer pins +and isolated endpoints keep their existing route. Failed starts do not overwrite +the remembered successful runtime, and ephemeral developer pins are not saved. + +If that runtime is unavailable, startup discovers the newest qualified local +runtime it can establish. It compares package versions; equal versions with source revisions use ancestry from the fixed official GitHub repository. Installation time and lexical SHA order never determine freshness. If the bounded check is offline, rate limited or revisions diverge, a saved discovery path follows the current default CLI @@ -117,13 +154,15 @@ Chat readiness uses `/api/chat/readiness`: the loaded service's frozen runtime identity and HTTP readiness only. It does not enumerate models, credentials, Sessions or Goal state, and grants no work authority. Both native and browser launchers retain the original capabilities fallback for older services. The -native probe keeps its 500 ms deadline, so slow metadata reads cannot multiply -startup probes into more capability-discovery work. Capability availability and -original-conversation authorization are still checked by their normal owners. +native probe gives the entire request and any legacy fallback one 500 ms +deadline. A listener sending fragments slowly cannot delay startup recovery +past this probe's deadline. Capability availability and original-conversation +authorization are still checked by their normal owners. Chat 就绪探针仅读取已加载服务的固定版本身份,不枚举模型、凭据、会话或 Goal, 也不授予执行权限。原生与浏览器启动器保留旧服务的完整能力接口兼容路径;原生探针 -仍为 500 毫秒期限,不通过延长期限掩盖问题。能力是否可用、原会话是否获授权,仍由 +的完整请求与兼容回退共用 500 毫秒期限。缓慢分段的响应不会拖住单次探测后的启动恢复。 +能力是否可用、原会话是否获授权,仍由 原入口单独实时核验。 Opening the selected original conversation is a read-only discovery. It uses a @@ -141,6 +180,10 @@ listener replacement. The loaded original manager supplies its explicit store route; the same accepted-work fence protects its queued and active Turns through restart. A private bootstrap does not need to match a desktop Python template. While work is pending the window explains the wait and retries automatically. +Native-account pending work and missing/incompatible provider bindings retain +Core's specific reason in the recovery view and diagnostics. A deferred handoff +does not claim that services were changed or rolled back. Missing components +remain an installation-owner repair; repeatedly reopening the App is not a fix. Unknown manager/store state grants no raw-kill fallback or second consumer. `loopx update activate --service chat --port 8767` retries this adoption without installing anything; its receipt is a restart request, not readiness proof. @@ -406,6 +449,13 @@ directly in Research after a normal quit and a loopback-port change. Window close/reopen, an explicit return to Manager and a corrupt preference were also checked. It does not demonstrate model execution or an official App upgrade. +Within a local Goal's Research view, the preference also retains an explicit +case/history choice, selected registered analysis pack and chapter or citation +bookmark. The dashboard rechecks the pack and source when reopening. A missing +or inaccessible pack keeps its existing reader recovery path. The bookmark +must match the selected pack and the dashboard's chapter grammar. Existing +version-1 preferences without research selections continue to open as before. + ![Packaged QA reopening the same synthetic Goal in Research](docs/assets/research-reopen-qa.jpg) For native qualification, use a separately identified packaged App with the diff --git a/apps/desktop/loopx-control-plane/src-tauri/Info.plist b/apps/desktop/loopx-control-plane/src-tauri/Info.plist new file mode 100644 index 0000000000..8c39f94712 --- /dev/null +++ b/apps/desktop/loopx-control-plane/src-tauri/Info.plist @@ -0,0 +1,5 @@ + + + + LoopXUpgradePreparation1 + diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/lib.rs b/apps/desktop/loopx-control-plane/src-tauri/src/lib.rs index ab887464ca..447c8dbf2e 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/lib.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/lib.rs @@ -130,6 +130,13 @@ fn workspace_navigation( pub fn run() { #[cfg(target_os = "macos")] service_lifetime::run_if_requested(); + let context = tauri::generate_context!(); + + #[cfg(target_os = "macos")] + if std::env::args().any(|arg| arg == "--loopx-upgrade-prepare") { + maintenance::prepare_terminal_upgrade(context); + return; + } // Release builds load the versioned LoopX Chat workspace that ships inside // the installed `loopx` release, so `loopx update` refreshes the frontend @@ -365,7 +372,7 @@ pub fn run() { let builder = builder.on_web_content_process_terminate(workspace_handoff::content_lost); let app = builder - .build(tauri::generate_context!()) + .build(context) .expect("failed to build LoopX desktop shell"); app.run(move |app, event| { if matches!(event, RunEvent::Exit | RunEvent::ExitRequested { .. }) { diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/maintenance.rs b/apps/desktop/loopx-control-plane/src-tauri/src/maintenance.rs index d46e35e3e3..09b438f266 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/maintenance.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/maintenance.rs @@ -34,7 +34,6 @@ pub struct Maintenance { phase_started: Mutex>, separately_managed_runtime: AtomicBool, automatic_update_checked: AtomicBool, - prepared_update_checked: AtomicBool, background_update: Mutex, incomplete_app_installation: AtomicBool, manual_failure_pending: AtomicBool, @@ -331,26 +330,7 @@ impl Maintenance { // A queued explicit action must become the final snapshot writer. if let Err(error) = &result { let details = self.failure_details(error, channel); - // A rejected prepared archive has not replaced the running App. - // app_install_failed additionally certifies the previous target, - // qualified runtime and retired journal. Keep its diagnostics, - // but do not tell the boot page startup has stopped while local - // service startup is about to continue. Unknown/incomplete and - // explicit-operation failures retain their recovery boundary. - if self.prepared_update_checked.load(Ordering::Acquire) - && matches!( - error.as_str(), - "update_download_or_signature_failed" | "app_install_failed" - ) - && !self.incomplete_app_installation.load(Ordering::Acquire) - && !self.manual_failure_pending.load(Ordering::Acquire) - && !self.busy.load(Ordering::Acquire) - { - *self.last_failure.lock().unwrap() = json!({"phase":"error","details":details}); - self.publish("connecting", json!({})); - } else { - self.publish("error", details); - } + self.publish("error", details); } result.map(Some) } @@ -484,18 +464,8 @@ impl Maintenance { if !runtime_error { // These exact codes come from Core's activation receipt; // arbitrary service diagnostics remain private. - let code = match error.as_str() { - "chat_work_pending" => "chat_work_pending", - "chat_state_unverified" => "chat_state_unverified", - "chat_service_unverified" => "chat_service_unverified", - "service_runtime_alignment_unavailable" => { - "service_runtime_alignment_unavailable" - } - "service_runtime_alignment_failed" => "service_runtime_alignment_failed", - "service_runtime_route_unverified" => "service_runtime_route_unverified", - "service_runtime_rollback_failed" => "service_runtime_rollback_failed", - _ => "service_start_failed", - }; + let code = crate::services::activation_error_code(&error) + .unwrap_or("service_start_failed"); let mut details = json!({"code":code}); if crate::services::runtime_alignment_error(code) { let failed_at = now(); @@ -1224,7 +1194,10 @@ fn runtime_state_publishes_own_phase(error: &str) -> bool { ) } -fn resume_runtime(app: &AppHandle) -> Result { +fn resume_runtime( + app: &AppHandle, + endpoints: &crate::service_endpoints::ServiceEndpoints, +) -> Result { use crate::runtime_ancestry::compare_official_commits; use crate::runtime_selection::{ is_private_runtime, prefer_current_bundle, prefer_discovered_runtime, @@ -1240,10 +1213,30 @@ fn resume_runtime(app: &AppHandle) -> Result(); let _guard = state.acquire()?; + let private_executable = bundled_runtime::private_executable(app)?; + let current = crate::services::SelectedRuntime { + executable: selection.executable.clone(), + identity: installed.clone(), + }; + // Opening an existing workspace must not require a different CLI's + // provider/account environment to replace healthy managed services. A + // terminal upgrade still owes its frozen target; private QA and explicit + // developer pins retain their existing route. Probe before ancestry/network + // discovery, and let ServiceSet recheck before handing over the window. + if !selection.environment_override + && !endpoints.isolated + && !state.upgrade_request.get().is_some_and(Option::is_some) + && crate::services::runtime_ready(¤t, endpoints) + { + state.separately_managed_runtime.store( + !is_private_runtime(&selection.executable, &private_executable), + Ordering::Release, + ); + return Ok(current); + } let bundled = bundled_runtime::identity(app)?; let candidate = crate::runtime_selection::bundled_runtime_candidate(app.package_info(), &bundled)?; - let private_executable = bundled_runtime::private_executable(app)?; // Only a launch-time developer override pins a runtime. Ordinary launches // reconcile discovery, a previous choice, and the App-owned installation. if !selection.environment_override { @@ -1342,11 +1335,6 @@ fn resume_runtime(app: &AppHandle) -> Result, String> = - tauri::async_runtime::block_on(state.run_automatic_update( - channel, - async { - let url = endpoint(channel)?; - let checked = - perform(app, "check", channel, url.clone(), Duration::from_secs(3)) - .await?; - Ok((checked["phase"] == "available").then_some(url)) - }, - |url| async move { - perform(app, "apply", channel, url, Duration::from_secs(3)).await?; - Ok(()) - }, - || app.restart(), - )); - if let Err(error) = result { - eprintln!("LoopX automatic App update deferred: {error}"); - } - } + // A normal macOS open is not an update transaction. Even a cached + // archive requires verification, replacement and restart; keep all of + // that off the route to an already usable workspace. The existing panel + // and terminal upgrade remain the explicit installation entrypoints. + if request.is_none() && !cfg!(target_os = "windows") { return; } if state.automatic_update_checked.swap(true, Ordering::AcqRel) { return; } + #[cfg(target_os = "macos")] + if let Some(request) = request.filter(|request| request.target.is_some()) { + let result = tauri::async_runtime::block_on(state.run_automatic_update( + channel, + async { + // Both no-update and replacement processes use this frozen + // candidate. A cache miss never falls back to network at boot. + let prepared = request.prepared_target( + &app.package_info().version.to_string(), + updater_public_key(app)?, + )?; + if prepared.is_none() { + state.publish("up_to_date", json!({"channel":channel})); + } + Ok(prepared) + }, + |prepared| async move { + let target = prepared.version; + let version = target.clone(); + install_verified_app(app, target, move || { + crate::macos_update::install_prepared(&version, &prepared.bytes) + }) + .await?; + Ok(()) + }, + || app.restart(), + )); + if let Err(error) = result { + eprintln!("LoopX prepared terminal upgrade failed: {error}"); + } + return; + } // A CLI-requested upgrade is an explicit operation, not an ordinary open. // Preserve its requested channel and exact service-ready return contract. let result: Result, String> = @@ -1473,6 +1435,85 @@ fn automatic_app_update(app: &AppHandle) { // of the installed App. Diagnostics retain the failed check. } +#[cfg(target_os = "macos")] +async fn prepare_terminal_candidate( + update: Option, + current: &str, + channel: &str, + key: &str, + automatic_root: &std::path::Path, + request_root: &std::path::Path, +) -> Result { + let Some(update) = update else { + return Ok(current.into()); + }; + let cached = crate::prepared_update::peek(automatic_root, current, channel, key) + .ok() + .flatten() + .filter(|cached| cached.version == update.version && cached.signature == update.signature); + let bytes = if let Some(cached) = cached { + cached.bytes + } else { + download_update(&update, |_, _| {}).await? + }; + crate::prepared_update::save( + request_root, + channel, + &update.version, + &update.signature, + &bytes, + )?; + Ok(update.version) +} + +// The installed App remains the signature/channel owner. This bounded helper +// has no window, single-instance callback or service lifecycle: the CLI waits +// for preparation before asking the existing window to quit. +#[cfg(target_os = "macos")] +pub fn prepare_terminal_upgrade(context: tauri::Context) { + tauri::Builder::default() + .plugin(tauri_plugin_updater::Builder::new().build()) + .setup(|app| { + app.set_activation_policy(tauri::ActivationPolicy::Prohibited); + let outcome = tauri::async_runtime::block_on(async { + let handle = app.handle(); + let request = crate::upgrade_request::UpgradeRequest::from_args( + &std::env::args().collect::>(), + handle + .path() + .app_local_data_dir() + .map_err(|_| "update_unavailable")?, + handle.package_info().version.to_string(), + Value::Null, + ) + .ok_or("invalid_update_action")?; + let channel = &request.channel; + let update = + find_update(handle, channel, endpoint(channel)?, Duration::from_secs(30)) + .await?; + let target = prepare_terminal_candidate( + update, + &handle.package_info().version.to_string(), + channel, + updater_public_key(handle)?, + &prepared_directory(handle)?, + &request.preparation_directory(), + ) + .await?; + Ok::<_, String>(json!({"ok":true,"channel":channel,"target":target})) + }); + let code = if outcome.is_ok() { 0 } else { 1 }; + println!( + "{}", + outcome.unwrap_or_else(|code| json!({"ok":false,"code":code})) + ); + app.handle().exit(code); + Ok(()) + }) + .run(context) + .expect("native upgrade preparation"); +} + pub fn start_background_update(app: &AppHandle) { let state = app.state::(); if cfg!(dev) @@ -1561,7 +1602,7 @@ pub fn start_services( .get_or_init(Instant::now); automatic_app_update(app); let result = app.state::().reconcile_services(|| { - let runtime = match resume_runtime(app) { + let runtime = match resume_runtime(app, endpoints) { Ok(runtime) => runtime, Err(error) => { // Runtime states publish the phase that explains them before they @@ -1584,6 +1625,18 @@ pub fn start_services( .map_err(|e| e.to_string()) }); if let Ok(Some(services)) = &result { + // Discovery is not adoption. Failed starts must preserve the previous + // usable choice; an ephemeral developer pin must not become a default. + if !std::env::var("LOOPX_BIN").is_ok_and(|value| !value.trim().is_empty()) { + let selection = crate::runtime_selection::Selection { + executable: services.runtime().executable.clone(), + explicit: false, + environment_override: false, + }; + if let Err(error) = crate::runtime_selection::remember(app, &selection) { + eprintln!("LoopX runtime preference was not saved: {error}"); + } + } if let Some(Some(request)) = app.state::().upgrade_request.get() { request.services_ready(services.runtime_identity()); } @@ -1603,7 +1656,7 @@ pub fn restore_services_after_update_failure( state.restore_services(|| { // Progress would replace the failure snapshot with "connecting"; this // start exists only to hand the live window its runtime back. - let runtime = resume_runtime(app)?; + let runtime = resume_runtime(app, endpoints)?; crate::services::ServiceSet::start(&runtime, endpoints, |_pending| {}) .map_err(|error| error.to_string()) }) @@ -1985,17 +2038,9 @@ mod tests { } #[test] - fn rejected_prepared_update_keeps_diagnostics_without_false_boot_stop() { - for (usable, discard_ok, prepared) in [ - (true, true, true), - (false, true, true), - (true, false, true), - (true, true, false), - ] { + fn requested_update_failure_keeps_its_recovery_boundary() { + for (usable, discard_ok) in [(true, true), (false, true), (true, false)] { let state = Maintenance::default(); - state - .prepared_update_checked - .store(prepared, Ordering::Release); let code = finalize_install_failure(&state, usable, platform_uses_install_journal(), || { if discard_ok { @@ -2012,27 +2057,23 @@ mod tests { )); assert_eq!(result.unwrap_err(), code); assert_eq!(state.last_failure.lock().unwrap()["details"]["code"], code); - if usable && prepared && (discard_ok || !platform_uses_install_journal()) { - assert_eq!(state.status_snapshot()["phase"], "connecting"); + assert_eq!(state.status_snapshot()["phase"], "error"); + if usable && (discard_ok || !platform_uses_install_journal()) { assert_eq!( state.last_failure.lock().unwrap()["details"]["journal_discarded"], platform_uses_install_journal() ); - assert_eq!(state.reconcile_services(|| Ok(())).unwrap(), Some(())); - } else { - assert_eq!(state.status_snapshot()["phase"], "error"); } } } #[test] - fn prepared_signature_rejection_is_optional_but_unknown_failures_are_not() { + fn requested_update_signature_and_unknown_failures_remain_visible() { for (code, phase) in [ - ("update_download_or_signature_failed", "connecting"), + ("update_download_or_signature_failed", "error"), ("backup_failed", "error"), ] { let state = Maintenance::default(); - state.prepared_update_checked.store(true, Ordering::Release); let error = tauri::async_runtime::block_on(state.run_automatic_update( "stable", async { Err::, String>(code.into()) }, @@ -2620,6 +2661,10 @@ mod tests { #[test] fn failed_alignment_recovers_automatically_after_backoff() { for code in [ + "native_account_work_pending", + "native_observer_provider_binding_required", + "native_observer_provider_upgrade_required", + "native_observer_requires_target_runtime", "service_runtime_alignment_unavailable", "service_runtime_route_unverified", "service_runtime_alignment_failed", @@ -2632,6 +2677,7 @@ mod tests { state.reconcile_services_with_clock::<()>(|| clock.get(), || Err(code.into())), Err(code.into()) ); + assert_eq!(state.snapshot.lock().unwrap()["details"]["code"], code); assert_eq!( state.snapshot.lock().unwrap()["details"]["retry_after_ms"], delay * 1000 diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/maintenance_transfer_tests.rs b/apps/desktop/loopx-control-plane/src-tauri/src/maintenance_transfer_tests.rs index 76774ab101..189670e541 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/maintenance_transfer_tests.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/maintenance_transfer_tests.rs @@ -37,6 +37,10 @@ impl Server { } fn with_archive(bytes: Vec, signature: String) -> Self { + Self::with_version(bytes, signature, "1.1.0") + } + + fn with_version(bytes: Vec, signature: String, version: &'static str) -> Self { let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); listener.set_nonblocking(true).unwrap(); let base = format!("http://{}", listener.local_addr().unwrap()); @@ -88,7 +92,7 @@ impl Server { pause(&done, Duration::from_secs(40)); return; } - let feed = json!({"version":"1.1.0", "url":format!("{url}/{mode}"), "signature":signature}).to_string(); + let feed = json!({"version":version, "url":format!("{url}/{mode}"), "signature":signature}).to_string(); let body = if path.starts_with("/feed/") { feed.as_bytes() } else { @@ -479,3 +483,173 @@ fn released_archive_survives_slow_native_transport_and_cache_reopen() { ); eprintln!("released signed archive: {} bytes, {:.3}s including verified cache reopen; no installation", bytes.len(), start.elapsed().as_secs_f64()); } + +#[cfg(target_os = "macos")] +#[test] +fn terminal_preparation_reuses_verified_bytes_and_freezes_an_offline_handoff() { + let app = app(KEY); + let server = Server::new(); + let root = tempfile::tempdir().unwrap(); + let automatic = root.path().join("automatic"); + let request = crate::upgrade_request::UpgradeRequest::from_args( + &[ + format!("--loopx-upgrade-request={}", "a".repeat(32)), + "--loopx-upgrade-channel=stable".into(), + "--loopx-upgrade-target=1.1.0".into(), + ], + root.path().into(), + "0.1.0".into(), + Value::Null, + ) + .unwrap(); + tauri::async_runtime::block_on(async { + let update = find_update( + app.handle(), + "stable", + server.feed("fast"), + Duration::from_secs(3), + ) + .await + .unwrap(); + assert_eq!( + prepare_terminal_candidate( + update.clone(), + "0.1.0", + "stable", + KEY, + &automatic, + &request.preparation_directory() + ) + .await + .unwrap(), + "1.1.0" + ); + assert_eq!(server.requests.load(Ordering::Acquire), 2); + assert_eq!( + request + .prepared_target("0.1.0", KEY) + .unwrap() + .unwrap() + .bytes, + BODY + ); + crate::prepared_update::save(&automatic, "stable", "1.1.0", SIGNATURE, BODY).unwrap(); + prepare_terminal_candidate( + update, + "0.1.0", + "stable", + KEY, + &automatic, + &request.preparation_directory(), + ) + .await + .unwrap(); + assert_eq!( + server.requests.load(Ordering::Acquire), + 2, + "verified automatic cache avoids a second archive transfer" + ); + }); + drop(server); // No network is available at the replacement boundary. + assert_eq!( + request + .prepared_target("0.1.0", KEY) + .unwrap() + .unwrap() + .bytes, + BODY + ); + // Another window's background cache cannot replace this request's bytes. + crate::prepared_update::clear(&automatic).unwrap(); + assert!(request.prepared_target("0.1.0", "invalid").is_err()); + crate::prepared_update::save( + &request.preparation_directory(), + "stable", + "1.2.0", + SIGNATURE, + BODY, + ) + .unwrap(); + assert!(request.prepared_target("0.1.0", KEY).is_err()); + crate::prepared_update::clear(&request.preparation_directory()).unwrap(); + assert!(request.prepared_target("0.1.0", KEY).is_err()); + assert!(request.prepared_target("1.1.0", KEY).unwrap().is_none()); +} + +#[cfg(target_os = "macos")] +#[test] +fn terminal_preparation_rejects_bad_download_before_any_handoff() { + let app = app(KEY); + let server = Server::new(); + let root = tempfile::tempdir().unwrap(); + tauri::async_runtime::block_on(async { + let update = find_update( + app.handle(), + "stable", + server.feed("tampered"), + Duration::from_secs(3), + ) + .await + .unwrap(); + let request = root.path().join("request"); + assert_eq!( + prepare_terminal_candidate( + update, + "0.1.0", + "stable", + KEY, + &root.path().join("automatic"), + &request + ) + .await + .unwrap_err(), + "update_signature_invalid" + ); + assert!(!request.exists()); + assert_eq!( + prepare_terminal_candidate(None, "1.1.0", "stable", KEY, root.path(), &request) + .await + .unwrap(), + "1.1.0" + ); + assert!(!request.exists()); + }); +} + +#[cfg(target_os = "macos")] +#[test] +fn rejected_cross_channel_preparation_preserves_original_verified_cache() { + let app = app(KEY); + let server = Server::with_version(BODY.to_vec(), SIGNATURE.into(), "1.1.0-main.2"); + let automatic = tempfile::tempdir().unwrap(); + let request = tempfile::tempdir().unwrap(); + crate::prepared_update::save(automatic.path(), "stable", "1.1.0", SIGNATURE, BODY).unwrap(); + let before = std::fs::read(automatic.path().join("prepared.json")).unwrap(); + let update = tauri::async_runtime::block_on(find_update( + app.handle(), + "main", + server.feed("tampered"), + Duration::from_secs(5), + )) + .unwrap(); + let result = tauri::async_runtime::block_on(prepare_terminal_candidate( + update, + "1.0.0", + "main", + KEY, + automatic.path(), + request.path(), + )); + assert_eq!(result.unwrap_err(), "update_signature_invalid"); + assert!(!request.path().join("prepared.json").exists()); + assert_eq!( + std::fs::read(automatic.path().join("prepared.json")).unwrap(), + before + ); + let original = crate::prepared_update::load(automatic.path(), "1.0.0", "stable", KEY) + .unwrap() + .expect("failed Main preparation must retain the signed Stable cache"); + assert_eq!(original.bytes, BODY); + assert_eq!(original.signature, SIGNATURE); + assert_eq!(server.requests.load(Ordering::Acquire), 2); +} diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/prepared_update.rs b/apps/desktop/loopx-control-plane/src-tauri/src/prepared_update.rs index e4045b4780..2085a3ba7a 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/prepared_update.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/prepared_update.rs @@ -106,13 +106,41 @@ pub(crate) fn load( current: &str, channel: &str, public_key: &str, +) -> Result, String> { + read(root, current, channel, public_key, CacheRead::Consume) +} + +/// Preparation may reuse a verified archive, but cannot retire another +/// channel's cache while its original workspace is still running. +pub(crate) fn peek( + root: &Path, + current: &str, + channel: &str, + public_key: &str, +) -> Result, String> { + read(root, current, channel, public_key, CacheRead::Reuse) +} + +enum CacheRead { + Consume, + Reuse, +} + +fn read( + root: &Path, + current: &str, + channel: &str, + public_key: &str, + mode: CacheRead, ) -> Result, String> { let Some(value) = metadata(root)? else { return Ok(None); }; let version = value["version"].as_str().ok_or(INVALID)?; if value["channel"] != channel || !is_newer(current, version, channel) { - clear(root)?; + if matches!(mode, CacheRead::Consume) { + clear(root)?; + } return Ok(None); } let bytes = fs::read(root.join(archive_name(&value)?)).map_err(|_| INVALID)?; diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/services.rs b/apps/desktop/loopx-control-plane/src-tauri/src/services.rs index b894078a00..633fd66171 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/services.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/services.rs @@ -4,7 +4,7 @@ use std::{ env, ffi::OsStr, fmt, fs, - io::{Read, Write}, + io::{ErrorKind, Read, Write}, net::{SocketAddr, TcpStream}, path::{Path, PathBuf}, process::{Command, Stdio}, @@ -20,10 +20,40 @@ const STARTUP_TIMEOUT: Duration = Duration::from_secs(15); const PROBE_TIMEOUT: Duration = Duration::from_millis(500); const MAX_PROBE_RESPONSE_BYTES: u64 = 1024 * 1024; +// Core owns activation admission. Keep its bounded reason codes intact across +// the native supervisor and recovery view; a deferred provider prerequisite is +// not a failed service transaction or proof that rollback happened. +pub(crate) fn activation_error_code(code: &str) -> Option<&'static str> { + match code { + "chat_work_pending" => Some("chat_work_pending"), + "chat_state_unverified" => Some("chat_state_unverified"), + "chat_service_unverified" => Some("chat_service_unverified"), + "native_account_work_pending" => Some("native_account_work_pending"), + "native_observer_provider_binding_required" => { + Some("native_observer_provider_binding_required") + } + "native_observer_provider_upgrade_required" => { + Some("native_observer_provider_upgrade_required") + } + "native_observer_requires_target_runtime" => { + Some("native_observer_requires_target_runtime") + } + "service_runtime_alignment_unavailable" => Some("service_runtime_alignment_unavailable"), + "service_runtime_alignment_failed" => Some("service_runtime_alignment_failed"), + "service_runtime_route_unverified" => Some("service_runtime_route_unverified"), + "service_runtime_rollback_failed" => Some("service_runtime_rollback_failed"), + _ => None, + } +} + pub(crate) fn runtime_alignment_error(code: &str) -> bool { matches!( code, - "service_runtime_alignment_unavailable" + "native_account_work_pending" + | "native_observer_provider_binding_required" + | "native_observer_provider_upgrade_required" + | "native_observer_requires_target_runtime" + | "service_runtime_alignment_unavailable" | "service_runtime_route_unverified" | "service_runtime_alignment_failed" | "service_runtime_rollback_failed" @@ -167,7 +197,21 @@ pub(crate) struct SelectedRuntime { pub identity: Option, } +/// A qualified installation is reusable only when both existing listeners +/// answer with its exact identity. Observation starts/stops no service. +pub(crate) fn runtime_ready(runtime: &SelectedRuntime, endpoints: &ServiceEndpoints) -> bool { + runtime.identity.is_some() + && SERVICE_KINDS.iter().all(|kind| { + probe_on_port(*kind, endpoints.port(*kind), runtime.identity.as_ref()) + == Probe::Matching + }) +} + impl ServiceSet { + pub(crate) fn runtime(&self) -> &SelectedRuntime { + &self.runtime + } + pub(crate) fn runtime_identity(&self) -> Option<&serde_json::Value> { self.runtime.identity.as_ref() } @@ -331,13 +375,10 @@ fn managed_runtime_alignment_result( { return Ok(()); } - let code = match payload["reason"].as_str() { - Some("chat_work_pending") => "chat_work_pending", - Some("chat_state_unverified") => "chat_state_unverified", - Some("service_runtime_route_unverified") => "service_runtime_route_unverified", - Some("service_runtime_rollback_failed") => "service_runtime_rollback_failed", - _ => "service_runtime_alignment_failed", - }; + let code = payload["reason"] + .as_str() + .and_then(activation_error_code) + .unwrap_or("service_runtime_alignment_failed"); Err(ServiceError(code.into())) } @@ -1344,7 +1385,9 @@ fn probe_on_port( port: u16, expected_runtime_identity: Option<&serde_json::Value>, ) -> Probe { - let mut response = match read_probe_response(port, kind.probe_path()) { + // This budget covers the whole observation, including any legacy request. + let deadline = Instant::now() + PROBE_TIMEOUT; + let mut response = match read_probe_response(port, kind.probe_path(), deadline) { Ok(response) => response, Err(probe) => return probe, }; @@ -1357,7 +1400,7 @@ fn probe_on_port( { // A legacy Core has no lightweight endpoint. Keep its original // fingerprint/identity checks; new services never enumerate metadata. - response = match read_probe_response(port, "/api/chat/capabilities") { + response = match read_probe_response(port, "/api/chat/capabilities", deadline) { Ok(response) => response, Err(probe) => return probe, }; @@ -1365,33 +1408,54 @@ fn probe_on_port( classify_response(kind, &response, expected_runtime_identity) } -fn read_probe_response(port: u16, path: &str) -> Result { +fn probe_time_left(deadline: Instant) -> Result { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return Err(Probe::Unresponsive); + } + Ok(remaining) +} + +fn read_probe_response(port: u16, path: &str, deadline: Instant) -> Result { let address = SocketAddr::from(([127, 0, 0, 1], port)); - let mut stream = match TcpStream::connect_timeout(&address, PROBE_TIMEOUT) { - Ok(stream) => stream, - Err(_) => return Err(Probe::Unavailable), - }; - let _ = stream.set_read_timeout(Some(PROBE_TIMEOUT)); - let _ = stream.set_write_timeout(Some(PROBE_TIMEOUT)); + let mut stream = TcpStream::connect_timeout(&address, probe_time_left(deadline)?) + .map_err(|_| Probe::Unavailable)?; let request = format!( "GET {} HTTP/1.1\r\nHost: 127.0.0.1:{}\r\nConnection: close\r\n\r\n", path, port ); - if stream.write_all(request.as_bytes()).is_err() { - return Err(Probe::Unresponsive); - } - let mut response = String::new(); - if stream - .take(MAX_PROBE_RESPONSE_BYTES + 1) - .read_to_string(&mut response) - .is_err() - { - return Err(Probe::Unresponsive); + let mut unsent = request.as_bytes(); + while !unsent.is_empty() { + stream + .set_write_timeout(Some(probe_time_left(deadline)?)) + .map_err(|_| Probe::Unresponsive)?; + match stream.write(unsent) { + Ok(0) => return Err(Probe::Unresponsive), + Ok(written) => unsent = &unsent[written..], + Err(error) if error.kind() == ErrorKind::Interrupted => continue, + Err(_) => return Err(Probe::Unresponsive), + } } - if response.len() as u64 > MAX_PROBE_RESPONSE_BYTES { - return Err(Probe::Foreign); + let mut reader = stream.take(MAX_PROBE_RESPONSE_BYTES + 1); + let mut response = Vec::new(); + let mut buffer = [0; 8192]; + loop { + reader + .get_ref() + .set_read_timeout(Some(probe_time_left(deadline)?)) + .map_err(|_| Probe::Unresponsive)?; + match reader.read(&mut buffer) { + Ok(0) => break, + Ok(read) => response.extend_from_slice(&buffer[..read]), + Err(error) if error.kind() == ErrorKind::Interrupted => continue, + Err(_) => return Err(Probe::Unresponsive), + } + if response.len() as u64 > MAX_PROBE_RESPONSE_BYTES { + return Err(Probe::Foreign); + } } - Ok(response) + probe_time_left(deadline)?; + String::from_utf8(response).map_err(|_| Probe::Unresponsive) } fn classify_response( diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs b/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs index 7f41c3979c..ecb7547f7b 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs @@ -564,6 +564,97 @@ fn chat_readiness_retains_identity_and_state_checks() { } } +fn read_probe_request(stream: &mut TcpStream, path: &str) -> bool { + stream + .set_read_timeout(Some(Duration::from_secs(2))) + .unwrap(); + let mut bytes = Vec::new(); + while !bytes.ends_with(b"\r\n\r\n") { + let mut buffer = [0; 512]; + let Ok(read) = stream.read(&mut buffer) else { + return false; + }; + if read == 0 { + return false; + } + bytes.extend_from_slice(&buffer[..read]); + } + String::from_utf8(bytes) + .unwrap() + .starts_with(&format!("GET {path} HTTP/1.1")) +} + +#[test] +fn a_trickling_readiness_response_cannot_extend_the_deadline() { + let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = listener.local_addr().unwrap().port(); + let responder = thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + assert!(read_probe_request(&mut stream, "/api/chat/readiness")); + let fragments: &[&[u8]] = &[ + b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", + b"{\"ok\":true,", + b"\"schema_version\":", + b"\"loopx_chat_readiness_v1\",", + b"\"state\":", + b"\"ready\"}", + ]; + for (index, fragment) in fragments.iter().enumerate() { + if index > 0 { + thread::sleep(Duration::from_millis(150)); + } + if stream.write_all(fragment).is_err() { + break; + } + } + }); + let actual = probe_on_port(ServiceKind::Chat, port, None); + responder.join().unwrap(); + assert_eq!(actual, Probe::Unresponsive); +} + +#[test] +fn legacy_chat_fallback_shares_the_original_readiness_deadline() { + let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = listener.local_addr().unwrap().port(); + let responder = thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + assert!(read_probe_request(&mut stream, "/api/chat/readiness")); + thread::sleep(Duration::from_millis(300)); + if stream + .write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n") + .is_err() + { + return; + } + drop(stream); + // Do not block the test if the first attempt has already timed out. + listener.set_nonblocking(true).unwrap(); + let deadline = Instant::now() + Duration::from_secs(1); + let mut stream = loop { + match listener.accept() { + Ok((stream, _)) => break stream, + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + if Instant::now() >= deadline { + return; + } + thread::sleep(Duration::from_millis(10)); + } + Err(error) => panic!("fallback accept: {error}"), + } + }; + if !read_probe_request(&mut stream, "/api/chat/capabilities") { + return; + } + thread::sleep(Duration::from_millis(300)); + let body = r#"{"ok":true,"schema_version":"loopx_chat_capabilities_v1"}"#; + let _ = write!(stream, "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n{body}"); + }); + let actual = probe_on_port(ServiceKind::Chat, port, None); + responder.join().unwrap(); + assert_eq!(actual, Probe::Unresponsive); +} + #[test] fn legacy_chat_readiness_uses_the_original_capabilities_fallback() { let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); @@ -573,19 +664,7 @@ fn legacy_chat_readiness_uses_the_original_capabilities_fallback() { let responder = thread::spawn(move || { for path in ["/api/chat/readiness", "/api/chat/capabilities"] { let (mut stream, _) = listener.accept().unwrap(); - stream - .set_read_timeout(Some(Duration::from_secs(2))) - .unwrap(); - let mut bytes = Vec::new(); - while !bytes.ends_with(b"\r\n\r\n") { - let mut buffer = [0; 512]; - let read = stream.read(&mut buffer).unwrap(); - assert!(read > 0); - bytes.extend_from_slice(&buffer[..read]); - } - assert!(String::from_utf8(bytes) - .unwrap() - .starts_with(&format!("GET {path} HTTP/1.1"))); + assert!(read_probe_request(&mut stream, path)); let response = if path.ends_with("readiness") { "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into() } else { @@ -1006,6 +1085,10 @@ fn runtime_alignment_requires_exact_identity_and_keeps_recovery_codes() { payload["runtime_identity"] = serde_json::json!({"release_id":"old"}); assert!(managed_runtime_alignment_result(output(payload.clone(), 0), Some(&identity)).is_err()); for reason in [ + "native_account_work_pending", + "native_observer_provider_binding_required", + "native_observer_provider_upgrade_required", + "native_observer_requires_target_runtime", "chat_work_pending", "chat_state_unverified", "service_runtime_route_unverified", @@ -1029,3 +1112,62 @@ fn runtime_alignment_requires_exact_identity_and_keeps_recovery_codes() { "service_runtime_alignment_unavailable" ); } + +#[test] +fn connected_runtime_requires_both_healthy_exact_identity_listeners() { + let identity = serde_json::json!({"schema_version":"loopx_runtime_identity_v1", + "release_id":"qualified", "source_revision":"a".repeat(40), "package_version":"2.3.0"}); + let runtime = SelectedRuntime { + executable: "unused-discovery-candidate".into(), + identity: Some(identity.clone()), + }; + for (chat_identity, status_ready, expected) in [ + (identity.clone(), true, true), + (serde_json::json!({"release_id":"other"}), true, false), + (identity.clone(), false, false), + ] { + let endpoints = ServiceEndpoints::allocate(true).unwrap(); + let servers: Vec<_> = SERVICE_KINDS.into_iter().map(|kind| { + let listener = std::net::TcpListener::bind(("127.0.0.1", endpoints.port(kind))).unwrap(); + listener.set_nonblocking(true).unwrap(); + let payload = match kind { + ServiceKind::Status => serde_json::json!({"source":"serve-status", "runtime_identity":identity, + "readiness":{"schema_version":"loopx_status_readiness_v0", + "state":if status_ready { "ready" } else { "failed" }, + "reason":if status_ready { "registry_readable" } else { "registry_invalid" }}}), + ServiceKind::Chat => serde_json::json!({"ok":true,"schema_version":"loopx_chat_readiness_v1", + "state":"ready","runtime_identity":chat_identity}), + }; + thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(2); + loop { + if let Ok((mut stream, _)) = listener.accept() { + stream.set_read_timeout(Some(Duration::from_secs(1))).unwrap(); + let mut request = [0; 1024]; + let _ = stream.read(&mut request); + let _ = write!(stream, "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n{payload}"); + return; + } + if Instant::now() >= deadline { return; } + thread::sleep(Duration::from_millis(5)); + } + }) + }).collect(); + assert_eq!(runtime_ready(&runtime, &endpoints), expected); + for server in servers { + server.join().unwrap(); + } + } + let endpoints = ServiceEndpoints::allocate(true).unwrap(); + assert!( + !runtime_ready(&runtime, &endpoints), + "a qualified install alone is not readiness" + ); + assert!(!runtime_ready( + &SelectedRuntime { + executable: "unused".into(), + identity: None + }, + &endpoints + )); +} diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/upgrade_request.rs b/apps/desktop/loopx-control-plane/src-tauri/src/upgrade_request.rs index 07f7321304..418310abcb 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/upgrade_request.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/upgrade_request.rs @@ -11,6 +11,8 @@ use std::{ pub(crate) struct UpgradeRequest { pub channel: String, + #[cfg(target_os = "macos")] + pub target: Option, id: String, path: PathBuf, version: String, @@ -39,8 +41,16 @@ impl UpgradeRequest { if !matches!(channel, "main" | "stable") { return None; } + let target = args + .iter() + .find_map(|s| s.strip_prefix("--loopx-upgrade-target=")); + if target.is_some_and(|value| value.len() > 128 || semver::Version::parse(value).is_err()) { + return None; + } Some(Self { channel: channel.to_string(), + #[cfg(target_os = "macos")] + target: target.map(str::to_owned), id: id.to_string(), path: directory.join("upgrades").join(format!("{id}.json")), version, @@ -51,6 +61,31 @@ impl UpgradeRequest { }) } + #[cfg(target_os = "macos")] + pub fn preparation_directory(&self) -> PathBuf { + self.path.with_extension("prepared") + } + + #[cfg(target_os = "macos")] + pub fn prepared_target( + &self, + current: &str, + key: &str, + ) -> Result, String> { + let target = self + .target + .as_deref() + .ok_or("update_download_or_signature_failed")?; + if target == current { + let _ = crate::prepared_update::clear(&self.preparation_directory()); + return Ok(None); + } + crate::prepared_update::load(&self.preparation_directory(), current, &self.channel, key)? + .filter(|prepared| prepared.version == target) + .map(Some) + .ok_or_else(|| "update_download_or_signature_failed".into()) + } + pub fn services_ready(&self, identity: Option<&Value>) { *self.runtime.lock().unwrap() = identity.cloned(); self.publish("ready", &json!({})); diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/workspace_location.rs b/apps/desktop/loopx-control-plane/src-tauri/src/workspace_location.rs index 2a17e5ae6d..3171e602e3 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/workspace_location.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/workspace_location.rs @@ -15,6 +15,66 @@ struct LocalWorkspace { view: Option, work_agent: Option, todo: Option, + research: Option, +} + +/// Selection within the existing dashboard reader, scoped to this local Goal. +#[derive(Debug, PartialEq)] +struct ResearchReading { + mode: String, + pack_id: Option, + chapter: Option, +} + +fn digest_id(value: &str) -> bool { + value.len() == 64 + && value + .bytes() + .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) +} + +impl ResearchReading { + fn selections(mode: &str, pack: &str, chapter: &str) -> Option { + if !matches!(mode, "case" | "history") { + return None; + } + let pack_id = digest_id(pack).then(|| pack.to_owned()); + // The frontend resolves this bookmark against the saved study. Carry + // only its declared chapter/citation grammar, never an arbitrary URL. + let chapter = pack_id.as_deref().and_then(|pack| { + let body = chapter.strip_prefix("case-section-")?; + let prefix = format!("{pack}-"); + let section = body.strip_prefix(&prefix).or_else(|| { + let (namespace, rest) = body.split_once('-')?; + digest_id(namespace).then_some(rest)?.strip_prefix(&prefix) + })?; + let (id, citation) = match section.split_once('~') { + Some((id, ordinal)) => (id, Some(ordinal)), + None => (section, None), + }; + let valid_id = id.len() <= 80 + && id + .bytes() + .all(|c| c.is_ascii_alphanumeric() || b"_-".contains(&c)) + && (!id.is_empty() || citation.is_some()); + let valid_citation = citation.is_none_or(|ordinal| { + ordinal.len() <= 2 + && !ordinal.starts_with('0') + && ordinal.bytes().all(|c| c.is_ascii_digit()) + && !ordinal.is_empty() + }); + (mode == "case" && valid_id && valid_citation).then(|| chapter.to_owned()) + }); + Some(Self { + mode: mode.to_owned(), + pack_id, + chapter, + }) + } + + fn value(&self) -> Value { + json!({"mode": self.mode, "pack_id": self.pack_id, "chapter": self.chapter}) + } } // Match the existing Goal instance ID and frontend Agent/Todo search boundary. @@ -44,6 +104,7 @@ impl LocalWorkspace { .then(|| view.to_owned()), work_agent: selection_id(agent), todo: selection_id(todo), + research: None, }) } @@ -71,7 +132,23 @@ impl LocalWorkspace { // authority. Reopening that unsupported context returns Manager. return Some(Self::default()); } - Self::selections(get("goalId"), get("view"), get("workAgent"), get("todo")) + let mut selection = + Self::selections(get("goalId"), get("view"), get("workAgent"), get("todo"))?; + if selection.view.as_deref() == Some("research") + && get("research_goal") == selection.goal_id + { + let pack = if get("research_analysis_goal") == selection.goal_id { + get("research_pack") + } else { + "" + }; + selection.research = ResearchReading::selections( + get("research_reading"), + pack, + current.fragment().unwrap_or(""), + ); + } + Some(selection) } fn destination(&self, origin: &Url) -> Url { @@ -90,7 +167,20 @@ impl LocalWorkspace { query.append_pair(key, value); } } + if let Some(research) = &self.research { + query.append_pair("research_goal", &self.goal_id); + query.append_pair("research_reading", &research.mode); + if let Some(pack) = &research.pack_id { + query.append_pair("research_analysis_goal", &self.goal_id); + query.append_pair("research_pack", pack); + } + } drop(query); + destination.set_fragment( + self.research + .as_ref() + .and_then(|research| research.chapter.as_deref()), + ); destination } @@ -98,17 +188,30 @@ impl LocalWorkspace { if value["version"] != 1 { return None; } - Self::selections( + let mut selection = Self::selections( value["goal_id"].as_str()?, value["view"].as_str().unwrap_or(""), value["work_agent"].as_str().unwrap_or(""), value["todo"].as_str().unwrap_or(""), - ) + )?; + if !selection.goal_id.is_empty() && selection.view.as_deref() == Some("research") { + let research = &value["research"]; + selection.research = ResearchReading::selections( + research["mode"].as_str().unwrap_or(""), + research["pack_id"].as_str().unwrap_or(""), + research["chapter"].as_str().unwrap_or(""), + ); + } + Some(selection) } fn value(&self) -> Value { - json!({"version": 1, "goal_id": self.goal_id, "view": self.view, - "work_agent": self.work_agent, "todo": self.todo}) + let mut value = json!({"version": 1, "goal_id": self.goal_id, "view": self.view, + "work_agent": self.work_agent, "todo": self.todo}); + if let Some(research) = &self.research { + value["research"] = research.value(); + } + value } } @@ -211,6 +314,124 @@ mod tests { format!("http://127.0.0.1:{port}/chat/").parse().unwrap() } + fn research_page(port: u16) -> Url { + let mut page = origin(port); + page.query_pairs_mut().extend_pairs([ + ("goalId", "example"), + ("view", "research"), + ("research_goal", "example"), + ("research_reading", "case"), + ("research_analysis_goal", "example"), + ("research_pack", &"a".repeat(64)), + ]); + page + } + + #[test] + fn research_reopen_keeps_registered_pack_and_chapter_or_citation_on_the_new_port() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("workspace-location.json"); + for namespace in [String::new(), format!("{}-", "b".repeat(64))] { + for section in ["turning-point", "turning-point~2", "~1"] { + let mut page = research_page(49123); + let chapter = format!("case-section-{namespace}{}-{section}", "a".repeat(64)); + page.set_fragment(Some(&chapter)); + let saved = LocalWorkspace::capture(&page, &origin(49123)).unwrap(); + write(&path, &saved).unwrap(); + let reopened = read(&path).unwrap().destination(&origin(59234)); + assert_eq!(reopened.port(), Some(59234)); + let reopened_query = reopened + .query_pairs() + .into_owned() + .collect::>(); + for (key, value) in page.query_pairs().into_owned() { + assert_eq!(reopened_query.get(&key), Some(&value)); + } + assert_eq!(reopened.fragment(), Some(chapter.as_str())); + let bytes = fs::read_to_string(&path).unwrap(); + assert!(!bytes.contains("49123") && !bytes.contains("http")); + assert_eq!(read(&path), Some(saved)); + } + } + } + + #[test] + fn research_selections_stay_with_their_goal_view_and_pack() { + let mut page = research_page(49123); + page.set_fragment(Some(&format!( + "case-section-{}-turning-point", + "a".repeat(64) + ))); + for (key, value) in [ + ("goalId", "other"), + ("view", "tasks"), + ("research_goal", "other"), + ] { + let mut changed = page.clone(); + let pairs = changed + .query_pairs() + .into_owned() + .map(|(k, v)| { + let v = if k == key { value.to_owned() } else { v }; + (k, v) + }) + .collect::>(); + changed.query_pairs_mut().clear().extend_pairs(pairs); + assert!(LocalWorkspace::capture(&changed, &origin(49123)) + .unwrap() + .research + .is_none()); + } + for pack in ["wrong", &"c".repeat(64)] { + let mut changed = page.clone(); + changed.query_pairs_mut().clear().extend_pairs([ + ("goalId", "example"), + ("view", "research"), + ("research_goal", "example"), + ("research_reading", "case"), + ("research_analysis_goal", "other"), + ("research_pack", pack), + ]); + let saved = LocalWorkspace::capture(&changed, &origin(49123)).unwrap(); + let research = saved.research.unwrap(); + assert!(research.pack_id.is_none() && research.chapter.is_none()); + } + let history = + ResearchReading::selections("history", &"a".repeat(64), page.fragment().unwrap()) + .unwrap(); + assert_eq!(history.mode, "history"); + assert!(history.chapter.is_none()); + assert!(ResearchReading::selections("retired", "", "").is_none()); + } + + #[test] + fn invalid_bookmarks_and_unrelated_preference_fields_are_not_restored() { + let pack = "a".repeat(64); + for chapter in [ + "https://example.org/secret".to_owned(), + format!("case-section-{}-chapter", "c".repeat(64)), + format!("case-section-{pack}-../secret"), + format!("case-section-{pack}-chapter~0"), + format!("case-section-{pack}-chapter~01"), + format!("case-section-{pack}-chapter~100"), + format!("case-section-{pack}-{}", "x".repeat(81)), + ] { + assert!(ResearchReading::selections("case", &pack, &chapter) + .unwrap() + .chapter + .is_none()); + } + let legacy = json!({"version": 1, "goal_id": "example", "view": "research"}); + let saved = LocalWorkspace::from_value(&legacy).unwrap(); + assert!(saved.research.is_none()); + let mut modified = legacy; + modified["research"] = json!({"mode": "case", "pack_id": pack, "chapter": "secret", "url": "https://example.org"}); + let restored = LocalWorkspace::from_value(&modified).unwrap(); + assert!(restored.research.as_ref().unwrap().chapter.is_none()); + assert!(!restored.value().to_string().contains("secret")); + assert!(!restored.value().to_string().contains("example.org")); + } + #[test] fn ordinary_reopen_keeps_selection_across_ports_without_replaying_other_inputs() { let old = origin(49123); diff --git a/apps/desktop/loopx-control-plane/src-tauri/tauri.conf.json b/apps/desktop/loopx-control-plane/src-tauri/tauri.conf.json index dd5963130e..d2eee415be 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/tauri.conf.json +++ b/apps/desktop/loopx-control-plane/src-tauri/tauri.conf.json @@ -19,6 +19,7 @@ "createUpdaterArtifacts": false, "resources": {"../runtime/runtime-source.tar.gz": "runtime/runtime-source.tar.gz", "../runtime/identity.json": "runtime/identity.json"}, "active": true, + "macOS": {"infoPlist": "Info.plist"}, "targets": ["app", "dmg", "msi", "nsis", "deb", "appimage"], "category": "DeveloperTool", "shortDescription": "Local LoopX control plane", diff --git a/apps/desktop/loopx-control-plane/static/boot.js b/apps/desktop/loopx-control-plane/static/boot.js index a5ff071a4e..8ce588b3ec 100644 --- a/apps/desktop/loopx-control-plane/static/boot.js +++ b/apps/desktop/loopx-control-plane/static/boot.js @@ -8,6 +8,10 @@ let timingObservedAt = pageStarted; let bootState = null; let observedEnvironment = null; const runtimeRecoveryTitles = { + native_account_work_pending: "账号服务正在处理请求", + native_observer_provider_binding_required: "需要兼容的账号服务组件", + native_observer_provider_upgrade_required: "需要更新账号服务组件", + native_observer_requires_target_runtime: "需要兼容的账号服务运行时", service_runtime_alignment_unavailable: "正在等待可用的运行时", service_runtime_route_unverified: "正在核验系统服务", service_runtime_alignment_failed: "正在恢复本地服务", @@ -52,7 +56,9 @@ function updateStartupElapsed() { if (serviceRecoveryPending(bootState)) { const remaining = Math.max(0, (bootState.details.retry_after_ms ?? 0) - (performance.now() - timingObservedAt)); bootElapsed.textContent = remaining > 0 ? `${Math.ceil(remaining / 1000)} 秒后自动重试` : "正在重新连接"; - bootDetail.textContent = "恢复后会自动打开工作区,无需手动操作。"; + bootDetail.textContent = ["native_observer_provider_binding_required", "native_observer_provider_upgrade_required", "native_observer_requires_target_runtime"].includes(bootState.details.code) + ? "现有服务保持运行。请展开「恢复与更新」查看所需组件;重复重启不会补齐组件。" + : "恢复后会自动打开工作区,无需手动操作。"; return; } if (["error", "runtime_required"].includes(bootState?.phase)) { @@ -118,6 +124,10 @@ const labels = { error: "更新未完成。请重试检查,或修复当前版本。Goal 数据不会被删除。", }; const errors = { + native_account_work_pending: "账号服务仍有已接受的请求,完成后会自动重试。现有服务保持运行,请勿强退或重复发送。", + native_observer_provider_binding_required: "所选运行时未绑定当前账号服务组件,尚未切换服务。请通过原安装方式修复运行时与账号组件的绑定;现有服务保持运行。", + native_observer_provider_upgrade_required: "所选运行时的账号服务组件版本不兼容,尚未切换服务。请通过原安装方式更新账号组件;现有服务保持运行。", + native_observer_requires_target_runtime: "账号服务无法使用所选运行时,尚未切换服务。请通过原安装方式修复匹配的运行时;现有服务保持运行。", service_runtime_alignment_unavailable: "当前运行时尚不支持服务版本对齐。App 会自动重新检测可用运行时;现有服务保持运行。", service_runtime_route_unverified: "系统服务来源暂时无法验证。App 会自动复查,来源确认后继续连接;自定义配置保持不变。", service_runtime_alignment_failed: "服务版本切换未完成,已尝试恢复原配置。App 会自动重试。", diff --git a/apps/presentation/dashboard/package.json b/apps/presentation/dashboard/package.json index 0051fbfde2..6360cf9020 100644 --- a/apps/presentation/dashboard/package.json +++ b/apps/presentation/dashboard/package.json @@ -5,6 +5,9 @@ "license": "Apache-2.0", "type": "module", "scripts": { + "smoke:goal-created-session": "tsc --noEmit --ignoreConfig --target ES2022 --module ES2022 --moduleResolution Bundler --allowImportingTsExtensions --types node --skipLibCheck --strict smoke/goal-created-session-smoke.ts src/vite-env.d.ts && vite build --ssr smoke/goal-created-session-smoke.ts --outDir node_modules/.cache/goal-created-session --emptyOutDir && node node_modules/.cache/goal-created-session/goal-created-session-smoke.js", + "smoke:goal-created-session-browser": "LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node smoke/goal-created-session-browser-smoke.mjs", + "smoke:conversation-find": "LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node smoke/conversation-find-browser-smoke.mjs", "smoke:queue-input-recovery": "vite build --ssr smoke/queue-input-recovery-smoke.mjs --outDir node_modules/.cache/queue-input-recovery --emptyOutDir && node node_modules/.cache/queue-input-recovery/queue-input-recovery-smoke.js", "smoke:todo-ownership": "vite build --ssr smoke/todo-ownership-smoke.mjs --outDir node_modules/.cache/todo-ownership --emptyOutDir && node node_modules/.cache/todo-ownership/todo-ownership-smoke.js", "smoke:workspace-progressive-loader": "node smoke/workspace-progressive-status-smoke.mjs", @@ -79,6 +82,7 @@ "smoke:conversation-history-order": "LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node smoke/conversation-history-order-browser-smoke.mjs", "smoke:conversation-returns-packaged": "LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node smoke/conversation-return-browser-smoke.mjs", "smoke:research-evidence-version": "LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node smoke/research-evidence-version-browser-smoke.mjs", + "smoke:research-human-attention": "LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node smoke/research-human-attention-browser-smoke.mjs", "smoke:workspace-scope-packaged": "LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node smoke/workspace-scope-browser-smoke.mjs", "smoke:recent-completions": "tsc --ignoreConfig --target ES2022 --module CommonJS --moduleResolution Node --ignoreDeprecations 6.0 --resolveJsonModule --esModuleInterop --jsx react-jsx --skipLibCheck --strict --types node --outDir /tmp/loopx-recent-completions-smoke smoke/recent-completions-smoke.ts && NODE_PATH=\"$PWD/node_modules\" node /tmp/loopx-recent-completions-smoke/apps/presentation/dashboard/smoke/recent-completions-smoke.js", "smoke:task-inspector-route": "npm run smoke:goal-work-browse && LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node smoke/task-inspector-route-smoke.mjs", diff --git a/apps/presentation/dashboard/smoke/app-steward-smoke.ts b/apps/presentation/dashboard/smoke/app-steward-smoke.ts index fe2e48c9bd..d606469c77 100644 --- a/apps/presentation/dashboard/smoke/app-steward-smoke.ts +++ b/apps/presentation/dashboard/smoke/app-steward-smoke.ts @@ -4,7 +4,7 @@ import {once} from "node:events"; import {resolve} from "node:path"; import {createInterface} from "node:readline"; import {resolveTestPython} from "../../../../scripts/test-python.mjs"; -import {fetchAppStewardTarget, fetchPrivateConversations, selectAppSteward, +import {ChatApiError, fetchAppStewardTarget, fetchPrivateConversations, selectAppSteward, fetchChatHistory, resolveBoundChatSession} from "../src/data/chat"; const repoRoot = resolve(process.cwd(), "../../.."); @@ -31,6 +31,12 @@ try { globalThis.fetch = (input, init) => originalFetch(new URL(String(input), origin), init); let connections = await fetchPrivateConversations(); const inspect = async () => {child.stdin.write("inspect\n"); return next();}; + const openDefault = async (overrides = {}) => { + const response = await fetch("/api/chat/sessions", {method: "POST", + headers: {"Content-Type": "application/json"}, + body: JSON.stringify({context_kind: "manager", ...overrides})}); + return {status: response.status, body: await response.json()}; + }; const before = await inspect(); assert.equal(before.sessions, 3); assert.equal(await fetchAppStewardTarget(), null, "No implicit selection between two original stewards"); @@ -39,6 +45,12 @@ try { connections = await selectAppSteward(bindingId, connections.revision); const target = {bindingId, sessionId}; assert.deepEqual(await fetchAppStewardTarget(), target); + const opened = await openDefault(); + assert.equal(opened.status, 200); + assert.equal(opened.body.session_id, sessionId, "Default API entry must reuse the configured private conversation"); + for (const overrides of [{mode: "new"}, {agent_model_id: "different-model"}]) { + assert.equal((await openDefault(overrides)).status, 400, "Explicit overrides cannot silently fork the selected source"); + } await assert.rejects(() => selectAppSteward(peer.binding_id, connections.revision - 1), /selection could not/); assert.deepEqual(await fetchAppStewardTarget(), target, "Stale selection cannot retarget the App"); const history = await fetchChatHistory({bound: target}); @@ -53,8 +65,14 @@ try { child.stdin.write("deny\n"); await next(); await assert.rejects(() => fetchAppStewardTarget(), /selected original steward is unavailable/); await assert.rejects(() => selectAppSteward(bindingId, connections.revision), /selection could not/); + assert.equal((await openDefault()).status, 400, "Failed identity verification must not fall back to a local manager"); + child.stdin.write("owner-login-missing\n"); await next(); + await assert.rejects(() => fetchAppStewardTarget(), error => error instanceof ChatApiError + && error.payload.error_code === "lark_owner_identity_unavailable"); + assert.equal((await openDefault()).status, 400); child.stdin.write("recover\n"); await next(); assert.deepEqual(await fetchAppStewardTarget(), target); + assert.equal((await openDefault()).body.session_id, sessionId, "Login recovery returns to the same original Session"); const after = await inspect(); assert.equal(after.sessions, before.sessions); assert.deepEqual(after.messages, before.messages); @@ -67,7 +85,26 @@ try { assert.equal(futurePeer.binding_id, replaced.new_peer_binding_id); assert.deepEqual(await fetchAppStewardTarget(), target, "A newly connected steward cannot capture the selected entry"); peer = futurePeer; - child.stdin.write("close\n"); await next(); + const beforeClose = await inspect(); + child.stdin.write("hold-steward-discovery\n"); + assert.deepEqual(await next(), {steward_discovery_armed: true}); + const opening = openDefault(); + assert.deepEqual(await next(), {steward_discovery_held: true}); + try { + const closed = await fetch(`/api/chat/sessions/${sessionId}`, {method: "DELETE"}); + assert.equal(closed.status, 200); + assert.equal((await closed.json()).closed, true); + } finally { + child.stdin.write("resume-steward-discovery\n"); + assert.deepEqual(await next(), {steward_discovery_released: true}); + } + const rejected = await opening; + assert.equal(rejected.status, 400, JSON.stringify(rejected.body)); + assert.match(rejected.body.error, /original steward Session is unavailable/i); + const afterClose = await inspect(); + assert.equal(afterClose.sessions, beforeClose.sessions); + assert.deepEqual(afterClose.messages, beforeClose.messages); + assert.equal(afterClose.native_requests, beforeClose.native_requests); await assert.rejects(() => fetchAppStewardTarget(), /selected original steward is unavailable/); child.stdin.write("revoke\n"); await next(); connections = await fetchPrivateConversations(); @@ -76,6 +113,9 @@ try { assert.equal((await fetchPrivateConversations()).connections[0].binding_id, peer.binding_id); connections = await selectAppSteward(null, connections.revision); assert.equal(await fetchAppStewardTarget(), null, "Only an explicit clear restores the ordinary entry"); + const local = await openDefault(); + assert.equal(local.status, 201); + assert.equal(local.body.session.channel_id, "manager", "Cleared selection preserves the existing local manager path"); const routedFetch = globalThis.fetch; for (const malformed of [{ok: true}, {ok: true, binding_id: null, session_id: sessionId}, {ok: true, binding_id: bindingId, session_id: "../other"}]) { diff --git a/apps/presentation/dashboard/smoke/bound-conversation-http-fixture.py b/apps/presentation/dashboard/smoke/bound-conversation-http-fixture.py index 8bbd6259c4..426935f323 100644 --- a/apps/presentation/dashboard/smoke/bound-conversation-http-fixture.py +++ b/apps/presentation/dashboard/smoke/bound-conversation-http-fixture.py @@ -5,6 +5,7 @@ """ from __future__ import annotations +import base64 import json import os from pathlib import Path @@ -30,6 +31,7 @@ class SyntheticPrivateSource: def __init__(self, root, *, steward=False, peer=False): self.root, self.verified = root, True + self.owner_login_missing = False self.steward, self.peer = steward, peer self.peer_provider = None default_compact_reply = "0" if os.environ.get("LOOPX_REPLY_BEFORE") == "1" else "1" @@ -38,6 +40,9 @@ def __init__(self, root, *, steward=False, peer=False): self.transport_ref = "synthetic-peer" def observe(self): + if self.owner_login_missing: + from loopx.extensions.lark.conversation_identity import LarkOwnerIdentityUnavailable + raise LarkOwnerIdentityUnavailable() provider = ("e" if self.peer else "c") * 24 operator = ("f" if self.peer else "d") * 24 if "--reply-context" in sys.argv and not self.peer: @@ -136,15 +141,28 @@ def start(self, server): "position": 1, "content": body}]}} frozen = conversation_reply_context(raw)["context_text"] + "\n\nCurrent user message:\n" + body record.update(reply_context_message=frozen, reply_context_source_text=body) - turn, _ = server.chat_store.create_turn(sid, client_turn_id=f"external-{request}", message=frozen, origin="lark") + queued_reply = "--queued-reply" in sys.argv + if queued_reply: + server.chat_store.create_turn(sid, client_turn_id="synthetic-held-turn", message="An active synthetic task.", origin="web") + create = server.chat_store.create_queued_turn if queued_reply else server.chat_store.create_turn + attachments = [] + if queued_reply: + image = "iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAIAAAASFvFNAAAAEElEQVR4nGP4v0gdghjgLABwBAqxX1jWkgAAAABJRU5ErkJggg==" + attachments = [{"id": "queued-image", "name": "queued-image.png", "mime_type": "image/png", + "size": len(base64.b64decode(image)), "data_url": "data:image/png;base64," + image}] + turn, _ = create(sid, client_turn_id=f"external-{request}", message=frozen, origin="lark", attachments=attachments) correlation = {"request_ref": request, "binding_id": binding["binding_id"], "source": source, "session_id": sid, "turn_id": turn["turn_id"]} for directory, value in (("external-requests", {**correlation, "status": "accepted", "command": None, "message": frozen}), ("lark-private-deliveries", {**record, **correlation, "status": "delivered"})): _atomic_write_json(server.chat_store.root / directory / f"{request}.json", value) - server.chat_store.update_turn(sid, turn["turn_id"], status="completed") - server.chat_store.release_active_turn(sid, turn["turn_id"]) - server.chat_store.append_message(sid, role="agent", text="已保留原要求,当前核验结果待进一步确认。", turn_id=turn["turn_id"]) + if queued_reply: + # Identical prose without admission journals must stay literal. + server.chat_store.create_queued_turn(sid, client_turn_id="synthetic-literal-context", message=frozen, origin="web") + else: + server.chat_store.update_turn(sid, turn["turn_id"], status="completed") + server.chat_store.release_active_turn(sid, turn["turn_id"]) + server.chat_store.append_message(sid, role="agent", text="已保留原要求,当前核验结果待进一步确认。", turn_id=turn["turn_id"]) paths = [server.chat_store.root / directory / f"{request}.json" for directory in ("external-requests", "lark-private-deliveries")] paths.extend([server.chat_store.sessions_root / sid / "messages.jsonl", @@ -155,18 +173,67 @@ def start(self, server): if "--returned-files" in sys.argv: returned_files, reply_evidence = self.seed_returned_files(server, original) bindings.select_app_steward(binding["binding_id"], expected_revision=bindings.read()["revision"]) + history_images = {} + if "--history-images" in sys.argv: + def image(name, encoded): + return server.chat_store.append_message(sid, role="user", text=f"Original {name}", origin="lark", + attachments=[{"id": name, "name": name + ".png", "mime_type": "image/png", + "size": len(base64.b64decode(encoded)), "data_url": "data:image/png;base64," + encoded}]) + + old = image("archived-image", "iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAIAAAA7ljmRAAAAEElEQVR4nGNQnLIKjhhwcgA6oBB17nqaVAAAAABJRU5ErkJggg==") + for index in range(75): + server.chat_store.append_message(sid, role="user", text=f"Original archived message {index:02d}.") + current = image("latest-image", "iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAIAAAASFvFNAAAAEElEQVR4nGP4v0gdghjgLABwBAqxX1jWkgAAAABJRU5ErkJggg==") + server.chat_store.append_message(sid, role="agent", text="Latest original result after archived images.") + history_images = {"historyImages": {"old": old["message_id"], "current": current["message_id"]}} + original_image_handler = server.RequestHandlerClass._serve_chat_history_image + failed = False + failure_lock = threading.Lock() + + def fail_first_image_read(handler, parts): + nonlocal failed + with failure_lock: + fail = parts[3] == sid and parts[5] == old["message_id"] and not failed + failed |= fail + if fail: + handler._send_error("Fixture image temporarily unavailable", status=503) + return True + return original_image_handler(handler, parts) + + server.RequestHandlerClass._serve_chat_history_image = fail_first_image_read + journal = server.chat_store.sessions_root / sid / "messages.jsonl" + reply_evidence[journal] = journal.read_bytes() other, _ = runtime.open_session(goal_id=None, agent_id="codex", objective="", mode="new", work_dir=self.root / "project", project_ref=binding["project_ref"]) server.chat_store.append_message(other["session_id"], role="agent", text="Unrelated desktop conversation — must remain separate.") print(json.dumps({"origin": f"http://127.0.0.1:{server.server_port}", "bindingId": binding["binding_id"], "sessionId": sid, "ordinarySessionId": other["session_id"], - **returned_files}), flush=True) + **returned_files, **history_images}), flush=True) settings_handler = server.RequestHandlerClass._private_conversations history_handler = server.RequestHandlerClass._session_snapshot sessions_handler = server.RequestHandlerClass._list_sessions slow_page, slow_source = threading.Event(), threading.Event() + history_unavailable = threading.Event() + hold_steward_discovery, resume_steward_discovery = threading.Event(), threading.Event() + + if self.steward: + core = bindings._core + + def controlled_core(operation, params, **kwargs): + result = core(operation, params, **kwargs) + if (operation == "collaboration.conversation.local_sessions" + and params.get("app_steward_entry") and hold_steward_discovery.is_set()): + hold_steward_discovery.clear() + print(json.dumps({"steward_discovery_held": True}), flush=True) + if not resume_steward_discovery.wait(15): + raise TimeoutError("steward discovery fixture was not released") + return result + + bindings._core = controlled_core def delayed_history(handler, selected_session): + if selected_session == sid and history_unavailable.is_set(): + return handler._send_error("Chat history is temporarily unavailable", status=503) if selected_session == sid and slow_page.is_set(): slow_page.clear() time.sleep(5.2) @@ -186,12 +253,23 @@ def control(): command = line.strip() if command in {"deny", "recover"}: self.verified = command == "recover" + self.owner_login_missing = False result = {"source_verified": self.verified} + elif command == "owner-login-missing": + self.owner_login_missing = True + result = {"owner_login_missing": True} elif command == "source": accepted, _ = runtime.enqueue_turn(session_id=sid, message="A new synthetic message from the original private source.", client_turn_id="synthetic-source-update", origin="lark", work_dir=self.root / "project", objective="") turn = runtime.wait_for_turn(session_id=sid, turn_id=accepted["turn_id"], timeout_sec=15) result = {"source_turn_status": turn["status"]} + elif command == "hold-steward-discovery": + resume_steward_discovery.clear() + hold_steward_discovery.set() + result = {"steward_discovery_armed": True} + elif command == "resume-steward-discovery": + resume_steward_discovery.set() + result = {"steward_discovery_released": True} elif command == "close": server.chat_store.update_session(sid, status="closed") result = {"closed": True} @@ -201,6 +279,12 @@ def control(): elif command == "slow-history-source": slow_source.set() result = {"slow_history_source": True} + elif command in {"history-unavailable", "history-available"}: + if command == "history-unavailable": + history_unavailable.set() + else: + history_unavailable.clear() + result = {"history_available": not history_unavailable.is_set()} elif command == "replace-peer" and self.peer_provider is not None: old = next(row for row in bindings.read()["bindings"] if row["transport_ref"] == self.peer_provider.transport_ref) bindings.disconnect(old["binding_id"], expected_revision=bindings.read()["revision"]) @@ -242,6 +326,32 @@ def unavailable(handler): elif command == "history-extra": server.chat_store.append_message(sid, role="agent", text="A full new original result. " * 150) result = {"history_rows": len(server.chat_store.messages(sid))} + elif command in {"history-return", "history-return-delivered", "history-return-unverified", + "history-return-unreadable"}: + from loopx.capabilities.manager_context import _hash, _root, _write + + store = server.chat_store + root = runtime.coordination_runtime_root + request_id = "b" * 64 + reply_dir = _root(root) / "replies" / request_id + message_id = f"handoff.{_hash([request_id, 'conclusion'])}" + if command == "history-return": + _write(_root(root) / "roundtrips" / f"{request_id}.json", { + "request_id": request_id, "session_id": sid, + "source_chat_runtime_root": str(store.root.parent), + }) + _write(reply_dir / "conclusion.json", {"text": "Original delegated result."}) + store.append_message(sid, role="agent", text="Original delegated result.", + origin="manager_followup", message_id=message_id) + elif command == "history-return-delivered": + _write(reply_dir / "conclusion.delivery.json", {"status": "delivered"}) + elif command == "history-return-unverified": + _write(reply_dir / "conclusion.delivery.json", { + "status": "explicit_unverified", "error": "provider_delivery_unverified", + }) + else: + (reply_dir / "conclusion.delivery.json").write_text("{", encoding="utf-8") + result = {"messageId": message_id} elif command == "history-rewrite": journal = server.chat_store.sessions_root / sid / "messages.jsonl" rows = [json.loads(line) for line in journal.read_text().splitlines()] @@ -249,6 +359,16 @@ def unavailable(handler): target["text"] = "Changed earlier original row 10" journal.write_text("".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows)) result = {"history_rows": len(rows)} + elif command == "history-image-refresh" and history_images: + journal = server.chat_store.sessions_root / sid / "messages.jsonl" + rows = [json.loads(line) for line in journal.read_text().splitlines()] + archived = next(row for row in rows if row["message_id"] == history_images["historyImages"]["old"]) + latest = next(row for row in rows if row["message_id"] == history_images["historyImages"]["current"]) + for key in ("data_url", "size"): + archived["attachments"][0][key] = latest["attachments"][0][key] + journal.write_text("".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows)) + reply_evidence[journal] = journal.read_bytes() + result = {"history_image_refreshed": archived["message_id"]} elif command == "inspect": saved = server.chat_store.load_session(sid) result = {"sessions": len(server.chat_store.list_sessions()), "original_thread": saved["upstream_thread_id"], diff --git a/apps/presentation/dashboard/smoke/bound-conversation-smoke.ts b/apps/presentation/dashboard/smoke/bound-conversation-smoke.ts index b0c3e86794..e78e28c46b 100644 --- a/apps/presentation/dashboard/smoke/bound-conversation-smoke.ts +++ b/apps/presentation/dashboard/smoke/bound-conversation-smoke.ts @@ -167,6 +167,24 @@ try { assert.equal(recovered.pendingReads?.size, 0); assert.ok(calls.every(row => row.method === "GET"), "Recovery never starts work"); globalThis.fetch = routedRead; + const plain503Offsets: number[] = []; + globalThis.fetch = async (input, init) => { + const response = await routedRead(input, init); + if (new URL(String(input), origin).pathname !== `/api/chat/sessions/${sessionId}`) return response; + const {message_page: {offset}} = await response.clone().json(); + plain503Offsets.push(offset); + if (offset === 200 && plain503Offsets.length === 2) { + return Response.json({error: "Original history store unavailable"}, {status: 503}); + } + return response; + }; + const boundUnavailable = await fetchChatHistory(options); + assert.deepEqual(boundUnavailable.messages, []); + assert.equal(boundUnavailable.pendingReads?.get(sessionId)?.messages.length, 200); + assert.deepEqual((await fetchChatHistory(options, boundUnavailable)).messages, recovered.messages); + assert.deepEqual(plain503Offsets, [0, 200, 200, 400]); + globalThis.fetch = routedRead; + // If the fresh post-history source read loses its connection, keep the // verified pages private until a later source check succeeds. const isBoundDiscovery = (input: RequestInfo | URL) => @@ -282,6 +300,96 @@ try { assert.ok(rewritten.messages.some(row => row.text === "Changed earlier original row 10")); assert.ok(!rewritten.messages.some(row => row.text === "Paged bound row 10")); + child.stdin.write("history-return\n"); + const {messageId} = await next(); + const queued = await fetchChatHistory(options, rewritten); + const returnStatus = (snapshot: typeof queued) => snapshot.messages + .find(row => row.message_id === messageId)?.return_delivery?.status; + assert.equal(returnStatus(queued), "queued"); + calls.length = 0; + assert.equal(returnStatus(await fetchChatHistory(options, queued)), "queued"); + assert.equal(readRequests().length, 1, "An unchanged pending return only needs the history proof"); + + sourceChecks = 0; + globalThis.fetch = (input, init) => { + if (isBoundDiscovery(input) && ++sourceChecks === 2) throw new Error("Lost pending return source check"); + return routedRead(input, init); + }; + const awaitingReturnSource = await fetchChatHistory(options); + assert.deepEqual(awaitingReturnSource.messages, []); + assert.deepEqual(awaitingReturnSource.snapshots, []); + assert.equal(awaitingReturnSource.pendingBoundSnapshot?.snapshot.messages + .find(row => row.message_id === messageId)?.return_delivery?.status, "queued"); + globalThis.fetch = routedRead; + + calls.length = 0; + assert.equal(returnStatus(await fetchChatHistory(options, awaitingReturnSource)), "queued"); + assert.deepEqual(readRequests().map(url => url.searchParams.has("known_history")), [true], + "Recovery of a private transcript with a pending return only needs the history proof if it still matches"); + assert.equal(calls.filter(row => new URL(row.path, origin).pathname === "/api/chat/sessions").length, 2, + "Recovery checks the original binding again after verifying the retained history"); + + child.stdin.write("history-return-delivered\n"); + assert.equal((await next()).messageId, messageId); + calls.length = 0; + const delivered = await fetchChatHistory(options, queued); + assert.equal(delivered.sessions[0].transcript_revision, queued.sessions[0].transcript_revision); + assert.equal(returnStatus(delivered), "delivered", "A return can complete without rewriting the Chat transcript"); + assert.equal(delivered.messages.length, queued.messages.length); + assert.equal(readRequests()[0].searchParams.has("known_history"), true); + assert.ok(calls.every(row => row.method === "GET")); + calls.length = 0; + const deliveredWhileWaiting = await fetchChatHistory(options, awaitingReturnSource); + assert.deepEqual(deliveredWhileWaiting.messages, delivered.messages); + assert.equal(readRequests()[0].searchParams.has("known_history"), true); + assert.equal(readRequests()[1].searchParams.has("message_cursor"), false, + "A pending return that changed while the source was unavailable restarts at page zero"); + calls.length = 0; + assert.equal(returnStatus(await fetchChatHistory(options, delivered)), "delivered"); + assert.equal(readRequests().length, 0, "A settled immutable transcript uses the compact discovery read again"); + + child.stdin.write("history-return-unreadable\n"); + assert.equal((await next()).messageId, messageId); + const unreadable = await fetchChatHistory(options, queued); + assert.equal(returnStatus(unreadable), "explicit_unverified"); + assert.equal(unreadable.messages.find(row => row.message_id === messageId)?.return_delivery?.error, + "delivery_state_unreadable"); + + child.stdin.write("history-return-unverified\n"); + assert.equal((await next()).messageId, messageId); + const unverified = await fetchChatHistory(options, unreadable); + assert.equal(returnStatus(unverified), "explicit_unverified"); + assert.equal(unverified.messages.find(row => row.message_id === messageId)?.return_delivery?.error, + "provider_delivery_unverified", "The owner recorded a failed verification, not a successful delivery"); + calls.length = 0; + assert.equal(returnStatus(await fetchChatHistory(options, unverified)), "explicit_unverified"); + assert.equal(readRequests().length, 0, "An owner-recorded terminal failure does not repeatedly fetch history"); + + child.stdin.write("history-extra\n"); + await next(); + child.stdin.write("history-unavailable\n"); + assert.equal((await next()).history_available, false); + const coldUnavailable = await fetchChatHistory(options); + assert.deepEqual(coldUnavailable.snapshots, [], "No verified transcript exists on a first read"); + assert.deepEqual(coldUnavailable.unavailableSessionIds, [sessionId]); + calls.length = 0; + const degraded = await fetchChatHistory(options, unverified); + assert.deepEqual(degraded.messages, unverified.messages, "An HTTP 503 alone must not hide verified history"); + assert.equal(degraded.snapshots[0]?.session.session_id, sessionId, "The same original composer retains a usable snapshot"); + assert.deepEqual(degraded.unavailableSessionIds, [sessionId], "Report the incomplete refresh without emptying history"); + assert.equal(calls.filter(row => isBoundDiscovery(row.path)).length, 2, + "A cached transcript is usable only after the bound source is checked again"); + child.stdin.write("deny\n"); + assert.equal((await next()).source_verified, false); + await assert.rejects(() => fetchChatHistory(options, degraded), + "Missing authority is not a degraded history read"); + child.stdin.write("recover\n"); + assert.equal((await next()).source_verified, true); + child.stdin.write("history-available\n"); + assert.equal((await next()).history_available, true); + const resumedAfterUnavailable = await fetchChatHistory(options, degraded); + assert.equal(resumedAfterUnavailable.messages.length, unverified.messages.length + 1); + assert.deepEqual(resumedAfterUnavailable.unavailableSessionIds, []); child.stdin.write("history-extra\n"); await next(); globalThis.fetch = async (input, init) => { @@ -292,7 +400,7 @@ try { } return response; }; - await assert.rejects(() => fetchChatHistory(options, rewritten), "A revoked original binding cannot publish a suffix"); + await assert.rejects(() => fetchChatHistory(options, resumedAfterUnavailable), "A revoked original binding cannot publish a suffix"); globalThis.fetch = routedRead; child.stdin.write("recover\n"); assert.equal((await next()).source_verified, true); diff --git a/apps/presentation/dashboard/smoke/compaction-memory-retirement-browser-smoke.mjs b/apps/presentation/dashboard/smoke/compaction-memory-retirement-browser-smoke.mjs new file mode 100644 index 0000000000..5d3c9276f8 --- /dev/null +++ b/apps/presentation/dashboard/smoke/compaction-memory-retirement-browser-smoke.mjs @@ -0,0 +1,107 @@ +// Retirement regression: a saved experimental opt-in stays inert and hidden; +// sibling settings retain real preview/apply/readback and stale-write recovery. +// Isolated machine, empty registry, unavailable native host; no model calls. +import assert from "node:assert/strict"; +import {spawn} from "node:child_process"; +import {mkdtemp, mkdir, rm, writeFile} from "node:fs/promises"; +import {tmpdir} from "node:os"; +import {join, resolve} from "node:path"; +import {resolveTestPython} from "../../../../scripts/test-python.mjs"; +import {launchBrowser, loadPlaywright, waitForHttp} from "../../../../examples/dashboard-browser-smoke-support.mjs"; + +const repoRoot = resolve(import.meta.dirname, "../../../.."); +const root = await mkdtemp(join(tmpdir(), "loopx-compaction-preference-")); +const port = Number(process.env.LOOPX_COMPACTION_MEMORY_PORT ?? 5414); +const screenshots = process.env.LOOPX_COMPACTION_MEMORY_SCREENSHOTS; +const registry = join(root, "registry.json"); +await mkdir(join(root, "runtime", "machine"), {recursive: true}); +await writeFile(join(root, "runtime", "machine", "configuration.json"), JSON.stringify({ + schema_version: "loopx_machine_configuration_v0", namespaces: { + compaction_memory: {schema_version: "compaction_memory_machine_defaults_v0", enabled: true}, + }, +})); +await writeFile(registry, '{"goals":[]}'); +await mkdir(join(root, "home")); +if (screenshots) await mkdir(screenshots, {recursive: true}); +const server = spawn(resolveTestPython({repoRoot}), ["-m", "loopx.cli", "--registry", registry, + "--runtime-root", join(root, "runtime"), "chat", "--port", String(port), "--no-open", + "--codex-bin", join(root, "unavailable-native-host"), "--assets-dir", join(repoRoot, "loopx/web/chat")], { + cwd: root, env: {...process.env, HOME: join(root, "home"), PYTHONPATH: repoRoot, LOOPX_USAGE_PING: "0"}, + stdio: ["ignore", "pipe", "pipe"], +}); +let serverError = "", browser; +for (const stream of [server.stdout, server.stderr]) stream.on("data", chunk => {serverError += String(chunk);}); +try { + const base = `http://127.0.0.1:${port}`; + await waitForHttp(`${base}/chat/`).catch(error => {throw new Error(`${error.message}\n${serverError}`);}); + browser = await launchBrowser(loadPlaywright().chromium); + const page = await browser.newPage({locale: "en-US", viewport: {width: 1440, height: 1000}}); + const workRequests = []; + page.on("request", request => { + if (request.method() === "POST") { + const path = new URL(request.url()).pathname; + if (path === "/api/chat/sessions" || /^\/api\/chat\/sessions\/[^/]+\/turns$/u.test(path)) workRequests.push(path); + } + }); + const open = async () => { + await page.goto(`${base}/chat/?settings_scope=machine&settings_tab=capabilities`, {waitUntil: "networkidle"}); + await page.getByText("Progressive context", {exact: true}).first().click(); + assert.equal(await page.getByText("Compaction working memory (experimental)", {exact: true}).count(), 0); + assert.equal(await page.getByRole("switch", {name: "Enable experimental compaction working memory"}).count(), 0); + }; + const progressive = page.getByRole("switch", {name: "Read context progressively"}); + const delta = page.getByRole("switch", {name: "Use cross-turn delta automatically on supported hosts"}); + const configuration = async () => (await (await page.request.get(`${base}/api/chat/machine-configuration`)).json()).machine_configuration; + const capture = async name => { + if (screenshots) await page.screenshot({path: join(screenshots, name)}); + }; + await open(); + assert.equal(await progressive.isChecked(), true); + assert.equal(await delta.isChecked(), true); + assert.equal((await configuration()).namespaces.compaction_memory, undefined); + await capture("desktop-settings.png"); + await page.setViewportSize({width: 430, height: 932}); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true); + await capture("narrow-settings.png"); + await page.setViewportSize({width: 1440, height: 1000}); + + // Keep the actual backend and invalidate only the request's CAS expectation. + const apply = "**/api/chat/machine-configuration/apply"; + await page.route(apply, route => route.continue({postData: JSON.stringify({ + ...route.request().postDataJSON(), expected_plan_revision: `sha256:${"0".repeat(64)}`, + })})); + await progressive.click(); + await page.getByText(/machine-configuration plan revision changed/u).waitFor(); + assert.equal(await progressive.isChecked(), true, "A rejected save retains the confirmed value"); + assert.equal((await configuration()).namespaces.context_delivery, undefined); + await capture("desktop-rejected.png"); + await page.unroute(apply); + await progressive.click(); + await page.getByText("Progressive reads preference saved.", {exact: true}).waitFor(); + assert.equal((await configuration()).namespaces.context_delivery.mode, "off"); + assert.equal(await delta.isChecked(), true); + await delta.click(); + await page.getByText("Cross-turn delta preference saved.", {exact: true}).waitFor(); + assert.equal((await configuration()).namespaces.context_delivery.delta_delivery, "off"); + assert.equal(await progressive.isChecked(), false); + await open(); + assert.equal(await progressive.isChecked(), false); + assert.equal(await delta.isChecked(), false); + assert.equal((await configuration()).namespaces.compaction_memory, undefined); + await page.evaluate(() => localStorage.setItem("loopx-pw-locale", "zh-CN")); + await page.reload({waitUntil: "networkidle"}); + assert.equal(await page.getByText("压缩工作记忆(实验)", {exact: true}).count(), 0); + assert.equal(await page.getByRole("switch", {name: "启用实验性压缩工作记忆"}).count(), 0); + await capture("chinese-settings.png"); + // Existing Workbench entry may create Session metadata; no Turn is dispatched. + assert.equal(workRequests.some(path => path.endsWith("/turns")), false); + console.log("compaction memory retirement: legacy-on hidden; sibling save/reload/stale-write recovery passed"); +} finally { + await browser?.close(); + if (server.exitCode === null) { + const exited = new Promise(resolveExit => server.once("exit", resolveExit)); + server.kill(); + await exited; + } + await rm(root, {recursive: true, force: true}); +} diff --git a/apps/presentation/dashboard/smoke/conversation-find-browser-smoke.mjs b/apps/presentation/dashboard/smoke/conversation-find-browser-smoke.mjs new file mode 100644 index 0000000000..46f2575ab1 --- /dev/null +++ b/apps/presentation/dashboard/smoke/conversation-find-browser-smoke.mjs @@ -0,0 +1,144 @@ +// Packaged reader, production HTTP/store, synthetic messages; no model calls. +import assert from "node:assert/strict"; +import {spawn} from "node:child_process"; +import {once} from "node:events"; +import {createInterface} from "node:readline"; +import {mkdir} from "node:fs/promises"; +import {resolve} from "node:path"; +import {resolveTestPython} from "../../../../scripts/test-python.mjs"; +import {launchBrowser, loadPlaywright, waitForHttp} from "../../../../examples/dashboard-browser-smoke-support.mjs"; + +process.env.LOOPX_PERSONAL_WORKSPACE_PACKAGED = "1"; +const {repoRoot, outputDir, port, startServer} = await import("../../../../examples/personal-workspace-browser/fixture.mjs"); +const {openWorkspacePage} = await import("../../../../examples/personal-workspace-browser/scenario-context.mjs"); +const child = spawn(resolveTestPython({repoRoot}), ["-u", "apps/presentation/dashboard/smoke/conversation-history-http-fixture.py", "--manager", "--find"], + {cwd: repoRoot, stdio: ["pipe", "pipe", "pipe"]}); +const exited = once(child, "exit"), lines = createInterface({input: child.stdout}); +const iterator = lines[Symbol.asyncIterator](); +let stderr = "", browser, server, workspace; +child.stderr.on("data", data => {stderr += String(data);}); +async function next() {const row = await iterator.next(); assert.equal(row.done, false, stderr); return JSON.parse(row.value);} +async function command(value) {child.stdin.write(`${value}\n`); return next();} +try { + const {origin} = await next(); + await command("recover"); + server = await startServer(); + const url = `http://127.0.0.1:${port}/chat/?statusUrl=/status.json`; + await waitForHttp(url); + browser = await launchBrowser(loadPlaywright().chromium); + for (const locale of ["en", "zh-CN"]) { + const zh = locale === "zh-CN"; + await command("fault"); + workspace = await openWorkspacePage(browser, url, {beforeGoto(_api, page) { + return Promise.all([page.addInitScript(value => localStorage.setItem("loopx-pw-locale", value), locale), + page.route("**/api/chat/sessions**", async route => { + const request = route.request(), target = new URL(request.url()); + if (!/^\/api\/chat\/sessions(?:\/(?:old|current|other-channel))?$/u.test(target.pathname)) return route.fallback(); + if (request.method() === "POST" && target.pathname === "/api/chat/sessions") { + if (request.postDataJSON().context_kind !== "manager") return route.fallback(); + const response = await route.fetch({url: `${origin}/api/chat/sessions/current`, method: "GET", postData: undefined}); + const snapshot = await response.json(); + return route.fulfill({status: 201, json: {ok: true, resumed: true, session_id: "current", session: snapshot.session}}); + } + assert.equal(request.method(), "GET", "Finding original messages cannot mutate the store"); + const response = await route.fetch({url: `${origin}${target.pathname}${target.search}`}); + return route.fulfill({response}); + })]); + }}); + const {page, api} = workspace; + await page.getByRole("navigation", {name: zh ? "管家视图" : "Manager view"}).getByRole("button", {name: /^(Chat|对话)$/}).click(); + const toggle = page.getByRole("button", {name: zh ? "查找对话" : "Find in conversation", exact: true}); + await toggle.click(); + const input = page.getByRole("searchbox", {name: zh ? "查找已加载消息" : "Find in loaded messages"}); + await input.fill("lunar"); + const bar = page.locator(".personal-conversation-find"), active = page.locator(".personal-message.is-find-match"); + await bar.getByRole("status").filter({hasText: "1 / 2"}).waitFor(); + await bar.getByText(zh ? "对话记录尚未完整读取,结果仅包含已加载消息。" : "History is incomplete; results include loaded messages only.").waitFor(); + const retained = await active.getAttribute("data-timeline-id"); + await command("recover"); + await page.getByRole("button", {name: zh ? "重试读取" : "Retry history", exact: true}).click(); + await bar.getByRole("status").filter({hasText: "2 / 3"}).waitFor(); + assert.equal(await active.getAttribute("data-timeline-id"), retained, "Backfill preserves the selected original message"); + // Reopen the timeline after the complete read to exercise folded history. + await page.locator(".personal-goal-link").first().click(); + await page.locator(".personal-manager-link").click(); + await page.getByRole("navigation", {name: zh ? "管家视图" : "Manager view"}).getByRole("button", {name: /^(Chat|对话)$/}).click(); + await toggle.click(); await input.fill("lunar"); + await bar.getByRole("status").filter({hasText: "1 / 3"}).waitFor(); + await active.getByText("Keep the lunar evidence. 保留原始证据。", {exact: true}).waitFor(); + assert.equal(await active.getByRole("button", {name: zh ? "收起消息" : "Collapse message"}).getAttribute("aria-expanded"), "true"); + const first = await active.getAttribute("data-timeline-id"); + await input.dispatchEvent("keydown", {key: "Escape", isComposing: true}); + assert.equal(await input.count(), 1, "IME composition does not close the reader"); + await input.press("Enter"); + await bar.getByRole("status").filter({hasText: "2 / 3"}).waitFor(); + assert.notEqual(await active.getAttribute("data-timeline-id"), first); + await input.press("Shift+Enter"); + await bar.getByRole("status").filter({hasText: "1 / 3"}).waitFor(); + await page.waitForFunction(key => document.querySelector(".is-find-match")?.getAttribute("data-timeline-id") === key, first); + await page.getByRole("button", {name: zh ? "上一条匹配消息" : "Previous matching message"}).click(); + await bar.getByRole("status").filter({hasText: "3 / 3"}).waitFor(); + await input.fill("保留原始证据"); + await bar.getByRole("status").filter({hasText: "1 / 1"}).waitFor(); + for (const width of [1200, 390]) { + await page.setViewportSize({width, height: 844}); + // Leave the long original expanded so the old short message can be scrolled away. + await input.fill("Earlier public report"); + await bar.getByRole("status").filter({hasText: "1 / 1"}).waitFor(); + const inViewport = () => page.waitForFunction(() => { + const row = document.querySelector(".is-find-match")?.getBoundingClientRect(); + const viewport = document.querySelector(".personal-channel-scroll")?.getBoundingClientRect(); + return row && viewport && row.top >= viewport.top && row.bottom <= viewport.bottom; + }, undefined, {timeout: 5000}); + await inViewport(); + for (const key of ["Enter", "Shift+Enter", "arrow"]) { + await page.locator(".personal-channel-scroll").evaluate(node => {node.scrollTop = node.scrollHeight;}); + assert(await active.evaluate(node => node.getBoundingClientRect().bottom < node.closest(".personal-channel-scroll").getBoundingClientRect().top), "The unique old message is outside the viewport before navigating again"); + if (key === "arrow") await bar.getByRole("button", {name: zh ? "上一条匹配消息" : "Previous matching message"}).click(); + else await input.press(key); + await inViewport(); + } + await input.fill("保留原始证据"); + for (const action of ["arrow", "Shift+Enter"]) { + await active.getByRole("button", {name: zh ? "收起消息" : "Collapse message", exact: true}).click(); + await active.getByRole("button", {name: zh ? "展开完整消息" : "Read full message", exact: true}).waitFor(); + if (action === "arrow") await bar.getByRole("button", {name: zh ? "下一条匹配消息" : "Next matching message"}).click(); + else await input.press(action); + await active.getByText("Keep the lunar evidence. 保留原始证据。", {exact: true}).waitFor({timeout: 5000}); + assert.equal(await active.getByRole("button", {name: zh ? "收起消息" : "Collapse message"}).getAttribute("aria-expanded"), "true"); + } + } + await page.setViewportSize({width: 1200, height: 844}); + await mkdir(outputDir, {recursive: true}); + // Short matching messages keep the useful reading context in the preview. + await input.fill("final report"); + await bar.getByRole("status").filter({hasText: "1 / 1"}).waitFor(); + await page.getByRole("button", {name: zh ? "收起消息" : "Collapse message", exact: true}).click(); + await input.fill(""); await input.fill("final report"); + await active.getByText("Please retain LUNAR evidence in the final report.", {exact: true}).waitFor(); + await page.screenshot({path: resolve(outputDir, `conversation-find-${locale}-desktop.png`), animations: "disabled"}); + await page.setViewportSize({width: 390, height: 844}); + assert(await page.locator("body").evaluate(body => body.scrollWidth <= innerWidth + 1)); + await page.screenshot({path: resolve(outputDir, `conversation-find-${locale}-mobile.png`), animations: "disabled"}); + await input.fill("[no such literal message]"); + await bar.getByRole("status").filter({hasText: zh ? "没有匹配消息" : "No matching messages"}).waitFor(); + assert.equal(await active.count(), 0); + assert(await page.getByRole("button", {name: zh ? "下一条匹配消息" : "Next matching message"}).isDisabled()); + await input.press("Escape"); + assert(await toggle.evaluate(button => button === document.activeElement)); + assert.equal(await input.count(), 0); + await page.setViewportSize({width: 1512, height: 982}); + await toggle.click(); await input.fill("lunar"); + await page.locator(".personal-goal-link").first().click(); + await page.locator(".personal-manager-link").click(); + await page.getByRole("navigation", {name: zh ? "管家视图" : "Manager view"}).getByRole("button", {name: /^(Chat|对话)$/}).click(); + assert.equal(await input.count(), 0, "Changing the conversation discards its private search"); + assert.equal(api.turnRequests.length, 0); + assert.deepEqual(await command("inspect"), {store_unchanged: true, turn_count: 0}); + await workspace.close(); workspace = null; + } + console.log("conversation-find: packaged HTTP/store, en/zh, full-text expansion, navigation/wrap, literal no-match, scope reset, narrow layout and zero writes passed"); +} finally { + await workspace?.close(); await browser?.close(); server?.kill("SIGTERM"); + child.stdin.end(); if (child.exitCode === null) await exited; lines.close(); +} diff --git a/apps/presentation/dashboard/smoke/conversation-history-http-fixture.py b/apps/presentation/dashboard/smoke/conversation-history-http-fixture.py index 2dbfbb3d9c..0fb2710907 100644 --- a/apps/presentation/dashboard/smoke/conversation-history-http-fixture.py +++ b/apps/presentation/dashboard/smoke/conversation-history-http-fixture.py @@ -44,6 +44,14 @@ def main() -> None: store.create_session(goal_id="research", agent_id="codex", adapter_kind="codex_app_server", upstream_thread_id=session_id, channel_id=channel, session_id=session_id) store.append_message(session_id, role="agent", text=text, message_id="answer") + if "--find" in sys.argv: + store.append_message("old", role="agent", message_id="long-evidence", + text="## Earlier acceptance decision\n\n" + "Original reviewed material. " * 300 + + "\n\nKeep the lunar evidence. 保留原始证据。") + store.append_message("current", role="user", message_id="correction", + text="Please retain LUNAR evidence in the final report.") + store.append_message("current", role="agent", message_id="latest", + text="The lunar evidence is retained. Awaiting the next independent check.") before = {str(path.relative_to(store.sessions_root)): path.read_bytes() for path in store.sessions_root.rglob("*") if path.is_file()} server = ChatHTTPServer(("127.0.0.1", 0), HistoryReadFault) diff --git a/apps/presentation/dashboard/smoke/conversation-history-order-browser-smoke.mjs b/apps/presentation/dashboard/smoke/conversation-history-order-browser-smoke.mjs index 4589dd28e6..48747950fe 100644 --- a/apps/presentation/dashboard/smoke/conversation-history-order-browser-smoke.mjs +++ b/apps/presentation/dashboard/smoke/conversation-history-order-browser-smoke.mjs @@ -5,7 +5,7 @@ import { cleanupBrowserSmoke, launchBrowser, loadPlaywright, startViteDashboardS const dashboardDir = fileURLToPath(new URL("..", import.meta.url)); const port = Number(process.env.LOOPX_HISTORY_ORDER_PORT ?? "5298"); const origin = `http://127.0.0.1:${port}`; -const server = startViteDashboardServer({ dashboardDir, port }); +const server = await startViteDashboardServer({ dashboardDir, port }); const scenarios = ["late-backfill", "failed-backfill", "backfill-during-refresh", "refresh-after-backfill", "overlapping-refreshes", "scope-switch", "scope-return", "retry-progress", "closed-first", "closed-only", "failed-current"]; function session(id, goal, version = 0) { diff --git a/apps/presentation/dashboard/smoke/conversation-reply-browser-smoke.mjs b/apps/presentation/dashboard/smoke/conversation-reply-browser-smoke.mjs index 9192c131a2..54f1f41596 100644 --- a/apps/presentation/dashboard/smoke/conversation-reply-browser-smoke.mjs +++ b/apps/presentation/dashboard/smoke/conversation-reply-browser-smoke.mjs @@ -11,10 +11,13 @@ import {launchBrowser, loadPlaywright} from "../../../../examples/dashboard-brow const repo = resolve(import.meta.dirname, "../../../.."); const returnedFiles = process.argv.includes("--returned-files"); +const historyImages = process.argv.includes("--history-images"); +const queuedReply = process.argv.includes("--queued-reply"); const output = resolve(process.env.LOOPX_REPLY_OUTPUT ?? resolve(repo, "output/playwright/conversation-reply")); await mkdir(output, {recursive: true}); const child = spawn(resolveTestPython({repoRoot: repo}), ["-u", - "apps/presentation/dashboard/smoke/bound-conversation-http-fixture.py", returnedFiles ? "--returned-files" : "--reply-context"], + "apps/presentation/dashboard/smoke/bound-conversation-http-fixture.py", returnedFiles ? "--returned-files" : "--reply-context", + ...(historyImages ? ["--history-images"] : []), ...(queuedReply ? ["--queued-reply"] : [])], {cwd: repo, env: {...process.env, LOOPX_USAGE_PING: "0"}, stdio: ["pipe", "pipe", "pipe"]}); const exited = once(child, "exit"), queue = [], waiting = []; let stderr = "", browser; @@ -78,11 +81,21 @@ async function checkReturnedFiles(ready, page, errors, writes) { } } await page.screenshot({path: resolve(output, `${baseline ? "before" : "after"}-files-desktop.png`), animations: "disabled"}); + const historyPath = `/api/chat/sessions/${ready.sessionId}`; + const readerRequest = page.context().waitForEvent("request", {predicate: request => + new URL(request.url()).pathname === historyPath + && new URL(request.frame().url()).searchParams.get("reportMessageId") === ready.fileMessageId}); const opened = page.context().waitForEvent("page"); await timeline.getByRole("link", {name: "单独阅读完整答复"}).click(); const report = await opened; report.on("pageerror", error => errors.push(error.message)); await report.getByRole("heading", {name: "结果已核验 / Verified result", exact: true}).waitFor(); + const readerQuery = new URL((await readerRequest).url()).searchParams; + if (!baseline) { + assert.equal(readerQuery.get("turn_id"), answer.turn_id, "The saved answer checks its original Turn"); + assert.equal(readerQuery.get("report_message_id"), answer.message_id, "The reader requests only the chosen answer"); + assert.equal(readerQuery.has("message_limit"), false); + } assert.equal(await report.locator("a[download]").count(), baseline ? 0 : ready.files.length); await report.screenshot({path: resolve(output, `${baseline ? "before" : "after"}-files-reader.png`), animations: "disabled"}); if (!baseline) { @@ -107,6 +120,91 @@ async function checkReturnedFiles(ready, page, errors, writes) { const url = ready.origin + answer.attachments[0].data_url; assert.equal((await page.request.get(url.replace(ready.sessionId, "unrelated-session"))).status(), 404); assert.equal((await page.request.get(url, {headers: {Origin: "https://unrelated.example"}})).status(), 403); + + const legacy = new URL(report.url()); + legacy.searchParams.delete("reportTurnId"); + const savedAnswerRequest = url => url.pathname === historyPath && url.searchParams.get("report_message_id") === ready.fileMessageId; + const legacyRead = report.waitForResponse(response => new URL(response.url()).pathname === historyPath); + await report.goto(legacy.toString()); + await report.getByRole("link", {name: "Download file: source.bin", exact: false}).waitFor(); + const legacyResponse = await legacyRead; + assert.ok(savedAnswerRequest(new URL(legacyResponse.url())), "An existing link selects its saved message without loading the transcript"); + const legacySnapshot = await legacyResponse.json(); + assert.deepEqual(legacySnapshot.messages.filter(row => row.role !== "user").map(row => row.message_id), [ready.fileMessageId]); + const legacyAnswer = legacySnapshot.messages.find(row => row.message_id === ready.fileMessageId); + assert.equal(legacyAnswer.text, answer.text); + assert.deepEqual(legacyAnswer.attachments, answer.attachments); + + await report.route(savedAnswerRequest, route => route.fulfill({status: 400, json: {ok: false, error: "invalid history page arguments"}})); + const fallbackRead = report.waitForRequest(request => { + const url = new URL(request.url()); + return url.pathname === historyPath && url.search === ""; + }); + await report.reload(); + await report.getByRole("link", {name: "Download file: source.bin", exact: false}).waitFor(); + await fallbackRead; + + const fallbackTurnRead = report.waitForRequest(request => { + const url = new URL(request.url()); + return url.pathname === historyPath && url.searchParams.get("turn_id") === answer.turn_id && url.searchParams.has("message_limit"); + }); + const withTurn = new URL(legacy); + withTurn.searchParams.set("reportTurnId", answer.turn_id); + await report.goto(withTurn.toString()); + await report.getByRole("link", {name: "Download file: source.bin", exact: false}).waitFor(); + await fallbackTurnRead; + await report.unroute(savedAnswerRequest); + await report.goto(legacy.toString()); + await report.getByRole("link", {name: "Download file: source.bin", exact: false}).waitFor(); + + // Earlier history readers accept unknown query arguments and return their + // complete v1 snapshot. Both existing and Turn-pinned links still open it. + await report.route(savedAnswerRequest, route => route.fulfill({json: snapshot})); + for (const address of [legacy, withTurn]) { + await report.goto(address.toString()); + await report.getByRole("link", {name: "Download file: source.bin", exact: false}).waitFor(); + assert.equal(await report.locator("a[download]").count(), ready.files.length); + } + const wrongTurn = new URL(withTurn); + wrongTurn.searchParams.set("reportTurnId", "unrelated-turn"); + await report.goto(wrongTurn.toString()); + await report.getByText("This answer was not found. It may have been removed, or the link may be incorrect.").waitFor(); + assert.equal(await report.locator("a[download]").count(), 0); + await report.unroute(savedAnswerRequest); + + for (const invalid of [ + {...snapshot, session: {...snapshot.session, session_id: "another-session"}}, + {...snapshot, report_message_id: "another-message"}, + {...snapshot, message_page: {next_cursor: "another-page"}}, + ]) { + await report.route(savedAnswerRequest, route => route.fulfill({json: invalid})); + await report.goto(legacy.toString()); + await report.getByText("Could not load this answer.").waitFor(); + assert.equal(await report.locator("a[download]").count(), 0); + await report.unroute(savedAnswerRequest); + } + + const refusedReads = []; + const observeRefusal = request => { + if (new URL(request.url()).pathname === historyPath) refusedReads.push(new URL(request.url())); + }; + report.on("request", observeRefusal); + for (const [status, error] of [[403, "Source access was revoked"], [400, "invalid Chat journal record"]]) { + refusedReads.length = 0; + await report.route(savedAnswerRequest, route => route.fulfill({status, json: {ok: false, error}})); + await report.reload(); + await report.getByText("Could not load this answer.").waitFor(); + assert.equal(await report.locator("a[download]").count(), 0); + assert.equal(refusedReads.length, 1); + assert.ok(savedAnswerRequest(refusedReads[0]), "A refused or invalid source must never trigger a wider history read"); + await report.unroute(savedAnswerRequest); + } + report.off("request", observeRefusal); + + legacy.searchParams.set("reportTurnId", "unrelated-turn"); + await report.goto(legacy.toString()); + await report.getByText(/This answer was not found|Could not load this answer/).waitFor(); + assert.equal(await report.locator("a[download]").count(), 0); } child.stdin.write("inspect\n"); const inspection = await next(); @@ -118,6 +216,135 @@ async function checkReturnedFiles(ready, page, errors, writes) { console.log(baseline ? "returned-files-browser: baseline reproduced (published files omitted from history and full reader; zero model Turns or repeat sends)" : "returned-files-browser: passed (real publisher, bound source, original history/reader, byte-exact downloads, desktop/narrow, keyboard, English, zero model Turns or repeat sends)"); } + +async function checkHistoryImages(ready, page, errors, writes) { + const {old, current} = ready.historyImages; + const requests = []; + const responses = []; + page.on("request", request => { + const url = new URL(request.url()); + if (url.origin === ready.origin && url.pathname.includes("/images/")) requests.push(url.pathname); + }); + page.on("response", response => { + const url = new URL(response.url()); + if (url.origin === ready.origin && url.pathname.includes(`/messages/${old}/images/`)) + responses.push({path: url.pathname, status: response.status()}); + }); + const requested = id => requests.filter(path => path.includes(`/messages/${id}/images/`)).length; + const timeline = page.locator(".personal-channel-timeline"); + const image = name => timeline.locator(`img[alt="${name}.png"]`); + await page.goto(ready.origin + "/chat/"); + await page.getByRole("navigation", {name: "管家视图"}).getByRole("button", {name: /^(Chat|对话)$/}).click(); + await timeline.getByText("Latest original result after archived images.", {exact: true}).waitFor(); + await page.waitForFunction(() => document.querySelector('img[alt="latest-image.png"]')?.naturalWidth === 3); + assert.equal(await image("archived-image").evaluate(node => node.naturalWidth), 0); + assert.equal(requested(old), 0, "Opening the latest conversation must not request the offscreen image"); + assert.equal(requested(current), 1); + await image("archived-image").scrollIntoViewIfNeeded(); + const oldMessage = timeline.locator(`article[data-message-id="${old}"]`); + const retry = oldMessage.getByRole("button", {name: "重试图片"}); + await retry.waitFor(); + assert.equal(requested(old), 1, "Scrolling requests only the selected original image"); + assert.deepEqual(responses.map(response => response.status), [503]); + await retry.click(); + await page.waitForFunction(() => document.querySelector('img[alt="archived-image.png"]')?.naturalWidth === 4); + assert.equal(requested(old), 2, "An inline retry reads the same original image without leaving the conversation"); + assert.deepEqual(responses.map(response => response.status), [503, 200]); + assert.equal(responses[0].path, responses[1].path, "Retry must preserve the original message and content digest"); + + requests.length = 0; + const focus = new URL(ready.origin + "/chat/"); + focus.search = new URLSearchParams({view: "conversation", conversationBinding: ready.bindingId, + conversationSession: ready.sessionId, messageSession: ready.sessionId, message: old}); + await page.goto(focus.href); + await page.waitForFunction(id => document.activeElement?.getAttribute("data-message-id") === id + && document.querySelector('img[alt="archived-image.png"]')?.naturalWidth === 4, old); + assert.equal(requested(old), 1, "Opening an original message link positions and loads that image"); + assert.equal(requested(current), 0, "An unrelated offscreen image stays deferred when reading a link"); + const oldUrl = await image("archived-image").getAttribute("src"); + child.stdin.write("history-image-refresh\n"); + assert.equal((await next()).history_image_refreshed, old); + assert.equal((await page.request.get(ready.origin + oldUrl)).status(), 404); + await page.getByRole("button", {name: "刷新状态", exact: true}).click(); + await page.waitForFunction(previous => { + const image = document.querySelector('img[alt="archived-image.png"]'); + return Boolean(image?.getAttribute("src") && image.getAttribute("src") !== previous && image.naturalWidth === 3); + }, oldUrl); + assert.equal(await oldMessage.count(), 1, "The refreshed image remains in the original message"); + assert.deepEqual(errors, []); + assert.ok(!writes.some(path => /\/turns(?:\/|$)/u.test(path)), "Reading history cannot submit a Turn"); + child.stdin.write("inspect\n"); + const inspection = await next(); + assert.equal(inspection.model_turns, 0); + assert.equal(inspection.reply_evidence_unchanged, true); + console.log("history-images-browser: passed (latest, scroll, inline retry and original message link; zero model Turns)"); +} + +async function checkQueuedReply(ready, page, errors, writes) { + const endpoint = `${ready.origin}/api/chat/sessions/${ready.sessionId}`; + const snapshot = await (await page.request.get(endpoint)).json(); + const original = snapshot.messages.find(row => row.origin === "lark" && row.reply_context); + assert.ok(original.text.startsWith("Referenced message (")); + const body = original.reply_context.source_text; + const queued = await (await page.request.get(`${endpoint}/queue`)).json(); + assert.equal(queued.turns.length, 2); + assert.equal(queued.turns[0].preview, body.slice(0, 240)); + assert.equal(queued.turns[0].character_count, [...body].length); + assert.equal(queued.turns[1].preview, [...original.text].slice(0, 240).join(""), + "An identical unbound literal must not become a source-backed quote"); + await openWhileCheckingOriginalConversation(ready, page); + await page.getByRole("navigation", {name: "管家视图"}).getByRole("button", {name: /^(Chat|对话)$/}).click(); + const queue = page.locator(".personal-conversation-queue"); + const message = queue.locator(":scope > ol > li").first(); + const summary = message.getByLabel("待处理消息 1", {exact: true}); + await summary.waitFor(); + assert.equal(await summary.getByText(body, {exact: true}).count(), 1); + assert.equal(queued.turns[0].attachment_count, 1); + await page.screenshot({path: resolve(output, "queue-default-desktop.png"), animations: "disabled"}); + child.stdin.write("history-unavailable\n"); + assert.equal((await next()).history_available, false); + await summary.focus(); await page.keyboard.press("Enter"); + await message.getByRole("alert").waitFor(); + child.stdin.write("history-available\n"); + assert.equal((await next()).history_available, true); + await message.getByRole("button", {name: "重试", exact: true}).click(); + const context = message.locator(".conversation-reply-context"); + await context.waitFor(); + await page.waitForFunction(() => document.querySelector('.personal-conversation-queue img[alt="queued-image.png"]')?.naturalWidth === 3); + assert.equal(await context.getAttribute("open"), null); + await context.locator("summary").focus(); await page.keyboard.press("Enter"); + await context.getByText("原要求:保留已有结果和失败记录。Original requirement: retain results and failed attempts.", {exact: true}).waitFor(); + assert.equal(await context.locator("section").count(), 1); + assert.equal(await context.locator("blockquote ol").first().evaluate(node => getComputedStyle(node).listStyleType), "decimal"); + assert.deepEqual(await context.locator("blockquote ol").evaluateAll(lists => lists.map(list => list.start)), [1, 2, 3, 7, 0]); + assert.equal(await message.locator(".personal-queue-message").getByText(body, {exact: true}).count(), 1); + await page.screenshot({path: resolve(output, "queue-expanded-desktop.png"), animations: "disabled"}); + await page.setViewportSize({width: 390, height: 844}); + await context.locator("summary").scrollIntoViewIfNeeded(); + assert.ok(await page.locator("body").evaluate(node => node.scrollWidth <= innerWidth + 1)); + await page.screenshot({path: resolve(output, "queue-expanded-narrow.png"), animations: "disabled"}); + const literal = queue.locator(":scope > ol > li").nth(1); + await literal.getByLabel("待处理消息 2", {exact: true}).click(); + await literal.locator(".personal-queue-message").getByText("Referenced message (", {exact: false}).waitFor(); + assert.equal(await literal.locator(".conversation-reply-context").count(), 0); + await page.evaluate(() => localStorage.setItem("loopx-pw-locale", "en")); + await page.reload(); + await queue.getByLabel("Queued message 1", {exact: true}).click(); + await queue.getByText("Reply and thread context", {exact: true}).waitFor(); + assert.deepEqual(errors, []); + assert.ok(!writes.some(path => /\/turns(?:\/|$)|\/queue\/[^/]+\/(?:input|steer)/u.test(path))); + child.stdin.write("inspect\n"); + const inspection = await next(); + assert.equal(inspection.model_turns, 0); + assert.equal(inspection.reply_evidence_unchanged, true); + child.stdin.write("revoke\n"); + assert.equal((await next()).revoked, ready.bindingId); + const denied = await page.request.get(`${endpoint}/queue`); + assert.ok(!denied.ok(), "Queue projection must not bypass revoked source access"); + assert.equal((await denied.json()).turns, undefined); + console.log("queued-reply-browser: passed (real HTTP/source journals, readable preview, full quote/thread, literal parity, read failure/retry, keyboard, narrow/English, no model Turns or queue mutations)"); +} + try { const ready = await next(); browser = await launchBrowser(loadPlaywright().chromium); @@ -126,8 +353,12 @@ try { const errors = [], writes = []; page.on("pageerror", error => errors.push(error.message)); page.on("request", request => {if (request.method() !== "GET") writes.push(new URL(request.url()).pathname);}); - if (returnedFiles) { + if (historyImages) { + await checkHistoryImages(ready, page, errors, writes); + } else if (returnedFiles) { await checkReturnedFiles(ready, page, errors, writes); + } else if (queuedReply) { + await checkQueuedReply(ready, page, errors, writes); } else { const snapshot = await (await page.request.get(`${ready.origin}/api/chat/sessions/${ready.sessionId}`)).json(); const source = snapshot.messages.find(row => row.role === "user" && row.turn_id); diff --git a/apps/presentation/dashboard/smoke/goal-acceptance-contract-browser-smoke.mjs b/apps/presentation/dashboard/smoke/goal-acceptance-contract-browser-smoke.mjs index d629b63f58..82d120a378 100644 --- a/apps/presentation/dashboard/smoke/goal-acceptance-contract-browser-smoke.mjs +++ b/apps/presentation/dashboard/smoke/goal-acceptance-contract-browser-smoke.mjs @@ -38,7 +38,7 @@ with tempfile.TemporaryDirectory() as directory: if (payload) payload.run_history.goals[0].acceptance_observation = acceptance; const server = packaged ? spawn(python, ["-m", "http.server", String(port), "--bind", "127.0.0.1", "--directory", resolve(root, "loopx/web")], { stdio: "ignore" }) - : startViteDashboardServer({ dashboardDir, port }); + : await startViteDashboardServer({ dashboardDir, port }); async function checkLiveWriteAuthority(browser, origin) { const page = await browser.newPage({viewport: {width: 1024, height: 768}}); const writes = [], errors = []; diff --git a/apps/presentation/dashboard/smoke/goal-created-session-browser-smoke.mjs b/apps/presentation/dashboard/smoke/goal-created-session-browser-smoke.mjs new file mode 100644 index 0000000000..c179e76574 --- /dev/null +++ b/apps/presentation/dashboard/smoke/goal-created-session-browser-smoke.mjs @@ -0,0 +1,185 @@ +// Source frontend with synthetic HTTP reads; no model or active Goal state. +import assert from "node:assert/strict"; +import {mkdir} from "node:fs/promises"; +import {resolve} from "node:path"; +import {cleanupBrowserSmoke, launchBrowser, loadPlaywright, startViteDashboardServer} from "../../../../examples/dashboard-browser-smoke-support.mjs"; +import {dashboardDir, repoRoot, installApi} from "../../../../examples/personal-workspace-browser/fixture.mjs"; + +const port = Number(process.env.LOOPX_GOAL_CREATED_SESSION_PORT ?? "5349"); +const origin = `http://127.0.0.1:${port}`; +const evidence = process.env.LOOPX_GOAL_CREATED_SESSION_EVIDENCE ?? resolve(repoRoot, ".local/validation/goal-created-session"); +const server = await startViteDashboardServer({dashboardDir, port}); +let browser; +try { + browser = await launchBrowser(loadPlaywright().chromium); + await mkdir(evidence, {recursive: true}); + for (const scenario of ["managed", "creation", "legacy", "malformed"]) { + const page = await browser.newPage({viewport: {width: 1440, height: 960}}); + page.setDefaultTimeout(10000); + await page.emulateMedia({reducedMotion: "reduce"}); + await page.addInitScript(() => localStorage.setItem("loopx-pw-locale", "zh-CN")); + const proposalId = `create-${scenario}`, goalId = "progress-projection", owner = "codex", sessionId = "created-original-session"; + const proposal = {schema_version: "loopx_chat_action_proposal_v1", proposal_id: proposalId, action_kind: "goal.create", + summary: "Prepare the original Session journey", normalized_parameters: {goal_id: goalId, title: "Original Session journey / 原会话", + objective: "Retain the original work conversation", completion_criteria: scenario === "creation" ? "Reopen its original history" : ["Reopen its original history"], execution_boundary: "Synthetic readback only", agent_id: "codex", + ...(scenario === "creation" ? {start_execution: true, permission: "workspace_write_on_confirmation", initial_todos: ["Reopen its original history"]} : {})}, + context: {kind: "manager"}, expected_state_fingerprint: "original-fingerprint", permission_classification: "durable_write", + validation_evidence: ["Synthetic proposal is ready for the routing check"], available_transitions: ["apply", "cancel"], + status: "preview_ready", receipt: null, stale: null, created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z"}; + const api = await installApi(page, {fixturePort: port, initialActionProposals: [proposal]}); + api.registeredAgentsByGoal = {[goalId]: [owner]}; + const runtime = page.__loopxRuntime; + const session = {session_id: sessionId, goal_id: goalId, goal_instance_id: null, managed_agent_id: owner, + agent_id: "codex", adapter_kind: "codex_app_server", channel_id: `agent.${owner}`, session_mode: "managed_runtime", + status: "ready", active_turn_id: null, last_error_code: null, resumable: true, + created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z", last_activity_at: "2026-01-01T00:00:00Z"}; + runtime.sessions.set(sessionId, session); + const longText = "## Original first-run result / 原首轮结果\n\n" + Array.from({length: 24}, (_, i) => + `### Evidence ${i + 1} / 证据 ${i + 1}\n\nOriginal scope retained; independent acceptance remains unverified. 原始范围保留;独立验收尚未确认。`).join("\n\n"); + runtime.messages.set(sessionId, Array.from({length: 19}, (_, i) => ({message_id: `original-message-${i}`, role: i % 3 === 0 ? "user" : "agent", + turn_id: null, text: i === 18 ? longText : `Original conversation record ${i + 1} / 原会话记录 ${i + 1}:${i % 2 ? "failed check retained" : "unverified work retained"}`, + created_at: `2026-01-01T00:00:${String(i).padStart(2, "0")}Z`})).map((row, i) => i === 18 ? {...row, role: "agent"} : row)); + const writes = [], discovery = []; + let mode = scenario === "creation" ? "pending-creation" : "ready"; + const creationRequest = {creation_operation_id: proposalId, operation_id: `goal-create-${proposalId}`, goal_id: goalId, + goal_instance_id: null, agent_id: owner, session_id: sessionId, todo_id: "original-task", permission: "workspace_write_on_confirmation", write_scope: ["**"]}; + const creationTurn = {session_id: sessionId, turn_id: "original-creation-native-turn", client_turn_id: `managed.${creationRequest.operation_id}`, + status: "failed", origin: "native_loopx", loopx_execution: true, + loopx_request: {operation: "native_turn", todo_id: creationRequest.todo_id, actor: {goal_id: goalId, agent_id: owner, session_id: sessionId}}}; + page.on("request", request => { + if (request.method() !== "GET") writes.push({path: new URL(request.url()).pathname, body: request.postDataJSON()}); + }); + const errors = []; + page.on("pageerror", error => errors.push(error.message)); + await page.route("**/api/actions/**", async route => { + const path = new URL(route.request().url()).pathname; + if (path !== `/api/actions/${proposalId}/apply`) return route.fallback(); + const ids = {goal_id: goalId, goal_instance_id: null, agent_id: "codex", session_id: sessionId, + ...(scenario === "legacy" ? {} : {managed_agent_id: owner, channel_id: scenario === "malformed" ? `goal.${goalId}` : `agent.${owner}`})}; + const applied = {...proposal, status: "applied", available_transitions: [], receipt: {outcome: "goal_created", projection_verified: true, resource_ids: ids}, updated_at: "2026-01-01T00:00:01Z"}; + runtime.actionProposals.set(proposalId, applied); + return route.fulfill({json: {ok: true, proposal: applied}}); + }); + await page.route("**/api/chat/sessions**", async route => { + const request = route.request(), url = new URL(request.url()); + if (scenario === "creation" && url.pathname === `/api/chat/sessions/${sessionId}/native-turn`) { + assert.equal(request.method(), "GET", "Populated original creation observation never launches"); + return route.fulfill({json: {ok: true, session_id: sessionId, managed_agent_id: owner, registered_agents: [owner], available: true, + task: {todo_id: creationRequest.todo_id, state: "ready", source: "goal-creation", canonical_done: false, + observation: {check_count: 6, pinned_file_count: 1, basis_sha256: "original-confirmed-checks"}, + creation_request: creationRequest, creation_turn: mode === "pending-creation" ? null : creationTurn}, turn: null}}); + } + if (url.pathname === "/api/chat/sessions" && request.method() === "GET" && url.searchParams.has("managed_agent_id")) { + discovery.push([url.searchParams.get("goal_id"), url.searchParams.get("managed_agent_id")]); + const actual = runtime.sessions.get(sessionId); + const current = mode === "identity-failure" ? {...actual, channel_id: `goal.${goalId}`} : actual; + return route.fulfill({json: {ok: true, schema_version: "loopx_chat_session_list_v1", goal_id: goalId, + managed_agent_id: owner, goal_instance_id: null, sessions: [current]}}); + } + return route.fallback(); + }); + try { + await page.goto(`${origin}/?statusUrl=/status.json&view=conversation`, {waitUntil: "domcontentloaded"}); + const row = page.locator('.personal-proposal-row[data-action-kind="goal.create"]'); + await row.waitFor(); + await row.click(); + const drawer = page.locator('.personal-context-drawer[data-context-kind="proposal"]'); + await drawer.getByRole("button", {name: scenario === "creation" ? "创建 Goal 并开始首轮" : "创建 Goal", exact: true}).click(); + const enter = drawer.getByRole("button", {name: "进入新 Goal", exact: true}); + if (scenario === "malformed") { + await drawer.getByRole("alert").filter({hasText: "无法验证新 Goal 的原 Session 地址"}).waitFor(); + assert.equal(await enter.count(), 0, "An invalid managed receipt must not expose the legacy Goal fallback"); + await page.screenshot({path: resolve(evidence, "managed-receipt-invalid-desktop.png"), animations: "disabled"}); + await page.reload({waitUntil: "domcontentloaded"}); + await row.waitFor(); await row.click(); + await drawer.getByRole("alert").filter({hasText: "无法验证新 Goal 的原 Session 地址"}).waitFor(); + assert.equal(await enter.count(), 0); + console.log("goal-created-session browser: PASS malformed receipt and reload"); + continue; + } + await enter.waitFor(); + await page.screenshot({path: resolve(evidence, `${scenario}-creation-receipt-desktop.png`), animations: "disabled"}); + await enter.click(); + await page.waitForURL(url => url.searchParams.get("goalId") === goalId); + const routed = new URL(page.url()); + assert.equal(routed.searchParams.get("statusUrl"), "/status.json", "Goal navigation retains the selected source"); + if (scenario === "legacy") { + assert.equal(routed.searchParams.get("workAgent"), null); + assert.equal(routed.searchParams.get("workSession"), null); + assert.equal(routed.searchParams.get("view"), "overview"); + console.log("goal-created-session browser: PASS legacy navigation parity"); + continue; + } + assert.equal(routed.searchParams.get("workAgent"), owner); + assert.equal(routed.searchParams.get("workSession"), `managed:${sessionId}`); + assert.equal(routed.searchParams.get("view"), "conversation"); + const original = page.getByRole("heading", {name: "Original first-run result / 原首轮结果", exact: true}); + await original.waitFor(); + if (scenario === "creation") { + const control = page.getByRole("region", {name: "当前任务", exact: true}); + const pending = control.getByRole("button", {name: "等待", exact: true}); + await pending.waitFor(); + assert.equal(await pending.isDisabled(), true); + await control.getByRole("status").filter({hasText: "已提交,等待执行"}).waitFor(); + assert.equal(writes.filter(row => row.path.endsWith("/native-turn")).length, 0); + mode = "ready"; + await page.reload({waitUntil: "domcontentloaded"}); + await control.getByRole("button", {name: "继续当前任务", exact: true}).waitFor(); + for (const [label, viewport] of [["desktop", {width: 1440, height: 960}], ["narrow", {width: 390, height: 844}]]) { + await page.setViewportSize(viewport); + await page.screenshot({path: resolve(evidence, `creation-populated-${label}.png`), animations: "disabled"}); + await control.getByRole("button", {name: "当前任务与检查", exact: true}).click(); + await page.getByRole("tooltip").filter({hasText: "当前任务与检查"}).waitFor(); + await page.screenshot({path: resolve(evidence, `creation-populated-help-${label}.png`), animations: "disabled"}); + await page.keyboard.press("Escape"); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth + 1), false); + } + assert.equal(writes.filter(row => row.path.endsWith("/native-turn")).length, 0); + await page.setViewportSize({width: 1440, height: 960}); + } + assert.ok(discovery.some(([goal, agent]) => goal === goalId && agent === owner)); + await page.screenshot({path: resolve(evidence, "managed-original-first-desktop.png"), animations: "disabled"}); + await original.evaluate(element => element.scrollIntoView({block: "start"})); + await page.screenshot({path: resolve(evidence, "managed-original-long-desktop.png"), animations: "disabled"}); + await page.reload({waitUntil: "domcontentloaded"}); await original.waitFor(); + assert.equal(new URL(page.url()).searchParams.get("workSession"), `managed:${sessionId}`); + const send = page.getByRole("button", {name: "发送", exact: true}), composer = page.getByLabel("向 LoopX 发送消息"); + await composer.fill("Keep this ordinary follow-up in the original Session."); + mode = "identity-failure"; + await page.reload({waitUntil: "domcontentloaded"}); + const error = page.getByRole("alert").filter({hasText: "cannot verify the registered Agent"}); + await error.waitFor(); + assert.equal(await send.isDisabled(), true); + assert.equal(await original.count(), 0, "Invalid discovery cannot show borrowed history"); + await page.screenshot({path: resolve(evidence, "managed-discovery-unavailable-desktop.png"), animations: "disabled"}); + await page.setViewportSize({width: 390, height: 844}); + await page.screenshot({path: resolve(evidence, "managed-discovery-unavailable-narrow.png"), animations: "disabled"}); + await page.setViewportSize({width: 1440, height: 960}); + mode = "ready"; + await error.getByRole("button", {name: "重新连接", exact: true}).click(); + await original.waitFor(); + await composer.fill("Keep this ordinary follow-up in the original Session."); + await send.click(); + await page.getByText("已沿用当前 Goal 与 Agent Session。接下来会先核对状态,再继续推进。", {exact: true}).waitFor(); + const turnWrites = writes.filter(row => /\/turns$/.test(row.path)); + assert.equal(turnWrites.length, 1); + assert.equal(turnWrites[0].path, `/api/chat/sessions/${sessionId}/turns`); + assert.equal(Object.hasOwn(turnWrites[0].body, "execution_control"), false, "An ordinary follow-up does not gain execution authority from the receipt"); + assert.equal(writes.some(row => row.path === "/api/chat/sessions" && row.body?.goal_id === goalId), false, + "Entering, reloading and retrying cannot create a replacement Goal Session"); + await page.setViewportSize({width: 390, height: 844}); + await original.evaluate(element => element.scrollIntoView({block: "start"})); + await page.screenshot({path: resolve(evidence, "managed-original-long-narrow.png"), animations: "disabled"}); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth + 1), false); + // Reopening the manager's receipt after reload is a read, never another apply. + await page.goto(`${origin}/?statusUrl=/status.json&view=conversation`, {waitUntil: "domcontentloaded"}); + await row.waitFor(); await row.click(); await enter.waitFor(); await enter.click(); await original.waitFor(); + assert.equal(writes.filter(row => row.path === `/api/actions/${proposalId}/apply`).length, 1); + assert.deepEqual(errors, []); + } catch (error) { + await page.screenshot({path: resolve(evidence, `${scenario}-failure.png`), animations: "disabled"}); + throw new Error(`${error.message}; pageerrors=${JSON.stringify(errors)}; url=${page.url()}; body=${(await page.locator("body").innerText()).slice(-10000)}`); + } finally {await page.unrouteAll({behavior: "ignoreErrors"}); await page.close();} + console.log(`goal-created-session browser: PASS ${scenario}`); + } +} finally {await cleanupBrowserSmoke({browser, server, dashboardDir, fixturePaths: []});} diff --git a/apps/presentation/dashboard/smoke/goal-created-session-smoke.ts b/apps/presentation/dashboard/smoke/goal-created-session-smoke.ts new file mode 100644 index 0000000000..ede6569481 --- /dev/null +++ b/apps/presentation/dashboard/smoke/goal-created-session-smoke.ts @@ -0,0 +1,79 @@ +import assert from "node:assert/strict"; +import {goalCreatedManagedSession} from "../src/features/personal-workspace/goal-created-session"; +import {conversationChannelId, conversationContextKey, createChatSession, fetchChatHistory, type TypedActionProposal} from "../src/data/chat"; + +const resources = {goal_id: "research", goal_instance_id: null, agent_id: "codex", + managed_agent_id: "codex", channel_id: "agent.codex", session_id: "original-session"}; +const proposal: TypedActionProposal = {schema_version: "loopx_chat_action_proposal_v1", proposal_id: "create-original", + action_kind: "goal.create", status: "applied", summary: "Create the original work Session", + normalized_parameters: {goal_id: "research", agent_id: "codex"}, context: {kind: "manager"}, + expected_state_fingerprint: "original-source", permission_classification: "durable_write", + validation_evidence: ["Original Session identity was read back"], available_transitions: [], stale: null, + created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:01Z", + receipt: {outcome: "goal_created", projection_verified: true, resource_ids: resources}}; +const address = goalCreatedManagedSession(proposal)!; +assert.deepEqual(address, {target: {goalId: "research", agentId: "codex", sessionId: "original-session"}}, + "The recorded registered owner and explicit null lifetime retain the original Session"); +assert.deepEqual(goalCreatedManagedSession({...proposal, receipt: {...proposal.receipt, resource_ids: {...resources, goal_instance_id: "explicit-instance"}}}), address); +assert.equal(goalCreatedManagedSession({...proposal, receipt: {resource_ids: {goal_id: "research", agent_id: "codex", session_id: "legacy"}}}), undefined, + "Legacy receipts keep their original navigation without inventing managed identity"); +for (const changed of [{goal_id: "another-goal"}, {managed_agent_id: null}, {managed_agent_id: ""}, {managed_agent_id: "another-worker"}, {session_id: ""}, + {channel_id: "goal.research"}, {goal_instance_id: undefined}, {goal_instance_id: ""}, {agent_id: "other-executor"}]) { + assert.deepEqual(goalCreatedManagedSession({...proposal, receipt: {...proposal.receipt, resource_ids: {...resources, ...changed}}}), {invalid: true}, + "A marked but unreadable address is an error, never a legacy fallback"); +} +const missingLifetime = {...resources} as Record; delete missingLifetime.goal_instance_id; +assert.deepEqual(goalCreatedManagedSession({...proposal, receipt: {...proposal.receipt, resource_ids: missingLifetime}}), {invalid: true}); +for (const changed of [{outcome: "other"}, {outcome: undefined}, {projection_verified: false}, {projection_verified: undefined}]) { + assert.deepEqual(goalCreatedManagedSession({...proposal, receipt: {...proposal.receipt, ...changed}}), {invalid: true}); +} +for (const changed of [{status: "preview_ready"}, {action_kind: "team.plan"}]) { + assert.equal(goalCreatedManagedSession({...proposal, ...changed} as TypedActionProposal), undefined); +} + +const target = address.target!, context = {kind: "managed" as const, ...target}; +assert.equal(conversationChannelId(context), "agent.codex"); +assert.equal(conversationContextKey(context), "managed/research/codex/original-session"); +const originalFetch = globalThis.fetch, requests: string[] = []; +const session = {session_id: target.sessionId, goal_id: target.goalId, goal_instance_id: resources.goal_instance_id, + managed_agent_id: target.agentId, channel_id: resources.channel_id, agent_id: "codex", adapter_kind: "codex_app_server", + session_mode: "managed_runtime", status: "ready", active_turn_id: null, resumable: true, last_error_code: null, + created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z", last_activity_at: "2026-01-01T00:00:00Z"}; +let discoveryMode = "original", snapshotMode = "original"; +try { + globalThis.fetch = async (input, init) => { + assert.equal(init?.method ?? "GET", "GET", "Reopening and retrying never create a Session or Turn"); + const url = new URL(String(input), "http://127.0.0.1"); + requests.push(url.pathname + url.search); + if (url.pathname === "/api/chat/sessions") { + assert.equal(url.searchParams.get("goal_id"), "research"); + assert.equal(url.searchParams.get("managed_agent_id"), "codex"); + const listedSession = discoveryMode === "changed" ? {...session, channel_id: "goal.research"} : session; + return Response.json({ok: true, schema_version: "loopx_chat_session_list_v1", goal_id: "research", + managed_agent_id: "codex", goal_instance_id: resources.goal_instance_id, + sessions: discoveryMode === "missing" ? [] : [listedSession]}); + } + assert.equal(url.pathname, "/api/chat/sessions/original-session"); + return Response.json({ok: true, schema_version: "loopx_chat_store_v1", + session: snapshotMode === "changed" ? {...session, goal_instance_id: "replacement-instance"} : session, + active_turn: null, messages: [{message_id: "original-answer", role: "agent", turn_id: null, + text: "Original result 原始结果", created_at: session.created_at}]}); + }; + assert.equal((await createChatSession(context, "codex")).session_id, "original-session"); + await assert.rejects(() => createChatSession(context, "codex", "new")); + const history = await fetchChatHistory({channelId: conversationContextKey(context), managed: target}); + assert.deepEqual(history.messages.map(row => [row.session_id, row.text]), [["original-session", "Original result 原始结果"]]); + assert.equal((await fetchChatHistory({channelId: conversationContextKey(context), managed: target}, history)).sessions[0].session_id, "original-session"); + discoveryMode = "missing"; + await assert.rejects(() => createChatSession(context, "codex"), /no longer available/); + discoveryMode = "changed"; + await assert.rejects(() => fetchChatHistory({channelId: conversationContextKey(context), managed: target}), /cannot verify/); + discoveryMode = "original"; snapshotMode = "changed"; + const unavailable = await fetchChatHistory({channelId: conversationContextKey(context), managed: target}); + assert.deepEqual(unavailable.messages, [], "Changed lifetime cannot expose another Goal's transcript"); + assert.deepEqual(unavailable.unavailableSessionIds, ["original-session"]); + snapshotMode = "original"; + assert.equal((await fetchChatHistory({channelId: conversationContextKey(context), managed: target}, unavailable)).messages[0].text, "Original result 原始结果"); + assert.ok(requests.every(path => path.startsWith("/api/chat/sessions"))); +} finally {globalThis.fetch = originalFetch;} +console.log("goal-created-session: original owner/history, replay, legacy parity and identity failure/recovery passed"); diff --git a/apps/presentation/dashboard/smoke/managed-task-entry-browser-smoke.mjs b/apps/presentation/dashboard/smoke/managed-task-entry-browser-smoke.mjs new file mode 100644 index 0000000000..93e98f9dd5 --- /dev/null +++ b/apps/presentation/dashboard/smoke/managed-task-entry-browser-smoke.mjs @@ -0,0 +1,230 @@ +#!/usr/bin/env node +// The original Task's primary control reads its typed owner; only explicit launch +// submits the original Todo, and recovery observes the same native operation. +// Synthetic HTTP replies isolate the browser contract; owning-backend qualification +// remains a separate packaged journey. +import assert from "node:assert/strict"; +import {dirname, resolve} from "node:path"; +import {fileURLToPath} from "node:url"; +import {cleanupBrowserSmoke, launchBrowser, loadPlaywright, startViteDashboardServer, waitForHttp} from "../../../../examples/dashboard-browser-smoke-support.mjs"; + +const dashboardDir = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const port = Number(process.env.LOOPX_MANAGED_TASK_TEST_PORT ?? 5371); +const origin = `http://127.0.0.1:${port}`; +const server = await startViteDashboardServer({dashboardDir, port}); +const storageKey = `loopx-managed-task:${JSON.stringify(["cart-repair", "codex", "original-session"])}`; +const session = {session_id: "original-session", goal_id: "cart-repair", goal_instance_id: null, + managed_agent_id: "codex", channel_id: "agent.codex", session_mode: "managed_runtime"}; +const ready = {todo_id: "original-cart-task", state: "ready", source: "goal-creation", + canonical_done: false, observation: {check_count: 6, pinned_file_count: 1, basis_sha256: "confirmed-check-source"}}; +const unbound = {todo_id: "original-cart-task", state: "unbound", source: null, canonical_done: false}; +const native = (operationId, status = "queued") => ({session_id: session.session_id, turn_id: "original-native-turn", + client_turn_id: `managed.${operationId}`, status, origin: "native_loopx", loopx_execution: true, + loopx_request: {operation: "native_turn", todo_id: ready.todo_id, + actor: {goal_id: session.goal_id, agent_id: "codex", session_id: session.session_id}}}); +const creation = {creation_operation_id: "owner-reviewed-creation", operation_id: "goal-create-owner-reviewed-creation", + goal_id: session.goal_id, goal_instance_id: session.goal_instance_id, agent_id: session.managed_agent_id, + session_id: session.session_id, todo_id: ready.todo_id, permission: "workspace_write_on_confirmation", write_scope: ["**"]}; +let browser; +async function probe(initial = {}) { + const page = await browser.newPage(); + await page.clock.install(); + await page.addInitScript(({key, attempt}) => { + localStorage.setItem("loopx-pw-locale", "en"); + if (attempt !== undefined && sessionStorage.getItem(key) === null) sessionStorage.setItem(key, attempt); + }, {key: storageKey, attempt: initial.attempt}); + const state = {task: ready, turn: null, available: true, loseAck: false, sessions: [session], ...initial}; + const reads = [], writes = [], errors = []; + page.on("pageerror", error => errors.push(error.message)); + await page.route("**/api/**", async route => { + const request = route.request(), url = new URL(request.url()); + if (url.pathname === "/api/chat/sessions") return route.fulfill({json: {ok: true, + schema_version: "loopx_chat_session_list_v1", goal_id: session.goal_id, managed_agent_id: "codex", + goal_instance_id: null, sessions: state.sessions}}); + assert.equal(url.pathname, "/api/chat/sessions/original-session/native-turn", "No coordinator/settings/Task/session creation endpoint"); + if (request.method() === "GET") { + reads.push(Object.fromEntries(url.searchParams)); + assert.equal(url.searchParams.get("original_task"), "true"); + assert.equal(url.searchParams.get("agent_id"), "codex"); + assert.equal(url.searchParams.has("todo_id"), false, "Task selection belongs to Core"); + return route.fulfill({json: {ok: true, session_id: session.session_id, managed_agent_id: "codex", + registered_agents: ["codex"], available: state.available, task: state.task, turn: state.turn}}); + } + const body = request.postDataJSON(); writes.push(body); + assert.deepEqual(Object.keys(body).sort(), ["agent_id", "operation_id", "todo_id"]); + assert.equal(body.agent_id, "codex"); assert.equal(body.todo_id, ready.todo_id); + state.turn = native(body.operation_id); + if (state.loseAck) return route.abort("failed"); + return route.fulfill({status: 202, json: {ok: true, session_id: session.session_id, turn: state.turn, created: true}}); + }); + const firstRead = initial.attempt === "{malformed" ? null : page.waitForResponse(row => row.url().includes("native-turn")); + await page.goto(origin + "/smoke/managed-task-entry-smoke.html"); + if (firstRead) await firstRead; + await page.waitForFunction(() => document.querySelector('output[aria-label="History observations"]')); + const section = page.getByRole("region", {name: "Current Task", exact: true}); + const button = section.locator("button.goal-loopx-primary"); + const poll = async () => { + const response = page.waitForResponse(row => new URL(row.url()).pathname.endsWith("/native-turn") && row.request().method() === "GET"); + await page.clock.fastForward(5100); await response; + await page.clock.runFor(30); + }; + return {page, state, reads, writes, errors, section, button, poll, + async finish() {assert.deepEqual(errors, []); await page.close();}}; +} +try { + await waitForHttp(origin + "/smoke/managed-task-entry-smoke.html"); + browser = await launchBrowser(loadPlaywright().chromium); + { + const p = await probe({task: unbound, available: false}); + assert.equal(await p.section.count(), 0, "Unconfirmed checks expose no launch control"); + await p.page.clock.fastForward(16000); await p.page.clock.runFor(30); + assert.equal(p.reads.length, 1, "An unconfigured default Goal has one initial native read and no empty background queries"); + assert.deepEqual(p.writes, []); await p.finish(); + } + { + const p = await probe(); await p.button.waitFor(); + assert.equal(await p.button.isDisabled(), false, "A ready definition permits repair despite a failed baseline"); + await p.page.clock.fastForward(16000); await p.page.clock.runFor(30); + assert.equal(p.reads.length, 1, "A ready idle Task also waits for an explicit operation"); + p.state.task = unbound; p.state.available = false; + await p.button.click(); + await p.page.waitForFunction(() => document.querySelector("button.goal-loopx-primary")?.disabled); + assert.deepEqual(p.writes, [], "A stale ready viewport cannot launch against changed current checks"); + await p.finish(); + } + { + const p = await probe({task: {...unbound, creation_request: creation, creation_turn: null}, available: false}); + await p.button.waitFor(); + assert.equal(await p.button.isDisabled(), true, "Creation already authorized the original request; no second launch control"); + await p.section.getByRole("status").filter({hasText: "waiting for checks"}).waitFor(); + assert.deepEqual(p.writes, [], "Reading pending creation never submits a native request"); + p.state.task = {...ready, reason: "The current allowance is unavailable", creation_request: creation, creation_turn: null}; + await p.poll(); + await p.section.getByRole("status").filter({hasText: "The current allowance is unavailable"}).waitFor(); + await p.section.getByRole("status").filter({hasText: "waiting to run"}).waitFor(); + assert.deepEqual(p.writes, [], "The backend reason describes held admission without another launch"); + p.state.task = {...ready, creation_request: creation, creation_turn: null}; p.state.available = true; + await p.poll(); assert.equal(await p.button.isDisabled(), true, "Ready checks let the queue consume prior approval without UI launch"); + await p.page.evaluate(key => sessionStorage.removeItem(key), storageKey); + await p.page.reload(); await p.button.waitFor(); + assert.equal(await p.button.isDisabled(), true, "Reload discovers the server request without browser storage"); + p.state.task.creation_turn = native(creation.operation_id, "running"); await p.poll(); + assert.equal(await p.section.locator('[data-active="true"]').count(), 1); + assert.ok(Number(await p.page.getByLabel("History observations").textContent()) >= 1, "Existing history owner observes the original creation Turn"); + p.state.task.creation_turn = native(creation.operation_id, "failed"); await p.poll(); + assert.equal(await p.button.isDisabled(), false); assert.equal(await p.button.textContent(), "Continue Task"); + const terminalReads = p.reads.length; + await p.page.clock.fastForward(16000); await p.page.clock.runFor(30); + assert.equal(p.reads.length, terminalReads, "Creation terminal stops polling"); assert.deepEqual(p.writes, []); + await p.button.click(); + await p.page.waitForFunction(() => document.querySelector(".goal-loopx-mode-status")?.textContent.includes("waiting to run")); + assert.equal(p.writes.length, 1); assert.notEqual(p.writes[0].operation_id, creation.operation_id, + "A later explicit repair uses the existing Continue operation"); + await p.finish(); + } + { + const p = await probe({task: {...unbound, todo_id: null, reason: "The original conversation is busy", + creation_request: creation, creation_turn: native(creation.operation_id, "starting")}, available: false}); + await p.button.waitFor(); + assert.equal(await p.button.isDisabled(), true); + await p.section.getByRole("status").filter({hasText: "waiting to run"}).waitFor(); + assert.equal(await p.section.getByRole("alert").count(), 0, + "Unavailable current Task selection does not hide the independently bound original request and Turn"); + assert.deepEqual(p.writes, []); await p.finish(); + } + for (const mutation of ["operation", "goal", "lifetime", "agent", "session", "todo", "turn", "missing-projection"]) { + const request = {...creation}, task = {...ready, creation_request: request, creation_turn: native(creation.operation_id)}; + if (mutation === "operation") request.creation_operation_id = "other-creation"; + if (mutation === "goal") request.goal_id = "other-goal"; + if (mutation === "lifetime") request.goal_instance_id = "other-lifetime"; + if (mutation === "agent") request.agent_id = "other-agent"; + if (mutation === "session") request.session_id = "other-session"; + if (mutation === "todo") request.todo_id = "other-task"; + if (mutation === "turn") task.creation_turn.client_turn_id = "managed.other-operation"; + if (mutation === "missing-projection") delete task.creation_turn; + const p = await probe({task}); + await p.section.getByRole("alert").waitFor(); + assert.equal(await p.button.textContent(), "Refresh"); assert.deepEqual(p.writes, []); + await p.page.clock.fastForward(16000); await p.page.clock.runFor(30); + assert.deepEqual(p.writes, [], `${mutation}: unverifiable server identity cannot authorize launch`); + p.state.task = {...ready, creation_request: creation, creation_turn: null}; + await p.button.click(); + await p.section.getByRole("status").filter({hasText: "waiting to run"}).waitFor(); + assert.deepEqual(p.writes, [], "Recovery rereads the existing server request"); + await p.finish(); + } + { + const p = await probe({loseAck: true}); await p.button.waitFor(); await p.button.click(); + await p.page.waitForFunction(() => document.querySelector(".goal-loopx-mode-status")?.textContent.includes("waiting to run")); + assert.equal(p.writes.length, 1); const operation = p.writes[0].operation_id; + assert.match(operation, /^task\./); assert.equal(await p.button.isDisabled(), true); + assert.equal(await p.section.locator('[data-active="true"]').count(), 0, "Queued ACK recovery does not imply running"); + await p.page.reload(); await p.button.waitFor(); + assert.equal(await p.button.isDisabled(), true); assert.equal(p.writes.length, 1); + assert.equal(p.reads.at(-1).operation_id, operation, "Reload reads the retained operation"); + await p.page.evaluate(() => { + Object.defineProperty(document, "hidden", {configurable: true, value: true}); + document.dispatchEvent(new Event("visibilitychange")); + }); + const hiddenReads = p.reads.length; + await p.page.clock.fastForward(16000); await p.page.clock.runFor(30); + assert.equal(p.reads.length, hiddenReads, "Hidden pending Tasks do not poll"); + const returned = p.page.waitForResponse(row => row.url().includes("native-turn")); + await p.page.evaluate(() => { + Object.defineProperty(document, "hidden", {configurable: true, value: false}); + document.dispatchEvent(new Event("visibilitychange")); + }); + await returned; + p.state.turn = native(operation, "running"); await p.poll(); + assert.equal(await p.section.locator('[data-active="true"]').count(), 1); + p.state.turn = native(operation, "failed"); await p.poll(); + assert.equal(await p.button.isDisabled(), false); assert.equal(p.writes.length, 1, "Failure never launches automatically"); + const terminalReads = p.reads.length; + await p.page.clock.fastForward(16000); await p.page.clock.runFor(30); + assert.equal(p.reads.length, terminalReads, "Known terminal Turns stop readback polling"); + await p.button.click(); + await p.page.waitForFunction(() => document.querySelector(".goal-loopx-mode-status")?.textContent.includes("waiting to run")); + assert.equal(p.writes.length, 2); assert.notEqual(p.writes[1].operation_id, operation, "Explicit retry owns a fresh operation after a confirmed terminal Turn"); + assert.ok(Number(await p.page.getByLabel("History observations").textContent()) >= 3); + await p.finish(); + } + for (const mutation of ["operation", "agent", "goal", "session", "todo", "turn-id", "missing-turn", "ordinary-turn"]) { + const saved = {operationId: "retained-request", todoId: ready.todo_id, turnId: "original-native-turn", status: "running"}; + const turn = native(saved.operationId, "failed"); + if (mutation === "operation") turn.client_turn_id = "managed.unrelated-request"; + if (mutation === "agent") turn.loopx_request.actor.agent_id = "other-agent"; + if (mutation === "goal") turn.loopx_request.actor.goal_id = "other-goal"; + if (mutation === "session") turn.session_id = "other-session"; + if (mutation === "todo") turn.loopx_request.todo_id = "other-task"; + if (mutation === "turn-id") turn.turn_id = "different-turn"; + if (mutation === "ordinary-turn") turn.loopx_execution = false; + const p = await probe({attempt: JSON.stringify(saved), turn: mutation === "missing-turn" ? null : turn}); + await p.section.getByRole("alert").waitFor(); + assert.equal(await p.button.textContent(), "Refresh"); await p.button.click(); + await p.poll(); assert.deepEqual(p.writes, [], `${mutation}: unverifiable recovery only rereads`); + assert.equal(await p.section.locator('[data-active="true"]').count(), 0); await p.finish(); + } + { + const p = await probe(); await p.button.waitFor(); + await p.page.evaluate(key => sessionStorage.setItem(key, "{malformed"), storageKey); + await p.button.click(); await p.section.getByRole("alert").waitFor(); + assert.deepEqual(p.writes, [], "Storage corruption immediately before launch also holds the request"); + await p.finish(); + } + { + const p = await probe({attempt: "{malformed"}); await p.section.getByRole("alert").waitFor(); + await p.button.click(); await p.page.clock.fastForward(5100); + assert.deepEqual(p.writes, []); assert.equal(p.reads.length, 0, "Unreadable saved operation is held without inventing another request"); + await p.finish(); + } + { + const p = await probe({attempt: JSON.stringify({operationId: "old-failed", todoId: ready.todo_id, status: "running"}), turn: native("old-failed", "failed")}); + await p.button.waitFor(); assert.equal(await p.button.isDisabled(), false, "A saved running label cannot override fresh terminal readback"); + assert.equal(await p.section.locator('[data-active="true"]').count(), 0); + await p.page.evaluate(key => sessionStorage.setItem(key, "[]"), storageKey); + await p.button.click(); + await p.section.getByRole("alert").waitFor(); await p.button.click(); + assert.deepEqual(p.writes, [], "Later storage corruption also revokes execution"); await p.finish(); + } + console.log("managed-task-entry: check-readiness, original identity, explicit native launch, ACK recovery, liveness, reload, retry and malformed-storage boundaries passed"); +} finally {await cleanupBrowserSmoke({browser, server, fixturePaths: []});} diff --git a/apps/presentation/dashboard/smoke/managed-task-entry-smoke.html b/apps/presentation/dashboard/smoke/managed-task-entry-smoke.html new file mode 100644 index 0000000000..ee482f3fd5 --- /dev/null +++ b/apps/presentation/dashboard/smoke/managed-task-entry-smoke.html @@ -0,0 +1,3 @@ + +Original Task entry +
diff --git a/apps/presentation/dashboard/smoke/managed-task-entry-smoke.tsx b/apps/presentation/dashboard/smoke/managed-task-entry-smoke.tsx new file mode 100644 index 0000000000..9bcc4fba89 --- /dev/null +++ b/apps/presentation/dashboard/smoke/managed-task-entry-smoke.tsx @@ -0,0 +1,16 @@ +import {useState} from "react"; +import {createRoot} from "react-dom/client"; +import {GoalLoopXMode} from "../src/features/personal-workspace/goal-loopx-mode"; +import {WorkspaceI18nProvider} from "../src/features/personal-workspace/i18n"; + +function OriginalTaskProbe() { + const [observations, setObservations] = useState(0); + const forbidden = () => {throw new Error("Managed Task entered the coordinator owner");}; + return
+ {forbidden(); return "";}} onExecute={forbidden} onChange={forbidden} + managed={{target: {goalId: "cart-repair", agentId: "codex", sessionId: "original-session"}, + onObserve: async () => {setObservations(value => value + 1);}}}/> + {observations} +
; +} +createRoot(document.getElementById("root")!).render(); diff --git a/apps/presentation/dashboard/smoke/research-evidence-version-browser-smoke.mjs b/apps/presentation/dashboard/smoke/research-evidence-version-browser-smoke.mjs index cf70d3c496..69d8220693 100644 --- a/apps/presentation/dashboard/smoke/research-evidence-version-browser-smoke.mjs +++ b/apps/presentation/dashboard/smoke/research-evidence-version-browser-smoke.mjs @@ -120,6 +120,23 @@ try { const atChapter = () => page.waitForFunction(id => document.activeElement?.id === id, address.hash.slice(1)); await page.goto(address.href); await atChapter(); + const views = page.getByRole("group", {name: "研究视图", exact: true}); + const historyView = views.getByRole("button", {name: "研究历程", exact: true}); + const caseView = views.getByRole("button", {name: "案例解读", exact: true}); + assert.equal(await caseView.getAttribute("aria-pressed"), "true"); + await historyView.press("Enter"); + await page.locator(".research-history-heading").waitFor(); + assert.equal(await historyView.getAttribute("aria-pressed"), "true"); + assert.equal(await historyView.evaluate(element => document.activeElement === element), true); + assert.equal(new URL(page.url()).searchParams.get("research_reading"), "history"); + await page.goBack(); + await atChapter(); + await page.goForward(); + await page.locator(".research-history-heading").waitFor(); + await caseView.press("Enter"); + await atChapter(); + assert.equal(new URL(page.url()).searchParams.get("research_pack"), studyPack.pack_id); + const sourceRequests = []; const quoteRoute = url => url.origin === new URL(study).origin && url.pathname.endsWith("/citation"); let failNextQuote = false; @@ -202,6 +219,8 @@ try { "The parent's address belongs to its own research"); } assertParentAddress(); + await page.locator(".research-history-heading").waitFor(); + assert.equal(await views.count(), 0, "A Goal without a saved study keeps its ordinary history"); await page.goBack(); await atChapter(); assert.equal(new URL(page.url()).searchParams.get("research_pack"), studyPack.pack_id); @@ -210,7 +229,7 @@ try { await page.goForward(); await page.waitForURL(url => url.searchParams.get("goalId") === parent.goal_id); assertParentAddress(); - console.log("research evidence version: saved excerpts, exact source links and chapter navigation restored"); + console.log("research evidence version: study and history navigation, saved excerpts and chapter position restored"); } finally { releaseOriginal?.(); await browser?.close(); diff --git a/apps/presentation/dashboard/smoke/research-human-attention-browser-smoke.mjs b/apps/presentation/dashboard/smoke/research-human-attention-browser-smoke.mjs new file mode 100644 index 0000000000..722f87592f --- /dev/null +++ b/apps/presentation/dashboard/smoke/research-human-attention-browser-smoke.mjs @@ -0,0 +1,141 @@ +import assert from 'node:assert/strict'; +import {createHash} from 'node:crypto'; +import {mkdtemp, mkdir, readFile, rm, writeFile} from 'node:fs/promises'; +import {tmpdir} from 'node:os'; +import {resolve} from 'node:path'; +import {launchBrowser, loadPlaywright} from '../../../../examples/dashboard-browser-smoke-support.mjs'; +import {startHistoryOwner} from '../../../../examples/personal-workspace-browser/research-history.mjs'; + +// Synthetic human observations exercise the production pack/HTTP/packaged UI. +// No native transcript, live Goal, inferred human origin or model is used. +const repo = resolve(import.meta.dirname, '../../../..'); +const root = await mkdtemp(resolve(tmpdir(), 'loopx-attention-reader-')); +const output = resolve(repo, 'output/playwright/research-human-attention'); +const owners = []; +let browser; +const at = m => new Date(Date.UTC(2026, 0, 1, 0, m)).toISOString(); +const source = (id, artifact, text) => ({id, artifact, text, first_line: 1, + artifact_sha256: createHash('sha256').update(text).digest('hex')}); +async function fixture(mode) { + const base = JSON.parse(await readFile(resolve(repo, 'apps/presentation/dashboard/src/data/fixtures/research-native-readback.json'), 'utf8')); + const a = base.analyses[0], input = a.input; + a.outputs = {}; + a.config = {model: 'fixture', effort: 'max', service_tier: 'fast', research_synthesis: false}; + const kinds = ['clarification', 'correction', 'review', 'approval', 'status', 'other']; + const texts = ['Human supplied an already recorded constraint.', 'Human corrected evidence applied outside its tested version.', + 'Human reviewed independent evidence before accepting the result.', 'Human approved a new scope.', + 'Human responded to a progress update.', 'Human changed the research objective.']; + const events = Array.from({length: mode === 'empty' ? 0 : mode === 'sparse' ? 1 : 16}, (_, i) => ({ + event_id: `input-${i + 1}`, episode_id: i % 5 ? input.episodes[0].id : null, + kind: kinds[i % 6], necessity: [0,1,4].includes(i % 6) ? 'avoidable' : i % 6 === 5 ? 'unknown' : 'required', + occurred_at: at(i + 10), active: mode === 'sparse' ? {start: at(10), end: at(10)} : i % 3 ? {start: at(i + 10), end: at(i + 11)} : null, + request: mode === 'sparse' ? null : i % 4 ? {start: at(i + 5), end: at(i + 10)} : null, + citation: {source_id: 'human-receipts', first_line: i + 1, last_line: i + 1}, + })); + const evidence = Array.from({length: 16}, (_,i) => texts[i % 6] + ' Synthetic observation only.').join('\n'); + const capture = JSON.stringify({schema_version: 'trajectory_human_attention_v1', scope: input.scope, + start: at(0), end: at(59), complete: mode === 'empty', events: events.length ? [...events, events[0]] : []}); + a.artifacts['human-receipts.txt'] = evidence; a.artifacts['attention.json'] = capture; + input.sources.push(source('human-receipts', 'human-receipts.txt', evidence), source('attention', 'attention.json', capture)); + input.episodes[0].source_ids.push('human-receipts', 'attention'); + if (mode !== 'absent') input.human_attention_source_id = 'attention'; + const path = resolve(root, mode + '.json'); await writeFile(path, JSON.stringify(base)); + const owner = await startHistoryOwner(path); owners.push(owner); + return {owner, goal: base.goal_id}; +} +try { + await mkdir(output, {recursive: true}); + const full = await fixture('populated'), absent = await fixture('absent'), empty = await fixture('empty'), sparse = await fixture('sparse'); + browser = await launchBrowser(loadPlaywright().chromium); + const page = await browser.newPage({locale: 'zh-CN', viewport: {width: 1440, height: 1000}}); + const errors = [], writes = []; + page.on('pageerror', e => errors.push(e.message)); + page.on('request', r => {if (r.method() === 'POST') writes.push(r.url());}); + const visit = f => page.goto(`${f.owner.base}/chat/?goalId=${f.goal}&view=research&research_goal=${f.goal}&statusUrl=%2Fstatus.json`, {waitUntil: 'networkidle'}); + await visit(absent); + await page.locator('.research-progress').waitFor(); + await page.screenshot({path: resolve(output, 'before-desktop.png')}); + await page.locator('.research-progress-basis > summary').click(); + assert.match(await page.locator('.research-human-attention').innerText(), /未采集|Not recorded/); + await visit(full); + const attention = page.locator('.research-human-attention'); + await attention.waitFor(); + assert.match(await attention.innerText(), /16/); + assert.match(await attention.innerText(), /10.*分钟|10.*min/); + assert.match(await attention.innerText(), /19.*分钟|19.*min/); + const slices = await attention.locator('.research-attention-donut circle[data-kind]').evaluateAll(nodes => nodes.map(node => ({ + kind: node.dataset.kind, count: Number(node.dataset.count), share: Number(node.dataset.share), + length: Number(node.getAttribute('stroke-dasharray').split(' ')[0]), + }))); + assert.equal(slices.length, 6); + assert.equal(slices.reduce((sum, slice) => sum + slice.count, 0), 16); + assert.ok(Math.abs(slices.reduce((sum, slice) => sum + slice.length, 0) - 100) < 1e-8); + assert.equal(slices.find(slice => slice.kind === 'review').length, 18.75, 'Three of sixteen recorded reviews occupy 3/16 of the ring'); + assert.equal(slices.find(slice => slice.kind === 'status').length, 12.5); + const timeShares = await attention.locator('.research-attention-time-track > span').evaluateAll(nodes => nodes.map(n => Number(n.dataset.share))); + assert.ok(Math.abs(timeShares[0] - 10 / 59) < 1e-8 && Math.abs(timeShares[1] - 19 / 59) < 1e-8, + 'Active and waiting tracks independently use the captured 59-minute window, not their summed time'); + assert.match(await attention.locator('.research-attention-necessity-legend').innerText(), /8.*50%/); + assert.equal(await attention.locator('.research-attention-detail').evaluate(e => e.open), false); + await page.screenshot({path: resolve(output, 'after-desktop.png')}); + await attention.locator('.research-attention-detail > summary').focus(); + await page.keyboard.press('Enter'); + assert.equal(await attention.locator('.research-attention-events > li').count(), 8); + assert.equal(await attention.locator('.research-attention-opportunities > li').count(), 3, 'Required reviews and approvals are not optimization points'); + await attention.locator('.research-attention-pages button').last().click(); + assert.equal(await attention.locator('.research-attention-events').getAttribute('start'), '9'); + await attention.locator('.research-attention-pages button').first().click(); + const check = attention.locator('.research-attention-opportunities button').first(); + await check.click(); + await page.locator('.analysis-source').getByText(/Human supplied/).waitFor(); + await page.locator('.analysis-source').press('Escape'); + await page.waitForFunction(() => document.activeElement?.textContent?.includes('input-1')); + await page.route('**/research-analysis/citation?**', route => route.fulfill({status: 503, json: {error: 'Synthetic transient source failure'}}), {times: 1}); + await check.click(); + await page.getByRole('button', {name: /重试读取原文|Retry reading source/}).click(); + await page.locator('.analysis-source').getByText(/Human supplied/).waitFor(); + await page.locator('.analysis-source').press('Escape'); + await page.screenshot({path: resolve(output, 'optimization-desktop.png')}); + await page.setViewportSize({width: 390, height: 844}); + await attention.scrollIntoViewIfNeeded(); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), true); + await checkPanels(page); + await page.screenshot({path: resolve(output, 'optimization-narrow.png')}); + await visit(empty); + assert.match(await attention.locator('.research-attention-total').innerText(), /0/); + assert.match(await attention.locator('.research-attention-times').innerText(), /未采集|Not recorded/); + assert.equal(await attention.locator('.research-attention-donut circle[data-kind]').count(), 0, 'Zero inputs cannot invent a type share'); + assert.equal(await attention.locator('.research-attention-time-track > span').count(), 0, 'Unmeasured time is not a zero-width measurement'); + await visit(sparse); + assert.equal(await attention.locator('.research-attention-donut circle[data-kind]').count(), 1); + assert.equal(await attention.locator('.research-attention-donut circle[data-kind]').getAttribute('stroke-dasharray'), '100 0'); + assert.equal(await attention.locator('.attention-active .research-attention-time-track').getAttribute('data-observed'), 'true'); + assert.equal(await attention.locator('.attention-active .research-attention-time-track > span').getAttribute('data-share'), '0'); + assert.equal(await attention.locator('.attention-waiting .research-attention-time-track').getAttribute('data-observed'), 'false'); + // This preference belongs only to this disposable browser context. + await page.addInitScript(() => localStorage.setItem('loopx-pw-locale', 'en')); + await visit(full); + await page.getByRole('region', {name: 'Human attention'}).waitFor().catch(async () => { + await page.locator('[aria-label="Human attention"]').waitFor(); + }); + assert.match(await attention.innerText(), /Recorded|recorded/); + assert.match(await attention.innerText(), /Active attention/); + await attention.locator('.research-attention-detail > summary').click(); + assert.match(await attention.locator('.research-attention-opportunities').innerText(), /counterevidence/); + await checkPanels(page); + await page.screenshot({path: resolve(output, 'optimization-english-narrow.png')}); + await page.setViewportSize({width: 320, height: 844}); + await checkPanels(page); + assert.deepEqual(errors, []); assert.deepEqual(writes, []); + console.log('PASS: measured type shares, separate capture-window tracks, necessity shares, sparse/unknown/zero, internal overflow, pagination and source recovery; zero model writes'); +} finally { + await browser?.close(); + await Promise.all(owners.map(owner => owner.close())); + await rm(root, {recursive: true, force: true}); +} + +async function checkPanels(page) { + const overflow = await page.locator('.research-attention-breakdown, .research-attention-counts, .research-attention-times, .research-attention-necessity-legend').evaluateAll(nodes => + nodes.filter(n => n.scrollWidth > n.clientWidth + 1).map(n => n.className)); + assert.deepEqual(overflow, [], 'Named attention panels must fit internally, including long English labels'); +} diff --git a/apps/presentation/dashboard/smoke/team-task-revalidation-smoke.mjs b/apps/presentation/dashboard/smoke/team-task-revalidation-smoke.mjs index a606139d2e..a4fa4476c4 100644 --- a/apps/presentation/dashboard/smoke/team-task-revalidation-smoke.mjs +++ b/apps/presentation/dashboard/smoke/team-task-revalidation-smoke.mjs @@ -44,7 +44,9 @@ try { const started = Date.now(); const response = await page.request.post(`${origin}/api/chat/sessions/recovery/loopx`, {data: { operation: body.operation, operation_id: ["accepted-analysis", "synthesis-1"].includes(body.operation_id) ? selected : body.operation_id}}); - console.log(`HTTP ${body.operation} returned in ${Date.now() - started}ms`); + const {status, worker_active, recovery_required} = await response.json(); + console.log(`HTTP ${body.operation} returned ${response.status()} in ${Date.now() - started}ms`, + {status, worker_active, recovery_required}); return route.fulfill({response}); }); await page.getByText("LoopX · 正在推进", {exact: true}).waitFor(); @@ -99,12 +101,15 @@ try { await page.screenshot({path: resolve(outputDir, "team-original-recovery-desktop.png")}); await page.setViewportSize({width: 390, height: 844}); await recover.click(); + let actual; for (let attempt = 0; attempt < 30; attempt++) { - const actual = await command("task-inspect"); + actual = await command("task-inspect"); assert.equal(actual.host_calls, "1"); if (actual.operation.status === "accepted") break; await new Promise(done => setTimeout(done, 500)); } + const {status, worker_active, recovery_required} = actual.operation; + assert.equal(status, "accepted", JSON.stringify({status, worker_active, recovery_required})); await recheck.click(); await evidence.getByLabel("证据内容: output.json").waitFor(); assert.equal(await failure.count(), 0); diff --git a/apps/presentation/dashboard/src/data/chat.ts b/apps/presentation/dashboard/src/data/chat.ts index 1111dd55d9..8488f528ef 100644 --- a/apps/presentation/dashboard/src/data/chat.ts +++ b/apps/presentation/dashboard/src/data/chat.ts @@ -959,6 +959,7 @@ export type ChatSessionSnapshot = { session: ChatSessionSummary; messages: ChatVisibleMessage[]; active_turn: Record | null; + selected_turn?: {turn_id: string; status: string; terminal: boolean; error?: string}; // Derived from one complete, verified read. Never persisted or an authority grant. verifiedHistoryBasis?: string; message_page?: { @@ -971,6 +972,32 @@ export async function fetchChatSession(sessionId: string, signal?: AbortSignal) return requestJson(`/api/chat/sessions/${encodeURIComponent(sessionId)}`, { signal }); } +export async function fetchSavedChatAnswer(sessionId: string, messageId: string, signal: AbortSignal, turnId?: string) { + const query = new URLSearchParams({report_message_id: messageId}); + if (turnId !== undefined) query.set("turn_id", turnId); + const path = `/api/chat/sessions/${encodeURIComponent(sessionId)}?${query}`; + try { + const snapshot = await requestJson(path, {signal}); + // A legacy service can ignore the selector and return its complete v1 + // snapshot. A conflicting marker or a partial history remains invalid. + if (Object.hasOwn(snapshot, "report_message_id")) { + if (snapshot.report_message_id !== messageId) throw new Error("The saved answer selection changed during read."); + } else if ("message_page" in snapshot || "history_resume" in snapshot) { + throw new Error("The saved answer history is incomplete."); + } + return snapshot; + } catch (error) { + // Older Chat builds reject unknown history selectors before reading the + // Session. Only that response enables the earlier history read paths. + if (!(error instanceof ChatApiError) || error.payload.http_status !== 400 + || error.message !== "invalid history page arguments") throw error; + signal.throwIfAborted(); + return turnId === undefined + ? fetchChatSession(sessionId, signal) + : fetchChatSessionHistory(sessionId, signal, turnId); + } +} + export const chatQueueInputRequestSchema = z.discriminatedUnion("action", [ z.object({action: z.literal("edit"), operation_id: z.string().min(1).max(160), expected_revision: z.number().int().nonnegative(), message: z.string().min(1).max(24000)}).strict(), @@ -982,15 +1009,16 @@ const chatQueuedInputSchema = z.object({input_revision: z.number().int().nonnega attachments: z.array(z.object({id: z.string(), name: z.string(), size: z.number(), mime_type: z.string(), data_url: z.string()})), }); -export type ChatQueuedInput = z.infer; +export type ChatQueuedInput = z.infer & Pick; export async function fetchQueuedChatInput(sessionId: string, turnId: string, signal?: AbortSignal) { // Keep original-source audience projection and complete paging. The visible // input and its revision come from one canonical user row, never raw model context. const history = await fetchChatSessionHistory(sessionId, signal, turnId); const original = history.messages.find(row => row.role === "user" && row.turn_id === turnId); if (!original) throw new Error("Original queued input is unavailable"); - return chatQueuedInputSchema.parse({input_revision: original.queue_input_revision ?? 0, - message: original.reply_context?.source_text ?? original.text, attachments: original.attachments ?? []}); + return {...chatQueuedInputSchema.parse({input_revision: original.queue_input_revision ?? 0, + message: original.reply_context?.source_text ?? original.text, attachments: original.attachments ?? []}), + reply_context: original.reply_context}; } const chatQueueSchema = z.object({ ok: z.literal(true), schema_version: z.literal("loopx_chat_store_v1"), session_id: z.string().min(1), @@ -1092,8 +1120,24 @@ export async function fetchChatSessionHistory(session: ChatSessionSummary | stri return readChatSessionHistory(session, signal, turnId); } +export async function fetchConfirmedTaskTurn( + {goalId, todoId, sessionId, turnId}: {goalId: string; todoId: string; sessionId: string; turnId: string}, + signal: AbortSignal, +) { + const history = await readChatSessionHistory(sessionId, signal, turnId, undefined, undefined, {taskScope: {goalId, todoId}}); + const turn = history.selected_turn; + if (history.session.goal_id !== goalId || history.session.channel_id !== `task.${todoId}` + || turn?.turn_id !== turnId || typeof turn.status !== "string" || !turn.status + || typeof turn.terminal !== "boolean" || (turn.error !== undefined && typeof turn.error !== "string")) { + throw new Error("The original Task Turn could not be verified."); + } + return {turn, messages: history.messages}; +} + async function readChatSessionHistory(session: ChatSessionSummary | string, signal?: AbortSignal, turnId?: string, - progress?: ChatHistoryReadProgress, checkpoint?: (progress: ChatHistoryReadProgress) => void): Promise { + progress?: ChatHistoryReadProgress, checkpoint?: (progress: ChatHistoryReadProgress) => void, + {linkImages = false, taskScope}: {linkImages?: boolean; taskScope?: {goalId: string; todoId: string}} = {}, +): Promise { const sessionId = typeof session === "string" ? session : session.session_id; // A delegation has the original Session ID; pin its first verified page's // scope. History discovery callers keep validating against their own source. @@ -1110,10 +1154,15 @@ async function readChatSessionHistory(session: ChatSessionSummary | string, sign signal?.throwIfAborted(); const query = new URLSearchParams({message_limit: "200"}); if (turnId !== undefined) query.set("turn_id", turnId); + if (taskScope) { + query.set("task_goal_id", taskScope.goalId); + query.set("task_todo_id", taskScope.todoId); + } if (cursor !== null) query.set("message_cursor", cursor); const snapshot = await requestJson( `/api/chat/sessions/${encodeURIComponent(sessionId)}?${query}`, - {signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(CHAT_HISTORY_READ_TIMEOUT_MS)]) : AbortSignal.timeout(CHAT_HISTORY_READ_TIMEOUT_MS)}); + {signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(CHAT_HISTORY_READ_TIMEOUT_MS)]) : AbortSignal.timeout(CHAT_HISTORY_READ_TIMEOUT_MS), + headers: historyImageHeaders(linkImages)}); signal?.throwIfAborted(); const expected = expectedSession; const sameSource = snapshot.session?.session_id === sessionId && (!expected || sameHistorySource(snapshot.session, expected)); @@ -1167,7 +1216,13 @@ function historyBasisMatches(basis: string, count: number) { && match[2].length === Math.ceil(count / 200) * 64; } -async function tryResumeChatSessionHistory(session: ChatSessionSummary, saved: ChatSessionSnapshot) { +function historyImageHeaders(linkImages: boolean): HeadersInit | undefined { + // The linked bytes are same-origin resources. A separately configured Chat + // server still uses the compatible inline representation. + return linkImages && !configuredChatOrigin ? {"X-LoopX-History-Images": "linked"} : undefined; +} + +async function tryResumeChatSessionHistory(session: ChatSessionSummary, saved: ChatSessionSnapshot, linkImages: boolean) { const basis = saved.verifiedHistoryBasis; if (!basis || !sameHistorySource(saved.session, session) || !historyBasisMatches(basis, saved.messages.length)) return null; const query = new URLSearchParams({message_limit: "200", known_history: basis}); @@ -1175,7 +1230,7 @@ async function tryResumeChatSessionHistory(session: ChatSessionSummary, saved: C try { snapshot = await requestJson( "/api/chat/sessions/" + encodeURIComponent(session.session_id) + "?" + query, - {signal: AbortSignal.timeout(CHAT_HISTORY_READ_TIMEOUT_MS)}); + {signal: AbortSignal.timeout(CHAT_HISTORY_READ_TIMEOUT_MS), headers: historyImageHeaders(linkImages)}); } catch (error) { // A service rollback may no longer accept this optional argument. if (error instanceof ChatApiError && error.payload.http_status === 400) return null; @@ -1296,11 +1351,26 @@ function sameHistoryRevision(current: ChatSessionSummary, read: ChatSessionSumma && current.status === read.status; } -function historyTransportUnavailable(error: unknown) { - if (!(error instanceof ChatApiError) || error.payload.error_code !== "chat_api_unavailable") return false; - const status = error.payload.http_status; +function hasPendingReturnDelivery(snapshot: ChatSessionSnapshot) { + // The owner also projects explicit_unverified when its receipt cannot be + // read. That projection can recover; a recorded terminal failure does not. + const pending = ({status, error}: {status: string; error?: string | null}) => + status !== "delivered" && status !== "superseded" + && (status !== "explicit_unverified" || error === "delivery_state_unreadable"); + return snapshot.messages.some(message => + (message.return_delivery && pending(message.return_delivery)) + || (message.collaborations ?? (message.collaboration ? [message.collaboration] : [])) + .some(request => request.returns.some(pending)) + ); +} + +function historyTransportUnavailable(error: unknown, allowPlain503 = false) { + if (!(error instanceof ChatApiError) || error.payload.session_invalidated === true) return false; + const {error_code: code, http_status: status} = error.payload; + // Bound private history can be confirmed separately when its store returns a plain 503. + if (allowPlain503 && status === 503 && code === undefined) return true; // A response body can be interrupted after successful history headers. - return status === undefined || status === 200 || Number(status) >= 500; + return code === "chat_api_unavailable" && (status === undefined || status === 200 || Number(status) >= 500); } export type ChatHistory = { @@ -1328,38 +1398,51 @@ export async function fetchChatHistory(options: { const exact = Boolean(options.bound || options.managed); const listed = options.managed ? {sessions: [await resolveManagedChatSession(options.managed, AbortSignal.timeout(CHAT_HISTORY_READ_TIMEOUT_MS))]} : (!options.bound ? previous : undefined) ?? await fetchChatSessions({ ...options, signal: AbortSignal.timeout(CHAT_HISTORY_READ_TIMEOUT_MS) }); - const known = new Map(previous?.snapshots.map((snapshot) => [snapshot.session.session_id, snapshot])); + const priorSnapshots = new Map(previous?.snapshots.map((snapshot) => [snapshot.session.session_id, snapshot])); + const known = new Map(priorSnapshots); const pending = previous?.pendingBoundSnapshot; const current = listed.sessions[0]; + const retained = !options.managed && pending && options.bound?.bindingId === pending.bindingId && current + && sameHistorySource(current, pending.snapshot.session) ? pending.snapshot : undefined; + const pendingReturnBasis = retained && hasPendingReturnDelivery(retained) ? retained : undefined; // This discovery happened after the retained read. An unchanged exact - // source and revision satisfy the pending check without fetching its pages. - if (!options.managed && pending && pending.bindingId === options.bound?.bindingId && current - && sameHistoryRevision(current, pending.snapshot.session)) { - known.set(current.session_id, pending.snapshot); + // source and revision can qualify a retained read with no outstanding returns. + if (current && retained && !pendingReturnBasis && sameHistoryRevision(current, retained.session)) { + known.set(current.session_id, retained); } const pendingReads = new Map(previous?.pendingReads); for (const id of pendingReads.keys()) if (!listed.sessions.some(session => session.session_id === id)) pendingReads.delete(id); // A failed historical read is not an empty transcript. Retrying only the // missing snapshots keeps this recovery read-only and bounds repeated work. const missing = listed.sessions.filter((session) => { - const saved = known.get(session.session_id)?.session; - return !saved || (exact && !sameHistoryRevision(session, saved)); + const saved = known.get(session.session_id); + // Return receipts can be written after the answer text. The bound suffix + // proof checks the displayed prefix, including delivery state. + return !saved || (exact && !sameHistoryRevision(session, saved.session)) + || (Boolean(options.bound) && (hasPendingReturnDelivery(saved) + || (priorSnapshots.has(session.session_id) && previous?.unavailableSessionIds.includes(session.session_id)))); }); if (exact) for (const session of missing) known.delete(session.session_id); const results = await Promise.allSettled(missing.map(async (session) => { const savedProgress = pendingReads.get(session.session_id); if (savedProgress && !sameHistorySource(savedProgress.first.session, session)) pendingReads.delete(session.session_id); const progress = pendingReads.get(session.session_id); - const saved = options.bound && !progress && previous?.snapshots.find(row => row.session.session_id === session.session_id); + // A retained read with pending returns is still private. Use it only as + // the basis for a fresh proof of the visible prefix through the same source. + const saved = options.bound && !progress && (pendingReturnBasis?.session.session_id === session.session_id + ? pendingReturnBasis : priorSnapshots.get(session.session_id)); let snapshot: ChatSessionSnapshot; try { - snapshot = (saved ? await tryResumeChatSessionHistory(session, saved) : null) + const linkImages = Boolean(options.bound); + snapshot = (saved ? await tryResumeChatSessionHistory(session, saved, linkImages) : null) ?? await readChatSessionHistory(session, undefined, undefined, progress, - checkpoint => pendingReads.set(session.session_id, checkpoint)); + checkpoint => pendingReads.set(session.session_id, checkpoint), {linkImages}); } catch (error) { // Reuse the hook's existing retry schedule only for a lost transport. // Revoked sources, invalid pages and stale cursors must start a fresh read. - if (!historyTransportUnavailable(error)) pendingReads.delete(session.session_id); + if (!historyTransportUnavailable(error, Boolean(options.bound && !options.managed))) { + pendingReads.delete(session.session_id); + } throw error; } pendingReads.delete(session.session_id); @@ -1382,7 +1465,7 @@ export async function fetchChatHistory(options: { throw new Error("The original Session scope changed during history read."); } } catch (error) { - if (options.managed || read?.status !== "fulfilled" || !historyTransportUnavailable(error)) throw error; + if (options.managed || read?.status !== "fulfilled" || !historyTransportUnavailable(error, true)) throw error; return { messages: [], sessions: listed.sessions, @@ -1398,12 +1481,28 @@ export async function fetchChatHistory(options: { for (const result of results) { if (result.status === "fulfilled") known.set(result.value.session.session_id, result.value); } - const snapshots = listed.sessions.flatMap((session) => known.has(session.session_id) ? [known.get(session.session_id)!] : []); + let sessions = listed.sessions; + let usingStaleBoundHistory = false; + const failed = results[0]; + const saved = current && priorSnapshots.get(current.session_id); + if (options.bound && !options.managed && failed?.status === "rejected" && historyTransportUnavailable(failed.reason, true) + && current && saved && sameHistorySource(current, saved.session)) { + // Keep only an already proven transcript. If the binding changed while the + // failed read was in flight, rechecking it here keeps this path fail-closed. + const confirmed = await resolveBoundChatSession(options.bound, AbortSignal.timeout(CHAT_HISTORY_READ_TIMEOUT_MS)); + if (!sameHistorySource(confirmed, saved.session)) { + throw new Error("The original Session scope changed during history read."); + } + sessions = [confirmed]; + known.set(confirmed.session_id, saved); + usingStaleBoundHistory = true; + } + const snapshots = sessions.flatMap((session) => known.has(session.session_id) ? [known.get(session.session_id)!] : []); return { messages: mergeChatSessionMessages(snapshots), - sessions: listed.sessions, + sessions, snapshots, - unavailableSessionIds: listed.sessions.filter((session) => !known.has(session.session_id)).map((session) => session.session_id), + unavailableSessionIds: sessions.filter(session => usingStaleBoundHistory || !known.has(session.session_id)).map(session => session.session_id), pendingReads, }; } @@ -1625,6 +1724,77 @@ export async function steerChatTurn(sessionId: string, turnId: string, message: return receipt; } +const managedTaskTurnSchema = z.object({ + session_id: z.string().min(1), turn_id: z.string().min(1), client_turn_id: z.string().min(1), status: z.string().min(1), + origin: z.literal("native_loopx"), loopx_execution: z.literal(true), + loopx_request: z.object({operation: z.literal("native_turn"), todo_id: z.string().min(1), + actor: z.object({goal_id: z.string().min(1), agent_id: z.string().min(1), session_id: z.string().min(1)})}), +}).passthrough(); +const managedTaskCreationRequestSchema = z.object({ + creation_operation_id: z.string().min(1), operation_id: z.string().min(1), + goal_id: z.string().min(1), goal_instance_id: z.string().min(1).nullable(), agent_id: z.string().min(1), + session_id: z.string().min(1), todo_id: z.string().min(1), + permission: z.enum(["read_only", "workspace_write_on_confirmation"]), write_scope: z.array(z.string().min(1)), +}); +const taskCreationReadback = {creation_request: managedTaskCreationRequestSchema.optional(), + creation_turn: managedTaskTurnSchema.nullable().optional()}; +const managedTaskEntrySchema = z.object({ok: z.literal(true), session_id: z.string().min(1), + managed_agent_id: z.string().nullable(), registered_agents: z.array(z.string()), available: z.boolean(), reason: z.string().optional(), + task: z.discriminatedUnion("state", [ + z.object({todo_id: z.string().min(1), state: z.literal("ready"), source: z.string().min(1), canonical_done: z.boolean(), + observation: z.object({check_count: z.number().int().nonnegative(), pinned_file_count: z.number().int().nonnegative(), + basis_sha256: z.string().min(1)}), reason: z.string().optional(), ...taskCreationReadback}), + z.object({todo_id: z.string().nullable(), state: z.literal("unbound"), source: z.null(), canonical_done: z.literal(false), + reason: z.string().optional(), ...taskCreationReadback}), + ]), turn: managedTaskTurnSchema.nullable(), +}); +export type ManagedTaskEntry = z.infer; +export type ManagedTaskTurn = z.infer; + +function verifyManagedTaskTurn(turn: ManagedTaskTurn, target: ManagedConversationTarget, operationId: string, todoId?: string) { + const actor = turn.loopx_request.actor; + if (turn.session_id !== target.sessionId || turn.client_turn_id !== `managed.${operationId}` + || actor.session_id !== target.sessionId || actor.goal_id !== target.goalId || actor.agent_id !== target.agentId + || todoId !== undefined && turn.loopx_request.todo_id !== todoId) throw new Error("The original Task Turn identity changed."); +} + +/** Read the Core-selected original Task; preparation and check adoption grant no launch. */ +export async function fetchManagedTaskEntry(target: ManagedConversationTarget, options: {operationId?: string; todoId?: string; signal?: AbortSignal} = {}) { + const session = await resolveManagedChatSession(target, options.signal); + const query = new URLSearchParams({original_task: "true", agent_id: target.agentId}); + if (options.operationId !== undefined) query.set("operation_id", options.operationId); + const result = managedTaskEntrySchema.parse(await requestJson( + `/api/chat/sessions/${encodeURIComponent(target.sessionId)}/native-turn?${query}`, {signal: options.signal})); + if (result.session_id !== target.sessionId || result.managed_agent_id !== target.agentId || !result.registered_agents.includes(target.agentId)) { + throw new Error("The original Task entry is unavailable from this Agent."); + } + if (result.turn) { + if (!options.operationId) throw new Error("The Task read returned an unrelated operation."); + verifyManagedTaskTurn(result.turn, target, options.operationId, options.todoId); + } + const creation = result.task.creation_request; + if (creation) { + if (creation.operation_id !== `goal-create-${creation.creation_operation_id}` + || creation.goal_id !== target.goalId || creation.goal_instance_id !== session.goal_instance_id + || creation.agent_id !== target.agentId || creation.session_id !== target.sessionId + || result.task.todo_id !== null && creation.todo_id !== result.task.todo_id + || result.task.creation_turn === undefined) throw new Error("The original creation request identity changed."); + if (result.task.creation_turn) verifyManagedTaskTurn(result.task.creation_turn, target, creation.operation_id, creation.todo_id); + } else if (result.task.creation_turn) throw new Error("The creation Turn has no original request."); + return result; +} + +/** Only an explicit owner operation calls the existing native Task admission. */ +export async function startManagedTaskTurn(target: ManagedConversationTarget, todoId: string, operationId: string, signal?: AbortSignal) { + await resolveManagedChatSession(target, signal); + const result = z.object({ok: z.literal(true), session_id: z.string(), turn: managedTaskTurnSchema, created: z.boolean()}).parse( + await requestJson(`/api/chat/sessions/${encodeURIComponent(target.sessionId)}/native-turn`, {method: "POST", signal, + body: JSON.stringify({agent_id: target.agentId, operation_id: operationId, todo_id: todoId})})); + if (result.session_id !== target.sessionId) throw new Error("The original Task Session changed during launch."); + verifyManagedTaskTurn(result.turn, target, operationId, todoId); + return result; +} + export type LoopXModeSnapshot = { ok: true; session_id: string; enabled: boolean; active_turn_id: string | null; conversation_busy: boolean; settings: Partial & { execution_config?: string }; @@ -2988,12 +3158,16 @@ export async function updateGoalOwnership(body: { goal_id: string; mode: Executi const privateAgentSessionSchema = z.object({session_id: z.string(), goal_id: z.string(), agent_id: z.string(), executor_endpoint_id: z.string()}); const privateAgentTargetSchema = privateAgentSessionSchema.extend({target_ref: z.string(), host_ref: z.string(), goal_instance_id: z.string().nullable()}); -const privateConversationSchema = z.object({ +const privateConversationSettingsRowSchema = z.object({ binding_id: z.string(), app_ref: z.string(), context_kind: z.enum(["project", "steward"]), project_ref: z.string(), project_title: z.string(), context_available: z.boolean(), executor_endpoint_id: z.string(), - grant: z.enum(["workspace_read", "workspace_write", "portfolio_read"]), goal_count: z.number().int().default(0), listener_status: z.string(), + grant: z.enum(["workspace_read", "workspace_write", "portfolio_read"]), goal_count: z.number().int().default(0), goal_scope: z.enum(["all_registered", "selected"]).nullable().optional(), audience: z.enum(["owner", "group"]).default("owner"), group_count: z.number().int().default(0), + agent_targets: z.array(privateAgentTargetSchema).default([]), +}); +const privateConversationDiagnosticsRowSchema = z.object({ + binding_id: z.string(), listener_status: z.string(), pending_count: z.number().int(), recovery_count: z.number().int(), ingress: z.object({status: z.enum(["unobserved", "verified", "gap", "unavailable"]), last_checked_at: z.number().nullable(), last_complete_at: z.number().nullable(), @@ -3026,14 +3200,21 @@ const privateConversationSchema = z.object({ z.object({available: z.literal(false), error_code: z.string(), execution_available: z.boolean().optional(), execution_error_code: z.string().optional()}), ]).optional(), - agent_candidates: z.array(privateAgentSessionSchema).default([]), agent_targets: z.array(privateAgentTargetSchema).default([]), + agent_candidates: z.array(privateAgentSessionSchema).default([]), }); +const privateConversationSchema = privateConversationSettingsRowSchema.extend(privateConversationDiagnosticsRowSchema.shape); const privateConversationStopRecoverySchema = z.object({binding_id: z.string(), project_ref: z.string(), project_title: z.string(), pending_count: z.number().int().positive()}); export type PrivateConversationStopRecovery = z.infer; -const privateConversationsSchema = z.object({ok: z.literal(true), revision: z.number().int(), +const privateConversationSettingsSchema = z.object({ok: z.literal(true), revision: z.number().int(), app_steward_binding_id: z.string().regex(/^[a-f0-9]{24}$/).nullable().default(null), + connections: z.array(privateConversationSettingsRowSchema)}); +const privateConversationDiagnosticsSchema = z.object({ok: z.literal(true), revision: z.number().int(), + connections: z.array(privateConversationDiagnosticsRowSchema), stop_recoveries: z.array(privateConversationStopRecoverySchema)}); +const privateConversationsSchema = privateConversationSettingsSchema.extend({ connections: z.array(privateConversationSchema), stop_recoveries: z.array(privateConversationStopRecoverySchema).default([])}); +export type PrivateConversationSettings = z.infer; +export type PrivateConversationDiagnostics = z.infer; export type PrivateConversation = z.infer; const boundConversationSourceSchema = privateConversationSchema.pick({ binding_id: true, app_ref: true, context_kind: true, project_title: true, executor_endpoint_id: true, @@ -3056,6 +3237,23 @@ export async function resolveBoundConversation(target: BoundConversationTarget, export async function fetchPrivateConversations(signal?: AbortSignal) { return privateConversationsSchema.parse(await requestJson("/api/chat/lark/private-conversations", { signal })); } + +export async function fetchPrivateConversationSettings(signal: AbortSignal) { + return privateConversationSettingsSchema.parse( + await requestJson("/api/chat/lark/private-conversations?view=settings", {signal})); +} + +export async function fetchPrivateConversationDiagnostics(settings: PrivateConversationSettings, signal: AbortSignal) { + const diagnostics = privateConversationDiagnosticsSchema.parse(await requestJson( + `/api/chat/lark/private-conversations?view=diagnostics&revision=${settings.revision}`, {signal})); + const observedBindingIds = new Set(diagnostics.connections.map(row => row.binding_id)); + if (diagnostics.revision !== settings.revision || diagnostics.connections.length !== settings.connections.length + || observedBindingIds.size !== diagnostics.connections.length + || !settings.connections.every(row => observedBindingIds.has(row.binding_id))) { + throw new Error("Conversation bindings changed during the read"); + } + return diagnostics; +} const appStewardTargetSchema = z.union([ z.object({ok: z.literal(true), binding_id: z.null(), session_id: z.null()}), z.object({ok: z.literal(true), binding_id: z.string().regex(/^[a-f0-9]{24}$/), @@ -3073,7 +3271,7 @@ export async function selectAppSteward(bindingId: string | null, revision: numbe return result; } export async function connectPrivateConversation(appRef: string, projectRef: string, executor: string, contextKind: "project" | "steward" = "project", projectGrant: "workspace_read" | "workspace_write" = "workspace_write", groupIds?: string[]) { - return privateConversationsSchema.parse(await requestJson("/api/chat/lark/private-conversations", { + return z.object({ok: z.literal(true)}).parse(await requestJson("/api/chat/lark/private-conversations?response=minimal", { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({app_ref: appRef, project_ref: projectRef, executor_endpoint_id: executor, context_kind: contextKind, project_grant: projectGrant, ...(contextKind === "steward" ? {goal_scope: "all_registered"} : {}), @@ -3081,7 +3279,7 @@ export async function connectPrivateConversation(appRef: string, projectRef: str })); } export async function disconnectPrivateConversation(bindingId: string, revision: number) { - return privateConversationsSchema.parse(await requestJson("/api/chat/lark/private-conversations", { + return z.object({ok: z.literal(true)}).parse(await requestJson("/api/chat/lark/private-conversations?response=minimal", { method: "DELETE", headers: {"Content-Type": "application/json"}, body: JSON.stringify({binding_id: bindingId, revision}), })); } diff --git a/apps/presentation/dashboard/src/data/conversation-returns.test.mjs b/apps/presentation/dashboard/src/data/conversation-returns.test.mjs index 4243c8f10f..787e9dc6c3 100644 --- a/apps/presentation/dashboard/src/data/conversation-returns.test.mjs +++ b/apps/presentation/dashboard/src/data/conversation-returns.test.mjs @@ -16,6 +16,28 @@ assert.equal(reconcileConversationReturns(cancelled, "queued-session", [editedIn assert.equal(reconcileConversationReturns(queuedInput, "other-session", [cancelledInput], () => assert.fail()), queuedInput); const liveAnswer = [{...queuedInput[0], role: "assistant", pending: true, text: "Live answer"}]; assert.equal(reconcileConversationReturns(liveAnswer, "queued-session", [{...cancelledInput, role: "agent"}], () => assert.fail())[0].text, "Live answer"); + +const historyImage = (sessionId, hash) => `/api/chat/sessions/${sessionId}/messages/original-image/images/0/${hash.repeat(64)}`; +const priorImage = {id: "image", mimeType: "image/png", name: "image.png", size: 70, dataUrl: historyImage("steward", "a")}; +const imageRow = {sourceSessionId: "steward", sourceMessageId: "original-image", role: "user", text: "Original image", attachments: [priorImage]}; +const currentImage = {message_id: "original-image", session_id: "steward", role: "user", attachments: [ + {id: "image", mime_type: "image/png", name: "image.png", size: 75, data_url: historyImage("steward", "b")}, +]}; +const noDuplicate = () => assert.fail("already observed message"); +const reloaded = reconcileConversationHistory([imageRow], [currentImage], noDuplicate, "steward"); +assert.equal(reloaded[0].attachments[0].dataUrl, historyImage("steward", "b")); +assert.equal(reloaded[0].attachments[0].size, 75); +assert.equal(reloaded[0].text, imageRow.text); +for (const [scope, attachment] of [ + [undefined, currentImage.attachments[0]], + ["different", currentImage.attachments[0]], + ["steward", {...currentImage.attachments[0], data_url: historyImage("different", "b")}], + ["steward", {...currentImage.attachments[0], data_url: historyImage("steward", "b").replace("/images/0/", "/images/1/")}], +]) { + assert.equal(reconcileConversationHistory([imageRow], [{...currentImage, attachments: [attachment]}], noDuplicate, scope)[0], imageRow); +} +const pendingImage = {...imageRow, pending: true}; +assert.equal(reconcileConversationHistory([pendingImage], [currentImage], noDuplicate, "steward")[0], pendingImage); const original = [ { sourceSessionId: "old", sourceMessageId: "brief", collaboration, text: "Original brief" }, { sourceSessionId: "current", sourceMessageId: "brief", text: "New conversation" }, diff --git a/apps/presentation/dashboard/src/data/conversation-returns.ts b/apps/presentation/dashboard/src/data/conversation-returns.ts index 904156b0b4..c5e6ec0378 100644 --- a/apps/presentation/dashboard/src/data/conversation-returns.ts +++ b/apps/presentation/dashboard/src/data/conversation-returns.ts @@ -1,4 +1,5 @@ import type { ChatVisibleMessage } from "./chat"; +import type { WorkspaceImageAttachment } from "../features/personal-workspace/personal-workspace-model"; type ConversationMessage = { queueInputRevision?: number; @@ -14,9 +15,30 @@ type ConversationMessage = { collaborations?: ChatVisibleMessage["collaborations"]; returnDelivery?: ChatVisibleMessage["return_delivery"]; replyContext?: ChatVisibleMessage["reply_context"]; + attachments?: WorkspaceImageAttachment[]; text?: string; }; +function refreshHistoryImageLinks(row: ConversationMessage, source: ChatVisibleMessage, sessionId: string) { + if (row.pending || row.queued || row.queueInputCancelled || !row.sourceMessageId || row.sourceMessageId !== source.message_id + || source.session_id !== sessionId || row.role !== (source.role === "user" ? "user" : "assistant") + || !row.attachments?.length || source.attachments?.length !== row.attachments.length) return row.attachments; + const oldAttachments = row.attachments; + const freshAttachments = source.attachments; + const imageBase = `/api/chat/sessions/${encodeURIComponent(sessionId)}/messages/${encodeURIComponent(source.message_id)}/images/`; + let updated: WorkspaceImageAttachment[] | undefined; + for (const [index, old] of oldAttachments.entries()) { + const given = freshAttachments[index]; + const prefix = `${imageBase}${index}/`; + if (given.id !== old.id || given.mime_type !== old.mimeType || given.data_url === old.dataUrl + || !old.dataUrl.startsWith(prefix) || !given.data_url.startsWith(prefix) + || !/^[a-f0-9]{64}$/.test(given.data_url.slice(prefix.length))) continue; + updated ??= oldAttachments.slice(); + updated[index] = {...old, dataUrl: given.data_url, name: given.name, size: given.size}; + } + return updated ?? oldAttachments; +} + /** Delivery of one result does not close the conversation or its later updates. */ export function conversationReturnSessions(activeSessionId: string | undefined, messages: ConversationMessage[]): string[] { const sessions = new Set(activeSessionId ? [activeSessionId] : []); @@ -49,7 +71,7 @@ export function conversationPendingReturnSessions(messages: ConversationMessage[ /** A snapshot may refresh only its own session; it never replaces streamed text. */ export function reconcileConversationReturns( previous: T[], sessionId: string, messages: ChatVisibleMessage[], - createReply: (message: ChatVisibleMessage) => T, + createReply: (message: ChatVisibleMessage) => T, refreshLinkedImages = false, ): T[] { const byId = new Map(messages.map((row) => [row.message_id, row])); const byTurn = new Map(); @@ -75,6 +97,7 @@ export function reconcileConversationReturns( const collaborations = source.collaborations ?? row.collaborations; const sourceCreatedAt = source.created_at ?? row.sourceCreatedAt; const replyContext = source.reply_context ?? row.replyContext; + const attachments = refreshLinkedImages ? refreshHistoryImageLinks(row, source, sessionId) : row.attachments; // Only the exact canonical user body can switch to its source-backed view. // A background read never replaces a live answer or a different draft. const inputChanged = row.role === "user" && source.role === "user" @@ -90,11 +113,12 @@ export function reconcileConversationReturns( if (row.sourceMessageId === source.message_id && JSON.stringify(row.returnDelivery) === JSON.stringify(returnDelivery) && JSON.stringify(row.collaboration) === JSON.stringify(collaboration) && JSON.stringify(row.collaborations) === JSON.stringify(collaborations) && row.sourceCreatedAt === sourceCreatedAt - && JSON.stringify(row.replyContext) === JSON.stringify(replyContext) && row.text === text + && JSON.stringify(row.replyContext) === JSON.stringify(replyContext) && row.text === text && row.attachments === attachments && row.queueInputRevision === queueInputRevision && row.queueInputCancelled === queueInputCancelled && row.queued === queued) return row; changed = true; return { ...row, sourceMessageId: source.message_id, sourceCreatedAt, returnDelivery, collaboration, collaborations, replyContext, text, - queueInputRevision, queueInputCancelled, ...(queueAnswered ? {queued: false} : {}) }; + ...(attachments === row.attachments ? {} : {attachments}), queueInputRevision, queueInputCancelled, + ...(queueAnswered ? {queued: false} : {}) }; }); for (const message of messages) { if (message.origin !== "manager_followup" || seen.has(message.message_id)) continue; @@ -108,11 +132,13 @@ export function reconcileConversationReturns( /** Recover missing history without retracting messages or overwriting live text. */ export function reconcileConversationHistory( previous: T[], messages: ChatVisibleMessage[], createMessage: (message: ChatVisibleMessage) => T, + verifiedBoundSessionId?: string, ): T[] { let updated = previous; const sessions = new Set(messages.map((message) => message.session_id).filter((id): id is string => Boolean(id))); for (const sessionId of sessions) { - updated = reconcileConversationReturns(updated, sessionId, messages.filter((message) => message.session_id === sessionId), createMessage); + updated = reconcileConversationReturns(updated, sessionId, messages.filter((message) => message.session_id === sessionId), + createMessage, sessionId === verifiedBoundSessionId); } // A history read can arrive before admission hydrates the optimistic row. // Deduplicate only established Session/message identities, never body text. diff --git a/apps/presentation/dashboard/src/features/personal-workspace/answer-report-page.tsx b/apps/presentation/dashboard/src/features/personal-workspace/answer-report-page.tsx index 5f38dc2034..167c0a129c 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/answer-report-page.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/answer-report-page.tsx @@ -1,6 +1,6 @@ import {useEffect, useMemo, useRef, useState} from "react"; -import {fetchChatSession, type ChatSessionSnapshot, type ChatVisibleMessage} from "../../data/chat"; +import {fetchSavedChatAnswer, type ChatSessionSnapshot, type ChatVisibleMessage} from "../../data/chat"; import {visibleAgentMessage} from "./answer-text"; import {readWorkspaceLocale} from "./i18n"; import {resolveConversationScope} from "../../../../../../loopx/control_plane/collaboration/conversation_scope"; @@ -24,7 +24,8 @@ export function AnswerReportPage({sessionId, messageId, statusUrl}: { messageId: string; statusUrl: string; }) { - const scope = JSON.stringify([statusUrl || "/status.json", sessionId, messageId]); + const turnId = new URLSearchParams(window.location.search).get("reportTurnId"); + const scope = JSON.stringify([statusUrl || "/status.json", sessionId, messageId, turnId]); const [loaded, setLoaded] = useState<{scope: string; value: ReportState} | null>(null); // A late read from the preceding source never appears in the new reader. const state: ReportState = loaded?.scope === scope ? loaded.value : {kind: "loading"}; @@ -44,16 +45,18 @@ export function AnswerReportPage({sessionId, messageId, statusUrl}: { setLoaded({scope, value: {kind: "loading"}}); setCopied(false); setCopyFailed(false); - void fetchChatSession(sessionId, controller.signal).then((snapshot) => { + const read = fetchSavedChatAnswer(sessionId, messageId, controller.signal, turnId ?? undefined); + void read.then((snapshot) => { if (!live) return; if (snapshot.ok !== true || snapshot.schema_version !== "loopx_chat_store_v1" || snapshot.session.session_id !== sessionId) throw new Error("The saved Session changed during read."); const message = snapshot.messages.find((item) => item.message_id === messageId - && ["agent", "assistant"].includes(item.role)); + && ["agent", "assistant"].includes(item.role) + && (turnId === null || item.turn_id === turnId)); setLoaded({scope, value: message ? {kind: "ready", snapshot, message} : {kind: "missing", snapshot}}); }).catch(() => { if (live) setLoaded({scope, value: {kind: "error"}}); }); return () => {live = false; controller.abort(); copyAttempt.current += 1; document.title = previousTitle;}; - }, [scope, sessionId, messageId, zh, readRevision]); + }, [scope, sessionId, messageId, turnId, zh, readRevision]); const navigation = answerReportNavigation( (state.kind === "ready" || state.kind === "missing") ? state.snapshot.session : null, window.location.href, statusUrl, zh, @@ -180,6 +183,7 @@ export function answerReportNavigation( const managed = scope.kind === "owner_goal" && session?.managed_agent_id; url.searchParams.delete("reportSessionId"); url.searchParams.delete("reportMessageId"); + url.searchParams.delete("reportTurnId"); url.searchParams.delete("todo"); url.searchParams.delete("messageSession"); url.searchParams.delete("message"); diff --git a/apps/presentation/dashboard/src/features/personal-workspace/app-steward-entry.tsx b/apps/presentation/dashboard/src/features/personal-workspace/app-steward-entry.tsx index 1a23420147..f24833ff38 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/app-steward-entry.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/app-steward-entry.tsx @@ -1,15 +1,22 @@ import {useEffect, useRef, useState, type ReactNode} from "react"; import {Button} from "../../components/ui/button"; -import {fetchAppStewardTarget, type BoundConversationTarget} from "../../data/chat"; +import {ChatApiError, fetchAppStewardTarget, type BoundConversationTarget} from "../../data/chat"; import {useWorkspaceI18n} from "./i18n"; +export function appStewardUnavailableMessage(ownerLoginUnavailable: boolean, zh: boolean) { + return ownerLoginUnavailable + ? (zh ? "已连接飞书管家,但本人登录不可用。请用原账号为同一飞书应用重新登录,再重试;原会话仍保留。" + : "The Lark steward is connected, but its owner login is unavailable. Sign in to the same App with the original account, then retry. Your original conversation is retained.") + : (zh ? "原管家会话暂不可用。请检查所选连接后重试。" : "The original steward conversation is unavailable. Check the selected connection and retry."); +} + /** One read-only resolver for both App entrypoints. Pending/failed discovery * never exposes the ordinary manager queue. Explicit bound routes bypass it. */ export function useAppStewardTarget(enabled: boolean) { const [read, setRead] = useState<{enabled: boolean; revision: number; ready: boolean; - target: BoundConversationTarget | null; unavailable: boolean}>( - {enabled, revision: 0, ready: false, target: null, unavailable: false}); + target: BoundConversationTarget | null; unavailable: boolean; ownerLoginUnavailable: boolean}>( + {enabled, revision: 0, ready: false, target: null, unavailable: false, ownerLoginUnavailable: false}); // Invalidate in the render that changes scope, before a composer can submit // using a previous ordinary result. React retries this component immediately. if (read.enabled !== enabled) setRead({...read, enabled, ready: false, target: null, unavailable: false}); @@ -24,17 +31,18 @@ export function useAppStewardTarget(enabled: boolean) { let active = true; const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 5000); - const settle = (target: BoundConversationTarget | null, unavailable: boolean) => { + const settle = (target: BoundConversationTarget | null, unavailable: boolean, ownerLoginUnavailable = false) => { if (active) setRead(value => value.enabled === enabled && value.revision === revision - ? {...value, ready: true, target, unavailable} : value); + ? {...value, ready: true, target, unavailable, ownerLoginUnavailable} : value); }; void fetchAppStewardTarget(controller.signal).then(target => settle(target, false)) - .catch(() => settle(null, true)).finally(() => clearTimeout(timeout)); + .catch(error => settle(null, true, error instanceof ChatApiError + && error.payload.error_code === "lark_owner_identity_unavailable")).finally(() => clearTimeout(timeout)); return () => {active = false; controller.abort(); clearTimeout(timeout);}; }, [enabled, revision]); const ready = enabled && read.enabled === enabled && read.ready; return {target: ready ? read.target : null, loading: enabled && !ready, - unavailable: ready && read.unavailable, retry}; + unavailable: ready && read.unavailable, ownerLoginUnavailable: ready && read.ownerLoginUnavailable, retry}; } export function AppStewardEntry({children, enabled, intercept, onOpen}: { @@ -61,7 +69,7 @@ export function AppStewardEntry({children, enabled, intercept, onOpen}: { {blocked ?

{zh ? "LoopX 管家" : "LoopX steward"}

{!entry.unavailable ?

{zh ? "正在打开管家对话…" : "Opening the steward conversation…"}

: <> -

{zh ? "原管家会话暂不可用。请检查所选连接后重试。" : "The original steward conversation is unavailable. Check the selected connection and retry."}

+

{appStewardUnavailableMessage(entry.ownerLoginUnavailable, zh)}

{zh ? "打开会话设置" : "Open conversation settings"} diff --git a/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx b/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx index 3fe4f5dda2..2645c89c58 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx @@ -2,7 +2,8 @@ import {DocumentAttachment, isDocumentAttachment} from "./document-attachment"; import { MessageActivity } from "./message-activity"; import { GoalDraftCard } from "./goal-draft-card"; import type { GoalDraft } from "../../../../../../loopx/control_plane/collaboration/goal_draft.js"; -import {Fragment, useLayoutEffect, useRef, useState} from "react"; +import {goalDraftReady} from "./goal-create-request"; +import {Fragment, memo, useEffect, useEffectEvent, useLayoutEffect, useRef, useState} from "react"; import { CollaborationCards } from "./collaboration-card"; import {ConversationReplyContext} from "./conversation-requests"; import { Activity, Bot, Sparkles } from "lucide-react"; @@ -19,19 +20,44 @@ import { ReturnDeliveryStatus } from "./return-delivery-status"; import {ManagerTeamResult} from "./manager-team-result"; import { compareProposalRecency } from "./proposal-recency"; import { conversationOrder } from "./conversation-order"; -import type { WorkspaceDrawerSelection, WorkspaceGoal, WorkspaceTimelineItem } from "./personal-workspace-model"; +import { ConversationFind, conversationMessageKey } from "./conversation-find"; +import type { WorkspaceActionPreview, WorkspaceDrawerSelection, WorkspaceGoal, WorkspaceTimelineItem } from "./personal-workspace-model"; -function answerLink(sessionId: string, messageId: string) { +function answerLink(sessionId: string, messageId: string, turnId?: string) { const url = new URL(window.location.href); url.searchParams.set("reportSessionId", sessionId); url.searchParams.set("reportMessageId", messageId); + if (turnId) url.searchParams.set("reportTurnId", turnId); + else url.searchParams.delete("reportTurnId"); url.searchParams.set("view", "conversation"); url.hash = ""; return url.toString(); } +function LinkedHistoryImage({name, source, ready, zh}: {name: string; source: string; ready: boolean; zh: boolean}) { + const ref = useRef(null); + const [imageRead, setImageRead] = useState<{source: string; failed?: boolean}>(); + const requested = imageRead?.source === source; + useEffect(() => { + const image = ref.current; + if (!image || !ready || requested) return; + const observer = new IntersectionObserver(([entry]) => { + if (!entry?.isIntersecting) return; + observer.disconnect(); + setImageRead({source}); + }, {root: image.closest(".personal-channel-scroll"), rootMargin: "64px 0px"}); + observer.observe(image); + return () => observer.disconnect(); + }, [ready, requested, source]); + if (requested && imageRead.failed) return
+
{name}{zh ? "图片无法显示" : "Could not load image"}
+ +
; + return {name} setImageRead(current => current?.source === source ? {source, failed: true} : current)}/>; +} -export function ChannelTimeline({ +export const ChannelTimeline = memo(function ChannelTimeline({ emptyState, readOnly = false, items, @@ -39,6 +65,8 @@ export function ChannelTimeline({ selectedGoal, showManagerTeamResults = false, onReviewGoalDraft, + onApplyGoalDraft, + goalDraftPreparationContext, onSuggestReply, onOpenGoalEvidence, onInterruptTurn, @@ -46,6 +74,7 @@ export function ChannelTimeline({ onCancelPreparation, messageFocus, historyPhase = "ready", + historyPositionReady = true, onReadMessage, onRetryHistory, queuedTurnKeys, @@ -53,6 +82,7 @@ export function ChannelTimeline({ emptyState?: { title: string; description: string }; messageFocus?: {sessionId: string; messageId: string}; historyPhase?: ConversationHistoryStatus["phase"]; + historyPositionReady?: boolean; onReadMessage?: () => void; onRetryHistory?: () => void; queuedTurnKeys?: ReadonlySet; @@ -62,14 +92,45 @@ export function ChannelTimeline({ onSelect: (selection: WorkspaceDrawerSelection) => void; selectedGoal: WorkspaceGoal | null; showManagerTeamResults?: boolean; - onReviewGoalDraft?: (draft: GoalDraft, edit?: boolean, draftId?: string) => Promise; + onReviewGoalDraft?: (draft: GoalDraft, edit?: boolean, draftId?: string) => Promise; + onApplyGoalDraft?: (proposal: WorkspaceActionPreview) => Promise; + goalDraftPreparationContext?: string; onSuggestReply?: (text: string) => void; onOpenGoalEvidence?: (goalId: string) => void; onInterruptTurn?: (turnId: string) => Promise; onAdjustTurn?: (turnId: string) => void; }) { const { locale, t } = useWorkspaceI18n(); - const orderedItems = conversationOrder(items.filter(item => { + const [draftProposalIds, setDraftProposalIds] = useState>({}); + const draftKey = (id: string, draft: GoalDraft) => JSON.stringify([id, draft, goalDraftPreparationContext]); + const inlineProposalIds = new Set(items.flatMap(item => item.kind === "message" + && item.message.goalDraft && goalDraftReady(item.message.goalDraft) + ? [draftProposalIds[draftKey(`${item.message.sourceSessionId ?? ""}:${item.message.id}`, item.message.goalDraft)]] : [])); + async function reviewDraft(draft: GoalDraft, edit = false, id = "") { + const result = await onReviewGoalDraft?.(draft, edit, id); + if (!edit && result) setDraftProposalIds(current => ({...current, [draftKey(id, draft)]: result.previewId})); + return result; + } + const [findNavigation, setFindNavigation] = useState(0); + const [findMessageId, setFindMessageId] = useState(null); + const timeline = useRef(null); + const readMessage = useEffectEvent(() => onReadMessage?.()); + useLayoutEffect(() => { + if (!findMessageId) return; + readMessage(); + // Keep the scroll with the selection so a later user scroll stays put. + const row = Array.from(timeline.current?.querySelectorAll("[data-timeline-id]") ?? []) + .find(node => node.dataset.timelineId === findMessageId); + row?.scrollIntoView({block: "start"}); + }, [findMessageId, findNavigation]); + const presentedItems = items.filter(item => { + // The visible draft already owns this confirmation and recovery entry. + // Its canonical proposal remains available when the draft is not loaded. + if (item.kind === "proposal" && !readOnly && onApplyGoalDraft && onReviewGoalDraft + && inlineProposalIds.has(item.proposal.previewId)) return false; + return true; + }); + const orderedItems = conversationOrder(presentedItems.filter(item => { if (item.kind !== "message") return true; if (item.message.queued) return false; const queued = item.message.role === "user" && queuedTurnKeys?.has( @@ -78,8 +139,7 @@ export function ChannelTimeline({ && messageFocus?.messageId === item.message.sourceMessageId; return !queued || focused; })); - const messageKey = (message: Extract["message"]) => - JSON.stringify([message.sourceSessionId, message.sourceMessageId]); + const messageKey = conversationMessageKey; const [historical, setHistorical] = useState | null>(null); // Freeze only the first settled historical batch. A live or newly completed // response, or a message already being read, never folds on a later refresh. @@ -90,23 +150,24 @@ export function ChannelTimeline({ && !item.message.pending && item.message.sourceSessionId && item.message.sourceMessageId).map(item => messageKey(item.message)))); } const focusTarget = useRef(null); - const restoredFocus = useRef(null); + const [restoredFocus, setRestoredFocus] = useState(null); const focusKey = messageFocus ? JSON.stringify([messageFocus.sessionId, messageFocus.messageId]) : null; const focusPresent = Boolean(messageFocus && items.some(item => item.kind === "message" && item.message.sourceSessionId === messageFocus.sessionId && item.message.sourceMessageId === messageFocus.messageId)); useLayoutEffect(() => { - if (!focusKey) {restoredFocus.current = null; return;} - if (!focusPresent || restoredFocus.current === focusKey || !focusTarget.current) return; + if (!focusKey) {if (restoredFocus !== null) setRestoredFocus(null); return;} + if (!focusPresent || restoredFocus === focusKey || !focusTarget.current) return; onReadMessage?.(); const frame = window.requestAnimationFrame(() => { if (!focusTarget.current) return; onReadMessage?.(); focusTarget.current.scrollIntoView({block: "start"}); focusTarget.current.focus({preventScroll: true}); - restoredFocus.current = focusKey; + setRestoredFocus(focusKey); }); return () => window.cancelAnimationFrame(frame); - }, [focusKey, focusPresent, onReadMessage]); + }, [focusKey, focusPresent, onReadMessage, restoredFocus]); + const loadHistoryImages = historyPositionReady && (!focusPresent || restoredFocus === focusKey); const focusNotice = messageFocus && !focusPresent ?
{historyPhase === "loading" ? (locale === "zh-CN" ? "正在定位原消息…" : "Finding the original message…") : historyPhase === "ready" ? (locale === "zh-CN" ? "原消息不在当前已读取的对话中。" : "The original message is not in the loaded conversation.") @@ -137,7 +198,7 @@ export function ChannelTimeline({ ? t("timeline.runCompleted", { run: latestAnnounceable.run.title }) : ""; - const gatedItems = items.filter((item): item is Extract => + const gatedItems = presentedItems.filter((item): item is Extract => item.kind === "proposal" && item.proposal.status === "gated" && item.proposal.actionKind !== "operation.execute"); // Only routine execution is folded. Waiting, interruption, and failures stay // visible; no prose-based inference that a waiting run is safe to ignore. @@ -158,7 +219,7 @@ export function ChannelTimeline({ ] as Array).concat(locale === "zh-CN" ? [workingCount && `${workingCount} 个执行中`, queuedCount && `${queuedCount} 个排队中`, completedCount && `${completedCount} 次执行已结束`, progressCount && `${progressCount} 项进展更新`] : [workingCount && `${workingCount} running`, queuedCount && `${queuedCount} queued`, completedCount && `${completedCount} runs finished`, progressCount && `${progressCount} progress updates`]).filter(Boolean).join(" · "); - const activeProposalItems = items.filter((item): item is Extract => + const activeProposalItems = presentedItems.filter((item): item is Extract => item.kind === "proposal" && (item.proposal.status !== "gated" || item.proposal.actionKind === "operation.execute")); // Only drafts awaiting the owner fold behind the newest one; applying, applied and failed results stay visible. // "Newest" is read from the stored proposal, not from the position in this @@ -185,14 +246,18 @@ export function ChannelTimeline({ } if (item.kind === "proposal") { const appliedTeamPlan = item.proposal.actionKind === "team.plan" && item.proposal.status === "applied"; + const taskReceipt = item.proposal.reviewPlan?.taskExecution; const pendingOperation = item.proposal.reviewPlan?.operationFrame?.kind === "pending"; return ( {showManagerTeamResults && onOpenGoalEvidence && appliedTeamPlan && item.proposal.goalId && item.proposal.teamPlanTodoIds?.length ? @@ -200,7 +265,8 @@ export function ChannelTimeline({ ); } return ( -
{item.message.role === "user" ? item.message.agentLabel ?? t("common.you") : item.message.agentLabel ?? t("header.manager")}{item.message.time ? : null} {item.message.queueInputCancelled ? {locale === "zh-CN" ? "已取消排队" : "Cancelled before starting"} : null} - {item.message.attachments?.length ?
{item.message.attachments.map((attachment) => isDocumentAttachment(attachment.mimeType) ? : {attachment.name})}
: null} + {item.message.attachments?.length ?
{item.message.attachments.map((attachment) => { + if (isDocumentAttachment(attachment.mimeType)) return ; + const linked = attachment.dataUrl.startsWith("/api/chat/sessions/") && attachment.dataUrl.includes("/images/"); + return linked ? + : {attachment.name}; + })}
: null} {item.message.role === "user" ?

{item.message.text}

: item.message.text ? : null} + focusRequest={messageKey(item.message) === findMessageId ? findNavigation : undefined} + focused={messageKey(item.message) === findMessageId || Boolean(messageFocus && messageKey(item.message) === focusKey)} zh={locale === "zh-CN"} onRead={onReadMessage}/> : null} {item.message.role === "assistant" && !item.message.pending && item.message.text.length >= MIN_SEPARATE_ANSWER_LENGTH && item.message.sourceSessionId && item.message.sourceMessageId - ? {locale === "zh-CN" ? "单独阅读完整答复" : "Read full answer separately"} : null} {item.message.role !== "user" && (item.message.pending || item.message.sourceTurnId || item.message.activity?.length || item.message.steps?.length) ? : null} {item.message.role === "assistant" && !item.message.pending && item.message.goalDraft - ? : null} + ? : null}
@@ -233,7 +306,9 @@ export function ChannelTimeline({ <>

{liveAnnouncement}

{focusNotice} -
+ {orderedItems.some(item => item.kind === "message") ? item.kind === "message" ? [item.message] : [])} + incomplete={historyPhase !== "ready"} zh={locale === "zh-CN"} onSelect={setFindMessageId} onNavigate={() => setFindNavigation(value => value + 1)}/> : null} +
{backgroundIds.size ?
{scheduleItems.map(renderItem)}{routineRuns.map(renderItem)}
@@ -254,4 +329,4 @@ export function ChannelTimeline({
); -} +}); diff --git a/apps/presentation/dashboard/src/features/personal-workspace/confirmed-task-result.tsx b/apps/presentation/dashboard/src/features/personal-workspace/confirmed-task-result.tsx new file mode 100644 index 0000000000..5852f9fa9e --- /dev/null +++ b/apps/presentation/dashboard/src/features/personal-workspace/confirmed-task-result.tsx @@ -0,0 +1,69 @@ +import {useEffect, useId, useState} from "react"; +import {fetchConfirmedTaskTurn} from "../../data/chat"; +import {visibleAgentMessage} from "./answer-text"; +import {localizedSessionStatus, useWorkspaceI18n} from "./i18n"; +import {MarkdownText} from "./markdown"; + +type TaskReceipt = Parameters[0]; +type Result = Awaited>; + +export function ConfirmedTaskResult({receipt}: {receipt: TaskReceipt}) { + const {t} = useWorkspaceI18n(); + const panelId = useId(); + const [open, setOpen] = useState(false); + const [read, setRead] = useState(null); + const [retry, setRetry] = useState(0); + const {goalId, todoId, sessionId, turnId} = receipt; + useEffect(() => { + if (!open) return; + const controller = new AbortController(); + let next: ReturnType | undefined; + async function load() { + try { + const result = await fetchConfirmedTaskTurn({goalId, todoId, sessionId, turnId}, controller.signal); + if (controller.signal.aborted) return; + setRead(result); + if (!result.turn.terminal) next = setTimeout(load, 2_500); + } catch { + if (!controller.signal.aborted) setRead(new Error()); + } + } + void load(); + return () => { controller.abort(); clearTimeout(next); }; + }, [open, goalId, todoId, sessionId, turnId, retry]); + + const result = read && !(read instanceof Error) ? read : null; + const messages = result?.turn.terminal + ? result.messages.filter(message => ["agent", "assistant", "error"].includes(message.role)) + .map(message => ({...message, text: visibleAgentMessage(message.text)})).filter(message => message.text) + : []; + const failure = result?.turn.terminal && result.turn.error ? visibleAgentMessage(result.turn.error) : ""; + const showFailure = failure && !messages.some(message => message.role === "error" && message.text === failure); + const retryRead = () => {setRead(null); setRetry(value => value + 1);}; + return <> + + + ; +} diff --git a/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx b/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx index 49283ad4e9..1ee6ce52e3 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx @@ -46,6 +46,8 @@ import { localizedGoalState, localizedSessionStatus, useWorkspaceI18n } from "./ import { formatCostUsd, formatDurationMs, formatTokenCount, formatUsageValue, hasGoalUsage } from "./personal-workspace-model"; import { TeamPlanResult } from "./team-plan-result"; import { TaskRequest, taskRequestIdentity, type TaskRequestRead } from "./task-request"; +import { ConfirmedTaskResult } from "./confirmed-task-result"; +import {GoalCreationExecution} from "./goal-creation-execution"; import { parseTodoResumeCondition, todoResumeTransition } from "./todo-resume-condition"; import { MarkdownText } from "./markdown"; import { formatMonitorDate } from "./monitor-readback"; @@ -184,6 +186,8 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention const visibleProposalFields = selection.kind === "proposal" ? selection.item.fields.filter(field => !completionProofFields.includes(field)) : []; const proposalTarget = selection.kind === "proposal" ? selection.item : null; + const taskExecution = proposalTarget?.status === "applied" && !proposalReadbackUnavailable && !readOnly + ? proposalTarget.reviewPlan?.taskExecution : undefined; const proposalRequests = proposalTarget?.todoId ? attentionHistory.filter(item => item.goalId === proposalTarget.goalId && item.todoId === proposalTarget.todoId) : []; @@ -343,7 +347,8 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention && selection.item.reviewPlan?.operationFrame?.kind === "result" && selection.item.reviewPlan.operationFrame.resultKind === "unknown"; const decisionFrame = selection.kind === "proposal" ? selection.item.reviewPlan?.decisionFrame : undefined; - const title = selection.kind === "attention" ? t("drawer.titleAttention") + const title = taskExecution ? t("drawer.taskLaunchReceipt") + : selection.kind === "attention" ? t("drawer.titleAttention") : selection.kind === "todo" ? t("drawer.taskDetails") : selection.kind === "run" ? t("drawer.runDetails") : selection.kind === "output" ? t("drawer.titleOutput") @@ -661,7 +666,7 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention role="dialog" >
-

{title}

{selection.kind !== "goal" ?

{contextLabel}

: null}
+

{title}

{selection.kind !== "goal" && !taskExecution ?

{contextLabel}

: null}
{selection.kind === "todo" && onToggleInspectorSize ? : null}
: null} {selection.item.actionKind === "team.plan" && selection.item.status === "applied" ? :
- {selection.item.reviewPlan?.operationFrame?.kind === "pending" + {!taskExecution ? {selection.item.reviewPlan?.operationFrame?.kind === "pending" ? t(`proposal.kind.${selection.item.actionKind}`) - : `${t(`proposal.kind.${selection.item.actionKind}`)} · ${t(`proposal.status.${selection.item.status}`)}`} + : `${t(`proposal.kind.${selection.item.actionKind}`)} · ${t(`proposal.status.${selection.item.status}`)}`} : null} {decisionFrame ? {t(`proposal.decision.${decisionFrame.decision}`)} : null}

{selection.item.title}

{selection.item.todoId && (selection.item.actionKind === "gate.resolve" || selection.item.actionKind === "todo.update") ?
: null} {selection.item.impact ?

{selection.item.impact}

: null} - {selection.item.reviewPlan && !selection.item.reviewPlan.retryOriginal && selection.item.actionKind !== "team.plan" && !(decisionFrame && ["ready", "applied"].includes(selection.item.status)) ?

{operationUnknown + {selection.item.reviewPlan && !selection.item.reviewPlan.creationExecution && !selection.item.reviewPlan.retryOriginal && !taskExecution && selection.item.actionKind !== "team.plan" && !(decisionFrame && ["ready", "applied"].includes(selection.item.status)) ?

{operationUnknown ? t("actionReview.operation_reconcile_original") : selection.item.reviewPlan.operationFrame?.kind === "inactive" ? t(`actionReview.${selection.item.reviewPlan.operationFrame.reason}`) @@ -1238,8 +1243,9 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention : selection.item.actionKind === "operation.execute" && selection.item.reviewPlan.reason === "readback_unverified" ? t("actionReview.operation_result_delivery_pending") : t(`actionReview.${selection.item.reviewPlan.reason}`)}

: null} - {selection.item.status === "ready" && selection.item.actionKind !== "team.plan" && !decisionFrame ?

{t("drawer.proposalExplainer")}

: null} - {visibleProposalFields.length ?
{visibleProposalFields.map((field) =>
{field.label}
{field.value}
)}
: null} + {selection.item.status === "ready" && !selection.item.reviewPlan?.creationExecution && selection.item.actionKind !== "team.plan" && !decisionFrame ?

{t("drawer.proposalExplainer")}

: null} + {selection.item.reviewPlan?.creationExecution ? : null} + {!taskExecution && visibleProposalFields.length ?
{visibleProposalFields.map((field) =>
{field.label}
{field.value}
)}
: null}
} {selection.item.reviewPlan?.creationProgress?.goalId && selection.item.status !== "applied" ?
{t("proposal.field.goalId")}: {selection.item.reviewPlan.creationProgress.goalId} · {t("proposal.status.applied")} @@ -1247,8 +1253,11 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention {selection.item.reviewPlan.creationProgress.todoIds ? {t("proposal.field.initialTodos")}: {selection.item.reviewPlan.creationProgress.todoIds.length} · {t("proposal.status.applied")} : null}
: null} {selection.item.status === "applied" && decisionFrame ?

{t(`proposal.applied.gate.${decisionFrame.decision}`)}{decisionFrame.dependentEffect ? {t(`proposal.dependentEffect.${decisionFrame.dependentEffect}`)} : null}

- : selection.item.status === "applied" && selection.item.actionKind !== "team.plan" ?

{selection.item.actionKind === "operation.execute" ? selection.item.primaryLabel : t("drawer.proposalApplied")}

: null} - {selection.item.status === "applied" && selection.item.actionKind !== "operation.execute" && selection.item.goalId ? : null} + : selection.item.status === "applied" && selection.item.actionKind !== "team.plan" ?

{selection.item.actionKind === "operation.execute" ? selection.item.primaryLabel : t(taskExecution ? "feedback.taskStartRequested" : "drawer.proposalApplied")}

: null} + {taskExecution ? + : selection.item.createdManagedSession?.invalid ?

{t("proposal.goalSessionUnavailable")}

+ : selection.item.status === "applied" && selection.item.actionKind !== "operation.execute" && selection.item.goalId ? : null} {selection.item.status === "stale" ?

{t("drawer.proposalStale")}

: null} {selection.item.status === "error" && !selection.item.reviewPlan?.retryOriginal ?
{operationUnknown ? t("proposal.operationState.submission_unknown") : selection.item.actionKind === "team.plan" || selection.item.actionKind === "goal.create" || selection.item.reviewPlan?.reason === "readback_unverified" ? t("actionReview.readback_unverified") : t("drawer.proposalApplyFailed")}{selection.item.errorMessage ? {selection.item.errorMessage} : null}{selection.item.actionKind !== "goal.create" ? {t(operationUnknown ? "actionReview.operation_reconcile_original" : selection.item.actionKind === "team.plan" ? "proposal.teamPlan.retryUnavailable" : "drawer.proposalApplyFailedHint")} : null}
: null} {selection.item.status === "rejected" ?

{t("drawer.proposalRejected")}

: null} @@ -1259,7 +1268,7 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention {selection.item.status === "gated" && selection.item.actionKind === "gate.resolve" ?
{t("drawer.gateDecisionRecheckTitle")}{t("drawer.gateDecisionRecheck")}
: selection.item.status === "gated" ?
{selection.item.actionKind === "operation.execute" ? selection.item.primaryLabel : selection.item.workspaceCandidates?.length || selection.item.gate?.kind === "agent_unavailable" ? selection.item.title : t("drawer.gateRequiresHost")}{selection.item.actionKind === "operation.execute" || selection.item.workspaceCandidates?.length || selection.item.gate?.kind === "agent_unavailable" ? selection.item.impact : t("drawer.gateRequiresHostDescription")}{selection.item.gate?.nextAction ? {selection.item.gate.nextAction} : null}
: null} {!readOnly && selection.item.workspaceCandidates?.length ?
{selection.item.workspaceCandidates.map((candidate) => )}
: null} - {!readOnly && selection.item.actionKind !== "operation.execute" && selection.item.status === "error" && (!["team.plan", "goal.create"].includes(selection.item.actionKind) || (selection.item.reviewPlan?.retryOriginal && selection.item.reviewPlan.canApply)) ? : !readOnly && selection.item.actionKind !== "operation.execute" && selection.item.status !== "gated" && !(["team.plan", "goal.create"].includes(selection.item.actionKind) && ["error", "stale"].includes(selection.item.status)) && !((selection.item.actionKind === "team.plan" || decisionFrame) && selection.item.status === "applied") ? : null} + {!readOnly && selection.item.actionKind !== "operation.execute" && selection.item.status === "error" && (!["team.plan", "goal.create"].includes(selection.item.actionKind) || (selection.item.reviewPlan?.retryOriginal && selection.item.reviewPlan.canApply)) ? : !readOnly && selection.item.actionKind !== "operation.execute" && selection.item.status !== "gated" && !(["team.plan", "goal.create"].includes(selection.item.actionKind) && ["error", "stale"].includes(selection.item.status)) && !((selection.item.actionKind === "team.plan" || decisionFrame || taskExecution) && selection.item.status === "applied") ? : null} {!readOnly && selection.item.actionKind !== "operation.execute" && !selection.item.reviewPlan?.creationProgress?.goalId && (["stale", "gated", "rejected"].includes(selection.item.status) || (selection.item.status === "ready" && selection.item.reviewPlan?.canApply === false)) ? : null} {!readOnly && selection.item.persisted !== false && selection.item.actionKind !== "operation.execute" && selection.item.actionKind !== "gate.resolve" && ["ready", "gated"].includes(selection.item.status) ?
: null} {!["applied", "applying"].includes(selection.item.status) ? : null} @@ -1314,7 +1323,7 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention
goal_id: {goalId}kind: {selection.kind} {selection.kind === "run" ? <>session_id: {selection.item.sessionId ?? t("drawer.notLinked")}turn_id: {selection.item.turnId ?? t("common.none")}adapter: {selection.item.agentId}status: {selection.item.sessionStatus ?? selection.item.status} : selection.kind === "proposal" ? <>action: {selection.item.actionKind}status: {selection.item.status} : <>schedule_id: {selection.item.scheduleId}status: {selection.item.status ?? "active"}} - {completionProofFields.map(field => {field.key}: {field.value})} + {(taskExecution ? visibleProposalFields : completionProofFields).map(field => {taskExecution ? field.label : field.key}: {field.value})}
) : null} diff --git a/apps/presentation/dashboard/src/features/personal-workspace/conversation-find.css b/apps/presentation/dashboard/src/features/personal-workspace/conversation-find.css new file mode 100644 index 0000000000..cb69deb561 --- /dev/null +++ b/apps/presentation/dashboard/src/features/personal-workspace/conversation-find.css @@ -0,0 +1,9 @@ +.personal-conversation-find {position:sticky;top:0;z-index:2;background:var(--pw-bg);padding:8px 0;border-bottom:1px solid var(--pw-line);} +.personal-conversation-find button {display:inline-flex;align-items:center;justify-content:center;gap:6px;min-height:36px;padding:6px 8px;border:1px solid var(--pw-line);border-radius:6px;color:var(--pw-text);background:var(--pw-bg);font:inherit;cursor:pointer;} +.personal-conversation-find button:disabled {opacity:.45;cursor:default;} +.personal-conversation-find form {display:flex;align-items:center;flex-wrap:wrap;gap:6px;margin-top:8px;} +.personal-conversation-find input {flex:1;min-width:120px;max-width:420px;padding:8px;border:1px solid var(--pw-line);border-radius:6px;color:var(--pw-text);background:var(--pw-bg);font:inherit;} +.personal-conversation-find [role=status] {font-size:12px;} +.personal-conversation-find small {flex-basis:100%;} +.personal-message.is-find-match {outline:2px solid var(--pw-text);outline-offset:4px;border-radius:6px;scroll-margin-top:140px;} +@media(max-width:640px) {.personal-conversation-find input {flex-basis:100%;max-width:none;}.personal-conversation-find button {min-height:40px;}.personal-message.is-find-match {scroll-margin-top:190px;}} diff --git a/apps/presentation/dashboard/src/features/personal-workspace/conversation-find.tsx b/apps/presentation/dashboard/src/features/personal-workspace/conversation-find.tsx new file mode 100644 index 0000000000..1e3806d819 --- /dev/null +++ b/apps/presentation/dashboard/src/features/personal-workspace/conversation-find.tsx @@ -0,0 +1,60 @@ +import {ArrowDown, ArrowUp, Search, X} from "lucide-react"; +import {useLayoutEffect, useRef, useState} from "react"; +import type {WorkspaceMessage} from "./personal-workspace-model"; +import "./conversation-find.css"; + +export function conversationMessageKey(message: WorkspaceMessage): string { + return JSON.stringify([message.sourceSessionId ?? null, message.sourceMessageId ?? message.id]); +} + +/** Search only the original text already read by the conversation owner. */ +export function ConversationFind({items, incomplete, zh, onSelect, onNavigate}: { + items: WorkspaceMessage[]; + incomplete: boolean; + zh: boolean; + onSelect: (id: string | null) => void; + onNavigate: () => void; +}) { + const [open, setOpen] = useState(false); + const [query, setQuery] = useState(""); + const [selected, setSelected] = useState(null); + const trigger = useRef(null); + const needle = query.trim().toLocaleLowerCase(); + const matches = open && needle ? items.filter(message => message.text.toLocaleLowerCase().includes(needle)) : []; + // Retain the selected original message when an older page or live reply arrives. + const index = Math.max(0, matches.findIndex(item => conversationMessageKey(item) === selected)); + const activeId = matches[index] ? conversationMessageKey(matches[index]) : null; + useLayoutEffect(() => {setSelected(activeId); onSelect(activeId);}, [activeId, selected, onSelect]); + function close() { + setOpen(false); setQuery(""); setSelected(null); onSelect(null); + trigger.current?.focus(); + } + function move(offset: number) { + if (!matches.length) return; + setSelected(conversationMessageKey(matches[(index + offset + matches.length) % matches.length])); + onNavigate(); + } + return
+ + {open ?
{event.preventDefault(); move(1);}} + onKeyDown={event => { + if (event.nativeEvent.isComposing) return; + if (event.key === "Escape") {event.preventDefault(); event.stopPropagation(); close();} + else if (event.key === "Enter" && event.shiftKey) {event.preventDefault(); move(-1);} + }}> + {setQuery(event.target.value); setSelected(null);}}/> + {needle ? matches.length + ? `${index + 1} / ${matches.length}` : (zh ? "没有匹配消息" : "No matching messages") + : (zh ? "仅查找已加载文本" : "Loaded text only")} + + + + {incomplete ? {zh ? "对话记录尚未完整读取,结果仅包含已加载消息。" : "History is incomplete; results include loaded messages only."} : null} +
: null} +
; +} diff --git a/apps/presentation/dashboard/src/features/personal-workspace/conversation-queue.css b/apps/presentation/dashboard/src/features/personal-workspace/conversation-queue.css index 273217988a..3ba5f38670 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/conversation-queue.css +++ b/apps/presentation/dashboard/src/features/personal-workspace/conversation-queue.css @@ -1,7 +1,7 @@ .personal-conversation-queue { min-width: 0; margin: 0 0 8px; font-size: var(--text-caption); color: var(--pw-text); } .personal-conversation-queue header { display: flex; align-items: center; gap: 8px; margin: 0 8px 4px; color: var(--pw-muted); } -.personal-conversation-queue ol { max-height: min(28dvh, 220px); overflow: auto; overscroll-behavior: contain; list-style: none; padding: 0; margin: 0; border: 1px solid var(--pw-line-strong); border-radius: 12px; background: #fff; } -.personal-conversation-queue li + li { border-top: 1px solid var(--pw-line-strong); } +.personal-conversation-queue > ol { max-height: min(28dvh, 220px); overflow: auto; overscroll-behavior: contain; list-style: none; padding: 0; margin: 0; border: 1px solid var(--pw-line-strong); border-radius: 12px; background: #fff; } +.personal-conversation-queue > ol > li + li { border-top: 1px solid var(--pw-line-strong); } .personal-queue-row { display: flex; align-items: start; gap: 8px; padding: 8px 10px; } .personal-queue-row details { min-width: 0; flex: 1; } .personal-queue-row summary { cursor: pointer; } @@ -13,7 +13,8 @@ .personal-conversation-queue button:focus-visible, .personal-queue-row summary:focus-visible { outline: 2px solid var(--pw-blue); outline-offset: 2px; } .personal-queue-steer { flex-shrink: 0; } .personal-queue-message { margin: 8px 0 0; font-size: var(--text-body); line-height: var(--leading-body); } -.personal-queue-message p { white-space: pre-wrap; overflow-wrap: anywhere; } +.personal-queue-message > .personal-md, .personal-workspace-shell[data-pw-theme="loopx"] .personal-queue-message > .personal-md { margin-top: 0; font-size: var(--text-body); line-height: var(--leading-body); } +.personal-queue-message p, .personal-queue-message > .personal-md > p { white-space: pre-wrap; overflow-wrap: anywhere; } .personal-queue-message img { display: block; max-width: 100%; max-height: 120px; object-fit: contain; } .personal-queue-feedback { margin: 0; padding: 0 10px 8px; color: var(--pw-muted); overflow-wrap: anywhere; } .personal-queue-actions { display: flex; flex-direction: column; align-items: flex-end; flex-shrink: 0; } diff --git a/apps/presentation/dashboard/src/features/personal-workspace/conversation-queue.tsx b/apps/presentation/dashboard/src/features/personal-workspace/conversation-queue.tsx index 333ebf0d19..7b3b361878 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/conversation-queue.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/conversation-queue.tsx @@ -5,6 +5,8 @@ import { ChatApiError, chatQueueInputRequestSchema, fetchQueuedChatInput, mutate import { composerKeyAction } from "./composer-keyboard"; import { DocumentAttachment, isTextDocument } from "./document-attachment"; import { ContextHelp } from "./context-help"; +import { ConversationReplyContext } from "./conversation-requests"; +import { MarkdownText } from "./markdown"; import { queueInputKeys, readQueueInputRecovery, retireQueueInputRequest } from "./queue-input-recovery"; import { RetainedQueueInputs } from "./retained-queue-inputs"; import { useWorkspaceI18n } from "./i18n"; @@ -135,7 +137,7 @@ function QueuedMessage({sessionId, turn, index, targetTurnId, onChange, onInputC {open ?
{failed ?

{zh ? "完整消息读取失败" : "Full message unavailable"}

: !message ?

{zh ? "正在读取完整消息…" : "Reading the full message…"}

- : <>

{message.message}

+ : <> {message.attachments?.map(attachment => isTextDocument(attachment.mime_type) ? : {attachment.name}/)}} diff --git a/apps/presentation/dashboard/src/features/personal-workspace/desktop-update.tsx b/apps/presentation/dashboard/src/features/personal-workspace/desktop-update.tsx index 032f35af33..8d602dd4e9 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/desktop-update.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/desktop-update.tsx @@ -170,7 +170,7 @@ export function DesktopUpdate() { : (zh ? "Windows 稳定版与 MSI 安装需手动运行新的签名安装包;App 内自动更新目前只在 main 预览通道提供(NSIS)。" : "Windows stable and MSI installs update by running a newer signed installer; in-App automatic updates currently ship on the main preview channel (NSIS)."); } if (platform === "macos") { - return zh ? "先打开本地版本,更新在后台准备,下次打开时生效。也可在此手动更新。" : "Open the local version first. Updates prepare in the background and apply on the next open. You can also update here."; + return zh ? "启动直接打开本地工作区,更新在后台准备。可在此更新并重启。" : "Open the local workspace immediately. Updates prepare in the background; update and restart here when ready."; } return zh ? "更新会跟随所选通道;请检查更新以确认本机是否有可用安装包。" : "Updates follow the selected channel; check for updates to see whether this machine has an installer."; }; @@ -181,7 +181,7 @@ export function DesktopUpdate() { runtime_required: phaseMessage(zh ? "请完成匹配组件安装,或检查 App 更新。" : "Install matching components or check for an App update.", zh ? "无法准备可用组件。可检查 App 更新;当前安装仍会保留。" : "Components are unavailable. Check for an App update; the current installation is kept."), connecting: zh ? "正在连接本地服务…" : "Connecting to local services…", checking: state.details?.background ? (zh ? "正在后台检查更新,当前版本可继续使用。" : "Checking in the background. Keep using this version.") : (zh ? "正在检查更新…" : "Checking for updates…"), - available: state.details?.prepared ? (zh ? "更新已下载并通过签名校验,下次打开时自动安装。" : "Update downloaded and signature verified. It installs on the next open.") : phaseMessage(zh ? "新版本已就绪,一次更新 App 与匹配的运行时。" : "Update the App and its matching runtime together.", zh ? "有新版本可用,可更新 App。" : "A new version is available; the App can be updated."), + available: state.details?.prepared ? (zh ? "更新已下载并通过签名校验,可更新并重启。" : "Update downloaded and signature verified. Update and restart when ready.") : phaseMessage(zh ? "新版本已就绪,一次更新 App 与匹配的运行时。" : "Update the App and its matching runtime together.", zh ? "有新版本可用,可更新 App。" : "A new version is available; the App can be updated."), up_to_date: zh ? "当前通道暂无更新。" : "No newer update on this channel.", downloading: state.details?.background ? (zh ? "正在后台下载并校验签名,当前版本可继续使用。" : "Downloading and verifying in the background. Keep using this version.") : (zh ? "正在下载并校验签名…" : "Downloading and verifying signature…"), installing_app: zh ? "正在安装 App,请保持窗口打开。" : "Installing the App. Keep this window open.", diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-agent-work-page.tsx b/apps/presentation/dashboard/src/features/personal-workspace/goal-agent-work-page.tsx index 8cdeb7c3fd..8279e95b1f 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/goal-agent-work-page.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-agent-work-page.tsx @@ -7,9 +7,10 @@ import {useWorkspaceI18n} from "./i18n"; import type {WorkspaceGoal} from "./personal-workspace-model"; /** Navigation uses the Goal directory; only the native provider can authorize a conversation. */ -export function GoalAgentWorkPage({goal, agentId, readOnly, sessionId, onSession, children, onSelect, onClose}: { +export function GoalAgentWorkPage({goal, agentId, readOnly, sessionId, onSession, onRetryManagedSession, children, onSelect, onClose}: { goal: WorkspaceGoal; agentId: string; readOnly: boolean; sessionId?: string; onSession: (sessionId: string, replace?: boolean) => void; children?: ReactNode; + onRetryManagedSession?: () => void; onSelect: (agentId: string) => void; onClose: () => void; }) { const zh = useWorkspaceI18n().locale === "zh-CN"; @@ -37,14 +38,15 @@ export function GoalAgentWorkPage({goal, agentId, readOnly, sessionId, onSession
: readOnly ?

{zh ? "此来源仅提供状态快照,无法在这里读取或回复原会话。" : "This source provides a status snapshot; original conversations cannot be read or replied to here."}

: !registered ?

{zh ? "此 Agent 不在当前 Goal 的已注册列表中,请选择列表中的 Agent。" : "This Agent is not registered in the current Goal. Choose an Agent from its directory."}

: {children}} + zh={zh} sessionId={sessionId} onSession={onSession} onRetryManagedSession={onRetryManagedSession}>{children}} ; } /** Both providers stay under the registered Agent; the reader retains its original owner. */ -function AgentSessions({goalId, agentId, hosts, attached, zh, sessionId, onSession, children}: { +function AgentSessions({goalId, agentId, hosts, attached, zh, sessionId, onSession, onRetryManagedSession, children}: { goalId: string; agentId: string; hosts: string[]; attached: boolean; zh: boolean; sessionId?: string; onSession: (sessionId: string, replace?: boolean) => void; children?: ReactNode; + onRetryManagedSession?: () => void; }) { const selectionKey = `loopx-attached-selection:${goalId}:${agentId}`; const [selected, setSelected] = useState(() => { @@ -53,7 +55,10 @@ function AgentSessions({goalId, agentId, hosts, attached, zh, sessionId, onSessi }); const [directory, setDirectory] = useState<{bindings: Binding[]; managed: ChatSessionSummary[]; errors: string[]} | null>(null); const [revision, setRevision] = useState(0); - const reconnect = () => setRevision(value => value + 1); + const reconnect = () => { + setRevision(value => value + 1); + if (sessionId?.startsWith("managed:")) onRetryManagedSession?.(); + }; const previousRoute = useRef(sessionId); const selectedValue = sessionId !== undefined ? sessionId : previousRoute.current !== sessionId ? "" : selected; useEffect(() => { diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-create-request.ts b/apps/presentation/dashboard/src/features/personal-workspace/goal-create-request.ts index 1c9c85e570..bd79a81e0d 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/goal-create-request.ts +++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-create-request.ts @@ -1,5 +1,7 @@ import type { WorkspaceTranslate } from "./i18n"; import type { WorkspaceActionPreviewRequest, WorkspaceAgentOption } from "./personal-workspace-model"; +import type {GoalCreationPermission} from "../../../../../../loopx/control_plane/goals/creation_execution_review.ts"; +export type {GoalCreationPermission} from "../../../../../../loopx/control_plane/goals/creation_execution_review.ts"; import {compactPythonWhitespace, hasPythonNonWhitespaceText} from "../../../../../../loopx/control_plane/coordination/python_whitespace.ts"; type GoalContent = { objective: string; completion: string; boundary: string }; @@ -31,7 +33,8 @@ export function goalCreateContent(input: GoalContent, t: WorkspaceTranslate) { /** One preview builder for explicit forms and conversational drafts. No effects. */ export function goalCreateRequest(input: GoalContent & { - workspaceRef?: string; agentId: string; permission: string; contextGoalId: string | null; operationId?: string; + workspaceRef?: string; agentId: string; permission: GoalCreationPermission; contextGoalId: string | null; operationId?: string; + startExecution?: boolean; }, t: WorkspaceTranslate): WorkspaceActionPreviewRequest { const content = goalCreateContent(input, t); return { @@ -41,6 +44,7 @@ export function goalCreateRequest(input: GoalContent & { normalizedParameters: { ...content, goal_id: `goal-${input.operationId ?? crypto.randomUUID()}`, agent_id: input.agentId, permission: input.permission, + ...(input.startExecution === true ? {start_execution: true} : {}), workspace_ref: input.workspaceRef ?? "current", heartbeat: { enabled: false, cadence: "1d", timezone: "Asia/Shanghai" }, stop_condition: "goal_complete", }, diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-created-session.ts b/apps/presentation/dashboard/src/features/personal-workspace/goal-created-session.ts new file mode 100644 index 0000000000..cc42d1428c --- /dev/null +++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-created-session.ts @@ -0,0 +1,20 @@ +import type {ManagedConversationTarget, TypedActionProposal} from "../../data/chat"; + +/** Display address only. The existing managed Session reader verifies it again. */ +export function goalCreatedManagedSession(proposal: TypedActionProposal): {target?: ManagedConversationTarget; invalid?: true} | undefined { + if (proposal.action_kind !== "goal.create" || proposal.status !== "applied") return undefined; + const ids = proposal.receipt?.resource_ids; + if (!ids || typeof ids !== "object" || Array.isArray(ids) || !Object.hasOwn(ids, "managed_agent_id")) return undefined; + const resources = ids as Record; + const goalId = resources.goal_id, agentId = resources.managed_agent_id, sessionId = resources.session_id; + if (proposal.receipt?.outcome !== "goal_created" || proposal.receipt.projection_verified !== true || resources.agent_id !== "codex" + || typeof goalId !== "string" || !/^[A-Za-z0-9._-]{1,160}$/.test(goalId) + || goalId !== proposal.normalized_parameters.goal_id + || typeof agentId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,119}$/.test(agentId) + || agentId !== proposal.normalized_parameters.agent_id + || typeof sessionId !== "string" || !/^[A-Za-z0-9._-]{1,160}$/.test(sessionId) + || resources.channel_id !== `agent.${agentId}` + || !Object.hasOwn(resources, "goal_instance_id") || !(resources.goal_instance_id === null + || typeof resources.goal_instance_id === "string" && resources.goal_instance_id.length > 0)) return {invalid: true}; + return {target: {goalId, agentId, sessionId}}; +} diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-creation-execution.tsx b/apps/presentation/dashboard/src/features/personal-workspace/goal-creation-execution.tsx new file mode 100644 index 0000000000..a1e09931d7 --- /dev/null +++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-creation-execution.tsx @@ -0,0 +1,14 @@ +import type {GoalCreationExecutionReview} from "../../../../../../loopx/control_plane/goals/creation_execution_review.ts"; +import {useWorkspaceI18n} from "./i18n"; + +/** Display the canonical creation approval; UI prose never grants authority. */ +export function GoalCreationExecution({execution}: {execution: GoalCreationExecutionReview}) { + const {t} = useWorkspaceI18n(); + return
+
{t("proposal.field.permission")}
{t(execution.permission === "read_only" + ? "proposal.execution.readOnly" : "proposal.execution.workspaceWrite")}
+
{t("proposal.execution.writeScope")}
{execution.writeScope.length === 0 + ? t("proposal.execution.noWrites") : execution.writeScope.map(scope => scope === "**" + ? t("proposal.execution.allWorkspaceFiles") : scope).join(" · ")}
+
; +} diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-draft-card.tsx b/apps/presentation/dashboard/src/features/personal-workspace/goal-draft-card.tsx index 692be830c2..79ea647030 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/goal-draft-card.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-draft-card.tsx @@ -1,21 +1,60 @@ -import { useRef, useState } from "react"; +import { useEffect, useEffectEvent, useRef, useState } from "react"; import type { GoalDraft } from "../../../../../../loopx/control_plane/collaboration/goal_draft.js"; +import type { WorkspaceActionPreview } from "./personal-workspace-model"; import {goalDraftReady} from "./goal-create-request"; +import {GoalCreationExecution} from "./goal-creation-execution"; import { useWorkspaceI18n } from "./i18n"; import "./goal-draft-card.css"; -export function GoalDraftCard({ draft, draftId, onReview, onSuggest }: { +export function GoalDraftCard({ draft, draftId, preparationContext = "", onReview, onApply, onSuggest }: { draft: GoalDraft; draftId: string; - onReview?: (draft: GoalDraft, edit?: boolean, draftId?: string) => Promise; + preparationContext?: string; + onReview?: (draft: GoalDraft, edit?: boolean, draftId?: string) => Promise; + onApply?: (proposal: WorkspaceActionPreview) => Promise; onSuggest?: (text: string) => void; }) { - const { locale } = useWorkspaceI18n(); + const { locale, t } = useWorkspaceI18n(); const zh = locale === "zh-CN"; const pending = useRef(false); + const card = useRef(null); + const [visible, setVisible] = useState(false); const [busy, setBusy] = useState(false); const [error, setError] = useState(""); + const [prepared, setPrepared] = useState<{ key: string; proposal: WorkspaceActionPreview }>(); + const [preparing, setPreparing] = useState(false); + const [preparationAttempt, setPreparationAttempt] = useState(0); const ready = goalDraftReady(draft); + const draftKey = JSON.stringify([draftId, draft, preparationContext]); + const proposal = prepared?.key === draftKey ? prepared.proposal : undefined; + const prepare = useEffectEvent(async () => onReview?.(draft, false, draftId)); + const preparesCreation = ready && visible && Boolean(onReview && onApply); + useEffect(() => { + if (visible || !card.current) return; + const observer = new IntersectionObserver(([entry]) => { + if (!entry?.isIntersecting) return; + observer.disconnect(); + setVisible(true); + }, {root: card.current.closest(".personal-channel-scroll")}); + observer.observe(card.current); + return () => observer.disconnect(); + }, [visible]); + useEffect(() => { + let current = true; + setPrepared(undefined); + setError(""); + if (!preparesCreation) { setPreparing(false); return; } + setPreparing(true); + void prepare().then(result => { + if (!current) return; + if (result?.actionKind === "goal.create") setPrepared({ key: draftKey, proposal: result }); + else setError(zh ? "无法准备创建,请重试。" : "Could not prepare creation. Please retry."); + }).catch(failure => { + if (current) setError(failure instanceof Error ? failure.message : String(failure)); + }).finally(() => { if (current) setPreparing(false); }); + return () => { current = false; }; + }, [draftKey, preparesCreation, preparationAttempt]); + const created = proposal?.status === "applied" && proposal.reviewPlan?.interaction === "completed"; async function review(edit = false) { if (!onReview || pending.current) return; pending.current = true; @@ -25,23 +64,47 @@ export function GoalDraftCard({ draft, draftId, onReview, onSuggest }: { catch (failure) { setError(failure instanceof Error ? failure.message : String(failure)); } finally { pending.current = false; setBusy(false); } } - return
+ async function create() { + if (!onApply || pending.current) return; + if (!proposal) { setPreparationAttempt(attempt => attempt + 1); return; } + pending.current = true; + setBusy(true); + setError(""); + try { + const result = await onApply(proposal); + setPrepared(current => current?.key === draftKey ? { key: draftKey, proposal: result } : current); + } + catch (failure) { setError(failure instanceof Error ? failure.message : String(failure)); } + finally { pending.current = false; setBusy(false); } + } + return
{zh ? "目标草稿" : "Goal draft"}
{[ [zh ? "目标" : "Objective", draft.objective], [zh ? "完成标准" : "Completion criteria", draft.completion_criteria], [zh ? "执行边界" : "Execution boundary", draft.execution_boundary], ].map(([label, value]) =>
{label}
{value || (zh ? "待补充" : "Not specified")}
)}
+ {proposal ?
{proposal.fields.filter(field => field.key === "agent_id" || field.key === "workspace_ref") + .map(field =>
{field.label}
{field.value}
)}
: null} + {proposal?.reviewPlan?.creationExecution ? : null} {draft.question ?

{draft.question}

: null} {onSuggest && draft.options.length ?
{draft.options.map(option => )} {zh ? "点选后可修改再发送,也可以直接输入。" : "Choose a reply to edit before sending, or type your own."}
: null} {error ?

{error}

: null} -
{zh ? "尚未创建或启动" : "Not created or started"} + {proposal?.gate ?

{proposal.gate.summary}

: null} + {proposal?.errorMessage ?

{proposal.reviewPlan + ? t(`actionReview.${proposal.reviewPlan.reason}`) : proposal.errorMessage}

: null} +
{onReview ? <> - {ready ? : null} - + {ready && !created ? : null} + {preparesCreation ? : } : null}
; diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-loopx-mode.tsx b/apps/presentation/dashboard/src/features/personal-workspace/goal-loopx-mode.tsx index 9d5a11924f..37a2787989 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/goal-loopx-mode.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-loopx-mode.tsx @@ -1,17 +1,199 @@ import {ContextHelp} from "./context-help"; import {useEffect, useRef, useState} from "react"; import {Pause, Play, Settings2, Users, X} from "lucide-react"; -import {fetchLoopXMode, updateLoopXMode, type LoopXModeSnapshot, type LoopXModeSettings} from "../../data/chat"; +import {fetchLoopXMode, updateLoopXMode, fetchManagedTaskEntry, startManagedTaskTurn, + type ManagedConversationTarget, type ManagedTaskEntry, type ManagedTaskTurn, type LoopXModeSnapshot, type LoopXModeSettings} from "../../data/chat"; import {useWorkspaceI18n} from "./i18n"; import {GoalTeamWork} from "./goal-team-work"; import "./goal-loopx-mode.css"; -export function GoalLoopXMode({sessionId, onPrepare, onExecute, onChange}: { +type GoalLoopXModeProps = { sessionId?: string; onPrepare: () => Promise; onExecute: (operation: "start" | "resume", settings?: LoopXModeSettings) => void; onChange: (snapshot: LoopXModeSnapshot | null) => void; -}) { + managed?: {target: ManagedConversationTarget; onObserve: () => Promise}; +}; + +/** The existing primary control has distinct native and coordinator owners. */ +export function GoalLoopXMode(props: GoalLoopXModeProps) { + return props.managed ? + : ; +} + +type TaskAttempt = {operationId: string; todoId: string; turnId?: string; status?: string}; +const terminalTaskTurn = (status?: string) => ["completed", "failed", "interrupted", "timed_out"].includes(status ?? ""); +function readTaskAttempt(key: string): TaskAttempt | null { + const stored = sessionStorage.getItem(key); + if (stored === null) return null; + const value: unknown = JSON.parse(stored); + if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Unreadable original Task request"); + const attempt = value as Record; + if (Object.keys(attempt).some(field => !["operationId", "todoId", "turnId", "status"].includes(field)) + || typeof attempt.operationId !== "string" || !/^[A-Za-z0-9._:-]{1,100}$/.test(attempt.operationId) + || typeof attempt.todoId !== "string" || !attempt.todoId + || attempt.turnId !== undefined && (typeof attempt.turnId !== "string" || !attempt.turnId) + || attempt.status !== undefined && (typeof attempt.status !== "string" || !attempt.status)) throw new Error("Unreadable original Task request"); + return attempt as TaskAttempt; +} +function observedTaskTurn(read: ManagedTaskEntry | null, attempt: TaskAttempt | null): ManagedTaskTurn | null { + if (!read) return null; + const creation = read.task.creation_request; + return read.turn ?? (creation && creation.operation_id === attempt?.operationId ? read.task.creation_turn ?? null : null); +} + +function ManagedTaskMode({target, onObserve}: NonNullable) { + const zh = useWorkspaceI18n().locale === "zh-CN"; + const storageKey = `loopx-managed-task:${JSON.stringify([target.goalId, target.agentId, target.sessionId])}`; + const [retained, setRetained] = useState<{attempt: TaskAttempt | null; unreadable: boolean}>(() => { + try {return {attempt: readTaskAttempt(storageKey), unreadable: false};} catch {return {attempt: null, unreadable: true};} + }); + const attempt = retained.attempt; + const attemptRef = useRef(attempt); attemptRef.current = attempt; + const [read, setRead] = useState(null); + const [busy, setBusy] = useState(false), [error, setError] = useState(""); + const flight = useRef(false), live = useRef(true), revision = useRef(0); + const observe = useRef(onObserve); observe.current = onObserve; + const seenTurn = useRef(""); + const shown = useRef(retained.unreadable || Boolean(attempt)); + const [refresh, setRefresh] = useState(0); + function retain(next: TaskAttempt) { + sessionStorage.setItem(storageKey, JSON.stringify(next)); + if (sessionStorage.getItem(storageKey) !== JSON.stringify(next)) throw new Error("Original request could not be retained"); + attemptRef.current = next; setRetained({attempt: next, unreadable: false}); + } + async function accept(turn: ManagedTaskTurn) { + if (!live.current) return; + const current = attemptRef.current!; + retain({...current, turnId: turn.turn_id, status: turn.status}); + const signature = JSON.stringify([turn.turn_id, turn.status]); + if (seenTurn.current !== signature) { + // The existing history/recovery owner adopts this exact Session and stream. + await observe.current(); + seenTurn.current = signature; + } + } + useEffect(() => { + live.current = true; + const controller = new AbortController(); + let reading = false, needsReadback = false, timer: number | undefined; + function scheduleReadback() { + window.clearTimeout(timer); + if (needsReadback && !document.hidden && !controller.signal.aborted) { + timer = window.setTimeout(() => void load(), 5000); + } + } + async function load() { + if (reading || flight.current) return; + reading = true; + const generation = ++revision.current; + let storageRead = false; + try { + const current = readTaskAttempt(storageKey); + storageRead = true; + needsReadback = Boolean(current); + attemptRef.current = current; + setRetained({attempt: current, unreadable: false}); + const result = await fetchManagedTaskEntry(target, {operationId: current?.operationId, todoId: current?.todoId, + signal: AbortSignal.any([controller.signal, AbortSignal.timeout(8000)])}); + if (controller.signal.aborted || generation !== revision.current) return; + const creation = result.task.creation_request; + const original = current ?? (creation ? {operationId: creation.operation_id, todoId: creation.todo_id} : null); + if (!current && original) retain(original); + const turn = observedTaskTurn(result, original); + if (original?.turnId && turn?.turn_id !== original.turnId) throw new Error("The original Task Turn is unavailable"); + needsReadback = Boolean(original && (!turn || !terminalTaskTurn(turn.status))); + setRead(result); setError(""); + if (turn) await accept(turn); + } catch { + if (!controller.signal.aborted && generation === revision.current) { + if (!storageRead) {needsReadback = false; setRetained(previous => ({...previous, unreadable: true}));} + setRead(null); setError(zh ? "当前任务或原请求暂时无法读取。重新读取不会启动任务。" : "The Task or original request could not be read. Refreshing does not launch it."); + } + } finally {reading = false; scheduleReadback();} + } + void load(); + const visibility = () => {if (document.hidden) window.clearTimeout(timer); else if (needsReadback) void load();}; + document.addEventListener("visibilitychange", visibility); + return () => {live.current = false; revision.current++; controller.abort(); window.clearTimeout(timer); document.removeEventListener("visibilitychange", visibility);}; + }, [storageKey, refresh]); + + const ready = read?.available === true && read.task.state === "ready" && read.task.canonical_done === false + && read.task.observation.check_count > 0 && !retained.unreadable; + const creation = read?.task.creation_request; + const originalCreation = creation && creation.operation_id === attempt?.operationId ? creation : undefined; + const turn = observedTaskTurn(read, attempt); + const creationPending = Boolean(originalCreation && !turn); + const waiting = creationPending || Boolean(turn && !terminalTaskTurn(turn.status)); + const running = turn?.status === "running"; + async function start() { + if (flight.current || !ready || waiting || retained.unreadable) return; + flight.current = true; revision.current++; setBusy(true); setError(""); + try { + let prior: TaskAttempt | null; + try {prior = readTaskAttempt(storageKey);} catch { + setRetained(previous => ({...previous, unreadable: true})); + throw new Error("The original Task request is unreadable"); + } + attemptRef.current = prior; + const current = await fetchManagedTaskEntry(target, {operationId: prior?.operationId, + todoId: prior?.todoId, signal: AbortSignal.timeout(8000)}); + if (!live.current) return; + setRead(current); + const creation = current.task.creation_request; + if (!prior && creation) { + retain({operationId: creation.operation_id, todoId: creation.todo_id}); + if (current.task.creation_turn) await accept(current.task.creation_turn); + return; + } + const turn = observedTaskTurn(current, prior); + if (prior?.turnId && turn?.turn_id !== prior.turnId) throw new Error("The original Task Turn is unavailable"); + if (creation && creation.operation_id === prior?.operationId && !turn) return; + if (turn && !terminalTaskTurn(turn.status)) {await accept(turn); return;} + if (!current.available || current.task.state !== "ready" || current.task.canonical_done || current.task.observation.check_count < 1 + || prior && current.task.todo_id !== prior.todoId) throw new Error("Original Task source changed"); + const next = prior && !turn ? prior : {operationId: `task.${crypto.randomUUID()}`, todoId: current.task.todo_id}; + retain(next); + const accepted = await startManagedTaskTurn(target, next.todoId, next.operationId, AbortSignal.timeout(15000)); + if (live.current) await accept(accepted.turn); + } catch { + if (live.current) {setRead(null); setError(zh ? "执行结果尚未确认。先读取原请求,不会自动重发。" : "Launch is unconfirmed. Read the original request first; it will not be resent automatically.");} + } finally { + flight.current = false; + if (live.current) {setBusy(false); setRefresh(value => value + 1);} + } + } + const confirmed = read?.task.state === "ready" && read.task.observation.check_count > 0; + if (confirmed || retained.unreadable || attempt || read?.task.creation_request || error) shown.current = true; + if (!shown.current) return null; + return
+
+ + {running ? (zh ? "正在推进当前任务" : "Working on the current Task") + : creationPending && read?.task.state === "unbound" ? (zh ? "已提交,等待检查就绪" : "Submitted; waiting for checks") + : waiting ? (zh ? "已提交,等待执行" : "Submitted; waiting to run") : read?.task.state === "ready" && read.task.canonical_done + ? (zh ? "当前任务已完成" : "Current Task completed") : (zh ? "当前任务" : "Current Task")} + +
+ +

{zh ? "在原会话推进当前任务,使用已确认的检查和现有额度。" : "Advance the current Task in its original conversation using its confirmed checks and existing allowance."}

+ {read?.task.state === "ready" ?

{zh ? `${read.task.observation.check_count} 项检查 · ${read.task.observation.pinned_file_count} 个固定来源文件` : `${read.task.observation.check_count} checks · ${read.task.observation.pinned_file_count} pinned source files`}

: null} +
+ +
+
+ {error ?

{error}

: null} + {read && !ready && (!waiting || creationPending && read.task.state === "ready") && !read.task.canonical_done + ?

{read.task.reason || read.reason || (zh ? "当前任务暂不能执行,请读取检查或原会话状态。" : "The Task cannot run yet. Read its checks or original conversation state.")}

: null} +
; +} + +function CoordinatorMode({sessionId, onPrepare, onExecute, onChange}: GoalLoopXModeProps) { const {locale} = useWorkspaceI18n(); const zh = locale === "zh-CN"; const [snapshot, setSnapshot] = useState(null); diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-outcome-requirements.tsx b/apps/presentation/dashboard/src/features/personal-workspace/goal-outcome-requirements.tsx index c01c13f911..3b9513d47c 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/goal-outcome-requirements.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-outcome-requirements.tsx @@ -75,7 +75,7 @@ function Outcome({goalId, outcome, fresh, canManage, revision, onRefresh, zh, sh if (busy || !fresh || !canManage || !revision || !text.trim()) return; const identity = crypto.randomUUID(); const request = pending ?? {action: "refine", expected_provider_revision: revision, operation_id: `outcome-ui:${identity}`, - refinement: {outcome_id: outcome.id, + refinement: {outcome_id: outcome.id, storage_format: "records", requirements: [{id: `requirement-${identity}`, description: text.trim()}], source: {ref: `owner:${identity}`, summary: text.trim()}}}; setPending(request); setBusy(true); setNotice(""); diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-report-reviews.tsx b/apps/presentation/dashboard/src/features/personal-workspace/goal-report-reviews.tsx index d98d0b0fad..73801ec851 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/goal-report-reviews.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-report-reviews.tsx @@ -72,10 +72,12 @@ export function GoalReportReviews({goalId, sourceId, zh, focusTodoId, refreshKey const [error, setError] = useState(""); const [textOnly, setTextOnly] = useState(false); const generation = useRef(0); + const completedRead = useRef(0); const navigation = useRef(""); const selectedId = useRef(focusTodoId ?? null); const focus = useResultCatalogFocus(); const storageKey = JSON.stringify(["loopx-report-reading", sourceId ?? location.origin, goalId]); + const pendingFocus = useRef<{scope: string; row?: string} | null>(null); function rememberSelection(todoId?: string) { selectedId.current = todoId ?? null; try { @@ -92,10 +94,23 @@ export function GoalReportReviews({goalId, sourceId, zh, focusTodoId, refreshKey try {saved = sessionStorage.getItem(storageKey);} catch { /* Reading works without storage. */ } selectedId.current = focusTodoId ?? saved; setReading(selectedId.current); setRows([]); setLoaded(false); setTextOnly(false); + if (selectedId.current) pendingFocus.current = {scope: storageKey}; } void load(); - return () => {generation.current++; focus.cancel();}; + return () => {generation.current++;}; }, [goalId, sourceId, focusTodoId, refreshKey]); + useEffect(() => {focus.cancel();}, [storageKey]); + useEffect(() => { + const target = pendingFocus.current; + // Navigation can start a newer read before this render receives its busy state. + // Consume focus only after that read has committed its readable or error view. + if (!target || busy || (!loaded && !error) || completedRead.current !== generation.current) return; + if (target.scope !== storageKey) {pendingFocus.current = null; return;} + if (target.row ? reading !== null : reading === null) return; + pendingFocus.current = null; + if (target.row) focus.row(target.row); + else focus.reader(); + }, [busy, loaded, error, reading, rows, storageKey]); async function read(todoId: string, current: number) { const value = await readReportReview(goalId, todoId); @@ -121,16 +136,17 @@ export function GoalReportReviews({goalId, sourceId, zh, focusTodoId, refreshKey if (selectedId.current) await read(selectedId.current, current); } catch { if (current === generation.current) setError(zh ? "材料或审阅状态暂不可读,请重试。" : "Material or review state is unavailable. Retry the read."); - } finally {if (current === generation.current) setBusy(false);} + } finally {if (current === generation.current) {completedRead.current = current; setBusy(false);}} } async function select(row: ReportReviewRow) { const current = ++generation.current; setReading(row.todo_id); setSelected(null); setTextOnly(false); rememberSelection(row.todo_id); - setBusy(true); setError(""); focus.reader(); + pendingFocus.current = {scope: storageKey}; + setBusy(true); setError(""); try {await read(row.todo_id, current);} catch {if (current === generation.current) setError(zh ? "原版本已不可读取,请重试。" : "The original edition cannot be read. Retry.");} - finally {if (current === generation.current) setBusy(false);} + finally {if (current === generation.current) {completedRead.current = current; setBusy(false);}} } const label = (row: ReportReviewRow) => row.superseded_by ? (zh ? "已有修订" : "Superseded") : row.status === "done" ? (zh ? "审阅已处理" : "Review handled") @@ -140,9 +156,10 @@ export function GoalReportReviews({goalId, sourceId, zh, focusTodoId, refreshKey const html = selected?.artifacts.find(item => item.renderer_id === "html_artifact_v0"); const htmlView = useMemo(() => html ? inertReportHtml(html.content, zh) : "", [html?.content, zh]); function returnToCatalog() { + pendingFocus.current = {scope: storageKey, row: reading ?? undefined}; generation.current++; setReading(null); setSelected(null); setBusy(false); setError(""); + completedRead.current = generation.current; rememberSelection(); - if (reading) focus.row(reading); } const attention: WorkspaceAttention | null = selected ? {goalId, sourceId, todoId: selected.review.todo_id, text: selected.review.title, blocking: false, decisionSource: "todo", details: {...attentionDetails(selected.todo), @@ -152,7 +169,10 @@ export function GoalReportReviews({goalId, sourceId, zh, focusTodoId, refreshKey
{reading ? :

{zh ? "审阅材料" : "Review materials"}

}

{zh ? "阅读不会完成验收。每份材料的审阅分别记录;处理材料不等于整个 Goal 验收通过。反馈回到负责 Agent 的原工作对话。页面版保留静态目录;外部来源可从文字版打开。" : "Reading does not accept a result. Each edition has its own review; handling it does not accept the entire Goal. Feedback returns to its responsible Agent's work conversation. Page view keeps the static index; open external sources from text view."}

-
+
{busy ?

{zh ? "正在读取材料…" : "Reading material…"}

: null} {error ?

{error}

: null}
: null; } -export function ResearchCaseReading({analysis: a, active, onHistory}: {analysis: Controller; active: boolean; onHistory: () => void}) { +export function ResearchCaseReading({analysis: a, active}: {analysis: Controller; active: boolean}) { const packs = (a.snapshot?.catalog.packs ?? []).filter(p => p.case_study_summary); const p = a.pack; const firstStudy = packs[0]?.pack_id; @@ -427,12 +427,12 @@ export function ResearchCaseReading({analysis: a, active, onHistory}: {analysis: if (!a.loading && !a.readError && p && !p.case_study && firstStudy && !(hash.startsWith(caseChapterHashPrefix) && hash.includes("~"))) a.select(firstStudy); }, [a.loading, a.readError, p?.pack_id, Boolean(p?.case_study), firstStudy]); - return
-
{(packs.length > 1 || (packs.length === 1 && !p?.case_study)) ?
: null} {p?.case_study ? span { display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; } .research-decision-ticks { position: relative; height: 12px; margin-top: 4px; } -.research-decision-ticks span { position: absolute; top: 0; width: 3px; height: 10px; margin-left: -1px; border-radius: 1px; background: var(--pw-blue); } -.research-decision-ticks span.is-replan, .research-tick-key.is-replan { background: var(--pw-orbit); } -.research-tick-key { display: inline-block; width: 3px; height: 10px; border-radius: 1px; background: var(--pw-blue); } +.research-decision-ticks span, .research-tick-key { display: inline-block; width: 3px; height: 10px; border-radius: 1px; background: var(--pw-blue); } +.research-decision-ticks span { position: absolute; top: 50%; transform: translate(-50%, -50%); } +.research-decision-ticks .is-replan, .research-tick-key.is-replan { width: 7px; height: 7px; rotate: 45deg; background: var(--pw-text); } .research-phase-divider { position: absolute; top: -4px; height: 76px; border-left: 1px dashed var(--pw-faint); pointer-events: none; } .research-axis { position: relative; height: 22px; margin-top: 2px; border-top: 1px solid var(--pw-line); } .research-axis time { position: absolute; top: 5px; transform: translateX(-50%); color: var(--pw-muted); font-size: var(--text-caption); white-space: nowrap; } @@ -240,7 +242,7 @@ .research-trail-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 12px; color: var(--pw-muted); font-size: var(--text-caption); } .research-trail-question > .research-link { margin: 8px 0 0 36px; min-height: 44px; } .research-outcome { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: var(--text-caption); font-weight: 600; background: var(--pw-blue-soft); color: var(--pw-blue-ink); } -.research-outcome.is-replan { background: var(--pw-tone); color: var(--pw-orbit); } +.research-outcome.is-replan { background: var(--pw-hover); color: var(--pw-text); } .research-outcome.is-stop, .research-outcome.is-ask_human { background: var(--pw-amber-bg); color: var(--pw-text); } .research-link { padding: 0; border: 0; background: none; color: var(--pw-blue-ink); font: inherit; text-decoration: underline; cursor: pointer; } .research-trail > .research-link { margin-top: 8px; font-size: var(--text-caption); } diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-research-history.tsx b/apps/presentation/dashboard/src/features/personal-workspace/goal-research-history.tsx index 23e08d9665..3b2ff20e73 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/goal-research-history.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-research-history.tsx @@ -62,11 +62,19 @@ export function GoalResearchHistory({goalId, originalGoalId = goalId, preferHist const readCaseMode = () => { const query = new URLSearchParams(window.location.search); const reading = query.get("research_goal") === goalId ? query.get("research_reading") : null; - return {goalId, requested: reading === null ? null : reading === "case"}; + return {goalId, requested: reading === "case" ? true : reading === "history" ? false : null}; }; const [caseMode, setCaseReading] = useState(readCaseMode); const requestedCase = caseMode.goalId === goalId ? caseMode.requested : null; const caseReading = requestedCase ?? !preferHistory; + const hasCases = (analysis.snapshot?.catalog.packs ?? []).some(pack => pack.case_study_summary); + // Preserve the saved reading during catalogue loading or failure. A + // successful catalogue without a study falls back to the original history. + const awaitingRequestedCase = requestedCase === true && (analysis.loading || Boolean(analysis.readError)); + const deferHistory = requestedCase === true && (hasCases || awaitingRequestedCase); + const historySource = JSON.stringify([goalId, originalGoalId, readSourceUrl]); + const [openedHistorySource, setOpenedHistorySource] = useState(null); + const readHistory = active && (!deferHistory || openedHistorySource === historySource); useEffect(() => { const changed = () => setCaseReading(readCaseMode()); changed(); window.addEventListener("popstate", changed); @@ -76,7 +84,8 @@ export function GoalResearchHistory({goalId, originalGoalId = goalId, preferHist const url = new URL(window.location.href); url.searchParams.set("research_goal", goalId); url.searchParams.set("research_reading", reading ? "case" : "history"); - window.history.pushState({}, "", url); setCaseReading({goalId, requested: reading}); + window.history.pushState(window.history.state, "", url); + setCaseReading({goalId, requested: reading}); }; const [read, setRead] = useState({events: [], total: null, complete: false}); const [originalDisplay, setOriginalDisplay] = useState(false); @@ -199,7 +208,10 @@ export function GoalResearchHistory({goalId, originalGoalId = goalId, preferHist const updateRecords = (events: readonly ExploreHistoryEvent[]) =>
    {events.map(event =>
  1. {stateLabel(event.status)} · {event.title}

    {event.summary ? findingBody(event) : null}
    {event.parent_id ? {copy.group}: {event.parent_id} : null}{event.evidence_refs.map(ref => {ref})}{event.run_id ? {event.run_id} : null}
  2. )}
; useEffect(() => { - if (!active) return; + if (!readHistory) return; + // Once history has opened, switching back to the saved case should not + // cancel a page in flight or start the same history scan again. + setOpenedHistorySource(historySource); let current = true; const controller = new AbortController(); setBusy(true); setError(""); setLoaded(0); @@ -244,7 +256,7 @@ export function GoalResearchHistory({goalId, originalGoalId = goalId, preferHist } finally {if (current) setBusy(false);} })(); return () => {current = false; controller.abort();}; - }, [goalId, originalGoalId, active, revision, refreshRevision, readSourceUrl]); + }, [goalId, originalGoalId, readHistory, historySource, revision, refreshRevision, readSourceUrl]); const history = useMemo(() => { try { const canonical = projectExploreHistory(read.events, originalGoalId); @@ -506,7 +518,7 @@ export function GoalResearchHistory({goalId, originalGoalId = goalId, preferHist const recordUnit = read.complete && history.canonical && read.events.length > history.canonical.events.length ? (zh ? "条原始记录" : "source rows") : read.total === 1 ? copy.record : copy.records; const emptySourceHistory = hasNativeSource && emptyHistory; - const hasSavedResult = Boolean(analysis.pack?.result || analysis.pack?.native_outcomes); + const hasSavedResult = Boolean(analysis.pack?.result || analysis.pack?.native_outcomes || analysis.pack?.human_attention); const emptyWithAnalysis = emptyHistory && hasSavedResult; const historyBeforeAnalysisSummary = hasNativeSource && Boolean(value?.nodes.length) && !hasSavedResult; // Reorder the existing reader in the DOM so visual and keyboard order agree. @@ -517,20 +529,22 @@ export function GoalResearchHistory({goalId, originalGoalId = goalId, preferHist : null; const emptyHistoryMessage = zh ? "这个 Goal 尚无研究历程" : "No research history for this Goal yet"; - const hasCases = (analysis.snapshot?.catalog.packs ?? []).some(p => p.case_study_summary); - // Keep an explicitly opened study in place during a read failure. A complete - // catalogue with no study still uses the ordinary history view. - const awaitingRequestedCase = requestedCase === true && (analysis.loading || Boolean(analysis.readError)); - if (hasNativeSource && strategies.selection !== null && !emptySourceHistory) { - return strategies.choose(null)}/>; - } - if (caseReading && (hasCases || awaitingRequestedCase)) { - return setCaseMode(false)}/>; - } - return
- {hasCases ? : null} + const selectedStrategy = hasNativeSource && !emptySourceHistory ? strategies.selection : null; + const readingCase = caseReading && (hasCases || awaitingRequestedCase) && (requestedCase === true || selectedStrategy === null); + const alternateReading = readingCase ? + : selectedStrategy !== null ? strategies.choose(null)}/> : null; + return <> + {hasCases || awaitingRequestedCase ?
+ + +
: null} + {alternateReading ??
{progressiveOverview ? <>
: null} - ; + } + ; } diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-research-progress.tsx b/apps/presentation/dashboard/src/features/personal-workspace/goal-research-progress.tsx index 038e0849d8..fb7ba838eb 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/goal-research-progress.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-research-progress.tsx @@ -7,12 +7,14 @@ import {ContextHelp} from "./context-help"; import {ResearchSynthesis} from "./goal-research-synthesis"; import {ResearchTurnCosts} from "./research-turn-costs"; import {ToolContextInventory} from "./goal-tool-context"; +import {ResearchHumanAttention, type ResearchHumanAttentionCapture} from './research-human-attention'; import {LoopXRequestFootprint, ResearchUsageComparison, type ReadUsageComparison} from "./research-usage-comparison"; import "./goal-research-progress.css"; // Read models from benchmark-toolkit. This view formats existing counts and // assessments; it never scores, reclassifies an episode or combines runs. export type ResearchProgressPack = {pack_id: string; title: string; scope: TrajectoryInput["scope"]; selection: TrajectoryInput["selection"]; + human_attention?: ResearchHumanAttentionCapture; episode_count: number; episodes?: TrajectoryEpisode[]; result?: TrajectoryAssessment | null; applicability?: "current" | "historical"; job?: {status: string; attempt?: number; analysis_wall_seconds?: number | null; usage?: {input_tokens?: number; output_tokens?: number} | null; config?: {model: string; effort: string; service_tier: string}} | null; @@ -305,6 +307,7 @@ export function ResearchProgress({pack: p, packs, selectedId, zh, onSelect, onCi {p ? <> {p.native_outcomes ? : null} {p.native_outcomes ? : null} + {p.human_attention ? : null} {result?.synthesis ? !analysisOpen && <>{includeReport && }
{zh ? "六项过程判读" : "Six process judgments"}
: result ? @@ -392,6 +395,7 @@ export function ResearchProgress({pack: p, packs, selectedId, zh, onSelect, onCi : null} + {!p.human_attention ? : null}
{zh ? "分析范围与来源" : "Analysis scope and sources"}
{zh ? "题目 / 运行" : "Case / run"}
{p.scope.case_id}
{p.scope.run_id}
{zh ? "证据窗口" : "Evidence window"}
{p.scope.window}
{zh ? "取样规则" : "Selection rule"}
{p.selection.rule}
diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-research-timeline.tsx b/apps/presentation/dashboard/src/features/personal-workspace/goal-research-timeline.tsx index 5dbf027af0..83bd36850b 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/goal-research-timeline.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-research-timeline.tsx @@ -105,7 +105,13 @@ export function GoalResearchTimeline({timeline, complete, zh, selectedIds, selec style={{left: pct(group.at)}} onClick={event => onSelectMany(ids, event.currentTarget)}>{ids.length}; }); const trail = groupExploreTimelineDecisions(timeline, phase); - const decisionOutcomes = [...new Set(timeline.decisions.map(item => item.sections!.decision!.outcome))]; + const timedDecisions = timeline.decisions.filter(item => item.at !== null); + const decisionCounts = new Map(); + for (const item of timedDecisions) { + const outcome = item.sections!.decision!.outcome; + decisionCounts.set(outcome, (decisionCounts.get(outcome) ?? 0) + 1); + } + const undatedDecisions = timeline.decisions.length - timedDecisions.length; const groupedIds = new Set(dayGroups.flatMap(group => group.nodes.map(node => node.id))); const swarm = timeline.singles.filter(id => !groupedIds.has(id)).map(id => timeline.nodes.get(id)!).filter(item => item.first !== null); const unknownTime = [...timeline.nodes.values()].filter(item => item.first === null).length; @@ -140,7 +146,7 @@ export function GoalResearchTimeline({timeline, complete, zh, selectedIds, selec {complete ?

{phaseNote}

: null}

{complete ? copy.densityHint : copy.partialDensityHint}{zh ? "。" : ". "}{zh ? "无记录空档不代表研究停止。" : "A recording gap does not establish that research stopped."}

-

{zh ? "悬停刻度可查看对应的本地时间。" : "Hover over a tick for its local time."}

+

{zh ? "悬停标记可查看记录时间。决策数量覆盖已读取的记录,时段选择只高亮对应的标记。" : "Hover over a mark for its record time. Counts cover the loaded records. Selecting a period highlights its marks."}

{findingCopy.meaning}

{!timeline.structuredCount ?

{copy.unstructuredHint}

: null}

{copy.routeHint}{zh ? "。" : ". "}{zh ? "相邻点合拢,数字为研究项数,一次展开原始时间与依据。" : "Nearby points group; the number counts research items. Select once for original times and sources."}

@@ -151,15 +157,19 @@ export function GoalResearchTimeline({timeline, complete, zh, selectedIds, selec
-
{copy.density}{axisLabel} - {hasRecordingGaps ?