diff --git a/.github/workflows/ark-turn.yml b/.github/workflows/ark-turn.yml index bef2e62448..62188c0d8e 100644 --- a/.github/workflows/ark-turn.yml +++ b/.github/workflows/ark-turn.yml @@ -8,7 +8,7 @@ on: - "loopx/control_plane/turn_driver/**" - "loopx/control_plane/collaboration/**" - "loopx/collaboration_mcp.py" - - "loopx/dsh_goal_mode/**" + - "loopx/hosts/dsh/**" - "loopx/cli_commands/turn*.py" - "loopx/control_plane/goals/acceptance*.ts" - "loopx/control_plane/goals/acceptance.py" diff --git a/.github/workflows/desktop-release-artifacts.yml b/.github/workflows/desktop-release-artifacts.yml index 565a09265e..280d50c55b 100644 --- a/.github/workflows/desktop-release-artifacts.yml +++ b/.github/workflows/desktop-release-artifacts.yml @@ -8,7 +8,9 @@ on: - "apps/presentation/dashboard/**" - "examples/desktop-icon-alpha-smoke.py" - "examples/desktop-release-workflow-smoke.py" + - "scripts/desktop_macos_signing.py" - "scripts/desktop_release_artifacts.py" + - "tests/desktop/test_desktop_signing_workflow.py" release: types: [published] workflow_dispatch: @@ -75,6 +77,19 @@ jobs: fi echo "release-tag=${release_tag}" >> "${GITHUB_OUTPUT}" + - name: Resolve macOS signing mode + id: macos-signing + if: github.event_name != 'pull_request' && runner.os == 'macOS' + env: + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} + APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + run: python3 scripts/desktop_macos_signing.py resolve-mode + - name: Set up Node uses: actions/setup-node@v6 with: @@ -125,11 +140,19 @@ jobs: working-directory: apps/desktop/loopx-control-plane run: npm run build -- --bundles ${{ matrix.bundles }} --no-sign - - name: Build integrity-signed macOS release bundles + - name: Build macOS release bundles if: github.event_name != 'pull_request' && runner.os == 'macOS' working-directory: apps/desktop/loopx-control-plane env: RELEASE_TAG: ${{ steps.identity.outputs.release-tag }} + EXPECTED_SIGNING_MODE: ${{ steps.macos-signing.outputs.signing-mode }} + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} + APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} run: | set -euo pipefail release_version="${RELEASE_TAG#v}" @@ -137,8 +160,22 @@ jobs: echo "::error title=Invalid desktop release version::${RELEASE_TAG} is not a supported release tag" exit 1 fi - npm run build -- --bundles ${{ matrix.bundles }} \ - --config "{\"version\":\"${release_version}\",\"bundle\":{\"macOS\":{\"signingIdentity\":\"-\"}}}" + python3 ../../../scripts/desktop_macos_signing.py build \ + --version "${release_version}" \ + --bundles ${{ matrix.bundles }} \ + --expected-mode "${EXPECTED_SIGNING_MODE}" + + - name: Notarize macOS disk image + if: github.event_name != 'pull_request' && runner.os == 'macOS' && steps.macos-signing.outputs.signing-mode == 'developer_id' + env: + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + run: | + set -euo pipefail + dmg_path="$(find apps/desktop/loopx-control-plane/src-tauri/target/release/bundle/dmg -maxdepth 1 -name '*.dmg' -print -quit)" + test -n "${dmg_path}" + python3 scripts/desktop_macos_signing.py notarize-dmg --dmg "${dmg_path}" - name: Build Windows release bundles if: github.event_name != 'pull_request' && runner.os == 'Windows' @@ -159,15 +196,17 @@ jobs: - name: Verify macOS desktop bundles if: github.event_name != 'pull_request' && runner.os == 'macOS' shell: bash + env: + SIGNING_MODE: ${{ steps.macos-signing.outputs.signing-mode }} run: | set -euo pipefail app_path="apps/desktop/loopx-control-plane/src-tauri/target/release/bundle/macos/LoopX.app" dmg_path="$(find apps/desktop/loopx-control-plane/src-tauri/target/release/bundle/dmg -maxdepth 1 -name '*.dmg' -print -quit)" test -n "${dmg_path}" - codesign --verify --deep --strict --verbose=2 "${app_path}" - codesign --display --verbose=4 "${app_path}" 2>&1 \ - | grep -q '^Signature=adhoc$' - hdiutil verify "${dmg_path}" + python3 scripts/desktop_macos_signing.py verify \ + --signing-mode "${SIGNING_MODE}" \ + --app "${app_path}" \ + --dmg "${dmg_path}" - name: Collect macOS desktop bundles if: runner.os == 'macOS' @@ -340,10 +379,20 @@ jobs: --jq '.assets[].name | select(. == "DESKTOP-SHA256SUMS" or (startswith("LoopX") and (endswith(".dmg") or endswith(".zip") or endswith(".exe") or endswith(".msi"))))' ) for asset in "${assets[@]}"; do - gh release download "${RELEASE_TAG}" \ - --repo "${GITHUB_REPOSITORY}" \ - --pattern "${asset}" \ - --dir dist/previous-desktop + for attempt in 1 2 3 4; do + rm -f "dist/previous-desktop/${asset}" + if gh release download "${RELEASE_TAG}" \ + --repo "${GITHUB_REPOSITORY}" \ + --pattern "${asset}" \ + --dir dist/previous-desktop + then + break + fi + if [[ "${attempt}" -eq 4 ]]; then + exit 1 + fi + sleep "$((1 << (attempt - 1)))" + done done { echo "release_tag=${RELEASE_TAG}" @@ -434,10 +483,20 @@ jobs: "LoopX_${RELEASE_VERSION}_x64_en-US.msi" \ DESKTOP-SHA256SUMS do - gh release download "${RELEASE_TAG}" \ - --repo "${GITHUB_REPOSITORY}" \ - --pattern "${asset}" \ - --dir dist/published-desktop + for attempt in 1 2 3 4; do + rm -f "dist/published-desktop/${asset}" + if gh release download "${RELEASE_TAG}" \ + --repo "${GITHUB_REPOSITORY}" \ + --pattern "${asset}" \ + --dir dist/published-desktop + then + break + fi + if [[ "${attempt}" -eq 4 ]]; then + exit 1 + fi + sleep "$((1 << (attempt - 1)))" + done done python scripts/desktop_release_artifacts.py verify-checksums \ --dist-dir dist/published-desktop \ diff --git a/.github/workflows/desktop-updater.yml b/.github/workflows/desktop-updater.yml index a6eaa65f18..e892efd24e 100644 --- a/.github/workflows/desktop-updater.yml +++ b/.github/workflows/desktop-updater.yml @@ -5,6 +5,9 @@ on: paths: - 'apps/desktop/**' - 'scripts/desktop_*' + - 'tests/desktop/**' + - 'loopx/cli_commands/public_default_contract.json' + - 'loopx/cli_commands/update_artifact.py' - '.github/workflows/desktop-updater.yml' release: types: [published] @@ -107,6 +110,17 @@ jobs: - uses: actions/setup-python@v6 with: python-version: "3.12" + - name: Resolve macOS signing mode + id: macos-signing + env: + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} + APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + run: python3 scripts/desktop_macos_signing.py resolve-mode - uses: dtolnay/rust-toolchain@stable - uses: Swatinem/rust-cache@v2 with: @@ -120,12 +134,38 @@ jobs: env: TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} TAURI_SIGNING_PRIVATE_KEY_PASSWORD: "" + EXPECTED_SIGNING_MODE: ${{ steps.macos-signing.outputs.signing-mode }} + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} + APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} VERSION: ${{ needs.identity.outputs.version }} BUNDLE: app run: | set -euo pipefail test -n "$TAURI_SIGNING_PRIVATE_KEY" - npm run build -- --bundles "$BUNDLE" --config "{\"version\":\"$VERSION\",\"bundle\":{\"createUpdaterArtifacts\":true,\"macOS\":{\"signingIdentity\":\"-\"}}}" + python3 ../../../scripts/desktop_macos_signing.py build \ + --version "$VERSION" \ + --bundles "$BUNDLE" \ + --create-updater-artifacts \ + --expected-mode "$EXPECTED_SIGNING_MODE" + - name: Verify macOS updater bundle + if: runner.os == 'macOS' + shell: bash + env: + SIGNING_MODE: ${{ steps.macos-signing.outputs.signing-mode }} + run: | + set -euo pipefail + app_path="apps/desktop/loopx-control-plane/src-tauri/target/release/bundle/macos/LoopX.app" + updater_tar_gz="$(find apps/desktop/loopx-control-plane/src-tauri/target/release/bundle -type f -name '*.app.tar.gz' -print -quit)" + test -n "${updater_tar_gz}" + python3 scripts/desktop_macos_signing.py verify \ + --signing-mode "${SIGNING_MODE}" \ + --app "${app_path}" \ + --updater-tar-gz "${updater_tar_gz}" - name: Collect native updater artifacts shell: bash env: @@ -257,7 +297,7 @@ jobs: # before the feed and channel pointer are published. shopt -s nullglob if [ "$EVENT_NAME" != release ]; then - gh release create "$RELEASE_TAG" --prerelease --target "$SOURCE_REF" --title "Desktop main $SOURCE_REF" --notes "Signed App and matching runtime preview." + gh release create "$RELEASE_TAG" --prerelease --latest=false --target "$SOURCE_REF" --title "Desktop main $SOURCE_REF" --notes "Signed App and matching runtime candidate for exact-revision qualification." fi for artifact in dist/updater/*.gz dist/updater/*.sig dist/updater/*.exe; do gh release upload "$RELEASE_TAG" "$artifact" @@ -272,7 +312,16 @@ jobs: decision=advance if grep -Fxq desktop-updater.json <<<"$pointer_assets"; then mkdir -p dist/current-pointer - gh release download "$pointer" --pattern desktop-updater.json --dir dist/current-pointer + for attempt in 1 2 3 4; do + rm -f dist/current-pointer/desktop-updater.json + if gh release download "$pointer" --pattern desktop-updater.json --dir dist/current-pointer; then + break + fi + if [ "$attempt" -eq 4 ]; then + exit 1 + fi + sleep "$((1 << (attempt - 1)))" + done decision="$(python scripts/desktop_update_feed.py \ --channel-pointer-decision "$CHANNEL" \ --current-feed dist/current-pointer/desktop-updater.json \ diff --git a/.github/workflows/dsh-plugin-publish.yml b/.github/workflows/dsh-plugin-publish.yml index 13401dce93..cf3b9fe5c0 100644 --- a/.github/workflows/dsh-plugin-publish.yml +++ b/.github/workflows/dsh-plugin-publish.yml @@ -17,7 +17,7 @@ concurrency: jobs: publish: - if: github.repository == 'loopx-project/loopx' && github.ref_type == 'tag' && github.ref_name == inputs.release_tag + if: github.repository == 'loopx-project/loopx' && ((github.ref_type == 'tag' && github.ref_name == inputs.release_tag) || (github.ref == 'refs/heads/main' && startsWith(inputs.release_tag, 'dsh-loopx-plugin-v'))) runs-on: ubuntu-latest timeout-minutes: 10 permissions: @@ -32,11 +32,13 @@ jobs: steps: - uses: actions/checkout@v7 with: - ref: ${{ github.sha }} + ref: refs/tags/${{ inputs.release_tag }} fetch-depth: 0 - uses: actions/setup-node@v6 with: node-version: "24" + registry-url: https://registry.npmjs.org + package-manager-cache: false - name: Require a merged, published release with matching package identity run: | git fetch origin main @@ -47,7 +49,7 @@ jobs: const manifest = JSON.parse(readFileSync('package.json', 'utf8')) assert.equal(process.env.RELEASE_TAG, `dsh-loopx-plugin-v${manifest.version}`) mkdirSync('output', { recursive: true }) - appendFileSync(process.env.GITHUB_ENV, `DSH_ARTIFACT=output/${manifest.name}-${manifest.version}.tgz\n`) + appendFileSync(process.env.GITHUB_ENV, `DSH_ARTIFACT=./output/${manifest.name}-${manifest.version}.tgz\n`) NODE gh release view "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" --json tagName,isDraft > output/release.json node -e 'const r=require("./output/release.json"); require("node:assert/strict").equal(r.isDraft, false)' @@ -70,8 +72,57 @@ jobs: const exists = response.ok && !!(await response.json()).versions?.[source.version] appendFileSync(process.env.GITHUB_ENV, `DSH_ALREADY_PUBLISHED=${exists}\n`) NODE + node --input-type=module <<'NODE' + import { appendFileSync, readFileSync } from 'node:fs' + const source = JSON.parse(readFileSync('package.json', 'utf8')) + const response = await fetch(`https://registry.npmjs.org/${encodeURIComponent(source.name)}`, { + signal: AbortSignal.timeout(15_000), + }) + const missing = response.status === 404 + const body = response.ok ? await response.json() : null + const versions = Object.keys(body?.versions ?? {}) + const stagingOnly = versions.length > 0 && versions.every(v => v === '0.0.0-stage') && !versions.includes(source.version) + appendFileSync(process.env.GITHUB_ENV, `DSH_NPM_PACKAGE_MISSING=${missing}\nDSH_NPM_STAGING_PLACEHOLDER=${stagingOnly}\n`) + NODE - name: Publish the same bytes with npm trusted publishing if: env.DSH_ALREADY_PUBLISHED != 'true' - run: npm publish "$DSH_ARTIFACT" --access public --tag latest --ignore-scripts --provenance + run: | + if [ -z "${ACTIONS_ID_TOKEN_REQUEST_URL:-}" ] || [ -z "${ACTIONS_ID_TOKEN_REQUEST_TOKEN:-}" ]; then + echo "::error title=GitHub OIDC unavailable::The hosted runner did not provide a GitHub OIDC request. Check the publish job's id-token permission." + exit 1 + fi + publish_log="$(mktemp)" + trap 'rm -f "$publish_log"' EXIT + set +e + npm publish "$DSH_ARTIFACT" --access public --tag latest --ignore-scripts --provenance --loglevel=verbose > "$publish_log" 2>&1 + rc=$? + set -e + if [ "$rc" -ne 0 ]; then + # Describe the stage without printing the trace, which can include an OIDC request URL. + if grep -Fq 'Successfully retrieved and set token' "$publish_log"; then + echo "::notice title=npm publish stage::npm accepted the workflow identity. Publishing the immutable archive failed afterward." + elif grep -Fq 'Failed token exchange request' "$publish_log"; then + echo "::notice title=npm publish stage::GitHub supplied an identity but npm rejected its token exchange." + elif grep -Fq 'Failed to fetch id_token from GitHub' "$publish_log"; then + echo "::notice title=npm publish stage::GitHub did not return an OIDC identity to npm." + fi + if [ "${DSH_NPM_PACKAGE_MISSING:-false}" = "true" ]; then + echo "::error title=npm package bootstrap required::dsh-loopx-plugin returns HTTP 404 on registry.npmjs.org. npm OIDC Trusted Publishing cannot create a brand-new package: enable 2FA (auth-and-writes), run one-time web-auth 'npm publish --access public --tag latest --ignore-scripts', run 'npm logout', then bind Trusted Publisher (loopx-project / loopx / dsh-plugin-publish.yml / blank Environment name / Allow npm publish checked)." + elif [ "${DSH_NPM_STAGING_PLACEHOLDER:-false}" = "true" ]; then + echo "::error title=npm package staging scan active::registry.npmjs.org still holds 0.0.0-stage from initial publish scan; wait 1-3 minutes for the target version to activate and re-dispatch." + else + echo "::error title=npm Trusted Publisher failed::Verify npmjs Trusted Publisher settings on https://www.npmjs.com/package/dsh-loopx-plugin/access (Provider: GitHub Actions, Organization or user: loopx-project, Repository: loopx, Workflow filename: dsh-plugin-publish.yml, Environment name: empty, Allow npm publish: checked)." + fi + exit "$rc" + fi + echo "Published the immutable GitHub archive to npm." - name: Read back npm bytes, latest, and marketplace repository discovery - run: node scripts/verify-distribution.mjs --tarball "$DSH_ARTIFACT" + run: | + if git cat-file -e origin/main:packages/dsh-loopx-plugin/scripts/verify-distribution.mjs 2>/dev/null; then + git show origin/main:packages/dsh-loopx-plugin/scripts/verify-distribution.mjs > scripts/verify-distribution.mjs + fi + propagation_timeout=0 + if [ "$DSH_ALREADY_PUBLISHED" = false ]; then + propagation_timeout=180000 + fi + node scripts/verify-distribution.mjs --tarball "$DSH_ARTIFACT" --registry-propagation-timeout-ms "$propagation_timeout" diff --git a/.github/workflows/full-public-smokes.yml b/.github/workflows/full-public-smokes.yml index b8914525b4..ec0ef531eb 100644 --- a/.github/workflows/full-public-smokes.yml +++ b/.github/workflows/full-public-smokes.yml @@ -60,15 +60,15 @@ jobs: - shard: 0 offset: 0 - shard: 1 - offset: 110 + offset: 80 - shard: 2 - offset: 220 + offset: 160 - shard: 3 - offset: 330 + offset: 240 - shard: 4 - offset: 440 + offset: 320 env: - SHARD_LIMIT: "110" + SHARD_LIMIT: "80" SMOKE_TIMEOUT_SECONDS: ${{ github.event_name == 'workflow_dispatch' && inputs.timeout_seconds || '360' }} SMOKE_JOBS: "4" steps: diff --git a/.github/workflows/package-smoke.yml b/.github/workflows/package-smoke.yml index d130915e13..3abaeae7a8 100644 --- a/.github/workflows/package-smoke.yml +++ b/.github/workflows/package-smoke.yml @@ -4,36 +4,54 @@ on: pull_request: paths: - ".github/workflows/package-smoke.yml" - - "packages/loopx-core/**" - - "loopx/**" + - "packages/**" + - "apps/presentation/dashboard/**" + - "scripts/chat_bundle.py" - "tests/test_core_distribution.py" + - "tests/test_core_workspace_distribution.py" + - "tests/test_core_benchmark_distribution.py" + - "tests/test_core_recall_distribution.py" + - "tests/test_core_pr_review_distribution.py" + - "tests/test_core_issue_fix_distribution.py" + - "tests/test_core_standard_distribution.py" - "tests/control_plane/test_installed_core_context.py" - - "packages/loopx-repo-health/**" - - "packages/loopx-obelisk/**" - - "packages/loopx-codex-provider-routing/**" - - "loopx/capabilities/decision_context/extension_provider.py" + - "tests/test_core_research_distribution.py" + - "tests/capabilities/test_external_evidence_cli.py" - "loopx/extensions/runtime.py" + - "loopx/capabilities/decision_context/extension_provider.py" + - "pyproject.toml" push: branches: - main paths: - ".github/workflows/package-smoke.yml" - - "packages/loopx-core/**" + - "packages/**" + - "apps/presentation/dashboard/**" + - "scripts/chat_bundle.py" - "loopx/**" - "tests/test_core_distribution.py" + - "tests/test_core_workspace_distribution.py" + - "tests/test_core_benchmark_distribution.py" + - "tests/test_core_recall_distribution.py" + - "tests/test_core_pr_review_distribution.py" + - "tests/test_core_issue_fix_distribution.py" + - "tests/test_core_standard_distribution.py" - "tests/control_plane/test_installed_core_context.py" - - "packages/loopx-repo-health/**" - - "packages/loopx-obelisk/**" - - "packages/loopx-codex-provider-routing/**" - - "loopx/capabilities/decision_context/extension_provider.py" + - "tests/test_core_research_distribution.py" + - "tests/capabilities/test_external_evidence_cli.py" - "loopx/extensions/runtime.py" + - "loopx/capabilities/decision_context/extension_provider.py" + - "pyproject.toml" + schedule: + - cron: "47 20 * * *" + workflow_dispatch: permissions: contents: read concurrency: - group: package-smoke-${{ github.ref }} - cancel-in-progress: true + group: package-smoke-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.number) || github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: core: @@ -47,7 +65,7 @@ jobs: python-version: "3.11" - uses: actions/setup-node@v6 with: - node-version: "26.0.0" + node-version: "24" - uses: astral-sh/setup-uv@v7 - name: Prepare source validation environment run: uv sync --extra test @@ -65,6 +83,89 @@ jobs: uv run --extra test python -m pytest -q tests/test_core_distribution.py tests/control_plane/test_installed_core_context.py + - name: Qualify matching Benchmark Toolkit installation and recovery + env: + LOOPX_USAGE_PING: "0" + run: | + uv run --extra test python packages/loopx-core/prepare.py \ + --distribution loopx-capability-benchmark-toolkit --output "$RUNNER_TEMP/benchmark-source" + uv build --wheel "$RUNNER_TEMP/benchmark-source" --out-dir "$RUNNER_TEMP/benchmark-dist" + export LOOPX_CORE_TEST_WHEEL=$(printf '%s' "$RUNNER_TEMP"/core-dist/loopx_core-*.whl) + export LOOPX_BENCHMARK_TEST_WHEEL=$(printf '%s' "$RUNNER_TEMP"/benchmark-dist/loopx_capability_benchmark_toolkit-*.whl) + uv run --extra test python -m pytest -q tests/test_core_benchmark_distribution.py + + - name: Qualify matched recall installation, execution, and removal + env: + LOOPX_USAGE_PING: "0" + run: | + uv run --extra test python packages/loopx-core/prepare.py \ + --distribution loopx-capability-agent-turn-recall --output "$RUNNER_TEMP/recall-source" + uv build --wheel "$RUNNER_TEMP/recall-source" --out-dir "$RUNNER_TEMP/core-dist" + uv pip install --python "$LOOPX_CORE_TEST_PYTHON" \ + "$RUNNER_TEMP"/core-dist/loopx_capability_agent_turn_recall-*.whl + LOOPX_RECALL_TEST_ENABLED=1 uv run --extra test python -m pytest -q tests/test_core_recall_distribution.py + uv pip uninstall --python "$LOOPX_CORE_TEST_PYTHON" loopx-capability-agent-turn-recall + uv run --extra test python -m pytest -q tests/test_core_distribution.py \ + -k 'reports_optional_turn_recall or completes_turn_with_configured_optional_recall' + + - name: Qualify matched pull-request review installation, checkpoint and removal + env: + LOOPX_USAGE_PING: "0" + run: | + uv run --extra test python packages/loopx-core/prepare.py \ + --distribution loopx-capability-pull-request-review --output "$RUNNER_TEMP/review-source" + uv build --wheel "$RUNNER_TEMP/review-source" --out-dir "$RUNNER_TEMP/core-dist" + uv pip install --python "$LOOPX_CORE_TEST_PYTHON" \ + "$RUNNER_TEMP"/core-dist/loopx_capability_pull_request_review-*.whl + LOOPX_REVIEW_TEST_ENABLED=1 uv run --extra test python -m pytest -q tests/test_core_pr_review_distribution.py + uv pip uninstall --python "$LOOPX_CORE_TEST_PYTHON" loopx-capability-pull-request-review + uv run --extra test python -m pytest -q tests/test_core_pr_review_distribution.py -k discovers + + - name: Qualify Issue Fix and the Standard CLI composition + env: + LOOPX_USAGE_PING: "0" + run: | + uv run --extra test python packages/loopx-core/prepare.py \ + --distribution loopx-capability-issue-fix --output "$RUNNER_TEMP/issue-fix-source" + uv build --wheel "$RUNNER_TEMP/issue-fix-source" --out-dir "$RUNNER_TEMP/core-dist" + uv pip install --python "$LOOPX_CORE_TEST_PYTHON" \ + "$RUNNER_TEMP"/core-dist/loopx_capability_issue_fix-*.whl + LOOPX_ISSUE_FIX_TEST_ENABLED=1 uv run --extra test python -m pytest -q tests/test_core_issue_fix_distribution.py + uv pip uninstall --python "$LOOPX_CORE_TEST_PYTHON" loopx-capability-issue-fix + uv pip install --offline --no-index --find-links "$RUNNER_TEMP/core-dist" --reinstall-package loopx-core \ + --python "$LOOPX_CORE_TEST_PYTHON" 'loopx-core[standard]' + LOOPX_ISSUE_FIX_TEST_ENABLED=1 LOOPX_REVIEW_TEST_ENABLED=1 LOOPX_RECALL_TEST_ENABLED=1 \ + uv run --extra test python -m pytest -q \ + tests/test_core_issue_fix_distribution.py tests/test_core_pr_review_distribution.py \ + tests/test_core_recall_distribution.py -k 'installed' + uv pip uninstall --python "$LOOPX_CORE_TEST_PYTHON" \ + loopx-capability-issue-fix loopx-capability-pull-request-review loopx-capability-agent-turn-recall + uv run --extra test python -m pytest -q tests/test_core_issue_fix_distribution.py -k 'quiet or retains_bound' + LOOPX_STANDARD_TEST_WHEELHOUSE="$RUNNER_TEMP/core-dist" uv run --extra test python -m pytest -q \ + tests/test_core_standard_distribution.py + + - name: Qualify research availability, Explore primary workflow, ledger recovery and removal + env: + LOOPX_USAGE_PING: "0" + run: | + uv run --extra test python -m pytest -q tests/test_core_research_distribution.py + uv run --extra test python packages/loopx-core/prepare.py --distribution loopx-capability-research --output "$RUNNER_TEMP/research-source" + uv build --wheel "$RUNNER_TEMP/research-source" --out-dir "$RUNNER_TEMP/research-dist" + uv pip install --python "$LOOPX_CORE_TEST_PYTHON" "$RUNNER_TEMP"/research-dist/loopx_capability_research-*.whl + LOOPX_RESEARCH_TEST_ENABLED=1 uv run --extra test python -m pytest -q tests/test_core_research_distribution.py + LOOPX_RESEARCH_TEST_PYTHON="$LOOPX_CORE_TEST_PYTHON" uv run --extra test python -m pytest -q tests/capabilities/test_external_evidence_cli.py -k preserves_receipt_clocks_and_idempotent_ledger + uv pip uninstall --python "$LOOPX_CORE_TEST_PYTHON" loopx-capability-research + uv run --extra test python -m pytest -q tests/test_core_research_distribution.py + LOOPX_CORE_TEST_PYTHON="$LOOPX_CORE_TEST_PYTHON" uv run --extra test python -m pytest -q tests/test_core_distribution.py -k 'identity_help_and_unavailable_workspace or defers_explore_evaluation' + - name: Build the matching Workspace wheel + run: | + uv run --extra test python scripts/chat_bundle.py build --install + uv run --extra test python packages/loopx-core/prepare.py --distribution loopx-workspace --output "$RUNNER_TEMP/workspace-source" + uv build --wheel "$RUNNER_TEMP/workspace-source" --out-dir "$RUNNER_TEMP/workspace-dist" + printf 'LOOPX_CORE_TEST_WHEEL=%s\n' "$RUNNER_TEMP"/core-dist/loopx_core-*.whl >> "$GITHUB_ENV" + printf 'LOOPX_WORKSPACE_TEST_WHEEL=%s\n' "$RUNNER_TEMP"/workspace-dist/loopx_workspace-*.whl >> "$GITHUB_ENV" + - name: Qualify Workspace readback and removal on File and SQLite + run: uv run --extra test python -m pytest -q tests/test_core_workspace_distribution.py codex-provider-routing: name: loopx-codex-provider-routing @@ -91,7 +192,15 @@ jobs: import json, subprocess from pathlib import Path from jsonschema import validate + import tomllib + from importlib.metadata import version + from importlib.resources import files + import loopx_codex_provider_routing as provider root = Path("packages/loopx-codex-provider-routing") + release = version("loopx-codex-provider-routing") + assert provider.__version__ == release + for manifest in (root / "extension.toml", files(provider) / "native-extension.toml"): + assert tomllib.loads(manifest.read_text(encoding="utf-8"))["version"] == release, manifest request_schema = json.loads((root / "schemas/request.schema.json").read_text()) response_schema = json.loads((root / "schemas/response.schema.json").read_text()) for example in sorted((root / "examples").glob("*.json")): diff --git a/.github/workflows/postgresql-integration.yml b/.github/workflows/postgresql-integration.yml deleted file mode 100644 index bad716be3c..0000000000 --- a/.github/workflows/postgresql-integration.yml +++ /dev/null @@ -1,118 +0,0 @@ -name: PostgreSQL Integration - -# The Python Tests coverage job runs without PostgreSQL, so the provider-backed -# integration suites skip there. This workflow qualifies the same commit against -# a disposable PostgreSQL server: the ladder row reports `unverified` when the -# URL is missing and the service suites are asserted by name, so a silent skip -# cannot pass. Remote commands additionally exercise TLS clients, a restricted -# database role, response loss and service restart. - -on: - pull_request: - paths: - - ".github/workflows/postgresql-integration.yml" - - "loopx/control_plane/**" - - "tests/control_plane_ts/**" - - "examples/coordination/remote-authority-*.ts" - - "package.json" - - "package-lock.json" - workflow_dispatch: - push: - branches: - - main - paths: - - ".github/workflows/postgresql-integration.yml" - - "loopx/control_plane/**" - - "tests/control_plane_ts/**" - - "examples/coordination/remote-authority-*.ts" - - "package.json" - - "package-lock.json" - -permissions: - contents: read - -concurrency: - group: postgresql-integration-${{ github.ref }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} - -jobs: - postgresql-authority: - name: postgresql-authority (real server) - runs-on: ubuntu-latest - timeout-minutes: 10 - services: - postgres: - image: postgres:16.15 - env: - POSTGRES_USER: loopx - POSTGRES_PASSWORD: loopx - POSTGRES_DB: loopx_store - ports: - - 5432:5432 - options: >- - --health-cmd "pg_isready -U loopx -d loopx_store" - --health-interval 5s - --health-timeout 5s - --health-retries 12 - steps: - - name: Check out repository - uses: actions/checkout@v7 - - - name: Set up the qualified Node.js runtime - uses: actions/setup-node@v6 - with: - node-version: "22.22.3" - cache: npm - cache-dependency-path: package-lock.json - - - name: Install locked dependencies - run: npm ci --ignore-scripts - - - name: Create the disposable service database - env: - PGPASSWORD: loopx - run: >- - psql --host 127.0.0.1 --username loopx --dbname postgres - --set ON_ERROR_STOP=1 --command "CREATE DATABASE loopx_service" - - - name: Qualify the PostgreSQL store conformance ladder row - env: - LOOPX_TEST_POSTGRES_URL: postgresql://loopx:loopx@127.0.0.1:5432/loopx_store - run: >- - python3 -m loopx.control_plane.testing.authority_e2e_ladder - --row s2b.postgresql_conformance_live - --report-json postgresql-conformance-report.json - - - name: Assert the service admission suite is available - run: | - set -euo pipefail - node -e 'const scripts = require("./package.json").scripts; if (!scripts["test:postgresql-authority-service"]) { console.error("package.json must expose test:postgresql-authority-service: the service admission path has no CI qualification without it"); process.exit(1); }' - - - name: Qualify the PostgreSQL service admission path - env: - LOOPX_TEST_POSTGRES_SERVICE_URL: postgresql://loopx:loopx@127.0.0.1:5432/loopx_service - LOOPX_TEST_POSTGRES_URL: postgresql://loopx:loopx@127.0.0.1:5432/loopx_store - run: | - set -euo pipefail - npm run test:postgresql-authority-service 2>&1 | tee postgresql-service-admission.log - grep -Fq "PostgreSQL service admits an authorized tenant and rotates a restored incarnation" postgresql-service-admission.log - - - name: Qualify authenticated remote task commands - env: - LOOPX_TEST_POSTGRES_URL: postgresql://loopx:loopx@127.0.0.1:5432/loopx_store - run: | - set -euo pipefail - npm run test:remote-authority 2>&1 | tee remote-authority.log - grep -Fq "lost response and server restart recover the exact receipt" remote-authority.log - - - name: Upload bounded PostgreSQL qualification evidence - if: always() - uses: actions/upload-artifact@v7 - with: - name: postgresql-conformance-report - path: | - postgresql-conformance-report.json - postgresql-service-admission.log - remote-authority.log - if-no-files-found: ignore - retention-days: 7 diff --git a/.github/workflows/python-tests.yml b/.github/workflows/python-tests.yml index dc7b2ed781..8421b2ee5e 100644 --- a/.github/workflows/python-tests.yml +++ b/.github/workflows/python-tests.yml @@ -51,6 +51,8 @@ jobs: outputs: core_tests: ${{ steps.classify.outputs.core_tests }} backend_tests: ${{ steps.classify.outputs.backend_tests }} + frontend_tests: ${{ steps.classify.outputs.frontend_tests }} + compat_tests: ${{ steps.classify.outputs.compat_tests }} change_kind: ${{ steps.classify.outputs.change_kind }} python_tests: ${{ steps.classify.outputs.python_tests }} stage2c_tests: ${{ steps.classify.outputs.stage2c_tests }} @@ -97,8 +99,15 @@ jobs: summary.write("## CI job exemptions\n\n") summary.write(f"Change kind: **{plan['change_kind']}**; Python shards: **{plan['python_shards']}**.\n\n") summary.write(plan['reason'] + ".\n\n") - summary.write(f"Backend: {plan['backend_tests']}; Python: {plan['python_tests']}; Stage2c: {plan['stage2c_tests']}; frontend: {plan['core_tests']}; freshness: {plan['presentation_tests']}.\n\n") - summary.write(plan["coverage_scope"] + ". Unknown/mixed changes and main run full. Label ci:full forces full qualification.\n") + summary.write( + f"Backend: {plan['backend_tests']}; Frontend browser: {plan['frontend_tests']}; " + f"Compat: {plan['compat_tests']}; Python: {plan['python_tests']}; " + f"Stage2c: {plan['stage2c_tests']}; freshness: {plan['presentation_tests']}.\n\n" + ) + summary.write( + plan["coverage_scope"] + + ". Normal PRs run fast static/contract/TS checks; Nightly schedule, main, merge_group, CI-policy/manifest edits and ci:full run full.\n" + ) PY - uses: actions/upload-artifact@v7 with: @@ -147,7 +156,7 @@ jobs: chat-bundle-browser: needs: [changes, chat-bundle] - if: needs.changes.outputs.core_tests == 'true' && !cancelled() && needs.chat-bundle.result == 'success' + if: needs.changes.outputs.frontend_tests == 'true' && !cancelled() && needs.chat-bundle.result == 'success' runs-on: ubuntu-latest # The packaged scenario catalog outgrew one 15-minute runner, so the # catalog is partitioned like dashboard-browser and the companion smokes @@ -255,6 +264,8 @@ jobs: python -m pytest -q --no-cov tests/test_stage2c_dependency_lock.py tests/architecture/test_top_level_module_budget.py + tests/test_repository_instruction_delivery.py + tests/test_contributing_guide.py - name: Lint test suite run: >- @@ -422,7 +433,7 @@ jobs: dashboard-browser: needs: [changes, chat-bundle] - if: needs.changes.outputs.core_tests == 'true' && !cancelled() && needs.chat-bundle.result == 'success' + if: needs.changes.outputs.frontend_tests == 'true' && !cancelled() && needs.chat-bundle.result == 'success' runs-on: ubuntu-latest timeout-minutes: 25 strategy: @@ -508,7 +519,7 @@ jobs: dashboard-acceptance: needs: [changes, dashboard-browser] - if: needs.changes.outputs.core_tests == 'true' && !cancelled() && needs.dashboard-browser.result == 'success' + if: needs.changes.outputs.frontend_tests == 'true' && !cancelled() && needs.dashboard-browser.result == 'success' runs-on: ubuntu-latest timeout-minutes: 5 steps: @@ -550,7 +561,7 @@ jobs: node-minimum-compatibility: needs: [changes, chat-bundle] - if: needs.changes.outputs.backend_tests == 'true' && !cancelled() && needs.chat-bundle.result == 'success' + if: needs.changes.outputs.compat_tests == 'true' && !cancelled() && needs.chat-bundle.result == 'success' runs-on: ubuntu-latest # The full suite runs under this exact Node version in typescript-core. timeout-minutes: 10 @@ -577,7 +588,7 @@ jobs: needs: [changes, chat-bundle] # Probe the future runtime once per night or on demand, outside the PR/main # critical path. The supported runtime still runs on every full candidate. - if: (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') && needs.changes.outputs.backend_tests == 'true' && !cancelled() && needs.chat-bundle.result == 'success' + if: (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') && needs.changes.outputs.compat_tests == 'true' && !cancelled() && needs.chat-bundle.result == 'success' continue-on-error: true runs-on: ubuntu-latest # This runs the full core conformance suite. Allow forward-runtime/runner @@ -615,13 +626,17 @@ jobs: cancel-in-progress: false # All shards were still progressing at 83-94% when the 45m job # deadline cancelled run 37916979857. Reserve setup/reporting headroom - # without changing test-level deadlines, collection or worker count. + # without changing test-level deadlines, collection or worker count; compute + # the remaining cooperative session deadline from the actual job start epoch + # while reserving 5m for partial JUnit/diagnostics flush and artifact upload. timeout-minutes: 60 strategy: fail-fast: false matrix: shard: [1, 2, 3, 4, 5, 6] steps: + - name: Record job start time + run: echo "LOOPX_SHARD_JOB_START_EPOCH=$(date -u +%s)" >> "$GITHUB_ENV" - uses: actions/checkout@v7 with: fetch-depth: 0 @@ -647,8 +662,10 @@ jobs: # Ubuntu 24.04 may need an executable-scoped userns profile for bwrap. # Do not disable AppArmor or the system-wide unprivileged-userns guard. run: | - sudo apt-get update - sudo apt-get install -y bubblewrap + if ! command -v bwrap >/dev/null 2>&1; then + sudo apt-get update + sudo apt-get install -y --no-install-recommends bubblewrap + fi if ! bwrap --unshare-all --ro-bind / / /bin/true; then sudo tee /etc/apparmor.d/loopx-qualification-bwrap >/dev/null <<'PROFILE' abi , @@ -663,12 +680,20 @@ jobs: - name: Run test shard # Split the whole collection, not a hand-maintained list of directories. # Without timing history least_duration alternates equal-weight tests. - # Each runner retains the measured two-worker pool. - # Cooperative per-test Python stacks diagnose stalls without terminating tests. + # Each runner retains the measured two-worker pool; cooperative stacks + # and the dynamic job-budget deadline diagnose slow/blocked cases and + # preserve the upload reserve even when setup steps overrun. run: >- - python -m pytest -v -n 2 -m "not stage2c_e2e" + python -m scripts.ci.shard_budget + --job-budget-seconds 3600 + --upload-reserve-seconds 300 + --min-session-seconds 300 + --diagnostics-file ci-shard-diagnostics.json + -- + -v -n 2 -m "not stage2c_e2e" -p scripts.ci.pytest_timing --ci-stall-after 120 + --ci-diagnostics-file ci-shard-diagnostics.json --splits 6 --group ${{ matrix.shard }} --splitting-algorithm least_duration --durations=25 --durations-min=1 @@ -676,13 +701,21 @@ jobs: --cov=loopx --cov-report=term - name: Upload full-shard outcomes for selection audit - if: always() + if: ${{ !cancelled() }} uses: actions/upload-artifact@v7 with: name: python-junit-${{ matrix.shard }} path: junit.xml if-no-files-found: error retention-days: 7 + - name: Upload shard timeout and progress diagnostics + if: always() + uses: actions/upload-artifact@v7 + with: + name: python-diagnostics-${{ matrix.shard }} + path: ci-shard-diagnostics.json + if-no-files-found: warn + retention-days: 7 - name: Upload shard coverage uses: actions/upload-artifact@v7 with: diff --git a/.github/workflows/release-artifacts.yml b/.github/workflows/release-artifacts.yml index b7ce17a6f8..afaf0d6ee7 100644 --- a/.github/workflows/release-artifacts.yml +++ b/.github/workflows/release-artifacts.yml @@ -7,22 +7,17 @@ on: - "examples/release-artifacts-smoke.py" - "examples/personal-workspace-browser/**" - "examples/personal-workspace-browser-smoke.mjs" - - "loopx/**" - - "package.json" - - "package-lock.json" - "pyproject.toml" - "setup.py" - "MANIFEST.in" - - "apps/presentation/dashboard/**" - - "scripts/chat_bundle.py" - - "scripts/verify_installed_chat.py" - - "README.md" - "scripts/release_artifacts.py" - "scripts/runtime_artifact.py" - "scripts/qualify_runtime_artifact.py" - - "tsconfig.control-plane.json" release: types: [published] + schedule: + # Nightly release-artifact and packaged browser verification without publishing assets. + - cron: "41 21 * * *" workflow_dispatch: inputs: tag: @@ -252,6 +247,7 @@ jobs: raise SystemExit("browser fixture correction must name a commit") allowed = { "examples/personal-workspace-browser/fixture.mjs", + "examples/personal-workspace-browser/chat-recovery.mjs", "examples/personal-workspace-browser/typed-actions.mjs", "examples/personal-workspace-browser/goal-work-map.mjs", "examples/personal-workspace-browser/goal-workspace-m2.mjs", @@ -692,7 +688,7 @@ jobs: JS - name: Attest release packages and checksum manifest - if: github.event_name != 'pull_request' + if: github.event_name == 'release' || github.event_name == 'workflow_dispatch' uses: actions/attest@v4 with: subject-path: | @@ -712,7 +708,7 @@ jobs: upload-release: if: >- !cancelled() && github.repository == 'loopx-project/loopx' && - github.event_name != 'pull_request' && + (github.event_name == 'release' || github.event_name == 'workflow_dispatch') && (needs.build.result == 'success' || (inputs.validated_run_id != '' && needs.build.result == 'skipped')) needs: build @@ -774,7 +770,8 @@ jobs: publish-pypi: if: >- - !cancelled() && github.event_name != 'pull_request' && + !cancelled() && + (github.event_name == 'release' || github.event_name == 'workflow_dispatch') && needs.upload-release.result == 'success' && vars.PYPI_PUBLISH_ENABLED == 'true' needs: upload-release diff --git a/.github/workflows/runtime-snapshots.yml b/.github/workflows/runtime-snapshots.yml index e037b7f104..7251028621 100644 --- a/.github/workflows/runtime-snapshots.yml +++ b/.github/workflows/runtime-snapshots.yml @@ -11,6 +11,7 @@ on: - "tests/test_runtime_snapshot_publication.py" - "tests/test_update_artifact.py" - "scripts/install*.sh" + - "loopx/cli_commands/public_default_contract.json" - "loopx/cli_commands/update*.py" - "loopx/cli_commands/support_control_update*.py" - "loopx/self_update*.py" @@ -93,47 +94,33 @@ jobs: # 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 import sys sys.path.insert(0, str(Path.cwd())) - from loopx.cli_commands.update_artifact import validate_default_contract + from loopx.cli_commands.update_artifact import ( + validate_published_manifest, verify_runtime_installation_qualification, + ) root = Path("runtime") manifest_bytes = (root / "loopx-runtime.json").read_bytes() - manifest = json.loads(manifest_bytes) + manifest = validate_published_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") - default_contract = validate_default_contract(manifest.get("default_contract")) - if qualification.get("default_contract") != default_contract: - raise SystemExit("Runtime default-contract qualification is missing or mismatched") - 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") + verify_runtime_installation_qualification(manifest, qualification, archive, channel="main") if (root / f"loopx-runtime-{revision}.json").read_bytes() != manifest_bytes: raise SystemExit("Immutable runtime metadata differs from the channel candidate") print(revision) PY )" + # Only main revisions may be published. + relation="$(gh api "repos/${GITHUB_REPOSITORY}/compare/${revision}...main" --jq .status)" + if [[ "$relation" != ahead && "$relation" != identical ]]; then exit 1; fi # Keep each immutable snapshot below GitHub's per-release asset cap. - # The existing channel release retains its historical assets and URL. + # These candidates can be tested by exact revision before adoption. tag="runtime-main-${revision}" if ! gh release view "$tag" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then - gh release create "$tag" --repo "$GITHUB_REPOSITORY" --target "$revision" --prerelease --latest=false --title "Qualified main runtime ${revision}" --notes "Immutable runtime snapshot. Stable users continue with PyPI or the stable runtime." + gh release create "$tag" --repo "$GITHUB_REPOSITORY" --target "$revision" --prerelease --latest=false --title "Main runtime candidate ${revision}" --notes "Immutable runtime snapshot for exact-revision qualification." fi actual="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${tag}" --jq .sha)" if [[ "$actual" != "$revision" ]]; then exit 1; fi @@ -148,10 +135,6 @@ jobs: gh release upload "$tag" "$file" --repo "$GITHUB_REPOSITORY" fi done - # Publication is serialized. A qualified ancestor is usable while a - # newer main is still building; never publish a non-main revision. - relation="$(gh api "repos/${GITHUB_REPOSITORY}/compare/${revision}...main" --jq .status)" - if [[ "$relation" != ahead && "$relation" != identical ]]; then exit 1; fi if ! gh release view runtime-main --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then gh release create runtime-main --repo "$GITHUB_REPOSITORY" --target "$revision" --prerelease --latest=false --title "Latest qualified main runtime" --notes "Mutable channel metadata points to immutable revision releases. Stable users continue with PyPI or the stable runtime." fi diff --git a/AGENTS.md b/AGENTS.md index 5948b2603b..0448772325 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,7 +40,7 @@ prompt. Keep the root within both the 24,000-byte (24 KB) Antigravity per-file rule cap and the default 32 KiB Codex discovery budget, and do not eagerly import linked detail documents. See [loading](docs/development/README.md#agent-instruction-loading-and-maintenance) -for host-specific checks; delivery does not prove model compliance. +for host-specific checks. Prefer [context](docs/development/README.md#progressive-context-for-development): current goals, constraints and acceptance criteria first; supporting evidence and @@ -65,16 +65,14 @@ acceptance is proven; reconcile the existing checkpoint as evidence changes. Carry one compact delivery brief from task to PR (goal/source, current gap, observable result, owning boundary and decisive acceptance evidence), keeping private Goal state out of public artifacts. Choose a complete, independently -reviewable and reversible outcome slice; small diffs, fields, receipts, test -counts and merged PR counts do not establish progress. Characterization, +reviewable and reversible outcome slice. Characterization, prerequisites, research, docs and maintenance are valid when they remove an evidenced gap or enable a named next step. For long-horizon improvements, trace the accepted goal and structured state through feedback, the replan decision, subsequent work and validated outcomes. Check whether new evidence changed the action or justified continuing it, and -preserve negative results and uncertainty (`state survival`, graph edges, read -receipts or replan records alone do not prove adoption or benefit). Compare +preserve negative results and uncertainty. Compare outcomes and complete costs under comparable conditions using the [measurement contract](docs/architecture/rfcs/long-horizon-harness-benchmark-research-program-v0.md#6-measurement-model); do not force a direction change merely to increase replan counts. @@ -93,8 +91,7 @@ a registered vocabulary, remains local or creates a shared contract, and follow the [diff advisory](CONTRIBUTING.md#check-new-semantic-vocabulary-while-developing) before the full-tree check (including intentional untracked sources). For multi-Agent changes, qualify dependency artifacts, receiver adoption, claim/lease -handling, independent acceptance and result return; sending a message or -registering workers does not prove collaboration, and missing frontend/Lark/CLI +handling, independent acceptance and result return; missing frontend/Lark/CLI companion work makes a product journey partial. Before delivery, reconcile the result with the original/current goal, update its @@ -102,7 +99,7 @@ task and RFC checkpoint when the boundary changes, and preserve passed, failed and untested distinctions. If user feedback exposes the same missing outcome, repair the owning rule, active task or projection through self-repair rather than appending stronger prose. PR review must execute the capability-owned -`problem_context` delivery judgment; author declarations do not certify it. +`problem_context` delivery judgment. ## Commit And PR Hygiene @@ -129,6 +126,10 @@ and unchanged head, and refresh the review packet (Drafts are excluded from the review queue). A reviewer must obey the packet's action authority and may not mark another author's Draft ready without authorization. Keep exact-head review, required validation, first-screen evidence and merge authorization separate. +Agents/subagents must not wait on or poll remote CI during development, review or +readiness when local gates pass (`wait_for_ci=false`); see +[local-first CI](docs/development/testing-and-quality.md#local-first-premerge-gate-vs-asynchronous-ci--本地优先门禁与异步-ci) +and [two-tier CI](docs/development/ci-impact-selection.md). ### DCO Sign-Off diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b772c03d17..c93498e0d3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -178,24 +178,32 @@ the CI, local/manual, and release-only boundaries. Only two checks block a merge: - `Sign-off`, the DCO check; -- `merge-gate`, which aggregates the Python Tests workflow. +- `merge-gate`, which aggregates the Python Tests workflow under a two-tier + lightweight-PR / heavy-nightly plan (agents and subagents do not wait on or + poll remote CI once local deterministic verification and `wait_for_ci=false` + exact-head review pass; see + [testing and quality](docs/development/testing-and-quality.md#local-first-premerge-gate-vs-asynchronous-ci--本地优先门禁与异步-ci)). `merge-gate` stays green only when these Python Tests jobs succeed or were -correctly skipped for your paths: `checks`, `pytest`, +correctly skipped for your tier/paths: `checks`, `pytest`, `node-minimum-compatibility`, `stage2c-correctness-e2e`, `windows-powershell`, -and `presentation`. The other workflows are path-filtered, advisory, or do not -run on pull requests. If an advisory workflow fails on a path you did not -touch, mention it in the PR instead of fixing it there. +and `presentation`. Normal backend PRs run fast static, contract, and TypeScript +checks while deferring unrelated browser suites and heavy matrices (6-shard +`pytest`, `node-minimum-compatibility`, `stage2c-correctness-e2e`, +`windows-powershell`) to Nightly `schedule`, `main` pushes, `merge_group`, +`ci:full` PRs, and CI-policy/manifest changes. The other workflows are +narrowly path-filtered, scheduled nightly, advisory, or manual. If an advisory +workflow fails on a path you did not touch, mention it in the PR instead of +fixing it there. | Workflow file | Runs on a PR | Blocks merge | What it checks | | --- | --- | --- | --- | -| `python-tests.yml` | every PR | yes (`merge-gate`) | lint, mypy, sharded pytest, TypeScript core and coverage, minimum Node.js, Windows PowerShell, dashboard presentation | +| `python-tests.yml` | every PR (tiered: lightweight PR vs full nightly/`main`/`merge_group`/`ci:full`) | yes (`merge-gate`) | fast lint, mypy, kernel contracts, TypeScript core/coverage on PRs; browser lanes on UI changes; full 6-shard pytest, minimum Node.js, Windows PowerShell, Stage 2C on full runs | | `dco.yml` | every PR | yes (`Sign-off`) | `Signed-off-by` on contribution commits; verified GitHub-generated two-parent merges are exempt | | `ci-maintenance.yml` | opened, reopened, edited, updated or closed PR (`pull_request_target`, trusted base code only) | no | inspects potential stale PR comparisons without mutating the head or target; cancels obsolete Python qualification runs after rechecking the PR and source branch | | `dependency-review.yml` | every PR | no | dependency changes introduced by the PR | -| `postgresql-integration.yml` | control-plane or npm lockfile paths | no | PostgreSQL authority store and service on a temporary instance | -| `package-smoke.yml` | `loopx-core` and extension package paths | no | `loopx-core` and extension packages install, entrypoints, and example schemas | -| `release-artifacts.yml` | `loopx/`, packaging, and lockfile paths | no | release identity and a release build from this source | +| `package-smoke.yml` | `packages/**`, distribution tests, extension entrypoints, and `pyproject.toml` (plus `main` push and nightly schedule) | no | `loopx-core` and extension packages install, entrypoints, and example schemas | +| `release-artifacts.yml` | release, installer, packaging metadata, and browser recovery paths (plus `release` and read-only nightly schedule) | no | release identity and a release build from this source | | `runtime-snapshots.yml` | runtime artifact, installer, and updater paths | no | qualified, revision-addressed runtime archives and the main channel pointer | | `ark-turn.yml` | Turn driver and collaboration paths | no | optional Ark Turn package, stdio MCP, and DSH parity | | `memt-turn.yml` | optional MemT package, Turn driver, lock, and packaging paths | no | explicit optional dependency installation, complete adapter workflow, stdio MCP, and driver binding | diff --git a/README.ja.md b/README.ja.md index 16fd08cfba..386c087b7c 100644 --- a/README.ja.md +++ b/README.ja.md @@ -105,8 +105,7 @@ LoopX は、永続的な作業状態を 1 つのコンパクトなレイヤー 作業を実行するのは Agent ランタイムです。LoopX は、エンジニアリング、研究、探索、 -運用のループが実行をまたいで継続できるようにするための状態を保持します。これは -新たなエージェントフレームワークでも、特定プロバイダー向けのオーケストレーションランタイムでもありません。 +運用のループが実行をまたいで継続できるようにするための状態を保持します。
詳細:コントロールレイヤーの仕組みと位置付け @@ -170,7 +169,7 @@ LoopX はそのオープンでハーネス非依存のコントロールレイ | 規模 | 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)をご覧ください | +| **エンジニアリングチームとエンタープライズへの道筋** | 対等なワーカーが todo を claim し、Desktop Workspace、GitHub、Lark を通じて共有ゴール上でレビュー済みの成果物を返します([3 エージェントのデモ](examples/collaboration-delivery/README.md)) | ワーカーのオーナーシップと人間の承認ゲートを維持します。ローカルの **File**/**SQLite** 権限およびアウトバウンド HTTPS **RemoteAuthority** クライアント契約([ワイヤー契約](loopx/control_plane/coordination/remote_authority_contract.ts))は `loopx` 内で Apache-2.0 のまま維持され、サーバーサイドの PostgreSQL 権限、分散コーディネーション、マルチテナント組織ガバナンス(RBAC、SSO、クォータ、署名付き監査)は `loopx-project/loopx-cloud` に配置されます。詳しくは[ライセンス境界](docs/project/licensing.md#open-core-and-commercial-boundaries)と[導入と SaaS のロードマップ](docs/product/roadmaps/saas-opportunity-assessment.md)をご覧ください | ## LoopX の動作を見る @@ -302,7 +301,7 @@ Todo として計画して、ホストの有効化をガイドします。アク | 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 の権限によってゲートされます | +| DeepSeek Harness (dsh) | [ネイティブの DSH プラグイン](packages/dsh-loopx-plugin/README.md)をインストールし、`loopx` スキルを選択して、タスクを記述します。ヘッドレスなターンには、引き続き [dsh goal-mode アダプター](loopx/hosts/dsh/README.md)を利用できます。 | ネイティブな同一セッション内での継続と GoalBar、またはヘッドレスな dsh セグメント。どちらも LoopX の権限によってゲートされます | | Cursor、シェル、カスタムランナー | `loopx start-goal --guided --project . --goal-text ""` を実行するか、ランナーから LoopX を呼び出します。 | お使いのシェル、スケジューラー、ランナー | そのままコピーできるセットアップメッセージとホストの復旧手順は、 @@ -311,8 +310,8 @@ Todo として計画して、ホストの有効化をガイドします。アク [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)を確認できます。 +[Kiro CLI の goal-mode アダプター](loopx/hosts/kiro_cli/README.md)、または +[DeepSeek Harness のターンアダプター](loopx/hosts/dsh/README.md)を確認できます。 ネイティブな手順については、[60 秒の DSH × LoopX Replan の録画と再現可能な フィクスチャ](docs/showcases/cases/dsh-loopx-replan-demo.md)をご覧ください: @@ -867,8 +866,7 @@ LoopX は、長時間稼働するエージェントのエコシステムを築 ## 現在のステータス LoopX は、長時間にわたるエージェントの作業のための実用的なローカルコントロールプレーンであり、 -より広い導入の段階に入りつつあります。完全なエージェントプラットフォーム、エージェントランタイム、 -自律的な本番コントローラーではありません。 +より広い導入の段階に入りつつあります。 現在の LoopX は、ゴール、型付きの todo と意思決定の スコープ、対等な claim とリース、エビデンスと writeback、クォータを考慮したスケジューリング、 diff --git a/README.md b/README.md index 7c74e0c5f7..14a89ffce2 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,10 @@ progress, decisions and verifiable results so work can continue across sessions. +https://github.com/user-attachments/assets/6d459488-4834-40ef-90bc-d6649c4f0ef1 + +

60-second overview — one sentence sets a long-horizon goal across Codex, Claude Code, Gemini & DeepSeek; LoopX keeps Todos, replanning, human sign-off, and 3% first-read session recovery verifiable across 200+ hour runs (community film by @lemomo_ai · more product recordings below).

+ --- @@ -172,7 +176,7 @@ operate 24/7 with explicit durability and human gates: | 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) | +| **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; keeps local **File**/**SQLite** authority and the outbound HTTPS **RemoteAuthority** client contract ([wire contract](loopx/control_plane/coordination/remote_authority_contract.ts)) Apache-2.0 in `loopx`, while server-side PostgreSQL authority, distributed coordination, and multi-tenant org governance—RBAC, SSO, quotas, signed audit—live in `loopx-project/loopx-cloud` ([licensing boundary](docs/project/licensing.md#open-core-and-commercial-boundaries), [adoption & SaaS roadmap](docs/product/roadmaps/saas-opportunity-assessment.md)) | ## See LoopX in Action @@ -229,6 +233,13 @@ contract](docs/reference/protocols/lark-manager-context-authority-v0.md). loopx dashboard ``` +For the optional [Workbench](apps/workbench/README.md#统一启动命令), use +`loopx workbench start`, `loopx workbench status`, and `loopx workbench stop` +after installing its separate application. These commands preserve its data and +leave independently managed Core services running. Opt in to current-user login +startup and crash recovery with `loopx workbench start --autostart` (macOS launchd +or Linux systemd); `stop --disable-autostart` removes that registration and keeps data. + `loopx dashboard` is the supported browser/PWA launch path. You can also download native desktop previews from the [current release](https://github.com/loopx-project/loopx/releases/latest); they reuse the same loopback services and Goal state. Apple Silicon macOS supports @@ -304,7 +315,7 @@ upgrades, rollback and uninstall. | ZCode | Install the skill facade with `loopx slash-commands --install --surface zcode`, then invoke the `$loopx` skill (or `/loopx `) from a ZCode session in the project. | The ZCode session's own turn loop; every continuation enters through `quota should-run` | | Antigravity CLI (agy) | Install the skill facade with `loopx slash-commands --install --surface agy`, then invoke the `loopx` skill (or `/loopx `) from an `agy` session in the project. | The session's native `/goal` loop (audited until ``) with `schedule` self-wakes while the session lives; the facade instructs every turn/wake to re-enter through `quota should-run` — advisory pacing, not a host-enforced gate | | Kiro CLI | Install the skill facade with `loopx slash-commands --install --surface kiro-cli`, then run `/loopx ` from a `kiro-cli` session in the project. | The session's native `/goal --max Done when: ` loop, with the acceptance criteria stated inside the goal statement because the host derives them from it, bounded by the host's own iteration budget (default 5) and settled through the built-in `goal` completion contract; the facade instructs every turn and iteration to re-enter through `quota should-run` — advisory pacing, not a host-enforced gate | -| DeepSeek Harness (dsh) | Install the [native DSH plugin](packages/dsh-loopx-plugin/README.md), select the `loopx` skill, and describe the task. The [dsh goal-mode adapter](loopx/dsh_goal_mode/README.md) remains available for headless turns. | Native same-session continuation and GoalBar, or headless dsh segments; both remain gated by LoopX authority | +| DeepSeek Harness (dsh) | Install the [native DSH plugin](packages/dsh-loopx-plugin/README.md), select the `loopx` skill, and describe the task. The [dsh goal-mode adapter](loopx/hosts/dsh/README.md) remains available for headless turns. | Native same-session continuation and GoalBar, or headless dsh segments; both remain gated by LoopX authority | | Cursor, shell, or custom runner | `loopx start-goal --guided --project . --goal-text ""`, or call LoopX from your runner. | Your shell, scheduler, or runner | The exact, copy-ready setup messages and host recovery paths live in @@ -313,8 +324,8 @@ the [Codex App host command registry contract](docs/reference/protocols/codex-ap the [Codex CLI packaged install path](docs/product/runtimes/codex-cli/codex-cli-packaged-install.md), the [Claude Code adapter](loopx/claude_goal_mode/README.md), the [KunlunCode native Goal adapter](loopx/kunluncode_goal_mode/README.md), the -[Kiro CLI goal-mode adapter](loopx/kiro_cli_goal_mode/README.md), or the -[DeepSeek Harness turn adapter](loopx/dsh_goal_mode/README.md). +[Kiro CLI goal-mode adapter](loopx/hosts/kiro_cli/README.md), or the +[DeepSeek Harness turn adapter](loopx/hosts/dsh/README.md). See the [60-second DSH × LoopX Replan recording and reproducible fixture](docs/showcases/cases/dsh-loopx-replan-demo.md) for the native path: @@ -390,14 +401,11 @@ benchmark's strict solved threshold. No score in this study equals 0.80, so these counts also match the study brief's >0.80 view. Against native Goal, task-level rewards improve on **23**, tie on **13**, and -regress on **10** tasks. Strict solves match Plain Codex, so the mean gain is -not a claim that every task improves or that more tasks are fully solved than -Plain. Mean reward also credits partial progress. +regress on **10** tasks. Strict solves match Plain Codex. Mean reward also credits partial progress. One effective trial per task and mode; designated replacement trials and unequal runtime/budgets, including longer budgets for some Heartbeat replacements. -These are observed system results, not an equal-budget efficiency result or -an isolated causal estimate of LoopX's effect. +These are observed system results. [Interactive results, task comparisons and methodology](https://loopx-project.github.io/loopx/benchmarks/lhtb/) · [Five-arm study and limits](benchmark/LHTB/studies/five-arm-gpt56sol-max/README.md) @@ -564,7 +572,7 @@ its own policy and authority checks before proposing a transition. | Session dash | Starts a live single-page panel that tracks fleet progress: sessions, their goals, and each goal's status/todo progress, with result statistics; auto-refreshes in place. | `loopx dash`, [session dash design](docs/product/surfaces/session-dash-panel-design.md) | | External projections | Projects todos and gates into collaboration surfaces while LoopX remains authoritative. | `loopx lark-kanban`, [Lark Kanban adapter](docs/integrations/lark-kanban-control-plane-adapter.md) | | Domain capabilities | Packages repeatable work lanes such as issue fixing, content operations, value connector planning, ML experiment advice, benchmark evidence, and Explore. | `loopx issue-fix`, `loopx content-ops`, `loopx value-connectors`, `loopx ml-experiment`, `loopx benchmark`, [Explore](loopx/capabilities/explore/README.md) | -| Experimental context learning | Lets named registered agents trial provider-neutral Reward Memory through ignored, default-off project configuration. OpenViking is one provider option, not a global dependency. | `loopx reward-memory experiment-status`, [Reward Memory architecture](loopx/capabilities/reward_memory/README.md) | +| Experimental context learning | Lets named registered agents trial provider-neutral Reward Memory through ignored, default-off project configuration. OpenViking is one provider option. | `loopx reward-memory experiment-status`, [Reward Memory architecture](loopx/capabilities/reward_memory/README.md) | | Governance patterns | Captures reusable routing, gate, evidence, projection, and planning shapes. | [interaction patterns](docs/concepts/interaction-pattern-catalog.md), [state model](docs/state-interaction-model.md) | The shipped primitives include lifetime goals, concrete user gates, audited safe @@ -583,8 +591,7 @@ signals, and public/private boundary checks. The execution path is `Agent -> Capability -> Provider`; the control path returns `Provider readback -> Capability transition -> Kernel`. An extension is -how an optional provider is packaged and managed, not another control-plane -owner. See [Architecture](docs/architecture.md) and +how an optional provider is packaged and managed. See [Architecture](docs/architecture.md) and [Extensions and Capabilities](docs/reference/extensions.md).
@@ -599,8 +606,7 @@ owner. See [Architecture](docs/architecture.md) 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. +[24/7 control plane](#always-on-agents) for agents you already run. - **Personal agent:** use the shipped Workspace and connected Lark surfaces to inspect goals, steer work and resolve decisions. The @@ -615,10 +621,9 @@ replacement for either product. [Reward Memory](loopx/capabilities/reward_memory/README.md), and evaluate candidate changes through [Explore](loopx/capabilities/explore/README.md). Both are optional. The link to **recursive self-improvement (RSI)** is the - engineering loop—propose, test, review, retain—not a claim that LoopX has - demonstrated autonomous model improvement or compounding capability gains. + engineering loop—propose, test, review, retain. -A personal steward is an interaction role, not a second source of authority. +A personal steward is an interaction role. Background execution still needs an available host and configured runtime. The [overall roadmap](docs/architecture/rfcs/loopx-overall-roadmap-v0.md) separates shipped foundations from the next end-to-end acceptance milestones. @@ -876,8 +881,7 @@ long-running agent ecosystem. Our confirmed partners include: ## Current Status LoopX is a usable local control plane for long-running agent work and is -entering broader adoption. It is not a full agent platform, an agent runtime, or -an autonomous production controller. +entering broader adoption. Today LoopX ships a durable state kernel for goals, typed todos and decision scopes, peer claims and leases, evidence and writeback, quota-aware scheduling, @@ -888,9 +892,7 @@ Workspace all build on that shared control state. Support levels remain explicit. The state and CLI contracts are the stable center; several host integrations and advanced paths are optional, default-off, -or experimental. LoopX does not grant credentials, approve destructive or -production actions, publish on a user's behalf without authorization, or turn -an unverified run into evidence of success. +or experimental. Current investment is organized through the [Technical Directions map](docs/project/technical-directions.md): long-horizon diff --git a/README.zh-CN.md b/README.zh-CN.md index 0bfad065b2..ce0f196c8c 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -18,6 +18,10 @@ +https://github.com/user-attachments/assets/eeb95ecd-6e5b-43d7-a8aa-b3d1b4449423 + +

60 秒看懂 LoopX:一句话设定长程目标,跨 Codex、Claude Code、Gemini 与 DeepSeek 分工协作、未过校验自动重规划、关键决策人类拍板、首读上下文压至 3% 跨会话续跑 200+ 小时(社区贡献者 @lemomo_ai 制作 · 更多实录演示见下文)。

+ --- @@ -94,8 +98,7 @@ LoopX 把长期控制状态留在同一层紧凑状态里: Agent runtime 负责执行,LoopX 负责治理跨运行延续的控制状态,让工程、 -研究、discovery 和运营 Loop 能持续推进。它不是又一个 agent framework,也不是 -绑定某一 Provider 的编排 runtime。 +研究、discovery 和运营 Loop 能持续推进。 @@ -149,7 +152,7 @@ LoopX 把这套**开源、Harness 中立**的控制面直接做成可运行基 | 使用形态 | 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 与审计能力平滑演进 | +| **工程团队 & 组织级扩展** | 多 Agent 认领 Todo、基于同一 Goal 经工作区 / GitHub / 飞书协同交付与互审([三 Agent 协作示例](examples/collaboration-delivery/README.md)) | 保留各自责任边界与人工审批门;本地 **File**/**SQLite** 权威及出站 HTTPS **RemoteAuthority** 客户端契约([协议契约](loopx/control_plane/coordination/remote_authority_contract.ts))在 `loopx` 中保持 Apache-2.0 开源,服务端 PostgreSQL 权威、分布式协调与多租户组织治理(RBAC、SSO、配额与签名审计)承载于 `loopx-project/loopx-cloud`(见[许可证边界](docs/project/licensing.md#open-core-and-commercial-boundaries)与[组织治理路线图](docs/product/roadmaps/saas-opportunity-assessment.zh-CN.md)) | ## 看看 LoopX 如何工作 @@ -260,7 +263,7 @@ LoopX 会复用项目已有状态或连接项目,把工作规划成 Todo,并 | ZCode | 用 `loopx slash-commands --install --surface zcode` 安装 skill facade,然后在项目里的 ZCode 会话中调用 `$loopx` skill(或 `/loopx <复杂任务>`)。 | ZCode 会话自身的 turn loop;每次续跑都从 `quota should-run` 进入 | | Antigravity CLI(agy) | 用 `loopx slash-commands --install --surface agy` 安装 skill facade,然后在项目里的 `agy` 会话中调用 `loopx` skill(或 `/loopx <复杂任务>`)。 | 会话原生 `/goal` 循环(审计至 ``)加 `schedule` 自唤醒,随会话存活;facade 指示每次 turn/唤醒都先过 `quota should-run`——advisory 节流,非宿主强制 gate | | Kiro CLI | 用 `loopx slash-commands --install --surface kiro-cli` 安装 skill facade,然后在项目里的 `kiro-cli` 会话中执行 `/loopx <复杂任务>`。 | 会话原生 `/goal --max <任务> Done when: <验收条件>` 循环,验收条件写入目标语句本身(宿主由该语句推导验收标准),由宿主自己的迭代预算兜底(默认 5),并通过内置 `goal` 完成契约收口;facade 指示每次 turn 与迭代都先过 `quota should-run`——advisory 节流,非宿主强制 gate | -| DeepSeek Harness(dsh) | 安装 [DSH 原生 Plugin](packages/dsh-loopx-plugin/README.md),在技能选择器中点 `loopx`,然后直接描述任务;[dsh goal-mode adapter](loopx/dsh_goal_mode/README.md) 继续支持 headless turn。 | 原生同会话续跑与 GoalBar,或 headless dsh 工作段;两条路径都遵守 LoopX authority | +| DeepSeek Harness(dsh) | 安装 [DSH 原生 Plugin](packages/dsh-loopx-plugin/README.md),在技能选择器中点 `loopx`,然后直接描述任务;[dsh goal-mode adapter](loopx/hosts/dsh/README.md) 继续支持 headless turn。 | 原生同会话续跑与 GoalBar,或 headless dsh 工作段;两条路径都遵守 LoopX authority | | Cursor、shell、自有 runner | `loopx start-goal --guided --project . --goal-text "<任务>"`,或由你的 runner 调用 LoopX。 | 你的 shell、scheduler 或 runner | 可直接粘贴的完整 setup message、host-specific 路由和故障恢复见 @@ -269,8 +272,8 @@ LoopX 会复用项目已有状态或连接项目,把工作规划成 Todo,并 [Codex CLI packaged install](docs/product/runtimes/codex-cli/codex-cli-packaged-install.md)和 [Claude Code adapter](loopx/claude_goal_mode/README.md)、 [KunlunCode 原生 Goal adapter](docs/guides/kunluncode-adapter.zh-CN.md)、 -[Kiro CLI goal-mode adapter](loopx/kiro_cli_goal_mode/README.md),以及 -[DeepSeek Harness turn adapter](loopx/dsh_goal_mode/README.md)。 +[Kiro CLI goal-mode adapter](loopx/hosts/kiro_cli/README.md),以及 +[DeepSeek Harness turn adapter](loopx/hosts/dsh/README.md)。 可查看 [60 秒 DSH × LoopX Replan 真实录屏和可复现 fixture](docs/showcases/cases/dsh-loopx-replan-demo.md):安装 Plugin、选择一个 @@ -340,12 +343,10 @@ loopx doctor 本组没有恰好等于 0.80 的分数,因此这里的计数与研究简报的 >0.80 一致。 相对原生 Goal,逐题 Reward **23 胜、13 平、10 负**。 -严格通过题数与 Plain Codex 相同;平均 Reward 也计入部分完成的得分, -因此均分提升不代表每题都改善,也不代表比 Plain 完整解决了更多任务。 +严格通过题数与 Plain Codex 相同;平均 Reward 也计入部分完成的得分。 每个任务、每种模式仅一条有效轨迹;包含指定替代运行,运行时与预算不完全相同, -部分 Heartbeat 替代运行使用了更长预算。这是观测到的系统结果, -不是等预算效率结论,也未单独识别 LoopX 的因果增益。 +部分 Heartbeat 替代运行使用了更长预算。这是观测到的系统结果。 [交互结果、逐题对比与方法](https://loopx-project.github.io/loopx/benchmarks/lhtb/?lang=zh) · [五臂研究与边界](benchmark/LHTB/studies/five-arm-gpt56sol-max/README.md) @@ -473,7 +474,7 @@ Kernel 把控制面归结为五个用户可以直接行动的问题。每个问 架构、控制面能力与运行责任 LoopX 显式保留架构边界,使同一个受治理结果在更换 Agent harness 或外部 Provider -后仍然成立。以下术语描述的是不同边界,而不是几种可以互换的插件: +后仍然成立。以下术语描述的是不同边界: | 边界 | 含义 | 深入阅读 | | --- | --- | --- | @@ -483,7 +484,7 @@ LoopX 显式保留架构边界,使同一个受治理结果在更换 Agent harn | **Extension** | 通过显式安装、readiness、启用、升级、停用和回滚生命周期交付可选 Provider。 | [Extension 生命周期](docs/reference/extensions.md#runtime-lifecycle) | `--available-capability shell` 等 host 声明描述的是已观测到的执行支持;在这张 -产品图里属于 runtime capacity,不是产品 Capability,也不授予权限。真正执行前, +产品图里属于 runtime capacity。真正执行前, Capability 仍须应用自己的 policy 和 authority check,再提出 typed transition。 ### 控制面能力 @@ -496,7 +497,7 @@ Capability 仍须应用自己的 policy 和 authority check,再提出 typed tr | Operator surface | 呈现紧凑状态,但不让浏览器成为状态事实源。 | `loopx serve-status`、[Dashboard](apps/presentation/dashboard/README.md) | | External projection | 把 todo / gate 投影到协作表面,同时保持 LoopX 权威。 | `loopx lark-kanban`、[Lark Kanban adapter](docs/integrations/lark-kanban-control-plane-adapter.md) | | Domain capability | 打包 Issue Fix、内容运营、value connector、ML 实验、benchmark 与 Explore 等可重复泳道。 | `loopx issue-fix`、`loopx content-ops`、`loopx value-connectors`、`loopx ml-experiment`、`loopx benchmark`、[Explore](loopx/capabilities/explore/README.md) | -| 实验性上下文学习 | 通过 ignored、默认关闭的项目配置,为明确注册的 agent 试用 provider-neutral Reward Memory;OpenViking 是 provider 之一,不是全局依赖。 | `loopx reward-memory experiment-status`、[Reward Memory 中文架构](loopx/capabilities/reward_memory/README.zh-CN.md) | +| 实验性上下文学习 | 通过 ignored、默认关闭的项目配置,为明确注册的 agent 试用 provider-neutral Reward Memory;OpenViking 是 provider 之一。 | `loopx reward-memory experiment-status`、[Reward Memory 中文架构](loopx/capabilities/reward_memory/README.zh-CN.md) | | Governance pattern | 沉淀可复用的 routing、gate、evidence、projection 和 planning 形状。 | [Interaction Pattern Catalog](docs/concepts/interaction-pattern-catalog.md)、[State Model](docs/state-interaction-model.md) | 这些能力共同提供 lifetime goal、具体 user gate、经过审计的安全侧路、平级 todo @@ -514,7 +515,7 @@ ownership、quota 与 steering、紧凑 run history、证据化 handoff、read-f 执行路径是 `Agent -> Capability -> Provider`,控制结果沿 `Provider readback -> Capability transition -> Kernel` 返回。Extension 负责可选 -provider 的打包和生命周期,不是另一个控制面 owner。详见 +provider 的打包和生命周期。详见 [核心架构](docs/architecture.md)与 [Extension / Capability 参考](docs/reference/extensions.md)。 @@ -529,8 +530,7 @@ provider 的打包和生命周期,不是另一个控制面 owner。详见 [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, -而不是提供这两款托管产品的等价替代。 +选择的是开放、Provider-neutral 的[7×24 控制面](#always-on-agents)路线,连接你已经在用的 Agent。 - **个人 Agent:**通过已发布的工作区与关联飞书入口查看目标、调整方向、处理决策。 [常驻管家与语义交接 RFC](docs/architecture/rfcs/capable-manager-semantic-handoff-v0.zh-CN.md) @@ -541,9 +541,9 @@ provider 的打包和生命周期,不是另一个控制面 owner。详见 - **自我改进:**用 [Reward Memory](loopx/capabilities/reward_memory/README.md) 将反馈带入下一次尝试,用 [Explore](loopx/capabilities/explore/README.md) 评估候选改动, 两者均按需启用。与 **RSI(递归自我改进)** 的交集在于“提出改动—验证—审阅—保留”的 - 工程闭环,而不是宣称 LoopX 已实现模型自主升级或能力递归增长。 + 工程闭环。 -个人管家是一种交互角色,不是另一套状态权威。后台执行仍需要可用的主机和已配置的运行时。 +个人管家是一种交互角色。后台执行仍需要可用的主机和已配置的运行时。 [整体路线图](docs/architecture/rfcs/loopx-overall-roadmap-v0.zh-CN.md) 区分了已交付的基础与下一步需要验收的端到端能力。 @@ -665,8 +665,7 @@ loopx check \ ## 当前技术方向 -LoopX 当前有三个活跃战略计划和一个架构与研究孵化器。这些内容用于表达方向, -不是交付承诺;`main`、已发布 artifact 和 stable reference contract 仍然定义真实 +LoopX 当前有三个活跃战略计划和一个架构与研究孵化器。这些内容用于表达方向;`main`、已发布 artifact 和 stable reference contract 仍然定义真实 已交付行为。 - **长程 Benchmark 与证据:**在互补 benchmark 环境中建立可复现的能力证据, @@ -677,8 +676,7 @@ LoopX 当前有三个活跃战略计划和一个架构与研究孵化器。这 旅程仍在验收,由 `@maxliux5` 作为 implementation lead。 [方向 Tracker](https://github.com/loopx-project/loopx/issues/3244) - **Shared Goal Authority 与跨 Host 协作:**为显式共享 goal 提供 - provider-neutral 协调;NoKV 是尚未晋级的 provider candidate,而不是新的控制面 - 权威。 + provider-neutral 协调;NoKV 是尚未晋级的 provider candidate。 [方向 Tracker](https://github.com/loopx-project/loopx/issues/3245) - **架构与研究孵化器:**以明确不同的成熟度推进 Effect Program hardening、 TypeScript parity migration、hierarchical stride、research exploration、human @@ -775,7 +773,6 @@ LoopX 欢迎与其他开源项目协作,共建长程 Agent 生态。已确认 ## 当前状态 LoopX 已经是一套可用的长程 Agent 本地控制面,正在进入更广泛的采用阶段。 -LoopX 不是完整 agent platform,不是 agent runtime,也不是自治生产控制器。 目前 LoopX 已交付围绕 goal、typed todo / decision scope、平级 claim / lease、 evidence / writeback、quota-aware scheduling 和跨轮 continuation 的 durable state diff --git a/apps/desktop/loopx-control-plane/README.md b/apps/desktop/loopx-control-plane/README.md index deac5411c4..bd41f618c2 100644 --- a/apps/desktop/loopx-control-plane/README.md +++ b/apps/desktop/loopx-control-plane/README.md @@ -315,8 +315,23 @@ shell, and a shell update does not certify Goal acceptance or provider readiness The release workflow packages both layers from one Git revision. The installer and App-owned services use the same bounded tool search, -including standard Homebrew locations on macOS, without loading interactive -shell profiles. Finder launches therefore do not depend on terminal PATH setup. +including standard Homebrew locations on macOS and nvm-managed Node +directories on Unix, without loading interactive shell profiles. Finder +launches therefore do not depend on terminal PATH setup. nvm resolution is +read-only and never runs nvm or sources a startup file. An `NVM_BIN` the +launching shell exported keeps the first position only while the inherited PATH +resolves the same Node; a PATH that resolves no Node is not evidence the shell +still selects that version, so a residual variable — left by a launchd plist or +an earlier shell — drops to the last resort, behind Homebrew, the inherited +PATH and every discovered nvm location. nvm +locations this App discovers on disk — the recorded `default` alias, then the +installed versions newest-first — are appended behind Homebrew and the +inherited PATH, so an inferred stale default cannot displace a Node the host +already provides, while a host whose only Node is nvm-managed still gets one. +Within those inferred locations the recorded `default` leads only while it +meets the supported Node floor; otherwise the newest installed version that +does is promoted ahead of it, so an old default never hides a newer supported +Node from Core's qualification. Each directory appears once in the search. When preparing the first App-owned snapshot, an already selected managed CLI's recorded Python is reused if the App has no interpreter record of its own. This leaves that CLI's launcher and installation owner unchanged. @@ -498,12 +513,284 @@ Self-service: serves your terminal runtime) checks that host's installation. It cannot diagnose this Mac App's local bootstrap; only the App's own diagnostics do. +### Fresh Mac without a usable Node.js stays on the boot screen + +The App's automatic runtime installation can also fail with +`runtime_install_exit_1` when no usable Node.js is reachable: the candidate's +`doctor --deep --installation-only` validation treats the managed TypeScript +Effect runtime as required, and it fails closed while `node` is missing or +older than the required minimum. The App does not bundle Node; Node.js 22.22.3 +or newer is required and 24 LTS is recommended, matching the CLI installation +guide. + +The installer and the owned services resolve `node` through one bounded search +path, in this order: `~/.local/bin`, an `NVM_BIN` the inherited PATH still +selects, `/opt/homebrew/bin`, `/usr/local/bin`, the Homebrew keg-only +`node@24` and `node@22` prefixes, the inherited process PATH, and last the nvm +installations found on disk. Finder does not load the interactive shell +profile, so a Node that only fnm or volta puts on the shell PATH stays +invisible to the App even though it works in a terminal. + +Self-service: + +1. Check the boot screen error code or Recovery & updates → Diagnostics + (`error_code: runtime_install_exit_1`, then `environment.node_found` and + `node_version`). The boot screen names the missing Node.js only when + `node_found` is `false`, so read the version from Diagnostics. +2. `node_found` is `false`: no `node` is reachable. Install Node.js 22.22.3+, + for example `brew install node` (the keg-only `brew install node@24` is + also covered by the search path) or via the official nodejs.org installer. + An fnm/volta installation needs a plain installation or a `~/.local/bin` + symlink the App can resolve. +3. `node_found` is `true` with a `node_version` older than 22.22.3: the App + reaches a Node that is too old, and Core reports the same + `node_unavailable`. Installing another version does not fix this by itself. + The App runs the `node` from the first search path entry that holds one, + for example a `~/.local/bin/node` ahead of every Homebrew location, and + Diagnostics report the version but not the path. Check that order, then + update the winning entry. Point it at a supported Node you have confirmed, + such as `/opt/homebrew/opt/node@24/bin/node` after `brew install node@24` + (`/usr/local/opt/node@24/bin/node` with Intel Homebrew) or the path your own + supported Node is installed at, and keep the old file. Do not use `ln -sf` + on its own: it succeeds even when its target is missing and leaves a + dangling link in place of the original. + + Run the block below in one Terminal window; every line is chained, so the + sequence stops before anything is moved when the candidate is missing or + older than 22.22.3. `--version` prints the candidate for you to read, and + the third line re-checks the same version numerically. + + ```bash + ( + node= && + node_qualifies() { + normalized="$(node_trim "$1")" + case "$normalized" in + '' | *$'\n'* | *$'\r'*) return 1 ;; + esac + printf '%s\n' "$normalized" | grep -Eq '^v?[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$' || return 1 + printf '%s\n' "$normalized" | awk ' + { + sub(/^v/, "") + n = split($0, a, /[.+-]/) + if (n < 3) exit 1 + maj = a[1] + 0; min = a[2] + 0; pat = a[3] + 0 + if (maj < 22) exit 1 + if (maj == 22 && min < 22) exit 1 + if (maj == 22 && min == 22 && pat < 3) exit 1 + if (maj == 22 && min == 22 && pat == 3) { + plus = index($0, "+") + dash = index($0, "-") + if (dash > 0 && (plus == 0 || dash < plus)) exit 1 + } + exit 0 + }' + } + node_trim() { + n="${1#"${1%%[![:space:]]*}"}" + printf '%s' "${n%"${n##*[![:space:]]}"}" + } + "$node" --version && + raw_ver="$("$node" --version)" && + node_ver="$(node_trim "$raw_ver")" && + node_qualifies "$node_ver" && + node="$(cd "$(dirname "$node")" && pwd)/$(basename "$node")" && + raw_ver="$("$node" --version)" && + node_ver="$(node_trim "$raw_ver")" && + node_qualifies "$node_ver" && + mkdir -p ~/.local/bin && + lock=~/.local/bin/.node-loopx-repair && + if mkdir "$lock" 2>/dev/null; then + lock_ino="$(stat -f %i "$lock")" && + trap 'if [ "$(stat -f %i "$lock" 2>/dev/null)" = "$lock_ino" ]; then rm -rf "$lock"; fi' EXIT + else + echo "Another repair is in progress; nothing was changed." && + echo "If no repair is actually running, remove $lock by hand and run this again." && + exit 1 + fi && + backup=~/.local/bin/node.before-loopx."$(date +%Y%m%d-%H%M%S)" && + if [ -e ~/.local/bin/node ] || [ -L ~/.local/bin/node ]; then + mkdir "$backup" && + mv ~/.local/bin/node "$backup/node" && + if ln -s "$node" ~/.local/bin/node && + installed_ino="$(stat -f %i ~/.local/bin/node)" && + installed_raw="$("$HOME/.local/bin/node" --version)" && + installed_ver="$(node_trim "$installed_raw")" && + node_qualifies "$installed_ver"; then + echo "Node launcher updated to $node (previous entry kept in $backup)" + else + # restore only when nothing else owns the entry: absent, or still + # this operation's own link; a later window's swap stays in place + if { [ ! -e ~/.local/bin/node ] && [ ! -L ~/.local/bin/node ]; } || + [ "$(stat -f %i ~/.local/bin/node 2>/dev/null)" = "$installed_ino" ]; then + mv "$backup/node" ~/.local/bin/node && + rmdir "$backup" && + echo "The candidate failed the final check; the original launcher was restored." + else + echo "The candidate failed the final check; a newer launcher from another repair was kept, and the previous launcher is still in $backup." + fi && + exit 1 + fi + else + if ln -s "$node" ~/.local/bin/node; then + created_ino="$(stat -f %i ~/.local/bin/node)" && + if installed_raw="$("$HOME/.local/bin/node" --version)" && + installed_ver="$(node_trim "$installed_raw")" && + node_qualifies "$installed_ver"; then + echo "Node launcher created at ~/.local/bin/node (remove the link to undo)" + else + # undo only when the entry is still this operation's own link; a + # later window's swap has a different inode and stays in place + if [ "$(stat -f %i ~/.local/bin/node 2>/dev/null)" = "$created_ino" ]; then + rm -f ~/.local/bin/node + fi && + echo "The candidate failed the final check; nothing was changed." && + exit 1 + fi + else + # the entry already exists: another window's successful repair owns it + echo "Another repair created the launcher; nothing was changed." && + exit 1 + fi + fi + ) + ``` + + `node_trim` follows `probe_node()`'s boundary handling: it removes the + leading and trailing whitespace of the whole captured output — including + CRLF endings and blank leading lines — and leaves every interior + character alone, so an interior carriage return fails the shape check + exactly as it fails Core's fullmatch. `node_qualifies` is the single + version judgment shared by the candidate and the installed link: the + normalized output must be exactly one `v?[maj.min.pat]` line with an + optional prerelease after `-` and an optional build after `+`; malformed + fields or missing segments fail. The base triple must reach 22.22.3, and + a base sitting exactly on the minimum is rejected when a prerelease is + present, while `22.22.3+build-5`, whose hyphen belongs to the build + metadata, still qualifies. The installed link is qualified through the + same function after the swap; the failure branches above are the undo + paths, and the `--version` lines remain as the readback prints. When + `~/.local/bin/node` does not exist yet — an nvm-managed old Node can be + first in the search order with no local launcher — the first-creation + branch creates the link; its `ln` failure means another window's repair + already created and qualified one, and that entry is left in place. + + The whole repair runs inside one lock inside its own subshell. The block + takes `~/.local/bin/.node-loopx-repair` with an exclusive `mkdir` before + either branch and releases the lock when that subshell exits. The repair + therefore never closes your terminal, not even when a check fails, any + EXIT hook you had registered stays yours, and a second window stops with + "Another repair is in progress; nothing was changed." instead of + interleaving its move, install, final check or rollback between this + window's steps. Rerun the block after the other window finishes. There is + no automatic takeover: a repair interrupted without its cleanup — its + subshell killed outright — leaves the lock in place and every later + attempt stops with the message above. When nothing is actually running + (check with `ps` that no repair shell remains), remove that directory by + hand and run the block again. The cleanup is instance-targeted: it + removes the lock only while the directory is still the instance this + repair created — a lock a later window acquired after your manual removal + has a different inode and survives this repair's exit. The launcher-entry + inode checks in the two branches guard the rollback the same way. + + The backup is a directory created atomically: a second repair in the same + second (from this window or another one) fails its `mkdir` and stops with + the original launcher untouched, so concurrent attempts cannot overwrite + each other's only copy of the original. Each attempt owns one directory + holding the launcher it replaced. The failure rollback respects the same + ownership: the original is moved back only while the entry is still absent + or still the failed attempt's own link — a later window's verified launcher + has a different inode and stays in place, and the failed attempt keeps its + backup for the manual restore below. + + To restore a backup, replace the launcher directory entry in the way that + preserves the backup's own entry type, and never copy through the current + link — `cp` would follow it and rewrite the supported Node binary that + other tools share. The restore takes the same lock as the repair below, + so it stops while a repair is running and cannot replace a launcher that + another window is still checking; the same ps-confirmed manual removal + applies if a lock was left by an interrupted repair. A missing launcher + is a recoverable state too: an interrupted repair leaves only the + backup, and `rm -f` accepts that. + + ```bash + ( + mkdir -p ~/.local/bin && + lock=~/.local/bin/.node-loopx-repair && + if mkdir "$lock" 2>/dev/null; then + lock_ino="$(stat -f %i "$lock")" && + trap 'if [ "$(stat -f %i "$lock" 2>/dev/null)" = "$lock_ino" ]; then rm -rf "$lock"; fi' EXIT + else + echo "Another repair is in progress; nothing was changed." && + echo "If no repair is actually running, remove $lock by hand and run this again." && + exit 1 + fi && + newest=$(ls -td ~/.local/bin/node.before-loopx.* 2>/dev/null | head -1) && + [ -n "$newest" ] && + staged=~/.local/bin/node.restored."$(date +%Y%m%d-%H%M%S)" && + if [ -d "$newest" ]; then src="$newest/node"; else src="$newest"; fi && + if [ -L "$src" ]; then + ln -s "$(readlink "$src")" "$staged" + else + cp "$src" "$staged" + fi && + "$staged" --version && + rm -f ~/.local/bin/node && + mv "$staged" ~/.local/bin/node && + shasum ~/.local/bin/node + ) + ``` + + The restore builds the restored entry beside the launcher first, so a + backup symlink's raw value is recreated where the original launcher lived + and a relative link resolves exactly as it did before the repair; the + `--version` line then qualifies that entry where it will live. Only after + that does the sequence remove the current launcher and move the staged + entry into place. If no backup exists, the newest one is empty — an + interrupted repair leaves exactly that — or its entry cannot run, the + chain stops with the working launcher still in place and a `node.restored-*` + scratch entry to delete. If the newest backup is unusable but an older one + is complete, restore that older one by naming it instead of `newest`. + + The backup keeps the launcher's own entry type and raw link value: a + symlink is recreated with its original target string at the original + location, so a relative link resolves exactly as it did before the repair + and a later version-manager update of its target is still followed; a + regular file is copied byte for byte. The final `shasum` reads the + restored entry through its route and is the readback that the original + routing works again. Removing the current entry before the copy is what + keeps the supported Node binary safe — nothing writes through the link + into a binary other tools share. To double-check the candidate itself, + checksum the path you chose as ``; the restore + never writes to it. + + `node_found` of `true` with no `node_version` means the App found a `node` + it could not read a version from: inspect that entry with `ls -l` and the + same `--version` call before replacing it the same way. +4. Confirm the result through the repair block's own readback. The repair + qualifies the actual hit entry: its `--version` must exit 0, the raw + version must satisfy the floor — a plain 22.22.3, build metadata, or a + prerelease above the floor all qualify — and Core's `probe_node()` then + reads the same binary as `ready`. A blank `node_version` in Diagnostics + is the App's numeric display gap, not a qualification failure: when the + repair printed its success line, or the message that a newer launcher + from another repair was kept, press **Repair this version**; when it + printed the restore message, follow the earlier replace-or-restore steps + instead. The environment reading refreshes every 30 seconds, or reopen + the App. `node --version` in a terminal only verifies the interactive + shell, which can select a Node the App does not. +5. Press **Repair this version** (or reopen the App); the environment probe + refreshes and the live supervisor reconnects the same window without a + second App restart. + The updater accepts only fixed official HTTPS channels, not browser-provided -commands, paths or download URLs. Its signing private key is confined to the -release secret; the App embeds the public key. PR validation has no signing -secret. Updater signing does not provide Apple notarization. It also does not -change Goal authority, grant capabilities, or stop running agents on behalf of -the user. Services may briefly disconnect during reconciliation. +commands, paths or download URLs. Its minisign private key +(`TAURI_SIGNING_PRIVATE_KEY`) is confined to the release secret; the App embeds +the public key. PR validation has no signing secret and keeps `--no-sign` +preview builds. Updater minisign signing is distinct from Apple Developer ID +signing and notarization; it also does not change Goal authority, grant +capabilities, or stop running agents on behalf of the user. Services may +briefly disconnect during reconciliation. The background feed check has a thirty-second deadline and is outside local workspace startup. A manual **Check for updates** allows 45 seconds for the same @@ -513,10 +800,45 @@ A timeout remains an explicit retryable error, never a claim that the App is current. Archive downloads use the separate connection, idle-read and total deadlines described above. Installation and recovery boundaries are unchanged. -Published macOS preview artifacts use ad-hoc code signing to verify bundle -integrity without requiring an Apple Developer account. They are not signed -with a Developer ID and are not notarized, so macOS may require the operator -to approve the first launch in System Settings > Privacy & Security. +On non-PR official macOS builds (`desktop-release-artifacts.yml` and +`desktop-updater.yml`), signing and notarization depend on the five core Apple +secrets (`APPLE_CERTIFICATE`, `APPLE_CERTIFICATE_PASSWORD`, `APPLE_ID`, +`APPLE_PASSWORD`, `APPLE_TEAM_ID`; plus optional `KEYCHAIN_PASSWORD`, which +defaults to an ephemeral random password per build if unset, and optional +`APPLE_SIGNING_IDENTITY`): + +- **Developer ID + Apple Notarization (all 5 core secrets set):** Tauri signs + `LoopX.app` with Developer ID Application and Hardened Runtime, notarizes and + staples `LoopX.app` before zipping `LoopX.app.zip` or packing the updater's + `.app.tar.gz`, and the release workflow notarizes and staples the `.dmg` with + `xcrun notarytool` / `xcrun stapler`. Both `.app` and `.dmg` are verified with + `codesign --verify --deep --strict`, `Authority=Developer ID Application:`, + `spctl --assess`, `xcrun stapler validate`, and `hdiutil verify`. +- **Ad-hoc integrity signing (all 5 core secrets unset):** Non-PR builds keep + `"signingIdentity": "-"` (`Signature=adhoc` verified via + `codesign --verify --deep --strict` and `hdiutil verify`). Partial + configurations (1–4 of 5 core secrets) fail closed instead of downgrading. +- **Updater signature compatibility across transitions:** `src-tauri` verifies + updater archives with the embedded minisign key and validates both staged + candidates and rollback backups with `codesign --verify --deep --strict` + (`installed_bundle_verifies` / `replace_bundle`), with no ad-hoc-only check. + Existing ad-hoc installations can upgrade in-app to Developer ID + notarized + releases (and between Developer ID releases) through the normal updater flow. + +When running an ad-hoc-signed or unsigned preview build on macOS Sequoia 15+, +Gatekeeper's initial dialog offers **Move to Trash** by default instead of an +inline **Open Anyway** button. Do not click **Move to Trash**; approve the first +launch using either option below: + +1. Click **Done** to dismiss the Gatekeeper dialog, open **System Settings → + Privacy & Security**, scroll to the Security section, click **Open Anyway** + next to the `LoopX` prompt, and confirm launch. +2. Or, after verifying the download against `DESKTOP-SHA256SUMS`, clear the + quarantine attribute in Terminal: + + ```bash + xattr -dr com.apple.quarantine /Applications/LoopX.app + ``` ## Runtime Model @@ -606,7 +928,10 @@ Session 与委派受众保持不变,不混合不同私聊或扩大权限。借 - A working Python interpreter for runtime installation; existing managed installations preserve their interpreter. Windows requires a separately installed LoopX CLI. Set `LOOPX_BIN` only for deliberate runtime overrides. -- Node.js 20.19+ or 22.12+ for dashboard builds. +- Node.js 22.22.3 or newer (24 LTS recommended) for the managed TypeScript + runtime the installed App bootstraps; Node.js 20.19+ or 22.12+ only covers + dashboard builds. See Known Issues when a fresh Mac stops on the boot screen + without it. - Rust stable and the platform-specific Tauri build dependencies. Linux requires WebKitGTK 4.1 and GTK 3 development packages. See the @@ -824,8 +1149,11 @@ comparison; they do not certify an installed update or an executing task's recov `src-tauri/target/release/bundle/`. The release workflow builds macOS `.dmg` and `.app.zip` artifacts on macOS, Windows `.msi` and `.exe` artifacts on Windows, and uploads them to the GitHub Release that triggered the workflow. -It verifies the ad-hoc macOS app signature and disk-image integrity before -upload. A separate `DESKTOP-SHA256SUMS` manifest covers all desktop artifacts +When the Apple signing and notarization secrets are configured, it verifies +Developer ID signing, Gatekeeper assessment (`spctl`), stapled notarization +tickets (`xcrun stapler validate`), and disk-image integrity before upload; +when all five core Apple secrets are unset, it verifies the ad-hoc macOS app +signature and disk-image integrity instead. A separate `DESKTOP-SHA256SUMS` manifest covers all desktop artifacts attached by the workflow, and release builds use the Git tag as the desktop bundle version. A manual rerun for an existing tag is an explicit full desktop republish: it rebuilds both macOS and Windows assets, preserves the previous diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/bundled_runtime.rs b/apps/desktop/loopx-control-plane/src-tauri/src/bundled_runtime.rs index 858eb610e7..0d9b551942 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/bundled_runtime.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/bundled_runtime.rs @@ -21,9 +21,11 @@ pub fn identity(app: &AppHandle) -> Result { fn identity_at(resources: &Path) -> Result { let path = resources.join("runtime/identity.json"); - let value: Value = - serde_json::from_slice(&fs::read(path).map_err(|_| "runtime_bundle_missing")?) - .map_err(|_| "runtime_bundle_invalid")?; + parse_identity(&fs::read(path).map_err(|_| "runtime_bundle_missing")?) +} + +pub(crate) fn parse_identity(bytes: &[u8]) -> Result { + let value: Value = serde_json::from_slice(bytes).map_err(|_| "runtime_bundle_invalid")?; if value["schema_version"] != "desktop_runtime_bundle_v1" || !value["source_revision"] .as_str() diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/macos_update.rs b/apps/desktop/loopx-control-plane/src-tauri/src/macos_update.rs index 4a876cbb2b..3ee168e9c4 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/macos_update.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/macos_update.rs @@ -3,13 +3,49 @@ //! the existing updater. This is only its macOS filesystem effect adapter. use std::{ fs, - io::{self, Cursor}, + io::{self, Cursor, Read}, path::{Component, Path}, }; use flate2::read::GzDecoder; +use serde_json::Value; use tauri_plugin_updater::Update; +const PUBLIC_DEFAULT_CONTRACT: &str = + include_str!("../../../../../loopx/cli_commands/public_default_contract.json"); + +/// Read the publisher's observed contract inside the signature-verified bytes +/// before an update can be cached, close the workspace, or replace its App. +pub(crate) fn qualify_candidate(verified_bytes: &[u8]) -> Result<(), String> { + let invalid = "runtime_bundle_invalid"; + let unavailable = "update_platform_unavailable"; + let current: Value = serde_json::from_str(PUBLIC_DEFAULT_CONTRACT).map_err(|_| invalid)?; + let identity_path = Path::new("LoopX.app/Contents/Resources/runtime/identity.json"); + let mut archive = tar::Archive::new(GzDecoder::new(Cursor::new(verified_bytes))); + let mut qualified = false; + for entry in archive.entries().map_err(|_| invalid)? { + let mut entry = entry.map_err(|_| invalid)?; + if entry.path().map_err(|_| invalid)? != identity_path { + continue; + } + if qualified || !entry.header().entry_type().is_file() || entry.size() > 16 * 1024 { + return Err(invalid.into()); + } + let mut raw = Vec::new(); + entry.read_to_end(&mut raw).map_err(|_| invalid)?; + let identity = crate::bundled_runtime::parse_identity(&raw)?; + let observed = identity + .get("default_contract") + .filter(|contract| contract.is_object()) + .ok_or(unavailable)?; + if observed != ¤t { + return Err(unavailable.into()); + } + qualified = true; + } + qualified.then_some(()).ok_or_else(|| unavailable.into()) +} + // Provider-local errors, never a new persisted or caller-facing vocabulary. #[derive(Debug, PartialEq)] enum InstallError { @@ -132,6 +168,63 @@ mod tests { builder.into_inner().unwrap().finish().unwrap() } + #[test] + fn only_qualified_runtime_can_replace_a_prepared_candidate() { + let root = tempfile::tempdir().unwrap(); + let candidate = root.path().join("candidate"); + let resources = candidate.join("Contents/Resources/runtime"); + fs::create_dir_all(&resources).unwrap(); + let cache = root.path().join("prepared"); + let channels = [("main", "0.0.0-main.2.1"), ("stable", "2.4.1")]; + let identity_path = resources.join("identity.json"); + let mut identity = serde_json::json!({ + "schema_version": "desktop_runtime_bundle_v1", + "source_revision": "1111111111111111111111111111111111111111" + }); + let rejected = [ + None, + Some(serde_json::json!({"surface": "unknown"})), + Some(serde_json::json!({ + "surface": "quota_packet", + "schema_version": null, + "interaction_schema_version": "loopx_interaction_contract_v0" + })), + Some(serde_json::json!({ + "surface": "complete_turn", + "schema_version": "loopx_turn_envelope_v0", + "interaction_schema_version": "loopx_interaction_contract_v0" + })), + ]; + for contract in rejected { + if let Some(contract) = contract { + identity["default_contract"] = contract; + } + fs::write(&identity_path, identity.to_string()).unwrap(); + let bytes = archive(&candidate); + for (channel, version) in channels { + assert_eq!( + crate::prepared_update::save(&cache, channel, version, "unused", &bytes), + Err("update_platform_unavailable".into()) + ); + } + assert!(!cache.exists()); + } + + identity["default_contract"] = serde_json::json!({ + "surface": "complete_turn", + "schema_version": "loopx_turn_envelope_v1", + "interaction_schema_version": "loopx_interaction_contract_v0" + }); + fs::write(&identity_path, identity.to_string()).unwrap(); + let bytes = archive(&candidate); + for (channel, version) in channels { + crate::prepared_update::save(&cache, channel, version, "unused", &bytes).unwrap(); + } + let pointer = fs::read(cache.join("prepared.json")).unwrap(); + assert!(crate::prepared_update::save(&cache, "stable", "2.4.1", "unused", b"bad").is_err()); + assert_eq!(fs::read(cache.join("prepared.json")).unwrap(), pointer); + } + #[test] fn verified_candidate_replaces_app_and_retains_intact_previous_bundle() { let root = tempfile::tempdir().unwrap(); 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 09b438f266..40eb9aa70f 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/maintenance.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/maintenance.rs @@ -896,14 +896,25 @@ async fn perform( let bytes = if let Some(cached) = cached { cached.bytes } else { - download_update(&update, |chunk, total| { + let bytes = download_update(&update, |chunk, total| { received += chunk as u64; state.publish( "downloading", json!({"received":received,"total":total,"version":update.version}), ); }) - .await? + .await?; + #[cfg(target_os = "macos")] + { + tauri::async_runtime::spawn_blocking(move || { + crate::macos_update::qualify_candidate(&bytes)?; + Ok::<_, String>(bytes) + }) + .await + .map_err(|_| "runtime_bundle_invalid".to_string())?? + } + #[cfg(not(target_os = "macos"))] + bytes }; let target = update.version.clone(); install_verified_app(app, target, move || { 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 189670e541..68ffa9fda6 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 @@ -1,20 +1,31 @@ //! Real HTTP and the shipped updater/signature verifier; no App installation, //! Core service, credentials or external network. Only the window runtime is fake. use super::*; +use base64::{engine::general_purpose::STANDARD, Engine}; use std::{ io::{Read, Write}, net::{TcpListener, TcpStream}, sync::{ atomic::{AtomicBool, AtomicUsize}, - Arc, + Arc, LazyLock, }, }; -const BODY: &[u8] = b"LoopX synthetic signed update transport fixture. No install or runtime.\n"; +const BODY_B64: &str = "H4sIAAAAAAAA/+3SzWoDIRQF4DzK4DpkHBgSyLbbrrrKToxzQ20dFf9oKXn3mum0lECh00Xbxfk2il49gvfWOX/YSO/bG2cT2RTbO4ouB0WxDdkmPVKrh7qh0/PmITq7WoxX276fxup65D3vPubTerfrd9tVw5dHLZdjkqFpfiPqP3phUd3TKEWhELWzbM8Gio/JeTH/vjhmOxgSpWNr9tYZIlDRczX/pnp4oJPMJglVOy1Ildi+pudwkorqRcqN3lAikXKwl6jrd5naqk/TriBbyDg/P0rXxr3cV8vEF6c+l7zHi8LZ+fzXHwAAAAAAAAAAAAAAAAAAAAAAAPBDrxI79dYAKAAA"; + +fn qualified_body() -> &'static [u8] { + static BODY: LazyLock> = + LazyLock::new(|| STANDARD.decode(BODY_B64).expect("fixture archive")); + &BODY +} // Disposable fixture public key and prehashed minisign signature. The signing // key is not retained. These bytes are deliberately not an installable App. +#[allow(dead_code)] const KEY: &str = "dW50cnVzdGVkIGNvbW1lbnQ6IExvb3BYIHRlc3QgcHVibGljIGtleQpSV1JzYjI5d2VIUnpkRWJGVGJ5dExTQ0VKK2RpdGw1NGgwcnBBTTFLa2xjdW5OYy9PaE80KzYwZwo="; +#[allow(dead_code)] const SIGNATURE: &str = "dW50cnVzdGVkIGNvbW1lbnQ6IExvb3BYIHN5bnRoZXRpYyB0cmFuc3BvcnQgZml4dHVyZQpSVVJzYjI5d2VIUnpkQVJhZGtJKy9nSTdQRzVibndOY3VDbUhyQmVzamNZOTgxaFg4KzhOYXZkRFJhTi91SDNheGNmNnBmOUNyaXRvL2UzTitHMklwMWM0dGVxNHNVTWNld0E9CnRydXN0ZWQgY29tbWVudDogTG9vcFggdHJhbnNwb3J0IGZpeHR1cmUKQUdNUDBuTnhqN0NITHdONURZY2hrTm5Rc0RxZklSZUxVMWM5WEpKcm1WTHpvUWR0bkJJb2F5TGlOY29LZlNHV00zVXdLbTB3c1N1WEVhSStQZFFOQWc9PQo="; +const QUALIFIED_KEY: &str = "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXkKUldReitVUjg5RUZCVHB6aWZha0hFUmprTmRBZUJCa0ZPNENQMGRwWGhnRVgyckFLMm52WUtRNDUK"; +const QUALIFIED_SIGNATURE: &str = "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUlVReitVUjg5RUZCVHVZWWJaeTY5TjBEWGJTWlVRZEJUSXJHRUNhUnBCZzJBZ3BEVFRiUSs1UzJhbGEyWThaaWRORktrLzRvaEwwd1hPMGR2TXlNdFVkN09UMTRNVXFQaEFnPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCWZpbGU6TG9vcFguYXBwLnRhci5neglwcmVoYXNoZWQKK1c2S2xwZUUxL0hOS24zRFNYeGlNeWx5elExUk1jMURQY2lnMER5K29oVkdwR3JyaW1ZMDRpbzMyQUJhRVJjRUxJck01UEtabmk5YVZkRE5qYWRvQUE9PQo="; struct Server { base: String, @@ -33,7 +44,7 @@ fn pause(stop: &AtomicBool, duration: Duration) { impl Server { fn new() -> Self { - Self::with_archive(BODY.to_vec(), SIGNATURE.into()) + Self::with_archive(qualified_body().to_vec(), QUALIFIED_SIGNATURE.into()) } fn with_archive(bytes: Vec, signature: String) -> Self { @@ -171,7 +182,7 @@ fn app(key: &str) -> tauri::App { #[test] fn manual_native_feed_releases_startup_before_http_finishes() { - let app = app(KEY); + let app = app(QUALIFIED_KEY); let server = Server::new(); let state = Arc::new(Maintenance::default()); let read_state = state.clone(); @@ -215,7 +226,7 @@ fn manual_native_feed_releases_startup_before_http_finishes() { #[test] fn manual_native_feed_timeout_retains_failure_and_allows_service_start() { - let app = app(KEY); + let app = app(QUALIFIED_KEY); let server = Server::new(); let state = Maintenance::default(); let result = tauri::async_runtime::block_on(state.run_manual_check( @@ -240,7 +251,7 @@ fn manual_native_feed_timeout_retains_failure_and_allows_service_start() { #[test] fn native_update_transport_checks_signatures_truncation_and_cache_readback() { - let app = app(KEY); + let app = app(QUALIFIED_KEY); let server = Server::new(); tauri::async_runtime::block_on(async { for (mode, expected_error) in [ @@ -264,7 +275,7 @@ fn native_update_transport_checks_signatures_truncation_and_cache_readback() { continue; } let bytes = result.unwrap(); - assert_eq!(bytes, BODY); + assert_eq!(bytes, qualified_body()); let root = tempfile::tempdir().unwrap(); crate::prepared_update::save( root.path(), @@ -274,17 +285,18 @@ fn native_update_transport_checks_signatures_truncation_and_cache_readback() { &bytes, ) .unwrap(); - let prepared = crate::prepared_update::load(root.path(), "0.1.0", "stable", KEY) - .unwrap() - .unwrap(); - assert_eq!(prepared.bytes, BODY); + let prepared = + crate::prepared_update::load(root.path(), "0.1.0", "stable", QUALIFIED_KEY) + .unwrap() + .unwrap(); + assert_eq!(prepared.bytes, qualified_body()); } }); } #[test] fn background_download_failures_keep_their_cause_without_blocking_local_services() { - let app = app(KEY); + let app = app(QUALIFIED_KEY); let server = Server::new(); tauri::async_runtime::block_on(async { for (mode, expected) in [ @@ -322,7 +334,7 @@ fn background_download_failures_keep_their_cause_without_blocking_local_services #[test] fn native_feed_keeps_its_short_deadline() { - let app = app(KEY); + let app = app(QUALIFIED_KEY); let server = Server::new(); let start = Instant::now(); let error = tauri::async_runtime::block_on(find_update( @@ -338,7 +350,7 @@ fn native_feed_keeps_its_short_deadline() { } fn assert_manual_feed_window(mode: &str) { - let app = app(KEY); + let app = app(QUALIFIED_KEY); let server = Server::new(); let start = Instant::now(); let update = tauri::async_runtime::block_on(find_update( @@ -353,7 +365,7 @@ fn assert_manual_feed_window(mode: &str) { assert!(elapsed > Duration::from_secs(30)); assert!(elapsed < Duration::from_secs(48)); let bytes = tauri::async_runtime::block_on(download_update(&update, |_, _| {})).unwrap(); - assert_eq!(bytes, BODY); + assert_eq!(bytes, qualified_body()); eprintln!( "manual {mode} feed: {:.3}s; signed archive still downloads", elapsed.as_secs_f64() @@ -375,7 +387,7 @@ fn manual_feed_body_keeps_the_original_forty_five_second_window() { #[test] #[ignore = "real transport spans the historical thirty-second download deadline"] fn progressing_signed_download_survives_the_old_total_deadline() { - let app = app(KEY); + let app = app(QUALIFIED_KEY); let server = Server::new(); let state = Maintenance::default(); state.reconcile_services(|| Ok(())).unwrap(); @@ -397,16 +409,16 @@ fn progressing_signed_download_survives_the_old_total_deadline() { let bytes = download_update(&update, |size, total| { *received += size; assert_eq!(state.recover_connected(|| 1), Some(1)); - assert_eq!(total, Some(BODY.len() as u64)); + assert_eq!(total, Some(qualified_body().len() as u64)); }) .await?; - assert_eq!(bytes, BODY); + assert_eq!(bytes, qualified_body()); Ok(json!({"version":update.version, "prepared":true})) } }, )) .unwrap(); - assert_eq!(received, BODY.len()); + assert_eq!(received, qualified_body().len()); assert!(start.elapsed() > Duration::from_secs(30)); assert_eq!(state.status_snapshot()["details"]["prepared"], true); eprintln!( @@ -419,7 +431,7 @@ fn progressing_signed_download_survives_the_old_total_deadline() { #[test] #[ignore = "real thirty-second idle deadlines for headers and mid-body stalls"] fn stalled_update_transfer_remains_bounded() { - let app = app(KEY); + let app = app(QUALIFIED_KEY); let server = Server::new(); for mode in ["headers", "body-stall"] { let update = tauri::async_runtime::block_on(find_update( @@ -487,7 +499,7 @@ fn released_archive_survives_slow_native_transport_and_cache_reopen() { #[cfg(target_os = "macos")] #[test] fn terminal_preparation_reuses_verified_bytes_and_freezes_an_offline_handoff() { - let app = app(KEY); + let app = app(QUALIFIED_KEY); let server = Server::new(); let root = tempfile::tempdir().unwrap(); let automatic = root.path().join("automatic"); @@ -516,7 +528,7 @@ fn terminal_preparation_reuses_verified_bytes_and_freezes_an_offline_handoff() { update.clone(), "0.1.0", "stable", - KEY, + QUALIFIED_KEY, &automatic, &request.preparation_directory() ) @@ -527,18 +539,25 @@ fn terminal_preparation_reuses_verified_bytes_and_freezes_an_offline_handoff() { assert_eq!(server.requests.load(Ordering::Acquire), 2); assert_eq!( request - .prepared_target("0.1.0", KEY) + .prepared_target("0.1.0", QUALIFIED_KEY) .unwrap() .unwrap() .bytes, - BODY + qualified_body() ); - crate::prepared_update::save(&automatic, "stable", "1.1.0", SIGNATURE, BODY).unwrap(); + crate::prepared_update::save( + &automatic, + "stable", + "1.1.0", + QUALIFIED_SIGNATURE, + qualified_body(), + ) + .unwrap(); prepare_terminal_candidate( update, "0.1.0", "stable", - KEY, + QUALIFIED_KEY, &automatic, &request.preparation_directory(), ) @@ -553,11 +572,11 @@ fn terminal_preparation_reuses_verified_bytes_and_freezes_an_offline_handoff() { drop(server); // No network is available at the replacement boundary. assert_eq!( request - .prepared_target("0.1.0", KEY) + .prepared_target("0.1.0", QUALIFIED_KEY) .unwrap() .unwrap() .bytes, - BODY + qualified_body() ); // Another window's background cache cannot replace this request's bytes. crate::prepared_update::clear(&automatic).unwrap(); @@ -566,20 +585,23 @@ fn terminal_preparation_reuses_verified_bytes_and_freezes_an_offline_handoff() { &request.preparation_directory(), "stable", "1.2.0", - SIGNATURE, - BODY, + QUALIFIED_SIGNATURE, + qualified_body(), ) .unwrap(); - assert!(request.prepared_target("0.1.0", KEY).is_err()); + assert!(request.prepared_target("0.1.0", QUALIFIED_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()); + assert!(request.prepared_target("0.1.0", QUALIFIED_KEY).is_err()); + assert!(request + .prepared_target("1.1.0", QUALIFIED_KEY) + .unwrap() + .is_none()); } #[cfg(target_os = "macos")] #[test] fn terminal_preparation_rejects_bad_download_before_any_handoff() { - let app = app(KEY); + let app = app(QUALIFIED_KEY); let server = Server::new(); let root = tempfile::tempdir().unwrap(); tauri::async_runtime::block_on(async { @@ -597,7 +619,7 @@ fn terminal_preparation_rejects_bad_download_before_any_handoff() { update, "0.1.0", "stable", - KEY, + QUALIFIED_KEY, &root.path().join("automatic"), &request ) @@ -607,9 +629,16 @@ fn terminal_preparation_rejects_bad_download_before_any_handoff() { ); assert!(!request.exists()); assert_eq!( - prepare_terminal_candidate(None, "1.1.0", "stable", KEY, root.path(), &request) - .await - .unwrap(), + prepare_terminal_candidate( + None, + "1.1.0", + "stable", + QUALIFIED_KEY, + root.path(), + &request, + ) + .await + .unwrap(), "1.1.0" ); assert!(!request.exists()); @@ -619,11 +648,22 @@ fn terminal_preparation_rejects_bad_download_before_any_handoff() { #[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 app = app(QUALIFIED_KEY); + let server = Server::with_version( + qualified_body().to_vec(), + QUALIFIED_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(); + crate::prepared_update::save( + automatic.path(), + "stable", + "1.1.0", + QUALIFIED_SIGNATURE, + qualified_body(), + ) + .unwrap(); let before = std::fs::read(automatic.path().join("prepared.json")).unwrap(); let update = tauri::async_runtime::block_on(find_update( app.handle(), @@ -636,7 +676,7 @@ fn rejected_cross_channel_preparation_preserves_original_verified_cache() { update, "1.0.0", "main", - KEY, + QUALIFIED_KEY, automatic.path(), request.path(), )); @@ -646,10 +686,10 @@ fn rejected_cross_channel_preparation_preserves_original_verified_cache() { std::fs::read(automatic.path().join("prepared.json")).unwrap(), before ); - let original = crate::prepared_update::load(automatic.path(), "1.0.0", "stable", KEY) + let original = crate::prepared_update::load(automatic.path(), "1.0.0", "stable", QUALIFIED_KEY) .unwrap() .expect("failed Main preparation must retain the signed Stable cache"); - assert_eq!(original.bytes, BODY); - assert_eq!(original.signature, SIGNATURE); + assert_eq!(original.bytes, qualified_body()); + assert_eq!(original.signature, QUALIFIED_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 2085a3ba7a..5ae776e2d0 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 @@ -75,6 +75,8 @@ pub(crate) fn save( if !matches!(channel, "main" | "stable") || semver::Version::parse(version).is_err() { return Err(INVALID.into()); } + #[cfg(target_os = "macos")] + crate::macos_update::qualify_candidate(bytes)?; fs::create_dir_all(root).map_err(|_| INVALID)?; let old = metadata(root).ok().flatten(); let value = json!({"schema_version":"desktop_prepared_update_v1", "channel":channel, @@ -156,6 +158,8 @@ fn read( let signature = Signature::decode(std::str::from_utf8(&signature).map_err(|_| INVALID)?) .map_err(|_| INVALID)?; key.verify(&bytes, &signature, true).map_err(|_| INVALID)?; + #[cfg(target_os = "macos")] + crate::macos_update::qualify_candidate(&bytes)?; Ok(Some(PreparedUpdate { version: version.into(), signature: value["signature"].as_str().ok_or(INVALID)?.into(), @@ -183,6 +187,33 @@ pub(crate) fn clear(root: &Path) -> Result<(), String> { mod tests { use super::*; + fn qualified_archive(marker: &str) -> Vec { + let contract: Value = serde_json::from_str(include_str!( + "../../../../../loopx/cli_commands/public_default_contract.json" + )) + .unwrap(); + let identity = json!({ + "schema_version": "desktop_runtime_bundle_v1", + "source_revision": "1111111111111111111111111111111111111111", + "default_contract": contract, + "test_payload": marker + }); + let body = identity.to_string(); + let encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); + let mut archive = tar::Builder::new(encoder); + let mut header = tar::Header::new_gnu(); + header.set_size(body.len() as u64); + header.set_mode(0o600); + archive + .append_data( + &mut header, + "LoopX.app/Contents/Resources/runtime/identity.json", + body.as_bytes(), + ) + .unwrap(); + archive.into_inner().unwrap().finish().unwrap() + } + #[test] fn update_order_matches_explicit_channel_selection() { assert!(is_newer("1.0.0", "1.1.0", "stable")); @@ -201,7 +232,14 @@ mod tests { fn missing_cache_is_ordinary_and_obsolete_cache_is_retired() { let root = tempfile::tempdir().unwrap(); assert!(load(root.path(), "1.0.0", "stable", "").unwrap().is_none()); - save(root.path(), "stable", "1.1.0", "unused", b"old").unwrap(); + save( + root.path(), + "stable", + "1.1.0", + "unused", + &qualified_archive("old"), + ) + .unwrap(); assert!(load(root.path(), "1.2.0", "stable", "").unwrap().is_none()); assert_eq!(fs::read_dir(root.path()).unwrap().count(), 0); } @@ -209,10 +247,11 @@ mod tests { #[test] fn cached_data_without_a_valid_shipped_signature_is_never_activated() { let root = tempfile::tempdir().unwrap(); - save(root.path(), "stable", "1.1.0", "invalid", b"untrusted").unwrap(); + let archive = qualified_archive("untrusted"); + save(root.path(), "stable", "1.1.0", "invalid", &archive).unwrap(); assert!(load(root.path(), "1.0.0", "stable", "invalid").is_err()); fs::write( - root.path().join(format!("{}.tar.gz", digest(b"untrusted"))), + root.path().join(format!("{}.tar.gz", digest(&archive))), b"changed", ) .unwrap(); @@ -237,13 +276,15 @@ mod tests { #[test] fn replacing_a_prepared_download_preserves_only_the_new_complete_archive() { let root = tempfile::tempdir().unwrap(); - save(root.path(), "stable", "1.1.0", "signature", b"first").unwrap(); - save(root.path(), "stable", "1.2.0", "signature", b"second").unwrap(); + let first = qualified_archive("first"); + let second = qualified_archive("second"); + save(root.path(), "stable", "1.1.0", "signature", &first).unwrap(); + save(root.path(), "stable", "1.2.0", "signature", &second).unwrap(); let value = metadata(root.path()).unwrap().unwrap(); assert_eq!(value["version"], "1.2.0"); assert_eq!( fs::read(root.path().join(archive_name(&value).unwrap())).unwrap(), - b"second" + second ); assert_eq!(fs::read_dir(root.path()).unwrap().count(), 2); clear(root.path()).unwrap(); @@ -271,7 +312,10 @@ mod tests { // the retained publisher signature on the next process's read. let mut changed = bytes; changed[0] ^= 1; - save(root.path(), "stable", "1.1.0", signature.trim(), &changed).unwrap(); + let mut value = metadata(root.path()).unwrap().unwrap(); + value["sha256"] = json!(digest(&changed)); + fs::write(root.path().join(archive_name(&value).unwrap()), changed).unwrap(); + fs::write(root.path().join("prepared.json"), value.to_string()).unwrap(); assert!(load(root.path(), "1.0.0", "stable", key).is_err()); } } 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 633fd66171..cfc6b2ce13 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/services.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/services.rs @@ -1088,38 +1088,291 @@ fn configure_codex_chat_home( } } +// Alias files chain (`default` -> `lts/*` -> `lts/krypton` -> `v24.22.1`). +// Read a bounded chain instead of running nvm, so a missing, cyclic or +// malformed chain just falls through to installed-version discovery. +#[cfg(unix)] +const NVM_ALIAS_DEPTH_LIMIT: usize = 8; + +// `v24.22.1`, `24.22.1` and the alias targets that name them are the only +// accepted forms; anything else is a non-version alias name to follow. +#[cfg(unix)] +fn nvm_version(name: &str) -> Option<(u64, u64, u64)> { + let trimmed = name.trim().strip_prefix('v').unwrap_or(name.trim()); + let mut fields = trimmed.split('.'); + let major = fields.next()?.parse().ok()?; + let minor = fields.next()?.parse().ok()?; + let patch = fields.next()?.parse().ok()?; + fields.next().is_none().then_some((major, minor, patch)) +} + +// Alias names are file names under `$NVM_DIR/alias`; keep the read inside that +// directory instead of letting a crafted alias escape it. +#[cfg(unix)] +fn is_bounded_nvm_alias(name: &str) -> bool { + !name.is_empty() + && !name.contains('\0') + && Path::new(name) + .components() + .all(|component| matches!(component, std::path::Component::Normal(_))) +} + +#[cfg(unix)] +fn resolve_nvm_alias(root: &Path, alias: &str, depth: usize) -> Option { + if depth >= NVM_ALIAS_DEPTH_LIMIT { + return None; + } + let name = alias.trim(); + if !is_bounded_nvm_alias(name) { + return None; + } + if let Some((major, minor, patch)) = nvm_version(name) { + // nvm names its version directories with the `v` prefix, whatever + // form the alias chain used to reach them. + return Some(format!("v{major}.{minor}.{patch}")); + } + let target = fs::read_to_string(root.join("alias").join(name)).ok()?; + resolve_nvm_alias(root, &target, depth + 1) +} + +#[cfg(unix)] +fn installed_nvm_versions(root: &Path) -> Vec { + let Ok(entries) = fs::read_dir(root.join("versions/node")) else { + return Vec::new(); + }; + let mut versions: Vec<_> = entries + .flatten() + .filter_map(|entry| { + let name = entry.file_name().to_string_lossy().into_owned(); + nvm_version(&name).map(|version| (version, name)) + }) + .collect(); + versions.sort_by_key(|(version, _)| std::cmp::Reverse(*version)); + versions.into_iter().map(|(_, name)| name).collect() +} + +// nvm activates a Node by prepending `$NVM_BIN` to the interactive shell +// PATH. Finder/launchd never load that activation, so a host whose only Node +// is nvm-managed looks Node-less to the private installer and the owned +// services. Resolve the same bounded locations the Lark CLI resolver uses, +// without executing nvm or sourcing any startup file. +// +// An activation inherited from the launching shell (`nvm use`, or a +// terminal-launched App) is explicit intent, but only while it still matches +// the Node that PATH selects. A shell can keep a stale `NVM_BIN` after putting +// another Node first, and preferring the stale directory there would replace a +// working Node with an unsupported one. A PATH that resolves no Node at all is +// not evidence either: the variable may be residue from a launchd plist or an +// earlier shell, and the standard Homebrew entries below may still hold a +// supported Node. Without that agreement the directory is only a fallback, +// ranked behind every discovered nvm location. +#[cfg(unix)] +fn explicit_nvm_directories( + nvm_bin: Option<&std::ffi::OsStr>, + inherited: Option<&std::ffi::OsStr>, +) -> Vec { + let Some(active) = nvm_bin.filter(|value| !value.is_empty()) else { + return Vec::new(); + }; + let directory = PathBuf::from(active); + if !nvm_bin_agrees_with_inherited_node(&directory, inherited) { + return Vec::new(); + } + let mut directories = Vec::new(); + push_tool_directory(&mut directories, directory); + directories +} + +// `NVM_BIN` agrees only when the inherited PATH resolves a Node and that Node +// is the same executable nvm activated. Both other shapes mean the variable is +// not the shell's current choice: PATH selected a different Node, or PATH has no +// Node at all and the value may simply be residue, which must not outrank a +// supported Homebrew Node the same launch would otherwise find. +#[cfg(unix)] +fn nvm_bin_agrees_with_inherited_node(nvm_bin: &Path, inherited: Option<&std::ffi::OsStr>) -> bool { + match resolve_executable_path("node", inherited) { + Some(inherited_node) => paths_refer_to_same_file( + &inherited_node.to_string_lossy(), + &nvm_bin.join("node").to_string_lossy(), + ), + None => false, + } +} + +// The App only ORDERS inferred nvm fallbacks; Core still performs the +// authoritative qualification on the resolved `node`. This mirrors Core's +// `MINIMUM_NODE_VERSION` (loopx/control_plane/runtime/node_probe.py) so an old +// recorded `default` alias is not chosen over a newer installed version that +// meets the supported floor. +#[cfg(unix)] +const MINIMUM_SUPPORTED_NODE: (u64, u64, u64) = (22, 22, 3); + +// `.../versions/node//bin` -> `` as a comparable tuple. +#[cfg(unix)] +fn nvm_directory_version(directory: &Path) -> Option<(u64, u64, u64)> { + let version_dir = directory.parent()?.file_name()?; + nvm_version(&version_dir.to_string_lossy()) +} + +// nvm candidates for a host whose only Node is nvm-managed. Ordered so a +// qualified Node is never hidden behind an old recorded `default`: the default +// alias leads only while it meets the supported floor, otherwise the newest +// installed version that does is promoted ahead of it (and ahead of any newer +// aliases that still would not qualify). Everything stays behind the known +// runtimes and the inherited PATH, so an inferred candidate never displaces a +// Node the host already provides. A demoted `NVM_BIN` ranks last: it is an +// explicit location the host no longer selects, so a discovered version must +// win before it. +#[cfg(unix)] +fn discovered_nvm_directories(nvm_root: &Path, demoted_nvm_bin: Option<&Path>) -> Vec { + // Installed versions newest-first; the recorded default is normally one of + // these, so it keeps its version position rather than being forced ahead. + let mut directories = Vec::new(); + for version in installed_nvm_versions(nvm_root) { + push_tool_directory( + &mut directories, + nvm_root.join("versions/node").join(version).join("bin"), + ); + } + let default_dir = resolve_nvm_alias(nvm_root, "default", 0) + .map(|version| nvm_root.join("versions/node").join(version).join("bin")); + if let Some(directory) = &default_dir { + push_tool_directory(&mut directories, directory.clone()); + } + // Prefer the recorded default while it meets the floor; otherwise lead with + // the newest version that does, so an old default never hides a supported + // one from Core's qualification. + let qualifies = |directory: &Path| { + nvm_directory_version(directory).is_some_and(|version| version >= MINIMUM_SUPPORTED_NODE) + }; + let lead = default_dir + .as_ref() + .filter(|directory| qualifies(directory)) + .or_else(|| directories.iter().find(|directory| qualifies(directory))) + .cloned(); + if let Some(lead) = lead { + if let Some(index) = directories.iter().position(|directory| directory == &lead) { + let lead = directories.remove(index); + directories.insert(0, lead); + } + } + if let Some(demoted) = demoted_nvm_bin { + push_tool_directory(&mut directories, demoted.to_path_buf()); + } + directories +} + +#[cfg(unix)] +fn push_tool_directory(directories: &mut Vec, candidate: PathBuf) { + if candidate.is_dir() && !directories.contains(&candidate) { + directories.push(candidate); + } +} + +// One tool search, one copy of each directory: a candidate discovered twice +// (an activated version that is also the recorded default, or an inherited +// entry this App also adds) must not appear twice in the search path. +fn extend_unique(paths: &mut Vec, candidates: impl IntoIterator) { + for candidate in candidates { + if !paths.contains(&candidate) { + paths.push(candidate); + } + } +} + +#[cfg(unix)] +fn nvm_root(home: Option<&std::ffi::OsStr>) -> Option { + if let Some(configured) = env::var_os("NVM_DIR").filter(|value| !value.is_empty()) { + return Some(PathBuf::from(configured)); + } + home.map(|home| PathBuf::from(home).join(".nvm")) +} + fn runtime_search_path( home: Option, inherited: Option, +) -> std::ffi::OsString { + #[cfg(unix)] + let nvm_root = nvm_root(home.as_deref()); + #[cfg(unix)] + let nvm_bin = env::var_os("NVM_BIN").filter(|value| !value.is_empty()); + runtime_search_path_from( + home, + inherited, + #[cfg(unix)] + nvm_root.as_deref(), + #[cfg(unix)] + nvm_bin.as_deref(), + ) +} + +// The nvm inputs are parameters so a test can pin them without mutating the +// process environment that parallel tests read. +fn runtime_search_path_from( + home: Option, + inherited: Option, + #[cfg(unix)] nvm_root: Option<&Path>, + #[cfg(unix)] nvm_bin: Option<&std::ffi::OsStr>, ) -> std::ffi::OsString { let mut paths = Vec::new(); - if let Some(home) = home { + if let Some(ref home) = home { paths.push(PathBuf::from(home).join(".local/bin")); } - if cfg!(target_os = "macos") { - paths.extend([ - PathBuf::from("/opt/homebrew/bin"), - PathBuf::from("/usr/local/bin"), - // Homebrew's supported LTS Node formulae are keg-only. Finder - // does not inherit the shell PATH that activates those runtimes. - // Use the same bounded search for the private installer and the - // services it starts; Core still qualifies the actual version. - PathBuf::from("/opt/homebrew/opt/node@24/bin"), - PathBuf::from("/usr/local/opt/node@24/bin"), - PathBuf::from("/opt/homebrew/opt/node@22/bin"), - PathBuf::from("/usr/local/opt/node@22/bin"), - ]); + // An activation the launching shell exported keeps the precedence the + // inherited PATH already gave it, but only while it still agrees with the + // Node that PATH selects. + #[cfg(unix)] + let explicit_nvm_bin = nvm_bin.and_then(|nvm_bin| { + explicit_nvm_directories(Some(nvm_bin), inherited.as_deref()) + .into_iter() + .next() + }); + #[cfg(unix)] + if let Some(nvm_bin) = explicit_nvm_bin.as_deref() { + extend_unique(&mut paths, [nvm_bin.to_path_buf()]); } - for path in inherited - .as_deref() - .map(env::split_paths) - .into_iter() - .flatten() - { - if !paths.contains(&path) { - paths.push(path); - } + if cfg!(target_os = "macos") { + extend_unique( + &mut paths, + [ + PathBuf::from("/opt/homebrew/bin"), + PathBuf::from("/usr/local/bin"), + // Homebrew's supported LTS Node formulae are keg-only. Finder + // does not inherit the shell PATH that activates those runtimes. + // Use the same bounded search for the private installer and the + // services it starts; Core still qualifies the actual version. + PathBuf::from("/opt/homebrew/opt/node@24/bin"), + PathBuf::from("/usr/local/opt/node@24/bin"), + PathBuf::from("/opt/homebrew/opt/node@22/bin"), + PathBuf::from("/usr/local/opt/node@22/bin"), + ], + ); } + // A `NVM_BIN` the host no longer selects is demoted to the last resort, + // behind the discovered versions so a newer install still wins over it. + #[cfg(unix)] + let demoted_nvm_bin = nvm_bin + .filter(|nvm_bin| explicit_nvm_bin.as_deref() != Some(Path::new(nvm_bin))) + .map(PathBuf::from); + #[cfg(unix)] + let discovered = match nvm_root { + Some(nvm_root) => discovered_nvm_directories(nvm_root, demoted_nvm_bin.as_deref()), + // Without an nvm root to enumerate, the demoted directory is still the + // last-resort candidate rather than being dropped from the search. + None => demoted_nvm_bin.iter().cloned().collect(), + }; + extend_unique( + &mut paths, + inherited + .as_deref() + .map(env::split_paths) + .into_iter() + .flatten(), + ); + // Inferred nvm locations are the last resort: they extend the search for a + // host that has no other Node, and never displace one that already exists. + #[cfg(unix)] + extend_unique(&mut paths, discovered); env::join_paths(paths).unwrap_or_else(|_| inherited.unwrap_or_default()) } 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 ecb7547f7b..915640c804 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 @@ -107,6 +107,12 @@ fn status_readiness_is_explicit_and_fails_closed() { #[test] #[cfg(target_os = "macos")] fn finder_runtime_path_includes_tools_without_loading_shell_profiles() { + // An nvm-activated test shell would prepend its own NVM_BIN to this + // fixture home's search path, so the fixed-position assertions below only + // hold for a process started without that activation. + if ambient_nvm_activation() { + return; + } let path = runtime_search_path( Some("/fixture/user".into()), Some("/usr/bin:/bin:/usr/sbin:/sbin".into()), @@ -134,6 +140,545 @@ fn finder_runtime_path_includes_tools_without_loading_shell_profiles() { assert_eq!(again, path, "tool search must be idempotent"); } +#[cfg(unix)] +fn nvm_fixture(root: &Path, default: &str) -> PathBuf { + let versions = root.join("versions/node"); + for version in ["v24.22.1", "v22.14.0", "v20.18.0"] { + fs::create_dir_all(versions.join(version).join("bin")).expect("nvm version bin"); + } + let alias = root.join("alias"); + fs::create_dir_all(alias.join("lts")).expect("nvm alias directory"); + fs::write(alias.join("default"), format!("{default}\n")).expect("default alias"); + fs::write(alias.join("lts/*"), "lts/krypton\n").expect("lts alias"); + fs::write(alias.join("lts/krypton"), "v24.22.1\n").expect("lts codename alias"); + root.to_path_buf() +} + +// A real Node stand-in so a resolution assertion doubles as a version +// qualification: the search order decides which executable Core would probe. +#[cfg(unix)] +fn node_fixture(bin: &Path, version: &str) -> PathBuf { + use std::os::unix::fs::PermissionsExt; + fs::create_dir_all(bin).expect("node fixture bin"); + let executable = bin.join("node"); + fs::write(&executable, format!("#!/bin/sh\nprintf 'v{version}\\n'\n")) + .expect("node fixture executable"); + fs::set_permissions(&executable, fs::Permissions::from_mode(0o755)).expect("node fixture mode"); + executable +} + +// An nvm-activated test shell would resolve this fixture home against the +// developer's own NVM_DIR/NVM_BIN, so the fixed-position assertions below only +// hold for a process started without that activation. +#[cfg(unix)] +fn ambient_nvm_activation() -> bool { + env::var_os("NVM_DIR").is_some() || env::var_os("NVM_BIN").is_some() +} + +#[test] +#[cfg(unix)] +fn finder_runtime_path_finds_nvm_managed_node() { + let home = tempfile::tempdir().expect("home fixture"); + let nvm_root = nvm_fixture(&home.path().join(".nvm"), "v24.22.1"); + let path = runtime_search_path_from( + Some(home.path().to_path_buf().into()), + Some("/usr/bin:/bin:/usr/sbin:/sbin".into()), + Some(&nvm_root), + None, + ); + let paths: Vec<_> = env::split_paths(&path).collect(); + let default_bin = nvm_root.join("versions/node/v24.22.1/bin"); + let position = |candidate: &Path| { + paths + .iter() + .position(|p| p == candidate) + .unwrap_or_else(|| panic!("{} missing from tool search", candidate.display())) + }; + assert_eq!(paths[0], home.path().join(".local/bin")); + // A host whose only Node is nvm-managed must still be found from Finder. + assert!(paths.contains(&default_bin)); + // Inferred nvm is the last resort: behind every candidate the host already + // provides, and behind the inherited PATH a terminal launch contributes. + // The Homebrew entries are only added on macOS, so they are asserted there. + let mut existing: Vec<&Path> = vec![Path::new("/usr/bin"), Path::new("/bin")]; + #[cfg(target_os = "macos")] + existing.extend([ + Path::new("/opt/homebrew/bin"), + Path::new("/usr/local/bin"), + Path::new("/opt/homebrew/opt/node@24/bin"), + Path::new("/usr/local/opt/node@24/bin"), + Path::new("/opt/homebrew/opt/node@22/bin"), + Path::new("/usr/local/opt/node@22/bin"), + ]); + for existing in existing { + assert!( + position(existing) < position(&default_bin), + "inferred nvm must stay behind the existing candidate {}", + existing.display() + ); + } + assert!( + position(&nvm_root.join("versions/node/v22.14.0/bin")) > position(&default_bin), + "the recorded default alias leads the discovered versions" + ); + assert!( + position(&nvm_root.join("versions/node/v20.18.0/bin")) + > position(&nvm_root.join("versions/node/v22.14.0/bin")), + "installed nvm versions are discovered newest-first" + ); + let mut unique = paths.clone(); + unique.sort(); + unique.dedup(); + assert_eq!( + unique.len(), + paths.len(), + "one tool search must not repeat a directory: {paths:?}" + ); + assert_eq!( + paths.iter().filter(|p| *p == &default_bin).count(), + 1, + "the recorded default alias is also an installed version and must appear once" + ); + let again = runtime_search_path_from( + Some(home.path().to_path_buf().into()), + Some(path.clone()), + Some(&nvm_root), + None, + ); + assert_eq!(again, path, "tool search must be idempotent"); +} + +// A recorded `default` alias that predates the supported floor must not hide a +// newer installed version: with no other Node on the host, the qualified newer +// version leads so Core's qualification succeeds instead of reporting the old +// default as unsupported. +#[test] +#[cfg(unix)] +fn old_default_alias_does_not_hide_a_newer_supported_version() { + let root = tempfile::tempdir().expect("nvm fixture"); + let nvm_root = nvm_fixture(root.path(), "v20.18.0"); + let v24 = nvm_root.join("versions/node/v24.22.1/bin"); + let v22 = nvm_root.join("versions/node/v22.14.0/bin"); + let v20 = nvm_root.join("versions/node/v20.18.0/bin"); + + let discovered = discovered_nvm_directories(&nvm_root, None); + assert_eq!( + discovered.first(), + Some(&v24), + "a supported newer version leads over an old recorded default" + ); + let position = |directory: &Path| { + discovered + .iter() + .position(|candidate| candidate == directory) + .unwrap_or_else(|| panic!("{} missing", directory.display())) + }; + assert!(position(&v24) < position(&v22)); + assert!( + position(&v22) < position(&v20), + "the old default is not promoted" + ); + + // The full search path reflects the same lead: the qualified newer version + // precedes the old default, so resolving `node` cannot pick the old one. + let home = tempfile::tempdir().expect("home fixture"); + let nvm_root = nvm_fixture(&home.path().join(".nvm"), "v20.18.0"); + node_fixture(&nvm_root.join("versions/node/v24.22.1/bin"), "24.22.1"); + node_fixture(&nvm_root.join("versions/node/v20.18.0/bin"), "20.18.0"); + let path = runtime_search_path_from( + Some(home.path().to_path_buf().into()), + Some("/usr/bin:/bin".into()), + Some(&nvm_root), + None, + ); + let paths: Vec<_> = env::split_paths(&path).collect(); + let nvm_lead = paths + .iter() + .find(|candidate| candidate.starts_with(&nvm_root)) + .expect("the nvm tree appears in the search"); + assert_eq!( + nvm_lead, + &nvm_root.join("versions/node/v24.22.1/bin"), + "the first nvm entry is the qualified newer version, not the old default" + ); +} + +// A terminal activation is authoritative only while it still matches the Node +// the inherited PATH selects. A shell that put another Node first after `nvm +// use` leaves a stale `NVM_BIN` behind, and preferring it would replace a +// working Node with an unsupported one. +#[test] +#[cfg(unix)] +fn stale_nvm_bin_yields_to_the_node_the_shell_selected() { + let home = tempfile::tempdir().expect("home fixture"); + let nvm_root = nvm_fixture(&home.path().join(".nvm"), "v24.22.1"); + let stale = nvm_root.join("versions/node/v20.18.0/bin"); + node_fixture(&stale, "20.18.0"); + let selected = node_fixture(&home.path().join("selected/node/bin"), "24.22.1"); + let selected_bin = selected.parent().expect("selected bin").to_path_buf(); + + // Still the selected Node: the activation keeps terminal-launch precedence. + let agreed = runtime_search_path_from( + Some(home.path().to_path_buf().into()), + Some(selected_bin.to_string_lossy().into_owned().into()), + Some(&nvm_root), + Some(selected_bin.as_os_str()), + ); + let agreed_paths: Vec<_> = env::split_paths(&agreed).collect(); + let position = |candidate: &Path| { + agreed_paths + .iter() + .position(|p| p == candidate) + .unwrap_or_else(|| panic!("{} missing from tool search", candidate.display())) + }; + assert_eq!( + position(selected_bin.as_path()), + 1, + "an activation that still matches the selected Node keeps its precedence" + ); + assert_demoted_nvm_bin_is_last_resort(&nvm_root, &selected, agreed.as_os_str()); + + // No longer the selected Node: the stale directory becomes a last resort. + let stale_nvm_bin = stale.as_os_str(); + let demoted = runtime_search_path_from( + Some(home.path().to_path_buf().into()), + Some(selected_bin.to_string_lossy().into_owned().into()), + Some(&nvm_root), + Some(stale_nvm_bin), + ); + let demoted_paths: Vec<_> = env::split_paths(&demoted).collect(); + let demoted_position = |candidate: &Path| { + demoted_paths + .iter() + .position(|p| p == candidate) + .unwrap_or_else(|| panic!("{} missing from tool search", candidate.display())) + }; + assert!( + demoted_position(selected_bin.as_path()) < demoted_position(&stale), + "a stale NVM_BIN must not precede the Node the shell selected" + ); + assert!( + demoted_position(&nvm_root.join("versions/node/v24.22.1/bin")) < demoted_position(&stale), + "a newer installed version outranks a demoted NVM_BIN" + ); + assert_demoted_nvm_bin_is_last_resort(&nvm_root, &selected, demoted.as_os_str()); + + // A PATH that resolves no Node at all: `NVM_BIN` is not evidence the shell + // still selects that version, so it is demoted — yet still discovered, so + // an nvm-only host keeps working. + let no_node_on_path = home.path().join("empty-bin"); + fs::create_dir_all(&no_node_on_path).expect("empty bin fixture"); + let only_nvm = runtime_search_path_from( + Some(home.path().to_path_buf().into()), + Some(no_node_on_path.to_string_lossy().into_owned().into()), + Some(&nvm_root), + Some(stale_nvm_bin), + ); + let only_nvm_paths: Vec<_> = env::split_paths(&only_nvm).collect(); + assert!( + only_nvm_paths.contains(&stale), + "an activation with no competing Node stays in the search" + ); + assert_ne!( + only_nvm_paths.first(), + Some(&stale), + "a stale NVM_BIN must not take the promoted activation position" + ); + assert!( + only_nvm_paths + .iter() + .position(|directory| directory == &stale) + > only_nvm_paths + .iter() + .position(|directory| directory == &nvm_root.join("versions/node/v24.22.1/bin")), + "a stale NVM_BIN ranks behind a discovered qualified version" + ); + let mut unique = only_nvm_paths.clone(); + unique.sort(); + unique.dedup(); + assert_eq!( + unique.len(), + only_nvm_paths.len(), + "no duplicate directories" + ); +} + +// The reviewer's regression: a launch with a minimal PATH that resolves no +// Node and a residual `NVM_BIN` pointing at an unsupported version. Promoting +// the residual variable would place it ahead of the standard Homebrew entries +// and break a host whose Homebrew Node qualified before. +#[test] +#[cfg(unix)] +fn residual_nvm_bin_does_not_outrank_the_standard_host_node() { + let home = tempfile::tempdir().expect("home fixture"); + let nvm_root = nvm_fixture(&home.path().join(".nvm"), "v24.22.1"); + let stale = nvm_root.join("versions/node/v20.18.0/bin"); + node_fixture(&stale, "20.18.0"); + let qualified_node = node_fixture(&nvm_root.join("versions/node/v24.22.1/bin"), "24.22.1"); + let empty_bin = home.path().join("empty-bin"); + fs::create_dir_all(&empty_bin).expect("empty bin fixture"); + let inherited: std::ffi::OsString = empty_bin.clone().into_os_string(); + assert!( + resolve_executable_path("node", Some(inherited.as_os_str())).is_none(), + "the inherited PATH must resolve no Node for this scenario" + ); + + let search = runtime_search_path_from( + Some(home.path().to_path_buf().into()), + Some(inherited), + Some(&nvm_root), + Some(stale.as_os_str()), + ); + let paths: Vec<_> = env::split_paths(&search).collect(); + let position = |candidate: &Path| { + paths + .iter() + .position(|p| p == candidate) + .unwrap_or_else(|| panic!("{} missing from tool search", candidate.display())) + }; + // The promoted activation position belongs to `~/.local/bin` only; the + // residual variable must rank behind every standard host entry. + assert_eq!(paths[0], home.path().join(".local/bin")); + #[cfg(target_os = "macos")] + { + assert!( + position(Path::new("/opt/homebrew/bin")) < position(&stale), + "a residual NVM_BIN must not precede the standard Homebrew Node" + ); + assert!( + position(Path::new("/usr/local/bin")) < position(&stale), + "a residual NVM_BIN must not precede /usr/local/bin" + ); + } + assert!( + position(&nvm_root.join("versions/node/v24.22.1/bin")) < position(&stale), + "a residual NVM_BIN must rank behind a discovered qualified version" + ); + assert!( + paths + .iter() + .filter(|directory| *directory == &stale) + .count() + == 1, + "the demoted NVM_BIN appears once: {paths:?}" + ); + + // Core qualifies the Node the search resolves first: the residual directory + // must not win while the host provides a Node, and when it does not the + // discovered qualified version must win. The oracle checks the host so it + // holds on a machine with a real Homebrew Node too. + assert_demoted_nvm_bin_is_last_resort(&nvm_root, &qualified_node, search.as_os_str()); + + // An nvm-only host with nothing else still finds the residual directory, so + // the demotion never makes nvm invisible. + let isolated_root = tempfile::tempdir().expect("isolated nvm fixture"); + let isolated_nvm = isolated_root.path().join(".nvm"); + let isolated = isolated_nvm.join("versions/node/v20.18.0/bin"); + fs::create_dir_all(&isolated).expect("isolated nvm version bin"); + fs::create_dir_all(isolated_nvm.join("alias")).expect("isolated alias directory"); + fs::write(isolated_nvm.join("alias/default"), "v20.18.0\n").expect("isolated default"); + node_fixture(&isolated, "20.18.0"); + let isolated_search = runtime_search_path_from( + Some(home.path().to_path_buf().into()), + Some(empty_bin.clone().into_os_string()), + Some(&isolated_nvm), + Some(isolated.as_os_str()), + ); + assert!( + env::split_paths(&isolated_search).any(|directory| directory == isolated), + "a residual NVM_BIN is still discovered when nothing else provides Node" + ); + let isolated_node = isolated.join("node"); + match env::split_paths(&isolated_search) + .find(|directory| !directory.starts_with(&isolated_nvm) && directory.join("node").is_file()) + { + Some(directory) => assert_eq!( + resolve_executable_path("node", Some(isolated_search.as_os_str())), + Some(directory.join("node")), + "a residual NVM_BIN must yield to a Node the host provides" + ), + None => assert_eq!( + resolve_executable_path("node", Some(isolated_search.as_os_str())), + Some(isolated_node), + "an nvm-only host resolves its only Node" + ), + } +} + +// An inferred nvm candidate may only be selected when no other candidate +// exists on the host. That rule must hold on any machine, with or without a +// Homebrew Node, so the oracle checks the host instead of assuming one. +#[cfg(unix)] +fn assert_inferred_nvm_never_displaces_existing( + nvm_root: &Path, + stale_default_bin: &Path, + search: &std::ffi::OsStr, +) { + let resolved = + resolve_executable_path("node", Some(search)).expect("the search must resolve a Node"); + let host_has_other_node = env::split_paths(search) + .any(|directory| !directory.starts_with(nvm_root) && directory.join("node").is_file()); + if host_has_other_node { + assert_ne!( + resolved, + stale_default_bin.join("node"), + "an inferred stale nvm default must not displace a candidate the host already provides" + ); + assert!( + !resolved.starts_with(nvm_root), + "resolution must come from an existing candidate, not the inferred default: {}", + resolved.display() + ); + } else { + assert_eq!( + resolved, + stale_default_bin.join("node"), + "nvm-managed Node stays discoverable when nothing else provides one" + ); + } +} + +// A demoted `NVM_BIN` may only be selected when nothing else can be: a Node +// the host provides, or a newer nvm install, must win first. The oracle reads +// the host instead of assuming which candidate that is, so it holds on a +// machine with a real Homebrew Node as well as on a bare one. `fallback` is the +// executable the search must resolve to when the host provides no Node. +#[cfg(unix)] +fn assert_demoted_nvm_bin_is_last_resort( + nvm_root: &Path, + fallback: &Path, + search: &std::ffi::OsStr, +) { + let resolved = + resolve_executable_path("node", Some(search)).expect("the search must resolve a Node"); + let host_candidate = env::split_paths(search) + .find(|directory| !directory.starts_with(nvm_root) && directory.join("node").is_file()); + match host_candidate { + Some(directory) => assert_eq!( + resolved, + directory.join("node"), + "a demoted NVM_BIN must yield to the Node the host provides" + ), + None => assert_eq!( + resolved, fallback, + "a demoted NVM_BIN may only be selected when nothing else can be" + ), + } +} + +// The reviewer's regression: a Finder launch with no NVM_BIN, an nvm `default` +// that predates the supported minimum, and a Node the host already provides. +// The inferred default must be discovered, never preferred. +#[test] +#[cfg(unix)] +fn inferred_nvm_default_cannot_shadow_an_existing_qualified_node() { + let home = tempfile::tempdir().expect("home fixture"); + let nvm_root = nvm_fixture(&home.path().join(".nvm"), "v20.18.0"); + let stale_default = nvm_root.join("versions/node/v20.18.0/bin"); + node_fixture(&stale_default, "20.18.0"); + // A supported Node the host already provides, the way Homebrew or an + // inherited terminal PATH would. + let qualified = node_fixture(&home.path().join("qualified/node/bin"), "24.22.1"); + let qualified_bin = qualified.parent().expect("qualified bin").to_path_buf(); + let with_candidate = runtime_search_path_from( + Some(home.path().to_path_buf().into()), + Some(qualified_bin.to_string_lossy().into_owned().into()), + Some(&nvm_root), + None, + ); + assert_inferred_nvm_never_displaces_existing( + &nvm_root, + &stale_default, + with_candidate.as_os_str(), + ); + + // The ordering guarantee behind that resolution: every non-nvm candidate, + // including the Homebrew entries this App adds, precedes the inferred one. + let paths: Vec<_> = env::split_paths(&with_candidate).collect(); + let position = |candidate: &Path| { + paths + .iter() + .position(|p| p == candidate) + .unwrap_or_else(|| panic!("{} missing from tool search", candidate.display())) + }; + // The Homebrew entries only exist on macOS, so they are asserted there. + let local_bin = home.path().join(".local/bin"); + let mut existing: Vec<&Path> = vec![local_bin.as_path(), qualified_bin.as_path()]; + #[cfg(target_os = "macos")] + existing.extend([ + Path::new("/opt/homebrew/bin"), + Path::new("/usr/local/bin"), + Path::new("/opt/homebrew/opt/node@24/bin"), + Path::new("/usr/local/opt/node@24/bin"), + Path::new("/opt/homebrew/opt/node@22/bin"), + Path::new("/usr/local/opt/node@22/bin"), + ]); + for existing in existing { + assert!( + position(existing) < position(&stale_default), + "inferred nvm must stay behind the existing candidate {}", + existing.display() + ); + } + + // Without any other Node on the host, the same stale default is still the + // only candidate, so nvm remains discoverable rather than invisible. + let isolated = runtime_search_path_from( + Some(home.path().to_path_buf().into()), + Some("/usr/bin:/bin".into()), + Some(&nvm_root), + None, + ); + assert!(env::split_paths(&isolated).any(|directory| directory == stale_default)); + assert_inferred_nvm_never_displaces_existing(&nvm_root, &stale_default, isolated.as_os_str()); +} + +#[test] +#[cfg(unix)] +fn nvm_alias_chain_resolves_versions_and_rejects_escapes() { + let root = tempfile::tempdir().expect("nvm fixture"); + let nvm_root = nvm_fixture(root.path(), "lts/*"); + assert_eq!( + resolve_nvm_alias(&nvm_root, "default", 0).as_deref(), + Some("v24.22.1"), + "the default alias chain resolves to the recorded version" + ); + assert_eq!( + resolve_nvm_alias(&nvm_root, "22.14.0", 0).as_deref(), + Some("v22.14.0"), + "a version without the v prefix still names nvm's directory" + ); + for alias in ["", "missing", "../outside", "/etc/passwd", "lts/../default"] { + assert_eq!( + resolve_nvm_alias(&nvm_root, alias, 0), + None, + "alias {alias:?} must not resolve" + ); + } + fs::write(nvm_root.join("alias/cycle"), "cycle").expect("cyclic alias"); + assert_eq!(resolve_nvm_alias(&nvm_root, "cycle", 0), None); + assert!(installed_nvm_versions(&nvm_root) + .iter() + .zip(["v24.22.1", "v22.14.0", "v20.18.0"]) + .all(|(found, expected)| found == expected)); + assert_eq!(nvm_version("v24.22.1"), Some((24, 22, 1))); + assert_eq!(nvm_version("not-a-version"), None); + assert_eq!(nvm_version("v24.22"), None); +} + +#[test] +#[cfg(unix)] +fn nvm_root_follows_configured_directory_and_conventional_home() { + match env::var_os("NVM_DIR").filter(|value| !value.is_empty()) { + Some(configured) => assert_eq!(nvm_root(None), Some(PathBuf::from(configured))), + None => assert_eq!( + nvm_root(Some(std::ffi::OsStr::new("/fixture/user"))), + Some(PathBuf::from("/fixture/user/.nvm")), + "an unset NVM_DIR keeps the conventional location" + ), + } +} + #[cfg(not(windows))] fn spawn_listener_fixture( executable: &Path, diff --git a/apps/presentation/dashboard/README.md b/apps/presentation/dashboard/README.md index 326e16e8e8..e48e95be79 100644 --- a/apps/presentation/dashboard/README.md +++ b/apps/presentation/dashboard/README.md @@ -150,7 +150,7 @@ so a Kiro tool call that needs approval is refused rather than auto-approved. LoopX passes no `--trust-all-tools`. Reaching the host this way drives one read-only Chat session; it is not the governed `/goal` loop, which is entered from a Kiro CLI session through the -[Kiro CLI goal-mode adapter](../../../loopx/kiro_cli_goal_mode/README.md). +[Kiro CLI goal-mode adapter](../../../loopx/hosts/kiro_cli/README.md). Source-checkout development is a separate mode: diff --git a/apps/presentation/dashboard/package.json b/apps/presentation/dashboard/package.json index 46d308a86b..9809927263 100644 --- a/apps/presentation/dashboard/package.json +++ b/apps/presentation/dashboard/package.json @@ -5,6 +5,7 @@ "license": "Apache-2.0", "type": "module", "scripts": { + "test:native-decision-read": "vite build --ssr src/features/personal-workspace/native-decision-read.test.mjs --outDir node_modules/.cache/native-decision-read --emptyOutDir && node node_modules/.cache/native-decision-read/native-decision-read.test.js", "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", @@ -45,10 +46,10 @@ "smoke:home-route": "rm -rf /tmp/loopx-home-route-smoke && tsc --ignoreConfig --target ES2022 --module CommonJS --moduleResolution Node --ignoreDeprecations 6.0 --skipLibCheck --strict --outDir /tmp/loopx-home-route-smoke smoke/home-route-smoke.ts && node /tmp/loopx-home-route-smoke/home-route-smoke.js", "smoke:delegation-preflight": "rm -rf node_modules/.cache/loopx-delegation-preflight-smoke && tsc --ignoreConfig --target ES2022 --module NodeNext --moduleResolution NodeNext --jsx react-jsx --skipLibCheck --strict --rootDir . --outDir node_modules/.cache/loopx-delegation-preflight-smoke smoke/delegation-preflight-smoke.tsx src/data/delegation-preflight.ts src/features/personal-workspace/delegation-preflight-status.tsx && node node_modules/.cache/loopx-delegation-preflight-smoke/smoke/delegation-preflight-smoke.js", "smoke:delegation-preflight-browser": "node --experimental-strip-types smoke/delegation-preflight-browser-smoke.mjs", - "smoke:personal-workspace": "npm run smoke:goal-work-browse && npm run smoke:team-report && npm run smoke:answer-report && npm run smoke:chat-model-menu && npm run smoke:conversation-history-order && npm run smoke:goal-order && npm run smoke:goal-activity && npm run smoke:proposal-recency && node src/features/personal-workspace/conversation-order.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/steering-recovery.test.mjs src/features/personal-workspace/composer-keyboard.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/runtime-readiness.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/attention-notifications.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/since-you-looked.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/goal-suggestions.test.mjs && npm run smoke:delegation-preflight && node src/features/personal-workspace/workspace-theme.test.mjs && node src/features/personal-workspace/font-token.test.mjs && node src/features/personal-workspace/personal-workspace-contract.test.mjs && node ../../../examples/personal-workspace-browser-smoke.mjs", + "smoke:personal-workspace": "npm run smoke:goal-work-browse && npm run smoke:team-report && npm run smoke:answer-report && npm run smoke:chat-model-menu && npm run smoke:conversation-history-order && npm run smoke:goal-order && npm run smoke:goal-activity && npm run smoke:proposal-recency && node src/features/personal-workspace/conversation-order.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/steering-recovery.test.mjs src/features/personal-workspace/composer-keyboard.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/runtime-readiness.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/attention-notifications.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/since-you-looked.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/goal-suggestions.test.mjs && npm run smoke:delegation-preflight && node src/features/personal-workspace/workspace-theme.test.mjs && node src/features/personal-workspace/font-token.test.mjs && npm run test:native-decision-read && node src/features/personal-workspace/personal-workspace-contract.test.mjs && node ../../../examples/personal-workspace-browser-smoke.mjs", "smoke:workspace-locale": "LOOPX_PERSONAL_WORKSPACE_SCENARIO=workspace-locale node ../../../examples/personal-workspace-browser-smoke.mjs", - "smoke:personal-workspace-packaged": "npm run smoke:goal-work-browse && npm run smoke:team-report && npm run smoke:answer-report && npm run smoke:chat-model-menu && npm run smoke:conversation-history-order && npm run smoke:goal-order && npm run smoke:goal-activity && npm run smoke:proposal-recency && node src/features/personal-workspace/conversation-order.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/steering-recovery.test.mjs src/features/personal-workspace/composer-keyboard.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/runtime-readiness.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/attention-notifications.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/since-you-looked.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/goal-suggestions.test.mjs && npm run smoke:delegation-preflight && node src/features/personal-workspace/workspace-theme.test.mjs && node src/features/personal-workspace/font-token.test.mjs && node src/features/personal-workspace/personal-workspace-contract.test.mjs && node ../../../examples/personal-workspace-browser/server-startup.test.mjs && LOOPX_PERSONAL_WORKSPACE_PACKAGED=1 LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node ../../../examples/personal-workspace-browser-smoke.mjs && LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node smoke/team-evidence-return-smoke.mjs && LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node smoke/team-feedback-recovery-smoke.mjs && LOOPX_PERSONAL_WORKSPACE_PACKAGED=1 LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node smoke/goal-workspace-craft-browser-smoke.mjs", - "smoke:personal-workspace-packaged:catalog": "npm run smoke:goal-work-browse && npm run smoke:team-report && npm run smoke:answer-report && npm run smoke:chat-model-menu && npm run smoke:conversation-history-order && npm run smoke:goal-order && npm run smoke:goal-activity && npm run smoke:proposal-recency && node src/features/personal-workspace/conversation-order.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/steering-recovery.test.mjs src/features/personal-workspace/composer-keyboard.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/runtime-readiness.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/attention-notifications.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/since-you-looked.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/goal-suggestions.test.mjs && npm run smoke:delegation-preflight && node src/features/personal-workspace/workspace-theme.test.mjs && node src/features/personal-workspace/font-token.test.mjs && node src/features/personal-workspace/personal-workspace-contract.test.mjs && node ../../../examples/personal-workspace-browser/server-startup.test.mjs && LOOPX_PERSONAL_WORKSPACE_PACKAGED=1 LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node ../../../examples/personal-workspace-browser-smoke.mjs", + "smoke:personal-workspace-packaged": "npm run smoke:goal-work-browse && npm run smoke:team-report && npm run smoke:answer-report && npm run smoke:chat-model-menu && npm run smoke:conversation-history-order && npm run smoke:goal-order && npm run smoke:goal-activity && npm run smoke:proposal-recency && node src/features/personal-workspace/conversation-order.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/steering-recovery.test.mjs src/features/personal-workspace/composer-keyboard.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/runtime-readiness.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/attention-notifications.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/since-you-looked.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/goal-suggestions.test.mjs && npm run smoke:delegation-preflight && node src/features/personal-workspace/workspace-theme.test.mjs && node src/features/personal-workspace/font-token.test.mjs && npm run test:native-decision-read && node src/features/personal-workspace/personal-workspace-contract.test.mjs && node ../../../examples/personal-workspace-browser/server-startup.test.mjs && LOOPX_PERSONAL_WORKSPACE_PACKAGED=1 LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node ../../../examples/personal-workspace-browser-smoke.mjs && LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node smoke/team-evidence-return-smoke.mjs && LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node smoke/team-feedback-recovery-smoke.mjs && LOOPX_PERSONAL_WORKSPACE_PACKAGED=1 LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node smoke/goal-workspace-craft-browser-smoke.mjs", + "smoke:personal-workspace-packaged:catalog": "npm run smoke:goal-work-browse && npm run smoke:team-report && npm run smoke:answer-report && npm run smoke:chat-model-menu && npm run smoke:conversation-history-order && npm run smoke:goal-order && npm run smoke:goal-activity && npm run smoke:proposal-recency && node src/features/personal-workspace/conversation-order.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/steering-recovery.test.mjs src/features/personal-workspace/composer-keyboard.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/runtime-readiness.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/attention-notifications.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/since-you-looked.test.mjs && node --no-warnings --experimental-strip-types --test src/features/personal-workspace/goal-suggestions.test.mjs && npm run smoke:delegation-preflight && node src/features/personal-workspace/workspace-theme.test.mjs && node src/features/personal-workspace/font-token.test.mjs && npm run test:native-decision-read && node src/features/personal-workspace/personal-workspace-contract.test.mjs && node ../../../examples/personal-workspace-browser/server-startup.test.mjs && LOOPX_PERSONAL_WORKSPACE_PACKAGED=1 LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node ../../../examples/personal-workspace-browser-smoke.mjs", "smoke:personal-workspace-packaged:team": "LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node smoke/team-evidence-return-smoke.mjs && LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node smoke/team-feedback-recovery-smoke.mjs", "smoke:personal-workspace-packaged:craft": "LOOPX_PERSONAL_WORKSPACE_PACKAGED=1 LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node smoke/goal-workspace-craft-browser-smoke.mjs && LOOPX_PERSONAL_WORKSPACE_PACKAGED=1 LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" npm run smoke:workspace-command-palette", "smoke:todo-resume-condition": "rm -rf /tmp/loopx-todo-resume-condition-smoke && tsc --ignoreConfig --target ES2022 --module commonjs --moduleResolution node --ignoreDeprecations 6.0 --skipLibCheck --strict --outDir /tmp/loopx-todo-resume-condition-smoke smoke/todo-resume-condition-smoke.ts src/features/personal-workspace/todo-resume-condition.ts && node /tmp/loopx-todo-resume-condition-smoke/smoke/todo-resume-condition-smoke.js", diff --git a/apps/presentation/dashboard/smoke/capability-configuration-smoke.ts b/apps/presentation/dashboard/smoke/capability-configuration-smoke.ts index 9033ddff70..330b37f752 100644 --- a/apps/presentation/dashboard/smoke/capability-configuration-smoke.ts +++ b/apps/presentation/dashboard/smoke/capability-configuration-smoke.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; -import { changeStewardExecutorDraft, goalExploreEditorValue, goalExploreWriteValue, goalReplanCadenceEditorValue, goalReplanCadenceWriteValue, hasReplanCadenceOverride, goalStorageEditorValue, parseEditableCapabilityJson, projectEditableCapabilityConfiguration, replanCadenceEditorDefaults } from "../src/data/capability-configuration.js"; +import { changeStewardExecutorDraft, goalExploreEditorValue, goalExploreWriteValue, goalReplanCadenceEditorValue, goalReplanCadenceWriteValue, hasReplanCadenceOverride, goalStorageEditorValue, parseEditableCapabilityJson, projectEditableCapabilityConfiguration, replanCadenceEditorDefaults, replanCadenceEditorValue } from "../src/data/capability-configuration.js"; const exploreEditor = {fields: [{key: "mode"}, {key: "profile"}, {key: "composition_mode"}, {key: "composition_scope_id", nullable: true}]}; const exploreEffective = {mode: "planning", profile: "generic", composition_mode: "disabled", composition_scope_id: null}; @@ -40,53 +40,65 @@ const periodicReportEditor = { }; const storageEditor = { fields: [{ key: "new_goal_provider" }, { key: "canonical_creation" }, { key: "new_goal_handoff_mode" }] }; -const cadenceEditor = { fields: [{ key: "count_unit" }, { key: "count" }, { key: "stride_strategy" }] }; -const cadenceDefault = { count_unit: "effective_turns", count: 6, stride_strategy: "off" }; +const cadenceEditor = { fields: [{ key: "count_unit" }, { key: "count" }, { key: "planning_horizon_goal" }] }; +const cadenceDefault = { count_unit: "effective_turns", count: 6 }; assert.deepEqual(projectEditableCapabilityConfiguration(cadenceEditor, - { stride_strategy: "evidence_conditioned_v1" }, - replanCadenceEditorDefaults({ count_unit: "effective_turns", count: 3, stride_strategy: "off" }, cadenceDefault)), - { count_unit: "effective_turns", count: 3, stride_strategy: "evidence_conditioned_v1" }, + { planning_horizon_goal: false }, + replanCadenceEditorDefaults({ count_unit: "effective_turns", count: 3 }, cadenceDefault)), + { count_unit: "effective_turns", count: 3, planning_horizon_goal: false }, "a sparse JSON draft returning to the form preserves the effective review interval"); assert.deepEqual(projectEditableCapabilityConfiguration(cadenceEditor, { count_unit: "completed_todos", count: 2 }, - replanCadenceEditorDefaults({ count_unit: "effective_turns", count: 3, stride_strategy: "evidence_conditioned_v1" }, cadenceDefault)), - { count_unit: "completed_todos", count: 2, stride_strategy: "off" }, - "an explicit cadence wins and omitted strategy retains default-off semantics"); + replanCadenceEditorDefaults({ count_unit: "effective_turns", count: 3 }, cadenceDefault)), + { count_unit: "completed_todos", count: 2 }, + "an explicit cadence wins over the effective interval"); assert.deepEqual(replanCadenceEditorDefaults( { schema_version: "todo_replan_cadence_machine_defaults_v0", completed_todos: 4 }, cadenceDefault), - { count_unit: "completed_todos", count: 4, stride_strategy: "off" }, + { count_unit: "completed_todos", count: 4 }, "legacy effective intervals retain their own unit and count"); -const inheritedReview = { count_unit: "effective_turns", count: 3, stride_strategy: "off" }; +// The stride switch was removed: evidence-conditioned v1 is always on. Legacy +// saved values are history only and never displayed or resubmitted. +for (const legacy of ["off", "evidence_conditioned_v1"]) { + assert.deepEqual(replanCadenceEditorValue({ count_unit: "effective_turns", count: 3, stride_strategy: legacy }), + { count_unit: "effective_turns", count: 3 }, `legacy stride_strategy=${legacy} is not displayed`); + assert.equal(Object.hasOwn(goalReplanCadenceEditorValue({ stride_strategy: legacy }, cadenceDefault), "stride_strategy"), false, + `legacy Goal stride_strategy=${legacy} is not displayed`); + assert.equal(Object.hasOwn(replanCadenceEditorDefaults({ ...cadenceDefault, stride_strategy: legacy }, cadenceDefault), "stride_strategy"), false); +} +assert.deepEqual(replanCadenceEditorValue({ completed_todos: 2 }), { count_unit: "completed_todos", count: 2 }); +assert.equal(parseEditableCapabilityJson(cadenceEditor, JSON.stringify({ stride_strategy: "off" })), null, + "the removed stride switch is not an editable JSON field"); +const inheritedReview = { count_unit: "effective_turns", count: 3 }; assert.deepEqual(goalReplanCadenceWriteValue({...inheritedReview, planning_horizon_goal: true}, false, false), - {stride_strategy: "off"}, "displaying the default Goal context does not create an override"); + {}, "displaying the default Goal context does not create an override"); for (const enabled of [true, false]) { assert.deepEqual(goalReplanCadenceWriteValue({...inheritedReview, planning_horizon_goal: enabled}, false, true), - {stride_strategy: "off", planning_horizon_goal: enabled}, "explicit horizon choices survive a form save"); + {planning_horizon_goal: enabled}, "explicit horizon choices survive a form save"); } assert.equal(replanCadenceEditorDefaults({...inheritedReview, planning_horizon_goal: false}, {...cadenceDefault, planning_horizon_goal: true}).planning_horizon_goal, false, "a sparse Goal form displays the effective machine opt-out"); -assert.deepEqual(goalReplanCadenceEditorValue({ stride_strategy: "evidence_conditioned_v1" }, inheritedReview), - { ...inheritedReview, stride_strategy: "evidence_conditioned_v1" }, - "strategy-only Goal settings display the live review interval"); -assert.deepEqual(goalReplanCadenceWriteValue({ ...inheritedReview, stride_strategy: "evidence_conditioned_v1" }, false), - { stride_strategy: "evidence_conditioned_v1" }, - "changing only the strategy must not pin the displayed interval"); -assert.deepEqual(goalReplanCadenceWriteValue({ ...inheritedReview, count: 2, stride_strategy: "evidence_conditioned_v1" }, true), - { count_unit: "effective_turns", count: 2, stride_strategy: "evidence_conditioned_v1" }, +assert.deepEqual(goalReplanCadenceEditorValue({ planning_horizon_goal: false }, inheritedReview), + { ...inheritedReview, planning_horizon_goal: false }, + "horizon-only Goal settings display the live review interval"); +assert.deepEqual(goalReplanCadenceWriteValue({ ...inheritedReview, planning_horizon_goal: false }, false), + { planning_horizon_goal: false }, + "changing only the horizon must not pin the displayed interval"); +assert.deepEqual(goalReplanCadenceWriteValue({ ...inheritedReview, count: 2 }, true), + { count_unit: "effective_turns", count: 2 }, "an edited interval remains an explicit Goal override"); -assert.deepEqual(goalReplanCadenceWriteValue({ count_unit: "completed_todos", count: 2, stride_strategy: "off" }, +assert.deepEqual(goalReplanCadenceWriteValue({ count_unit: "completed_todos", count: 2 }, false), - { stride_strategy: "off" }, + {}, "legacy device units can be inherited without pinning their count"); -assert.equal(hasReplanCadenceOverride({ stride_strategy: "evidence_conditioned_v1" }), false); +assert.equal(hasReplanCadenceOverride({ planning_horizon_goal: false }), false); assert.equal(hasReplanCadenceOverride({ count_unit: "effective_turns", count: 3 }), true); assert.equal(hasReplanCadenceOverride({ completed_todos: 2 }), true, "legacy pinned cadences stay explicit"); -assert.deepEqual(goalReplanCadenceWriteValue({ ...inheritedReview, stride_strategy: "evidence_conditioned_v1" }, true), - { ...inheritedReview, stride_strategy: "evidence_conditioned_v1" }, +assert.deepEqual(goalReplanCadenceWriteValue({ ...inheritedReview }, true), + { ...inheritedReview }, "an explicit interval remains pinned even when it matches the machine policy"); -assert.deepEqual(goalReplanCadenceWriteValue({ count_unit: "effective_turns", count: 2, stride_strategy: "evidence_conditioned_v1" }, false), - { stride_strategy: "evidence_conditioned_v1" }, +assert.deepEqual(goalReplanCadenceWriteValue({ count_unit: "effective_turns", count: 2, yardstick_enabled: true }, false), + { yardstick_enabled: true }, "removing JSON interval fields clears only the cadence, including a previously pinned value"); const storageDefault = { schema_version: "loopx_goal_storage_defaults_v1", new_goal_provider: "sqlite", canonical_creation: true, new_goal_handoff_mode: "hard_lease" }; @@ -172,12 +184,8 @@ assert.deepEqual( "an explicit Goal CI opt-out must survive default projection and omit envelope fields", ); -// Capability defaults may enable Stride without changing saved legacy choices. -const enabledStrideDefault = {...cadenceDefault, stride_strategy: "evidence_conditioned_v1"}; -assert.deepEqual(goalReplanCadenceEditorValue(null, enabledStrideDefault), enabledStrideDefault); -assert.equal(goalReplanCadenceEditorValue({stride_strategy: "off"}, enabledStrideDefault).stride_strategy, "off"); -assert.equal(goalReplanCadenceEditorValue({count_unit: "effective_turns", count: 3}, enabledStrideDefault).stride_strategy, "off"); -assert.equal(projectEditableCapabilityConfiguration(cadenceEditor, {}, enabledStrideDefault).stride_strategy, "evidence_conditioned_v1"); +// An unconfigured Goal displays the live inherited review value unchanged. +assert.deepEqual(goalReplanCadenceEditorValue(null, cadenceDefault), cadenceDefault); // Independent Yardstick inheritance must not be pinned by editing the interval. const yardstickEffective = {...inheritedReview, yardstick_enabled: true}; @@ -186,6 +194,6 @@ assert.deepEqual(goalReplanCadenceWriteValue({...yardstickEffective, count: 2}, {...inheritedReview, count: 2}, "an unchanged inherited measurement choice stays live"); for (const enabled of [true, false]) { assert.deepEqual(goalReplanCadenceWriteValue({...yardstickEffective, yardstick_enabled: enabled}, false, false, true), - {stride_strategy: "off", yardstick_enabled: enabled}, "explicit measurement opt-in and opt-out survive form saving"); + {yardstick_enabled: enabled}, "explicit measurement opt-in and opt-out survive form saving"); } assert.equal(replanCadenceEditorDefaults(yardstickEffective, {...cadenceDefault, yardstick_enabled: false}).yardstick_enabled, true); diff --git a/apps/presentation/dashboard/smoke/delegation-search-browser-smoke.mjs b/apps/presentation/dashboard/smoke/delegation-search-browser-smoke.mjs index 8b8ecf52ae..a672f56f32 100644 --- a/apps/presentation/dashboard/smoke/delegation-search-browser-smoke.mjs +++ b/apps/presentation/dashboard/smoke/delegation-search-browser-smoke.mjs @@ -156,6 +156,39 @@ try { const afterOriginal = await fixture('inspect'); assert.equal(afterOriginal.posts, beforeOriginal.posts); assert.deepEqual(writes.slice(originalWrites), [], 'Reading, retrying and closing originals cannot submit an operation'); + + // Use the real inventory and original Turn reader with the typed overlap + // already exercised by collaboration_turn_context.test.ts. + const inventoryRoute = '**/api/chat/request-inventory?*'; + await page.route(inventoryRoute, async route => { + const response = await route.fetch(); + const data = await response.json(); + const row = data.rows[0]; + if (row) { + row.control_state = 'effect_pending'; + row.agenda.step = 'reconcile_reservation'; + row.returns.push({phase: 'conclusion', status: 'explicit_unverified', error: 'manager_return_payload_conflict'}); + } + await route.fulfill({response, json: data}); + }); + await dialog.getByRole('button', {name: '清空', exact: true}).click(); await rows(12); + const conflicted = dialog.locator('.conversation-request-row').first(); + await conflicted.locator(':scope > summary').scrollIntoViewIfNeeded(); + await page.screenshot({path: resolve(output, 'return-verification-desktop.png')}); + await conflicted.getByText('原操作待收尾', {exact: false}).waitFor(); + await conflicted.getByText('回传待核对', {exact: true}).waitFor(); + assert.equal(await dialog.getByText('回传待核对', {exact: true}).count(), 1); + await page.setViewportSize({width: 390, height: 844}); + await conflicted.locator(':scope > summary').scrollIntoViewIfNeeded(); + await page.screenshot({path: resolve(output, 'return-verification-narrow-summary.png')}); + if (await conflicted.getAttribute('open') === null) await conflicted.locator(':scope > summary').click(); + await conflicted.getByText('核对原对话', {exact: true}).click(); + await conflicted.locator('.conversation-request-detail article').nth(1).waitFor(); + assert.ok(await dialog.evaluate(node => node.scrollWidth <= node.clientWidth + 1)); + await page.screenshot({path: resolve(output, 'return-verification-narrow.png')}); + assert.deepEqual(writes.slice(originalWrites), [], 'Return verification reads the original conversation without changing it'); + await page.unroute(inventoryRoute); + await page.setViewportSize({width: 1440, height: 1000}); await search('no matching request'); await settled(); await dialog.getByText('未找到匹配的委派。', {exact: true}).waitFor(); await dialog.getByRole('button', {name: '清空', exact: true}).click(); await settled(); diff --git a/apps/presentation/dashboard/smoke/execution-feedback-browser-smoke.mjs b/apps/presentation/dashboard/smoke/execution-feedback-browser-smoke.mjs new file mode 100644 index 0000000000..c4172967fa --- /dev/null +++ b/apps/presentation/dashboard/smoke/execution-feedback-browser-smoke.mjs @@ -0,0 +1,104 @@ +// The same native Explore records cross HTTP, client decoding and both readers. +// Fault injection changes only transport; source state and authority stay intact. +import assert from "node:assert/strict"; +import {mkdir} from "node:fs/promises"; +import {resolve} from "node:path"; +import {startHistoryOwner} from "../../../../examples/personal-workspace-browser/research-history.mjs"; +import {launchBrowser, loadPlaywright} from "../../../../examples/dashboard-browser-smoke-support.mjs"; + +const root = resolve(import.meta.dirname, "../../../.."); +const output = resolve(root, ".local/feedback-qualification"); +await mkdir(output, {recursive: true}); +const missing = process.env.LOOPX_FEEDBACK_EXPECT_MISSING === "1"; +const browser = await launchBrowser(loadPlaywright().chromium); +try { + for (const provider of ["file", "sqlite"]) { + const owner = await startHistoryOwner(resolve(root, "apps/presentation/dashboard/src/data/fixtures/execution-feedback-readback.json"), + {provider, assetsDir: process.env.LOOPX_FEEDBACK_ASSETS}); + const page = await browser.newPage({viewport: {width: 1280, height: 900}, locale: "zh-CN"}); + let corrupt = false; + try { + await page.addInitScript(() => localStorage.setItem("loopx-pw-locale", "zh-CN")); + await page.route("**/api/chat/explore-results?*", async route => { + if (!corrupt || new URL(route.request().url()).searchParams.get("view") !== "findings") return route.continue(); + const response = await route.fetch(), packet = await response.json(); + const changed = packet.items.find(item => item.execution_observation); + changed.execution_observation.result_candidate_sha256 = "b".repeat(64); + return route.fulfill({response, json: packet}); + }); + const url = new URL("/chat/", owner.base); + url.search = new URLSearchParams({goalId: "feedback-readback", view: "research", research_goal: "feedback-readback", + research_reading: "history", research_node: "method-choice", research_finding: "result-11"}); + await page.goto(url.href); + const saved = page.locator(".research-saved-evidence"); + await saved.waitFor(); + const capturePrefix = missing ? "before" : "after"; + await page.screenshot({path: resolve(output, `${capturePrefix}-${provider}-default-desktop.png`), animations: "disabled"}); + await page.setViewportSize({width: 390, height: 844}); + assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), "Narrow default page has no horizontal overflow"); + await page.screenshot({path: resolve(output, `${capturePrefix}-${provider}-default-mobile.png`), animations: "disabled"}); + await page.setViewportSize({width: 1280, height: 900}); + await saved.locator(":scope > summary").click(); + const evidence = saved.locator(".goal-explore-results"); + const reader = evidence.locator(".goal-team-result-reader"); + await reader.waitFor(); + const observation = reader.locator("details").filter({has: page.locator("summary", {hasText: "实际执行与资源观测"})}); + if (missing) { + assert.equal(await observation.count(), 0, "Baseline saved findings discarded execution observations"); + await reader.scrollIntoViewIfNeeded(); + await page.screenshot({path: resolve(output, `before-${provider}-desktop.png`), animations: "disabled"}); + continue; + } + assert.equal(await observation.count(), 1); + assert.equal(await observation.getAttribute("open"), null, "Execution detail stays on demand"); + await observation.locator(":scope > summary").click(); + const text = await observation.innerText(); + assert.match(text, /broad-search → targeted-check/); + assert.match(text, /counterexample ruled out/); + assert.match(text, /12\.5 \/ 60/); + assert.match(text, /未测量/); + assert.match(text, /input-v1/); + assert.match(text, /artifact:negative-result/); + const helpTrigger = observation.getByRole("button", {name: "执行观测说明"}); + await helpTrigger.click(); + const helpPopover = observation.locator(".context-help-popover"); + await helpPopover.waitFor({state: "visible"}); + assert.match(await helpPopover.innerText(), /不等于方法有效/); + await page.keyboard.press("Escape"); + await helpPopover.waitFor({state: "hidden"}); + await observation.scrollIntoViewIfNeeded(); + await observation.screenshot({path: resolve(output, `after-${provider}-detail.png`), animations: "disabled"}); + await page.screenshot({path: resolve(output, `after-${provider}-desktop.png`), animations: "disabled"}); + await page.screenshot({path: resolve(output, `after-${provider}-full-page.png`), fullPage: true, animations: "disabled"}); + await page.setViewportSize({width: 390, height: 844}); + await observation.scrollIntoViewIfNeeded(); + assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), "Narrow reader has no horizontal overflow"); + await page.screenshot({path: resolve(output, `after-${provider}-mobile.png`), animations: "disabled"}); + // A taller reading viewport keeps the complete narrow detail visible in + // the guide image; the real 390x844 viewport remains qualified above. + await page.setViewportSize({width: 390, height: 1400}); + await observation.scrollIntoViewIfNeeded(); + await observation.screenshot({path: resolve(output, `after-${provider}-mobile-detail.png`), animations: "disabled"}); + await page.setViewportSize({width: 390, height: 844}); + await evidence.getByRole("combobox", {name: "选择结论"}).selectOption("result-0"); + assert.equal(await observation.count(), 0, "Missing observation adds no invented execution block"); + await evidence.getByRole("combobox", {name: "选择结论"}).selectOption("result-11"); + corrupt = true; + await evidence.getByRole("button", {name: "刷新证据"}).click(); + await evidence.getByRole("alert").waitFor(); + assert.equal(await reader.count(), 0, "Wrong-candidate evidence cannot leave old facts visible"); + corrupt = false; + await evidence.getByRole("button", {name: "刷新证据"}).click(); + await reader.waitFor(); + assert.equal(await observation.count(), 1, "Valid source recovers in place"); + const history = page.locator(".research-history-detail"); + const historicObservation = history.locator("details").filter({has: page.locator("summary", {hasText: "实际执行与资源观测"})}); + await historicObservation.first().locator(":scope > summary").click(); + assert.match(await historicObservation.first().innerText(), /broad-search → targeted-check/, "Append-only history shares the same reader"); + const readback = await (await fetch(`${owner.base}/fixture/readback`)).json(); + assert.equal(readback.source_unchanged, true); + assert.equal(readback.mutation_attempts, 0); + console.log(`${provider}: HTTP -> saved/history reader, missing/rejected/recovery, desktop/narrow PASS`); + } finally {await page.close(); await owner.close();} + } +} finally {await browser.close();} 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 82d120a378..c70f05d42b 100644 --- a/apps/presentation/dashboard/smoke/goal-acceptance-contract-browser-smoke.mjs +++ b/apps/presentation/dashboard/smoke/goal-acceptance-contract-browser-smoke.mjs @@ -212,7 +212,7 @@ try { execution_authority_granted: false, goal_completion_assessed: false, outcomes: [ { - id: "plan", owner_agent_id: "author", objective: "First colliding outcome", revision: 1, + id: "plan", owner_agent_id: "former-author", owner_registration_missing: true, objective: "First colliding outcome", revision: 1, requirements: [ requirement("section:opening", "Colon in the requirement id", "failed"), requirement("detail", "Second unmet requirement", "failed"), @@ -239,12 +239,36 @@ try { await first.locator(".goal-outcome-disclosure > summary").focus(); await page.keyboard.press("Enter"); assert.equal(await first.locator(".goal-outcome-criteria > li").count(), 3); + await first.getByText("Linked work and sources", {exact: true}).click(); + await first.getByText(/former-author \(unregistered for this Goal at readback\)/).waitFor(); + assert.equal(await second.getByText(/unregistered for this Goal/).count(), 0); assert.equal(await second.locator(".goal-outcome-disclosure").getAttribute("open"), null, "Colon-bearing identities do not open another outcome's requirements"); await second.locator(".goal-outcome-disclosure > summary").click(); await second.getByText("Unrelated met requirement", {exact: true}).waitFor(); assert.equal(await outcomes.locator(".goal-outcome-criteria > li:visible").count(), 4, "Each selected outcome exposes every requirement without identity collisions"); + + // A second operator can finish a handoff while the selection form is open. + collision.handoff_receivers = ["receiver"]; + collision.outcomes[1].owner_registration_missing = true; + const handoff = outcomes.locator(".goal-outcome-handoff"); + await handoff.locator("summary").click(); + await handoff.getByRole("button", {name: "Refresh ownership"}).click(); + const source = handoff.getByLabel("Previous owner"); + await source.selectOption(collision.outcomes[1].owner_agent_id); + await handoff.getByLabel("Receiving Agent").selectOption("receiver"); + await handoff.getByRole("checkbox").check(); + // Even if that same outcome now belongs to the other retired source, it + // was never selected for transfer from its new owner. + collision.outcomes[1].owner_agent_id = "former-author"; + await handoff.getByRole("button", {name: "Refresh ownership"}).click(); + const remaining = handoff.getByRole("checkbox", {name: /First colliding outcome/}); + await remaining.waitFor(); + assert.equal(await source.inputValue(), "former-author"); + assert.equal(await remaining.isChecked(), false); + assert.equal(await handoff.getByRole("checkbox", {name: /Second colliding outcome/}).isChecked(), false); + assert.equal(await handoff.getByRole("button", {name: "Preview handoff"}).isDisabled(), true); response = structuredClone(snapshot); payload.run_history.goals[0].acceptance_observation = acceptance; await page.reload({waitUntil: "networkidle"}); diff --git a/apps/presentation/dashboard/smoke/goal-created-session-smoke.ts b/apps/presentation/dashboard/smoke/goal-created-session-smoke.ts index ede6569481..2af4de94e9 100644 --- a/apps/presentation/dashboard/smoke/goal-created-session-smoke.ts +++ b/apps/presentation/dashboard/smoke/goal-created-session-smoke.ts @@ -1,6 +1,8 @@ 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"; +import {preparedAcceptancePlan} from "../src/data/goal-acceptance-actions"; +import {conversationChannelId, conversationContextKey, createChatSession, fetchChatHistory, + readManagedTaskValidation, type ManagedTaskTurn, 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"}; @@ -76,4 +78,52 @@ try { 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;} + +const lineage = {goal_id: target.goalId, agent_id: target.agentId, todo_id: "cart-repair"}; +const turn: ManagedTaskTurn = {session_id: target.sessionId, turn_id: "first-task", client_turn_id: "managed.first-task", + status: "completed", origin: "native_loopx", loopx_execution: true, loopx_request: { + operation: "native_turn", todo_id: lineage.todo_id, + actor: {goal_id: target.goalId, agent_id: target.agentId, session_id: target.sessionId}, + }}; +const postcondition = {schema_version: "loopx_turn_execution_v0", dry_run: false, + validation_stage: "task_postcondition", receipt: {ok: true, lineage}}; +const passingCheck = {schema_version: "loopx_turn_task_validation_v0", ok: true, status: "passed", summary: "Checks passed"}; +const checkedTurn = {...turn, response: {native_loopx: {...postcondition, validation: passingCheck}}}; +assert.equal(readManagedTaskValidation(checkedTurn)?.status, "passed"); +assert.equal(readManagedTaskValidation({...turn, response: {native_loopx: {...postcondition, + validation: {...passingCheck, ok: false, status: "failed", summary: "One required check failed"}}}})?.status, "failed", + "A terminal conversation receipt can carry a failed independent check"); +for (const native_loopx of [ + {...postcondition, dry_run: true, validation: passingCheck}, + {...postcondition, validation_stage: "host_result_contract", validation: passingCheck}, + {...postcondition, validation: {...passingCheck, ok: false}}, + {...postcondition, receipt: {ok: true, lineage: {...lineage, todo_id: "another-task"}}, validation: passingCheck}, +]) { + assert.equal(readManagedTaskValidation({...turn, response: {native_loopx}}), undefined, + "Simulation, unrelated lineage and inconsistent receipts cannot certify the selected Task"); +} +assert.equal(readManagedTaskValidation(turn), undefined, "Legacy responses cannot attest a check"); +assert.equal(readManagedTaskValidation({...checkedTurn, status: "running"}), undefined); +const preparedCheck = (scope: Record): TypedActionProposal => ({ + ...proposal, action_kind: "goal.acceptance.check", status: "preview_ready", + context: {kind: "goal", goal_id: target.goalId}, + permission_classification: "local_command_execution", available_transitions: ["apply"], + normalized_parameters: {goal_id: target.goalId, document: { + objective: "Check the repair", scope, + criteria: [{id: "completion", description: "Use the existing checker", validation_argv: ["loopx:python", "checks.py"]}], + }}, +}); +const scoped = preparedCheck({kind: "selected_work", todo_ids: [lineage.todo_id]}); +assert.equal(preparedAcceptancePlan([scoped], target.goalId, lineage.todo_id)?.proposal, scoped); +for (const scope of [{kind: "goal"}, {kind: "all_advancement"}, + {kind: "selected_work", todo_ids: ["another-task"]}, + {kind: "selected_work", todo_ids: [lineage.todo_id, "another-task"]}]) { + const other = preparedCheck(scope); + assert.equal(preparedAcceptancePlan([other], target.goalId, lineage.todo_id), null); + assert.ok(preparedAcceptancePlan([other], target.goalId), "The regular Goal check remains available in Overview"); +} +assert.equal(preparedAcceptancePlan([scoped, + {...scoped, status: "applied", proposal_id: "confirmed-plan", created_at: "2026-01-01T00:00:02Z"}], + target.goalId, lineage.todo_id), null, "A newer applied plan cannot make an earlier confirmation runnable again"); + console.log("goal-created-session: original owner/history, replay, legacy parity and identity failure/recovery passed"); 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 69d8220693..9f4c5e879f 100644 --- a/apps/presentation/dashboard/smoke/research-evidence-version-browser-smoke.mjs +++ b/apps/presentation/dashboard/smoke/research-evidence-version-browser-smoke.mjs @@ -103,14 +103,19 @@ try { localizedReady = false; const child = JSON.parse(await readFile(resolve(import.meta.dirname, "../src/data/fixtures/case-study-child.json"), "utf8")); const parent = {goal_id: child.parent_goal_id, display_name: "Benchmark", events: [], analyses: []}; + const recordsOnly = structuredClone(child.analyses[0]); + recordsOnly.title = "仅保留研究记录的版本"; + delete recordsOnly.case_study; const second = structuredClone(child.analyses[0]); second.title = "另一版解读"; + second.case_study.title = "修订版:误差与留存证据"; second.case_study.sections[1].citations[0].first_line = 2; - child.analyses.push(second); + child.analyses.push(recordsOnly, second); const study = await start("study", child, parent); const studyRead = await (await fetch(new URL(analysisPath + "?" + new URLSearchParams({goal_id: child.goal_id}), study))).json(); const studyPack = studyRead.pack; - const otherPack = studyRead.catalog.packs.find(pack => pack.pack_id !== studyPack.pack_id); + const otherPack = studyRead.catalog.packs.find(pack => pack.pack_id !== studyPack.pack_id && pack.case_study_summary); + const recordsPack = studyRead.catalog.packs.find(pack => !pack.case_study_summary); assert(otherPack, "Same Goal has two saved versions"); const chapter = studyPack.case_study.sections[1]; const address = new URL("/chat/", study); @@ -118,11 +123,45 @@ try { research_reading: "case", research_analysis_goal: child.goal_id, research_pack: studyPack.pack_id}); address.hash = "case-section-" + studyPack.pack_id + "-" + chapter.id; 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}); + const ordinary = new URL(study); + const fullAxis = page.locator('.research-timeline .research-axis time.is-end[datetime="PT64800S"]'); + await page.goto(ordinary.href); + await fullAxis.waitFor(); + await caseView.waitFor(); + assert.equal(await historyView.getAttribute("aria-pressed"), "true"); + assert.equal(await page.locator(".research-case-reader").count(), 0); + assert.equal(new URL(page.url()).searchParams.has("research_reading"), false); + await caseView.press("Enter"); + await page.locator(".case-opening h2").waitFor(); + await page.goBack(); + await fullAxis.waitFor(); + + await page.setViewportSize({width: 390, height: 900}); + const historyGet = url => url.pathname === "/api/chat/explore-results" + && url.searchParams.get("goal_id") === child.goal_id && url.searchParams.get("view") === "history"; + await page.route(historyGet, route => route.fulfill({status: 503, json: {ok: false}}), {times: 1}); + await page.goto(ordinary.href); + const historyError = page.locator(".research-history-read-error"); + await historyError.waitFor(); + await caseView.waitFor(); + assert.equal(await historyView.getAttribute("aria-pressed"), "true"); + await historyError.getByRole("button", {name: "重试", exact: true}).press("Enter"); + await fullAxis.waitFor(); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false); + + const caseOnly = await start("case-only", {...child, events: []}, parent); + await page.goto(caseOnly); + await page.locator(".case-opening h2").waitFor(); + assert.equal(await caseView.getAttribute("aria-pressed"), "true"); + const caseOnlyReadback = await (await fetch(new URL("/fixture/readback", caseOnly))).json(); + assert(caseOnlyReadback.history_reads > 0 && caseOnlyReadback.source_unchanged); + await page.setViewportSize({width: 1200, height: 900}); + + await page.goto(address.href); + await atChapter(); assert.equal(await caseView.getAttribute("aria-pressed"), "true"); await historyView.press("Enter"); await page.locator(".research-history-heading").waitFor(); @@ -193,6 +232,22 @@ try { await citation.getByRole("button", {name: "关闭原文", exact: true}).click(); assert.equal(new URL(page.url()).hash, address.hash); assert.equal(await citation.count(), 0); + // A stale link can arrive while the current original is scrolled into view. + await page.evaluate(href => {window.location.assign(href);}, bookmark.href); + await citation.locator("pre").first().waitFor(); + const missingCitation = new URL(bookmark); + missingCitation.hash = bookmark.hash.replace(/~[0-9]+$/, "~99"); + const readsBeforeUnknown = sourceRequests.length; + await page.evaluate(href => {window.location.assign(href);}, missingCitation.href); + await page.waitForFunction(() => { + const notice = document.activeElement; + if (!notice?.matches(".case-read-warning[role=status]") || + !notice.textContent.includes("这条链接在所选解读中找不到原文")) return false; + const rect = notice.getBoundingClientRect(); + return rect.top >= 0 && rect.bottom <= innerHeight && rect.width > 0; + }); + assert.equal(sourceRequests.length, readsBeforeUnknown); + assert.equal(await citation.count(), 0); // A valid position from another pack must never fall through to this pack. const misplaced = new URL(bookmark); misplaced.searchParams.set("research_pack", otherPack.pack_id); @@ -229,6 +284,117 @@ try { await page.goForward(); await page.waitForURL(url => url.searchParams.get("goalId") === parent.goal_id); assertParentAddress(); + + // Pinning the default study to its chapter address rereads the same version. + // Its late response must respect the focus returned by the evidence reader. + const defaultStudy = new URL(address); + defaultStudy.searchParams.delete("research_pack"); + defaultStudy.searchParams.delete("research_analysis_goal"); + defaultStudy.hash = ""; + await page.goto(defaultStudy.href); + await page.setViewportSize({width: 390, height: 900}); + await chapterControl.locator("summary").waitFor(); + const isSelectedVersionRead = url => url.origin === defaultStudy.origin && url.pathname === analysisPath + && url.searchParams.get("pack_id") === studyPack.pack_id; + const isLocalizedRead = url => isSelectedVersionRead(url) && url.searchParams.has("output_language"); + const stagedRead = Promise.withResolvers(); + await page.route(isLocalizedRead, async route => { + await stagedRead.promise; + return route.continue(); + }, {times: 1}); + try { + const selectedVersionRequest = page.waitForRequest(request => isLocalizedRead(new URL(request.url()))); + await page.getByRole("navigation", {name: "解读目录"}).getByRole("link").nth(1).press("Enter"); + await selectedVersionRequest; + await atChapter(); + await chapterControl.locator("summary").press("Enter"); + await originalLink.press("Enter"); + await citation.locator("pre").first().waitFor(); + await citation.press("Escape"); + await page.waitForFunction(id => document.activeElement?.id === id, bookmark.hash.slice(1)); + const savedOriginalRead = page.waitForResponse(response => { + const url = new URL(response.url()); + return response.ok() && isSelectedVersionRead(url) && !url.searchParams.has("output_language"); + }); + stagedRead.resolve(); + await (await savedOriginalRead).finished(); + await page.evaluate(() => new Promise(resolvePaint => requestAnimationFrame(() => requestAnimationFrame(resolvePaint)))); + assert.equal(await originalLink.evaluate(link => document.activeElement === link), true, + "A delayed reread of the selected version must leave focus on the citation after closing it"); + assert.equal(new URL(page.url()).hash, address.hash); + } finally { + stagedRead.resolve(); + await page.unroute(isLocalizedRead); + } + await page.setViewportSize({width: 1200, height: 900}); + + // A saved case address is never rewritten to a nearby version. Recover + // explicitly with the owner's version selector or default catalogue read. + const metrics = async () => (await fetch(new URL("/fixture/readback", study))).json(); + const beforeRecovery = await metrics(); + const caseHistoryReads = []; + const observeCaseHistory = request => { + const url = new URL(request.url()); + if (url.pathname === "/api/chat/explore-results" && url.searchParams.get("goal_id") === child.goal_id + && url.searchParams.get("view") === "history") caseHistoryReads.push(url.search); + }; + page.on("request", observeCaseHistory); + const versionWithoutStudy = new URL(address); + versionWithoutStudy.searchParams.set("research_pack", recordsPack.pack_id); + const versionOnly = new URL(versionWithoutStudy); + versionOnly.hash = ""; + await page.goto(versionOnly.href); + await page.getByText("此版本没有已保存的案例解读。", {exact: true}).waitFor({timeout: 6000}); + assert.equal(new URL(page.url()).searchParams.get("research_pack"), recordsPack.pack_id); + await page.goto(versionWithoutStudy.href); + await page.getByText("此版本没有已保存的案例解读。", {exact: true}).waitFor({timeout: 6000}); + assert.equal(new URL(page.url()).searchParams.get("research_pack"), recordsPack.pack_id); + assert.equal(new URL(page.url()).hash, address.hash); + assert.equal(await page.locator(".case-opening h2").count(), 0); + await page.getByRole("combobox", {name: "选择解读版本"}).selectOption(otherPack.pack_id); + await page.locator(".case-opening h2").waitFor(); + assert.equal(new URL(page.url()).searchParams.get("research_pack"), otherPack.pack_id); + assert.equal(await page.locator(".case-opening h2").textContent(), otherPack.case_study_summary.title); + await page.goBack(); + await page.getByText("此版本没有已保存的案例解读。", {exact: true}).waitFor(); + assert.equal(new URL(page.url()).hash, address.hash); + + await page.setViewportSize({width: 390, height: 900}); + const unavailable = new URL(bookmark); + unavailable.searchParams.set("research_pack", "f".repeat(64)); + await page.goto(unavailable.href); + await page.getByText("无法读取链接指定的解读。", {exact: true}).waitFor(); + const exactRetry = page.waitForResponse(response => { + const url = new URL(response.url()); + return url.pathname === analysisPath && url.searchParams.get("pack_id") === unavailable.searchParams.get("research_pack"); + }); + await page.getByRole("button", {name: "重试读取", exact: true}).press("Enter"); + assert.equal((await exactRetry).status(), 409); + assert.equal(new URL(page.url()).hash, unavailable.hash); + const browseSaved = page.getByRole("button", {name: "查看已保存的解读", exact: true}); + await browseSaved.press("Enter"); + await page.getByRole("heading", {name: studyPack.case_study.title, exact: true}).waitFor(); + assert.equal(await page.getByRole("combobox", {name: "选择解读版本"}).evaluate(el => el === document.activeElement), true); + assert.equal(new URL(page.url()).searchParams.get("goalId"), child.goal_id); + assert.equal(new URL(page.url()).hash, ""); + await page.goBack(); + await page.getByText("无法读取链接指定的解读。", {exact: true}).waitFor(); + assert.equal(new URL(page.url()).hash, unavailable.hash); + + const absentChapter = new URL(address); + absentChapter.hash = `case-section-${studyPack.pack_id}-absent`; + await page.goto(absentChapter.href); + await page.getByText("这条链接在所选解读中找不到章节。", {exact: false}).waitFor(); + assert.equal(new URL(page.url()).hash, absentChapter.hash); + await page.getByRole("navigation", {name: "解读目录"}).getByRole("link").nth(1).press("Enter"); + await atChapter(); + assert.equal(await page.getByText("这条链接在所选解读中找不到章节。", {exact: false}).count(), 0); + const afterRecovery = await metrics(); + page.off("request", observeCaseHistory); + assert.equal(afterRecovery.citation_reads, beforeRecovery.citation_reads); + assert.deepEqual(caseHistoryReads, [], "Explicit case links do not read the case's research history"); + assert.equal(afterRecovery.mutation_attempts, beforeRecovery.mutation_attempts); + assert.equal(afterRecovery.source_unchanged, true); console.log("research evidence version: study and history navigation, saved excerpts and chapter position restored"); } finally { releaseOriginal?.(); diff --git a/apps/presentation/dashboard/smoke/status-source-catalog-smoke.ts b/apps/presentation/dashboard/smoke/status-source-catalog-smoke.ts index e783f20df5..3490f58dc9 100644 --- a/apps/presentation/dashboard/smoke/status-source-catalog-smoke.ts +++ b/apps/presentation/dashboard/smoke/status-source-catalog-smoke.ts @@ -116,10 +116,143 @@ equal(activeStatusSourceForUrl(added.catalog, null, added.source.statusUrl, base const configuredHosts = parseConfiguredSshHostCatalog({ ok: true, schema_version: "ssh_host_catalog_v0", - hosts: [{ alias: "remote-lab" }, { alias: "*.example" }, { alias: "remote-lab" }, { alias: "jump_box" }], + hosts: [ + { alias: "remote-lab" }, + { alias: "*.example" }, + { alias: "remote-lab" }, + { alias: "jump_box" }, + { alias: "desk-box" }, + { alias: "desk..backup" }, + { alias: "task-worker" }, + { alias: "lab.sk-integration" }, + { alias: "sk-integration" }, + ], }); equal(defaultConfiguredSshHostsUrl, "/ssh-hosts", "configured Host discovery stays on the active local Dashboard origin"); -deepEqual(configuredHosts.hosts, [{ alias: "remote-lab" }, { alias: "jump_box" }], "only explicit safe SSH aliases enter the browser catalog"); +deepEqual( + configuredHosts.hosts, + [ + { alias: "remote-lab" }, + { alias: "jump_box" }, + { alias: "desk-box" }, + { alias: "desk..backup" }, + { alias: "task-worker" }, + { alias: "lab.sk-integration" }, + { alias: "sk-integration" }, + ], + "only explicit safe SSH aliases enter the browser catalog and feature-off rows keep exact { alias } shape", +); + +const observedHosts = parseConfiguredSshHostCatalog({ + ok: true, + schema_version: "ssh_host_catalog_v0", + hosts: [ + { + alias: "desk-box", + observation: { + schema_version: "session_fabric_ssh_observation_v0", + alias: "desk-box", + connection_state: "connected", + failure_code: null, + checked_at: "2026-11-20T00:00:00Z", + tunnel_latency_ms: 12, + }, + }, + { alias: "desk..backup" }, + { alias: "lab.sk-integration" }, + { alias: "task-worker" }, + { + alias: "sk-integration", + observation: { + schema_version: "session_fabric_ssh_observation_v0", + alias: "sk-integration", + connection_state: "degraded", + failure_code: "unreachable", + checked_at: "2026-11-22T00:00:00Z", + tunnel_latency_ms: null, + }, + }, + ], +}); +deepEqual( + observedHosts.hosts, + [ + { + alias: "desk-box", + observation: { + schema_version: "session_fabric_ssh_observation_v0", + alias: "desk-box", + connection_state: "connected", + failure_code: null, + checked_at: "2026-11-20T00:00:00Z", + tunnel_latency_ms: 12, + }, + }, + { alias: "desk..backup" }, + { alias: "lab.sk-integration" }, + { alias: "task-worker" }, + { + alias: "sk-integration", + observation: { + schema_version: "session_fabric_ssh_observation_v0", + alias: "sk-integration", + connection_state: "degraded", + failure_code: "unreachable", + checked_at: "2026-11-22T00:00:00Z", + tunnel_latency_ms: null, + }, + }, + ], + "optional validated L0 SSH observations round-trip without altering unobserved entries", +); + +let invalidObservationRejected = false; +try { + parseConfiguredSshHostCatalog({ + ok: true, + schema_version: "ssh_host_catalog_v0", + hosts: [ + { + alias: "desk-box", + observation: { + schema_version: "session_fabric_ssh_observation_v0", + alias: "other-host", + connection_state: "connected", + failure_code: null, + checked_at: null, + tunnel_latency_ms: null, + }, + }, + ], + }); +} catch { + invalidObservationRejected = true; +} +assert(invalidObservationRejected, "mismatched or invalid SSH observations fail closed"); + +let credentialObservationRejected = false; +try { + parseConfiguredSshHostCatalog({ + ok: true, + schema_version: "ssh_host_catalog_v0", + hosts: [ + { + alias: "desk-box", + observation: { + schema_version: "session_fabric_ssh_observation_v0", + alias: "sk-" + "proj-abcdef12", + connection_state: "connected", + failure_code: null, + checked_at: null, + tunnel_latency_ms: null, + }, + }, + ], + }); +} catch { + credentialObservationRejected = true; +} +assert(credentialObservationRejected, "sensitive credential prefixes in SSH observations fail closed"); const configuredDraft = configuredSshTunnelDraft("remote-lab", "8876"); assert("command" in configuredDraft, "a configured Host and valid local port produce a tunnel draft"); equal(configuredDraft.command, "ssh -N -L 8876:127.0.0.1:8766 remote-lab", "the UI generates one exact OpenSSH command"); diff --git a/apps/presentation/dashboard/src/data/action-source-basis.ts b/apps/presentation/dashboard/src/data/action-source-basis.ts index 1f2baff596..a5d38cb6ac 100644 --- a/apps/presentation/dashboard/src/data/action-source-basis.ts +++ b/apps/presentation/dashboard/src/data/action-source-basis.ts @@ -5,6 +5,7 @@ const todoBasis = { provider_revision: z.string().min(1), source_authority: z.enum(["file_v0", "sqlite_v0"]), registry_sha256: digest, + source_identity: digest.optional(), }; // Decode existing backend contracts; effect authority and stale-source checks diff --git a/apps/presentation/dashboard/src/data/capability-configuration.ts b/apps/presentation/dashboard/src/data/capability-configuration.ts index 6c61e3d091..1c86cd9628 100644 --- a/apps/presentation/dashboard/src/data/capability-configuration.ts +++ b/apps/presentation/dashboard/src/data/capability-configuration.ts @@ -62,13 +62,19 @@ export function parseEditableCapabilityJson( return value as Record; } -/** Read the legacy cadence without reinterpreting its unit or writing it back. */ +/** + * Read the legacy cadence without reinterpreting its unit or writing it back. + * Evidence-conditioned stride is always on; a legacy saved `stride_strategy` + * is history only, so the editor never displays or resubmits it. + */ export function replanCadenceEditorValue(value: unknown): unknown { const record = configurationObject(value); if (Object.hasOwn(record, "completed_todos") && !Object.hasOwn(record, "count_unit")) { - return { count_unit: "completed_todos", count: record.completed_todos, stride_strategy: "off" }; + return { count_unit: "completed_todos", count: record.completed_todos }; } - return { ...record, stride_strategy: record.stride_strategy ?? "off" }; + const editable = { ...record }; + delete editable.stride_strategy; + return editable; } /** Fill omitted review interval fields from the currently effective value. */ @@ -79,11 +85,10 @@ export function replanCadenceEditorDefaults(effective: unknown, fallback: unknow if (Object.hasOwn(live, "count")) defaults.count = live.count; if (Object.hasOwn(live, "planning_horizon_goal")) defaults.planning_horizon_goal = live.planning_horizon_goal; if (Object.hasOwn(live, "yardstick_enabled")) defaults.yardstick_enabled = live.yardstick_enabled; - // Strategy omission keeps the existing default-off meaning. return defaults; } -/** Show the live interval when a Goal stores only its strategy choice. */ +/** Show the live interval when a Goal stores only horizon or Yardstick choices. */ export function goalReplanCadenceEditorValue(current: unknown, effective: unknown): Record { const inherited = configurationObject(replanCadenceEditorValue(effective)); return current == null ? inherited : { @@ -127,7 +132,7 @@ export function goalExploreWriteValue(draft: Record, modeOverri return value; } -/** A v0 storage selector did not enable creation; opening Settings must not. */ +/** opening Settings must not. */ export function goalStorageEditorValue(value: unknown): unknown { const record = configurationObject(value); return record.schema_version === "loopx_goal_storage_defaults_v0" diff --git a/apps/presentation/dashboard/src/data/chat.ts b/apps/presentation/dashboard/src/data/chat.ts index c3db5a2c22..ef833231a7 100644 --- a/apps/presentation/dashboard/src/data/chat.ts +++ b/apps/presentation/dashboard/src/data/chat.ts @@ -1,3 +1,4 @@ +import {normalizeExploreExecutionObservation} from "../../../../../loopx/control_plane/capabilities/explore_execution_observation.js"; import {normalizeWorkYardstickCapture} from "../../../../../loopx/control_plane/work_items/yardstick_decision.js"; import {sourceReadApiUrl} from "./local-status-query"; import type {OracleEvidence} from "./goal-acceptance-observation"; @@ -34,6 +35,21 @@ export function exportConfigurationBackup(goalIds?: string[]) { }); } +export type ConfigurationBackupComparison = { + ok: boolean; status: "compared"; before_sha256: string; after_sha256: string; + before_goal_ids: string[]; after_goal_ids: string[]; only_in_before: string[]; only_in_after: string[]; + before_machine_configuration_present: boolean; after_machine_configuration_present: boolean; + change_count: number; changes: {path: string; before_present: boolean; after_present: boolean; before?: unknown; after?: unknown}[]; +}; + +export function compareConfigurationSnapshots(before: Record, after: Record) { + const body = JSON.stringify({before, after}); + if (new TextEncoder().encode(body).byteLength > 64 * 1024 * 1024) { + throw new Error("Combined configuration snapshots exceed the 64 MiB comparison limit."); + } + return requestJson("/api/chat/configuration-backup/compare", {method: "POST", body}); +} + export function restoreConfigurationCheckpoint(backup: Record, execute: boolean) { return requestJson("/api/chat/configuration-backup/restore", { method: "POST", body: JSON.stringify({backup, expected_sha256: backup.sha256, execute}), @@ -470,6 +486,7 @@ export const typedActionProposalSchema = z.object({ validation_evidence: z.array(z.string().refine((value) => value.trim().length > 0, "Validation evidence must be non-blank text")), available_transitions: z.array(z.enum(["apply", "cancel", "regenerate", "reject", "defer"])), status: z.enum(["preview_ready", "applying", "gated", "failed", "rejected", "deferred", "cancelled", "stale", "applied"]), + task_execution_dispatch_pending: z.literal(true).optional(), receipt: z.record(z.string(), z.unknown()).nullable(), stale: z.record(z.string(), z.unknown()).nullable(), gate: z.record(z.string(), z.unknown()).nullable().optional(), @@ -1027,6 +1044,7 @@ const chatQueueSchema = z.object({ preview: z.string(), character_count: z.number().int().nonnegative(), attachment_count: z.number().int().nonnegative(), input_revision: z.number().int().nonnegative().default(0), + input_mutation_allowed: z.boolean().optional(), mutation: z.object({action: z.enum(["edit", "cancel"]), operation_id: z.string().min(1), expected_revision: z.number().int().nonnegative(), input_revision: z.number().int().positive(), message: z.string().optional()}).nullable().optional().default(null), @@ -1092,10 +1110,10 @@ const chatMessagePageSchema = z.object({ visible_page_sha256: z.string().regex(/^[a-f0-9]{64}$/).optional(), }); -// A long original transcript can outlive the interactive request budget even -// when each verified page succeeds. Apply the same bounded read deadline to -// its pages and fresh source checks; caller cancellation still takes priority. -const CHAT_HISTORY_READ_TIMEOUT_MS = 30_000; +// Apply one bounded read deadline to transcript pages and fresh source checks. +export const CHAT_HISTORY_READ_TIMEOUT_MS = 30_000; +const MAX_VERIFIED_HISTORY_MESSAGES = 50_000; +const MAX_VERIFIED_HISTORY_BASIS_CHARS = 6 + Math.ceil(MAX_VERIFIED_HISTORY_MESSAGES / 200) * 64; type ChatHistoryReadProgress = { first: ChatSessionSnapshot; @@ -1210,14 +1228,13 @@ async function readChatSessionHistory(session: ChatSessionSummary | string, sign } function historyBasisMatches(basis: string, count: number) { - const match = /^([1-9][0-9]{0,3}):([a-f0-9]+)$/.exec(basis); - return match !== null && count >= 1 && count <= 5000 && Number(match[1]) === count + const match = /^([1-9][0-9]{0,4}):([a-f0-9]+)$/.exec(basis); + return match !== null && count >= 1 && count <= MAX_VERIFIED_HISTORY_MESSAGES && Number(match[1]) === count && match[2].length === Math.ceil(count / 200) * 64; } function historyImageHeaders(linkImages: boolean): HeadersInit | undefined { - // The linked bytes are same-origin resources. A separately configured Chat - // server still uses the compatible inline representation. + // The linked bytes are same-origin resources; a separate Chat origin stays inline. return linkImages && !configuredChatOrigin ? {"X-LoopX-History-Images": "linked"} : undefined; } @@ -1237,7 +1254,7 @@ async function tryResumeChatSessionHistory(session: ChatSessionSummary, saved: C } if (!snapshot || snapshot.history_resume === undefined) return null; // Restart or older service. const proof = z.object({schema_version: z.literal("loopx_chat_history_resume_v1"), - base: z.literal(basis), next: z.string().max(1605)}).safeParse(snapshot.history_resume); + base: z.literal(basis), next: z.string().max(MAX_VERIFIED_HISTORY_BASIS_CHARS)}).safeParse(snapshot.history_resume); if (!proof.success || snapshot.ok !== true || snapshot.schema_version !== "loopx_chat_store_v1" || !snapshot.session || !sameHistorySource(snapshot.session, session) || Object.hasOwn(snapshot, "message_page") || !Array.isArray(snapshot.messages) || snapshot.messages.length > 200 @@ -1727,7 +1744,8 @@ 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)})}), + actor: z.object({goal_id: z.string().min(1), agent_id: z.string().min(1), session_id: z.string().min(1), + goal_instance_id: z.string().min(1).nullable().optional()})}), }).passthrough(); const managedTaskCreationRequestSchema = z.object({ creation_operation_id: z.string().min(1), operation_id: z.string().min(1), @@ -1742,7 +1760,8 @@ const managedTaskEntrySchema = z.object({ok: z.literal(true), session_id: z.stri 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}), + basis_sha256: z.string().min(1)}), reason: z.string().optional(), + completion_turn: managedTaskTurnSchema.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(), @@ -1750,6 +1769,35 @@ const managedTaskEntrySchema = z.object({ok: z.literal(true), session_id: z.stri export type ManagedTaskEntry = z.infer; export type ManagedTaskTurn = z.infer; +const managedTaskValidationSchema = z.object({ + native_loopx: z.object({ + schema_version: z.literal("loopx_turn_execution_v0"), + dry_run: z.literal(false), + validation_stage: z.literal("task_postcondition"), + receipt: z.object({ok: z.literal(true), lineage: z.object({ + goal_id: z.string(), agent_id: z.string(), todo_id: z.string(), + })}), + validation: z.object({ + schema_version: z.literal("loopx_turn_task_validation_v0"), + status: z.enum(["passed", "failed", "inconclusive", "unavailable"]), + ok: z.boolean(), + summary: z.string().trim().min(1).max(240), + }), + }), +}); + +/** Read independent checks from an already verified managed Task turn. */ +export function readManagedTaskValidation(turn: ManagedTaskTurn) { + if (turn.status !== "completed") return undefined; + const parsed = managedTaskValidationSchema.safeParse(turn.response); + if (!parsed.success) return undefined; + const {receipt: {lineage}, validation} = parsed.data.native_loopx; + const {actor, todo_id: todoId} = turn.loopx_request; + if (lineage.goal_id !== actor.goal_id || lineage.agent_id !== actor.agent_id || lineage.todo_id !== todoId + || validation.ok !== (validation.status === "passed")) return undefined; + return validation; +} + 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}` @@ -1780,6 +1828,15 @@ export async function fetchManagedTaskEntry(target: ManagedConversationTarget, o || 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."); + const completionTurn = result.task.state === "ready" ? result.task.completion_turn : undefined; + if (completionTurn) { + const operationId = /^managed\.([A-Za-z0-9._:-]{1,100})$/.exec(completionTurn.client_turn_id)?.[1]; + if (!operationId || !result.task.canonical_done || !result.task.todo_id || completionTurn.status !== "completed" + || completionTurn.loopx_request.actor.goal_instance_id !== session.goal_instance_id) { + throw new Error("The completed Task Turn identity changed."); + } + verifyManagedTaskTurn(completionTurn, target, operationId, result.task.todo_id); + } return result; } @@ -3353,6 +3410,7 @@ const exploreResultPageSchema = z.object({ evidence_refs: z.array(z.string()), last_updated_at: z.string(), measurements: z.unknown().transform(value => normalizeExploreMeasurements(value)).optional(), measurement_error: z.string().optional(), + execution_observation: z.unknown().transform(observation => normalizeExploreExecutionObservation({observation})).optional(), work_yardstick: z.unknown().transform(capture => normalizeWorkYardstickCapture({capture})).optional(), linked_todos_available: z.boolean().optional(), linked_todos: z.array(z.object({ diff --git a/apps/presentation/dashboard/src/data/conversation-requests.ts b/apps/presentation/dashboard/src/data/conversation-requests.ts index 20238d59ee..c674dfecfe 100644 --- a/apps/presentation/dashboard/src/data/conversation-requests.ts +++ b/apps/presentation/dashboard/src/data/conversation-requests.ts @@ -9,7 +9,8 @@ const rowSchema = z.object({request_id: z.string(), goal_id: z.string(), agent_i control_state: z.string().nullable(), brief: requestBriefSchema.nullable().optional(), source_question: z.string(), request_revision: z.number().int().positive().nullable(), read_status: z.string(), decision: z.string(), decision_reason: z.string().nullable().optional(), - returns: z.array(z.object({phase: z.string(), status: z.string(), request_revision: z.number().nullable().optional()})), + returns: z.array(z.object({phase: z.string(), status: z.string(), request_revision: z.number().nullable().optional(), + error: z.string().nullable().optional()})), linked_todos: z.array(z.object({todo_id: z.string(), title: z.string().nullable().optional(), status: z.string().optional()})), evidence_refs: z.array(z.string()), warnings: z.array(z.string()), source_session_id: z.string(), source_turn_id: z.string(), last_event_at: z.string().nullable()}); diff --git a/apps/presentation/dashboard/src/data/conversation-returns.test.mjs b/apps/presentation/dashboard/src/data/conversation-returns.test.mjs index 787e9dc6c3..1198d2e356 100644 --- a/apps/presentation/dashboard/src/data/conversation-returns.test.mjs +++ b/apps/presentation/dashboard/src/data/conversation-returns.test.mjs @@ -224,3 +224,13 @@ assert.deepEqual(conversationPendingReturnSessions(revised), []); revised[0].collaborations[0].returns.unshift({phase: "conclusion", status: "superseded", request_revision: 2}); assert.deepEqual(conversationPendingReturnSessions(revised), [], "A superseded result cannot hide the delivered current conclusion"); + +const documentSource = {role: "agent", session_id: "local", turn_id: "first", message_id: "managed.first.completed", + text: "Your checklist", attachments: [{id: "artifact", name: "checklist.md", mime_type: "text/markdown", + size: 3, data_url: "data:text/markdown;base64,YWJj"}]}; +const liveReply = {role: "assistant", pending: false, sourceSessionId: "local", sourceTurnId: "first", text: "Your checklist"}; +const attach = source => reconcileConversationReturns([liveReply], "local", [source], createReply)[0].attachments; +assert.equal(attach(documentSource)[0].dataUrl, documentSource.attachments[0].data_url); +assert.equal(attach({...documentSource, session_id: "other"}), undefined); +assert.equal(attach({...documentSource, message_id: "commentary"}), undefined); +assert.equal(attach({...documentSource, attachments: [{...documentSource.attachments[0], data_url: "https://example.com/file"}]}), undefined); diff --git a/apps/presentation/dashboard/src/data/conversation-returns.ts b/apps/presentation/dashboard/src/data/conversation-returns.ts index c5e6ec0378..72c3358af1 100644 --- a/apps/presentation/dashboard/src/data/conversation-returns.ts +++ b/apps/presentation/dashboard/src/data/conversation-returns.ts @@ -19,6 +19,25 @@ type ConversationMessage = { text?: string; }; +export function workspaceImageAttachments(attachments?: ChatVisibleMessage["attachments"]): WorkspaceImageAttachment[] | undefined { + return attachments?.map((attachment) => ({ + dataUrl: attachment.data_url, + id: attachment.id, + mimeType: attachment.mime_type, + name: attachment.name, + size: attachment.size, + })); +} + +/** Fetch completed files from the stored assistant message, including on live readback. */ +export function managedReplyDocuments(source: ChatVisibleMessage) { + if (source.role !== "agent" || !source.turn_id || source.message_id !== `managed.${source.turn_id}.completed` + || !source.attachments?.length || !source.attachments.every(file => + (file.mime_type === "text/plain" || file.mime_type === "text/markdown") + && file.data_url.startsWith(`data:${file.mime_type};base64,`))) return undefined; + return workspaceImageAttachments(source.attachments); +} + 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") @@ -97,7 +116,9 @@ 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; + const replyDocuments = row.role === "assistant" && !row.pending && !row.attachments?.length + && source.session_id === sessionId ? managedReplyDocuments(source) : undefined; + const attachments = replyDocuments ?? (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" diff --git a/apps/presentation/dashboard/src/data/fixtures/case-study-child.json b/apps/presentation/dashboard/src/data/fixtures/case-study-child.json index d736ab7f91..9990b1bf9c 100644 --- a/apps/presentation/dashboard/src/data/fixtures/case-study-child.json +++ b/apps/presentation/dashboard/src/data/fixtures/case-study-child.json @@ -2,7 +2,88 @@ "goal_id": "synthetic-case-search", "parent_goal_id": "synthetic-benchmark", "display_name": "Search · Case 研究", - "events": [], + "events": [ + { + "schema_version": "loopx_explore_result_event_v0", + "goal_id": "synthetic-case-search", + "event_kind": "node", + "recorded_at": "2026-11-21T01:00:00Z", + "title": "Can an early candidate satisfy both checks?", + "boundary": { + "raw_task_text_recorded": false, + "raw_logs_recorded": false, + "raw_trajectory_recorded": false, + "raw_session_transcript_recorded": false, + "credential_values_recorded": false, + "absolute_paths_recorded": false + }, + "agent_id": "synthetic-researcher", + "result_id": "history-start", + "node_kind": "question", + "status": "open", + "event_id": "b12628df1f9fcc7c" + }, + { + "schema_version": "loopx_explore_result_event_v0", + "goal_id": "synthetic-case-search", + "event_kind": "finding", + "recorded_at": "2026-11-21T02:00:00Z", + "title": "Early probe missed the second check", + "boundary": { + "raw_task_text_recorded": false, + "raw_logs_recorded": false, + "raw_trajectory_recorded": false, + "raw_session_transcript_recorded": false, + "credential_values_recorded": false, + "absolute_paths_recorded": false + }, + "agent_id": "synthetic-researcher", + "result_id": "ruled-out-probe", + "node_id": "history-start", + "status": "refuted", + "event_id": "c4c1d855090973bd" + }, + { + "schema_version": "loopx_explore_result_event_v0", + "goal_id": "synthetic-case-search", + "event_kind": "node", + "recorded_at": "2026-11-21T17:00:00Z", + "title": "Does the retained candidate cover both cases?", + "boundary": { + "raw_task_text_recorded": false, + "raw_logs_recorded": false, + "raw_trajectory_recorded": false, + "raw_session_transcript_recorded": false, + "credential_values_recorded": false, + "absolute_paths_recorded": false + }, + "agent_id": "synthetic-researcher", + "result_id": "history-end", + "node_kind": "question", + "status": "open", + "event_id": "969d2846d7e02569" + }, + { + "schema_version": "loopx_explore_result_event_v0", + "goal_id": "synthetic-case-search", + "event_kind": "finding", + "recorded_at": "2026-11-21T19:00:00Z", + "title": "Retained candidate covered both cases", + "boundary": { + "raw_task_text_recorded": false, + "raw_logs_recorded": false, + "raw_trajectory_recorded": false, + "raw_session_transcript_recorded": false, + "credential_values_recorded": false, + "absolute_paths_recorded": false + }, + "agent_id": "synthetic-researcher", + "result_id": "recorded-outcome", + "node_id": "history-end", + "status": "confirmed", + "event_id": "da42d4af65d99f3a" + } + ], "analyses": [ { "title": "初版解读", diff --git a/apps/presentation/dashboard/src/data/fixtures/execution-feedback-readback.json b/apps/presentation/dashboard/src/data/fixtures/execution-feedback-readback.json new file mode 100644 index 0000000000..74e2c7121f --- /dev/null +++ b/apps/presentation/dashboard/src/data/fixtures/execution-feedback-readback.json @@ -0,0 +1,331 @@ +{ + "goal_id": "feedback-readback", + "display_name": "Method feedback", + "events": [ + { + "schema_version": "loopx_explore_result_event_v0", + "goal_id": "feedback-readback", + "event_kind": "node", + "recorded_at": "2026-01-01T00:00:00Z", + "title": "Compare a method and its actual execution", + "boundary": { + "raw_task_text_recorded": false, + "raw_logs_recorded": false, + "raw_trajectory_recorded": false, + "raw_session_transcript_recorded": false, + "credential_values_recorded": false, + "absolute_paths_recorded": false + }, + "summary": "Read the recorded method, deviation and result; acceptance stays independent.", + "result_id": "method-choice", + "node_kind": "area", + "status": "open", + "event_id": "8b0bf5d2d23f9d6f" + }, + { + "schema_version": "loopx_explore_result_event_v0", + "goal_id": "feedback-readback", + "event_kind": "finding", + "recorded_at": "2026-01-01T00:01:00Z", + "title": "Observation 0", + "boundary": { + "raw_task_text_recorded": false, + "raw_logs_recorded": false, + "raw_trajectory_recorded": false, + "raw_session_transcript_recorded": false, + "credential_values_recorded": false, + "absolute_paths_recorded": false + }, + "summary": "A negative result remains negative. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable.", + "agent_id": "reader-agent", + "evidence_refs": [ + "artifact:negative-result" + ], + "result_id": "result-0", + "node_id": "method-choice", + "status": "refuted", + "event_id": "fe63a49692bf13ca" + }, + { + "schema_version": "loopx_explore_result_event_v0", + "goal_id": "feedback-readback", + "event_kind": "finding", + "recorded_at": "2026-01-01T00:02:00Z", + "title": "Observation 1", + "boundary": { + "raw_task_text_recorded": false, + "raw_logs_recorded": false, + "raw_trajectory_recorded": false, + "raw_session_transcript_recorded": false, + "credential_values_recorded": false, + "absolute_paths_recorded": false + }, + "summary": "A negative result remains negative. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable.", + "agent_id": "reader-agent", + "evidence_refs": [ + "artifact:negative-result" + ], + "result_id": "result-1", + "node_id": "method-choice", + "status": "refuted", + "event_id": "4a83ea109c7241d1" + }, + { + "schema_version": "loopx_explore_result_event_v0", + "goal_id": "feedback-readback", + "event_kind": "finding", + "recorded_at": "2026-01-01T00:03:00Z", + "title": "Observation 2", + "boundary": { + "raw_task_text_recorded": false, + "raw_logs_recorded": false, + "raw_trajectory_recorded": false, + "raw_session_transcript_recorded": false, + "credential_values_recorded": false, + "absolute_paths_recorded": false + }, + "summary": "A negative result remains negative. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable.", + "agent_id": "reader-agent", + "evidence_refs": [ + "artifact:negative-result" + ], + "result_id": "result-2", + "node_id": "method-choice", + "status": "refuted", + "event_id": "28ab31ca7421ba95" + }, + { + "schema_version": "loopx_explore_result_event_v0", + "goal_id": "feedback-readback", + "event_kind": "finding", + "recorded_at": "2026-01-01T00:04:00Z", + "title": "Observation 3", + "boundary": { + "raw_task_text_recorded": false, + "raw_logs_recorded": false, + "raw_trajectory_recorded": false, + "raw_session_transcript_recorded": false, + "credential_values_recorded": false, + "absolute_paths_recorded": false + }, + "summary": "A negative result remains negative. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable.", + "agent_id": "reader-agent", + "evidence_refs": [ + "artifact:negative-result" + ], + "result_id": "result-3", + "node_id": "method-choice", + "status": "refuted", + "event_id": "42dd1e21cfdfd704" + }, + { + "schema_version": "loopx_explore_result_event_v0", + "goal_id": "feedback-readback", + "event_kind": "finding", + "recorded_at": "2026-01-01T00:05:00Z", + "title": "Observation 4", + "boundary": { + "raw_task_text_recorded": false, + "raw_logs_recorded": false, + "raw_trajectory_recorded": false, + "raw_session_transcript_recorded": false, + "credential_values_recorded": false, + "absolute_paths_recorded": false + }, + "summary": "A negative result remains negative. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable.", + "agent_id": "reader-agent", + "evidence_refs": [ + "artifact:negative-result" + ], + "result_id": "result-4", + "node_id": "method-choice", + "status": "refuted", + "event_id": "f6e4e52febefe975" + }, + { + "schema_version": "loopx_explore_result_event_v0", + "goal_id": "feedback-readback", + "event_kind": "finding", + "recorded_at": "2026-01-01T00:06:00Z", + "title": "Observation 5", + "boundary": { + "raw_task_text_recorded": false, + "raw_logs_recorded": false, + "raw_trajectory_recorded": false, + "raw_session_transcript_recorded": false, + "credential_values_recorded": false, + "absolute_paths_recorded": false + }, + "summary": "A negative result remains negative. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable.", + "agent_id": "reader-agent", + "evidence_refs": [ + "artifact:negative-result" + ], + "result_id": "result-5", + "node_id": "method-choice", + "status": "refuted", + "event_id": "437d3b06c356a3e4" + }, + { + "schema_version": "loopx_explore_result_event_v0", + "goal_id": "feedback-readback", + "event_kind": "finding", + "recorded_at": "2026-01-01T00:07:00Z", + "title": "Observation 6", + "boundary": { + "raw_task_text_recorded": false, + "raw_logs_recorded": false, + "raw_trajectory_recorded": false, + "raw_session_transcript_recorded": false, + "credential_values_recorded": false, + "absolute_paths_recorded": false + }, + "summary": "A negative result remains negative. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable.", + "agent_id": "reader-agent", + "evidence_refs": [ + "artifact:negative-result" + ], + "result_id": "result-6", + "node_id": "method-choice", + "status": "refuted", + "event_id": "e351ef2cb007f74e" + }, + { + "schema_version": "loopx_explore_result_event_v0", + "goal_id": "feedback-readback", + "event_kind": "finding", + "recorded_at": "2026-01-01T00:08:00Z", + "title": "Observation 7", + "boundary": { + "raw_task_text_recorded": false, + "raw_logs_recorded": false, + "raw_trajectory_recorded": false, + "raw_session_transcript_recorded": false, + "credential_values_recorded": false, + "absolute_paths_recorded": false + }, + "summary": "A negative result remains negative. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable.", + "agent_id": "reader-agent", + "evidence_refs": [ + "artifact:negative-result" + ], + "result_id": "result-7", + "node_id": "method-choice", + "status": "refuted", + "event_id": "8517c1d3e3b15aea" + }, + { + "schema_version": "loopx_explore_result_event_v0", + "goal_id": "feedback-readback", + "event_kind": "finding", + "recorded_at": "2026-01-01T00:09:00Z", + "title": "Observation 8", + "boundary": { + "raw_task_text_recorded": false, + "raw_logs_recorded": false, + "raw_trajectory_recorded": false, + "raw_session_transcript_recorded": false, + "credential_values_recorded": false, + "absolute_paths_recorded": false + }, + "summary": "A negative result remains negative. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable.", + "agent_id": "reader-agent", + "evidence_refs": [ + "artifact:negative-result" + ], + "result_id": "result-8", + "node_id": "method-choice", + "status": "refuted", + "event_id": "bf7613aaa94c7698" + }, + { + "schema_version": "loopx_explore_result_event_v0", + "goal_id": "feedback-readback", + "event_kind": "finding", + "recorded_at": "2026-01-01T00:10:00Z", + "title": "Observation 9", + "boundary": { + "raw_task_text_recorded": false, + "raw_logs_recorded": false, + "raw_trajectory_recorded": false, + "raw_session_transcript_recorded": false, + "credential_values_recorded": false, + "absolute_paths_recorded": false + }, + "summary": "A negative result remains negative. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable.", + "agent_id": "reader-agent", + "evidence_refs": [ + "artifact:negative-result" + ], + "result_id": "result-9", + "node_id": "method-choice", + "status": "refuted", + "event_id": "e2e4af3af1a5b077" + }, + { + "schema_version": "loopx_explore_result_event_v0", + "goal_id": "feedback-readback", + "event_kind": "finding", + "recorded_at": "2026-01-01T00:11:00Z", + "title": "Observation 10", + "boundary": { + "raw_task_text_recorded": false, + "raw_logs_recorded": false, + "raw_trajectory_recorded": false, + "raw_session_transcript_recorded": false, + "credential_values_recorded": false, + "absolute_paths_recorded": false + }, + "summary": "A negative result remains negative. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable.", + "agent_id": "reader-agent", + "evidence_refs": [ + "artifact:negative-result" + ], + "result_id": "result-10", + "node_id": "method-choice", + "status": "refuted", + "event_id": "9025be02e1a9ab01" + }, + { + "schema_version": "loopx_explore_result_event_v0", + "goal_id": "feedback-readback", + "event_kind": "finding", + "recorded_at": "2026-01-01T00:12:00Z", + "title": "Recorded method change", + "boundary": { + "raw_task_text_recorded": false, + "raw_logs_recorded": false, + "raw_trajectory_recorded": false, + "raw_session_transcript_recorded": false, + "credential_values_recorded": false, + "absolute_paths_recorded": false + }, + "summary": "A negative result remains negative. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable. The same long scope boundary remains readable.", + "agent_id": "reader-agent", + "evidence_refs": [ + "artifact:negative-result" + ], + "result_id": "result-11", + "node_id": "method-choice", + "status": "refuted", + "execution_observation": { + "candidate_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "change_reason": "The counterexample ruled out the planned search.", + "elapsed_seconds": 12.5, + "evidence_refs": [ + "artifact:negative-result" + ], + "executed_method_id": "targeted-check", + "input_revision": "input-v1", + "limit_seconds": 60, + "planned_method_id": "broad-search", + "result_candidate_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "result_ref": "artifact:negative-result", + "schema_version": "explore_execution_observation_v0", + "search_iterations": null, + "stop_reason": null + }, + "event_id": "686464f745c278cf" + } + ] +} diff --git a/apps/presentation/dashboard/src/data/goal-acceptance-actions.ts b/apps/presentation/dashboard/src/data/goal-acceptance-actions.ts index c956403af4..f5121100ad 100644 --- a/apps/presentation/dashboard/src/data/goal-acceptance-actions.ts +++ b/apps/presentation/dashboard/src/data/goal-acceptance-actions.ts @@ -24,7 +24,7 @@ const preparedDocument = z.object({objective: z.string().min(1), oracle: z.object({output_refs: z.array(z.string())}).passthrough().optional(), }).passthrough()).min(1), }).passthrough(); -export function preparedAcceptancePlan(proposals: TypedActionProposal[], goalId: string) { +export function preparedAcceptancePlan(proposals: TypedActionProposal[], goalId: string, originalTodoId?: string) { // Never resurrect an older draft after the newest plan was applied, cancelled // or invalidated. Ambiguous creation order requires a fresh Agent proposal. const matching = proposals.filter(proposal => proposal.action_kind === "goal.acceptance.check" @@ -38,5 +38,9 @@ export function preparedAcceptancePlan(proposals: TypedActionProposal[], goalId: || !proposal.available_transitions.includes("apply")) return null; const input = proposal.normalized_parameters.document as Record | undefined; const parsed = preparedDocument.safeParse(input?.outcome_id === undefined ? input : proposal.normalized_parameters.resolved_document); - return parsed.success ? {proposal, document: parsed.data} : null; + if (!parsed.success) return null; + const {scope} = parsed.data; + if (originalTodoId !== undefined && (scope.kind !== "selected_work" + || scope.todo_ids.length !== 1 || scope.todo_ids[0] !== originalTodoId)) return null; + return {proposal, document: parsed.data}; } diff --git a/apps/presentation/dashboard/src/data/goal-acceptance-observation.ts b/apps/presentation/dashboard/src/data/goal-acceptance-observation.ts index cd50a77ad6..242310f1a4 100644 --- a/apps/presentation/dashboard/src/data/goal-acceptance-observation.ts +++ b/apps/presentation/dashboard/src/data/goal-acceptance-observation.ts @@ -8,9 +8,10 @@ export const oracleEvidenceSchema = z.object({source_id: z.string(), source_dige export type OracleEvidence = z.infer; export const outcomeRequirementsSchema = z.object({schema_version: z.literal("loopx_goal_outcomes_v0"), revision: z.number().int().positive(), current_lifetime: z.boolean(), execution_authority_granted: z.literal(false), goal_completion_assessed: z.literal(false), - outcomes: z.array(z.object({id: z.string(), owner_agent_id: z.string(), objective: z.string(), revision: z.number().int().positive(), + handoff_receivers: z.array(z.string()).optional(), + outcomes: z.array(z.object({id: z.string(), declaration_owner_agent_id: z.string().optional(), owner_agent_id: z.string(), owner_registration_missing: z.literal(true).optional(), objective: z.string(), revision: z.number().int().positive(), requirements: z.array(z.object({id: z.string(), description: z.string(), - agent_review: z.object({id: z.string(), conclusion: z.enum(["met", "unmet", "uncertain"]), evidence_refs: z.array(z.string()), note: z.string(), basis_current: z.boolean(), independently_verified: z.literal(false)}).optional(), + agent_review: z.object({id: z.string(), recorded_for_agent_id: z.string().optional(), conclusion: z.enum(["met", "unmet", "uncertain"]), evidence_refs: z.array(z.string()), note: z.string(), basis_current: z.boolean(), independently_verified: z.literal(false)}).optional(), planning_satisfied: z.boolean(), status: z.enum(["unverified", "stale", "failed", "partial", "accepted", "held"])})), todo_ids: z.array(z.string()), sources: z.array(z.object({ref: z.string(), summary: z.string()})), work: z.array(z.object({todo_id: z.string(), status: z.string()})), diff --git a/apps/presentation/dashboard/src/data/ssh-host-catalog.ts b/apps/presentation/dashboard/src/data/ssh-host-catalog.ts index e761c18942..5075089ee3 100644 --- a/apps/presentation/dashboard/src/data/ssh-host-catalog.ts +++ b/apps/presentation/dashboard/src/data/ssh-host-catalog.ts @@ -1,7 +1,15 @@ +import { + decodeSshHostObservationWith, + isSafeHostAlias, + type SshHostObservation, +} from "../../../../../loopx/control_plane/collaboration/session_quota_fabric_contract.js"; +import { parseIsoTimestamp } from "../../../../../loopx/control_plane/runtime_timestamp.js"; + export const defaultConfiguredSshHostsUrl = "/ssh-hosts"; export type ConfiguredSshHost = { alias: string; + observation?: SshHostObservation; }; export type ConfiguredSshHostCatalog = { @@ -9,10 +17,8 @@ export type ConfiguredSshHostCatalog = { schemaVersion: "ssh_host_catalog_v0"; }; -const safeAliasPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/; - export function isConfiguredSshHostAlias(value: unknown): value is string { - return typeof value === "string" && safeAliasPattern.test(value.trim()); + return isSafeHostAlias(value); } export function parseConfiguredSshHostCatalog(value: unknown): ConfiguredSshHostCatalog { @@ -24,12 +30,25 @@ export function parseConfiguredSshHostCatalog(value: unknown): ConfiguredSshHost throw new Error("SSH Host 列表协议不兼容,请更新本机 LoopX 服务。"); } const seen = new Set(); - const hosts = payload.hosts.flatMap((value) => { - if (!value || typeof value !== "object" || Array.isArray(value)) return []; - const alias = String((value as Record).alias ?? "").trim(); + const hosts = payload.hosts.flatMap((item): ConfiguredSshHost[] => { + if (!item || typeof item !== "object" || Array.isArray(item)) return []; + const record = item as Record; + const alias = String(record.alias ?? "").trim(); if (!isConfiguredSshHostAlias(alias) || seen.has(alias)) return []; seen.add(alias); - return [{ alias }]; + if (record.observation === undefined || record.observation === null) { + return [{ alias }]; + } + const observation = decodeSshHostObservationWith(record.observation, { + fail: (message) => { + throw new Error(`SSH Host observation 无效:${message}`); + }, + parseTimestamp: parseIsoTimestamp, + }); + if (observation.alias !== alias) { + throw new Error(`SSH Host observation 别名不匹配:${observation.alias} !== ${alias}`); + } + return [{ alias, observation }]; }); return { hosts, schemaVersion: "ssh_host_catalog_v0" }; } diff --git a/apps/presentation/dashboard/src/data/status.ts b/apps/presentation/dashboard/src/data/status.ts index b79f89b55d..72d8d1e663 100644 --- a/apps/presentation/dashboard/src/data/status.ts +++ b/apps/presentation/dashboard/src/data/status.ts @@ -533,8 +533,16 @@ export const projectMapSchema = z.object({ }); export const runRecordSchema = z.object({ + agent_id: z.string().nullish().catch(null), generated_at: z.string(), goal_id: z.string(), + turn_instance_id: z.string().nullish().catch(null), + execution_ref: z.string().regex(/^[a-f0-9]{64}$/).optional().catch(undefined), + agent_vision: z.record(z.string(), z.unknown()).nullish().catch(null), + vision_checkpoint: z.object({ + schema_version: z.literal("vision_checkpoint_v0"), + decision: z.string(), + }).nullish().catch(null), classification: z.string().optional().nullable(), lifecycle_phase: z.string().optional().nullable(), lifecycle_flags: z.array(z.string()).optional().default([]), @@ -606,12 +614,11 @@ export const runGoalSchema = z.object({ turn_started_at: z.string().optional().nullable(), last_turn_ended_at: z.string().optional().nullable(), last_event_at: z.string().optional().nullable(), - // This is cadence evidence about observed host activity, not proof that - // a scheduled prompt was delivered or an agent started. + delivery_window: z.object({ schema_version: z.string().optional(), state: z.enum(["fresh", "stale", "missing", "unknown"]).catch("unknown"), - reason: z.enum(["no_expectation", "no_observation", "unparseable_observation"]).optional().nullable(), + reason: z.enum(["no_expectation", "no_observation", "unparseable_observation", "unverified_activity"]).optional().nullable(), last_observed_at: z.string().optional().nullable(), age_seconds: z.number().optional().nullable(), age_hours: z.number().optional().nullable(), diff --git a/apps/presentation/dashboard/src/data/use-bound-conversation.ts b/apps/presentation/dashboard/src/data/use-bound-conversation.ts index 9db4c27430..eb41157328 100644 --- a/apps/presentation/dashboard/src/data/use-bound-conversation.ts +++ b/apps/presentation/dashboard/src/data/use-bound-conversation.ts @@ -1,5 +1,5 @@ import { useEffect, useState } from "react"; -import { resolveBoundConversation, +import { CHAT_HISTORY_READ_TIMEOUT_MS, resolveBoundConversation, type BoundConversationTarget, type ChatSessionSummary, type BoundConversationSource } from "./chat"; /** Reads the source's title and executor. Admission remains with the Core owner. */ @@ -12,7 +12,7 @@ export function useBoundConversation(target: BoundConversationTarget | null, ena if (!enabled || bindingId === undefined || sessionId === undefined) return; let active = true; const controller = new AbortController(); - const timeout = setTimeout(() => controller.abort(), 5000); + const timeout = setTimeout(() => controller.abort(), CHAT_HISTORY_READ_TIMEOUT_MS); resolveBoundConversation({ bindingId, sessionId }, controller.signal) .then(({session, source}) => { if (!active) return; diff --git a/apps/presentation/dashboard/src/data/use-lark-apps.ts b/apps/presentation/dashboard/src/data/use-lark-apps.ts index 82d58d3bbe..55e41a3476 100644 --- a/apps/presentation/dashboard/src/data/use-lark-apps.ts +++ b/apps/presentation/dashboard/src/data/use-lark-apps.ts @@ -21,7 +21,7 @@ export function useLarkApps() { if (!active()) return; setApps(profiles); let next = 0; - // A slow profile neither holds the catalog nor other profile results. + const worker = async () => { while (active() && next < profiles.length) { const profile = profiles[next++]; diff --git a/apps/presentation/dashboard/src/data/workspace-progressive-status.ts b/apps/presentation/dashboard/src/data/workspace-progressive-status.ts index 5c771f0df4..7264bc259b 100644 --- a/apps/presentation/dashboard/src/data/workspace-progressive-status.ts +++ b/apps/presentation/dashboard/src/data/workspace-progressive-status.ts @@ -49,12 +49,10 @@ export function scopeWorkspaceDirectory( /** * Snapshots a same-source read may keep visible while it reconciles. - * * A directory entry is the cheap authoritative signal for "this Goal's - * lifecycle did not move here". It does not establish Todo freshness: a full - * refresh still re-reads retained Goals. A partial retry or known action may - * skip unaffected peers. Touched Goals and entries that moved or left the - * directory lose their snapshot. + * lifecycle did not move here". A full refresh still re-reads retained Goals; + * a partial retry or known action may skip unaffected peers. Touched Goals and + * entries that moved or left the directory lose their snapshot. */ export function reusableGoalSnapshots( previous: Pick | null, diff --git a/apps/presentation/dashboard/src/features/personal-workspace/attached-agent-conversations.css b/apps/presentation/dashboard/src/features/personal-workspace/attached-agent-conversations.css index 80461ad86d..93a3a02355 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/attached-agent-conversations.css +++ b/apps/presentation/dashboard/src/features/personal-workspace/attached-agent-conversations.css @@ -43,12 +43,16 @@ .goal-agent-work-page .attached-conversation-heading h2 {overflow-wrap: anywhere;} .agent-work-navigation {display: flex; flex-wrap: wrap; align-items: center; gap: 8px; min-width: 0;} .agent-work-navigation select, .agent-work-directory button {font: inherit; border: 1px solid var(--pw-line); background: var(--pw-card); color: var(--pw-text); border-radius: 6px; padding: 8px 12px; min-height: 44px; max-width: 100%;} -.agent-work-directory {display: grid; gap: 12px; padding-block: 24px;} -.agent-work-directory button {text-align: left; cursor: pointer;} +.agent-work-directory {display: grid; gap: 10px; padding-block: 20px; min-width: 0;} +.agent-work-directory-row {display: grid; gap: 6px; padding: 10px 12px; border: 1px solid var(--pw-line); border-radius: 8px; background: var(--pw-card); min-width: 0;} +.agent-work-directory-top {display: flex; flex-wrap: wrap; align-items: center; gap: 6px 8px; min-width: 0;} +.agent-work-directory-top .pw-roster-progress {margin-left: auto;} +.agent-work-directory button {text-align: left; cursor: pointer; font-weight: 600;} .agent-work-unavailable {padding-block: 24px; color: var(--pw-muted); line-height: var(--leading-prose);} .goal-agent-work-page .attached-conversation-content {flex: 1; display: flex; flex-direction: column; padding: 0 0 16px; overflow: auto;} .goal-agent-work-page .attached-conversation-content > p {margin-block: 8px;} -.goal-agent-work-page .attached-conversation-source {display: flex; align-items: center; gap: 8px; font-size: var(--text-caption); color: var(--pw-muted);} +.goal-agent-work-page .attached-conversation-source {display: flex; flex-wrap: wrap; align-items: center; gap: 6px 8px; font-size: var(--text-caption); color: var(--pw-muted); min-width: 0;} +.attached-connection-meta {display: grid; gap: 6px; min-width: 0;} .goal-agent-work-page .attached-conversation-messages {flex: 1; min-height: 160px; max-height: none; margin-block: 12px;} .goal-agent-work-page .attached-conversation-content > button {align-self: flex-start; min-height: 44px;} .goal-agent-work-page form {flex-shrink: 0; display: flex; gap: 12px; align-items: flex-end; border-top: 1px solid var(--pw-line); padding-top: 8px;} diff --git a/apps/presentation/dashboard/src/features/personal-workspace/attached-agent-conversations.tsx b/apps/presentation/dashboard/src/features/personal-workspace/attached-agent-conversations.tsx index 7f490d8abd..5c4b7bf95a 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/attached-agent-conversations.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/attached-agent-conversations.tsx @@ -3,6 +3,8 @@ import {ExternalLink, Keyboard} from "lucide-react"; import {AttachedConversationTimeline, type ConversationRecord, type ContentPage} from "./attached-conversation-record"; import {composerKeyAction} from "./composer-keyboard"; import {ContextHelp} from "./context-help"; +import {deriveAttachedWorkerStatus} from "./collaboration-status"; +import {WorkerNowLine, WorkerScopeTag, WorkerStateBadge} from "./worker-roster"; import "./attached-agent-conversations.css"; export type Binding = {agent_id: string; thread_id: string; binding_ref: string}; @@ -91,8 +93,8 @@ async function readVisiblePage(params: URLSearchParams, current: () => boolean): } /** Remount on binding changes so history, live readers and pending input cannot cross Sessions. */ -export function AttachedConversation({goalId, binding, zh, reconnect}: { - goalId: string; binding: Binding; zh: boolean; reconnect: () => void; +export function AttachedConversation({goalId, binding, agentLabel, hostSurfaces, zh, reconnect}: { + goalId: string; binding: Binding; agentLabel?: string; hostSurfaces?: readonly string[]; zh: boolean; reconnect: () => void; }) { const [messages, setMessages] = useState([]); const [snapshot, setSnapshot] = useState(null); @@ -509,13 +511,29 @@ export function AttachedConversation({goalId, binding, zh, reconnect}: { ? (zh ? "无法验证原会话的绑定或访问权限。" : "This conversation's binding or access could not be verified.") : error; const connectionError = connectionMessage ?

{connectionMessage}

: null; + const attachedStatus = deriveAttachedWorkerStatus({ + agentId: binding.agent_id, + label: agentLabel, + connected: snapshot?.connected, + canReply: snapshot?.can_reply, + activeTurn: activeRevision !== null, + liveActive, + bindingRejected: bindingReadRejected, + bindingError: error, + turnModel, + hostSurfaces, + includeFallbackNow: false, + locale: zh ? "zh-CN" : "en", + }); return
{recoveryError ?

{recoveryError}

: null} {sendNotice ?

{sendNotice}

: null} -
+
- Codex App + + + Codex App

{zh ? "已保存消息与工具记录自动更新;实时内容来自原宿主。" : "Saved messages and tools update automatically; live content comes from the original host."}

@@ -523,6 +541,7 @@ export function AttachedConversation({goalId, binding, zh, reconnect}: { {connectionStatus} {activeRevision !== null ? <>{" · "}{turnProfile} : null}

: null} +
diff --git a/apps/presentation/dashboard/src/features/personal-workspace/attached-conversation-record.tsx b/apps/presentation/dashboard/src/features/personal-workspace/attached-conversation-record.tsx index 129b1d6d56..d51dbd6365 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/attached-conversation-record.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/attached-conversation-record.tsx @@ -6,7 +6,7 @@ export type ConversationRecord = { id: string; end: number; role: "user" | "assistant" | "tool" | "activity"; kind: string; label: string; text: string; truncated: boolean; timestamp?: string | null; content_ref?: string; redacted?: boolean; unavailable?: string; - /** Saved shell observations only; neither inferred failures nor task acceptance. */ + /** Saved shell observations only; */ tool_exit_codes?: number[]; }; export type ContentPage = {text: string; next_offset: number; has_more: boolean}; diff --git a/apps/presentation/dashboard/src/features/personal-workspace/capability-localization.ts b/apps/presentation/dashboard/src/features/personal-workspace/capability-localization.ts index bb4d4f76dc..f93f635ee8 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/capability-localization.ts +++ b/apps/presentation/dashboard/src/features/personal-workspace/capability-localization.ts @@ -25,7 +25,11 @@ const capabilityCopy: Record> = { displayName: "Model and executor", description: "Guides the steward executor, model, and selection boundary for this machine. A pinned route blocks substitution; a flexible pool permits only authorized fallback.", }, - todo_replan_cadence: { displayName: "Goal review and stride", description: "Set review frequency and optionally choose a versioned stride strategy for work scope and route changes." }, + steward_memory: { + displayName: "Isolated OpenViking memory", + description: "Connects owner private steward conversations to an isolated OpenViking memory namespace with per-speaker preferences and bounded recall.", + }, + todo_replan_cadence: { displayName: "Goal review and stride", description: "Set review frequency. Evidence-conditioned stride (v1) is always on and reviews work scope and route changes." }, change_quality_qualification: { displayName: "Change quality qualification", description: "Prepares a provider-neutral review packet, allows at most one policy-authorized safe-fix pass, and can require an exact-diff receipt.", @@ -95,7 +99,11 @@ const capabilityCopy: Record> = { displayName: "模型与执行器", description: "配置本机管家的执行器、模型与选择边界;锁定路径禁止替代,灵活池只允许在已授权范围内回退。", }, - todo_replan_cadence: { displayName: "Goal 复盘与步幅", description: "设置复盘周期,可选用带版本的步幅策略,调节工作大小与路线变化。" }, + steward_memory: { + displayName: "独立 OpenViking 长期记忆", + description: "为本人私聊管家启用独立身份的 OpenViking 记忆命名空间:按已验证发言人持久化偏好、跨会话按需检索并限制超时,不向群聊或工作 Agent 泄露。", + }, + todo_replan_cadence: { displayName: "Goal 复盘与步幅", description: "设置复盘周期。依据证据的步幅策略(v1)始终开启,复核工作大小与路线变化。" }, change_quality_qualification: { displayName: "变更质量验证", description: "生成与 Provider 无关的审阅包,最多允许一次策略授权的安全修复,并可要求精确 diff 回执。", @@ -164,10 +172,12 @@ const fieldCopy: Record = { eligible_endpoints: { label: "Flexible eligible executors", description: "One authorized executor per line. Use only with flexible selection and include the primary executor." }, executor_model: { label: "Model", description: "Optional model for the selected executor. Leave blank to keep the executor's own default." }, executor_reasoning_effort: { label: "Reasoning effort", description: "Optional reasoning effort for the selected executor. Leave blank to keep the executor's own default." }, + user_space: { label: "User space", description: "OpenViking user space isolating steward memory on this machine." }, + auto_recall: { label: "Auto recall history", description: "Search past steward events automatically on substantive private messages." }, + recall_timeout_seconds: { label: "Recall timeout (seconds)", description: "Wait budget (1–15s) before continuing without recalled memory." }, count_unit: { label: "Review after", description: "Work Turns require accepted settlement; polls and retries do not count.", options: { completed_todos: "Completed Todos", effective_turns: "Settled work Turns" } }, planning_horizon_goal: { label: "Show Goal in planning horizon", description: "Default on. Keep the original Goal and acceptance visible before choosing work. Turn off for rollback or comparisons; replan, stride and execution authority are unchanged." }, yardstick_enabled: { label: "Review measurement criteria", description: "Default off. Review measurement scope and feedback using available Explore evidence. Requires Explore evidence; does not enable it or authorize execution." }, - stride_strategy: { label: "Stride strategy", description: "Structured work scope, route and validation proposals are required for enabled fresh Vision reviews. Does not grant execution authority.", options: { off: "Off", evidence_conditioned_v1: "Evidence-conditioned · v1" } }, count: { label: "Number between reviews", description: "Settled work Turns: 1–6; completed Todos: 1–5. Goal overrides take precedence over device defaults." }, allowed_domains: { label: "Allowed responsibility domains", description: "Enter one bounded, public-safe domain per line." }, coordinator_agent_id: { label: "Coordinator Agent", description: "Use an already registered Agent id; leave blank to disable coordination." }, @@ -202,10 +212,12 @@ const fieldCopy: Record = { eligible_endpoints: { label: "灵活池可用执行器", description: "每行一个已授权执行器,仅用于 flexible;必须包含首选执行器。" }, executor_model: { label: "模型", description: "所选执行器使用的模型,可留空;留空表示沿用执行器自身的默认模型。" }, executor_reasoning_effort: { label: "推理档位", description: "所选执行器使用的推理档位,可留空;留空表示沿用执行器自身的默认档位。" }, + user_space: { label: "记忆用户空间", description: "本机管家在 OpenViking 中隔离使用的 user space 标识。" }, + auto_recall: { label: "跨会话自动召回", description: "收到非命令的实质私聊消息时,执行一次有界历史事件检索。" }, + recall_timeout_seconds: { label: "召回超时(秒)", description: "等待记忆读取的上限(1–15 秒);超时后跳过记忆直接恢复正常回复。" }, count_unit: { label: "复核计数依据", description: "有效工作 Turn 须完成结算;轮询和重复重试不计数。", options: { completed_todos: "已完成 Todo", effective_turns: "已结算工作 Turn" } }, planning_horizon_goal: { label: "在规划视野中显示 Goal", description: "默认开启,选择工作前可见原目标与验收要求。可为回滚或对照实验关闭;不改变复盘、步幅策略或执行权限。" }, yardstick_enabled: { label: "复核衡量标准", description: "默认关闭。使用已有 Explore 证据复核测量范围与反馈;需有可用的 Explore 证据,不会自动启用它或授予执行权限。" }, - stride_strategy: { label: "步幅策略", description: "启用后,新的 Vision 路线复盘须提交工作大小、路线及验证范围的结构化提案,不授予执行权限。", options: { off: "关闭", evidence_conditioned_v1: "依据证据调整 · v1" } }, count: { label: "两次复核间的数量", description: "已结算工作 Turn 为 1–6,已完成 Todo 为 1–5;Goal 显式设置优先于设备默认值。" }, allowed_domains: { label: "允许的职责域", description: "每行填写一个有边界、可公开的职责域。" }, coordinator_agent_id: { label: "协调 Agent", description: "填写一个已经注册的 Agent ID;留空表示关闭协调。" }, @@ -280,6 +292,11 @@ export function localizedCapabilityFieldCopy(locale: WorkspaceLocale, capability label: "Exploration mode", description: "Planning includes the evidence graph; worker and execution permissions remain separate.", options: {off: "Off", evidence: "Evidence only", planning: "Evidence and planning"}, }}; + if (capabilityId === "steward_memory") return {...fieldCopy[locale], enabled: locale === "zh-CN" ? { + label: "启用", description: "为本人私聊管家开启独立 OpenViking 长期记忆。", + } : { + label: "Enabled", description: "Enable isolated OpenViking long-term memory for owner private steward conversations.", + }}; return fieldCopy[locale]; } diff --git a/apps/presentation/dashboard/src/features/personal-workspace/channel-header.tsx b/apps/presentation/dashboard/src/features/personal-workspace/channel-header.tsx index b1ca0d2a3f..f1cfefad3b 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/channel-header.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/channel-header.tsx @@ -61,7 +61,7 @@ export function ChannelHeader({ managerRuntime?: ManagerRuntimeSessionReadback | null; mobileNavigationOpen?: boolean; onOpenGoalCapabilities?: () => void; - onOpenGoalDetails?: () => void; + onOpenGoalDetails?: (openingControl: HTMLButtonElement) => void; onOpenAllWork?: () => void; allWorkOpen?: boolean; onOpenManagerChat?: () => void; 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 2645c89c58..8f74f2e779 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx @@ -21,7 +21,7 @@ import {ManagerTeamResult} from "./manager-team-result"; import { compareProposalRecency } from "./proposal-recency"; import { conversationOrder } from "./conversation-order"; import { ConversationFind, conversationMessageKey } from "./conversation-find"; -import type { WorkspaceActionPreview, WorkspaceDrawerSelection, WorkspaceGoal, WorkspaceTimelineItem } from "./personal-workspace-model"; +import type { PersonalWorkspaceCallbacks, WorkspaceActionPreview, WorkspaceDrawerSelection, WorkspaceGoal, WorkspaceTimelineItem } from "./personal-workspace-model"; function answerLink(sessionId: string, messageId: string, turnId?: string) { const url = new URL(window.location.href); @@ -68,7 +68,7 @@ export const ChannelTimeline = memo(function ChannelTimeline({ onApplyGoalDraft, goalDraftPreparationContext, onSuggestReply, - onOpenGoalEvidence, + onOpenGoalChat, onInterruptTurn, onAdjustTurn, onCancelPreparation, @@ -96,7 +96,7 @@ export const ChannelTimeline = memo(function ChannelTimeline({ onApplyGoalDraft?: (proposal: WorkspaceActionPreview) => Promise; goalDraftPreparationContext?: string; onSuggestReply?: (text: string) => void; - onOpenGoalEvidence?: (goalId: string) => void; + onOpenGoalChat?: PersonalWorkspaceCallbacks["onOpenGoal"]; onInterruptTurn?: (turnId: string) => Promise; onAdjustTurn?: (turnId: string) => void; }) { @@ -251,16 +251,16 @@ export const ChannelTimeline = memo(function ChannelTimeline({ return ( {showManagerTeamResults && onOpenGoalEvidence && appliedTeamPlan + {showManagerTeamResults && onOpenGoalChat && appliedTeamPlan && item.proposal.goalId && item.proposal.teamPlanTodoIds?.length - ? + ? : null} ); } @@ -295,7 +295,7 @@ export const ChannelTimeline = memo(function ChannelTimeline({ : 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}
diff --git a/apps/presentation/dashboard/src/features/personal-workspace/collaboration-card.css b/apps/presentation/dashboard/src/features/personal-workspace/collaboration-card.css index c9a01e4019..b32f23f223 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/collaboration-card.css +++ b/apps/presentation/dashboard/src/features/personal-workspace/collaboration-card.css @@ -1,13 +1,203 @@ -.personal-collaboration { margin-top: 12px; border: 1px solid var(--color-border, #ebebeb); border-radius: 6px; padding: 12px 16px; overflow-wrap: anywhere; } -.personal-collaboration header { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 8px; } -.personal-collaboration header span, .personal-collaboration-status { font-size: var(--text-caption); line-height: var(--leading-caption); opacity: .75; } -.personal-collaboration-status { display: flex; flex-wrap: wrap; gap: 8px 16px; } -.personal-collaboration summary { cursor: pointer; min-height: 44px; display: list-item; align-content: center; } -.personal-collaboration h4 { margin: 12px 0 4px; font-size: var(--text-body); line-height: var(--leading-body); } -.personal-collaboration p { white-space: pre-wrap; } -.personal-collaboration ul { padding-left: 20px; } +.pw-collab-roster-summary { + margin-top: 12px; + padding: 10px 12px; + border: 1px solid var(--pw-line); + border-radius: 8px; + background: var(--pw-bg); + display: grid; + gap: 8px; + min-width: 0; +} + +.pw-collab-roster-head { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 6px 12px; + min-width: 0; +} + +.pw-collab-roster-list { + list-style: none; + margin: 0; + padding: 0; + display: grid; + gap: 6px; +} + +.pw-collab-roster-list li { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 4px 8px; + padding-top: 6px; + border-top: 1px solid var(--pw-line); + min-width: 0; + font-size: var(--text-caption); + line-height: var(--leading-caption); +} + +.pw-collab-roster-agent { + font-weight: 600; + color: var(--pw-text); + white-space: nowrap; +} + +.pw-collab-roster-state-text { + color: var(--pw-muted); + white-space: nowrap; +} + +.pw-collab-roster-list li[data-roster-state="working"] .pw-collab-roster-state-text { + color: var(--pw-green); +} + +.pw-collab-roster-list li[data-roster-state="lease_expired"] .pw-collab-roster-state-text { + color: var(--pw-amber); +} + +.pw-collab-roster-list li[data-roster-state="needs_decision"] .pw-collab-roster-state-text { + color: var(--pw-red); +} + +.pw-collab-roster-list .pw-roster-progress { + order: 2; + margin-left: auto; +} + +.pw-collab-roster-list .pw-roster-scope { + order: 3; +} + +.pw-collab-roster-now { + flex: 1 0 100%; + order: 10; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--pw-muted); +} + +.personal-collaboration { + margin-top: 10px; + border: 1px solid var(--pw-line); + border-radius: 8px; + padding: 12px 14px; + background: var(--pw-card); + overflow-wrap: anywhere; + min-width: 0; + display: grid; + gap: 8px; +} + +.personal-collaboration[data-roster-state="needs_decision"] { + border-color: color-mix(in srgb, var(--pw-red) 32%, var(--pw-line)); +} + +.personal-collaboration[data-roster-state="lease_expired"] { + border-color: color-mix(in srgb, var(--pw-amber) 36%, var(--pw-line)); +} + +.personal-collaboration[data-roster-state="working"] { + border-color: color-mix(in srgb, var(--pw-green) 28%, var(--pw-line)); +} + +.personal-collaboration header { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + align-items: flex-start; + gap: 8px 12px; + min-width: 0; +} + +.pw-collab-title-group { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + min-width: 0; + flex: 1 1 220px; +} + +.pw-collab-title-group strong { + font-size: var(--text-body); + line-height: var(--leading-body); + color: var(--pw-text); + overflow-wrap: anywhere; +} + +.pw-collab-meta-group { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; + min-width: 0; +} + +.pw-collab-owner-label { + color: var(--pw-muted); + white-space: nowrap; +} + +.personal-collaboration header span, +.personal-collaboration-status { + font-size: var(--text-caption); + line-height: var(--leading-caption); +} + +.personal-collaboration-status { + display: flex; + flex-wrap: wrap; + gap: 4px 12px; + margin: 0; + color: var(--pw-muted); +} + +.pw-collab-reason { + margin: 0; + color: var(--pw-text); + font-size: var(--text-caption); + line-height: var(--leading-caption); +} + +.personal-collaboration summary { + cursor: pointer; + min-height: 44px; + display: list-item; + align-content: center; + color: var(--pw-text); + font-size: var(--text-caption); + font-weight: 500; +} + +.personal-collaboration h4 { + margin: 12px 0 4px; + font-size: var(--text-body); + line-height: var(--leading-body); +} + +.personal-collaboration p { + white-space: pre-wrap; +} + +.personal-collaboration .pw-roster-now { + white-space: nowrap; +} + +.personal-collaboration ul { + padding-left: 20px; +} + .personal-collaboration small { display: block; font-family: var(--font-mono); font-size: var(--text-caption); line-height: var(--leading-caption); } -.personal-collaboration summary:focus-visible { outline: 2px solid var(--color-link, #0070f3); outline-offset: 2px; } + +.personal-collaboration summary:focus-visible { + outline: 2px solid var(--pw-blue); + outline-offset: 2px; +} + .personal-request-control { border-top: 1px solid var(--pw-line); margin-top: 16px; padding-top: 12px; } .personal-request-control form, .personal-request-control label { display: grid; gap: 6px; } .personal-request-control form { gap: 12px; margin-top: 12px; } @@ -21,3 +211,9 @@ .personal-request-control button:disabled { opacity: .5; cursor: default; } .personal-request-control :is(button, input, textarea):focus-visible { outline: 2px solid var(--pw-blue); outline-offset: 2px; } .personal-request-control :is(input, textarea) { padding: 8px 10px; border: 1px solid var(--pw-line-strong); border-radius: 6px; background: var(--pw-card); color: var(--pw-text); font: inherit; } + +@media (max-width: 640px) { + .pw-collab-meta-group { + width: 100%; + } +} diff --git a/apps/presentation/dashboard/src/features/personal-workspace/collaboration-card.tsx b/apps/presentation/dashboard/src/features/personal-workspace/collaboration-card.tsx index c67facf8b1..24b61acd0a 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/collaboration-card.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/collaboration-card.tsx @@ -1,30 +1,53 @@ import type { CollaborationReadback } from "../../data/chat-model"; -import {currentCollaborationConclusion} from "../../data/conversation-returns"; -import {useEffect, useState} from "react"; -import type {RequestControlView} from "../../data/request-control"; -import {RequestControl} from "./request-control"; +import { currentCollaborationConclusion } from "../../data/conversation-returns"; +import { useEffect, useState } from "react"; +import type { RequestControlView } from "../../data/request-control"; +import { RequestControl } from "./request-control"; import { useWorkspaceI18n } from "./i18n"; import { needsOriginalDeliveryProof } from "./return-delivery-status"; +import { + WORKER_ROSTER_STATES, + deriveCollaborationCardStatus, + deriveCollaborationRosterSummary, + workerRosterStateLabel, +} from "./collaboration-status"; +import { + WorkerNowLine, + WorkerProgressBadge, + WorkerScopeTag, + WorkerStateBadge, + WorkerStateGlyph, +} from "./worker-roster"; import "./collaboration-card.css"; const copy = { "zh-CN": { - title: "交办说明", context: "背景与补充", constraints: "约束", inputs: "输入材料", - acceptance: "验收要求", return: "需要回传", supplied: "已提供给接收方", pending: "等待接收方读取", - decision: "接收方判断", unknown: "尚未记录", unavailable: "暂时无法读取", - adopt: "已采纳", defer: "已暂缓", reject: "未采纳", no_change: "无需调整", - result: "回复等待送达", delivered: "回复已送达", unverified: "回复送达尚未核验", details: "查看交办内容", - owner: "接收方", reason: "原因", + title: "交办说明", + context: "背景与补充", + constraints: "约束", + inputs: "输入材料", + acceptance: "验收要求", + return: "需要回传", + decision: "接收方判断", + details: "查看交办内容", + owner: "接收方", + reason: "原因", + rosterSummary: "协作接收方概览", }, en: { - title: "Delegation brief", context: "Context & corrections", constraints: "Constraints", inputs: "Inputs", - acceptance: "Acceptance", return: "Expected return", supplied: "Supplied to receiver", pending: "Awaiting receiver read", - decision: "Receiver decision", unknown: "Not recorded", unavailable: "Readback unavailable", - adopt: "Adopted", defer: "Deferred", reject: "Rejected", no_change: "No change needed", - result: "Reply awaiting delivery", delivered: "Reply delivered", unverified: "Reply delivery unverified", details: "View delegation details", - owner: "Recipient", reason: "Reason", + title: "Delegation brief", + context: "Context & corrections", + constraints: "Constraints", + inputs: "Inputs", + acceptance: "Acceptance", + return: "Expected return", + decision: "Receiver decision", + details: "View delegation details", + owner: "Recipient", + reason: "Reason", + rosterSummary: "Recipient collaboration roster", }, -}; +} as const; export function CollaborationCard({ request }: { request?: CollaborationReadback }) { const { locale, t } = useWorkspaceI18n(); @@ -32,60 +55,150 @@ export function CollaborationCard({ request }: { request?: CollaborationReadback const [unavailable, setUnavailable] = useState(false); const [editing, setEditing] = useState(false); const [detailsOpen, setDetailsOpen] = useState(false); - useEffect(() => {setObserved(null); setUnavailable(false);}, [request?.request_id]); + + useEffect(() => { + setObserved(null); + setUnavailable(false); + }, [request?.request_id]); + useEffect(() => { if (request?.request_control && observed && request.request_control.control_version >= observed.control_version) { - setObserved(null); setUnavailable(false); + setObserved(null); + setUnavailable(false); } - }, [request?.request_control]); + }, [request?.request_control, observed]); + if (!request) return null; + const c = copy[locale]; const brief = observed?.brief ?? request.brief; const revision = observed?.revision ?? request.request_revision; - const readStatus = unavailable ? "unavailable" : observed ? observed.read_readback === "recorded" ? "supplied" - : observed.read_readback === "unavailable" ? "unavailable" : "pending" : request.read_status; - const recordedDecision = unavailable ? "unavailable" : observed ? observed.assessment?.decision - ?? (observed.assessment_readback === "unavailable" ? "unavailable" : "pending") : request.decision; - const decision = (() => { - switch (recordedDecision) { - case "adopt": return c.adopt; - case "defer": return c.defer; - case "reject": return c.reject; - case "no_change": return c.no_change; - case "unavailable": return c.unavailable; - default: return c.unknown; - } - })(); - const conclusion = currentCollaborationConclusion({...request, request_revision: revision}); + const status = deriveCollaborationCardStatus({ request, observed, unavailable, locale }); + const conclusion = currentCollaborationConclusion({ ...request, request_revision: revision }); const decisionReason = observed ? observed.assessment?.reason : request.decision_reason; - return
-
{brief.purpose}{c.owner}: {request.goal_id ? `${request.goal_id} / ` : ""}{request.agent_id}
-

- {revision !== undefined ? {locale === "zh-CN" ? "请求版本" : "Request revision"} {revision} : null} - {readStatus === "supplied" ? c.supplied : readStatus === "unavailable" ? c.unavailable : c.pending} - {c.decision}: {decision} - {conclusion ? {needsOriginalDeliveryProof(conclusion) ? t("returnDelivery.originalHandoff") - : conclusion.status === "delivered" ? c.delivered - : conclusion.status === "queued" ? c.result : c.unverified} : null} -

- {decisionReason && !unavailable ?

{c.reason}: {decisionReason}

: null} -
setDetailsOpen(event.currentTarget.open)}> - {c.details} - {request.control_route ? {setObserved(value); setUnavailable(value === null);}} onEditing={setEditing} /> : null} - {!editing && <> -

{c.context}

{brief.context}

- {brief.constraints.length ? <>

{c.constraints}

    {brief.constraints.map((item, i) =>
  • {item}
  • )}
: null} - {brief.inputs.length ? <>

{c.inputs}

    {brief.inputs.map((input, i) =>
  • {input.ref} — {input.description}{input.sha256 ? sha256:{input.sha256} : null}
  • )}
: null} -

{c.acceptance}

    {brief.acceptance.map((item, i) =>
  • {item}
  • )}
-

{c.return}

{brief.return_requirement}

- } -
-
; + const conclusionText = conclusion + ? (needsOriginalDeliveryProof(conclusion) ? t("returnDelivery.originalHandoff") : status.conclusionLabel) + : null; + + return ( +
+
+
+ + {brief.purpose} +
+
+ {c.owner}: + + +
+
+ +

+ {status.revisionLabel ? {status.revisionLabel} : null} + {status.readLabel} + {c.decision}: {status.decisionLabel} + {conclusionText ? {conclusionText} : null} +

+ {decisionReason && !unavailable && status.decisionReason !== status.now ? ( +

{c.reason}: {decisionReason}

+ ) : null} +
setDetailsOpen(event.currentTarget.open)}> + {c.details} + {request.control_route ? ( + { + setObserved(value); + setUnavailable(value === null); + }} + onEditing={setEditing} + /> + ) : null} + {!editing && ( + <> +

{c.context}

+

{brief.context}

+ {brief.constraints.length ? ( + <> +

{c.constraints}

+
    {brief.constraints.map((item, i) =>
  • {item}
  • )}
+ + ) : null} + {brief.inputs.length ? ( + <> +

{c.inputs}

+
    + {brief.inputs.map((input, i) => ( +
  • + {input.ref} — {input.description} + {input.sha256 ? sha256:{input.sha256} : null} +
  • + ))} +
+ + ) : null} +

{c.acceptance}

+
    {brief.acceptance.map((item, i) =>
  • {item}
  • )}
+

{c.return}

+

{brief.return_requirement}

+ + )} +
+
+ ); } /** Each recipient retains its own request controls, decision and return. */ -export function CollaborationCards({request, requests}: {request?: CollaborationReadback; requests?: CollaborationReadback[]}) { - return <>{(requests ?? (request ? [request] : [])).map(row => - )}; +export function CollaborationCards({ + request, + requests, +}: { + request?: CollaborationReadback; + requests?: CollaborationReadback[]; +}) { + const { locale } = useWorkspaceI18n(); + const rows = requests ?? (request ? [request] : []); + if (!rows.length) return null; + const summary = rows.length > 1 ? deriveCollaborationRosterSummary(rows, locale) : null; + + return ( + <> + {summary ? ( + + ) : null} + {rows.map((row) => )} + + ); } diff --git a/apps/presentation/dashboard/src/features/personal-workspace/collaboration-status.test.mjs b/apps/presentation/dashboard/src/features/personal-workspace/collaboration-status.test.mjs new file mode 100644 index 0000000000..5a78faf1ea --- /dev/null +++ b/apps/presentation/dashboard/src/features/personal-workspace/collaboration-status.test.mjs @@ -0,0 +1,391 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + WORKER_ROSTER_STATES, + deriveAttachedWorkerStatus, + deriveCollaborationCardStatus, + deriveCollaborationRosterSummary, + deriveGoalWorkerRoster, + formatProgressCounter, + sanitizeFocusLine, +} from "./collaboration-status.ts"; + +function makeCollaborationRequest(overrides = {}) { + return { + schema_version: "collaboration_request_readback_v0", + request_id: "req-1", + agent_id: "worker-a", + goal_id: "goal-ui", + request_revision: 1, + brief: { + purpose: "Refine collaboration header layout", + context: "Check desktop and narrow spacing", + constraints: ["Keep zero horizontal overflow at 390px"], + inputs: [], + acceptance: ["Verified visual layout across viewports"], + return_requirement: "Report updated contrast and responsive screenshots", + }, + read_status: "pending", + decision: "pending", + returns: [], + ...overrides, + }; +} + +function makeControlView(overrides = {}) { + return { + schema_version: "collaboration_request_control_v0", + request_id: "req-1", + goal_ref: { goal_id: "goal-ui", goal_instance_id: "inst-1" }, + receiver_agent_id: "worker-a", + revision: 2, + control_version: 2, + revision_digest: "deadbeef", + brief: makeCollaborationRequest().brief, + reason: "Initial delegation", + read_at: "2026-11-21T10:00:00Z", + read_readback: "recorded", + assessment: { decision: "adopt", reason: "Accepted UX slice", assessed_at: "2026-11-21T10:01:00Z" }, + assessment_readback: "recorded", + control_state: "open", + cancellation: null, + active_reservation: null, + terminal_effects: [], + execution_authority_granted: false, + ...overrides, + }; +} + +test("sanitizeFocusLine strips JSON payloads, ANSI codes, shell noise, and preserves clean surrogate-safe text", () => { + const noisy = [ + '{"schema_version":"v0","ok":true,"turn_id":"t_123"}', + "$ npm run build", + "[stderr] Traceback (most recent call last):", + "2026-11-21T10:05:00Z Now: \u001b[32mPASS\u001b[0m \u001b[1mAlign roster badges & truncate long CJK titles\u001b[0m {\"exit\":0}", + "Second line ignored", + ].join("\n"); + assert.equal( + sanitizeFocusLine(noisy, 80), + "PASS Align roster badges & truncate long CJK titles", + ); + + const emojiAndCjk = "🔥 迁移并核验多 Worker 协作状态看板与响应式卡片在 390px 窄屏下的换行表现避免截断"; + const truncated = sanitizeFocusLine(emojiAndCjk, 18); + assert.ok(Array.from(truncated).length <= 18); + assert.ok(truncated.endsWith("…")); + assert.ok(!/[\uD800-\uDFFF]/.test(truncated.replace(/[\u{10000}-\u{10FFFF}]/gu, ""))); + + assert.equal(sanitizeFocusLine('{"raw":"only"}'), ""); + assert.equal(sanitizeFocusLine("sha256:0123456789abcdef0123456789abcdef"), ""); +}); + +test("formatProgressCounter keeps unknown measurements distinct instead of fabricating zero", () => { + assert.deepEqual(formatProgressCounter(2, 5), { done: 2, total: 5, open: null, label: "[2/5]" }); + assert.deepEqual(formatProgressCounter(3, null, 2), { done: 3, total: 5, open: 2, label: "[3/5]" }); + assert.deepEqual(formatProgressCounter(3, null), { done: 3, total: null, open: null, label: "[3/—]" }); + assert.deepEqual(formatProgressCounter(null, null, 4, "en"), { done: null, total: null, open: 4, label: "[4 open]" }); + assert.deepEqual(formatProgressCounter(null, null, 4, "zh-CN"), { done: null, total: null, open: 4, label: "[4 待办]" }); + assert.deepEqual(formatProgressCounter(null, null, null), { done: null, total: null, open: null, label: "" }); +}); + +test("request receipts preserve delivery and decision without asserting worker execution", () => { + const waitingCard = deriveCollaborationCardStatus({ + request: makeCollaborationRequest(), + locale: "en", + }); + assert.equal(waitingCard.state, "waiting"); + assert.equal(waitingCard.scope, "goal-ui / worker-a"); + assert.equal(waitingCard.progress.label, "[0/3]"); + + const queuedCard = deriveCollaborationCardStatus({ + request: makeCollaborationRequest({ + read_status: "supplied", + decision: "adopt", + decision_reason: "Starting implementation", + returns: [{ phase: "conclusion", status: "queued", request_revision: 1 }], + }), + locale: "zh-CN", + }); + assert.equal(queuedCard.state, "waiting"); + assert.equal(queuedCard.conclusionLabel, "回复等待送达"); + assert.equal(queuedCard.now, "回复等待送达"); + assert.equal(queuedCard.progress.label, "[2/3]"); + + const adoptedBeforeReadSyncCard = deriveCollaborationCardStatus({ + request: makeCollaborationRequest({ + read_status: "pending", + decision: "adopt", + decision_reason: "Independent check underway", + }), + locale: "zh-CN", + }); + assert.equal(adoptedBeforeReadSyncCard.state, "waiting"); + assert.equal(adoptedBeforeReadSyncCard.now, "已采纳,等待执行记录"); + + const decisionCard = deriveCollaborationCardStatus({ + request: makeCollaborationRequest({ + read_status: "supplied", + decision: "defer", + decision_reason: "Waiting for schema owner confirmation", + }), + observed: makeControlView({ + assessment: { decision: "defer", reason: "Needs owner sign-off\n{\"internal\":1}", assessed_at: "2026-11-21T10:05:00Z" }, + control_state: "effect_pending", + }), + locale: "en", + }); + assert.equal(decisionCard.state, "needs_decision"); + assert.equal(decisionCard.now, "Needs owner sign-off"); + + const unverifiedCard = deriveCollaborationCardStatus({ + request: makeCollaborationRequest({ + read_status: "supplied", + decision: "adopt", + returns: [ + { phase: "conclusion", status: "verification_required", error: "initial_delivery_receipt_unavailable", request_revision: 1 }, + ], + }), + locale: "en", + }); + assert.equal(unverifiedCard.state, "waiting"); + assert.equal(unverifiedCard.conclusionLabel, "Awaiting original handoff proof"); + assert.match(unverifiedCard.now, /delivery unverified/); + + const failedRead = deriveCollaborationCardStatus({ + request: makeCollaborationRequest({ read_status: "supplied", decision: "adopt" }), + unavailable: true, + locale: "en", + }); + assert.equal(failedRead.state, "waiting"); + assert.equal(failedRead.readLabel, "Readback unavailable"); + assert.match(failedRead.now, /Check the original conversation/); + + const settledCard = deriveCollaborationCardStatus({ + request: makeCollaborationRequest({ + read_status: "supplied", + decision: "adopt", + decision_reason: "Completed roster polish", + returns: [{ phase: "conclusion", status: "delivered", request_revision: 1 }], + }), + locale: "zh-CN", + }); + assert.equal(settledCard.state, "waiting"); + assert.equal(settledCard.progress.label, "[3/3]"); +}); + +test("deriveCollaborationRosterSummary rolls up multi-recipient roster counts and progress", () => { + const summary = deriveCollaborationRosterSummary([ + makeCollaborationRequest({ request_id: "r1", agent_id: "builder", read_status: "supplied", decision: "adopt" }), + makeCollaborationRequest({ request_id: "r2", agent_id: "reviewer", read_status: "supplied", decision: "adopt", returns: [{ phase: "conclusion", status: "delivered", request_revision: 1 }] }), + makeCollaborationRequest({ request_id: "r3", agent_id: "qa", read_status: "supplied", decision: "reject", decision_reason: "Scope mismatch" }), + makeCollaborationRequest({ request_id: "r4", agent_id: "ops", read_status: "unavailable", decision: "unavailable" }), + ], "en"); + + assert.equal(summary.total, 4); + assert.equal(summary.concluded, 1); + assert.equal(summary.progress.label, "[1/4]"); + assert.deepEqual(summary.counts, { + working: 0, + waiting: 3, + needs_decision: 1, + lease_expired: 0, + }); +}); + +test("deriveGoalWorkerRoster classifies populated multi-worker states from observed typed facts without fabricating liveness", () => { + const nowMs = Date.parse("2026-11-21T12:00:00Z"); + const goal = { + goalId: "goal-ui", + agentId: "coordinator", + agentLabel: "Coordinator", + registeredAgentIds: ["coordinator", "builder", "verifier", "scout", "recoverer"], + agentLanes: [ + { agentId: "builder", label: "Builder Agent with an Extraordinarily Long Multi-Word Roster Name", hostSurfaces: ["codex-app"] }, + { agentId: "verifier", label: "Verifier", hostSurfaces: ["loopx"] }, + { agentId: "scout", label: "Scout", hostSurfaces: ["codex-app"] }, + { agentId: "recoverer", label: "Recoverer", state: "lease_expired" }, + { agentId: "coordinator", label: "Coordinator", hostSurfaces: ["loopx"] }, + ], + agentSentence: "Shipping workspace polish", + nextSentence: "Verify narrow screen", + activationState: "active", + state: "安静运行", + title: "Personal Workspace Roster UX", + doneTodoCount: 3, + openTodoCount: 4, + agentTodos: [ + { todoId: "t1", done: true, claimedBy: "builder", taskDomain: "dashboard", text: "Extract pure collaboration status helper" }, + { todoId: "t2", done: false, claimedBy: "builder", taskDomain: "dashboard", text: "Render Roster rings in overview" }, + { todoId: "t3", done: false, claimedBy: "verifier", taskDomain: "qa", status: "blocked", blockedReason: "Confirm narrow 390px overflow policy", text: "Review PR head" }, + { todoId: "t4", done: false, claimedBy: "scout", taskDomain: "research", text: "Inspect legacy screenshot fixtures" }, + { todoId: "t5", done: true, claimedBy: "coordinator", taskDomain: "ops", text: "Wire worktree environment" }, + { todoId: "t6", done: false, claimedBy: "coordinator", taskDomain: "ops", status: "deferred", resumeWhen: "After verifier approves", text: "Prepare handoff note" }, + ], + hostThreadActivity: { + completeness: "complete", + threads: [ + { agentId: "builder", hostSurface: "codex-app", state: "turn_open", lastEventAt: "2026-11-21T11:57:00Z", deliveryWindow: { state: "fresh" } }, + { agentId: "scout", hostSurface: "codex-app", state: "turn_open", lastEventAt: "2026-11-21T10:30:00Z", deliveryWindow: { state: "stale" } }, + ], + }, + workerObservations: { + read_status: "read", + rows: [], + }, + }; + + const digest = { + schema: "goal_workspace_digest_v0", + observedAt: "2026-11-21T12:00:00Z", + objective: "Polish Roster UX", + lifecycle: { activation: "active", finishingTurn: false }, + attentionSummary: { blocking: 1, optional: 0, coverage: "complete" }, + work: { + open: 4, + done: 3, + total: 7, + coverage: "complete", + listedOpen: 4, + classes: { running_observed: 1, needs_you: 0, waiting_dependency: 0, open: 1, blocked: 1, deferred: 1, done: 3 }, + rows: [ + { todoId: "t2", ownerId: "builder", displayClass: "running_observed", prerequisiteIds: [] }, + { todoId: "t3", ownerId: "verifier", displayClass: "blocked", prerequisiteIds: [] }, + { todoId: "t4", ownerId: "scout", displayClass: "open", prerequisiteIds: [] }, + { todoId: "t6", ownerId: "coordinator", displayClass: "deferred", prerequisiteIds: [] }, + ], + groups: [], + rail: { needsYou: [], open: ["t2", "t4"], blocked: ["t3", "t6"], done: ["t1", "t5"] }, + }, + needsYou: { availability: "ok", blocking: 1, optional: 0, coverage: "complete" }, + vitals: { attention: { kind: "ok" }, execution: { kind: "idle" }, progress: { done: 3, total: 7 }, usage: { kind: "empty" } }, + }; + + const items = [ + { + id: "run-1", + kind: "run", + run: { + runId: "run-1", + agentId: "builder", + agentLabel: "Builder", + completedSteps: 2, + totalSteps: 4, + goalId: "goal-ui", + goalTitle: "Personal Workspace Roster UX", + latestActivity: "{\"event\":\"step\"}\nRefining CollaborationCard status pills", + status: "running", + title: "Build Roster Strip", + }, + }, + ]; + + const roster = deriveGoalWorkerRoster({ + goal, + digest, + items, + locale: "en", + nowMs, + }); + + assert.equal(roster.progress.label, "[3/7]"); + assert.deepEqual( + roster.workers.map((w) => [w.agentId, w.state]), + [ + ["verifier", "needs_decision"], + ["builder", "working"], + ["recoverer", "lease_expired"], + ["coordinator", "waiting"], + ["scout", "waiting"], + ], + ); + + const builder = roster.workers.find((w) => w.agentId === "builder"); + assert.equal(builder?.scope, "dashboard"); + assert.equal(builder?.now, "Refining CollaborationCard status pills"); + assert.equal(builder?.progress.total, null); + assert.equal(builder?.progress.label, "[≥1 done]"); + assert.ok((builder?.label.length ?? 0) <= 48); + + const scout = roster.workers.find((w) => w.agentId === "scout"); + assert.equal(scout?.state, "waiting"); + assert.match(scout?.now ?? "", /Host delivery window stale/); + + const verifier = roster.workers.find((w) => w.agentId === "verifier"); + assert.equal(verifier?.now, "Confirm narrow 390px overflow policy"); + + assert.deepEqual( + new Set(roster.workers.map((w) => w.state)), + new Set(WORKER_ROSTER_STATES), + ); +}); + +test("worker task totals require both complete open rows and complete completed rows", () => { + const agentTodos = [ + { todoId: "done", done: true, claimedBy: "worker", text: "Publish first version" }, + { todoId: "open", done: false, claimedBy: "worker", text: "Verify second version" }, + ]; + const goal = { goalId: "goal-ui", registeredAgentIds: ["worker"], agentTodos }; + const digest = { work: { rows: [], coverage: "partial", done: 10, open: 1, projectedOpen: 23, total: null } }; + const items = [{ + kind: "run", + run: { + goalId: "goal-ui", agentId: "worker", status: "running", completedSteps: 2, totalSteps: 4, + }, + }]; + const partial = deriveGoalWorkerRoster({ + goal: { ...goal, doneTodoCount: 10, openTodoCount: 23 }, digest, items, locale: "en", + }); + assert.equal(partial.progress.label, "[10/33]"); + assert.equal(partial.workers[0].state, "working"); + assert.deepEqual(partial.workers[0].progress, { done: 1, open: 1, total: null, label: "[≥1 done]" }); + + const unknown = deriveGoalWorkerRoster({ goal, locale: "zh-CN" }); + assert.equal(unknown.progress.total, null); + assert.equal(unknown.workers[0].progress.label, "[≥1 已完成]"); + + const complete = deriveGoalWorkerRoster({ + goal: { ...goal, doneTodoCount: 1, openTodoCount: 1 }, locale: "en", + }); + assert.equal(complete.workers[0].progress.label, "[1/2]"); + + const duplicate = deriveGoalWorkerRoster({ + goal: { ...goal, agentTodos: [...agentTodos, agentTodos[1]], doneTodoCount: 1, openTodoCount: 2 }, + locale: "en", + }); + assert.deepEqual(duplicate.workers[0].progress, { done: 1, open: 1, total: null, label: "[≥1 done]" }); +}); + +test("deriveAttachedWorkerStatus reflects active turn, idle accepting, and disconnected states", () => { + const live = deriveAttachedWorkerStatus({ + agentId: "builder", + label: "Frontend Builder", + connected: true, + canReply: false, + activeTurn: true, + turnModel: { model: "gpt-5.4", reasoning_effort: "high" }, + locale: "en", + }); + assert.equal(live.state, "working"); + assert.equal(live.scope, "codex-app / builder"); + assert.match(live.now, /gpt-5.4 · high/); + + const broken = deriveAttachedWorkerStatus({ + agentId: "builder", + bindingRejected: true, + activeTurn: false, + locale: "zh-CN", + }); + assert.equal(broken.state, "waiting"); + assert.equal(broken.now, "无法验证原会话绑定与访问权限"); + + const quiet = deriveAttachedWorkerStatus({ + agentId: "builder", + connected: true, + canReply: true, + activeTurn: false, + includeFallbackNow: false, + locale: "zh-CN", + }); + assert.equal(quiet.state, "waiting"); + assert.equal(quiet.now, ""); +}); diff --git a/apps/presentation/dashboard/src/features/personal-workspace/collaboration-status.ts b/apps/presentation/dashboard/src/features/personal-workspace/collaboration-status.ts new file mode 100644 index 0000000000..75e7488e5a --- /dev/null +++ b/apps/presentation/dashboard/src/features/personal-workspace/collaboration-status.ts @@ -0,0 +1,748 @@ +import type { GoalWorkspaceDigest, GoalWorkDisplayClass } from "../../../../../../loopx/control_plane/presentation/goal_workspace_digest.js"; +import type { CollaborationReadback } from "../../data/chat-model"; +import type { RequestControlView } from "../../data/request-control"; +import type { GoalHostThread } from "./goal-activity"; + +/** Mirrors `quietTurnMinutes` from `goal-activity.ts` to keep zero runtime imports for Node test execution. */ +const QUIET_TURN_MINUTES = 15; +import type { + WorkspaceAgentTodo, + WorkspaceAttention, + WorkspaceGoal, + WorkspaceRun, + WorkspaceTimelineItem, +} from "./personal-workspace-model"; + +export const WORKER_ROSTER_STATES = [ + "needs_decision", + "working", + "lease_expired", + "waiting", +] as const; + +export type WorkerRosterState = (typeof WORKER_ROSTER_STATES)[number]; +export type CollaborationLocale = "zh-CN" | "en"; + +export type ProgressCounter = { + done: number | null; + total: number | null; + open: number | null; + label: string; +}; + +export type CollaborationCardRosterStatus = { + state: WorkerRosterState; + stateLabel: string; + scope: string; + now: string; + progress: ProgressCounter; + revisionLabel: string | null; + readLabel: string; + decisionLabel: string; + conclusionLabel: string | null; + decisionReason: string; + unavailable: boolean; +}; + +export type CollaborationRosterSummary = { + total: number; + concluded: number; + counts: Record; + progress: ProgressCounter; + workers: Array<{ + requestId: string; + agentId: string; + scope: string; + state: WorkerRosterState; + stateLabel: string; + now: string; + progress: ProgressCounter; + }>; +}; + +export type WorkerRosterEntry = { + agentId: string; + label: string; + state: WorkerRosterState; + stateLabel: string; + scope: string; + now: string; + progress: ProgressCounter; + hostSurfaces: string[]; + hasConversation: boolean; +}; + +export type GoalWorkerRoster = { + workers: WorkerRosterEntry[]; + counts: Record; + progress: ProgressCounter; +}; + +export type AttachedWorkerStatusInput = { + agentId: string; + label?: string | null; + connected?: boolean | null; + canReply?: boolean | null; + activeTurn: boolean; + liveActive?: boolean; + bindingRejected?: boolean; + bindingError?: string | null; + turnModel?: { model: string; reasoning_effort?: string | null } | null; + hostSurfaces?: readonly string[]; + latestFocus?: string | null; + includeFallbackNow?: boolean; + locale: CollaborationLocale; +}; + +export type AttachedWorkerStatus = { + agentId: string; + label: string; + state: WorkerRosterState; + stateLabel: string; + scope: string; + now: string; +}; + +const STATE_PRIORITY: Record = { + needs_decision: 0, + working: 1, + lease_expired: 2, + waiting: 3, +}; + +const STATE_LABELS: Record> = { + "zh-CN": { + needs_decision: "需决定", + working: "执行中", + lease_expired: "租约过期", + waiting: "等待中", + }, + en: { + needs_decision: "Needs decision", + working: "Working", + lease_expired: "Lease expired", + waiting: "Waiting", + }, +}; + +const CARD_WORDS = { + "zh-CN": { + supplied: "已提供给接收方", + pending: "等待接收方读取", + unavailable: "暂时无法读取", + adopt: "已采纳", + defer: "已暂缓", + reject: "未采纳", + no_change: "无需调整", + unknown: "尚未记录", + delivered: "回复已送达", + result: "回复等待送达", + unverified: "回复送达尚未核验", + originalHandoff: "等待原会话回传确认", + revisionPrefix: "请求版本", + awaitingReadNow: "等待接收方读取交办说明", + cancelledNow: "请求已取消,已交付任务保留", + decisionPendingNow: "待确认请求调整或暂缓决定", + readbackUnavailableNow: "读回暂不可用,请核对原会话", + unverifiedReturnNow: "回复送达尚未核验,请确认原发送记录", + adoptedNow: "已采纳,等待执行记录", + settledNow: "结论已送达", + }, + en: { + supplied: "Supplied to receiver", + pending: "Awaiting receiver read", + unavailable: "Readback unavailable", + adopt: "Adopted", + defer: "Deferred", + reject: "Rejected", + no_change: "No change needed", + unknown: "Not recorded", + delivered: "Reply delivered", + result: "Reply awaiting delivery", + unverified: "Reply delivery unverified", + originalHandoff: "Awaiting original handoff proof", + revisionPrefix: "Request revision", + awaitingReadNow: "Awaiting receiver readback", + cancelledNow: "Request cancelled; committed work retained", + decisionPendingNow: "Needs decision on deferred or pending change", + readbackUnavailableNow: "Readback unavailable. Check the original conversation.", + unverifiedReturnNow: "Reply delivery unverified. Check the original handoff.", + adoptedNow: "Adopted. Awaiting an execution record.", + settledNow: "Conclusion delivered", + }, +} as const; + +const ROSTER_WORDS = { + "zh-CN": { + standingBy: "待命,等待下一项分配", + completedStandingBy: "近期任务已完成,待命", + replanPaused: "需要补充方向或确认,已暂停复核", + outcomeUnknown: "原请求结果未知,待核实后再继续", + staleWindow: "宿主投递窗口已过期,待核实连接", + leaseExpired: "执行租约已过期", + connecting: "正在连接原会话", + acceptingReplies: "原会话空闲,可直接回复", + runningTurn: "原会话回合运行中", + connectionLost: "原会话连接或状态未确认", + bindingRejected: "无法验证原会话绑定与访问权限", + openCount: (open: number) => `${open} 待办`, + doneCount: (done: number) => `${done} 已完成`, + }, + en: { + standingBy: "Standing by for next assignment", + completedStandingBy: "Recent work completed; standing by", + replanPaused: "Needs direction; review paused", + outcomeUnknown: "Original outcome unknown; check settlement", + staleWindow: "Host delivery window stale; check connection", + leaseExpired: "Execution lease expired", + connecting: "Connecting to original conversation", + acceptingReplies: "Idle and accepting replies", + runningTurn: "Running active turn in original host", + connectionLost: "Original conversation unavailable or unconfirmed", + bindingRejected: "Binding or access verification failed", + openCount: (open: number) => `${open} open`, + doneCount: (done: number) => `${done} done`, + }, +} as const; + +// eslint-disable-next-line no-control-regex +const ANSI_PATTERN = /\u001b\[[0-9;]*[A-Za-z]/g; +// eslint-disable-next-line no-control-regex +const CONTROL_PATTERN = /[\u0000-\u0008\u000b-\u001f\u007f]/g; + +export function workerRosterStateLabel(state: WorkerRosterState, locale: CollaborationLocale): string { + return STATE_LABELS[locale][state]; +} + +export function truncateCodePoints(text: string, maxLength: number): string { + const safeLimit = Math.max(2, Math.floor(maxLength)); + const points = Array.from(text); + if (points.length <= safeLimit) return text; + const trimmed = points + .slice(0, safeLimit - 1) + .join("") + .replace(/[\s,.;:!?,。;:!?\-—/]+$/u, ""); + return `${trimmed || points.slice(0, safeLimit - 1).join("")}…`; +} + +function isTerminalOrJsonNoiseLine(line: string): boolean { + if (!line) return true; + if (/^(```|~~~|---+|===+|\*{3,})/.test(line)) return true; + if (/^[{\[]/.test(line) && (/[}\]]$/.test(line) || /"[^"]+"\s*:/.test(line))) return true; + if (/^(?:\$\s+|(?:npm|pnpm|yarn)\s+(?:run|test|exec|install)\b|(?:uv\s+run|pytest|node\s+--test)\b)/.test(line)) return true; + if (/^(Traceback\b|File\s+"|at\s+[\w.$<>]+\s*\(|EXIT_CODE[:=]|\[(?:stdout|stderr|debug|trace)\])/i.test(line)) return true; + if (/^sha256:[a-f0-9]{12,}$/i.test(line)) return true; + if (/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?Z?$/.test(line)) return true; + if (/^\/Users\/[^/\s]+\/[^\s]*$/.test(line)) return true; + return false; +} + +function cleanSingleLine(line: string): string { + return line + .replace(ANSI_PATTERN, "") + .replace(CONTROL_PATTERN, " ") + .replace(/\{[^{}]*"[^"]+"\s*:[^{}]*\}/g, " ") + .replace(/\[[^[\]]*"[^"]+"\s*:[^[\]]*\]/g, " ") + .replace(/\/(?:Users|home)\/[^/\s]+/g, "~") + .replace(/\bsha256:[a-f0-9]{12,}\b/gi, "") + .replace(/\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?Z?\b\s*[-:|]?\s*/g, "") + .replace(/^([#>*]+\s+|\d+\.\s+)/, "") + .replace(/^(?:Now|Current|Focus|当前|实时)\s*[::]\s*/i, "") + .replace(/\s+/g, " ") + .trim(); +} + +export function sanitizeFocusLine(raw: string | null | undefined, maxLength = 88): string { + if (!raw) return ""; + const stripped = raw.replace(ANSI_PATTERN, "").replace(CONTROL_PATTERN, "\n"); + const lines = stripped.split(/\r?\n+/).map((entry) => entry.trim()).filter(Boolean); + for (const candidate of lines) { + if (isTerminalOrJsonNoiseLine(candidate)) continue; + const cleaned = cleanSingleLine(candidate); + if (!cleaned || /^[{}\[\](),.;:!?'"`~\\/|+\-=*_]+$/.test(cleaned)) continue; + return truncateCodePoints(cleaned, maxLength); + } + return ""; +} + +export function formatProgressCounter( + done: number | null | undefined, + total: number | null | undefined, + open?: number | null, + locale: CollaborationLocale = "en", +): ProgressCounter { + const safeDone = typeof done === "number" && Number.isFinite(done) ? Math.max(0, Math.round(done)) : null; + const safeOpen = typeof open === "number" && Number.isFinite(open) ? Math.max(0, Math.round(open)) : null; + const safeTotal = typeof total === "number" && Number.isFinite(total) && total >= 0 + ? Math.round(total) + : safeDone !== null && safeOpen !== null + ? safeDone + safeOpen + : null; + + if (safeDone !== null && safeTotal !== null) { + return { done: safeDone, total: safeTotal, open: safeOpen, label: `[${safeDone}/${safeTotal}]` }; + } + if (safeDone !== null) { + return { done: safeDone, total: null, open: safeOpen, label: `[${safeDone}/—]` }; + } + if (safeOpen !== null) { + return { + done: null, + total: null, + open: safeOpen, + label: `[${ROSTER_WORDS[locale].openCount(safeOpen)}]`, + }; + } + return { done: null, total: null, open: null, label: "" }; +} + +function currentConclusion(request: CollaborationReadback, revision: number | undefined) { + const replies = request.returns.filter( + (reply) => reply.phase === "conclusion" + && (revision === undefined || (reply.request_revision ?? 1) === revision), + ); + return replies.find((reply) => reply.status === "delivered") + ?? replies.find((reply) => reply.status !== "superseded") + ?? replies[0]; +} + +function isConclusionProofMissing(conclusion?: { error?: string | null; status: string }) { + return conclusion?.error === "initial_delivery_receipt_unavailable" + && conclusion.status !== "delivered" + && conclusion.status !== "superseded"; +} + +function formatScope(parts: Array, fallback = ""): string { + const cleaned = parts + .map((part) => sanitizeFocusLine(part, 36)) + .filter(Boolean); + const unique = [...new Set(cleaned)]; + if (!unique.length) return fallback; + return truncateCodePoints(unique.join(" / "), 44); +} + +export function deriveCollaborationCardStatus({ + request, + observed, + unavailable = false, + locale, +}: { + request: CollaborationReadback; + observed?: RequestControlView | null; + unavailable?: boolean; + locale: CollaborationLocale; +}): CollaborationCardRosterStatus { + const c = CARD_WORDS[locale]; + const brief = observed?.brief ?? request.brief; + const revision = observed?.revision ?? request.request_revision; + const readStatus = unavailable + ? "unavailable" + : observed + ? observed.read_readback === "recorded" + ? "supplied" + : observed.read_readback === "unavailable" + ? "unavailable" + : "pending" + : request.read_status; + const recordedDecision = unavailable + ? "unavailable" + : observed + ? observed.assessment?.decision ?? (observed.assessment_readback === "unavailable" ? "unavailable" : "pending") + : request.decision; + const controlState = observed?.control_state ?? request.request_control?.control_state ?? null; + const conclusion = currentConclusion(request, revision); + const decisionReason = sanitizeFocusLine(observed ? observed.assessment?.reason : request.decision_reason, 120); + + const decisionLabel = (() => { + switch (recordedDecision) { + case "adopt": return c.adopt; + case "defer": return c.defer; + case "reject": return c.reject; + case "no_change": return c.no_change; + case "unavailable": return c.unavailable; + default: return c.unknown; + } + })(); + + const readLabel = readStatus === "supplied" + ? c.supplied + : readStatus === "unavailable" + ? c.unavailable + : c.pending; + + const proofMissing = isConclusionProofMissing(conclusion); + const conclusionLabel = conclusion + ? proofMissing + ? c.originalHandoff + : conclusion.status === "delivered" + ? c.delivered + : conclusion.status === "queued" + ? c.result + : c.unverified + : null; + + const readbackUnavailable = unavailable + || readStatus === "unavailable" + || recordedDecision === "unavailable"; + + const needsDecision = recordedDecision === "defer" + || recordedDecision === "reject" + || controlState === "effect_pending" + || controlState === "cancellation_pending"; + + // Request readback carries delivery and assessment facts. + const state: WorkerRosterState = needsDecision && controlState !== "cancelled" ? "needs_decision" : "waiting"; + + const stepDone = conclusion?.status === "delivered" + ? 3 + : ["adopt", "defer", "reject", "no_change"].includes(recordedDecision) + ? 2 + : readStatus === "supplied" + ? 1 + : 0; + + const cleanPurpose = sanitizeFocusLine(brief.purpose, 72); + const cleanReturnReq = sanitizeFocusLine(brief.return_requirement, 72); + const cleanContext = sanitizeFocusLine(brief.context, 72); + const cleanAcceptance = sanitizeFocusLine(brief.acceptance[0], 72); + + const now = (() => { + if (controlState === "cancelled") return c.cancelledNow; + if (proofMissing || conclusion?.status === "explicit_unverified" || conclusion?.status === "failed") { + return c.unverifiedReturnNow; + } + if (readbackUnavailable) return c.readbackUnavailableNow; + if (needsDecision) return decisionReason || cleanContext || c.decisionPendingNow; + if (conclusion?.status === "delivered") return decisionReason || cleanReturnReq || c.settledNow; + if (conclusion?.status === "queued") return c.result; + if (recordedDecision === "adopt") return c.adoptedNow; + if (readStatus !== "supplied") return cleanReturnReq || cleanContext || c.awaitingReadNow; + return [cleanReturnReq, cleanAcceptance, cleanContext].find((candidate) => candidate && candidate !== cleanPurpose) + || decisionReason; + })(); + + return { + state, + stateLabel: workerRosterStateLabel(state, locale), + scope: formatScope([request.goal_id, request.agent_id], request.agent_id), + now: sanitizeFocusLine(now, 88), + progress: formatProgressCounter(stepDone, 3, null, locale), + revisionLabel: revision !== undefined ? `${c.revisionPrefix} ${revision}` : null, + readLabel, + decisionLabel, + conclusionLabel, + decisionReason, + unavailable, + }; +} + +export function deriveCollaborationRosterSummary( + requests: readonly CollaborationReadback[], + locale: CollaborationLocale, +): CollaborationRosterSummary { + const counts: Record = { + needs_decision: 0, + working: 0, + lease_expired: 0, + waiting: 0, + }; + let concluded = 0; + const workers = requests.map((request) => { + const status = deriveCollaborationCardStatus({ request, locale }); + counts[status.state] += 1; + if (status.progress.done === 3) concluded += 1; + return { + requestId: request.request_id, + agentId: request.agent_id, + scope: status.scope, + state: status.state, + stateLabel: status.stateLabel, + now: status.now, + progress: status.progress, + }; + }); + return { + total: requests.length, + concluded, + counts, + progress: formatProgressCounter(concluded, requests.length, null, locale), + workers, + }; +} + +function pickPrioritizedTodo( + todos: readonly WorkspaceAgentTodo[], + rowById: ReadonlyMap, +): WorkspaceAgentTodo | undefined { + const order: Record = { + running_observed: 0, + needs_you: 1, + blocked: 2, + open: 3, + waiting_dependency: 4, + deferred: 5, + done: 6, + }; + return [...todos] + .filter((todo) => !todo.done) + .sort((left, right) => { + const leftClass = rowById.get(left.todoId)?.displayClass ?? "open"; + const rightClass = rowById.get(right.todoId)?.displayClass ?? "open"; + return order[leftClass] - order[rightClass]; + })[0]; +} + +function isFreshHostTurn(thread: GoalHostThread, nowMs: number, quietMinutes = QUIET_TURN_MINUTES): boolean { + if (thread.state !== "turn_open") return false; + if (thread.deliveryWindow?.state === "stale" || thread.deliveryWindow?.state === "missing") return false; + const stamp = thread.lastEventAt ?? thread.turnStartedAt; + const parsed = stamp ? Date.parse(stamp) : Number.NaN; + if (Number.isNaN(parsed)) return false; + return nowMs - parsed <= quietMinutes * 60_000; +} + +function isStaleHostObservation(thread: GoalHostThread, nowMs: number, quietMinutes = QUIET_TURN_MINUTES): boolean { + if (thread.state === "unknown") return true; + if (thread.deliveryWindow?.state === "stale" || thread.deliveryWindow?.state === "missing") return true; + if (thread.state === "turn_open") { + const stamp = thread.lastEventAt ?? thread.turnStartedAt; + const parsed = stamp ? Date.parse(stamp) : Number.NaN; + if (Number.isNaN(parsed) || nowMs - parsed > quietMinutes * 60_000) return true; + } + return false; +} + +export function deriveGoalWorkerRoster({ + goal, + digest = null, + items = [], + userTodos = [], + locale, + nowMs = Date.now(), +}: { + goal: WorkspaceGoal; + digest?: GoalWorkspaceDigest | null; + items?: readonly WorkspaceTimelineItem[]; + userTodos?: readonly WorkspaceAttention[]; + locale: CollaborationLocale; + nowMs?: number; +}): GoalWorkerRoster { + const w = ROSTER_WORDS[locale]; + const counts: Record = { + needs_decision: 0, + working: 0, + lease_expired: 0, + waiting: 0, + }; + const laneById = new Map((goal.agentLanes ?? []).map((lane) => [lane.agentId, lane])); + const registeredSet = new Set(goal.registeredAgentIds ?? []); + const runsByAgent = new Map(); + const runningTodoIds = new Set(); + for (const item of items) { + if (item.kind !== "run" || item.run.goalId !== goal.goalId) continue; + const list = runsByAgent.get(item.run.agentId) ?? []; + list.push(item.run); + runsByAgent.set(item.run.agentId, list); + if (item.run.status === "running" && item.run.todoId) runningTodoIds.add(item.run.todoId); + } + const digestRows: ReadonlyArray<{ todoId: string; ownerId: string | null; displayClass: GoalWorkDisplayClass }> = digest + ? digest.work.rows + : goal.agentTodos.filter((todo) => !todo.done).map((todo) => ({ + todoId: todo.todoId, + ownerId: todo.claimedBy ?? null, + displayClass: todo.status === "blocked" + ? "blocked" + : todo.status === "deferred" + ? "deferred" + : runningTodoIds.has(todo.todoId) + ? "running_observed" + : "open", + })); + const rowById = new Map(digestRows.map((row) => [row.todoId, row])); + const distinctTodos = [...new Map(goal.agentTodos.map((todo) => [todo.todoId, todo])).values()]; + const listedDone = distinctTodos.filter((todo) => todo.done).length; + // The work digest covers the open list. Completed rows are independently bounded. + const coverageComplete = (!digest || digest.work.coverage === "complete") + && distinctTodos.length === goal.agentTodos.length + && goal.openTodoCount === distinctTodos.length - listedDone + && goal.doneTodoCount === listedDone; + const goalAttention = userTodos.filter((item) => item.goalId === goal.goalId); + + const discoveredIds = [ + ...(goal.agentLanes ?? []).map((lane) => lane.agentId), + ...(goal.registeredAgentIds ?? []), + ...(goal.workerObservations?.rows ?? []).map((row) => row.agent_id), + ...(goal.hostThreadActivity?.threads ?? []).flatMap((thread) => (thread.agentId ? [thread.agentId] : [])), + ...digestRows.flatMap((row) => (row.ownerId ? [row.ownerId] : [])), + ...runsByAgent.keys(), + ]; + const workerIds = [...new Set(discoveredIds.filter(Boolean))]; + + const workers: WorkerRosterEntry[] = workerIds.map((agentId) => { + const lane = laneById.get(agentId); + const label = sanitizeFocusLine(lane?.label, 48) || agentId; + const workerRuns = runsByAgent.get(agentId) ?? []; + const activeRun = workerRuns.find((run) => run.status === "running"); + const failedRun = workerRuns.find((run) => run.status === "failed" || run.sessionStatus === "resume_failed"); + const workerTodos = distinctTodos.filter((todo) => todo.claimedBy === agentId); + const workerRows = digestRows.filter((row) => row.ownerId === agentId); + const threads = (goal.hostThreadActivity?.threads ?? []).filter((thread) => thread.agentId === agentId); + const observations = (goal.workerObservations?.rows ?? []).filter((row) => row.agent_id === agentId); + + const freshThread = threads.some((thread) => isFreshHostTurn(thread, nowMs)); + const staleThread = threads.find((thread) => isStaleHostObservation(thread, nowMs)); + const pausedObs = observations.find((row) => row.status === "replan_paused"); + const unknownObs = observations.find((row) => row.status === "replan_outcome_unknown"); + const hasExpiredLease = lane?.state === "lease_expired"; + const hasObservedActive = Boolean(activeRun) || freshThread || (!hasExpiredLease && workerRows.some((row) => row.displayClass === "running_observed")); + + const matchingAttention = goalAttention.find((item) => + item.blocking && workerTodos.some((todo) => todo.todoId === item.todoId || (todo.dependencies ?? []).includes(item.todoId)), + ); + const blockingTodo = workerTodos.find((todo) => !todo.done && (todo.status === "blocked" || rowById.get(todo.todoId)?.displayClass === "needs_you" || rowById.get(todo.todoId)?.displayClass === "blocked")); + const hasDecisionGate = Boolean(pausedObs || blockingTodo || matchingAttention); + + const state: WorkerRosterState = pausedObs + ? "needs_decision" + : hasExpiredLease && !activeRun && !freshThread + ? "lease_expired" + : hasObservedActive + ? "working" + : hasDecisionGate + ? "needs_decision" + : "waiting"; + + counts[state] += 1; + + const hostSurfaces = [...new Set([...(lane?.hostSurfaces ?? []), ...threads.map((thread) => thread.hostSurface)].filter(Boolean))]; + const domains = [...new Set(workerTodos.map((todo) => todo.taskDomain).filter((value): value is string => Boolean(value && value.trim())))]; + const scope = formatScope( + domains.length + ? domains.slice(0, 2) + : hostSurfaces.length + ? [hostSurfaces[0], label !== agentId ? agentId : null] + : [label !== agentId ? agentId : goal.repository?.branch ?? goal.goalId], + agentId, + ); + + const openTodos = workerTodos.filter((todo) => !todo.done); + const doneTodos = workerTodos.filter((todo) => todo.done); + const doneCount = doneTodos.length; + const openCount = openTodos.length; + // Timeline totals are display estimates. Use the listed tasks as a lower bound. + const progress: ProgressCounter = workerTodos.length > 0 && coverageComplete + ? formatProgressCounter(doneCount, workerTodos.length, openCount, locale) + : { + done: doneCount || null, + total: null, + open: openCount || null, + label: doneCount ? `[≥${w.doneCount(doneCount)}]` : openCount ? `[≥${w.openCount(openCount)}]` : "", + }; + + const prioritizedTodo = pickPrioritizedTodo(workerTodos, rowById); + const rawNow = (() => { + if (state === "working") { + return sanitizeFocusLine(activeRun?.latestActivity, 84) + || sanitizeFocusLine(activeRun?.title, 84) + || sanitizeFocusLine(prioritizedTodo?.text, 84) + || w.runningTurn; + } + if (state === "needs_decision") { + return sanitizeFocusLine(blockingTodo?.blockedReason, 84) + || sanitizeFocusLine(matchingAttention?.text, 84) + || sanitizeFocusLine(blockingTodo?.text, 84) + || (pausedObs ? w.replanPaused : w.standingBy); + } + if (state === "lease_expired") return w.leaseExpired; + if (unknownObs) return w.outcomeUnknown; + if (staleThread?.deliveryWindow?.state === "stale") return w.staleWindow; + if (staleThread || failedRun?.sessionStatus === "resume_failed") return w.connectionLost; + return sanitizeFocusLine(prioritizedTodo?.text, 84) + || sanitizeFocusLine(prioritizedTodo?.resumeWhen, 84) + || sanitizeFocusLine(workerRuns[0]?.latestActivity, 84) + || (doneTodos.length > 0 ? w.completedStandingBy : w.standingBy); + })(); + + return { + agentId, + label, + state, + stateLabel: workerRosterStateLabel(state, locale), + scope, + now: sanitizeFocusLine(rawNow, 84), + progress, + hostSurfaces, + hasConversation: registeredSet.has(agentId), + }; + }); + + workers.sort((left, right) => { + const priorityDiff = STATE_PRIORITY[left.state] - STATE_PRIORITY[right.state]; + return priorityDiff !== 0 ? priorityDiff : left.label.localeCompare(right.label); + }); + + const overallDone = digest?.work.done ?? goal.doneTodoCount ?? null; + const overallTotal = digest?.work.total ?? null; + const overallOpen = overallTotal !== null + ? digest?.work.open + : digest?.work.projectedOpen ?? goal.openTodoCount ?? null; + + return { + workers, + counts, + progress: formatProgressCounter(overallDone, overallTotal, overallOpen, locale), + }; +} + +export function deriveAttachedWorkerStatus({ + agentId, + label, + connected, + canReply, + activeTurn, + liveActive = false, + bindingRejected = false, + bindingError, + turnModel, + hostSurfaces = [], + latestFocus, + includeFallbackNow = true, + locale, +}: AttachedWorkerStatusInput): AttachedWorkerStatus { + const w = ROSTER_WORDS[locale]; + const connectionUnavailable = bindingRejected || Boolean(bindingError) || connected === false; + const state: WorkerRosterState = !connectionUnavailable && (liveActive || activeTurn) ? "working" : "waiting"; + + const scope = formatScope( + [hostSurfaces[0] ?? "codex-app", label && label !== agentId ? agentId : null], + agentId, + ); + const modelText = turnModel + ? [turnModel.model, turnModel.reasoning_effort].filter(Boolean).join(" · ") + : ""; + const sanitizedFocus = sanitizeFocusLine(latestFocus, 84); + const now = sanitizedFocus || ( + !includeFallbackNow + ? "" + : bindingRejected + ? w.bindingRejected + : bindingError + ? sanitizeFocusLine(bindingError, 84) || w.connectionLost + : connectionUnavailable || (canReply === false && state === "waiting") + ? w.connectionLost + : state === "working" + ? (modelText ? `${w.runningTurn} · ${modelText}` : w.runningTurn) + : canReply + ? w.acceptingReplies + : w.connecting + ); + + return { + agentId, + label: sanitizeFocusLine(label, 48) || agentId, + state, + stateLabel: workerRosterStateLabel(state, locale), + scope, + now, + }; +} diff --git a/apps/presentation/dashboard/src/features/personal-workspace/configuration-backup-comparison.css b/apps/presentation/dashboard/src/features/personal-workspace/configuration-backup-comparison.css new file mode 100644 index 0000000000..73bfeca3bb --- /dev/null +++ b/apps/presentation/dashboard/src/features/personal-workspace/configuration-backup-comparison.css @@ -0,0 +1,13 @@ +.personal-backup-comparison { display: grid; gap: 0.75rem; min-width: 0; margin-block: 1.25rem; } +.personal-backup-comparison h3, .personal-backup-comparison h4, .personal-backup-comparison p { margin: 0; overflow-wrap: anywhere; } +.personal-backup-files { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1rem; } +.personal-backup-files > * { min-width: 0; } +.personal-backup-files label { display: grid; gap: 0.5rem; } +.personal-backup-files input { max-width: 100%; } +.personal-backup-comparison details { margin-block: 0.5rem; } +.personal-backup-comparison summary { overflow-wrap: anywhere; cursor: pointer; } +.personal-backup-comparison code { overflow-wrap: anywhere; white-space: pre-wrap; } +.personal-backup-comparison pre { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 20rem; overflow: auto; } +@media (max-width: 640px) { .personal-backup-files { grid-template-columns: minmax(0, 1fr); } } + +.personal-configuration-preview-digest { display: block; max-width: 100%; overflow-wrap: anywhere; white-space: normal; } diff --git a/apps/presentation/dashboard/src/features/personal-workspace/configuration-backup-comparison.tsx b/apps/presentation/dashboard/src/features/personal-workspace/configuration-backup-comparison.tsx new file mode 100644 index 0000000000..09b404bb5e --- /dev/null +++ b/apps/presentation/dashboard/src/features/personal-workspace/configuration-backup-comparison.tsx @@ -0,0 +1,74 @@ +import {useEffect, useRef, useState} from "react"; +import {compareConfigurationSnapshots, type ConfigurationBackupComparison} from "../../data/chat"; +import {useWorkspaceI18n} from "./i18n"; +import "./configuration-backup-comparison.css"; + +type Snapshot = {name: string; data: Record}; +export function ConfigurationBackupComparisonSettings({disabled, onChange, onReview, onBusyChange}: { + disabled: boolean; onBusyChange: (busy: boolean) => void; onChange: () => void; onReview: (backup: Record) => void; +}) { + const zh = useWorkspaceI18n().locale === "zh-CN"; + const [snapshots, setSnapshots] = useState<[Snapshot | null, Snapshot | null]>([null, null]); + const [comparison, setComparison] = useState(null); + const [error, setError] = useState(""); + const [busy, setBusy] = useState(false); + const alive = useRef(true); + useEffect(() => {alive.current = true; return () => {alive.current = false;};}, []); + const labels = zh ? ["比较前文件", "比较后文件"] : ["Before snapshot", "After snapshot"]; + async function select(file: File | undefined, index: number) { + setComparison(null); setError(""); onChange(); + setSnapshots(previous => index === 0 ? [null, previous[1]] : [previous[0], null]); + if (!file) return; + setBusy(true); onBusyChange(true); + try { + if (file.size > 64 * 1024 * 1024) throw new Error(zh ? "文件超过 64 MiB 比较限制。" : "File exceeds the 64 MiB comparison limit."); + const data: unknown = JSON.parse(await file.text()); + if (!data || Array.isArray(data) || typeof data !== "object") throw new Error(zh ? "请选择配置快照 JSON 文件。" : "Select a configuration snapshot JSON object."); + if (!alive.current) return; + const selected = {name: file.name, data: data as Record}; + setSnapshots(previous => index === 0 ? [selected, previous[1]] : [previous[0], selected]); + } catch (failure) {if (alive.current) setError(String(failure));} finally {if (alive.current) {setBusy(false); onBusyChange(false);}} + } + async function compare() { + if (!snapshots[0] || !snapshots[1]) return; + setBusy(true); onBusyChange(true); setComparison(null); setError(""); onChange(); + try {const compared = await compareConfigurationSnapshots(snapshots[0].data, snapshots[1].data); if (alive.current) setComparison(compared);} + catch (failure) {if (alive.current) setError(String(failure));} finally {if (alive.current) {setBusy(false); onBusyChange(false);}} + } + return
+

{zh ? "比较配置快照" : "Compare configuration snapshots"}

+

{zh ? "先比较两个保存的文件,再选择要核对恢复的快照。比较不会修改当前设置;Goal 仅在某一文件出现可能是备份范围不同,不代表已新建或删除。" : "Compare two saved files before choosing a snapshot to review for recovery. Comparison changes no live settings. Goals present in only one file may reflect different backup cohorts, not creation or deletion."}

+

{zh ? "两文件请求合计最多 64 MiB;完整差异最多 56 MiB,超限时不返回部分结果。" : "Combined request limit: 64 MiB. Complete comparison limit: 56 MiB; oversized comparisons return no partial result."}

+
{labels.map((label, index) => )}
+ + {error ?

{error}

: null} + {comparison ? <> +

{zh ? `已比较:${comparison.change_count} 项差异。当前设置未改变。` : `Compared: ${comparison.change_count} differences. Live settings unchanged.`}

+
{snapshots.map((snapshot, index) => { + const before = index === 0; + const ids = before ? comparison.before_goal_ids : comparison.after_goal_ids; + const only = before ? comparison.only_in_before : comparison.only_in_after; + return
+

{labels[index]}: {snapshot?.name}

+

{ids.length} Goal · {(before ? comparison.before_machine_configuration_present : comparison.after_machine_configuration_present) ? (zh ? "包含设备配置" : "Includes device configuration") : (zh ? "设备配置缺省" : "Device configuration absent")}

+
{zh ? "散列与备份范围" : "Hash and cohort"} +

SHA-256: {before ? comparison.before_sha256 : comparison.after_sha256}

+

Goal: {ids.join(", ") || (zh ? "无" : "None")}

+

{zh ? "仅在此文件: " : "Only in this file: "}{only.join(", ") || (zh ? "无" : "None")}

+
+ +
; + })}
+ {comparison.changes.length === 0 ?

{zh ? "保存的配置内容一致。" : "Stored configuration contents are identical."}

:
{comparison.changes.map(change =>
+ {change.path} +
{[true, false].map(before =>

{labels[before ? 0 : 1]}

+
{(before ? change.before_present : change.after_present) ? JSON.stringify(before ? change.before : change.after, null, 2) : (zh ? "不存在" : "Absent")}
+
)}
+
)}
} + : null} +
; +} diff --git a/apps/presentation/dashboard/src/features/personal-workspace/configuration-backup-settings.tsx b/apps/presentation/dashboard/src/features/personal-workspace/configuration-backup-settings.tsx index d5847f62ff..4dd4d4fb83 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/configuration-backup-settings.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/configuration-backup-settings.tsx @@ -1,6 +1,7 @@ -import {useEffect, useState} from "react"; +import {useEffect, useRef, useState} from "react"; import {exportConfigurationBackup, restoreConfigurationCheckpoint, type ConfigurationBackupResult} from "../../data/chat"; import {useWorkspaceI18n} from "./i18n"; +import {ConfigurationBackupComparisonSettings} from "./configuration-backup-comparison"; import {StateRecoverySettings} from "./state-recovery-settings"; export function ConfigurationBackupSettings({goalId}: {goalId: string | null}) { @@ -11,43 +12,56 @@ export function ConfigurationBackupSettings({goalId}: {goalId: string | null}) { const [error, setError] = useState(""); const [busy, setBusy] = useState(false); const [kind, setKind] = useState<"configuration" | "state">("configuration"); - useEffect(() => {setBackup(null); setResult(null); setError(""); setKind("configuration");}, [goalId]); - async function perform(action: () => Promise) { + const generation = useRef(0); + useEffect(() => {generation.current++; setBusy(false); setBackup(null); setResult(null); setError(""); setKind("configuration"); return () => {generation.current++;};}, [goalId]); + async function perform(action: (current: () => boolean) => Promise) { + const request = generation.current; + const current = () => request === generation.current; setBusy(true); setError(""); - try {await action();} catch (failure) {setError(String(failure));} - finally {setBusy(false);} + try {await action(current);} catch (failure) {if (current()) setError(String(failure));} + finally {if (current()) setBusy(false);} } return
{zh ? "配置备份与恢复" : "Configuration backup and recovery"} {goalId === null ?
{zh ? "备份类型" : "Backup type"} - - + +
: null} {kind === "configuration" || goalId !== null ? <>

{zh ? "备份包含私有路径、Goal 设置及设备默认值,需自行保管和审查。凭据文件不包含在此组件中。恢复只建立隔离检查点;启用仍在原配置页面办理。" : "Keep and review this private backup: it includes Goal settings, paths and device defaults. Credential files are outside this component. Recovery creates an isolated checkpoint; activate settings through their existing editors."}

- + {setBackup(null); setResult(null); setError("");}} onReview={candidate => { + setBackup(null); setResult(null); + void perform(async current => { + const preview = await restoreConfigurationCheckpoint(candidate, false); + if (current()) {setBackup(candidate); setResult(preview);} + }); + }} /> - {backup && result?.status === "preview" ? : null} {result ?

{result.status === "restored" ? (zh ? "检查点已恢复并核对;当前设置及存储 provider 未改变。" : "Checkpoint restored and verified. Live settings and storage provider are unchanged.") : (zh ? "配置备份已核对" : "Configuration backup verified")}: {result.goal_count} Goal · {result.machine_configuration_present ? (zh ? "包含设备配置" : "includes device configuration") : (zh ? "设备配置缺省" : "device configuration absent")} + {result.status === "preview" ? SHA-256: {result.sha256} : null} {result.checkpoint_ref ? {result.checkpoint_ref} : null}

: null} {error ?

{error}

: null} : } 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 1ee6ce52e3..b044cea6ac 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx @@ -52,7 +52,50 @@ import { parseTodoResumeCondition, todoResumeTransition } from "./todo-resume-co import { MarkdownText } from "./markdown"; import { formatMonitorDate } from "./monitor-readback"; import { parseTodoCompletionProof } from "./todo-completion-feedback"; +import { SourceRunHistory } from "./source-run-history"; import { useDrawerOverlay } from "./workspace-shell"; +import { + deriveGoalWorkerRoster, + formatProgressCounter, + sanitizeFocusLine, + type CollaborationLocale, + type WorkerRosterState, +} from "./collaboration-status"; +import { + GoalWorkerRosterStrip, + WorkerProgressBadge, + WorkerStateBadge, +} from "./worker-roster"; + +function GoalDrawerWorkerRoster({ + goal, + runs, + attentionHistory, + locale, +}: { + goal: WorkspaceGoal; + runs: WorkspaceRun[]; + attentionHistory: WorkspaceAttention[]; + locale: CollaborationLocale; +}) { + const roster = deriveGoalWorkerRoster({ + goal, + items: runs.map((run) => ({ id: run.runId, kind: "run" as const, run })), + userTodos: attentionHistory, + locale, + }); + return roster.workers.length > 0 ? ( + + ) : null; +} + +function runRosterState(run: WorkspaceRun): WorkerRosterState { + if (run.status === "running") return "working"; + if (run.status === "failed" || run.status === "interrupted" || run.sessionStatus === "resume_failed") { + return "lease_expired"; + } + return "waiting"; +} function subagentModelRequest(include: boolean, model: string, effort: string) { if (!include) return {}; @@ -186,6 +229,13 @@ 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 recoveringTodoCreation = proposalTarget?.reviewPlan?.reason === "todo_creation_retry"; + const preserveOriginalProposal = proposalTarget?.reviewPlan?.prohibitRegeneration === true; + const retainedTodoGate = preserveOriginalProposal && proposalTarget?.actionKind === "todo.create" + && proposalTarget.gate?.kind === "canonical_authority_required" ? proposalTarget.gate : null; + const shownProposalFields = retainedTodoGate ? [] : recoveringTodoCreation + ? visibleProposalFields.filter(field => field.key !== "text" && field.key !== "goal_id") + : visibleProposalFields; const taskExecution = proposalTarget?.status === "applied" && !proposalReadbackUnavailable && !readOnly ? proposalTarget.reviewPlan?.taskExecution : undefined; const proposalRequests = proposalTarget?.todoId @@ -269,14 +319,15 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention } }, [authoritativeSubagentConfiguration, verifiedSubagentConfiguration]); + const openingControl = selection.kind === "goal" ? selection.openingControl : undefined; useEffect(() => { - const activeElement = document.activeElement; - if (activeElement instanceof HTMLElement && !drawerRef.current?.contains(activeElement)) { - returnFocusRef.current = activeElement; + const opener = openingControl ?? document.activeElement; + if (opener instanceof HTMLElement && !drawerRef.current?.contains(opener)) { + returnFocusRef.current = opener; } const frame = window.requestAnimationFrame(() => titleRef.current?.focus()); return () => window.cancelAnimationFrame(frame); - }, [selectionIdentity]); + }, [openingControl, selectionIdentity]); useEffect(() => { if (!taskInspectorModal || drawerRef.current?.contains(document.activeElement)) return; @@ -347,10 +398,15 @@ 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 completedTodoCreation = proposalTarget?.actionKind === "todo.create" + && proposalTarget.reviewPlan?.interaction === "completed"; + const sourceRunGoal = selection.kind === "run" + ? goals.find(goal => goal.goalId === selection.item.goalId && goal.sourceAccess) + : undefined; 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 === "run" ? t(sourceRunGoal ? "drawer.sourceRunHistory" : "drawer.runDetails") : selection.kind === "output" ? t("drawer.titleOutput") : selection.kind === "proposal" && selection.item.actionKind === "team.plan" && selection.item.status === "applied" ? t("proposal.teamPlan.resultTitle") : selection.kind === "proposal" && selection.item.actionKind === "operation.execute" ? t("drawer.operationReadOnly") @@ -666,7 +722,7 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention role="dialog" >
-

{title}

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

{contextLabel}

: null}
+

{title}

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

{contextLabel}

: null}
{selection.kind === "todo" && onToggleInspectorSize ? : null} - - ) : ( - <> -

{t("drawer.noRun")}

-

{t("drawer.noRunDescription")}

- - )} - + {selection.item.sourceAccess + ? + :
+ {t("drawer.runDetails")} + {selectedGoalRun?.sessionId ? ( + <> +

{localizedSessionStatus(selectedGoalRun.sessionStatus ?? selectedGoalRun.status, t)}

+

{selectedGoalRun.title}

+ {callbacks.onOpenRunSession ? : null} + + ) : ( + <> +

{t("drawer.noRun")}

+

{t("drawer.noRunDescription")}

+ + )} +
} {selection.item.zcodeGoalEligibleAgentIds?.length ? : null} {!readOnly ?
@@ -1071,7 +1130,8 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention ) : null} - {selection.kind === "run" ? ( + {sourceRunGoal ? : null} + {selection.kind === "run" && !sourceRunGoal ? ( <>
@@ -1082,7 +1142,11 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention
{selection.item.agentLabel} · {localizedSessionStatus(selection.item.sessionStatus ?? selection.item.status, t)}

{selection.item.title}

-

{selection.item.latestActivity}

+
+ + +
+

{sanitizeFocusLine(selection.item.latestActivity, 140) || selection.item.latestActivity}

Goal
{selection.item.goalTitle}
{t("drawer.progress")}
{selection.item.completedSteps}/{selection.item.totalSteps}
@@ -1123,7 +1187,7 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention
{selection.item.agentLabel} · {localizedSessionStatus(selection.item.status, t)}

{selection.item.title}

-

{selection.item.latestActivity}

+

{sanitizeFocusLine(selection.item.latestActivity, 140) || selection.item.latestActivity}

Goal
{selection.item.goalTitle}
{t("drawer.progress")}
{selection.item.completedSteps}/{selection.item.totalSteps}
@@ -1224,15 +1288,19 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention ?

{t("proposal.readbackUnavailable")}

{onRetryProposalReadback ? : null}
: null} {selection.item.actionKind === "team.plan" && selection.item.status === "applied" ? :
- {!taskExecution ? {selection.item.reviewPlan?.operationFrame?.kind === "pending" + {!taskExecution ? {(selection.item.reviewPlan?.operationFrame?.kind === "pending" || recoveringTodoCreation) ? t(`proposal.kind.${selection.item.actionKind}`) : `${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.creationExecution && !selection.item.reviewPlan.retryOriginal && !taskExecution && selection.item.actionKind !== "team.plan" && !(decisionFrame && ["ready", "applied"].includes(selection.item.status)) ?

{operationUnknown + {retainedTodoGate ?

+ {retainedTodoGate.summary}{retainedTodoGate.nextAction ? {retainedTodoGate.nextAction} : null} +
: selection.item.reviewPlan?.retryOriginal && selection.item.errorMessage + ?

{selection.item.errorMessage}

+ : selection.item.impact ?

{selection.item.impact}

: null} + {selection.item.reviewPlan && !retainedTodoGate && !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}`) @@ -1245,7 +1313,7 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention : t(`actionReview.${selection.item.reviewPlan.reason}`)}

: 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} + {!taskExecution && shownProposalFields.length ?
{shownProposalFields.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")} @@ -1266,10 +1334,23 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention ?

{t("proposal.primary.operationCancelled")}

: null} {selection.item.status === "deferred" ?

{t("drawer.proposalDeferred")}

: null} {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} + : selection.item.status === "gated" && !retainedTodoGate ?
{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 || 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.actionKind !== "operation.execute" && selection.item.status === "error" + && ((selection.item.reviewPlan?.retryOriginal && selection.item.reviewPlan.canApply) + || (!preserveOriginalProposal && !["team.plan", "goal.create"].includes(selection.item.actionKind))) + ? + : !readOnly && selection.item.actionKind !== "operation.execute" && selection.item.status !== "gated" + && !((preserveOriginalProposal || ["team.plan", "goal.create"].includes(selection.item.actionKind)) + && ["error", "stale"].includes(selection.item.status)) + && !((selection.item.actionKind === "team.plan" || decisionFrame || taskExecution || completedTodoCreation) + && selection.item.status === "applied") + ? + : null} + {!readOnly && selection.item.actionKind !== "operation.execute" && !preserveOriginalProposal + && !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 +1395,7 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention ) : null} - {selection.kind === "run" || selection.kind === "proposal" || selection.kind === "schedule" ? ( + {((selection.kind === "run" && !sourceRunGoal) || selection.kind === "proposal" || selection.kind === "schedule") ? ( <>
+ {!sourceEditable ?

+ {zh ? "请在原协作入口编辑或取消排队。" : "Edit or cancel this queued message in its original conversation."} +

: null} + {!sourceEditable && (editing || draft !== null) ? : null} +
- {menu ?
+ aria-label={!sourceEditable + ? (zh ? `编辑或取消不可用:待处理消息 ${index + 1}` : `Editing or cancelling unavailable for queued message ${index + 1}`) + : (zh ? `更多操作:待处理消息 ${index + 1}` : `More actions for queued message ${index + 1}`)} + aria-describedby={sourceEditable ? undefined : sourceDescriptionId} + aria-expanded={menu && editable} onClick={() => setMenu(!menu)}> + {menu && editable ?
: null}
{editing ?
{draft === null ?

{failed ? (zh ? "完整消息读取失败" : "Full message unavailable") : (zh ? "正在读取…" : "Reading…")}

- : +
`); + const actual = await page.evaluate(() => { + const style = selector => getComputedStyle(document.querySelector(selector)); + const probe = document.createElement('div'); document.body.append(probe); + const token = (property, name) => { + probe.style.setProperty(property, `var(${name})`); + return getComputedStyle(probe).getPropertyValue(property); + }; + const values = { + fill: style('.composer-box').backgroundColor, queue: style('.queue-item').backgroundColor, + context: style('.composer-context').backgroundColor, shadow: style('.composer-box').boxShadow, + blur: style('.composer-box').backdropFilter, queueBottom: style('.queue').paddingBottom, + canvas: token('background-color', '--bg'), surface: token('background-color', '--surface'), + row: token('background-color', '--surface-2'), glass: token('background-color', '--glass-bg'), + halo: token('box-shadow', '--glass-halo'), glassShadow: token('box-shadow', '--glass-shadow'), + glassFilter: token('backdrop-filter', '--glass-filter'), + }; + probe.remove(); return values; + }); + if (id === 'codex' && theme === 'light') { + assert.equal(actual.fill, actual.canvas); + assert.equal(actual.queue, 'rgba(0, 0, 0, 0)'); + assert.equal(actual.context, 'rgba(0, 0, 0, 0)'); + assert.equal(actual.shadow, 'none'); + assert.equal(actual.blur, 'none'); + assert.equal(actual.queueBottom, '8px'); + } else { + assert.equal(actual.fill, width >= 900 ? actual.surface : actual.glass); + assert.equal(actual.queue, actual.row); + assert.equal(actual.context, actual.row); + assert.equal(actual.shadow, width >= 900 ? actual.halo : actual.glassShadow); + assert.equal(actual.blur, width >= 900 ? 'none' : actual.glassFilter); + assert.equal(actual.queueBottom, '0px'); + } + }); + } + } finally { await browser.close(); } +}); diff --git a/apps/workbench/packages/e2e/test/coordination.spec.mjs b/apps/workbench/packages/e2e/test/coordination.spec.mjs index 468a114ea7..4e09bba024 100644 --- a/apps/workbench/packages/e2e/test/coordination.spec.mjs +++ b/apps/workbench/packages/e2e/test/coordination.spec.mjs @@ -47,7 +47,7 @@ for (const phone of [false, true]) for (const colorScheme of ['light', 'dark']) assert.equal(await page.locator('.coord-row').count(), 0); const choiceRow = list.getByRole('menuitem', { name: /claude/i }).first(); assert.ok(await choiceRow.locator('svg').count()); - const shots = '/tmp/loochat-coordination-shots'; mkdirSync(shots, { recursive: true }); + const shots = process.env.LOOCHAT_E2E_SHOTS_DIR ?? '/tmp/loochat-coordination-shots'; mkdirSync(shots, { recursive: true }); await page.screenshot({ path: `${shots}/${phone ? 'phone' : 'desktop'}-${colorScheme}-menu.png` }); await choiceRow.click(); assert.equal(await box.inputValue(), 'Keep this draft while choosing a collaborator'); @@ -140,9 +140,11 @@ for (const phone of [false, true]) for (const colorScheme of ['light', 'dark']) await page.route(`**/threads/${child}/events?tail=1`, route => route.fulfill({ status: 503, body: '{"error":"offline"}' }), { times: 1 }); await card.click(); await panel.getByText('文档审查完成。', { exact: false }).waitFor(); - const own = panel.locator('.agent-panel-head .member-model.set', { hasText: picked }); + assert.equal(await panel.locator('.agent-panel-head .member-model').count(), 0); + if (phone) await panel.locator('.composer textarea').click(); + const own = panel.locator('.agent-panel-composer .model-control-trigger'); await own.waitFor(); - // Opened from the top of the panel, the member's own setting is all on screen. + // Opened from the bottom of the panel, the member's own setting is all on screen. await own.click(); const ownPanel = page.getByRole('menu', { name: '模型与思考强度', exact: true }); await ownPanel.waitFor(); @@ -153,6 +155,13 @@ for (const phone of [false, true]) for (const colorScheme of ['light', 'dark']) await page.screenshot({ path: `${shots}/${phone ? 'phone' : 'desktop'}-${colorScheme}-own-model.png` }); await page.keyboard.press('Escape'); await ownPanel.waitFor({ state: 'detached' }); + const originalLead = await (await api(daemon, `/api/threads/${root.id}`)).json(); + await panel.locator('.composer-permission').click(); + const permissionSaved = page.waitForResponse(res => res.url().endsWith(`/threads/${child}`) && res.request().method() === 'PATCH'); + await page.getByRole('menuitemradio', { name: /^完全访问/ }).click(); + assert.equal((await permissionSaved).status(), 200); + assert.equal((await (await api(daemon, `/api/threads/${child}`)).json()).permissionMode, 'full_access'); + assert.equal((await (await api(daemon, `/api/threads/${root.id}`)).json()).permissionMode, originalLead.permissionMode, 'member settings never change the lead'); // A member has a box of its own, saying whom it writes to. await panel.getByRole('textbox', { name: '消息', exact: true }).waitFor(); assert.equal(await panel.getByRole('textbox', { name: '消息', exact: true }).getAttribute('placeholder'), '发给 文档审查…'); @@ -162,6 +171,7 @@ for (const phone of [false, true]) for (const colorScheme of ['light', 'dark']) assert.ok(rect && rect.x === 0 && Math.abs(rect.width - 390) < 2); } await page.screenshot({ path: `${shots}/${phone ? 'phone' : 'desktop'}-${colorScheme}-detail.png` }); + await panel.screenshot({ path: `${shots}/${phone ? 'phone' : 'desktop'}-${colorScheme}-member-panel.png` }); await panel.getByRole('button', { name: '返回智能体列表' }).click(); await card.waitFor(); await panel.locator('.coord-unread').waitFor({ state: 'detached' }); @@ -255,6 +265,19 @@ for (const phone of [false, true]) for (const colorScheme of ['light', 'dark']) await page.getByRole('button', { name: '查看智能体', exact: true }).click(); await card.click(); assert.equal(await direct.inputValue(), ''); + await panel.getByRole('button', { name: '关闭智能体面板' }).click(); + await page.getByLabel('这个对话的更多操作').click(); + await page.getByRole('menuitem', { name: '分叉与交接', exact: true }).click(); + await page.getByRole('menuitem', { name: '交接', exact: true }).click(); + const handover = page.getByRole('dialog', { name: '交接', exact: true }); + const takeTeam = handover.getByRole('checkbox', { name: /协作成员随交接带走/ }); + assert.equal(await takeTeam.isChecked(), true); + await takeTeam.uncheck(); + const handoverRequest = page.waitForRequest(req => req.url().endsWith(`/threads/${root.id}/handover-thread`) && req.method() === 'POST'); + await handover.getByRole('button', { name: '新建接手对话', exact: true }).click(); + assert.equal((await handoverRequest).postDataJSON().takeTeam, false); + await handover.waitFor({ state: 'detached' }); + assert.equal((await (await api(daemon, `/api/threads/${root.id}/coordination`)).json()).rootId, root.id); assert.deepEqual(errors, []); } finally { await context.close(); } }); diff --git a/apps/workbench/packages/e2e/test/goal-board.spec.mjs b/apps/workbench/packages/e2e/test/goal-board.spec.mjs new file mode 100644 index 0000000000..b5ff1d6630 --- /dev/null +++ b/apps/workbench/packages/e2e/test/goal-board.spec.mjs @@ -0,0 +1,248 @@ +import { test, before, after } from 'node:test'; +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import { mkdirSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { startDaemon, launchBrowser, openUi, api } from '../harness.mjs'; + +// The packaged web and daemon are real; only Core Goal records are synthetic. +let daemon, browser, core, bound, paused, plain; +let filesFail = false; +const additionalBindings = new Map(); +const reads = []; +const goals = [ + { id: 'proposal', display_name: 'Review the launch proposal and verify the complete delivery', goal_objective: 'Prepare a proposal with clear acceptance evidence.', status: 'active_state_user_gate', activation_state: 'active' }, + { id: 'paused', display_name: 'Research the next release', status: 'connected_without_run', activation_state: 'stopped' }, +]; +for (let number = 3; number <= 8; number++) goals.push({ id: `core-${number}`, display_name: `Core-only Goal ${number}: verify the research conclusions`, goal_objective: `Retain independently readable results for Core Goal ${number}.`, status: number === 8 ? 'connected_without_run' : 'active_state_agent_todo', activation_state: number === 8 ? 'stopped' : 'active' }); +const todo = { todo_id: 'draft', text: 'Review the proposal and choose the next step', status: 'open', task_class: 'user_action', claimed_by: null, priority: 'P1' }; +const counts = (items) => ({ items, total_count: items.length, open_count: items.length, done_count: 0 }); +const attention = { goal_id: 'proposal', status: 'active_state_user_gate', waiting_on: 'user', user_todos: counts([todo]), agent_todos: counts([{ ...todo, todo_id: 'agent', text: 'Run independent checks', task_class: 'advancement_task', claimed_by: 'pi' }, { ...todo, todo_id: 'peer', text: 'Review supporting evidence', task_class: 'advancement_task', claimed_by: 'reviewer' }]) }; +const attentionFor = id => id === 'proposal' ? attention : { goal_id: id, status: goals.find(goal => goal.id === id)?.status ?? 'unknown', activation_state: goals.find(goal => goal.id === id)?.activation_state, goal_channel_projection: { display_name: goals.find(goal => goal.id === id)?.display_name }, user_todos: counts([]), agent_todos: counts([{ ...todo, todo_id: `${id}-task`, text: `Review supporting evidence for ${id}`, task_class: 'advancement_task', claimed_by: 'researcher' }]), recommended_action: `Read the retained findings for ${id}` }; +const coreReport = { todo_id: 'core-8-report', title: 'Core-only retained report', producer_agent_id: 'researcher', sha256: 'fixture-report-digest', content_type: 'text/plain', size_bytes: 48 }; +const inventory = { items: [], next_cursor: null, unavailable_count: 0, unavailable_todo_ids: [] }; +before(async () => { + core = createServer((req, res) => { + const url = new URL(req.url, 'http://localhost'); reads.push(url.pathname + url.search); + res.setHeader('Content-Type', 'application/json'); + if (url.pathname === '/status.json') { + const id = url.searchParams.get('goal_id'); + res.end(JSON.stringify({ served_at: new Date().toISOString(), ...(id ? { goal_filter: id } : {}), run_history: { goals: id ? goals.filter(goal => goal.id === id) : goals }, attention_queue: { items: id ? [attentionFor(id)] : goals.map(goal => attentionFor(goal.id)) } })); + } else if (url.pathname === '/api/chat/goal-results') { + res.statusCode = filesFail ? 502 : 200; res.end(JSON.stringify(filesFail ? { error: 'Synthetic Core temporarily unavailable' } : url.searchParams.get('goal_id') === 'core-8' ? { ...inventory, items: [coreReport] } : inventory)); + } else if (url.pathname === '/api/chat/goal-results/core-8-report') { + res.end(JSON.stringify({ goal_id: 'core-8', todo_id: coreReport.todo_id, result: coreReport, text: 'Retained Core report without a Workbench conversation.' })); + } else if (url.pathname === '/api/chat/goal-acceptance') { + res.end(JSON.stringify({ ok: true, goal_id: url.searchParams.get('goal_id'), provider_revision: 'fixture-revision', goal_acceptance_contract: { lifecycle_state: 'active', objective: 'Review the retained findings', criteria: [{ id: 'check', description: 'Independent evidence remains readable' }] } })); + } else if (url.pathname === '/api/actions') { res.end(JSON.stringify({ proposals: [] })); } + else { res.statusCode = 502; res.end(JSON.stringify({ error: 'Synthetic Core temporarily unavailable' })); } + }); + await new Promise(resolve => core.listen(0, '127.0.0.1', resolve)); + daemon = await startDaemon({ LOOCHAT_LOOPX_CORE_URL: `http://127.0.0.1:${core.address().port}`, LOOCHAT_AGENTS_JSON: JSON.stringify({ agents: [{ id: 'pi', adapter: 'pi', command: ['fake-pi'] }] }) }); + console.log(JSON.stringify({ fixture: 'goal-board', daemonPid: daemon.pid, daemonBase: daemon.base, corePort: core.address().port, web: 'packages/web/dist' })); + const extensions = await (await api(daemon, '/api/extensions')).json(); + assert.equal(extensions.some(state => state.manifest.id === 'loopx' && state.installed), false, 'Goal UI works without the external LoopX extension'); + writeFileSync(join(daemon.workdir, 'proposal.txt'), 'Synthetic proposal with review evidence.'); + browser = await launchBrowser(); + const create = async (title) => { + const response = await api(daemon, '/api/threads', { method: 'POST', body: JSON.stringify({ agent: 'pi', cwd: daemon.workdir, title }) }); + assert.equal(response.status, 201); return response.json(); + }; + bound = await create('[Launch] Proposal review'); + paused = await create('[Research] Release research'); + plain = await create('Ordinary conversation'); + for (let number = 2; number <= 5; number++) await create(`Ordinary conversation ${number}`); + for (const [title, patch] of [ + ['[Launch] Independent checks', { stage: 'doing' }], + ['[Launch] Approve the release notes', { stage: 'blocked' }], + ['[Launch] Review the final evidence', { stage: 'review' }], + ['[Launch] Accepted documentation', { done: true }], + ['[Research] Follow-up experiment', { stage: 'backlog' }], + ]) { + const thread = await create(title); + await api(daemon, `/api/threads/${thread.id}`, { method: 'PATCH', body: JSON.stringify(patch) }); + additionalBindings.set(thread.id, 'proposal'); + } +}); +after(async () => { await browser?.close(); await daemon?.stop(); if (core) await new Promise(resolve => core.close(resolve)); }); + +async function pageFor(t, mobile = false, theme = 'light', bindings = true) { + const context = await browser.newContext({ viewport: mobile ? { width: 390, height: 844 } : { width: 1440, height: 960 }, colorScheme: theme, isMobile: mobile, hasTouch: mobile }); + t.after(() => context.close()); + const page = await context.newPage(); + const mutations = []; + page.on('request', request => { if (request.method() !== 'GET' && (new URL(request.url()).pathname.startsWith('/api/loopx/') || /\/api\/threads(?:$|\/.*\/turns$)/.test(new URL(request.url()).pathname) && request.method() === 'POST')) mutations.push(request.url()); }); + t.after(() => assert.deepEqual(mutations, [], 'reading Goal details never starts work or creates a conversation')); + const errors = []; page.on('pageerror', error => errors.push(error.message)); + t.after(() => assert.deepEqual(errors, [])); + // Binding metadata normally comes from the Core's session lookup. Keep the real transport and + // thread behavior, adding only these two public-safe identities to the HTTP read response. + await page.route('**/api/threads**', async route => { + const url = new URL(route.request().url()); + if (route.request().method() !== 'GET' || !/^\/api\/threads(?:\/[^/]+)?$/.test(url.pathname)) return route.continue(); + const response = await route.fetch(); + if (!response.ok()) return route.fulfill({ response }); + const raw = await response.json(); + const value = !bindings && Array.isArray(raw) ? raw.filter(thread => thread.title.startsWith('Ordinary conversation')) : raw; + const enrich = thread => !bindings ? thread : thread.id === bound.id || additionalBindings.has(thread.id) ? { ...thread, loopxInfo: { goalId: 'proposal', goalTitle: goals[0].display_name, basis: 'core', source: 'fixture' } } + : thread.id === paused.id ? { ...thread, loopxInfo: { goalId: 'paused', goalTitle: goals[1].display_name, basis: 'core', source: 'fixture' } } : thread; + await route.fulfill({ response, json: Array.isArray(value) ? value.map(enrich) : enrich(value) }); + }); + await openUi(page, daemon); + return page; +} +async function shot(page, name) { + if (!process.env.LOOCHAT_E2E_SHOTS_DIR) return; + mkdirSync(process.env.LOOCHAT_E2E_SHOTS_DIR, { recursive: true }); + await page.screenshot({ path: join(process.env.LOOCHAT_E2E_SHOTS_DIR, `${name}.png`), animations: 'disabled' }); +} +const noOverflow = async page => assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false); + +test('packaged board shows Goal tags and persists the goal-only filter in desktop and mobile themes', async t => { + for (const mobile of [false, true]) for (const theme of ['light', 'dark']) { + const page = await pageFor(t, mobile, theme); + await page.goto(daemon.base + '/#/board'); + await page.getByRole('button', { name: '仅长程目标', exact: true }).click(); + if (mobile) await page.getByRole('tab', { name: /待验收/ }).click(); + await page.locator('.ext-board-goal[data-goal-id="proposal"]:visible').first().waitFor(); + assert.match(await page.locator('.ext-board-goal[data-goal-id="proposal"]:visible').first().textContent(), /等你/); + assert.match(await page.locator('.ext-board-goal[data-goal-id="paused"]').textContent(), /暂停/); + assert.equal(await page.getByRole('button', { name: 'Ordinary conversation', exact: true }).count(), 0); + assert.equal(await page.locator('.ext-board-goal').evaluateAll(nodes => nodes.every(node => getComputedStyle(node).whiteSpace === 'nowrap' && node.clientHeight <= 22)), true); + await noOverflow(page); + await shot(page, `goal-board-${mobile ? 'phone' : 'desktop'}-${theme}`); + if (!mobile && theme === 'light') { + await page.getByRole('button', { name: '项目', exact: true }).click(); + await shot(page, 'goal-board-desktop-filter-open'); + await page.keyboard.press('Escape'); + } + await page.reload(); + await page.getByRole('button', { name: '仅长程目标', exact: true }).waitFor(); + assert.equal(await page.getByRole('button', { name: '仅长程目标', exact: true }).getAttribute('aria-pressed'), 'true'); + await page.getByRole('button', { name: '仅长程目标', exact: true }).click(); + if (mobile) await page.getByRole('tab', { name: /待验收/ }).click(); + await page.getByRole('button', { name: 'Ordinary conversation', exact: true }).waitFor(); + const plainCard = page.locator('.ext-board-card').filter({ has: page.getByRole('button', { name: 'Ordinary conversation', exact: true }) }); + assert.equal(await plainCard.locator('.ext-board-tags').count(), 0, 'ordinary cards have unchanged tag markup'); + await page.close(); + } +}); + +test('legacy Goal deep links and All Goals lead to the one board or in-place conversation details', async t => { + for (const mobile of [false, true]) for (const theme of ['light', 'dark']) { + const page = await pageFor(t, mobile, theme); + await page.goto(daemon.base + '/#/goals'); + await page.locator('.steward-overview').waitFor(); + await page.waitForURL(daemon.base + '/#/steward?goals'); + await page.getByRole('button', { name: '在看板查看 Goal 对话', exact: true }).click(); + await page.locator('.ext-board-page').waitFor(); + await page.waitForURL(daemon.base + '/#/board'); + assert.equal(await page.getByRole('button', { name: '仅长程目标', exact: true }).getAttribute('aria-pressed'), 'true'); + await page.goto(daemon.base + '/#/goals/proposal/files'); + await page.locator('[data-goal-detail="proposal"]').waitFor(); + assert.equal(await page.locator('.goal-page,.goals-page,.goal-tabs').count(), 0); + assert.equal(await page.getByRole('button', { name: '收起目标', exact: true }).count(), 1); + const toggles = page.locator('.goal-detail-toggle'); + assert.deepEqual(await toggles.evaluateAll(nodes => nodes.map(node => node.getAttribute('aria-expanded'))), ['false', 'false', 'false', 'false']); + const before = reads.filter(path => path.includes('goal_id=proposal')).length; + await toggles.filter({ hasText: '任务' }).click(); + await page.getByRole('button', { name: /Review the proposal and choose/ }).waitFor(); + assert.ok(reads.filter(path => path.includes('goal_id=proposal')).length > before); + assert.equal(await page.locator('.goal-tasks-board,.goal-tasks-switch').count(), 0); + await page.locator('.goal-tasks-owner').click(); + await page.getByRole('menuitemradio', { name: 'reviewer', exact: true }).click(); + await page.getByRole('button', { name: /Review supporting evidence/ }).waitFor(); + assert.equal(await page.getByRole('button', { name: /Run independent checks/ }).count(), 0); + await page.locator('.goal-tasks-owner').click(); + await page.getByRole('menuitemradio', { name: '全部负责人(2)', exact: true }).click(); + await noOverflow(page); + const fitted = await page.locator('.thread-overview.with-goal-details').evaluate(el => { + const content = el.querySelector('.overview-content').getBoundingClientRect(); + const footer = el.querySelector('.overview-foot').getBoundingClientRect(); + return content.bottom <= footer.top + 1 && el.getBoundingClientRect().bottom <= innerHeight; + }); + assert.equal(fitted, true, 'expanded readers stay inside the panel above its footer'); + await shot(page, `goal-details-${mobile ? 'phone' : 'desktop'}-${theme}`); + filesFail = true; + await toggles.filter({ hasText: '文件' }).click(); + await page.locator('.goal-files [role="alert"]').waitFor(); + await shot(page, `goal-files-failure-${mobile ? 'phone' : 'desktop'}-${theme}`); + filesFail = false; + await page.getByRole('button', { name: '刷新', exact: true }).click(); + await page.locator('.goal-files [role="alert"]').waitFor({ state: 'hidden' }); + await page.getByRole('button', { name: '浏览工作区', exact: true }).click(); + const files = page.locator('.files-panel'); + await files.locator('.files-row', { hasText: 'proposal.txt' }).click(); + await files.getByText('Synthetic proposal with review evidence.', { exact: false }).waitFor(); + await shot(page, `goal-workspace-${mobile ? 'phone' : 'desktop'}-${theme}`); + await files.getByRole('button', { name: mobile ? '关闭' : '关闭文件', exact: true }).click(); + await files.waitFor({ state: 'hidden' }); + if (mobile) await page.keyboard.press('Escape'); + await page.goto(daemon.base + '/#/goals'); + await page.locator('.steward-overview').waitFor(); + await page.getByRole('button', { name: '在看板查看 Goal 对话', exact: true }).click(); + await page.locator('.ext-board-page').waitFor(); + await page.waitForURL(daemon.base + '/#/board'); + assert.equal(new URL(page.url()).hash, '#/board'); + assert.equal(await page.getByRole('button', { name: '仅长程目标', exact: true }).getAttribute('aria-pressed'), 'true'); + await page.goto(daemon.base + '/#/goals/missing'); + await page.locator('.steward-overview').waitFor(); + await page.waitForURL(daemon.base + '/#/steward?goal=missing'); + await page.locator('.overview-goal[data-goal-id="missing"]').getByText('这个 Goal 已经不在了:可能已被删除。', { exact: true }).waitFor(); + await page.close(); + } +}); + + +test('unbound Core Goal bookmarks open a read-only steward reader and survive reload', async t => { + for (const mobile of [false, true]) for (const theme of ['light', 'dark']) { + const page = await pageFor(t, mobile, theme); + await page.goto(daemon.base + '/#/goals/core-8/tasks'); + const details = page.locator('[data-goal-detail="core-8"]'); + await details.waitFor(); + await page.waitForURL(daemon.base + '/#/steward?goal=core-8'); + const row = page.locator('.overview-goal[data-goal-id="core-8"]'); + assert.match(await row.textContent(), /Core-only Goal 8/); + assert.equal(await page.locator('.ext-board-page,.goal-page,.goals-page').count(), 0); + const toggles = details.locator('.goal-detail-toggle'); + assert.deepEqual(await toggles.evaluateAll(nodes => nodes.map(node => node.getAttribute('aria-expanded'))), ['false', 'false', 'false', 'false']); + await toggles.filter({ hasText: '概览' }).click(); + await details.getByText('Retain independently readable results for Core Goal 8.', { exact: true }).waitFor(); + await noOverflow(page); + await shot(page, `unbound-goal-${mobile ? 'phone' : 'desktop'}-${theme}`); + await toggles.filter({ hasText: '任务' }).click(); + await details.getByRole('button', { name: /Review supporting evidence for core-8/ }).waitFor(); + await toggles.filter({ hasText: '文件' }).click(); + await details.getByRole('button', { name: /Core-only retained report/ }).click(); + await details.getByText('Retained Core report without a Workbench conversation.', { exact: true }).waitFor(); + assert.equal(await details.getByRole('button', { name: '对话', exact: true }).count(), 0); + assert.equal(await details.getByRole('button', { name: '浏览工作区', exact: true }).count(), 0); + await toggles.filter({ hasText: '验收' }).click(); + await details.getByText('Independent evidence remains readable', { exact: true }).waitFor(); + assert.equal(await details.locator('.goal-accept-actions').count(), 0); + await page.reload(); + await page.locator('[data-goal-detail="core-8"]').waitFor(); + assert.match(new URL(page.url()).hash, /goal=core-8/); + await page.close(); + } +}); + +test('eight Core Goals with no Workbench bindings keep their reader and hide the board shortcut', async t => { + for (const mobile of [false, true]) { + const page = await pageFor(t, mobile, 'light', false); + await page.goto(daemon.base + '/#/goals'); + await page.locator('.steward-overview').waitFor(); + await page.waitForURL(daemon.base + '/#/steward?goals'); + assert.equal(await page.getByRole('button', { name: '在看板查看 Goal 对话', exact: true }).count(), 0); + assert.equal(await page.locator('.ext-board-page').count(), 0); + assert.equal(await page.locator('.thread-item').count(), 5); + await page.reload(); + await page.locator('.steward-overview').waitFor(); + assert.equal(new URL(page.url()).hash, '#/steward?goals'); + await page.goto(daemon.base + '/#/goals/proposal'); + await page.locator('[data-goal-detail="proposal"]').waitFor(); + await page.waitForURL(daemon.base + '/#/steward?goal=proposal'); + assert.match(await page.locator('.overview-goal[data-goal-id="proposal"]').textContent(), /Review the launch proposal/); + await page.close(); + } +}); diff --git a/apps/workbench/packages/e2e/test/import-outside-roots.spec.mjs b/apps/workbench/packages/e2e/test/import-outside-roots.spec.mjs new file mode 100644 index 0000000000..c35753e124 --- /dev/null +++ b/apps/workbench/packages/e2e/test/import-outside-roots.spec.mjs @@ -0,0 +1,54 @@ +// Importing a sidebar session from outside the project roots adds its directory as a root; the +// page reads the roots again, so the new one is there without a reload. +import { test, before, after } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { randomUUID } from 'node:crypto'; +import { join } from 'node:path'; +import { startDaemon, openUi, api, launchBrowser } from '../harness.mjs'; + +let elsewhere, messagesDir, daemon, browser; +const sessionId = randomUUID(); + +before(async () => { + elsewhere = mkdtempSync(join(tmpdir(), 'loochat-e2e-elsewhere-')); + messagesDir = mkdtempSync(join(tmpdir(), 'loochat-e2e-msgs-')); + // The session is there before the hub starts, so its first scan finds it. + const sessions = join(messagesDir, 'pi-agent', 'sessions', 'e2e'); + mkdirSync(sessions, { recursive: true }); + writeFileSync(join(sessions, `e2e_${sessionId}.jsonl`), JSON.stringify({ type: 'session', id: sessionId, cwd: elsewhere }) + '\n' + JSON.stringify({ type: 'session_info', name: '别处的会话' }) + '\n'); + writeFileSync(join(messagesDir, 'messages.json'), JSON.stringify({ + [sessionId]: [{ role: 'user', content: '你好' }, { role: 'assistant', content: [{ type: 'text', text: '在别的目录里' }] }], + })); + daemon = await startDaemon({ FAKE_PI_MESSAGES_FILE: join(messagesDir, 'messages.json'), PI_CODING_AGENT_DIR: join(messagesDir, 'pi-agent') }); + browser = await launchBrowser(); +}); + +after(async () => { + await browser?.close(); + await daemon?.stop(); + rmSync(elsewhere, { recursive: true, force: true }); + rmSync(messagesDir, { recursive: true, force: true }); +}); + +test('importing a session from outside the roots adds its directory, and the page shows it', async () => { + const before = await (await api(daemon, '/api/config')).json(); + assert.ok(!before.workdirs.includes(elsewhere)); + + const context = await browser.newContext({ viewport: { width: 1440, height: 960 } }); + const page = await context.newPage(); + try { + await openUi(page, daemon); + const row = page.locator('.thread-row.external', { hasText: '别处的会话' }); + // The scan after startup may still be running when the page first asks; a reload reads it again. + await row.waitFor({ timeout: 10_000 }).catch(async () => { await page.reload(); await row.waitFor({ timeout: 10_000 }); }); + const reread = page.waitForResponse((res) => new URL(res.url()).pathname === '/api/config' && res.request().method() === 'GET', { timeout: 15_000 }); + await row.locator('.thread-item').click(); + const roots = await (await reread).json(); + assert.ok(roots.workdirs.includes(elsewhere), 'the page reads the roots with the new directory'); + assert.ok((await (await api(daemon, '/api/config')).json()).workdirs.includes(elsewhere)); + } finally { + await context.close(); + } +}); diff --git a/apps/workbench/packages/e2e/test/install.spec.mjs b/apps/workbench/packages/e2e/test/install.spec.mjs index ea661c9679..016137ac42 100644 --- a/apps/workbench/packages/e2e/test/install.spec.mjs +++ b/apps/workbench/packages/e2e/test/install.spec.mjs @@ -123,6 +123,14 @@ test('setup preserves current and historical tokens without appending a second c } }); +test('help works when the installer is supplied on stdin', () => { + const installer = readFileSync(join(repo, 'install.sh'), 'utf8'); + const result = spawnSync('bash', ['-s', '--', '--help'], { input: installer, encoding: 'utf8' }); + assert.equal(result.status, 0, result.stderr); + assert.match(result.stdout, /--dry-run/); + assert.match(result.stdout, /--no-service/); +}); + test('a dry run changes nothing', (t) => { const { run, read, home } = fixture(t); const r = run('--dry-run'); diff --git a/apps/workbench/packages/e2e/test/oar.spec.mjs b/apps/workbench/packages/e2e/test/oar.spec.mjs new file mode 100644 index 0000000000..e747f1a2af --- /dev/null +++ b/apps/workbench/packages/e2e/test/oar.spec.mjs @@ -0,0 +1,90 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdirSync, mkdtempSync, writeFileSync, rmSync } from 'node:fs'; +import { join, dirname } from 'node:path'; +import { tmpdir } from 'node:os'; +import { fileURLToPath } from 'node:url'; +import { startDaemon, launchBrowser, openUi, api } from '../harness.mjs'; + +const fixture = fileURLToPath(new URL('../../daemon/test/fixtures/fake-oar-grok.mjs', import.meta.url)); +const ids = ['cursor', 'codebuddy', 'devin', 'factory', 'grok', 'kimi', 'opencode', 'qoder', 'qwen']; +const names = ['Cursor', 'CodeBuddy Code', 'Devin', 'Factory Droid', 'Kimi Code', 'OpenCode', 'Qoder', 'Qwen Code']; + +test('OAR dependencies cannot shadow the existing native Pi on the shipped server path', { timeout: 30000 }, async () => { + const bin = mkdtempSync(join(tmpdir(), 'native-pi-bin-')); + const nativeFixture = new URL('../../daemon/test/fixtures/fake-pi.mjs', import.meta.url).href; + writeFileSync(join(bin, 'pi'), `#!${process.execPath}\nawait import(${JSON.stringify(nativeFixture)});\n`, { mode: 0o755 }); + const serverBin = fileURLToPath(new URL('../../../node_modules/.bin', import.meta.url)); + let daemon; + try { + daemon = await startDaemon({ + PATH: `${serverBin}:${bin}:${dirname(process.execPath)}:/usr/bin:/bin`, + LOOCHAT_AGENTS_JSON: JSON.stringify({ agents: [{ id: 'pi', adapter: 'pi', command: ['pi'] }] }), + }); + const models = await (await api(daemon, '/api/agents/pi/models')).json(); + assert.deepEqual(models.map(model => model.id), ['fake/think', 'fake/plain', 'fake/loose']); + const discovered = await (await api(daemon, '/api/agents/discover')).json(); + assert.ok(!discovered.some(agent => agent.command?.includes('@earendil-works/pi-coding-agent'))); + } finally { await daemon?.stop(); rmSync(bin, { recursive: true, force: true }); } +}); + +for (const mobile of [false, true]) for (const colorScheme of ['light', 'dark']) { + test(`OAR discovery and native ACP chat: ${mobile ? 'phone' : 'desktop'} ${colorScheme}`, { timeout: 90000 }, async () => { + const daemon = await startDaemon({ PATH: `${dirname(process.execPath)}:/usr/bin:/bin`, LOOCHAT_AGENTS_JSON: JSON.stringify({ agents: [{ id: 'grok', adapter: 'grok', command: [fixture] }] }) }); + const browser = await launchBrowser(); + const context = await browser.newContext({ viewport: mobile ? { width: 390, height: 844 } : { width: 1440, height: 1000 }, isMobile: mobile, hasTouch: mobile, colorScheme }); + const page = await context.newPage(); + const errors = []; + page.on('pageerror', error => errors.push(error.message)); + const shot = async name => { + if (!process.env.LOOCHAT_E2E_SHOTS_DIR) return; + mkdirSync(process.env.LOOCHAT_E2E_SHOTS_DIR, { recursive: true }); + await page.screenshot({ path: join(process.env.LOOCHAT_E2E_SHOTS_DIR, `oar-${name}-${mobile ? 'phone' : 'desktop'}-${colorScheme}.png`), animations: 'disabled' }); + }; + try { + const supported = await (await api(daemon, '/api/agents/supported')).json(); + for (const id of ids) assert.ok(supported.some(agent => agent.adapter === id), id); + await openUi(page, daemon); + await page.locator('.composer textarea').last().fill('hello'); + await page.locator('.composer .send-btn:not(.stop)').last().click(); + await page.getByText(/Native ACP answer: hello/).first().waitFor({ timeout: 25000 }); + const threads = await (await api(daemon, '/api/threads')).json(); + assert.equal(threads.length, 1); + assert.equal(threads[0].permissionMode, 'full_access'); + assert.equal(threads[0].agentSessionId, 'public-fixture-session'); + await page.waitForFunction(async ({ base, token, id }) => { const response = await fetch(base + '/api/threads/' + id, { headers: { Authorization: 'Bearer ' + token } }); return (await response.json()).status === 'idle'; }, { base: daemon.base, token: daemon.token, id: threads[0].id }); + await page.locator('.composer .send-btn:not(.stop)').last().waitFor(); + await shot('chat'); + await page.goto(daemon.base + '/#/thread/' + threads[0].id, { waitUntil: 'domcontentloaded' }); + await page.getByText(/Native ACP answer: hello/).first().waitFor(); + const detail = await (await api(daemon, '/api/threads/' + threads[0].id)).json(); + assert.equal(detail.resumeCommand, null, 'no unusable native terminal shortcut'); + await page.locator('.composer textarea').last().fill('crash'); + await page.locator('.composer .send-btn:not(.stop)').last().click(); + await page.waitForFunction(async ({ base, token, id }) => { + const response = await fetch(base + '/api/threads/' + id, { headers: { Authorization: 'Bearer ' + token } }); + return (await response.json()).status === 'error'; + }, { base: daemon.base, token: daemon.token, id: threads[0].id }); + await page.locator('.error-box').last().waitFor(); + await page.locator('.error-box').last().scrollIntoViewIfNeeded(); + await page.locator('.composer .send-btn:not(.stop)').last().waitFor(); + await shot('failure'); + await page.locator('.composer textarea').last().fill('recovered'); + await page.locator('.composer .send-btn:not(.stop)').last().click(); + await page.getByText('Native ACP answer: recovered', { exact: true }).waitFor({ timeout: 20000 }); + assert.equal((await (await api(daemon, '/api/threads/' + threads[0].id)).json()).agentSessionId, 'public-fixture-session'); + await page.goto(daemon.base + '/#/agents'); + await page.getByRole('button', { name: '添加 agent', exact: true }).click(); + await page.getByRole('button', { name: '接入已安装的 agent 或已有账号', exact: true }).click(); + const dialog = page.locator('.onboard-dialog-results'); + await dialog.waitFor(); + for (const name of names) await dialog.getByText(name, { exact: true }).waitFor({ timeout: 20000 }); + assert.equal(await dialog.getByRole('link', { name: '安装说明', exact: true }).count(), 7); + await shot('discovery-first'); + await dialog.getByText('Qwen Code', { exact: true }).scrollIntoViewIfNeeded(); + await shot('discovery-agents'); + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), 'no horizontal overflow'); + assert.deepEqual(errors, []); + } finally { await context.close(); await browser.close(); await daemon.stop(); } + }); +} diff --git a/apps/workbench/packages/e2e/test/optimistic-send.spec.mjs b/apps/workbench/packages/e2e/test/optimistic-send.spec.mjs new file mode 100644 index 0000000000..3ed26051bd --- /dev/null +++ b/apps/workbench/packages/e2e/test/optimistic-send.spec.mjs @@ -0,0 +1,187 @@ +// Optimistic thread creation, optimistic user messages, and mobile/desktop composer guarantees. +import { test, before, after } from 'node:test'; +import assert from 'node:assert/strict'; +import { startDaemon, openUi, api, launchBrowser } from '../harness.mjs'; + +let daemon; +let browser; + +before(async () => { + daemon = await startDaemon(); + browser = await launchBrowser(); +}); + +after(async () => { + await browser?.close(); + await daemon?.stop(); +}); + +test('desktop new thread navigates immediately on send without waiting for createThread or GET /api/threads', async () => { + const context = await browser.newContext({ viewport: { width: 1280, height: 820 } }); + const page = await context.newPage(); + await openUi(page, daemon); + + // Delay thread creation, turn start, and thread-list refresh to expose any non-optimistic blocking. + await page.route('**/api/threads', async (route) => { + const method = route.request().method(); + if (method === 'POST') await new Promise(r => setTimeout(r, 900)); + else if (method === 'GET') await new Promise(r => setTimeout(r, 1200)); + await route.continue().catch(() => undefined); + }); + await page.route('**/api/threads/*/turns', async (route) => { + await new Promise(r => setTimeout(r, 600)); + await route.continue().catch(() => undefined); + }); + + const textarea = page.locator('.composer-box textarea'); + await textarea.fill('Optimistic desktop prompt'); + const sentAt = Date.now(); + await page.locator('.composer .send-btn:not(.stop)').click(); + + // Immediately leaves the empty new-thread screen and shows the user message (well before the 900ms POST finishes). + await page.locator('.row.user', { hasText: 'Optimistic desktop prompt' }).waitFor({ timeout: 500 }); + const elapsed = Date.now() - sentAt; + assert.ok(elapsed < 500, `expected instant optimistic navigation, took ${elapsed}ms`); + assert.equal(await page.locator('.empty').count(), 0, 'new-thread empty prompt must disappear immediately'); + assert.equal(await textarea.inputValue(), '', 'composer clears immediately so follow-up typing never sticks'); + + // Once the delayed backend finishes, the message never disappears or duplicates and the reply arrives. + await page.locator('.row.assistant .markdown').first().waitFor({ timeout: 15_000 }); + assert.equal(await page.locator('.row.user').count(), 1, 'optimistic and confirmed messages reconcile into one bubble'); + assert.equal(await page.locator('.row.user[data-optimistic]').count(), 0, 'optimistic marker clears after confirmation'); + + await context.close(); +}); + +test('typing a follow-up during a slow send does not stick old sent text in the box', async () => { + const post = (path, body) => api(daemon, path, { method: 'POST', body: JSON.stringify(body) }); + const thread = await (await post('/api/threads', { agent: 'pi', cwd: daemon.workdir })).json(); + await post(`/api/threads/${thread.id}/turns`, { text: 'seed turn' }); + for (let i = 0; i < 80; i++) { + if ((await (await api(daemon, `/api/threads/${thread.id}`)).json()).status !== 'running') break; + await new Promise(r => setTimeout(r, 100)); + } + + const context = await browser.newContext({ viewport: { width: 1280, height: 820 } }); + const page = await context.newPage(); + await openUi(page, daemon); + await page.locator('.thread-item', { hasText: 'seed turn' }).click(); + await page.locator('.row.assistant .markdown').waitFor(); + + await page.route('**/turns', async (route) => { + await new Promise(r => setTimeout(r, 900)); + await route.continue().catch(() => undefined); + }); + + const textarea = page.locator('.composer-box textarea'); + await textarea.fill('first slow message'); + await page.locator('.composer .send-btn:not(.stop)').click(); + // User immediately sees the message in timeline and starts typing the next message while POST is in flight. + await page.locator('.row.user', { hasText: 'first slow message' }).waitFor({ timeout: 500 }); + assert.equal(await textarea.inputValue(), ''); + await textarea.fill('next draft while sending'); + + await page.locator('.row.user:not([data-optimistic])', { hasText: 'first slow message' }).waitFor({ timeout: 10_000 }); + assert.equal(await textarea.inputValue(), 'next draft while sending', 'only the new draft remains; old sent text never sticks'); + + await context.close(); +}); + +test('failed first turn on a new thread rolls back to new thread, restores draft, and removes orphan thread', async () => { + const context = await browser.newContext({ viewport: { width: 1280, height: 820 } }); + const page = await context.newPage(); + await openUi(page, daemon); + + const beforeThreads = await (await api(daemon, '/api/threads')).json(); + await page.route('**/api/threads/*/turns', async (route) => { + await route.fulfill({ status: 500, contentType: 'application/json', body: JSON.stringify({ error: 'simulated failure' }) }); + }); + + const textarea = page.locator('.composer-box textarea'); + await textarea.fill('must not become orphan'); + await page.locator('.composer .send-btn:not(.stop)').click(); + + // Rolls back to the new-thread screen and restores the exact draft text in the composer. + await page.locator('.empty').waitFor({ timeout: 5000 }); + await page.waitForFunction(() => document.querySelector('.composer-box textarea')?.value === 'must not become orphan', { timeout: 5000 }); + + // Wait briefly for DELETE /api/threads/:id?ifEmpty=1 cleanup and confirm no orphan thread remains on daemon. + await page.waitForTimeout(400); + const afterThreads = await (await api(daemon, '/api/threads')).json(); + assert.equal(afterThreads.length, beforeThreads.length, 'orphan 0-turn thread must be cleaned up on first-turn failure'); + + await context.close(); +}); + +test('dropped POST /turns response after completed turn preserves durable thread and shows reply', async () => { + const context = await browser.newContext({ viewport: { width: 1280, height: 820 } }); + const page = await context.newPage(); + await openUi(page, daemon); + + let createdThreadId = null; + await page.route('**/api/threads/*/turns', async (route) => { + const match = route.request().url().match(/\/api\/threads\/([^/]+)\/turns/); + createdThreadId = match?.[1] ?? null; + // Deliver the POST to the real daemon and wait until the turn finishes in SQLite, + // then abort the client response to simulate a transport drop after acceptance. + const response = await route.fetch(); + assert.equal(response.status(), 202); + if (createdThreadId) { + for (let i = 0; i < 80; i++) { + const res = await api(daemon, `/api/threads/${createdThreadId}`); + if (res.status === 200 && (await res.json()).status !== 'running') break; + await new Promise(r => setTimeout(r, 100)); + } + } + await route.abort('failed'); + }); + + const textarea = page.locator('.composer-box textarea'); + await textarea.fill('must survive dropped response'); + await page.locator('.composer .send-btn:not(.stop)').click(); + + // The durable thread stays HTTP 200 (never deleted as an orphan) and renders the completed answer. + await page.locator('.row.assistant .markdown').first().waitFor({ timeout: 15_000 }); + assert.ok(createdThreadId, 'captured created thread id'); + const readback = await api(daemon, `/api/threads/${createdThreadId}`); + assert.equal(readback.status, 200, 'completed thread must remain HTTP 200 after client response drop'); + assert.equal(await textarea.inputValue(), '', 'accepted message must not be restored as unsent draft'); + + await context.close(); +}); + +test('mobile touch: optimistic new-thread send, IME blur without compositionend never deadlocks, and composer blurs after send', async () => { + const context = await browser.newContext({ + viewport: { width: 390, height: 844 }, + isMobile: true, + hasTouch: true, + }); + const page = await context.newPage(); + await openUi(page, daemon); + + await page.route('**/api/threads', async (route) => { + if (route.request().method() === 'POST') await new Promise(r => setTimeout(r, 700)); + await route.continue().catch(() => undefined); + }); + + const textarea = page.locator('.composer-box textarea'); + await textarea.tap(); + await textarea.fill('Mobile optimistic send test'); + + // Simulate an IME that enters compositionstart and commits silently on blur without firing compositionend. + await textarea.evaluate((el) => { + el.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true, data: 'test' })); + }); + await page.locator('.composer .send-btn:not(.stop)').tap(); + + // Fallback timer (120ms) unblocks IME and sends; UI leaves empty state well before the 700ms POST returns. + await page.locator('.row.user', { hasText: 'Mobile optimistic send test' }).waitFor({ timeout: 600 }); + assert.equal(await page.locator('.empty').count(), 0); + + // Wait for confirmation & reply; on touch devices the textarea should not force-refocus after send. + await page.locator('.row.assistant .markdown').first().waitFor({ timeout: 15_000 }); + const activeTag = await page.evaluate(() => document.activeElement?.tagName ?? ''); + assert.notEqual(activeTag, 'TEXTAREA', 'mobile send must not force-refocus textarea after sending'); + + await context.close(); +}); diff --git a/apps/workbench/packages/e2e/test/overview-adaptive.spec.mjs b/apps/workbench/packages/e2e/test/overview-adaptive.spec.mjs index 6691c85b74..376b4934d7 100644 --- a/apps/workbench/packages/e2e/test/overview-adaptive.spec.mjs +++ b/apps/workbench/packages/e2e/test/overview-adaptive.spec.mjs @@ -108,8 +108,8 @@ test('adaptive overview waits at its trigger, fits without scrolling and preserv if (shots && width !== 320) await page.screenshot({ path: `${shots}/overview-files-${width}-${theme}.png` }); await detail.locator('.overview-row').hover(); await detail.locator('.overview-preview').click(); - await page.locator('.preview-scrim').waitFor(); - await page.locator('.preview-bar').getByRole('button', { name: '关闭预览' }).click(); + await page.locator('.preview-scrim, .dock-panel .preview').waitFor(); + await page.locator('.preview-bar').getByRole('button', { name: mobile ? '关闭预览' : '返回', exact: true }).click(); assert.equal(await detail.locator('input').inputValue(), 'report-7'); if (mobile) await detail.locator('.overview-details-head button').click(); else await page.evaluate(() => history.back()); diff --git a/apps/workbench/packages/e2e/test/overview-dock.spec.mjs b/apps/workbench/packages/e2e/test/overview-dock.spec.mjs new file mode 100644 index 0000000000..2a7bfc929e --- /dev/null +++ b/apps/workbench/packages/e2e/test/overview-dock.spec.mjs @@ -0,0 +1,153 @@ +import { test, before, after } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdirSync } from 'node:fs'; +import { join } from 'node:path'; +import { DatabaseSync } from 'node:sqlite'; +import { startDaemon, launchBrowser, openUi, api } from '../harness.mjs'; + +let hub, browser, thread; +const json = async (path, body, method = body ? 'POST' : 'GET') => { + const response = await api(hub, path, { method, ...(body ? { body: JSON.stringify(body) } : {}) }); + assert.ok(response.ok, await response.clone().text()); return response.json(); +}; +const idle = async id => { + for (let n = 0; n < 200; n++) { + if ((await json(`/api/threads/${id}`)).status !== 'running') return; + await new Promise(r => setTimeout(r, 50)); + } + assert.fail('thread did not settle'); +}; +before(async () => { + hub = await startDaemon({ FAKE_ACP_VISIBLE_ECHO: '1' }); browser = await launchBrowser(); + thread = await json('/api/threads', { agent: 'claude', cwd: hub.workdir, title: '变更与产物' }); + await json(`/api/threads/${thread.id}/turns`, { text: 'edit file make outputs plan' }); await idle(thread.id); +}); +after(async () => { await browser?.close(); await hub?.stop(); }); +const shots = process.env.LOOCHAT_E2E_SHOTS_DIR; +const capture = async (page, name) => { if (shots) { mkdirSync(shots, { recursive: true }); await page.screenshot({ path: join(shots, name + '.png'), animations: 'disabled' }); } }; +const openGroup = async (page, name) => { + const trigger = page.locator('.topbar-overview'); + if (!(await page.locator('.overview-panel:visible').count()) && await trigger.getAttribute('aria-pressed') !== 'true') await trigger.click(); + await page.locator('.overview-panel .thread-overview[data-ready=true]').waitFor(); + const group = page.locator('.overview-group').filter({ has: page.locator('.overview-toggle strong', { hasText: new RegExp(`^${name}$`) }) }); + const all = group.getByRole('button', { name: '查看全部', exact: true }); + if (await all.isVisible()) await all.click(); else await group.locator('.overview-toggle').click(); + await page.locator('.overview-details-page').waitFor(); +}; + +for (const phone of [false, true]) for (const colorScheme of ['light', 'dark']) { + test(`overview details, diffs, pages and pictures keep their owner: ${phone ? 'phone' : 'desktop'} ${colorScheme}`, async () => { + const context = await browser.newContext({ viewport: phone ? { width: 390, height: 844 } : { width: 1440, height: 960 }, isMobile: phone, hasTouch: phone, colorScheme }); + const page = await context.newPage(); page.setDefaultTimeout(12_000); + const errors = []; page.on('pageerror', e => errors.push(e.message)); + const name = `${phone ? 'phone' : 'desktop'}-${colorScheme}`; + try { + await openUi(page, hub); + if (phone) await page.locator('.menu-btn').click(); + await page.locator('.thread-row', { hasText: thread.title }).click(); + const draft = page.locator('main .composer textarea'); + await draft.fill('保留主对话的草稿'); + await openGroup(page, '变更'); + const list = page.locator('.overview-details-page'); + assert.equal(await list.locator('..').evaluate(el => el.classList.contains('dock-panel')), !phone); + await list.locator('.overview-row', { hasText: 'app.ts' }).click(); + const diff = page.locator('.change-diff-dialog'); + await diff.locator('.diff-line.add', { hasText: 'const c = 4' }).waitFor(); + assert.equal(await page.locator('.dialog-scrim:visible').count(), phone ? 1 : 0); + assert.equal(await page.locator('.dock-panel:visible').count(), phone ? 0 : 1); + assert.equal(await draft.inputValue(), '保留主对话的草稿'); + await capture(page, `${name}-diff`); + if (!phone) { + const dock = page.locator('.dock-panel:visible'); const width = (await dock.boundingBox()).width; + const edge = await dock.getByRole('separator').boundingBox(); + await page.mouse.move(edge.x + 3, edge.y + 180); await page.mouse.down(); + await page.mouse.move(edge.x + 53, edge.y + 180, { steps: 3 }); await page.mouse.up(); + assert.ok((await dock.boundingBox()).width < width - 40); + await diff.getByRole('button', { name: '返回', exact: true }).click(); + } else await diff.getByRole('button', { name: '关闭', exact: true }).click(); + await list.waitFor(); + if (!phone) assert.ok(Math.abs((await page.locator('.dock-panel:visible').boundingBox()).width - await page.evaluate(() => Number(localStorage.getItem('calli.files.width')))) <= 2, 'returning to the list keeps the resized shared width'); + await list.locator('.overview-details-head button').click(); await page.locator('.overview-panel:visible').waitFor(); + await openGroup(page, '文件'); + // An unavailable HTML preview retries in place and keeps its frame through parent updates. + await page.route(`**/threads/${thread.id}/preview-link?*`, route => route.fulfill({ status: 503, json: { error: 'preview temporarily unavailable' } }), { times: 1 }); + await list.locator('.overview-row', { hasText: 'report.html' }).click(); + const preview = page.locator('.preview'); + await preview.getByRole('alert').waitFor(); + await preview.getByRole('button', { name: '重试', exact: true }).click(); + await page.frameLocator('.preview-frame').getByRole('heading', { name: 'Thread report' }).waitFor(); + assert.equal(await page.getByText('preview temporarily unavailable', { exact: true }).count(), 0, 'successful retry clears the error everywhere'); + const frame = await page.locator('.preview-frame').elementHandle(); + await json(`/api/threads/${thread.id}`, { title: thread.title }, 'PATCH'); + await page.waitForTimeout(250); + assert.equal(await frame.evaluate(el => el.isConnected), true, 'streaming metadata must not reload the preview'); + if (!phone) assert.equal(await page.locator('.preview-scrim').count(), 0); + await capture(page, `${name}-page`); + await preview.getByRole('button', { name: phone ? '关闭预览' : '返回', exact: true }).click(); + await list.waitFor(); await list.locator('.overview-details-head button').click(); await page.locator('.overview-panel:visible').waitFor(); + await openGroup(page, '图片'); + await list.locator('.overview-picture-row img').waitFor(); + if (!phone) await page.route(`**/threads/${thread.id}/files?*`, route => route.fulfill({ status: 503, json: { error: 'image temporarily unavailable' } }), { times: 1 }); + await list.locator('.overview-picture-row').click(); + if (!phone) { + const picture = page.locator('.picture-dock'); + await picture.getByRole('alert').waitFor(); + await picture.getByRole('button', { name: '重试', exact: true }).click(); + await picture.locator('img').waitFor(); + assert.equal(await page.locator('.lightbox').count(), 0); + await capture(page, `${name}-picture`); + await picture.getByRole('button', { name: '放大查看', exact: true }).click(); + } + await page.locator('.lightbox').waitFor(); + await page.locator('.lightbox-close').click(); + if (!phone) { await page.keyboard.press('Escape'); await list.waitFor(); } + await list.locator('.overview-details-head button').click(); await page.locator('.overview-panel:visible').waitFor(); + assert.equal(await draft.inputValue(), '保留主对话的草稿'); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false); + assert.deepEqual(errors, []); + } catch (error) { await capture(page, `${name}-failure`); throw error; } + finally { await context.close(); } + }); +} + +test('overview chain jumps read the handover boundary and explicitly expose follow-ups', async () => { + const source = await json('/api/threads', { agent: 'claude', cwd: hub.workdir, title: '交接前的工作' }); + const next = await json(`/api/threads/${source.id}/handover-thread`, { agent: 'pi', mode: 'continue' }); + const db = new DatabaseSync(join(hub.dataDir, 'hub.db')); + const insert = db.prepare('INSERT INTO events VALUES (?, ?, ?, ?, ?, ?)'); + let seq = Number(db.prepare('SELECT MAX(seq) AS n FROM events').get().n ?? 0); + const event = (id, turn, type, data) => insert.run(id, ++seq, turn, type, new Date(1760000000000 + seq * 1000).toISOString(), JSON.stringify(data)); + for (let n = 1; n <= 12; n++) { + event(source.id, `old-${n}`, 'turn.started', { text: `交接前问题 ${n}` }); + event(source.id, `old-${n}`, 'message.delta', { text: `交接前回答 ${n}` }); + event(source.id, `old-${n}`, 'turn.done', {}); + } + const boundary = seq; + db.prepare("UPDATE threads SET handover=json_set(handover, '$.sourceSeq', ?) WHERE id=?").run(boundary, next.id); + event(source.id, 'later', 'turn.started', { text: '交接后的补充' }); + event(source.id, 'later', 'message.delta', { text: '后续结果应按需查看' }); + event(source.id, 'later', 'turn.done', {}); + event(next.id, 'new', 'turn.started', { text: '继续工作' }); + event(next.id, 'new', 'message.delta', { text: '接手后的回答' }); + event(next.id, 'new', 'turn.done', {}); + db.close(); + for (const phone of [false, true]) { + const context = await browser.newContext({ viewport: phone ? { width: 390, height: 844 } : { width: 1440, height: 960 }, isMobile: phone, hasTouch: phone }); + const page = await context.newPage(); page.setDefaultTimeout(12_000); + const requests = []; page.on('request', req => requests.push(req.url())); + try { + await openUi(page, hub); + await page.evaluate(id => { location.hash = `#/thread/${id}`; }, next.id); + await page.getByText('接手后的回答', { exact: true }).waitFor(); + await openGroup(page, '接力'); + await page.locator('.overview-details-page .overview-member[title="交接前的工作"]').click(); + await page.getByText('交接前回答 12', { exact: true }).waitFor(); + assert.equal(await page.getByText('后续结果应按需查看', { exact: true }).count(), 0); + assert.ok(requests.some(url => url.includes(`/threads/${source.id}/history?`) && new URL(url).searchParams.get('before') === String(boundary + 1))); + if (!phone) await page.locator('.dock-panel .overview-member[aria-current=true]', { hasText: source.title }).waitFor(); + await page.getByRole('button', { name: '查看交接后的后续消息', exact: true }).click(); + await page.getByText('后续结果应按需查看', { exact: true }).waitFor(); + } catch (error) { await capture(page, `chain-${phone}-failure`); throw error; } + finally { await context.close(); } + } +}); diff --git a/apps/workbench/packages/e2e/test/overview-panel.spec.mjs b/apps/workbench/packages/e2e/test/overview-panel.spec.mjs index 791a70c922..5bd0e7ed14 100644 --- a/apps/workbench/packages/e2e/test/overview-panel.spec.mjs +++ b/apps/workbench/packages/e2e/test/overview-panel.spec.mjs @@ -3,6 +3,7 @@ // for the reading, and against the demo workspace for the tall panel that must not scroll. import { test } from 'node:test'; import assert from 'node:assert/strict'; +import { mkdirSync } from 'node:fs'; import { startDaemon, launchBrowser, openUi, api, openCollaboration } from '../harness.mjs'; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); @@ -77,6 +78,10 @@ test('the overview panel reads the thread from one top-bar button, and a change await panel.locator('.overview-row', { hasText: 'app.ts' }).click(); const diff = page.locator('.change-diff-dialog'); await diff.waitFor(); + // On a computer it takes the side column and the conversation stays beside it. + assert.equal(await page.locator('.dock-panel .change-diff-dialog').count(), 1, 'the diff is docked, not a dialog'); + assert.equal(await page.locator('.dialog-scrim').count(), 0); + await page.locator('.thread').waitFor(); await diff.locator('.diff-line.add', { hasText: 'const c = 4' }).first().waitFor(); const head = await diff.locator('.change-diff-head').innerText(); assert.match(head, /app\.ts/); @@ -84,6 +89,7 @@ test('the overview panel reads the thread from one top-bar button, and a change assert.match(head, /共 2 轮/); // Newest turn first, one section each. assert.deepEqual(await diff.locator('.change-diff-turn h3').allTextContents(), ['第 2 轮', '第 1 轮']); + if (process.env.LOOCHAT_E2E_SHOTS_DIR) { mkdirSync(process.env.LOOCHAT_E2E_SHOTS_DIR, { recursive: true }); await page.screenshot({ path: `${process.env.LOOCHAT_E2E_SHOTS_DIR}/overview-change-column.png`, animations: 'disabled' }); } await diff.locator('.change-diff-head .icon-btn').click(); await diff.waitFor({ state: 'detached' }); @@ -93,10 +99,18 @@ test('the overview panel reads the thread from one top-bar button, and a change await htmlRow.locator('.overview-row').waitFor(); await htmlRow.locator('.overview-row').hover(); await htmlRow.locator('.overview-preview').click(); - await page.locator('.preview-scrim').waitFor(); + await page.locator('.preview-scrim, .dock-panel .preview').waitFor(); assert.match(await page.locator('.preview-name').innerText(), /report\.html/); await page.locator('.preview-bar').getByRole('button', { name: '关闭预览' }).click(); - await page.locator('.preview-scrim').waitFor({ state: 'detached' }); + await page.locator('.preview-scrim, .dock-panel .preview').waitFor({ state: 'detached' }); + + // A picture opens in the column too, fitted, and closes back to the panel's place. + await panel.locator('.overview-picture-row').first().click(); + await page.locator('.dock-panel .picture-dock-stage img').waitFor(); + assert.equal(await page.locator('.lightbox').count(), 0, 'no full-screen viewer until asked for'); + await page.locator('.dock-panel .preview-bar button[aria-label="关闭"]').click(); + await page.locator('.dock-panel').waitFor({ state: 'detached' }); + await panel.waitFor(); // The more menu keeps the terminal and the trace beside the thread. await page.locator('.topbar-more').click(); diff --git a/apps/workbench/packages/e2e/test/pwa-install.spec.mjs b/apps/workbench/packages/e2e/test/pwa-install.spec.mjs new file mode 100644 index 0000000000..b4bad5a1c2 --- /dev/null +++ b/apps/workbench/packages/e2e/test/pwa-install.spec.mjs @@ -0,0 +1,85 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdirSync } from 'node:fs'; +import { join } from 'node:path'; +import { startDaemon, launchBrowser, openUi, api } from '../harness.mjs'; + +// Real packaged UI/backend; only browser-owned consent events are simulated. This does not +// certify OS installation on macOS or Windows. Screenshots contain synthetic conversations. +const shots = new URL('../../../../../output/playwright/pwa-install/', import.meta.url).pathname; +async function offer(page, outcome = 'dismissed', fail = false) { + await page.evaluate(({ outcome, fail }) => { + const event = new Event('beforeinstallprompt', { cancelable: true }); + event.prompt = () => { + window.installCalls = (window.installCalls ?? 0) + 1; + window.installClickedWithActivation = navigator.userActivation.isActive; + return fail ? Promise.reject(new Error('simulated browser refusal')) : Promise.resolve(); + }; + event.userChoice = Promise.resolve({ outcome }); + window.dispatchEvent(event); + }, { outcome, fail }); +} + +test('install entrypoints preserve consent, suppression, recovery and populated layouts', { timeout: 120000 }, async () => { + mkdirSync(shots, { recursive: true }); + const daemon = await startDaemon(); + const browser = await launchBrowser(); + try { + for (let i = 0; i < 18; i++) await api(daemon, '/api/threads', { + method: 'POST', body: JSON.stringify({ agent: 'pi', cwd: daemon.workdir, title: `Workspace review ${i + 1} — long conversation title for layout verification` }), + }); + for (const mobile of [false, true]) for (const theme of ['light', 'dark']) { + const context = await browser.newContext({ viewport: mobile ? { width: 390, height: 844 } : { width: 1440, height: 1000 }, isMobile: mobile, hasTouch: mobile, colorScheme: theme }); + const page = await context.newPage(); page.setDefaultTimeout(10000); + const errors = []; page.on('pageerror', error => errors.push(error.message)); + try { + // A synthetic expiring credential exercises the other standing footer notice. + await page.route('**/api/auth/kind', route => route.fulfill({ json: { kind: 'link', linkId: 'layout-fixture', expiresAt: new Date(Date.now() + 3600000).toISOString() } })); + await openUi(page, daemon); + await page.addStyleTag({ content: '*,*::before,*::after{animation:none!important;transition:none!important}' }); + if (!mobile && theme === 'light') { + const cdp = await context.newCDPSession(page); + const manifest = await cdp.send('Page.getAppManifest'); + assert.deepEqual(manifest.errors, [], 'the served manifest parses without errors'); + assert.equal(JSON.parse(manifest.data).name, 'LoopX'); + assert.deepEqual((await cdp.send('Page.getInstallabilityErrors')).installabilityErrors, []); + await cdp.detach(); + } + if (mobile) await page.getByRole('button', { name: '打开对话列表', exact: true }).click(); + await page.screenshot({ path: join(shots, `before-${mobile ? 'phone' : 'desktop'}-${theme}.png`) }); + await offer(page); + const promo = page.locator('.pwa-install-promo'); + await promo.waitFor(); + await page.locator('.sidebar-scroll').evaluate(el => { el.scrollTop = el.scrollHeight; }); + const [list, card] = await Promise.all([page.locator('.sidebar-scroll').boundingBox(), promo.boundingBox()]); + assert.ok(list.y + list.height <= card.y + 1, 'installation does not cover the populated list'); + assert.ok(card.x >= 0 && card.x + card.width <= (mobile ? 390 : 1440), 'card fits viewport'); + const notice = await page.locator('.link-login-notice').boundingBox(); + assert.ok(card.y + card.height <= notice.y + 1, 'installation does not cover the expiring-login notice'); + await page.screenshot({ path: join(shots, `after-${mobile ? 'phone' : 'desktop'}-${theme}.png`) }); + await promo.getByRole('button', { name: '以后再说' }).click(); + await promo.waitFor({ state: 'detached' }); + await page.locator('.sidebar').getByRole('button', { name: '配置', exact: true }).click(); + await page.locator('.settings-nav').getByRole('button', { name: '安装 LoopX', exact: true }).click(); + const settings = page.getByRole('region', { name: '安装 LoopX', exact: true }); + await settings.getByRole('button', { name: '安装', exact: true }).click(); + assert.equal(await page.evaluate(() => window.installCalls), 1); + assert.equal(await page.evaluate(() => window.installClickedWithActivation), true); + await settings.getByText('浏览器尚未提供快捷安装。', { exact: false }).waitFor(); + await page.reload(); await settings.waitFor(); await offer(page); + assert.equal(await promo.count(), 0, 'dismissal survives reload and renewed offers'); + await offer(page, 'dismissed', true); + await settings.getByRole('button', { name: '安装', exact: true }).click(); + await settings.getByRole('alert').waitFor(); + await page.screenshot({ path: join(shots, `recovery-${mobile ? 'phone' : 'desktop'}-${theme}.png`) }); + await offer(page, 'accepted'); + await settings.getByRole('button', { name: '安装', exact: true }).click(); + await settings.getByRole('status').filter({ hasText: '已接受安装' }).waitFor(); + await page.evaluate(() => window.dispatchEvent(new Event('appinstalled'))); + await settings.getByRole('status').filter({ hasText: '已安装' }).waitFor(); + assert.equal(await settings.getByRole('button', { name: '安装', exact: true }).count(), 0); + assert.deepEqual(errors, []); + } finally { await context.close(); } + } + } finally { await browser.close(); await daemon.stop(); } +}); diff --git a/apps/workbench/packages/e2e/test/quote-paste.spec.mjs b/apps/workbench/packages/e2e/test/quote-paste.spec.mjs new file mode 100644 index 0000000000..34accf2df5 --- /dev/null +++ b/apps/workbench/packages/e2e/test/quote-paste.spec.mjs @@ -0,0 +1,86 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdirSync } from 'node:fs'; +import { join } from 'node:path'; +import { startDaemon, openUi, launchBrowser, api } from '../harness.mjs'; + +// Native copy action, synthetic paste delivery, real daemon and fake model. No OS clipboard claim. +test('copied references paste as durable notes with scoped provenance on four layouts', { timeout: 180000 }, async () => { + const daemon = await startDaemon(); + const browser = await launchBrowser(); + const post = async (path, body) => { + const response = await api(daemon, path, { method: 'POST', body: JSON.stringify(body) }); + assert.ok(response.ok, await response.clone().text()); return response.json(); + }; + const idle = async id => { + for (let n = 0; n < 120; n++) { + if ((await (await api(daemon, `/api/threads/${id}`)).json()).status === 'idle') return; + await new Promise(resolve => setTimeout(resolve, 100)); + } + throw new Error('turn did not finish'); + }; + const paste = async (input, text) => input.evaluate((element, text) => { + const data = new DataTransfer(); data.setData('text/plain', text); + element.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true })); + }, text); + try { + for (const mobile of [false, true]) for (const theme of ['light', 'dark']) { + const source = await post('/api/threads', { agent: 'pi', cwd: daemon.workdir, title: 'Quote source' }); + const target = await post('/api/threads', { agent: 'pi', cwd: daemon.workdir, title: 'Quote target' }); + await post(`/api/threads/${source.id}/turns`, { text: 'A passage with **bold** and a second sentence.' }); await idle(source.id); + await post(`/api/threads/${target.id}/turns`, { text: 'target-ready' }); await idle(target.id); + const context = await browser.newContext({ viewport: mobile ? { width: 390, height: 844 } : { width: 1440, height: 1000 }, isMobile: mobile, hasTouch: mobile, colorScheme: theme }); + try { + const page = await context.newPage(), errors = []; + page.on('pageerror', error => errors.push(error.message)); + await openUi(page, daemon); + await page.evaluate(id => { location.hash = `#/thread/${id}`; }, source.id); + await page.locator('.main .thread .markdown').filter({ hasText: 'A passage with' }).waitFor(); + await page.getByRole('button', { name: '更多消息操作', exact: true }).last().click(); + await page.getByRole('menuitem', { name: '复制为引用', exact: true }).click(); + const copied = await page.evaluate(() => JSON.parse(localStorage.getItem('calli.copiedQuote'))); + assert.equal(copied.threadId, source.id); assert.equal(copied.host, null); + await page.getByRole('button', { name: '更多消息操作', exact: true }).last().click(); + await page.getByRole('menuitem', { name: '复制回答', exact: true }).click(); + await page.waitForFunction(() => localStorage.getItem('calli.copiedQuote') === null); + await page.getByRole('button', { name: '更多消息操作', exact: true }).last().click(); + await page.getByRole('menuitem', { name: '复制为引用', exact: true }).click(); + const text = copied.text.trim().split('\n').map(line => `> ${line}`.trimEnd()).join('\n'); + await page.evaluate(id => { location.hash = `#/thread/${id}`; }, target.id); + await page.getByText('hi there target-ready', { exact: true }).waitFor(); + const composer = page.locator('.composer'), input = composer.locator('textarea').last(); + await input.fill('My existing draft'); await paste(input, text); + await composer.locator('.note-strip').waitFor(); + assert.equal(await input.inputValue(), 'My existing draft'); + assert.equal(await composer.locator('.note-strip').count(), 1); + await page.waitForFunction(id => { const draft = JSON.parse(localStorage.getItem('calli.drafts') ?? '{}')[id]; return draft?.text === 'My existing draft' && draft.notes?.length === 1; }, target.id); + await page.reload(); + await page.locator('.sidebar-inner').waitFor({ state: 'attached' }); + await page.evaluate(id => { location.hash = `#/thread/${id}`; }, target.id); + await composer.locator('.note-strip').waitFor(); + assert.equal(await input.inputValue(), 'My existing draft'); + if (process.env.LOOCHAT_E2E_SHOTS_DIR) { + mkdirSync(process.env.LOOCHAT_E2E_SHOTS_DIR, { recursive: true }); + await page.screenshot({ path: join(process.env.LOOCHAT_E2E_SHOTS_DIR, `pasted-quote-${mobile ? 'phone' : 'desktop'}-${theme}.png`), animations: 'disabled' }); + } + const sentResponse = page.waitForResponse(response => response.request().method() === 'POST' && new URL(response.url()).pathname === `/api/threads/${target.id}/turns`); + await composer.locator('.send-btn:not(.stop)').click(); await sentResponse; await idle(target.id); + await composer.locator('.note-strip').waitFor({ state: 'detached' }); + const events = await (await api(daemon, `/api/threads/${target.id}/events`)).json(); + const sent = events.findLast(event => event.type === 'turn.started').data.text; + assert.ok(sent.includes(`来源:另一个会话,原文和上下文用 loochat history ${source.id} --turn ${copied.turnId} 读`)); + assert.match(sent, /My existing draft/); + assert.equal((await (await api(daemon, `/api/threads/${source.id}/events`)).json()).filter(e => e.type === 'turn.started').length, 1); + // The same ids on a different machine must not grant local provenance. + await page.evaluate(copied => localStorage.setItem('calli.copiedQuote', JSON.stringify({ ...copied, host: 'another-machine' })), copied); + await paste(input, text); await composer.locator('.note-strip').waitFor(); + await input.fill('Cross-machine quote'); + const crossResponse = page.waitForResponse(response => response.request().method() === 'POST' && new URL(response.url()).pathname === `/api/threads/${target.id}/turns`); + await composer.locator('.send-btn:not(.stop)').click(); await crossResponse; await idle(target.id); + const cross = (await (await api(daemon, `/api/threads/${target.id}/events`)).json()).findLast(e => e.type === 'turn.started').data.text; + assert.match(cross, /\[注释 1\]/); assert.ok(!cross.includes('loochat history')); + assert.deepEqual(errors, []); + } finally { await context.close(); } + } + } finally { await browser.close(); await daemon.stop(); } +}); diff --git a/apps/workbench/packages/e2e/test/quote.spec.mjs b/apps/workbench/packages/e2e/test/quote.spec.mjs index 3fd9665a97..9af84f01db 100644 --- a/apps/workbench/packages/e2e/test/quote.spec.mjs +++ b/apps/workbench/packages/e2e/test/quote.spec.mjs @@ -3,7 +3,7 @@ import { test, before, after } from 'node:test'; import assert from 'node:assert/strict'; import { writeFileSync } from 'node:fs'; import { join } from 'node:path'; -import { startDaemon, openUi, launchBrowser } from '../harness.mjs'; +import { startDaemon, openUi, launchBrowser, api } from '../harness.mjs'; let daemon; let browser; @@ -112,6 +112,18 @@ test('asking in the side chat opens a thread of its own', async () => { assert.equal(await page.locator('.side-chat-passage').innerText(), 'hi ther'); assert.equal(await page.locator('.sidebar .thread-row').count(), 1); + // The side chat starts on the source model but can choose its own before the first question. + await api(daemon, '/api/draft-model-preferences', { + method: 'PATCH', + body: JSON.stringify({ agent: 'pi', model: 'fake/think', effort: 'low' }), + }); + const sideModel = page.locator('.side-chat .model-control-trigger'); + await sideModel.filter({ hasText: 'Think' }).waitFor({ timeout: 10_000 }); + await sideModel.click(); + await page.locator('.model-control-panel .effort-model').click(); + await page.getByRole('menuitemradio', { name: /^Plain\b/ }).click(); + await page.keyboard.press('Escape'); + await page.locator('.side-chat textarea').click(); await page.keyboard.type('go on'); await page.keyboard.press('Enter'); @@ -133,6 +145,21 @@ test('asking in the side chat opens a thread of its own', async () => { assert.match(titles.join('\n'), /^追问:hi ther$/m); assert.equal(await page.locator('.sidebar .thread-fork').count(), 0); assert.match(await page.locator('.sidebar .thread-item').filter({ hasText: '追问:hi ther' }).getAttribute('title'), /分叉/); + const sideThread = (await (await api(daemon, '/api/threads')).json()).find(thread => thread.title === '追问:hi ther'); + assert.equal(sideThread.model, 'fake/plain'); + + // After the thread exists, changing the model applies to the same thread rather than a new one, + // and switching back to a model restores its remembered thinking effort. + const patched = page.waitForResponse(response => response.request().method() === 'PATCH' + && new URL(response.url()).pathname === `/api/threads/${sideThread.id}`); + await sideModel.click(); + await page.getByRole('menuitemradio', { name: /^Think\b/ }).click(); + const patchedThread = await (await patched).json(); + assert.equal(patchedThread.model, 'fake/think'); + assert.equal(patchedThread.effort, 'low'); + assert.equal((await (await api(daemon, '/api/threads')).json()).filter(thread => thread.title === '追问:hi ther').length, 1); + await page.locator('.side-chat-title').click(); + await page.locator('.model-control-panel').waitFor({ state: 'detached' }); // The conversation it came from is untouched underneath. assert.equal(await page.locator('.main .thread .markdown').first().innerText(), originalAnswer); @@ -164,3 +191,51 @@ test('a picture attached to the composer can be looked at full size before sendi await page.locator('.attachment-remove').click(); await page.locator('.attachment img').waitFor({ state: 'detached', timeout: 3_000 }); }); + +for (const mobile of [false, true]) for (const theme of ['light', 'dark']) test(`quoted follow-up preserves model choices: ${mobile ? 'phone' : 'desktop'} ${theme}`, { timeout: 45000 }, async () => { + const post = async (path, body, method = 'POST') => { + const response = await api(daemon, path, { method, body: JSON.stringify(body) }); + assert.ok(response.ok, await response.clone().text()); return response.json(); + }; + const source = await post('/api/threads', { agent: 'pi', cwd: daemon.workdir, model: 'fake/think', effort: 'high', title: `Source ${mobile} ${theme}` }); + await post(`/api/threads/${source.id}/turns`, { text: 'quote model choices' }); + for (let i = 0; i < 100; i++) { + if ((await (await api(daemon, `/api/threads/${source.id}`)).json()).status === 'idle') break; + await new Promise(resolve => setTimeout(resolve, 100)); + } + await post('/api/draft-model-preferences', { agent: 'pi', model: 'fake/think', effort: 'low' }, 'PATCH'); + const context = await browser.newContext({ viewport: mobile ? { width: 390, height: 844 } : { width: 1440, height: 1000 }, isMobile: mobile, hasTouch: mobile, colorScheme: theme }); + try { + const p = await context.newPage(); + const errors = []; p.on('pageerror', error => errors.push(error.message)); + await openUi(p, daemon); await p.evaluate(id => { location.hash = `#/thread/${id}`; }, source.id); + await p.locator('.main .thread .markdown').first().waitFor(); + await p.evaluate(() => { + const node = document.createTreeWalker(document.querySelector('.main .thread .markdown'), NodeFilter.SHOW_TEXT).nextNode(); + const range = document.createRange(); range.setStart(node, 0); range.setEnd(node, 7); + const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range); + }); + await p.locator('.selection-menu button', { hasText: '在侧边栏提问' }).click(); + const side = p.locator('.side-chat'), picker = side.locator('.model-control-trigger'); + await picker.waitFor(); await picker.click(); + await p.locator('.model-control-panel .effort-model').click(); + await p.getByRole('menuitemradio', { name: /^Plain\b/ }).click(); await p.keyboard.press('Escape'); + const fork = p.waitForResponse(response => response.request().method() === 'POST' && new URL(response.url()).pathname === `/api/threads/${source.id}/fork`); + await side.locator('textarea').fill('Follow up with this model'); await side.locator('.send-btn:not(.stop)').click(); + const child = await (await fork).json(); + await side.locator('.row.user .bubble').last().waitFor(); + assert.equal((await (await api(daemon, `/api/threads/${child.id}`)).json()).model, 'fake/plain'); + const update = p.waitForResponse(response => response.request().method() === 'PATCH' && new URL(response.url()).pathname === `/api/threads/${child.id}`); + await picker.click(); await p.getByRole('menuitemradio', { name: /^Think\b/ }).click(); + const changed = await (await update).json(); + assert.equal(changed.id, child.id); assert.equal(changed.model, 'fake/think'); assert.equal(changed.effort, 'low'); + const original = await (await api(daemon, `/api/threads/${source.id}`)).json(); + assert.equal(original.model, 'fake/think'); assert.equal(original.effort, 'high'); + await side.locator('.side-chat-title').click(); + if (process.env.LOOCHAT_E2E_SHOTS_DIR) { + const { mkdirSync } = await import('node:fs'); mkdirSync(process.env.LOOCHAT_E2E_SHOTS_DIR, { recursive: true }); + await p.screenshot({ path: join(process.env.LOOCHAT_E2E_SHOTS_DIR, `side-quote-${mobile ? 'phone' : 'desktop'}-${theme}.png`), animations: 'disabled' }); + } + assert.deepEqual(errors, []); + } finally { await context.close(); } +}); diff --git a/apps/workbench/packages/e2e/test/sending.spec.mjs b/apps/workbench/packages/e2e/test/sending.spec.mjs index 3c7704dc0e..f6e1f7ba09 100644 --- a/apps/workbench/packages/e2e/test/sending.spec.mjs +++ b/apps/workbench/packages/e2e/test/sending.spec.mjs @@ -107,7 +107,7 @@ test('reloaded before the daemon got the message: the words and notes are still test('a send that comes back is forgotten on the device at once', async () => { const { page } = await boxWithNoteAndPicture('plain send'); await page.locator('.composer .send-btn:not(.stop)').click(); - await page.locator('.row.user').nth(1).waitFor({ timeout: 10_000 }); + await page.locator('.row.user:not([data-optimistic])').nth(1).waitFor({ timeout: 10_000 }); // Not after the next pause in typing: a reload right now must find nothing. assert.deepEqual(await box(page), { notes: 0, pictures: 0, stored: 0 }); await page.close(); diff --git a/apps/workbench/packages/ext-autotitle/src/AutoTitleView.tsx b/apps/workbench/packages/ext-autotitle/src/AutoTitleView.tsx index 8251d5e386..d380d39a45 100644 --- a/apps/workbench/packages/ext-autotitle/src/AutoTitleView.tsx +++ b/apps/workbench/packages/ext-autotitle/src/AutoTitleView.tsx @@ -94,13 +94,18 @@ export function AutoTitleView({ host }: ExtensionViewProps) {

{t(locale, 'agent')}

: {t(locale, 'chooseAgent')} + picked ? : {t(locale, 'autoAgent')} }> - {close => agents.map(a => ( - { void save({ agent: a.id }); close(); }}> - - - ))} + {close => [ + { void save({ agent: null }); close(); }}> + {t(locale, 'autoAgent')} + , + ...agents.map(a => ( + { void save({ agent: a.id }); close(); }}> + + + )), + ]} {picked && ( {modelLabel}}> @@ -112,7 +117,7 @@ export function AutoTitleView({ host }: ExtensionViewProps) { )}
- {!picked &&

{t(locale, 'noAgent')}

} + {!picked &&

{t(locale, 'autoHint')}

} {picked?.permissionModes && !picked.permissionModes.includes('ask') && (

{t(locale, 'noAsk')}

)} diff --git a/apps/workbench/packages/ext-autotitle/src/i18n/en.ts b/apps/workbench/packages/ext-autotitle/src/i18n/en.ts index 13fd85ce4d..8c097b4363 100644 --- a/apps/workbench/packages/ext-autotitle/src/i18n/en.ts +++ b/apps/workbench/packages/ext-autotitle/src/i18n/en.ts @@ -3,8 +3,8 @@ import type { zh } from './zh'; export const en: typeof zh = { lead: 'After a new thread’s first turn, the agent you choose gives it a short title by the rules below. Titles you set yourself are left alone.', agent: 'Naming agent', - chooseAgent: 'Choose an agent', - noAgent: 'None yet. Naming starts once you choose one.', + autoAgent: 'Automatic', + autoHint: 'Each thread is named by its own agent on its cheapest model: Luna for Codex, Gemini 3.8 Flash Low for Antigravity, Haiku for Claude. A thread whose agent has no model of known price is not named.', noAsk: 'This agent has no ask-first mode; while naming it may run tools on its own', model: 'Model', defaultModel: 'Default model', diff --git a/apps/workbench/packages/ext-autotitle/src/i18n/ja.ts b/apps/workbench/packages/ext-autotitle/src/i18n/ja.ts index d1e6fde439..c2d976f686 100644 --- a/apps/workbench/packages/ext-autotitle/src/i18n/ja.ts +++ b/apps/workbench/packages/ext-autotitle/src/i18n/ja.ts @@ -3,8 +3,8 @@ import type { zh } from './zh'; export const ja: typeof zh = { lead: '新しいスレッドの最初のターンが終わると、選んだエージェントが下のルールで短いタイトルを付けます。自分で付けたタイトルはそのままです。', agent: 'タイトルを付けるエージェント', - chooseAgent: 'エージェントを選択', - noAgent: 'まだ選ばれていません。選ぶと付け始めます', + autoAgent: '自動', + autoHint: 'スレッド自身のエージェントの最も安いモデルで付けます。Codex は Luna、Antigravity は Gemini 3.8 Flash Low、Claude は Haiku です。価格の分かるモデルがないエージェントでは付けません', noAsk: 'このエージェントには「確認してから」モードがなく、命名中にツールを自分で使うことがあります', model: 'モデル', defaultModel: 'デフォルトのモデル', diff --git a/apps/workbench/packages/ext-autotitle/src/i18n/zh.ts b/apps/workbench/packages/ext-autotitle/src/i18n/zh.ts index 05359a1a25..ed05509cec 100644 --- a/apps/workbench/packages/ext-autotitle/src/i18n/zh.ts +++ b/apps/workbench/packages/ext-autotitle/src/i18n/zh.ts @@ -1,8 +1,8 @@ export const zh = { lead: '新对话第一轮结束后,让你选的 agent 按下面的规则起一个简短标题。你自己改过的标题不会被动。', agent: '取名的 agent', - chooseAgent: '选择 agent', - noAgent: '还没选,选好后才会开始取名', + autoAgent: '自动', + autoHint: '用对话自己的 agent 里最便宜的模型取名,比如 Codex 用 Luna、Antigravity 用 Gemini 3.8 Flash Low、Claude 用 Haiku;agent 的模型都没有已知价格时不取名', noAsk: '这个 agent 没有「先问再做」模式,取名时可能自行调用工具', model: '模型', defaultModel: '默认模型', diff --git a/apps/workbench/packages/ext-board/package.json b/apps/workbench/packages/ext-board/package.json index 9ab30ce2d9..677caf97ff 100644 --- a/apps/workbench/packages/ext-board/package.json +++ b/apps/workbench/packages/ext-board/package.json @@ -5,6 +5,7 @@ "type": "module", "exports": { ".": "./src/index.ts", + "./filters": "./src/columns.ts", "./manifest.json": "./manifest.json" }, "scripts": { diff --git a/apps/workbench/packages/ext-board/src/BoardView.tsx b/apps/workbench/packages/ext-board/src/BoardView.tsx index e521babdbf..fdd377e428 100644 --- a/apps/workbench/packages/ext-board/src/BoardView.tsx +++ b/apps/workbench/packages/ext-board/src/BoardView.tsx @@ -1,15 +1,15 @@ import { useEffect, useId, useMemo, useRef, useState, type DragEvent, type KeyboardEvent, type MouseEvent, type PointerEvent } from 'react'; import type { WorkProjection } from '@calli/extension-api'; import type { ExtensionViewProps, WebHost } from '@calli/extension-api/web'; -import { BACKLOG_OPEN_KEY, parseBacklogOpen, buildColumns, COLUMN_IDS, FILTERS_VERSION, GONE_PROJECT, machineOptions, markAllDone, emptyFilters, firstColumn, newThreadOptions, parseFilters, projectKey, projectLabels, projectOptions, showStaleWarning, staleMachines, cardFor, type BoardCard, type BoardFilters, type ColumnId } from './columns'; +import { BACKLOG_OPEN_KEY, parseBacklogOpen, buildColumns, COLUMN_IDS, FILTERS_VERSION, FILTERS_KEY, GONE_PROJECT, machineOptions, markAllDone, emptyFilters, firstColumn, newThreadOptions, parseFilters, projectKey, projectLabels, projectOptions, showStaleWarning, staleMachines, cardFor, type BoardCard, type BoardFilters, type ColumnId } from './columns'; import { buildSummary } from './assist'; import { applyDrop, createLongPress, dropAction, withGuesses, type DropAction, type Guess } from './drag'; import { machineName, reasonOf } from './reason'; import { parsePins, PINS_KEY, pillFilter, pillSelected, pinCount, togglePin } from './pins'; import { t } from './i18n'; +import { goalLabel, goalStatus } from './goal'; import { collectTags, parseTitleTags } from './tags'; -const FILTERS_KEY = 'filters.v1'; function readFilters(host: WebHost): BoardFilters { try { @@ -53,6 +53,8 @@ function ThreadCard({ card, host, now, work, tagLabels, projects, drag }: { card const parsed = parseTitleTags(thread.title); const title = parsed.title || t(locale, 'untitled'); const tags = parsed.tags.map(tag => tagLabels.get(tag.toLowerCase()) ?? tag); + const goal = goalLabel(thread.goal, locale); + const goalState = thread.goal ? goalStatus(thread.goal.status, locale) : null; const note = card.reason.kind === 'report' ? thread.report?.note.trim() : ''; const project = projectKey(thread); const projectLabel = projects.label(project); @@ -98,7 +100,8 @@ function ThreadCard({ card, host, now, work, tagLabels, projects, drag }: { card - {tags.length > 0 && + {(goal || tags.length > 0) && + {goal && {thread.goal!.title || thread.goal!.goalId}{goalState && · {goalState}}} {tags.slice(0, 2).map(tag => {tag})} {tags.length > 2 && {t(locale, 'moreTags', tags.length - 2)}} } @@ -275,7 +278,7 @@ export function BoardView({ host }: ExtensionViewProps) { const current = selectedColumn ?? firstColumn(columns); const empty = columns.every((column) => column.total === 0); const showMachines = machines.length > 1 || threads.some((thread) => thread.machine); - const hasFilters = filters.tags.length + filters.project.length + filters.agent.length + filters.scheduled.length + (showMachines ? filters.machine.length : 0) > 0; + const hasFilters = filters.goalOnly || filters.tags.length + filters.project.length + filters.agent.length + filters.scheduled.length + (showMachines ? filters.machine.length : 0) > 0; const tags = collectTags(threads); const tagLabels = new Map(tags.map(tag => [tag.key, tag.label])); const tagCounts = new Map(tags.map(tag => [tag.key, tag.count])); @@ -367,6 +370,7 @@ export function BoardView({ host }: ExtensionViewProps) { {filter('project', t(locale, 'project'), filters.project, projectChoices.map((option) => option.key), projects.label, (project) => updateFilters({ ...filters, project }), (key) => projectCounts.get(key) ?? 0)} {showMachines && filter('machine', t(locale, 'machine'), filters.machine, machineChoices.map((option) => option.key), (key) => machineInfo.get(key)?.label || t(locale, 'localMachine'), (machine) => updateFilters({ ...filters, machine }), (key) => machineInfo.get(key)?.count ?? t(locale, 'countUnknown'))} {filter('agent', t(locale, 'agent'), filters.agent, agents, (agent) => agentLabels.get(agent) ?? agent, (agent) => updateFilters({ ...filters, agent }))} + {filter('scheduled', t(locale, 'scheduledFilter'), filters.scheduled, [true, false], (scheduled) => t(locale, scheduled ? 'scheduled' : 'notScheduled'), (scheduled) => updateFilters({ ...filters, scheduled }))} {hasFilters && } } diff --git a/apps/workbench/packages/ext-board/src/board.css b/apps/workbench/packages/ext-board/src/board.css index 168ccdb354..2fb1cf40a6 100644 --- a/apps/workbench/packages/ext-board/src/board.css +++ b/apps/workbench/packages/ext-board/src/board.css @@ -230,3 +230,10 @@ .ext-board-narrow .ext-board-action > span { display: none; } .ext-board-action.is-busy svg { animation: ext-board-breathe 1.2s ease-in-out infinite; } @media (prefers-reduced-motion: reduce) { .ext-board-action.is-busy svg { animation: none; } } + +/* The Goal shares the tag row; its full name remains available on hover. */ +.ext-board-goal { display: flex; flex: 1; max-width: 100%; } +.ext-board-goal-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.ext-board-goal-status { flex-shrink: 0; } +.ext-board-filters { max-width: 100%; overflow-x: auto; scrollbar-width: none; } +.ext-board-filters::-webkit-scrollbar { display: none; } diff --git a/apps/workbench/packages/ext-board/src/columns.ts b/apps/workbench/packages/ext-board/src/columns.ts index 62c7699c55..ec1e6f5245 100644 --- a/apps/workbench/packages/ext-board/src/columns.ts +++ b/apps/workbench/packages/ext-board/src/columns.ts @@ -26,9 +26,11 @@ export function parseBacklogOpen(value: string | null): boolean { } /** Bumped when a saved filter's meaning changes. */ -export const FILTERS_VERSION = 3; +export const FILTERS_VERSION = 4; +export const FILTERS_KEY = 'filters.v1'; export interface BoardFilters { + goalOnly: boolean; tags: string[]; project: string[]; agent: string[]; @@ -61,7 +63,7 @@ export interface BoardColumn { } export function emptyFilters(): BoardFilters { - return { tags: [], project: [], agent: [], scheduled: [], machine: [] }; + return { goalOnly: false, tags: [], project: [], agent: [], scheduled: [], machine: [] }; } function timestamp(iso: string | null | undefined): number { @@ -183,7 +185,8 @@ export function newThreadOptions(filters: BoardFilters): { project?: string; mac } export function matchesFilters(thread: ThreadSummary, filters: BoardFilters): boolean { - return (filters.tags.length === 0 || parseTitleTags(thread.title).tags.some(tag => filters.tags.some(value => value.toLowerCase() === tag.toLowerCase()))) + return (!filters.goalOnly || Boolean(thread.goal?.goalId)) + && (filters.tags.length === 0 || parseTitleTags(thread.title).tags.some(tag => filters.tags.some(value => value.toLowerCase() === tag.toLowerCase()))) && (filters.project.length === 0 || filters.project.includes(projectKey(thread))) && (filters.agent.length === 0 || filters.agent.includes(thread.agent)) && (filters.scheduled.length === 0 || filters.scheduled.includes(thread.scheduled)) @@ -257,6 +260,7 @@ export function parseFilters(value: string | null): BoardFilters { const strings = (input: unknown) => Array.isArray(input) ? [...new Set(input.filter((item): item is string => typeof item === 'string'))] : []; return { + goalOnly: object.goalOnly === true, tags: [...new Set(strings(object.tags).map(tag => tag.trim()).filter(validTag).map(tag => tag.toLowerCase()))], // Before version 2 projects were kept as the path was typed, not resolved; they match nothing now. project: typeof object.v === 'number' && object.v >= 2 ? strings(object.project) : [], diff --git a/apps/workbench/packages/ext-board/src/goal.ts b/apps/workbench/packages/ext-board/src/goal.ts new file mode 100644 index 0000000000..d8e655cb25 --- /dev/null +++ b/apps/workbench/packages/ext-board/src/goal.ts @@ -0,0 +1,22 @@ +import type { ThreadSummary } from '@calli/extension-api'; +import type { Locale } from '@calli/extension-api/web'; +import { t } from './i18n'; + +/** Goal state is stored work state, never evidence of a running agent. */ +export function goalStatus(status: string | null, locale: Locale): string | null { + return status === 'stopped' || status === 'paused' ? t(locale, 'goalPaused') + : status === 'active_state_user_gate' || status === 'active_state_user_todo' ? t(locale, 'waiting') + : status === 'connected_without_run' ? t(locale, 'goalReady') + : status === 'active_state_agent_todo' ? t(locale, 'goalWork') + : status === 'state_refreshed' ? t(locale, 'goalRefreshed') + : status === 'state_incomplete' || status === 'state_projection_gap' ? t(locale, 'goalIncomplete') + : status === 'run_artifact_missing' ? t(locale, 'goalMissingResult') + : status === 'unknown' ? t(locale, 'goalUnknown') + : status?.replace(/_/g, ' ') || null; +} + +export function goalLabel(goal: ThreadSummary['goal'], locale: Locale): string | null { + if (!goal?.goalId) return null; + const word = goalStatus(goal.status, locale); + return `${goal.title || goal.goalId}${word ? ` · ${word}` : ''}`; +} diff --git a/apps/workbench/packages/ext-board/src/i18n/en.ts b/apps/workbench/packages/ext-board/src/i18n/en.ts index 5cf4682782..440cfd275c 100644 --- a/apps/workbench/packages/ext-board/src/i18n/en.ts +++ b/apps/workbench/packages/ext-board/src/i18n/en.ts @@ -3,6 +3,14 @@ import type { zh } from './zh'; const threads = (count: number) => `${count} ${count === 1 ? 'thread' : 'threads'}`; export const en: typeof zh = { + goalOnly: 'Long-horizon goals only', + goalPaused: 'Paused', + goalReady: 'Linked', + goalWork: 'Work pending', + goalUnknown: 'Unknown', + goalRefreshed: 'Refreshed', + goalIncomplete: 'Incomplete state', + goalMissingResult: 'Result missing', title: 'Board', backlog: 'Later', doing: 'In progress', diff --git a/apps/workbench/packages/ext-board/src/i18n/ja.ts b/apps/workbench/packages/ext-board/src/i18n/ja.ts index 93cf6b5300..269b4d2dbf 100644 --- a/apps/workbench/packages/ext-board/src/i18n/ja.ts +++ b/apps/workbench/packages/ext-board/src/i18n/ja.ts @@ -1,6 +1,14 @@ import type { zh } from './zh'; export const ja: typeof zh = { + goalOnly: '長期目標のみ', + goalPaused: '一時停止', + goalReady: '紐付け済み', + goalWork: 'タスクあり', + goalUnknown: '状態不明', + goalRefreshed: '更新済み', + goalIncomplete: '状態に欠落', + goalMissingResult: '成果物なし', title: 'ボード', backlog: '後で', doing: '進行中', diff --git a/apps/workbench/packages/ext-board/src/i18n/zh.ts b/apps/workbench/packages/ext-board/src/i18n/zh.ts index a0dd9b9599..9d16b0e6f8 100644 --- a/apps/workbench/packages/ext-board/src/i18n/zh.ts +++ b/apps/workbench/packages/ext-board/src/i18n/zh.ts @@ -1,4 +1,12 @@ export const zh = { + goalOnly: '仅长程目标', + goalPaused: '暂停', + goalReady: '已关联', + goalWork: '有待办', + goalUnknown: '状态未知', + goalRefreshed: '已刷新', + goalIncomplete: '状态缺口', + goalMissingResult: '产物缺失', title: '看板', backlog: '以后再做', doing: '进行中', diff --git a/apps/workbench/packages/ext-board/test/columns.test.ts b/apps/workbench/packages/ext-board/test/columns.test.ts index 1107638d4d..968b4a4d8a 100644 --- a/apps/workbench/packages/ext-board/test/columns.test.ts +++ b/apps/workbench/packages/ext-board/test/columns.test.ts @@ -92,7 +92,7 @@ test('combines project, instance and schedule filters and leaves archived thread thread('archived', { archived: true }), ]; const ids = (filters: Parameters[1]) => buildColumns(items, filters, now)[3].cards.map((card) => card.thread.id).sort(); - assert.deepEqual(ids({ tags: [], project: ['/projects/one', '/projects/two'], agent: ['agent-1', 'agent-2'], scheduled: [true], machine: [] }), ['match-one', 'match-two']); + assert.deepEqual(ids({ ...emptyFilters(), tags: [], project: ['/projects/one', '/projects/two'], agent: ['agent-1', 'agent-2'], scheduled: [true], machine: [] }), ['match-one', 'match-two']); assert.deepEqual(ids({ ...emptyFilters(), scheduled: [false] }), ['not-scheduled']); assert.equal(buildColumns(items, emptyFilters(), now)[3].total, 4); }); @@ -131,10 +131,10 @@ test('phones open on the first column that asks something of the person', () => test('invalid persisted filters fall back safely and mixed values are sanitized', () => { for (const input of [null, '', '{bad', 'null', '42']) assert.deepEqual(parseFilters(input), emptyFilters()); assert.deepEqual(parseFilters('{"v":2,"project":["/a",1,"/a"],"agent":false,"scheduled":[true,"false",false,true]}'), { - tags: [], project: ['/a'], agent: [], scheduled: [true, false], machine: [], + ...emptyFilters(), tags: [], project: ['/a'], agent: [], scheduled: [true, false], machine: [], }); // Projects saved before they were resolved paths are dropped once; the other filters stay. - assert.deepEqual(parseFilters('{"project":["/home/me/code"],"agent":["codex"]}'), { tags: [], project: [], agent: ['codex'], scheduled: [], machine: [] }); + assert.deepEqual(parseFilters('{"project":["/home/me/code"],"agent":["codex"]}'), { ...emptyFilters(), tags: [], project: [], agent: ['codex'], scheduled: [], machine: [] }); }); test('project labels use the final directory segment', () => { diff --git a/apps/workbench/packages/ext-board/test/goal.test.ts b/apps/workbench/packages/ext-board/test/goal.test.ts new file mode 100644 index 0000000000..27ebbcf368 --- /dev/null +++ b/apps/workbench/packages/ext-board/test/goal.test.ts @@ -0,0 +1,33 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import type { ThreadSummary } from '@calli/extension-api'; +import { emptyFilters, matchesFilters, parseFilters, FILTERS_VERSION } from '../src/columns'; +import { goalLabel } from '../src/goal'; + +const thread = (goal?: ThreadSummary['goal']): ThreadSummary => ({ id: 'conversation', title: '[work] Proposal', agent: 'agent', project: '/workspace', scheduled: false, goal } as ThreadSummary); + +test('Goal tags show the title and honest stored state, with no tag for ordinary conversations', () => { + assert.equal(goalLabel(undefined, 'zh'), null); + assert.equal(goalLabel({ goalId: 'g', title: 'Proposal', status: null }, 'en'), 'Proposal'); + assert.equal(goalLabel({ goalId: 'g', title: 'Proposal', status: 'active_state_user_gate' }, 'zh'), 'Proposal · 等你'); + assert.equal(goalLabel({ goalId: 'g', title: 'Proposal', status: 'stopped' }, 'ja'), 'Proposal · 一時停止'); + assert.equal(goalLabel({ goalId: 'g', title: 'Proposal', status: 'connected_without_run' }, 'en'), 'Proposal · Linked'); +}); + +test('long-horizon filtering composes with existing filters and preserves ordinary default behavior', () => { + const plain = thread(), bound = thread({ goalId: 'g', title: 'Proposal', status: null }); + assert.equal(matchesFilters(plain, emptyFilters()), true); + assert.equal(matchesFilters(bound, emptyFilters()), true); + const filters = { ...emptyFilters(), goalOnly: true }; + assert.equal(matchesFilters(plain, filters), false); + assert.equal(matchesFilters(bound, filters), true); + assert.equal(matchesFilters(bound, { ...filters, project: ['/other'] }), false); + assert.equal(matchesFilters(bound, { ...filters, tags: ['work'], agent: ['agent'], scheduled: [false] }), true); +}); + +test('Goal filter shares persistence and accepts only an explicit boolean', () => { + const filters = { ...emptyFilters(), goalOnly: true, agent: ['agent'] }; + assert.deepEqual(parseFilters(JSON.stringify({ ...filters, v: FILTERS_VERSION })), filters); + assert.deepEqual(parseFilters('{"v":3,"agent":["agent"]}'), { ...emptyFilters(), agent: ['agent'] }); + for (const value of ['"true"', '1', '{}', 'null']) assert.equal(parseFilters(`{"goalOnly":${value}}`).goalOnly, false); +}); diff --git a/apps/workbench/packages/extension-api/summary.d.ts b/apps/workbench/packages/extension-api/summary.d.ts index c690bf4691..bc10e28434 100644 --- a/apps/workbench/packages/extension-api/summary.d.ts +++ b/apps/workbench/packages/extension-api/summary.d.ts @@ -47,6 +47,8 @@ export interface ThreadSummary { title: string; /** Agent instance id, e.g. `codex` or `claude-2`. Use capabilities, never branch on it. */ agent: string; + /** The bound long-horizon Goal, read by the built-in host. No workspace or authority state. */ + goal?: { goalId: string; title: string; status: string | null }; /** * Project directory with symlinks resolved, so two spellings of one directory are one project * (worktrees resolve to the directory they were made from). `''` for a thread in no project. diff --git a/apps/workbench/packages/web/package.json b/apps/workbench/packages/web/package.json index 7871f8776c..20acee00fa 100644 --- a/apps/workbench/packages/web/package.json +++ b/apps/workbench/packages/web/package.json @@ -12,12 +12,12 @@ "test:extensions:e2e": "node --test e2e/extensions.spec.mjs" }, "dependencies": { - "@novnc/novnc": "^1.7.0", "@calli/ext-autotitle": "*", "@calli/ext-board": "*", "@calli/ext-memory": "*", "@calli/ext-voice": "*", "@calli/extension-api": "*", + "@novnc/novnc": "^1.7.0", "@xterm/addon-fit": "^0.11.0", "@xterm/addon-web-links": "^0.12.0", "@xterm/xterm": "^6.0.0", @@ -26,16 +26,18 @@ "react": "^18.3.1", "react-dom": "^18.3.1", "react-markdown": "^9.0.1", + "rehype-raw": "^7.0.0", + "rehype-sanitize": "^6.0.0", "remark-gfm": "^4.0.0" }, "devDependencies": { "@types/react": "^18.3.12", "@types/react-dom": "^18.3.1", + "@types/react-test-renderer": "^18.3.1", "@vitejs/plugin-react": "^4.3.4", + "react-test-renderer": "18.3.1", "tsx": "^4.19.0", "typescript": "^5.6.0", - "vite": "^5.4.11", - "react-test-renderer": "18.3.1", - "@types/react-test-renderer": "^18.3.1" + "vite": "^5.4.11" } } diff --git a/apps/workbench/packages/web/public/manifest.webmanifest b/apps/workbench/packages/web/public/manifest.webmanifest index bebbeee3ae..c1c3c5c703 100644 --- a/apps/workbench/packages/web/public/manifest.webmanifest +++ b/apps/workbench/packages/web/public/manifest.webmanifest @@ -11,6 +11,18 @@ "background_color": "#f8f6f1", "theme_color": "#f8f6f1", "icons": [ + { + "src": "/pwa/icon-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "any" + }, + { + "src": "/pwa/icon-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "any" + }, { "src": "/loochat-icon.png?v=crab-1", "sizes": "1024x1024", diff --git a/apps/workbench/packages/web/public/pwa/icon-192.png b/apps/workbench/packages/web/public/pwa/icon-192.png new file mode 100644 index 0000000000..ed9957d940 Binary files /dev/null and b/apps/workbench/packages/web/public/pwa/icon-192.png differ diff --git a/apps/workbench/packages/web/public/pwa/icon-512.png b/apps/workbench/packages/web/public/pwa/icon-512.png new file mode 100644 index 0000000000..26cc2db73c Binary files /dev/null and b/apps/workbench/packages/web/public/pwa/icon-512.png differ diff --git a/apps/workbench/packages/web/src/App.tsx b/apps/workbench/packages/web/src/App.tsx index 7397d0dcb4..b8546e23d9 100644 --- a/apps/workbench/packages/web/src/App.tsx +++ b/apps/workbench/packages/web/src/App.tsx @@ -1,3 +1,5 @@ +import { AgentLoginRecovery, needsAgentLogin } from './components/AgentLoginRecovery'; +import { createPortal } from 'react-dom'; import { GitPanel } from './components/GitPanel'; import { SettingsPage, type SettingsGroup } from './components/SettingsPage'; import { AssistantSettingsPage, assistantTitle } from './components/AssistantSettingsPage'; @@ -12,7 +14,10 @@ import { GeneralSettingsDialog } from './components/GeneralSettingsDialog'; import { AutoHandoverNotice, HandoverSettingsDialog } from './components/AutoHandover'; import { useWorkSources, WorkSummary } from './extensions/work'; import { HostIcon } from './extensions/ui'; -import { historyPage, mergeHistory, mergeHistoryPage, prependHistory, refreshHistoryPage, watchHistory } from './history'; +import { historyPage, mergeHistory, mergeHistoryPage, peekCachedPage, prependHistory, refreshHistoryPage, watchHistory } from './history'; +import { isOptimisticThreadId, mergeOptimisticEvents, mergeServerThreads, runOptimisticMainSend, useOptimisticTurns, type PendingThreadCreation } from './optimistic'; +import { cachedRouterThreadId, rememberRouterThreadId } from './history-cache'; +import { useReadingPosition } from './use-reading-position'; import type { WorkMode, WritingStage } from './api'; import { forkBlocked, useThreadActions } from './components/ThreadActions';import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent, type ComponentProps, type ReactNode } from 'react'; import type { Theme } from './appearance'; @@ -53,9 +58,9 @@ import { newerBuildAvailable } from './version'; import { AppearancePanel } from './components/AppearancePanel'; import { ActionSheet, type SheetTarget } from './components/ActionSheet'; import { ArchivePanel } from './components/ArchivePanel'; -import { Composer, prefillComposerDraft, type DraftNote } from './components/Composer'; +import { Composer, prefillComposerDraft, replaceAutomaticComposerReference, useDraftKeys, type DraftNote } from './components/Composer'; import { HandToAssistant, type MessageSnapshot } from './components/MessageActions'; -import type { ContextReference } from './context-references'; +import { pendingThreadReference, type ContextReference } from './context-references'; import { CollaborationMenu } from './components/CollaborationMenu'; import { DirectoryPicker } from './components/DirectoryPicker'; import { Dialog } from './components/Dialog'; @@ -66,6 +71,9 @@ import { TerminalPanel } from './components/TerminalPanel'; import { DesktopPanel } from './components/DesktopPanel'; import { FilesPanel, type FilesTarget } from './components/FilesPanel'; import { PreviewPanel } from './components/PreviewPanel'; +import { DockPanel } from './components/DockPanel'; +import { PictureDock } from './components/PictureDock'; +import { handoverGroups } from './sidebar'; import { fileRef } from './files'; import { AddAgentDialog } from './components/AddAgentDialog'; import { OnboardingDialog } from './components/OnboardingDialog'; @@ -76,6 +84,8 @@ import { QuotaNavigation, quotaPushed } from './quota-reading'; import { noteSource, SelectionMenu } from './components/SelectionMenu'; import { AgentPanel } from './components/AgentPanel'; import { memberProgress, ThreadOverview, type OverviewSection } from './components/ThreadOverview'; +import { goalConversation, goalDestination, goalOverviewHash, goalOverviewRequest, goalsBoardTarget, type GoalSection } from './loopx/goal-navigation'; +import { extensionStorage } from './extensions/host'; import { prepareOverview } from './overview-reading'; import { ChangeDiffDialog } from './components/ChangeDiffDialog'; import { AgentsPage } from './components/AgentsPage'; @@ -91,12 +101,13 @@ import { needsExplore, exploreSummary } from './personal-explore'; import { PersonalSettingsDialog } from './components/PersonalSettingsDialog'; import { SkillsPage } from './components/SkillsPage'; import { SchedulesPage } from './components/SchedulesPage'; -import { GoalWorkPage, GOAL_TABS, type GoalTab } from './components/GoalWorkPage'; -import { GoalsPage, type GoalsFilter } from './components/GoalsPage'; +import { ConversationSkeleton } from './components/ConversationSkeleton'; import { AccessSettings } from './components/AccessSettings'; +import { PwaInstallPromotion, PwaInstallSettings } from './components/PwaInstall'; import { LinkLoginNotice, useAuthKind } from './components/LinkLoginNotice'; -import { StewardActions, StewardPage } from './components/StewardPage'; -import { SidebarGoals, useLoopxStatus } from './components/SidebarGoals'; +import { StewardPage } from './components/StewardPage'; +import { StewardOverview } from './components/StewardOverview'; +import { useLoopxStatus } from './loopx/use-status'; import { needsYouGoalIds, sortGoalTree } from './loopx/status'; import { ActivityPage } from './components/ActivityPage'; import { LoopxGoalGroup } from './components/LoopxGoalGroup'; @@ -117,23 +128,23 @@ import { machineSummaries, threadMachine, parseThreadLink } from './extensions/p import { createThreadFeed } from './extensions/thread-feed'; import { cachedAgentMarks, cachedThreads, rememberAgentMarks, rememberThreads } from './thread-cache'; import { cachedAgents, cachedDraft, cachedModels, rememberAgents, rememberDraft, rememberModels } from './host-cache'; -import { clampSidebarWidth, defaultSidebarWidth, projectDir, savedSidebarWidth, SIDEBAR_MAX_WIDTH, SIDEBAR_MIN_WIDTH, type HostSource } from './sidebar'; +import { clampSidebarWidth, defaultSidebarWidth, forkGroupsByRoot, ownRows, projectDir, savedSidebarWidth, SIDEBAR_MAX_WIDTH, SIDEBAR_MIN_WIDTH, type HostSource } from './sidebar'; import { enabledViews, extensionHash, looksLikeExtensionRoute, resolveExtensionRoute } from './extensions/routes'; -import { AgentPicker, type DiscoveredAccount, type DiscoveredAgent, effortsForModel, imagesBlocked, imagesNote, modelName, speedsForModel, ModelPicker, PermissionPicker, UsageMeter, WorkspacePicker } from './components/Pickers'; +import { AgentPicker, type DiscoveredAccount, type DiscoveredAgent, effortsForModel, imagesBlocked, imagesNote, modelName, resolveModel, speedsForModel, ModelPicker, PermissionPicker, UsageMeter, WorkspacePicker } from './components/Pickers'; import { Sidebar, SIDEBAR_SHORTCUT } from './components/Sidebar'; import { MergedHistory } from './components/MergedHistory'; import { currentPlan, PlanButton } from './components/PlanPanel'; import { HandoverComposer } from './components/HandoverComposer'; import { WritingBar } from './components/WritingBar'; -import { handoverHistoryKey, laterSegment, latestHandoverThread } from './handover'; +import { handoverHistoryKey, laterSegment, latestHandoverThread, overviewHistoryBoundary } from './handover'; import { TurnRuler } from './components/TurnRuler'; import { NewProjectDialog, ProjectPicker, RootsDialog } from './components/Projects'; import { NoteMarks, type NoteMark } from './components/NoteMarks'; import { ConnectDialog, DemoBar } from './components/ConnectDialog'; import { DemoApi, DemoError } from './demo/DemoApi'; import { EMPTY_MODEL_PREFERENCE, type DraftModelPreference } from '../../daemon/src/model-preferences'; -import { QUICK_SWITCH_HIDDEN_KEY, clampQuickSwitchBottom, savedQuickSwitchBottom, saveQuickSwitchBottom } from './quick-switch'; -import { IconCheck, IconBell, AgentMark, IconActivity, IconAgents, IconArchive, IconArrowLeft, IconArrowDown, IconBack, IconClose, IconEdit, IconFolder, IconGauge, IconGlobe, IconList, IconMenu, IconSettings, IconMore, IconOverview, IconPalette, IconPlus, IconPuzzle, IconServer, IconShield, IconSidebar, IconSignIn, IconSignOut, IconSparkle, IconTerminal, IconTrace, IconLanguage, IconWaveform, IconSideChat } from './components/icons'; +import { ThreadQuickSwitch } from './components/ThreadQuickSwitch'; +import { IconDownload, IconCheck, IconBell, AgentMark, IconActivity, IconAgents, IconArchive, IconArrowDown, IconBack, IconClose, IconEdit, IconFolder, IconGauge, IconGlobe, IconList, IconMenu, IconSettings, IconMore, IconOverview, IconPalette, IconPlus, IconPuzzle, IconServer, IconShield, IconSidebar, IconSignIn, IconSignOut, IconSparkle, IconTerminal, IconTrace, IconLanguage, IconWaveform, IconSideChat } from './components/icons'; import { StatReadings } from './components/SessionStats'; import { ThreadTracePanel } from './components/TracePanel'; import { chooseLocale, locale, LOCALES, localeChoice, t } from './i18n'; @@ -192,34 +203,20 @@ const EXTENSIONS_HASH = '#/extensions'; /** The hub's own pages. Any other `#/…` may be an extension's view; see extensions/routes.ts. */ const CORE_ROUTES = ['#/settings', AGENTS_HASH, TEAMS_HASH, STEWARD_HASH, '#/goals', SKILLS_HASH, MCP_HASH, SCHEDULES_HASH, ACTIVITY_HASH, OBSERVABILITY_HASH, MACHINES_HASH, EXTENSIONS_HASH]; -type MainView = 'settings' | 'agents' | 'teams' | 'thread' | 'goal' | 'goals' | 'steward' | 'schedules' | 'activity' | 'observability' | 'machines' | 'skills' | 'mcp' | 'extensions' | 'ext'; +type MainView = 'settings' | 'agents' | 'teams' | 'thread' | 'steward' | 'schedules' | 'activity' | 'observability' | 'machines' | 'skills' | 'mcp' | 'extensions' | 'ext'; function quotaAccount(path: string): string | undefined { if (!path.startsWith('quota/')) return undefined; try { return decodeURIComponent(path.slice('quota/'.length)); } catch { return path.slice('quota/'.length); } } -/** The Goal id a `#/goals/` address names. */ -function goalIdForHash(hash: string): string | null { - const id = hash.startsWith('#/goals/') ? decodeURIComponent(hash.slice('#/goals/'.length).split('/')[0]) : ''; - return id ? id : null; -} - -/** The tab a `#/goals//` address names; the overview when it names none. */ -function goalTabForHash(hash: string): GoalTab { - const tab = hash.startsWith('#/goals/') ? hash.slice('#/goals/'.length).split('/')[1] : ''; - return GOAL_TABS.find(known => known === tab) ?? 'overview'; -} - /** The page an address opens; null for none (a thread). Skills and MCP are the hub's own machinery, which the demo has none of. */ function viewForHash(hash: string, connected: boolean): MainView | null { if (hash.startsWith('#/schedules/')) return 'schedules'; if (hash.startsWith('#/machines/')) return 'machines'; if (hash === '#/settings' || hash.startsWith('#/settings/')) return 'settings'; if (hash.startsWith('#/thread/')) return null; - // The whole list, before any one Goal's own page. - if (hash === '#/goals') return 'goals'; - if (hash.startsWith('#/goals/')) return 'goal'; + if (goalOverviewRequest(hash)) return 'steward'; // The assistant desk and its matters list are gone; their addresses open the steward, their successor. if (hash === DESK_HASH || hash.startsWith(`${DESK_HASH}/`) || hash === TODOS_HASH) return 'steward'; switch (hash) { @@ -268,132 +265,6 @@ const MEMBER_DEFAULTS_KEY = 'calli.coord.defaults'; /** A plan the user chose to leave be, by thread: the proposal's key, so a reload does not ask again. */ const PLAN_SKIP_KEY = 'calli:plan-skipped'; -const QUICK_SWITCH_SIDE = 10; -function ThreadQuickSwitch({ threads, selectedId, agents, onSelect }: { - threads: Thread[]; - selectedId: string; - agents: AgentInfo[]; - onSelect: (id: string) => void; -}) { - const selectedIndex = threads.findIndex((thread) => thread.id === selectedId); - const items = useMemo(() => selectedIndex < 0 ? [] : threads.slice(Math.max(0, selectedIndex - QUICK_SWITCH_SIDE), Math.min(threads.length, selectedIndex + QUICK_SWITCH_SIDE + 1)), [threads, selectedIndex]); - const root = useRef(null); - const current = useRef(null); - const start = useRef<{ pointerId: number; x: number; y: number; bottom: number; moved: boolean } | null>(null); - const [open, setOpen] = useState(false); - const [hidden, setHidden] = useStoredFlag(QUICK_SWITCH_HIDDEN_KEY); - const [bottom, setBottom] = useState(savedQuickSwitchBottom); - const agentById = useMemo(() => new Map(agents.map((agent) => [agent.id, agent])), [agents]); - // The panel is short: it opens on the current session, with its neighbours above and below. - useLayoutEffect(() => { if (open) current.current?.scrollIntoView({ block: 'center' }); }, [open]); - useEffect(() => { - if (!open) return; - // Dismissing is all a tap outside does: what lies under it is not pressed as well. - const onPointerDown = (e: PointerEvent) => { - if (!root.current || root.current.contains(e.target as Node)) return; - setOpen(false); - const swallow = (click: MouseEvent) => { click.stopPropagation(); click.preventDefault(); }; - document.addEventListener('click', swallow, { capture: true, once: true }); - window.setTimeout(() => document.removeEventListener('click', swallow, { capture: true }), 500); - }; - const onKeyDown = (e: KeyboardEvent) => { - if (e.key === 'Escape') setOpen(false); - }; - document.addEventListener('pointerdown', onPointerDown, true); - document.addEventListener('keydown', onKeyDown); - return () => { - document.removeEventListener('pointerdown', onPointerDown, true); - document.removeEventListener('keydown', onKeyDown); - }; - }, [open]); - if (hidden || selectedIndex < 0 || items.length <= 1) return null; - const release = (el: HTMLElement, pointerId: number) => { - if (el.hasPointerCapture(pointerId)) el.releasePointerCapture(pointerId); - start.current = null; - }; - return ( -
- {/* A small visible handle near the right edge, inset from iOS's own edge gestures. Tap it or - pull it left to open the panel; drag it up or down to move it out of the way of text. It - covers only its own few pixels, so selecting text elsewhere is never intercepted. */} - - {open && ( -
- {items.map((thread) => { - const agent = agentById.get(thread.agent); - const isCurrent = thread.id === selectedId; - const place = thread.scratch ? t('projects.none') : folderName(projectDir(thread).cwd); - return ( - - ); - })} - -
- )} -
- ); -} - function savedMemberDefaults(key: string): Record { try { const saved = JSON.parse(localStorage.getItem(key) ?? '{}'); @@ -404,26 +275,32 @@ function savedMemberDefaults(key: string): Record { } function fitDraftModelPreference(value: DraftModelPreference, models: ModelOption[], effortLevels: string[], canSpeed: boolean): DraftModelPreference { - const model = value.model && models.length > 0 && !models.some((option) => option.id === value.model) ? null : value.model; + const resolved = value.model && models.length > 0 ? resolveModel(models, value.model) : undefined; + const impliedEffort = value.model && resolved && resolved.id !== value.model ? value.model.slice(resolved.id.length + 1) : null; + const model = value.model && models.length > 0 ? (resolved?.id ?? null) : value.model; const levels = effortsForModel(models, model, effortLevels); - const effort = value.effort && (levels.includes(value.effort) || (models.length === 0 && effortLevels.length === 0)) ? value.effort : null; + const rawEffort = value.effort ?? impliedEffort; + const effort = rawEffort && (levels.includes(rawEffort) || (models.length === 0 && effortLevels.length === 0)) ? rawEffort : null; const speeds = speedsForModel(models, model); const speed = canSpeed && value.speed && (models.length === 0 || speeds.some((option) => option.id === value.speed)) ? value.speed : null; return { model, effort, speed }; } /** The model and thinking effort for one instance's members: a quiet mark until something is chosen. */ -function MemberModel({ agent, models, value, permission, onNeed, onChange, onPermission }: { +function MemberModel({ agent, models, value, permission, part, onNeed, onChange, onPermission }: { agent: AgentInfo; models: ModelOption[]; value: MemberDefault; onNeed: (agent: string, refresh?: boolean) => void; onChange: (value: MemberDefault) => void; /** The level in force, and how to change it; left out where the agent has no levels. */ permission?: string; onPermission?: (mode: string) => void; + /** One half only, drawn as the composer's own control rather than a quiet line: a member's box sits like the lead's. */ + part?: 'permission' | 'model'; }) { - useEffect(() => { onNeed(agent.id); }, [agent.id]); // eslint-disable-line react-hooks/exhaustive-deps + useEffect(() => { if (part !== 'permission') onNeed(agent.id); }, [agent.id]); // eslint-disable-line react-hooks/exhaustive-deps const efforts = agent.capabilities.effortLevels ?? []; + const quiet = part ? undefined : agent.label; return (<> - {permission && onPermission && } - } + {part !== 'permission' && onChange({ ...value, model, effort: value.effort && effortsForModel(models, model, efforts).includes(value.effort) ? value.effort : null })} onEffort={(effort) => onChange({ ...value, effort })} - /> + />} ); } @@ -540,7 +417,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } }, [token, authKindRead.error, onToken]); // A browser alert for each Goal that newly waits on the person. The first read is only the baseline. const alertSeen = useRef | null>(null); - const openGoalRef = useRef<(goalId: string, tab?: GoalTab) => void>(() => undefined); + const openGoalRef = useRef<(goalId: string | null, section?: GoalSection | null) => void>(() => undefined); useEffect(() => { if (!loopxStatus) return; const { now, fresh } = newlyWaiting(alertSeen.current, loopxStatus.attention); @@ -569,9 +446,9 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } // Those pages have addresses of their own, so a reload or a bookmark lands back on them. const [threadLink, setThreadLink] = useState(() => window.location.hash.startsWith('#/thread/') ? window.location.hash : null); const [schedulePath, setSchedulePath] = useState(() => window.location.hash.startsWith('#/schedules/') ? window.location.hash.slice('#/schedules/'.length) : ''); - /** The goal the work page shows, from its address. */ - const [goalPath, setGoalPath] = useState(() => goalIdForHash(window.location.hash) ?? ''); - const [goalTab, setGoalTab] = useState(() => goalTabForHash(window.location.hash)); + const [boardEntry, setBoardEntry] = useState(0); + const [goalRequest, setGoalRequest] = useState(() => goalOverviewRequest(window.location.hash)); + const [goalDetailFocus, setGoalDetailFocus] = useState<{ api: Api; threadId: string | null; goalId: string | null; section?: GoalSection | null } | null>(null); const [machinePath, setMachinePath] = useState(() => window.location.hash.startsWith('#/machines/') ? window.location.hash.slice('#/machines/'.length) : ''); const [settingsPath, setSettingsPath] = useState(() => start === 'machines' ? 'machines' : window.location.hash.replace(/^#\/settings\/?/, '')); // `list`: the phone's thread list was open, so closing settings goes back to it. @@ -583,14 +460,18 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } useAppHistory(appBack, appHref); const [view, setView] = useState(() => start === 'machines' ? 'settings' : (typeof start === 'object' ? 'thread' : viewForHash(window.location.hash, Boolean(token)) ?? 'thread')); /** The address of the extension view asked for. Which view that is waits for the list of extensions. */ - const [extTarget, setExtTarget] = useState(() => (viewForHash(window.location.hash, Boolean(token)) === 'ext' ? window.location.hash : null)); + const [extTarget, setExtTarget] = useState(() => viewForHash(window.location.hash, Boolean(token)) === 'ext' ? window.location.hash : null); /** The extension catalog and what is installed on the machine on screen; null until read. */ const [extensions, setExtensions] = useState(null); /** How the list stream is doing, and when the thread list was last read: how extension views tell whether what they show may be stale. */ const [connection, setConnection] = useState('reconnecting'); const [observedAt, setObservedAt] = useState(null); + const pinnedThreadIds = useRef(new Set()); + const pendingCreations = useRef(new Map()); + const optimistic = useOptimisticTurns(); const threadFeed = useMemo(() => createThreadFeed(api, (list, at) => { - setThreads(list); + for (const thread of list) pinnedThreadIds.current.delete(thread.id); + setThreads(prev => mergeServerThreads(list, prev, pinnedThreadIds.current)); setObservedAt(at); setThreadsKnown(true); if (keepThreads) rememberThreads(hostId, list, at ?? new Date().toISOString()); @@ -712,6 +593,8 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } setExternalSessions((prev) => prev.filter((s) => `${s.agent}:${s.sessionId}` !== key)); setSelectedId(thread.id); setImportingExternal(null); + // Importing a session from outside the project roots adds its directory there: show it. + api.workdirs().then(applyWorkdirs).catch(() => undefined); }) .catch((e) => { setImportingExternal(null); @@ -775,6 +658,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } return () => { live = false; }; }, [api]); const [singleSegmentId, setSingleSegmentId] = useState(null); + const [overviewSegment, setOverviewSegment] = useState<{ api: Api; threadId: string; before: number } | null>(null); const [coordination, setCoordination] = useState(null); const memberDefaultsKey = hostId ? `${MEMBER_DEFAULTS_KEY}:${hostId}` : MEMBER_DEFAULTS_KEY; const [memberDefaults, setMemberDefaults] = useState(() => savedMemberDefaults(memberDefaultsKey)); @@ -810,6 +694,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } const [writingBusy, setWritingBusy] = useState(false); const [draftPermission, setDraftPermission] = useState('auto_edit'); const modelPreferences = useModelPreferences(api, error => setError(message(error))); + const [modelLogin, setModelLogin] = useState<{ agent: string; label: string; login?: AgentInfo['login']; empty?: boolean; key: string; client: Api; scope: Api } | null>(null); const [modelsByAgent, setModelsByAgent] = useState>(() => (keepThreads ? cachedModels(hostId) ?? {} : {})); const draftCaps = agents.find(agent => agent.id === draftAgent)?.capabilities; const goalCap = goalCaps.find(cap => cap.agent === draftAgent); @@ -966,6 +851,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } }, [api, demo]); /** The terminal a login started; null attaches to the newest live one. */ const [terminalTarget, setTerminalTarget] = useState(null); + const [terminalClient, setTerminalClient] = useState(null); const [observabilityTab, setObservabilityTab] = useState<'usage' | 'diagnostics'>('usage'); const [observabilityFocus, setObservabilityFocus] = useState(undefined); // Bumped on every visit so the page opens on the requested tab, even when it is already showing. @@ -992,8 +878,15 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } const [restore, setRestore] = useState<{ text: string; nonce: number; mentions?: AgentMention[] } | null>(null); // Text quoted out of a message by selecting it. const composerDraftKey = hostId ? `host:${hostId}:${selectedId ?? (draftTeam ? `new:team:${draftTeam}` : 'new')}` : selectedId ?? (draftTeam ? `new:team:${draftTeam}` : 'new'); + const draftKeys = useDraftKeys(); + const [draftGeneration, setDraftGeneration] = useState(0); + const draftGenerationRef = useRef(0); + const composerScope = JSON.stringify([composerDraftKey, draftGeneration]); + const composerScopeRef = useRef(composerScope); composerScopeRef.current = composerScope; const [noteSignal, setNoteSignal] = useState<{ draftKey: string; note: DraftNote & { nonce: number } } | null>(null); - const [messageReference, setMessageReference] = useState<{ draftKey: string; value: ContextReference; nonce: number } | null>(null); + const pendingNoteId = useRef(null); + pendingNoteId.current = noteSignal?.note.id ?? null; + const [messageReference, setMessageReference] = useState<{ scope: string; value: ContextReference; nonce: number } | null>(null); const [assistantMessage, setAssistantMessage] = useState(null); const messageAssistantApi = useMemo(() => hostId === null ? api : new Api(token), [api, hostId, token]); const messageSnapshot = async (text: string, turnId: string, threadId?: string): Promise => { @@ -1005,31 +898,44 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } }, []); // Where each noted passage stands in the conversation, for as long as its note waits in the box. const noteRanges = useRef(new Map()); + const notesByTarget = useRef(new Map()); const [noteMarks, setNoteMarks] = useState([]); // Notes waiting in the box, and a tick each time one is picked out of the file panel — the phone's // full-screen page cannot show the box, so it counts them at its foot instead. const [noteCount, setNoteCount] = useState(0); const [filesNotePulse, setFilesNotePulse] = useState(0); - const onNotesChange = useCallback((notes: DraftNote[]) => { - const ranges = noteRanges.current; - for (const id of [...ranges.keys()]) if (!notes.some((n) => n.id === id)) ranges.delete(id); - setNoteCount(notes.length); - setNoteMarks(notes.flatMap((n, i) => { - const range = ranges.get(n.id); - return range ? [{ id: n.id, n: i + 1, range }] : []; - })); + const onNotesChangeFor = useCallback((target: string, notes: DraftNote[]) => { + if (notes.length) notesByTarget.current.set(target, notes); + else notesByTarget.current.delete(target); + const allIds = new Set(); + const marks: NoteMark[] = []; + let total = 0; + for (const list of notesByTarget.current.values()) { + total += list.length; + list.forEach((n, i) => { + allIds.add(n.id); + const range = noteRanges.current.get(n.id); + if (range) marks.push({ id: n.id, n: i + 1, range }); + }); + } + for (const id of [...noteRanges.current.keys()]) if (!allIds.has(id) && id !== pendingNoteId.current) noteRanges.current.delete(id); + setNoteCount(total); + setNoteMarks(marks); }, []); + const onNotesChange = useCallback((notes: DraftNote[]) => onNotesChangeFor(composerDraftKey, notes), [composerDraftKey, onNotesChangeFor]); + useEffect(() => () => onNotesChangeFor(composerDraftKey, []), [composerDraftKey, onNotesChangeFor]); // The passage a side chat was opened for, if one is open. const [sideAsk, setSideAsk] = useState<{ text: string; nonce: number; source?: Thread } | null>(null); // A message waiting for the user to confirm sending into a session the terminal also used. - const [pendingSend, setPendingSend] = useState<{ text: string; images: PreparedImage[]; videos?: PreparedVideo[]; mentions?: AgentMention[]; resolve: () => void; reject: (e: unknown) => void } | null>(null); + const [pendingSend, setPendingSend] = useState<{ text: string; images: PreparedImage[]; videos?: PreparedVideo[]; mentions?: AgentMention[]; references: string[]; resolve: () => void; reject: (e: unknown) => void } | null>(null); const [pageHidden, setPageHidden] = useState(() => document.hidden); const baseTitle = useRef(document.title); - const voice = useVoiceSession(api, selectedId, hostId); - const timeline = useMemo(() => buildCachedTimeline(events, + const voice = useVoiceSession(api, isOptimisticThreadId(selectedId) ? null : selectedId, hostId); + const displayEvents = useMemo(() => mergeOptimisticEvents(events, optimistic.turns, selectedId), [events, optimistic.turns, selectedId]); + const timeline = useMemo(() => buildCachedTimeline(displayEvents, voice.state.messagesThreadId === selectedId ? voice.state.messages : []), - [events, selectedId, voice.state.messages, voice.state.messagesThreadId]); + [displayEvents, selectedId, voice.state.messages, voice.state.messagesThreadId]); const turnPreviewMap = useMemo(() => turnPreviews(timeline.items), [timeline.items]); // The newest turn's plan sits in the top bar, so the conversation does not show it twice. const topPlan = useMemo(() => currentPlan(timeline.items), [timeline.items]); @@ -1047,16 +953,24 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } const lastSent = useMemo(() => { for (let i = timeline.items.length - 1; i >= 0; i--) { const item = timeline.items[i]; - if (item.kind === 'user' && !item.coordination && !item.key.startsWith('voice:')) return { turnId: item.turnId, text: item.text }; + if (item.kind === 'user' && !item.coordination && !item.optimistic && !item.key.startsWith('voice:')) return { turnId: item.turnId, text: item.text }; } return null; }, [timeline.items]); const selected = threads.find((t) => t.id === selectedId) ?? null; + const threadPending = !selected && (Boolean(threadLink) || (Boolean(selectedId) && !threadsKnown)); // Her own conversation is told apart by the hub's answer, never by its agent or title. - const [routerThreadId, setRouterThreadId] = useState(null); + const [routerThreadId, setRouterThreadId] = useState(() => (api.demo ? null : cachedRouterThreadId(api.host))); useEffect(() => { - if (api.demo) return; let live = true; - void api.petRouter().then(router => { if (live) setRouterThreadId(router.threadId); }).catch(() => undefined); + if (api.demo) { setRouterThreadId(null); return; } + let live = true; + const cached = cachedRouterThreadId(api.host); + if (cached) setRouterThreadId(current => current ?? cached); + void api.petRouter().then(router => { + if (!live) return; + rememberRouterThreadId(api.host, router.threadId); + setRouterThreadId(router.threadId); + }).catch(() => undefined); return () => { live = false; }; }, [api, threads.length]); const onRouterThread = Boolean(selected && routerThreadId === selected.id); @@ -1064,6 +978,8 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } const latestSegment = selected ? latestHandoverThread(selected, threads) : null; const viewingEarlier = Boolean(selected && latestSegment && latestSegment.id !== selected.id); const mergedHandover = !api.demo && singleSegmentId !== selectedId && Boolean(selected?.handover?.mode === 'continue' || viewingEarlier); + const historyCutoff = overviewSegment?.api === api && overviewSegment.threadId === selectedId && singleSegmentId !== selectedId ? overviewSegment.before : undefined; + useLayoutEffect(() => { setOverviewSegment(value => value?.api === api && value.threadId === selectedId ? value : null); }, [api, selectedId]); const selectDraftAgent = (id: string, list = agents) => { const caps = list.find(item => item.id === id)?.capabilities; setDraftAgent(id); @@ -1080,8 +996,6 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } }, [api, selectedId, threads]); useEffect(() => { setAgentsOpen(false); setDraftCollaboration(false); setCollaborationDirectories([]); }, [selectedId, hostId]); const onSettings = view === 'settings'; - const onGoal = view === 'goal' && !selectedId; - const onGoalsList = view === 'goals' && !selectedId; const onSteward = view === 'steward' && !selectedId; const onSchedules = view === 'schedules' && !selectedId; const onActivity = view === 'activity' && !selectedId; @@ -1097,7 +1011,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } const extOpen = onExt && extensions && extTarget ? resolveExtensionRoute(extTarget, extensions) : null; const extName = extOpen ? extensions?.find((e) => e.manifest.id === extOpen.extensionId)?.manifest.name[locale()] ?? extOpen.extensionId : ''; /** The name of the page the main area shows instead of a thread, for the top bar; null on a thread. */ - const viewTitle = onSettings ? t('sidebar.settings') : onGoal ? t('loopx.goalsGroup') : onGoalsList ? t('goals.title') : onSteward ? t('loopx.steward') : onObservability ? t('obs.title') : onMachines ? t('hosts.machines') : onAgents ? t('agents.title') : onTeams ? t('teams.title') : onSchedules + const viewTitle = onSettings ? t('sidebar.settings') : onSteward ? t('loopx.steward') : onObservability ? t('obs.title') : onMachines ? t('hosts.machines') : onAgents ? t('agents.title') : onTeams ? t('teams.title') : onSchedules ? t('sidebar.schedules') : onActivity ? t('activity.title') @@ -1113,17 +1027,17 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } const onPage = viewTitle !== null; // What an extension view is handed: the summaries of the threads the page holds, and how fresh they are. const connectionShown: ConnectionState = api.demo || (host && !hostUp) ? 'offline' : connection; - const workSources = useWorkSources(api, extensions, Boolean(selectedId) || onExt, onExt ? extOpen?.extensionId : undefined, selectedId ?? undefined); + const workSources = useWorkSources(api, extensions, (Boolean(selectedId) && !isOptimisticThreadId(selectedId)) || onExt, onExt ? extOpen?.extensionId : undefined, selectedId && !isOptimisticThreadId(selectedId) ? selectedId : undefined); const machineSources = useMemo(() => [{ hostId, label: host?.label ?? t('hosts.local'), threads, agents: sidebarAgents, state: connectionShown === 'offline' ? 'offline' : connectionShown === 'live' ? 'live' : threadsKnown ? 'cached' : 'loading', at: observedAt ?? (keepThreads ? cachedThreads(hostId)?.at ?? null : null), }, ...(merging ? elsewhere : [])], [hostId, host?.label, threads, sidebarAgents, connectionShown, threadsKnown, observedAt, keepThreads, merging, elsewhere]); const extInputs = useMemo( - () => (onExt ? { workSources, threads: machineSummaries(machineSources, selectedId, merging), + () => (onExt ? { workSources, threads: machineSummaries(machineSources.map(source => ({ ...source, goals: source.hostId === hostId ? loopxStatus?.goals : undefined })), selectedId, merging), machines: machineSources.map((source): MachineState => ({ id: source.hostId, label: source.label, state: source.state, observedAt: source.at })), connection: connectionShown, observedAt: api.demo ? null : observedAt, agents, extension: extensions?.find(e => e.manifest.id === extOpen?.extensionId) ?? null } : null), - [workSources, onExt, machineSources, merging, selectedId, connectionShown, observedAt, agents, api.demo, extensions, extOpen?.extensionId], + [workSources, onExt, machineSources, hostId, loopxStatus, merging, selectedId, connectionShown, observedAt, agents, api.demo, extensions, extOpen?.extensionId], ); // An extension view that is not there (never installed, removed, switched off, or an address @@ -1162,15 +1076,16 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } // The address follows what the main area shows. Replaced, not pushed: going between the pages and // threads is not a trail for the back button to walk. + const stewardWant = goalRequest ? goalOverviewHash(goalRequest.goalId, goalRequest.section) : goalDetailFocus?.api === api && goalDetailFocus.threadId === null ? goalOverviewHash(goalDetailFocus.goalId, goalDetailFocus.section) : STEWARD_HASH; const extWant = onExt ? (extOpen ? extensionHash(extOpen) : extTarget ?? '') : ''; useEffect(() => { if (threadLink) return; - const want = onSettings ? `#/settings${settingsPath ? `/${settingsPath}` : ''}` : onGoal ? `#/goals/${encodeURIComponent(goalPath)}${goalTab === 'overview' ? '' : `/${goalTab}`}` : onGoalsList ? '#/goals' : onSteward ? STEWARD_HASH : onObservability ? OBSERVABILITY_HASH : onMachines ? `${MACHINES_HASH}${machinePath ? `/${machinePath}` : ''}` : onAgents ? AGENTS_HASH : onTeams ? TEAMS_HASH : onSchedules ? `${SCHEDULES_HASH}${schedulePath ? `/${schedulePath}` : ''}` : onActivity ? ACTIVITY_HASH : onSkills ? SKILLS_HASH : onMcp ? MCP_HASH : onExtensions ? EXTENSIONS_HASH : extWant; + const want = onSettings ? `#/settings${settingsPath ? `/${settingsPath}` : ''}` : onSteward ? stewardWant : onObservability ? OBSERVABILITY_HASH : onMachines ? `${MACHINES_HASH}${machinePath ? `/${machinePath}` : ''}` : onAgents ? AGENTS_HASH : onTeams ? TEAMS_HASH : onSchedules ? `${SCHEDULES_HASH}${schedulePath ? `/${schedulePath}` : ''}` : onActivity ? ACTIVITY_HASH : onSkills ? SKILLS_HASH : onMcp ? MCP_HASH : onExtensions ? EXTENSIONS_HASH : extWant; if (window.location.hash !== want) { window.history.replaceState(window.history.state, '', want || window.location.pathname + window.location.search); } appHref.current = window.location.pathname + window.location.search + window.location.hash; - }, [schedulePath, machinePath, goalPath, goalTab, onSettings, settingsPath, onGoal, onSteward, onObservability, onMachines, onAgents, onTeams, onActivity, onSkills, onSchedules, onMcp, onExtensions, extWant, threadLink]); + }, [stewardWant, goalRequest, goalDetailFocus, api, boardEntry, schedulePath, machinePath, onSettings, settingsPath, onSteward, onObservability, onMachines, onAgents, onTeams, onActivity, onSkills, onSchedules, onMcp, onExtensions, extWant, threadLink]); // Whether the directory a new thread would start in is a git repository. Asked once per directory picked. useEffect(() => { @@ -1217,8 +1132,13 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } setView(next); if (next === 'schedules') setSchedulePath(hash.startsWith('#/schedules/') ? hash.slice('#/schedules/'.length) : ''); if (next === 'machines') setMachinePath(hash.startsWith('#/machines/') ? hash.slice('#/machines/'.length) : ''); - if (next === 'goal') { setGoalPath(goalIdForHash(hash) ?? ''); setGoalTab(goalTabForHash(hash)); } if (next === 'settings') setSettingsPath(hash.replace(/^#\/settings\/?/, '')); + if (next !== 'steward') setGoalRequest(null); + if (next === 'steward') { + const request = goalOverviewRequest(hash); + setGoalRequest(request); + if (!request) setGoalDetailFocus(null); + } if (next === 'ext') setExtTarget(hash); setDrawer(false); }; @@ -1266,7 +1186,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } }, [timeline, planSkip]); const waitingOn = waiting[0] ?? null; - const topLevelThreads = useMemo(() => threads.filter((t) => !t.coordination || t.coordination.rootId === t.id || !threads.some((r) => r.id === t.coordination!.rootId)), [threads]); + const topLevelThreads = useMemo(() => ownRows(threads), [threads]); // Her conversation is reached through her, from the sidebar's own row and the desk, not listed twice. const listedThreads = useMemo(() => routerThreadId ? topLevelThreads.filter((t) => t.id !== routerThreadId) : topLevelThreads, [topLevelThreads, routerThreadId]); @@ -1289,6 +1209,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } } return byLead; }, [threads]); + const forkMembers = useMemo(() => forkGroupsByRoot(threads), [threads]); // A takeover under way, from the button on a turn that failed because the plan ran out. const [takingOver, setTakingOver] = useState(false); @@ -1326,6 +1247,8 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } }); const [agentsStart, setAgentsStart] = useState(null); const stickToBottom = useRef(true); + const [jump, setJump] = useState<{ threadId: string; turnId: string } | null>(null); + const readingPosition = useReadingPosition(scrollerRef, stickToBottom, selectedId, events, `${mergedHandover}:${historyEpoch}:${onSettings}`, Boolean(jump)); // The thread on screen, for answers that arrive after the user has moved on. const shownThread = useRef(null); shownThread.current = selectedId; @@ -1490,6 +1413,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } const { agent, models } = ev.data as { agent: string; models: ModelOption[] }; modelVersions.current[agent] = (modelVersions.current[agent] ?? 0) + 1; setModelsByAgent(previous => ({ ...previous, [agent]: models })); + setModelLogin(current => models.length && current?.scope === api && current.client === api && current.key === agent ? null : current); } else refresh(); }, ctrl.signal, @@ -1529,21 +1453,35 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } // The card reads the goal from events once they arrive; this covers goals older than the page. useEffect(() => { setGoalFetched(null); - if (!api || !selectedId) return; + if (!api || !selectedId || isOptimisticThreadId(selectedId)) return; let active = true; api.threadGoal(selectedId).then(value => { if (active) setGoalFetched(value.goal); }).catch(() => undefined); return () => { active = false; }; }, [api, selectedId, historyEpoch]); useEffect(() => { - setEvents([]); setHistoryTurnIds([]); setHasOlder(false); setLoadingOlder(false); setHistoryReady(false); - setEventsLoading(Boolean(api && selectedId)); historyCursor.current = null; olderRequest.current = null; + if (isOptimisticThreadId(selectedId)) { + setEvents([]); setHistoryTurnIds([]); setHasOlder(false); setLoadingOlder(false); + setHistoryReady(true); setEventsLoading(false); historyCursor.current = null; olderRequest.current = null; + return; + } + const cached = api && selectedId && historyCutoff === undefined ? peekCachedPage(api, selectedId, undefined, undefined, mergedHandover)?.page ?? null : null; + if (cached) { + setEvents(cached.events); setHistoryTurnIds(cached.turnIds ?? []); setHasOlder(cached.hasOlder); + setLoadingOlder(false); setHistoryReady(true); setEventsLoading(false); + setHistoryRevision(cached.snapshotSeq); historyCursor.current = cached.nextCursor; olderRequest.current = null; + } else { + const hasOpt = optimistic.hasForThread(selectedId); + setEvents([]); setHistoryTurnIds([]); setHasOlder(false); setLoadingOlder(false); + setHistoryReady(hasOpt); setEventsLoading(Boolean(api && selectedId) && !hasOpt); historyCursor.current = null; olderRequest.current = null; + } if (!api || !selectedId) return; const ctrl = new AbortController(); stickToBottom.current = true; setAtBottom(true); - void watchHistory(api, selectedId, ctrl.signal, { - chain: mergedHandover, + const callbacks: Parameters[3] = { + chain: mergedHandover, maximumSeq: historyCutoff, pinned: selectedId === routerThreadId, page: page => { - setEvents(page.events); setHistoryTurnIds(page.turnIds ?? []); setEventsLoading(false); setHistoryReady(true); + setEvents(page.events); optimistic.reconcile(selectedId, page.events); + setHistoryTurnIds(page.turnIds ?? []); setEventsLoading(false); setHistoryReady(true); setHistoryRevision(page.snapshotSeq); historyCursor.current = page.nextCursor; setHasOlder(page.hasOlder); }, @@ -1556,13 +1494,14 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } } // Everything the page has seen is part of the history it may edit against. setHistoryRevision((revision) => batch.reduce((latest, ev) => Math.max(latest, ev.seq), revision)); - setEvents(previous => mergeHistory(previous, batch)); + setEvents(previous => { const next = mergeHistory(previous, batch); optimistic.reconcile(selectedId, next); return next; }); }, error: error => { setEventsLoading(false); handleError(error); }, - }); + }; + void watchHistory(api, selectedId, ctrl.signal, callbacks); return () => ctrl.abort(); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [api, selectedId, mergedHandover, historyEpoch]); + }, [api, selectedId, mergedHandover, historyEpoch, historyCutoff]); /** Prepends the page of turns before the loaded ones, keeping the scroll position on the same content. */ const loadOlder = async () => { @@ -1570,6 +1509,8 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } const first = historyCursor.current ?? 0; if (!api || !id || loadingOlder || olderRequest.current || first <= 1) return; const request = {}; olderRequest.current = request; + // Loading older turns is an explicit upward reading intent; unpin immediately. + stickToBottom.current = false; setLoadingOlder(true); try { const page = await historyPage(api, id, first, undefined, mergedHandover); @@ -1577,13 +1518,10 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } // The answer is for the thread that asked; another one may be open by now. if (shownThread.current !== id || olderRequest.current !== request) return; setHasOlder(page.hasOlder); historyCursor.current = page.nextCursor; - const el = scrollerRef.current; - const fromBottom = el ? el.scrollHeight - el.scrollTop : 0; + stickToBottom.current = false; + const firstTurn = older.find(event => event.type === 'turn.started') ?? older[0]; + readingPosition.preparePrepend(firstTurn?.seq); setEvents((prev) => prependHistory(older, prev)); - // New content lands above the viewport; stay on the same row while it inserts. - requestAnimationFrame(() => { - if (el && !stickToBottom.current && !jump) el.scrollTop = el.scrollHeight - fromBottom; - }); } catch (e) { if (olderRequest.current === request) { setJump(null); handleError(e); } } finally { @@ -1607,7 +1545,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } useEffect(() => { const el = scrollerRef.current; if (el && stickToBottom.current) el.scrollTop = el.scrollHeight; - }, [events, selected?.autoHandover?.state, selected?.autoHandover?.step]); + }, [displayEvents, selected?.autoHandover?.state, selected?.autoHandover?.step]); // Screenshots and slow-rendering blocks grow the thread after the scroll above, which used to // leave a reopened thread parked at the top. Watching the thread's height keeps it pinned. The @@ -1617,15 +1555,18 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } const content = el?.querySelector('.merged-history, .thread'); if (!el || !content) return; const ro = new ResizeObserver(() => { - if (stickToBottom.current) el.scrollTop = el.scrollHeight; + if (stickToBottom.current) { readingPosition.capture(); el.scrollTop = el.scrollHeight; } // Growth below an unpinned view moves nothing, so no scroll event reports that the view // has fallen behind; the jump button has to learn it here. - else setAtBottom(isNearBottom(el)); + else { + readingPosition.restore(); + setAtBottom(isNearBottom(el)); + } }); ro.observe(content); ro.observe(el); return () => ro.disconnect(); - }, [selectedId, mergedHandover, onSettings]); + }, [selected?.id, eventsLoading, mergedHandover, onSettings]); // A phone keyboard does not resize the page: it covers the bottom of it, and the browser pans // what is left (the visual viewport) over the page to keep the focused field in sight. So the @@ -1711,15 +1652,16 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } const onScroll = () => { const el = scrollerRef.current; if (!el) return; + if (readingPosition.didRestore()) { setAtBottom(isNearBottom(el)); return; } const near = isNearBottom(el); const byHand = gesture.current.held || Date.now() - gesture.current.at < GESTURE_GRACE_MS; if (near) stickToBottom.current = true; else if (byHand) stickToBottom.current = false; + readingPosition.capture(); setAtBottom(near); }; // The turn a search led to: shown once it is on the page, which for an old turn means fetching back to it. - const [jump, setJump] = useState<{ threadId: string; turnId: string } | null>(null); useEffect(() => { if (!jump || jump.threadId !== selectedId || eventsLoading) return; const scope = scrollerRef.current?.querySelector(`[data-history-thread="${CSS.escape(jump.threadId)}"]`) ?? scrollerRef.current; @@ -1756,6 +1698,25 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } const activeAgent = selected?.agent ?? draftTeamDefinition?.entryAgent ?? draftAgent; const activeCwd = selected?.cwd ?? draftCwd; const commandsKey = `${activeAgent}\n${activeCwd}`; + const activeCatalog = useRef({ api, agent: activeAgent }); + activeCatalog.current = { api, agent: activeAgent }; + useEffect(() => { setModelLogin(null); }, [api, activeAgent]); + const acceptModelCatalog = (agent: string, list: ModelOption[], client = api, id = agent) => { + setModelsByAgent(previous => ({ ...previous, [agent]: list })); + const info = agents.find(item => item.id === agent) ?? remoteAgents.find(item => item.id === agent); + if (!list.length && info?.available && info.capabilities.modelCatalog !== false) { + setModelLogin({ agent: id, key: agent, client, scope: api, label: info.label, login: info.login, empty: true }); + return; + } + setModelLogin(current => current?.scope === api && current.key === agent ? null : current); + }; + const handleModelError = (error: unknown, agent: string, client = api, key = agent, report = true) => { + if (!needsAgentLogin(error)) { if (report) handleError(error); return; } + modelVersions.current[key] = (modelVersions.current[key] ?? 0) + 1; + setModelsByAgent(previous => { const next = { ...previous }; delete next[key]; return next; }); + const info = agents.find(item => item.id === key) ?? remoteAgents.find(item => item.id === key); + setModelLogin({ agent, key, client, scope: api, label: info?.label ?? agent, login: info?.login }); + }; const lastFocusModelRefresh = useRef<{ agent: string; at: number } | null>(null); const refreshActiveModels = useCallback((force = false) => { if (!api || !activeAgent || document.hidden) return; @@ -1767,9 +1728,9 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } void api .models(activeAgent, force) .then((list) => { - if ((modelVersions.current[activeAgent] ?? 0) === version) setModelsByAgent(prev => ({ ...prev, [activeAgent]: list })); + if (activeCatalog.current.api === api && activeCatalog.current.agent === activeAgent && (modelVersions.current[activeAgent] ?? 0) === version) acceptModelCatalog(activeAgent, list); }) - .catch(error => { if (force) handleError(error); }); + .catch(error => { if (activeCatalog.current.api === api && activeCatalog.current.agent === activeAgent && (modelVersions.current[activeAgent] ?? 0) === version) handleModelError(error, activeAgent, api, activeAgent, force); }); }, [api, activeAgent]); // Models of an agent other than the thread's own, for choosing what its members start with. @@ -1780,21 +1741,25 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } const version = modelVersions.current[agent] ?? 0; // An instance of another machine is asked there, under the id it has on that machine. const remote = remoteAgents.find((a) => a.id === agent); - (remote && token ? new Api(token, '', remote.host).models(agent.slice(0, -(remote.host.length + 1)), refresh) : api.models(agent, refresh)).then((list) => { - if ((modelVersions.current[agent] ?? 0) === version) setModelsByAgent(prev => ({ ...prev, [agent]: list })); - }).catch(error => { if (refresh) handleError(error); }).finally(() => { modelsAsked.current.delete(agent); }); + const client = remote && token ? new Api(token, '', remote.host) : api; + const id = remote && token ? agent.slice(0, -(remote.host.length + 1)) : agent; + client.models(id, refresh).then((list) => { + if ((modelVersions.current[agent] ?? 0) === version) acceptModelCatalog(agent, list, client, id); + }).catch(error => { if ((modelVersions.current[agent] ?? 0) === version) handleModelError(error, id, client, agent, refresh); }).finally(() => { modelsAsked.current.delete(agent); }); }; // Models for that agent, loaded once per agent. useEffect(() => { - if (!api || !activeAgent || modelsByAgent[activeAgent]) return; + if (!api || !activeAgent || modelsByAgent[activeAgent]?.length) return; + let live = true; const version = modelVersions.current[activeAgent] ?? 0; api .models(activeAgent) .then((list) => { - if ((modelVersions.current[activeAgent] ?? 0) === version) setModelsByAgent(prev => ({ ...prev, [activeAgent]: list })); + if (live && (modelVersions.current[activeAgent] ?? 0) === version) acceptModelCatalog(activeAgent, list); }) - .catch(handleError); + .catch(error => { if (live && (modelVersions.current[activeAgent] ?? 0) === version) handleModelError(error, activeAgent); }); + return () => { live = false; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [api, activeAgent]); @@ -1842,10 +1807,12 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } const loadImage = useCallback( (attachmentId: string) => { - if (!api || !selectedId) return Promise.reject(new Error('no thread')); + const local = optimistic.imageBlob(attachmentId); + if (local) return Promise.resolve(local); + if (!api || !selectedId || isOptimisticThreadId(selectedId)) return Promise.reject(new Error('no thread')); return api.attachment(selectedId, attachmentId); }, - [api, selectedId], + [api, selectedId, optimistic.imageBlob], ); const loadFile = useCallback( @@ -1863,20 +1830,62 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } /** The thread's trace, beside the conversation on a desktop, a page of its own on a phone. */ const [traceOpen, setTraceOpen] = useState(false); const [gitOpen, setGitOpen] = useState(false); + const [referenceId, setReferenceId] = useState(null); + const referenceOrigin = useRef<{ focus: HTMLElement | null; top: number; offset: number } | null>(null); + const referenceOverlay = !useMinWidth(901); + const openReference = (id: string) => { + const focus = document.activeElement instanceof HTMLElement ? document.activeElement : null; + referenceOrigin.current ??= { focus, top: scrollerRef.current?.scrollTop ?? 0, offset: focus?.getBoundingClientRect().top ?? 0 }; + stickToBottom.current = false; + setFiles(null); setTraceOpen(false); setGitOpen(false); setAgentsOpen(false); setOverviewDetail(null); + setReferenceId(id); + }; + useLayoutEffect(() => { + const origin = referenceOrigin.current; + if (!origin || !scrollerRef.current) return; + if (referenceId) { + if (origin.focus?.isConnected) scrollerRef.current.scrollTop += origin.focus.getBoundingClientRect().top - origin.offset; + } else { + stickToBottom.current = false; + scrollerRef.current.scrollTop = origin.top; + origin.focus?.focus({ preventScroll: true }); + referenceOrigin.current = null; + } + }, [referenceId]); + useLayoutEffect(() => { + const main = mainRef.current; + if (!referenceId || !referenceOverlay || !main) return; + main.inert = true; + return () => { main.inert = false; }; + }, [referenceId, referenceOverlay]); + useLayoutEffect(() => { setReferenceId(null); referenceOrigin.current = null; }, [api, selectedId, onPage]); + useEffect(() => { if (files || traceOpen || agentsOpen || gitOpen) setReferenceId(null); }, [files, traceOpen, agentsOpen, gitOpen]); useLayoutEffect(() => { setGitOpen(false); }, [selectedId, api]); useEffect(() => { if (files || traceOpen || agentsOpen) setGitOpen(false); }, [files, traceOpen, agentsOpen]); const filesSeq = useRef(0); useEffect(() => { setFiles(null); setFilesThreadId(null); setTraceOpen(false); }, [selectedId]); // The overview: a popover on narrow screens and the pages, a standing panel beside the - // conversation on a wide one. Its switch is remembered here, and starts open. - const overviewDock = useMinWidth(OVERVIEW_DOCK_MIN_WIDTH) && !onPage; + // conversation on a wide one. Ordinary threads remember their switch and start open; the steward + // stays calm and chat-first until opened on demand or targeted by a Goal deep link. + const overviewDock = useMinWidth(OVERVIEW_DOCK_MIN_WIDTH) && (!onPage || onSteward); const [overviewOpen, setOverviewOpen] = useStoredFlag(OVERVIEW_OPEN_KEY, true); + const [stewardOverviewOpen, setStewardOverviewOpen] = useState(() => Boolean(goalRequest)); + const activeOverviewOpen = onSteward ? stewardOverviewOpen : overviewOpen; + const setActiveOverviewOpen = onSteward ? setStewardOverviewOpen : setOverviewOpen; const [overviewDetail, setOverviewDetail] = useState<{ api: Api; threadId: string; section: OverviewSection; returnToPreview: boolean } | null>(null); const [overviewSignal, setOverviewSignal] = useState(0); + const [goalDetailsExpanded, setGoalDetailsExpanded] = useState<{ threadId: string; expanded: boolean } | null>(null); + const onGoalDetailsChange = useCallback((threadId: string, expanded: boolean) => { + setGoalDetailsExpanded(current => current?.threadId === threadId && current.expanded === expanded ? current : { threadId, expanded }); + }, []); + useEffect(() => { + if (onSteward && (goalRequest || (goalDetailFocus?.api === api && goalDetailFocus.threadId === null))) setStewardOverviewOpen(true); + if (goalDetailFocus?.api === api && (goalDetailFocus.threadId === null ? onSteward : goalDetailFocus.threadId === selectedId && !onPage)) setOverviewSignal(signal => signal + 1); + }, [goalRequest, goalDetailFocus, api, selectedId, onPage, onSteward]); const [overviewLoading, setOverviewLoading] = useState(false); const activeOverviewDetail = overviewDetail?.api === api && overviewDetail?.threadId === selectedId && !onPage ? overviewDetail : null; - useLayoutEffect(() => { setOverviewDetail(null); setOverviewSignal(0); }, [api, selectedId, onPage]); + useLayoutEffect(() => { setOverviewDetail(d => d && d.api === api && d.threadId === selectedId && !onPage ? d : null); setOverviewSignal(0); }, [api, selectedId, onPage]); const closeOverviewDetail = () => { setOverviewDetail(null); if (overviewDock && !activeOverviewDetail?.returnToPreview) setOverviewOpen(false); @@ -1884,12 +1893,30 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } }; /** A side panel takes the same edge as the overview, so the panel steps aside while one is open — * but the person's own switch is left alone: it comes back when the side panel closes. */ - const sideOpen = Boolean(agentsOpen && coordination) || Boolean(files) || traceOpen || gitOpen; - const overviewShown = overviewDock && overviewOpen && !sideOpen && !activeOverviewDetail && Boolean(selected) && hostUp; + const [preview, setPreview] = useState<{ threadId: string; path: string } | null>(null); + const [diffFile, setDiffFile] = useState<{ threadId: string; file: ChangedFile } | null>(null); + const [picture, setPicture] = useState<{ threadId: string; path: string; name: string } | null>(null); + useLayoutEffect(() => { + setPreview(value => !onPage && value?.threadId === selectedId ? value : null); + setDiffFile(value => !onPage && value?.threadId === selectedId ? value : null); + setPicture(value => !onPage && value?.threadId === selectedId ? value : null); + }, [selectedId, onPage]); + useLayoutEffect(() => { setPreview(null); setDiffFile(null); setPicture(null); }, [api]); + const dockOpen = !compact && Boolean(activeOverviewDetail || preview || diffFile || picture || termOpen); + const sideKeys = Boolean(referenceId) || Boolean(agentsOpen && coordination) || Boolean(files) || traceOpen || gitOpen; + const wasSide = useRef(false); + const wasDock = useRef(false); + useEffect(() => { + if (sideKeys && !wasSide.current) { setPreview(null); setDiffFile(null); setPicture(null); setOverviewDetail(null); setTermOpen(false); } + if (dockOpen && !wasDock.current) { setFiles(null); setTraceOpen(false); setAgentsOpen(false); setGitOpen(false); setReferenceId(null); } + wasSide.current = sideKeys; wasDock.current = dockOpen; + }, [sideKeys, dockOpen]); + const sideOpen = sideKeys || dockOpen; + const overviewRoom = overviewDock && activeOverviewOpen && !sideOpen && !activeOverviewDetail && (onSteward || (Boolean(selected || threadPending) && hostUp)); + const overviewShown = overviewRoom && (onSteward || (Boolean(selected) && !isOptimisticThreadId(selected?.id))); /** Only the person turns the standing panel off; the switch above remembers it. */ - const closeOverview = useCallback(() => { if (overviewDock) setOverviewOpen(false); }, [overviewDock, setOverviewOpen]); + const closeOverview = useCallback(() => { if (overviewDock) setActiveOverviewOpen(false); }, [overviewDock, setActiveOverviewOpen]); // A page the agent wrote, rendered in a sandboxed iframe. - const [preview, setPreview] = useState<{ threadId: string; path: string } | null>(null); const openFileLink = useCallback( async (raw: string) => { if (!api || !selectedId) throw new Error('no thread'); @@ -1905,6 +1932,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } const listing = await api.threadTree(selectedId, ref.path); setFilesThreadId(selectedId); setAgentsOpen(false); + setTraceOpen(false); setFiles({ path: null, folder: listing.path, seq: ++filesSeq.current }); return; } catch { @@ -1915,6 +1943,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } } setFilesThreadId(selectedId); setAgentsOpen(false); + setTraceOpen(false); setFiles({ path: file.path, line: ref.line, file, seq: ++filesSeq.current }); }, [api, selectedId], @@ -2051,7 +2080,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } }, }); - // A new thread is created by its first message, or by starting voice on the draft. + // A new thread is created by starting voice on the draft (messages go through runOptimisticMainSend). const createDraftThread = async (isNewThread: boolean, onCreated?: (threadId: string) => void) => { const t = await api.createThread({ agent: draftAgent, @@ -2065,12 +2094,11 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } ...(draftScratch ? { scratch: true } : draftWorktree && offer ? { worktree: true } : {}), }); const id = t.id; + pinnedThreadIds.current.add(id); onCreated?.(id); - if (draftWriting) { - const updated = await api.setWriting(id, draftWriting); - setThreads(prev => [updated, ...prev.filter(v => v.id !== updated.id)]); - setDraftWriting(null); - } + const added = draftWriting ? await api.setWriting(id, draftWriting) : t; + if (draftWriting) setDraftWriting(null); + setThreads(prev => [added, ...prev.filter(v => v.id !== added.id)]); setSelectedId(id); setDraftSectionId(null); // Every worktree is a new branch; the next thread starts in place unless asked again. @@ -2078,9 +2106,9 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } return id; }; - const performSend = async (text: string, images: PreparedImage[], isNewThread: boolean, mentions?: AgentMention[], videos: PreparedVideo[] = [], onCreated?: (draftKey: string) => void) => { + const performSend = async (text: string, images: PreparedImage[], isNewThread: boolean, mentions?: AgentMention[], videos: PreparedVideo[] = [], onCreated?: (draftKey: string | null) => void, references: string[] = []) => { setError(null); - let id = selectedId; + const id = selectedId; const created = (threadId: string) => onCreated?.(hostId ? `host:${hostId}:${threadId}` : threadId); try { // A Goal is reviewed by the LoopX core before it exists; the draft stays in the box until it is created or backed out of. @@ -2088,26 +2116,16 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } if (images.length || videos.length) throw new Error(t('loopx.goal.noMedia')); return await new Promise((resolve, reject) => setPendingGoal({ text, onCreated: created, resolve, reject })); } - if (!id && draftTeam) { - if (videos.length) throw new Error(t('teams.attachments')); - const task = await api.dispatchTeam(draftTeam, text, draftCwd, images.map(({ data, mimeType }) => ({ data, mimeType }))); - created(task.threadId); - setSelectedId(task.threadId); setDraftTeam(null); setDraftSectionId(null); - setView('thread'); void refreshThreads(); return; - } - if (!id) id = await createDraftThread(isNewThread, created); - // Bringing an agent in with @ is itself the request to collaborate; there is no switch to find first. - const collaboration = (draftCollaboration || mentions?.length) && !selected?.coordination - ? { directories: collaborationDirectories.length ? collaborationDirectories : undefined, defaults: startingDefaults, permission: memberPermission } : undefined; - stickToBottom.current = true; - // "queue" only matters while a turn is running: then the message waits instead of being refused. - await api.startTurn( - id, - text, - images.map(({ data, mimeType }) => ({ data, mimeType })), - { queue: true, mentions, collaboration, videos: await Promise.all(videos.map(async video => (await api.uploadVideo(id!, video.file)).id)) }, - ); - void refreshThreads(); + await runOptimisticMainSend({ + api, selectedId, selected, running, events, draftTeam, draftAgent, draftCwd, draftScratch, draftPermission, draftWorkMode, + draftModel, draftEffort, draftSpeed, draftSectionId, draftWorktree, draftWriting, hasWorktreeOffer: Boolean(offer), + draftCollaboration, collaborationDirectories, startingDefaults, memberPermission, + text, images, isNewThread, mentions, videos, references, teamAttachmentsError: t('teams.attachments'), + setThreads, setSelectedId, setView, setDraftWriting, setDraftSectionId, setDraftWorktree, setDraftTeam, + pinnedThreadIds, shownThread, stickToBottom, optimistic, pendingCreations, refreshThreads: () => { void refreshThreads(); }, + onCreated: created, + onRollback: () => onCreated?.(null), + }); } catch (e) { // The composer keeps the draft; the dialog says it will still be there. if (e instanceof DemoError) { @@ -2119,19 +2137,24 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } } }; - const send = async (text: string, images: PreparedImage[], mentions?: AgentMention[], videos: PreparedVideo[] = [], onCreated?: (draftKey: string) => void) => { + const send = async (text: string, images: PreparedImage[], mentions?: AgentMention[], videos: PreparedVideo[] = [], onCreated?: (draftKey: string | null) => void, references: string[] = []) => { // The terminal wrote to this session after the hub last did. Both sides writing the same session // interleaves turns, so ask before joining in again. // The composer keeps the draft and its pictures until this settles, so backing out loses nothing. if (selectedId && selected?.terminalActivity) { - return new Promise((resolve, reject) => setPendingSend({ text, images, videos, mentions, resolve, reject })); + return new Promise((resolve, reject) => setPendingSend({ text, images, videos, mentions, references, resolve, reject })); } - await performSend(text, images, true, mentions, videos, onCreated); + await performSend(text, images, true, mentions, videos, onCreated, references); }; // Stopping means stopping: messages that were waiting are not sent. Their text goes back in the box. const stop = () => { if (!selectedId) return; + if (isOptimisticThreadId(selectedId)) { + const pending = pendingCreations.current.get(selectedId); + if (pending) pending.cancelled = true; + return; + } api .cancel(selectedId) .then(({ dropped, mentions }) => { @@ -2206,7 +2229,12 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } // The hub's "back", for a back swipe or the browser's back button (see appHistory.ts): the same // steps as the top-left button, one at a time. Nothing left to undo hands the swipe to the browser. appBack.current = () => { + if (referenceId) { setReferenceId(null); return true; } if (listOpen) { setDrawer(false); return true; } + if (!compact && diffFile) { setDiffFile(null); return true; } + if (!compact && preview) { setPreview(null); return true; } + if (!compact && picture) { setPicture(null); return true; } + if (termOpen) { setTermOpen(false); setTerminalTarget(null); setTerminalClient(null); return true; } if (activeOverviewDetail) { closeOverviewDetail(); return true; } if (onSettings) { if (settingsPath.includes('/')) openSettings(settingsPath.slice(0, settingsPath.lastIndexOf('/'))); @@ -2253,18 +2281,38 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } else onHost?.(machine, { thread: id }); }; - // The LoopX steward page and the goal work pages take the place of a thread, so no thread is open on them. + // The steward takes the place of a thread; Goal work stays in the shared overview. const openSteward = () => navigate(() => { + setGoalRequest(null); setGoalDetailFocus(null); setThreadLink(null); setSelectedId(null); setView('steward'); setDrawer(false); }); - const [goalsFilter, setGoalsFilter] = useState('all'); - const openGoalsList = (filter: GoalsFilter = 'all') => navigate(() => { - setGoalsFilter(filter); setSelectedId(null); setView('goals'); setDrawer(false); - }); - const openGoal = (goalId: string, tab: GoalTab = 'overview') => navigate(() => { - setGoalPath(goalId); setGoalTab(tab); setSelectedId(null); setView('goal'); setDrawer(false); + const openGoalsBoard = () => navigate(() => { + setExtTarget(goalsBoardTarget(extensionStorage('board'))); + setBoardEntry(value => value + 1); + setThreadLink(null); setSelectedId(null); setView('ext'); setDrawer(false); }); + const openGoal = (goalId: string | null, section: GoalSection | null = null) => { + const target = goalDestination(goalId, threads); + navigate(() => { + setThreadLink(null); + if (target.threadId) { + openThread(threads.find(thread => thread.id === target.threadId)!); + setOverviewOpen(true); + } else { + setSelectedId(null); setView('steward'); setDrawer(false); + setStewardOverviewOpen(true); + } + setGoalDetailFocus({ api, threadId: target.threadId, goalId, section }); + }); + }; openGoalRef.current = openGoal; + // Keep the requested Goal identity while the host is reading its conversation bindings. + // Bookmarks only select a reader; they never create a conversation or start Goal work. + useEffect(() => { + if (!goalRequest || !onSteward || !observedAt && !api.demo) return; + setGoalRequest(null); + openGoalRef.current(goalRequest.goalId, goalRequest.section); + }, [goalRequest, onSteward, observedAt, api.demo, threads]); const [exploreOpen, setExploreOpen] = useState(false); const [setupNeeded, setSetupNeeded] = useState(null); const [setupNotice, setSetupNotice] = useState<{ text: string; at: number } | null>(null); @@ -2321,12 +2369,25 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } const openAgents = () => { openSettings('agents'); void reloadAgents().catch(handleError); }; - const openTerminal = () => { setTerminalTarget(null); setTermOpen(true); }; + const openTerminal = () => { + setPreview(null); + setDiffFile(null); + setPicture(null); + setOverviewDetail(null); + setTerminalTarget(null); + setTerminalClient(null); + setTermOpen(true); + }; /** Starts an instance's CLI login in a fresh terminal and shows that terminal. */ - const openAgentLogin = async (agent: AgentInfo) => { - const { terminalId } = await api.loginAgentTerminal(agent.id); + const openAgentLogin = async (agent: Pick, client = api) => { + const { terminalId } = await client.loginAgentTerminal(agent.id); + setPreview(null); + setDiffFile(null); + setPicture(null); + setOverviewDetail(null); setTerminalTarget(terminalId); + setTerminalClient(client); setTermOpen(true); }; @@ -2356,9 +2417,16 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } onOpen: () => openExtensionView(extensionHash(v)), })); - const newThread = (opts: { cwd?: string; sectionId?: string | null; scratch?: boolean } = {}) => navigate(() => { + const newThread = (opts: { cwd?: string; sectionId?: string | null; scratch?: boolean; beside?: Thread } = {}) => navigate(() => { void modelPreferences.refresh(); if (showcase) { showcase.onInstall(); return; } + const targetKey = hostId ? `host:${hostId}:${opts.beside || !draftTeam ? 'new' : `new:team:${draftTeam}`}` : opts.beside || !draftTeam ? 'new' : `new:team:${draftTeam}`; + // Directory selection and visible read attachments are separate; restoring the former never recreates the latter. + replaceAutomaticComposerReference(targetKey, opts.beside ? pendingThreadReference(opts.beside) : null); + const generation = ++draftGenerationRef.current; + composerScopeRef.current = JSON.stringify([targetKey, generation]); + setDraftGeneration(generation); + setMessageReference(null); setNoteSignal(null); setRestore(null); setSelectedId(null); setView('thread'); setDrawer(false); @@ -2427,6 +2495,8 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } const agentLabel = (id: string) => agents.find((a) => a.id === id)?.label ?? id; const capsOf = (id: string) => agents.find((a) => a.id === id)?.capabilities; const activeCaps = capsOf(activeAgent); + const sideAgent = sideAsk?.source?.agent ?? activeAgent; + const sideAgentInfo = agents.find(agent => agent.id === sideAgent); const models = modelsByAgent[activeAgent] ?? []; const permissionModes = activeCaps?.permissionModes ?? []; const effortLevels = activeCaps?.effortLevels ?? []; @@ -2480,7 +2550,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } const speed = selected ? selected.speed ?? null : draftSpeed; const updateSelected = (patch: { speed?: string | null; permissionMode?: string; model?: string | null; effort?: string | null }) => { - if (!selected) return; + if (!selected || isOptimisticThreadId(selected.id)) return; // Shown at once: a control that waits for the round trip snaps back to the old value first. const id = selected.id; const before = { permissionMode: selected.permissionMode, model: selected.model, effort: selected.effort, speed: selected.speed }; @@ -2506,7 +2576,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } // Adds a discovered CLI as its own instance and selects it for the new thread. const addDiscoveredAgent = async (found: DiscoveredAgent) => { if (!api) return; - await api.addAgent({ id: found.id, adapter: found.adapter, command: [found.command] }); + await api.addAgent({ id: found.id, adapter: found.adapter, ...(found.command ? { command: [found.command] } : {}) }); const [list, more] = await Promise.all([api.agents(), api.discoverAgents()]); setAgents(list); setDiscovered(more); @@ -2603,7 +2673,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } // The top bar names a thread's agent and directory, so the composer does not repeat them: its // strip is only for choosing them, before the thread exists. - const header = selected ? null : ( + const header = selected || threadPending ? null : ( <> { const id = teamRecipient(value); setDraftTeam(id); if (id) { setDraftScratch(false); setDraftWorktree(false); setDraftCollaboration(false); } else pickAgent(value); }} accounts={accounts} onAddAccount={addAccount} /> memberProgress(member) === 'need').length ?? 0; + const waitingOnUser = loopxStatus?.attention.filter(item => loopxNeedsYou.has(item.goalId)) ?? []; + const goalNeeds = selected?.loopxInfo && !selected.loopxInfo.missing && loopxNeedsYou.has(selected.loopxInfo.goalId) ? 1 : 0; + const overviewNeeds = onSteward ? waitingOnUser.length : teamNeeds + goalNeeds; + const overviewBusy = onSteward ? loopxRead.loading : overviewLoading; + const goalsChanged = () => { loopxRead.reload(); void refreshThreads(); }; // The conversation's turns, for naming the section each change belongs to in the diff dialog. const turnOrder = useMemo(() => { const seen = new Set(); @@ -2774,9 +2849,8 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } return order; }, [timeline.items]); // One file's whole change history, opened from the changes group; read only while it is open. - const [diffFile, setDiffFile] = useState<{ threadId: string; file: ChangedFile } | null>(null); // A member's own thread: it was sent from the lead's, which is where its way back goes. - const atMember = Boolean(teamShown && selected!.coordination!.rootId !== selected!.id); + const atMember = Boolean(teamShown && selected!.coordination!.rootId !== selected!.id && !selected!.coordination!.retired); // Where the thread runs, beside its title; a page or a team task names itself instead. const placeShown = Boolean(selected && !viewTitle && !(host && !hostUp) && !selected.coordination?.team && !atMember); const leadTitle = atMember ? threads.find((v) => v.id === selected!.coordination!.rootId)?.title ?? '' : ''; @@ -2827,6 +2901,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } { label: t('settings.preferences'), entries: [ ...(!demo ? [{ id: 'general', label: t('general.title'), icon: IconSettings, render: () => { setStartupSettings(value); setExternalNonce(n => n + 1); }} onClose={closeSettings} /> }] : []), { id: 'appearance', label: t('appearance.title'), icon: IconPalette, render: () => }, + ...(!showcase ? [{ id: 'install', label: t('pwa.title'), icon: IconDownload, render: () => }] : []), { id: 'language', label: t('locale.menu'), icon: IconLanguage, render: () =>
{[{ id: 'system' as const, name: t('locale.system') }, ...LOCALES].map(l => )}
}, @@ -2863,16 +2938,36 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } ]; // The same body in both shapes: the standing panel beside the conversation, and the popover a // narrow window still gets. Only the standing one keeps itself open behind its own rows. - const overviewBody = (close: () => void, persistent: boolean, detail?: OverviewSection) => selected && api && ( + const overviewChain = selected && !demo ? (() => { + const group = handoverGroups(threads).find(group => group.members.some(item => item.id === selected.id)); + if (!group || group.members.length < 2) return undefined; + return { rows: group.members, latestId: group.latest.id, viewingId: selected.id, onOpen: (id: string) => { + const before = overviewHistoryBoundary(id, group.members); + setOverviewSegment(before === undefined ? null : { api, threadId: id, before }); + setSingleSegmentId(null); + setOverviewDetail(d => d && d.section === 'chain' && !compact ? { ...d, threadId: id } : d); + pick(id); + } }; + })() : undefined; + const overviewBody = (close: () => void, persistent: boolean, detail?: OverviewSection) => onSteward ? ( + cap.agent === draftAgent && cap.available)?.agent ?? goalCaps.find(cap => cap.available)?.agent ?? ''} pickDirectory={pickGoalDir} + onOpenThread={id => { if (!persistent) close(); openThreadById(id); }} + onBrowseFiles={threadId => { if (!persistent) close(); setFilesThreadId(threadId); setFiles({ path: null, seq: ++filesSeq.current }); }} + onOpenAll={showcase ? undefined : () => { if (!persistent) close(); openGoalsBoard(); }} /> + ) : selected && !isOptimisticThreadId(selected.id) && api && ( setOverviewDetail({ api, threadId: selected.id, section, returnToPreview })} api={api} threadId={selected.id} updatedAt={selected.updatedAt} active={selected.status === 'running'} team={overviewTeam} agents={agents} plan={topPlan} roots={threadRoots} - goal={selected.loopxInfo && !api.demo ? { close(); openGoal(goalId); }} /> : undefined} + goal={selected.loopxInfo && !api.demo ? goal.goalId === selected.loopxInfo?.goalId)} attention={loopxStatus?.attention.find(item => item.goalId === selected.loopxInfo?.goalId)} onChanged={goalsChanged} onExpandedChange={onGoalDetailsChange} threads={threads} onBrowseFiles={threadId => { if (!persistent) close(); setFilesThreadId(threadId); setFiles({ path: null, seq: ++filesSeq.current }); }} initiallyExpanded={goalDetailFocus?.api === api && goalDetailFocus.threadId === selected.id && goalDetailFocus.goalId === selected.loopxInfo.goalId} section={goalDetailFocus?.section ?? null} /> : undefined} loadFile={loadFile} persistent={persistent} onOpenMember={(member) => { setAgentsStart(member ?? null); setAgentsOpen(true); setFiles(null); }} onOpenDiff={(file) => setDiffFile({ threadId: selected.id, file })} + onOpenPicture={compact ? undefined : (path, name) => setPicture({ threadId: selected.id, path, name })} onOpenFile={async (path) => { if (/\.html?$/i.test(path)) setPreview({ threadId: selected.id, path }); else await openFileLink(path); @@ -2932,7 +3027,8 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } /> )} {/* The same picker, answering a Goal join instead of setting the draft's directory. */} - {goalDirAsk && ( + {goalDirAsk && createPortal( +
{ const ask = goalDirAsk; setGoalDirAsk(null); ask.resolve(cwd); }} onClose={() => { const ask = goalDirAsk; setGoalDirAsk(null); ask.resolve(null); }} /> +
, document.body )} {projectDialog === 'new' && ( openGoal(goalId, 'tasks')} - onOpenAllGoals={showcase ? undefined : () => openGoalsList()} + needsYouGoals={loopxNeedsYou} onOpenSchedules={showcase ? undefined : openSchedules} onOpenDesktop={hasDesktop ? () => { setDrawer(false); setDesktop('open'); } : undefined} desktopRunning={desktop === 'minimized'} schedulesActive={onSchedules} extensionNav={extensionNav} + draftKeys={draftKeys} notice={demo && compact ? showcase ? showcase.notice(selectedId, extWant) : : undefined} - footerNotice={authKind?.kind === 'link' && !showcase ? openSettings('access')} /> : undefined} + footerNotice={!showcase ? <> + openSettings('install')} /> + {authKind?.kind === 'link' && openSettings('access')} />} + : undefined} /> {!compact && !sidebarHidden && ( @@ -3042,9 +3140,9 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } {/* A conversation under way leans toward the middle of the screen, as in Codex; a new thread, and the pages, stay centred where they are. */} -
+
{compact && selected && !listOpen && !onPage && hostUp && ( - + )} {!onSettings &&
{/* In a member's thread the way back is to the thread that sent it, not to the list. */} @@ -3071,80 +3169,110 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase }
{/* Every page names itself here, the way a thread does: the bar is never left blank. */} {/* On a phone there is no room for the tag: the title itself opens where the thread runs. */} - {placeShown && !compact && } - {compact && placeShown ? ( - - ) : ( -
{host && !hostUp ? host.label : viewTitle ?? (selected ? (onRouterThread ? routerTitle : selected.title) : t('sidebar.newThread'))}
- )} - {selected?.coordination?.team &&
{selected.coordination.team.name} · {t(`teams.${selected.coordination.team.status}`)}
} - {!selected && host && hostUp &&
{host.label}
} - {busyLine && busyLine.threadId === selected?.id &&
{busyLine.message}
} - {atMember && ( - - )} +
+ {placeShown && !compact && } + {threadPending && !viewTitle && !compact && } + {compact && placeShown ? ( + + ) : ( +
{host && !hostUp ? host.label : viewTitle ?? (selected ? (onRouterThread ? routerTitle : selected.title) : threadPending ? '' : t('sidebar.newThread'))}
+ )} +
+ {!selected && !threadPending && host && hostUp &&
{host.label}
} +
+ {selected?.coordination?.team &&
{selected.coordination.team.name} · {t(`teams.${selected.coordination.team.status}`)}
} + {busyLine && busyLine.threadId === selected?.id &&
{busyLine.message}
} + {atMember && ( + + )} +
- {selected && ( -
+ {(selected || onSteward) && ( +
{/* The thread at a glance: one panel for the team, the plan, the changes, the pictures - and the files. The badge is only ever what needs the person. */} - {api && hostUp && (overviewDock ? ( + and the files. On the steward, quiet glass circles keep the chat unobstructed. */} + {(onSteward || api && hostUp) && (overviewDock ? ( ) : ( prepareOverview(api, selected.id, selected.updatedAt)} + prepare={onSteward ? undefined : () => prepareOverview(api!, selected!.id, selected!.updatedAt)} openSignal={overviewSignal} - triggerBusy={overviewLoading} - triggerClassName={`icon-btn topbar-overview${teamNeeds ? ' attention' : ''}`} + triggerBusy={overviewBusy} + triggerClassName={`icon-btn topbar-overview${overviewNeeds ? ' attention' : ''}`} triggerLabel={t('overview.label')} - triggerTitle={teamNeeds ? t('overview.needsYou', teamNeeds) : t('overview.label')} + triggerTitle={overviewNeeds ? t('overview.needsYou', overviewNeeds) : t('overview.label')} align="end" placement="below" panelClassName="overview-panel" - trigger={<>{teamNeeds > 0 && {teamNeeds}}} + suspendDismissal={onSteward && Boolean(goalDirAsk)} + trigger={<>{overviewNeeds > 0 && (onSteward ? ))} + {onSteward && !showcase && ( + + )} {/* A phone keeps its plan button: it has no margin card, and the lead's list of what leaves the bar was the desktop's. The overview has the plan too, one tap away. */} {compact && topPlan && !onPage && } - {compact && ( + {compact && selected && ( )} - -
- )} - {onSteward && !selected && ( -
- + }
)}
} @@ -3176,6 +3304,15 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } {demo && (showcase ? showcase.notice(selectedId, extWant) : )} + {modelLogin?.scope === api && openAgentLogin({ id: modelLogin.agent }, modelLogin.client)} onRecovered={list => { + modelVersions.current[modelLogin.key] = (modelVersions.current[modelLogin.key] ?? 0) + 1; + setModelsByAgent(previous => ({ ...previous, [modelLogin.key]: list })); + setModelLogin(current => current === modelLogin ? null : current); + void reloadAgents().catch(handleError); + }} />} + {error && (
{error} @@ -3209,7 +3346,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase }
) : onExt ? ( // An extension's view, behind a boundary of its own. Until the list is read, it is on its way. -
+
{extOpen && extInputs ? ( patchBoardThread(id, { done }).catch(error => { handleError(error); throw error; })} @@ -3300,57 +3437,43 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } onError={handleError} />
- ) : onGoal ? ( - // A document, not a conversation: starts at the top, like the other pages. -
- + loopxRead.reload()} - threads={threads} - onOpenThread={openThreadById} - onBrowseFiles={threadId => { setFilesThreadId(threadId); setFiles({ path: null, seq: ++filesSeq.current }); }} - defaultAgent={draftAgent || agents[0]?.id || 'codex'} - pickDirectory={pickGoalDir} + deferSessionOpen={Boolean(goalRequest || goalDetailFocus?.api === api && goalDetailFocus.threadId === null)} + waitingGoals={overviewShown ? [] : (loopxStatus?.goals ?? []) + .filter(goal => goal.activationState !== 'stopped' && loopxNeedsYou.has(goal.goalId)) + .map(goal => { + const att = loopxStatus?.attention.find(item => item.goalId === goal.goalId); + return { + goalId: goal.goalId, + title: goal.title, + summary: att?.topTodo?.text ?? att?.recommendedAction ?? att?.nextAction ?? null, + threadId: goalConversation(goal.goalId, threads)?.id ?? null, + }; + })} + onOpenGoal={(goalId) => openGoal(goalId)} + onOpenThread={pick} + onOpenGoalsOverview={() => { if (overviewDock) setStewardOverviewOpen(true); else setOverviewSignal(signal => signal + 1); }} />
- ) : onGoalsList ? ( -
- loopxRead.reload()} - /> -
- ) : onSteward ? ( -
- -
) : onActivity ? ( // The same document shape: days from the top, each conversation's asks under its name.
) : ( -
+
{selected && setJump({ threadId: selected.id, turnId })} />} - {selected && eventsLoading &&
{t('common.loading')}
} + {selected && eventsLoading && } {showcase && selected && !eventsLoading && !timeline.items.length && showcase.intro(selected.id)} {selected ? (
: undefined} laterOf={latestSegment ? thread => laterSegment(thread, latestSegment, threads) : undefined} onBrowseOlder={() => { stickToBottom.current = false; setAtBottom(false); }} canFork={thread => ({ enabled: Boolean(thread.agentSessionId && capsOf(thread.agent)?.fork), any: Boolean(capsOf(thread.agent)?.forkAt) })} @@ -3381,13 +3504,15 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } setNoteSignal({ draftKey: composerDraftKey, note: { id, quote, comment: '', nonce: Date.now(), ...(threadId && threadId !== selectedId ? { source: { threadId, turnId } } : {}) } }); }} onMessageContext={!demo && !voice.state.active && !writing ? async (text, turnId, threadId) => { - const draftKey = composerDraftKey; + const scope = composerScope; const source = await messageSnapshot(text, turnId, threadId); + if (composerScopeRef.current !== scope) return; const value = await api.createReference({ kind: 'message', ...source }); - setMessageReference({ draftKey, value, nonce: Date.now() }); + if (composerScopeRef.current === scope) setMessageReference({ scope, value, nonce: Date.now() }); } : undefined} onHandToAssistant={!demo ? async (text, turnId, threadId) => setAssistantMessage(await messageSnapshot(text, turnId, threadId)) : undefined} historyThreadId={selected.id} + historyTitle={selected.title} items={threadItems} revealTurnId={jump?.threadId === selected.id ? jump.turnId : undefined} roots={threadRoots} @@ -3405,9 +3530,9 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } if (known) { openThread(known); return; } if (api) void api.thread(id).then(openThread).catch(handleError); }} - // A message names another thread in passing; the link opens it like a pick in the list. + // Read a referenced conversation beside this one, keeping the draft and reading position. threads={threads} - onOpenThread={openThreadById} + onOpenThread={openReference} hasOlder={hasOlder} loadingOlder={loadingOlder} onLoadOlder={loadOlder} @@ -3491,16 +3616,18 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } note={noteSignal?.draftKey === composerDraftKey ? noteSignal.note : null} onNotesChange={onNotesChange} /> : void voice.stop()} /> : undefined} running={voice.state.active ? false : running} - disabled={modeBusy || (!selected && (!draftCwd || modelPreferences.status !== 'ready'))} + disabled={modeBusy} + sendDisabled={!selected && ((!draftCwd && !draftScratch) || modelPreferences.status !== 'ready')} placeholder={voice.state.active ? t('app.placeholder.continue') : onRouterThread && !running ? t('pet.threadPlaceholder') : demo ? t('app.placeholder.demo') : workMode === 'plan' && !running ? t('composerMenu.planOn') : writing && !running ? t('writing.placeholder') : selected ? (running ? t('sideChat.queuePlaceholder') : t('app.placeholder.continue')) : draftScratch ? t('app.placeholder.scratch') : t('app.placeholder.startIn', folderName(draftCwd))} onSend={voice.state.active ? async (text, images, _mentions, videos = []) => { try { await voice.appendText(text, images.map(img => ({ data: img.data, mimeType: img.mimeType })), await Promise.all(videos.map(async video => (await api.uploadVideo(selectedId!, video.file)).id))); } catch (error) { handleError(error); throw error; } } : send} - referenceSource={!demo && !voice.state.active ? { api, cwd: activeCwd, threadId: selected?.id } : undefined} - reference={messageReference?.draftKey === composerDraftKey ? messageReference : null} + referenceSource={!demo && !voice.state.active ? { api, cwd: activeCwd, threadId: selected?.id, sourceId: selected?.handover?.sourceId } : undefined} + reference={messageReference?.scope === composerScope ? messageReference : null} onReferenceConsumed={id => setMessageReference(current => current?.value.id === id ? null : current)} mentionOptions={collaborationOptions} mentionIcon={collaborationIcon} @@ -3517,7 +3644,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } onStop={stop} header={header} writingMode={draftTeam ? undefined : { active: !!writing, disabled: writingBusy, onChange: active => void changeWriting(active ? 'draft' : null) }} - takeover={outOfPlan && !voice.state.active ? { from: agentLabel(selected!.agent), current: selected!.agent, go: (agent, note) => threadActions.takeOver(selected!, agent, note) } : undefined} + takeover={outOfPlan && !voice.state.active ? { from: agentLabel(selected!.agent), current: selected!.agent, go: (agent, note, references) => threadActions.takeOver(selected!, agent, note, references) } : undefined} banner={<>{selected && !api.demo && drivenByApp(selected.loopxInfo, selected.origin) &&

{t('loopx.driven')}

}{writing && !draftTeam && void changeWriting(stage)} onEnd={() => void changeWriting(null)} onOpen={file => void openFileLink(file).catch(handleError)} habits={habitsPath ? { path: habitsPath, ready: habitsReady } : null} @@ -3563,6 +3690,8 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } note={noteSignal?.draftKey === composerDraftKey ? noteSignal.note : null} onNoteConsumed={consumeNote} onNotesChange={onNotesChange} + quoteSource={(threadId, turnId, sourceHost) => sourceHost === (hostId ?? null) && threadId !== selectedId && threads.some(thread => thread.id === threadId) + ? { threadId, turnId, elsewhere: true } : undefined} lastSent={selected ? lastSent : null} />} } @@ -3593,7 +3722,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } )}
)} - {activeOverviewDetail && overviewBody(closeOverviewDetail, true, activeOverviewDetail.section)} + {activeOverviewDetail && compact && overviewBody(closeOverviewDetail, true, activeOverviewDetail.section)}
{/* The overview standing beside the conversation: a layer of its own, put away only by the @@ -3604,11 +3733,33 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } )} - {agentsOpen && coordination && new Api(token ?? '', '', id)} team={coordination} agents={agents} memberModel={(thread) => { + {referenceId && setReferenceId(null)} onOpen={() => { setReferenceId(null); openThreadById(referenceId); }} + onChange={() => { void refreshThreads(); }} />} + {agentsOpen && coordination && new Api(token ?? '', '', id)} team={coordination} agents={agents} memberModel={(thread, part) => { const a = agents.find((v) => v.id === thread.agent); - return a ? { void api.updateThread(thread.id, { model, effort }).then(() => refreshThreads()).catch(handleError); }} + return a ? { void api.updateThread(thread.id, { model, effort }).then(() => refreshThreads()).catch(handleError); }} permission={a.capabilities.permissionModes.length ? thread.permissionMode : undefined} onPermission={(permissionMode) => { void api.updateThread(thread.id, { permissionMode }).then(() => refreshThreads()).catch(handleError); }} /> : null; - }} leadAgent={threads.find((t) => t.id === coordination.rootId)?.agent} phone={compact} onClose={() => setAgentsOpen(false)} onOpen={thread => { openThread(thread); setAgentsOpen(false); }} onAdjust={(name, draft) => { setAgentsOpen(false); setSelectedId(coordination.rootId); setRestore({ text: t('app.adjustTask', name) + draft, nonce: Date.now() }); }} onRefresh={() => { void refreshThreads(); }} onError={handleError} />} + }} leadAgent={threads.find((t) => t.id === coordination.rootId)?.agent} phone={compact} noteSignal={noteSignal} onNoteConsumed={consumeNote} onNotesChange={onNotesChangeFor} onClose={() => setAgentsOpen(false)} onOpen={thread => { openThread(thread); setAgentsOpen(false); }} onAdjust={(name, draft) => { setAgentsOpen(false); setSelectedId(coordination.rootId); setRestore({ text: t('app.adjustTask', name) + draft, nonce: Date.now() }); }} onRefresh={() => { void refreshThreads(); }} onError={handleError} />} + {activeOverviewDetail && !compact && } + {picture && api && !compact && picture.threadId === selected?.id && { setPicture(null); setOverviewDetail(null); }} onBack={activeOverviewDetail ? () => setPicture(null) : undefined} />} + {preview && api && { setPreview(null); if (!compact) setOverviewDetail(null); }} onBack={!compact && activeOverviewDetail ? () => setPreview(null) : undefined} docked={!compact} />} + {api && diffFile && diffFile.threadId === selected?.id && ( + setDiffFile(null) : undefined} + onClose={() => { setDiffFile(null); if (!compact) setOverviewDetail(null); }} + onJumpTurn={(turnId) => { setDiffFile(null); setJump({ threadId: diffFile.threadId, turnId }); }} + /> + )} {files && filesThread && api && setFiles(null)} />} {gitOpen && selected && api && setGitOpen(false)} />} {traceOpen && selected && ( @@ -3621,22 +3772,20 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } onClose={() => setTraceOpen(false)} /> )} - - {preview && api && ( - setPreview(null)} onError={handleError} /> - )} - {desktop !== 'closed' && ( -