diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 4c4948c346..a7f1e74ada 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -56,7 +56,6 @@ /tests/ @huangruiteng @songoow @loopx-agent /scripts/ @huangruiteng @songoow @loopx-agent /demo/ @huangruiteng @songoow @loopx-agent -/deprecate/ @huangruiteng @songoow @loopx-agent # --- Subsystem routes -------------------------------------------------------- diff --git a/.github/workflows/ark-turn.yml b/.github/workflows/ark-turn.yml index 5a6cfc6295..bef2e62448 100644 --- a/.github/workflows/ark-turn.yml +++ b/.github/workflows/ark-turn.yml @@ -29,7 +29,7 @@ concurrency: jobs: adapter-contract: runs-on: ubuntu-latest - timeout-minutes: 10 + timeout-minutes: 15 strategy: matrix: python: ["3.11", "3.13"] diff --git a/.github/workflows/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..1b67e421f1 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: @@ -256,13 +296,23 @@ jobs: # nullglob, Bash passes the unmatched pattern to `gh`, which exits # before the feed and channel pointer are published. shopt -s nullglob + channel_action="$(python - <<'PY' + from loopx.cli_commands.update_artifact import PUBLIC_DEFAULT_CONTRACT, public_channel_allows_default + + print("promote" if public_channel_allows_default(PUBLIC_DEFAULT_CONTRACT) else "hold") + PY + )" 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" done gh release upload "$RELEASE_TAG" dist/updater/desktop-updater.json --clobber + if [ "$channel_action" != promote ]; then + echo "::notice title=Desktop channel retained::The candidate's default contract is pending public channel qualification." + exit 0 + fi # Channel pointers are independent of repository Latest, which also # serves separately versioned plugin releases. Advance only after the # immutable signed assets and feed are completely uploaded. @@ -272,7 +322,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..6029397d9d 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,7 +32,7 @@ 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: @@ -47,7 +47,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 +70,38 @@ 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: | + set +e + npm publish "$DSH_ARTIFACT" --access public --tag latest --ignore-scripts --provenance + rc=$? + set -e + if [ "$rc" -ne 0 ]; then + 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 - 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 + node scripts/verify-distribution.mjs --tarball "$DSH_ARTIFACT" diff --git a/.github/workflows/frontstage-pages.yml b/.github/workflows/frontstage-pages.yml index 80e1783366..0ef56a9f1d 100644 --- a/.github/workflows/frontstage-pages.yml +++ b/.github/workflows/frontstage-pages.yml @@ -12,6 +12,7 @@ on: - ".github/workflows/frontstage-pages.yml" - "README.md" - "README.zh-CN.md" + - "README.ja.md" - "apps/presentation/dashboard/**" - "scripts/chat_bundle.py" - "scripts/chat_bundle_launcher.mjs" @@ -56,6 +57,7 @@ on: - ".github/workflows/frontstage-pages.yml" - "README.md" - "README.zh-CN.md" + - "README.ja.md" - "apps/presentation/dashboard/**" - "scripts/chat_bundle.py" - "scripts/chat_bundle_launcher.mjs" diff --git a/.github/workflows/full-public-smokes.yml b/.github/workflows/full-public-smokes.yml index 8b2e68dd92..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: @@ -148,7 +148,7 @@ jobs: retention-days: 7 smoke-fleet-health: - if: always() + if: always() && github.repository == 'loopx-project/loopx' needs: full-public-smokes runs-on: ubuntu-latest timeout-minutes: 10 diff --git a/.github/workflows/package-smoke.yml b/.github/workflows/package-smoke.yml index d130915e13..cd0f1efaa8 100644 --- a/.github/workflows/package-smoke.yml +++ b/.github/workflows/package-smoke.yml @@ -47,7 +47,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 @@ -91,7 +91,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/python-tests.yml b/.github/workflows/python-tests.yml index f6329b30dc..61af7e764f 100644 --- a/.github/workflows/python-tests.yml +++ b/.github/workflows/python-tests.yml @@ -168,7 +168,7 @@ jobs: python-version: "3.11" - name: Install checkout for Python-backed browser scenarios run: | - python -m pip install --disable-pip-version-check -e . + python -m pip install --disable-pip-version-check -e '.[test]' echo "LOOPX_TEST_PYTHON=$(python -c 'import sys; print(sys.executable)')" >> "$GITHUB_ENV" - uses: actions/setup-node@v6 with: @@ -192,7 +192,9 @@ jobs: npm run smoke:chat-upgrade npm run smoke:delegation-search npm run smoke:task-inspector-route + npm run smoke:explore-timeline-scan npm run smoke:conversation-find + node smoke/todo-confirmation-browser-smoke.mjs - name: Qualify packaged team evidence and feedback recovery if: matrix.shard == 2 working-directory: apps/presentation/dashboard diff --git a/.github/workflows/runtime-snapshots.yml b/.github/workflows/runtime-snapshots.yml index 88c7948c24..c5e5d196d4 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" @@ -79,6 +80,7 @@ jobs: permissions: contents: write steps: + - uses: actions/checkout@v7 - uses: actions/download-artifact@v7 with: name: loopx-runtime @@ -89,12 +91,38 @@ jobs: shell: bash run: | set -euo pipefail - revision="$(python -c 'import json; print(json.load(open("runtime/loopx-runtime.json"))["source_revision"])')" + # Validate the downloaded qualification before any remote mutation. + # Successful installation alone does not qualify outcome/cost claims. + publication="$(python - <<'PY' + import json + from pathlib import Path + import sys + sys.path.insert(0, str(Path.cwd())) + from loopx.cli_commands.update_artifact import ( + public_channel_allows_default, validate_published_manifest, verify_runtime_installation_qualification, + ) + root = Path("runtime") + manifest_bytes = (root / "loopx-runtime.json").read_bytes() + manifest = validate_published_manifest(json.loads(manifest_bytes)) + revision = manifest["source_revision"] + qualification = json.loads((root / f"qualification-{revision}.json").read_bytes()) + archive = root / f"loopx-runtime-{revision}.tar.gz" + 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") + channel_action = "promote" if public_channel_allows_default(manifest["default_contract"]) else "hold" + print(revision, channel_action) + PY + )" + read -r revision channel_action <<< "$publication" + # Only main revisions may be published, even when the channel is held. + 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 @@ -109,10 +137,10 @@ 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 [[ "$channel_action" != promote ]]; then + echo "::notice title=Runtime channel retained::The candidate's default contract is pending public channel qualification." + exit 0 + 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/.gitignore b/.gitignore index de759d548c..96b5096168 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,6 @@ .venv/ .idea node_modules/ -apps/dashboard/public/*.local.json apps/presentation/dashboard/public/*.local.json __pycache__/ *.pyc diff --git a/AGENTS.md b/AGENTS.md index 5948b2603b..7f4891e1d2 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 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a75a60c2b3..b772c03d17 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -127,7 +127,8 @@ LoopX needs two runtimes: - **Python 3.11+.** `uv` installs a compatible one for you. - **Node.js 22.22.3 or newer**, with Node.js 24 LTS recommended. `pyproject.toml` - declares no Python dependencies, but the TypeScript control plane runs on the + declares no cross-platform Python dependencies (only `tzdata; sys_platform == 'win32'`), + but the TypeScript control plane runs on the system Node.js, both for `loopx` itself and for the test suite. `pip` and `uv` cannot install Node.js for you. @@ -193,7 +194,7 @@ touch, mention it in the PR instead of fixing it there. | `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` | extension package paths | no | extension packages install, entrypoints, and example schemas | +| `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 | | `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 | @@ -203,7 +204,7 @@ touch, mention it in the PR instead of fixing it there. | `frontstage-pages.yml` | README, dashboard, and chat bundle paths | no | public Pages build | | `desktop-release-artifacts.yml` | desktop app and dashboard paths | no | macOS and Windows desktop builds | | `desktop-updater.yml` | desktop app paths | no | desktop app build and updater feed | -| `full-public-smokes.yml` | no (push to `main`, schedule) | no | every public smoke, in shards | +| `full-public-smokes.yml` | no (manual, schedule) | no | every public smoke, in shards | | `sonarcloud.yml` | no (called by Python Tests) | no | SonarCloud analysis of that run's coverage | | `stale.yml` | no (schedule) | no | stale-issue reminders (never closes issues) | | `update-notes.yml` | no (schedule) | no | biweekly update notes | diff --git a/README.ja.md b/README.ja.md new file mode 100644 index 0000000000..8382eccc47 --- /dev/null +++ b/README.ja.md @@ -0,0 +1,976 @@ +
+ +

LoopX 2.0

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

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

+

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

+ +## Star の推移 + +

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

+ +## ライセンス + +Copyright 2026 LoopX contributors. 作者は +[`@huangruiteng`](https://github.com/huangruiteng) です。公開されている +[作者とコントリビューターの記録](docs/project/authors.md)をご覧ください。 + +`v0.4.8` 以降は Apache License 2.0 です。[LICENSE](LICENSE) と +[NOTICE](NOTICE) をご覧ください。`v0.4.7` までのリリースは、元の MIT の +条件のままです。その歴史的なテキストと告知は +[LICENSE-MIT](LICENSE-MIT) に保存されています。[ライセンスポリシー](docs/project/licensing.md)では、 +バージョン、コントリビューション、特許許諾、オープンコアの範囲について説明しています。 + +AI による生成、コードの書き換え、言語間の翻訳、 +プロジェクト名の変更を根拠に、適用されるライセンスの下での著作権、帰属表示、 +NOTICE の保持の要件を削除したり回避したりしてはなりません。配布される +素材が LoopX の派生物である場合、それらの義務は引き続き適用されます。この +説明は、適用されるライセンスで許可されている改変や再配布を制限するものではありません。[再利用と帰属表示](docs/project/licensing.md#reuse-ports-and-attribution) +と[名称と商標のガイダンス](docs/project/trademarks.md)をご覧ください。派生物の +配布物を LoopX の公式リリースとして提示してはなりません。 + +[osai-verify: eb42dd9cf910399988f0]: # diff --git a/README.md b/README.md index bbdcd18b88..2a7a15f16e 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ **Start with one goal. Keep long-running agent work verifiable.** -Tell the Agent you already use what you want done. LoopX preserves goals, +Tell your agent what you want to accomplish. LoopX preserves goals, progress, decisions and verifiable results so work can continue across sessions.
An open, harness-neutral control plane for 24/7 always-on agents across Codex, Claude Code, DeepSeek Harness and other runtimes—scaling from local SQLite workflows to multi-agent teams. @@ -14,10 +14,14 @@ progress, decisions and verifiable results so work can continue across sessions. [![Local-first state](https://img.shields.io/badge/local--first-state-brightgreen.svg)](docs/public-private-boundary.md) [![Loop Agents](https://img.shields.io/badge/status-loop%20agents%20supported-brightgreen.svg)](docs/product/release-readiness.md) [![GitHub contributors](https://img.shields.io/github/contributors-anon/loopx-project/loopx?color=blue)](https://github.com/loopx-project/loopx/graphs/contributors) [![Discord](https://img.shields.io/badge/Discord-Join-5865F2?logo=discord&logoColor=white)](https://discord.gg/XmGgQyCFZd) [![Listed on dsh-plugin.org](https://dsh-plugin.org/badges/listed.svg)](https://dsh-plugin.org/plugins/loopx-project/loopx) -[Get started](#quick-start) · [Why LoopX](#why-loopx) · [24/7 Always-On](#always-on-agents) · [See it in action](#see-loopx-in-action) · [Evidence](#evidence) · [Contribute](#contributing) · [Docs](https://loopx-project.github.io/loopx/docs/) · [简体中文](README.zh-CN.md) +[Get started](#quick-start) · [Why LoopX](#why-loopx) · [24/7 Always-On](#always-on-agents) · [See it in action](#see-loopx-in-action) · [Evidence](#evidence) · [Contribute](#contributing) · [Docs](https://loopx-project.github.io/loopx/docs/) · [简体中文](README.zh-CN.md) · [日本語](README.ja.md) +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).

+ --- @@ -53,7 +57,7 @@ run? [Choose a task below](#try-loopx). not news. Keep both languages aligned, newest first, using verified publication dates (UTC). --> -- **2026-11-01 · 📘 [Progressive context delivery for 24/7 agents](https://loopx-project.github.io/loopx/blog/context-delivery/)** — Compaction-cycle structured deltas and progressive views cut control-plane bytes across 213 model-facing wakes (`32.5%` single-layer progressive view; `3.0%` body / `5.0%` CLI stacked first-read entry across 112 in-cycle continuations) while preserving lossless baseline recovery ([47-day freshness postmortem](https://loopx-project.github.io/loopx/blog/five-freshness-incidents/)). +- **2026-11-01 · 📘 [Progressive context delivery for 24/7 agents](https://loopx-project.github.io/loopx/blog/context-delivery/)** — Compaction-cycle structured deltas and progressive views cut control-plane bytes across 213 model-facing wakes (`32.5%` single-layer progressive view; `3.0%` body / `5.0%` CLI stacked first-read entry across 112 in-cycle continuations) while preserving lossless baseline recovery. - **2026-10-25 · 🤝 [Long-horizon agent research: collaborators welcome](https://loopx-project.github.io/loopx/blog/edgebench-feedback-and-memory/)** — Exploring **breakthroughs in long-horizon outcomes under equal budgets**, through feedback, replanning and reproducible evaluation on EdgeBench and real-world tasks. Academic labs and industry teams are welcome to collaborate, comparing outcomes and total cost. [Discuss collaboration](https://github.com/loopx-project/loopx/discussions). - **2026-10-20 · 🚀 [LoopX 2.0](https://github.com/loopx-project/loopx/releases/tag/v2.0.0)** — A shared TypeScript state layer and long-horizon research workbench. [Migration guide](docs/product/releases/v2.0.0.md) · [Engineering story](https://loopx-project.github.io/loopx/blog/typescript-control-plane-refactor/). - **2026-10-14 · 🤖 [Agentic software](https://loopx-project.github.io/loopx/blog/semantic-software-development/)** — Connecting goals, evidence and human feedback to engineering delivery. @@ -163,7 +167,7 @@ operate 24/7 with explicit durability and human gates: | --- | --- | --- | | **Event Inbox** | Single-flight **Goal / Todo / Hard Lease** queue, async app inbox, and connected Lark / GitHub listeners | Duplicate workers mutating the same repo state; dropped human inputs mid-run | | **Timers & Wakeups** | **Guarded Heartbeat** and safe recurring presets (`daily-triage`, `changelog-draft`, `pr-watch`; inspect via `loopx preset list`) | Blind cron loops burning tokens when nothing changed or a gate is still waiting on a human | -| **Memory & Compaction** | [`Decision Context`](loopx/capabilities/decision_context/README.md) source tracking, compaction-cycle **Progressive + Delta** [`context_delivery`](https://loopx-project.github.io/loopx/blog/context-delivery/) (`32.5%` view across 213 wakes; `3.0% / 5.0%` first-read entry across 112 in-cycle wakes), and optional [`Reward Memory`](loopx/capabilities/reward_memory/README.md) | Silent source staleness ([5 incidents across 253 turns / 47 days](https://loopx-project.github.io/loopx/blog/five-freshness-incidents/)); compounding prompt replay or broken deltas across compaction | +| **Memory & Compaction** | [`Decision Context`](loopx/capabilities/decision_context/README.md) source tracking, compaction-cycle **Progressive + Delta** [`context_delivery`](https://loopx-project.github.io/loopx/blog/context-delivery/) (`32.5%` view across 213 wakes; `3.0% / 5.0%` first-read entry across 112 in-cycle wakes), and optional [`Reward Memory`](loopx/capabilities/reward_memory/README.md) | Silent source staleness; compounding prompt replay or broken deltas across compaction | | **Permissions & Deferred Calls** | Explicit **owner, safety, publication, and private-data gates**, isolated worktrees, and review-ready handoffs | Autonomous cron runs publishing externally, forcing merges, or leaking private context | | **Outbox** | Shared Workspace & Lark Goal/Decision/Evidence views surfacing genuine completions, blockers, and open gates | Fragmented terminal logs and high-noise pings that force humans to babysit runs | @@ -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 @@ -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 ed24b4d2ba..ee67ed5cb2 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -14,10 +14,14 @@ [![Local first](https://img.shields.io/badge/control--plane-local--first-brightgreen.svg)](docs/public-private-boundary.md) [![Loop Agents](https://img.shields.io/badge/status-loop%20agents%20supported-brightgreen.svg)](docs/product/release-readiness.md) [![GitHub contributors](https://img.shields.io/github/contributors-anon/loopx-project/loopx?color=blue)](https://github.com/loopx-project/loopx/graphs/contributors) [![Discord](https://img.shields.io/badge/Discord-Join-5865F2?logo=discord&logoColor=white)](https://discord.gg/XmGgQyCFZd) [![Listed on dsh-plugin.org](https://dsh-plugin.org/badges/listed.svg)](https://dsh-plugin.org/plugins/loopx-project/loopx) -[快速上手](#快速开始) · [为什么需要 LoopX](#为什么需要-loopx) · [7×24 常驻架构](#always-on-agents) · [看看实际使用](#看看-loopx-如何工作) · [证据与案例](#证据) · [参与贡献](#贡献) · [文档](https://loopx-project.github.io/loopx/docs/) · [English](README.md) +[快速上手](#快速开始) · [为什么需要 LoopX](#为什么需要-loopx) · [7×24 常驻架构](#always-on-agents) · [看看实际使用](#看看-loopx-如何工作) · [证据与案例](#证据) · [参与贡献](#贡献) · [文档](https://loopx-project.github.io/loopx/docs/) · [English](README.md) · [日本語](README.ja.md) +https://github.com/user-attachments/assets/eeb95ecd-6e5b-43d7-a8aa-b3d1b4449423 + +

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

+ --- @@ -50,7 +54,7 @@ LoopX 会按需把它变成可见的任务、决策门和证据。Claude Code not news. Keep both languages aligned, newest first, using verified publication dates (UTC). --> -- **2026-11-01 · 📘 [面向 7×24 Agent 的渐进式上下文交付](https://loopx-project.github.io/loopx/blog/zh/context-delivery/)** — 受 Compaction 周期约束的结构化差分与按需视图在 213 次模型唤醒中将单层渐进载荷降至原文 `32.5%`,112 次同周期续跑的叠加首读入口降至 `3.0%` 正文 / `5.0%` 含封装,同时保留压缩失配时原子回切完整基线的能力(延伸阅读:[47 天保鲜事故复盘](https://loopx-project.github.io/loopx/blog/zh/five-freshness-incidents/))。 +- **2026-11-01 · 📘 [面向 7×24 Agent 的渐进式上下文交付](https://loopx-project.github.io/loopx/blog/zh/context-delivery/)** — 受 Compaction 周期约束的结构化差分与按需视图在 213 次模型唤醒中将单层渐进载荷降至原文 `32.5%`,112 次同周期续跑的叠加首读入口降至 `3.0%` 正文 / `5.0%` 含封装,同时保留压缩失配时原子回切完整基线的能力。 - **2026-10-25 · 🤝 [长程 Agent 研究:欢迎学术与企业合作者](https://loopx-project.github.io/loopx/blog/zh/edgebench-feedback-and-memory/)** — 探索**等预算下的长期效果突破**:围绕 EdgeBench 和真实长程任务,研究反馈、重规划与可复现评测,同时核对效果与完整成本。欢迎学术与企业团队合作。[交流合作](https://github.com/loopx-project/loopx/discussions)。 - **2026-10-20 · 🚀 [LoopX 2.0](https://github.com/loopx-project/loopx/releases/tag/v2.0.0)** — 共享 TypeScript 控制面与长程研究工作台。[迁移指南](docs/product/releases/v2.0.0.md#中文指南) · [重构历程](https://loopx-project.github.io/loopx/blog/zh/typescript-control-plane-refactor/)。 - **2026-10-14 · 🤖 [Agentic Software](https://loopx-project.github.io/loopx/blog/zh/semantic-software-development/)** — 连接目标、证据、人的反馈与工程交付。 @@ -94,8 +98,7 @@ LoopX 把长期控制状态留在同一层紧凑状态里: Agent runtime 负责执行,LoopX 负责治理跨运行延续的控制状态,让工程、 -研究、discovery 和运营 Loop 能持续推进。它不是又一个 agent framework,也不是 -绑定某一 Provider 的编排 runtime。 +研究、discovery 和运营 Loop 能持续推进。 @@ -140,7 +143,7 @@ LoopX 把这套**开源、Harness 中立**的控制面直接做成可运行基 | --- | --- | --- | | **Event Inbox(事件收件箱)** | Single-flight **Goal / Todo / Hard Lease** 队列、异步对话收件箱,以及飞书 / GitHub 事件监听 | 多 Worker 并发踩踏同一份仓库状态;运行中途用户消息丢失 | | **Timers(定时与唤醒)** | **Guarded Heartbeat** 与安全周期预设(`daily-triage`、`changelog-draft`、`pr-watch`,可用 `loopx preset list` 只读查看) | 盲目 cron 在零增量或人门尚未批准时反复唤醒模型白烧 Token | -| **Memory(记忆与压缩恢复)** | [`Decision Context`](loopx/capabilities/decision_context/README.md) 来源追踪、受 Compaction 周期约束的 **Progressive + Delta** [`context_delivery`](https://loopx-project.github.io/loopx/blog/zh/context-delivery/)(213 次唤醒中单层渐进降至原文 `32.5%`,112 次同周期续跑首读降至原文 `3.0% / 5.0%`),以及可选 [`Reward Memory`](loopx/capabilities/reward_memory/README.md) | 数据源过期却一路亮绿灯([47 天 / 253 轮中的 5 次保鲜事故](https://loopx-project.github.io/loopx/blog/zh/five-freshness-incidents/));上下文压缩后全量重放或差分悬空 | +| **Memory(记忆与压缩恢复)** | [`Decision Context`](loopx/capabilities/decision_context/README.md) 来源追踪、受 Compaction 周期约束的 **Progressive + Delta** [`context_delivery`](https://loopx-project.github.io/loopx/blog/zh/context-delivery/)(213 次唤醒中单层渐进降至原文 `32.5%`,112 次同周期续跑首读降至原文 `3.0% / 5.0%`),以及可选 [`Reward Memory`](loopx/capabilities/reward_memory/README.md) | 数据源过期却一路亮绿灯;上下文压缩后全量重放或差分悬空 | | **Permissions(权限与延后批准)** | 显式 **Owner / 安全 / 公开发布 / 私有数据 Gate**、隔离 Worktree 与可评审交付交接 | 定时任务在无人确认时私自对外发布、强行合并或越界读写 | | **Outbox(低噪成果回传)** | 本地工作区与飞书共享同一份 Goal / 决策 / 证据视图,仅在真正完成、阻塞或待决时打扰人类 | 碎片化终端日志与各端高频无效推送,避免人肉盯盘 | @@ -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 dc3df5bb77..e119a4b9f4 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. @@ -449,6 +464,13 @@ directly in Research after a normal quit and a loopback-port change. Window close/reopen, an explicit return to Manager and a corrupt preference were also checked. It does not demonstrate model execution or an official App upgrade. +Within a local Goal's Research view, the preference also retains an explicit +case/history choice, selected registered analysis pack and chapter or citation +bookmark. The dashboard rechecks the pack and source when reopening. A missing +or inaccessible pack keeps its existing reader recovery path. The bookmark +must match the selected pack and the dashboard's chapter grammar. Existing +version-1 preferences without research selections continue to open as before. + ![Packaged QA reopening the same synthetic Goal in Research](docs/assets/research-reopen-qa.jpg) For native qualification, use a separately identified packaged App with the @@ -492,11 +514,13 @@ 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. 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 @@ -506,10 +530,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 @@ -817,8 +876,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..af66a0f9b2 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,63 @@ //! 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 ARTIFACT_DEFAULT_CONTRACTS: &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( + channel: &str, + version: &str, + verified_bytes: &[u8], +) -> Result<(), String> { + // Historical stable bundles predate the attestation and remain usable. + // A preview stays subject to the check even if cache metadata changes channel. + if channel != "main" + && !semver::Version::parse(version) + .is_ok_and(|value| value.pre.as_str().starts_with("main.")) + { + return Ok(()); + } + let invalid = "runtime_bundle_invalid"; + let unavailable = "update_platform_unavailable"; + let supported: Value = serde_json::from_str(ARTIFACT_DEFAULT_CONTRACTS).map_err(|_| invalid)?; + let current = supported.get("current").ok_or(invalid)?; + let historical = supported.get("historical").ok_or(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 != current && observed != historical { + 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 +182,58 @@ mod tests { builder.into_inner().unwrap().finish().unwrap() } + #[test] + fn only_qualified_preview_can_replace_the_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 version = "0.0.0-main.2.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": "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); + assert_eq!( + crate::prepared_update::save(&cache, "main", version, "unused", &bytes), + Err("update_platform_unavailable".into()) + ); + assert!(!cache.exists()); + assert_eq!( + qualify_candidate("stable", version, &bytes), + Err("update_platform_unavailable".into()) + ); + assert!(qualify_candidate("stable", "2.3.0", &bytes).is_ok()); + } + + let qualified: Value = serde_json::from_str(ARTIFACT_DEFAULT_CONTRACTS).unwrap(); + for contract in ["historical", "current"] { + identity["default_contract"] = qualified[contract].clone(); + fs::write(&identity_path, identity.to_string()).unwrap(); + let bytes = archive(&candidate); + crate::prepared_update::save(&cache, "main", version, "unused", &bytes).unwrap(); + } + let pointer = fs::read(cache.join("prepared.json")).unwrap(); + assert!(crate::prepared_update::save(&cache, "main", version, "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..e94f056365 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,27 @@ 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")] + { + let version = update.version.clone(); + let channel = channel.to_owned(); + tauri::async_runtime::spawn_blocking(move || { + crate::macos_update::qualify_candidate(&channel, &version, &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/prepared_update.rs b/apps/desktop/loopx-control-plane/src-tauri/src/prepared_update.rs index 2085a3ba7a..07e596e2a1 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(channel, version, 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(channel, version, &bytes)?; Ok(Some(PreparedUpdate { version: version.into(), signature: value["signature"].as_str().ok_or(INVALID)?.into(), 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/desktop/loopx-control-plane/src-tauri/src/workspace_location.rs b/apps/desktop/loopx-control-plane/src-tauri/src/workspace_location.rs index 2a17e5ae6d..3171e602e3 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/workspace_location.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/workspace_location.rs @@ -15,6 +15,66 @@ struct LocalWorkspace { view: Option, work_agent: Option, todo: Option, + research: Option, +} + +/// Selection within the existing dashboard reader, scoped to this local Goal. +#[derive(Debug, PartialEq)] +struct ResearchReading { + mode: String, + pack_id: Option, + chapter: Option, +} + +fn digest_id(value: &str) -> bool { + value.len() == 64 + && value + .bytes() + .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) +} + +impl ResearchReading { + fn selections(mode: &str, pack: &str, chapter: &str) -> Option { + if !matches!(mode, "case" | "history") { + return None; + } + let pack_id = digest_id(pack).then(|| pack.to_owned()); + // The frontend resolves this bookmark against the saved study. Carry + // only its declared chapter/citation grammar, never an arbitrary URL. + let chapter = pack_id.as_deref().and_then(|pack| { + let body = chapter.strip_prefix("case-section-")?; + let prefix = format!("{pack}-"); + let section = body.strip_prefix(&prefix).or_else(|| { + let (namespace, rest) = body.split_once('-')?; + digest_id(namespace).then_some(rest)?.strip_prefix(&prefix) + })?; + let (id, citation) = match section.split_once('~') { + Some((id, ordinal)) => (id, Some(ordinal)), + None => (section, None), + }; + let valid_id = id.len() <= 80 + && id + .bytes() + .all(|c| c.is_ascii_alphanumeric() || b"_-".contains(&c)) + && (!id.is_empty() || citation.is_some()); + let valid_citation = citation.is_none_or(|ordinal| { + ordinal.len() <= 2 + && !ordinal.starts_with('0') + && ordinal.bytes().all(|c| c.is_ascii_digit()) + && !ordinal.is_empty() + }); + (mode == "case" && valid_id && valid_citation).then(|| chapter.to_owned()) + }); + Some(Self { + mode: mode.to_owned(), + pack_id, + chapter, + }) + } + + fn value(&self) -> Value { + json!({"mode": self.mode, "pack_id": self.pack_id, "chapter": self.chapter}) + } } // Match the existing Goal instance ID and frontend Agent/Todo search boundary. @@ -44,6 +104,7 @@ impl LocalWorkspace { .then(|| view.to_owned()), work_agent: selection_id(agent), todo: selection_id(todo), + research: None, }) } @@ -71,7 +132,23 @@ impl LocalWorkspace { // authority. Reopening that unsupported context returns Manager. return Some(Self::default()); } - Self::selections(get("goalId"), get("view"), get("workAgent"), get("todo")) + let mut selection = + Self::selections(get("goalId"), get("view"), get("workAgent"), get("todo"))?; + if selection.view.as_deref() == Some("research") + && get("research_goal") == selection.goal_id + { + let pack = if get("research_analysis_goal") == selection.goal_id { + get("research_pack") + } else { + "" + }; + selection.research = ResearchReading::selections( + get("research_reading"), + pack, + current.fragment().unwrap_or(""), + ); + } + Some(selection) } fn destination(&self, origin: &Url) -> Url { @@ -90,7 +167,20 @@ impl LocalWorkspace { query.append_pair(key, value); } } + if let Some(research) = &self.research { + query.append_pair("research_goal", &self.goal_id); + query.append_pair("research_reading", &research.mode); + if let Some(pack) = &research.pack_id { + query.append_pair("research_analysis_goal", &self.goal_id); + query.append_pair("research_pack", pack); + } + } drop(query); + destination.set_fragment( + self.research + .as_ref() + .and_then(|research| research.chapter.as_deref()), + ); destination } @@ -98,17 +188,30 @@ impl LocalWorkspace { if value["version"] != 1 { return None; } - Self::selections( + let mut selection = Self::selections( value["goal_id"].as_str()?, value["view"].as_str().unwrap_or(""), value["work_agent"].as_str().unwrap_or(""), value["todo"].as_str().unwrap_or(""), - ) + )?; + if !selection.goal_id.is_empty() && selection.view.as_deref() == Some("research") { + let research = &value["research"]; + selection.research = ResearchReading::selections( + research["mode"].as_str().unwrap_or(""), + research["pack_id"].as_str().unwrap_or(""), + research["chapter"].as_str().unwrap_or(""), + ); + } + Some(selection) } fn value(&self) -> Value { - json!({"version": 1, "goal_id": self.goal_id, "view": self.view, - "work_agent": self.work_agent, "todo": self.todo}) + let mut value = json!({"version": 1, "goal_id": self.goal_id, "view": self.view, + "work_agent": self.work_agent, "todo": self.todo}); + if let Some(research) = &self.research { + value["research"] = research.value(); + } + value } } @@ -211,6 +314,124 @@ mod tests { format!("http://127.0.0.1:{port}/chat/").parse().unwrap() } + fn research_page(port: u16) -> Url { + let mut page = origin(port); + page.query_pairs_mut().extend_pairs([ + ("goalId", "example"), + ("view", "research"), + ("research_goal", "example"), + ("research_reading", "case"), + ("research_analysis_goal", "example"), + ("research_pack", &"a".repeat(64)), + ]); + page + } + + #[test] + fn research_reopen_keeps_registered_pack_and_chapter_or_citation_on_the_new_port() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("workspace-location.json"); + for namespace in [String::new(), format!("{}-", "b".repeat(64))] { + for section in ["turning-point", "turning-point~2", "~1"] { + let mut page = research_page(49123); + let chapter = format!("case-section-{namespace}{}-{section}", "a".repeat(64)); + page.set_fragment(Some(&chapter)); + let saved = LocalWorkspace::capture(&page, &origin(49123)).unwrap(); + write(&path, &saved).unwrap(); + let reopened = read(&path).unwrap().destination(&origin(59234)); + assert_eq!(reopened.port(), Some(59234)); + let reopened_query = reopened + .query_pairs() + .into_owned() + .collect::>(); + for (key, value) in page.query_pairs().into_owned() { + assert_eq!(reopened_query.get(&key), Some(&value)); + } + assert_eq!(reopened.fragment(), Some(chapter.as_str())); + let bytes = fs::read_to_string(&path).unwrap(); + assert!(!bytes.contains("49123") && !bytes.contains("http")); + assert_eq!(read(&path), Some(saved)); + } + } + } + + #[test] + fn research_selections_stay_with_their_goal_view_and_pack() { + let mut page = research_page(49123); + page.set_fragment(Some(&format!( + "case-section-{}-turning-point", + "a".repeat(64) + ))); + for (key, value) in [ + ("goalId", "other"), + ("view", "tasks"), + ("research_goal", "other"), + ] { + let mut changed = page.clone(); + let pairs = changed + .query_pairs() + .into_owned() + .map(|(k, v)| { + let v = if k == key { value.to_owned() } else { v }; + (k, v) + }) + .collect::>(); + changed.query_pairs_mut().clear().extend_pairs(pairs); + assert!(LocalWorkspace::capture(&changed, &origin(49123)) + .unwrap() + .research + .is_none()); + } + for pack in ["wrong", &"c".repeat(64)] { + let mut changed = page.clone(); + changed.query_pairs_mut().clear().extend_pairs([ + ("goalId", "example"), + ("view", "research"), + ("research_goal", "example"), + ("research_reading", "case"), + ("research_analysis_goal", "other"), + ("research_pack", pack), + ]); + let saved = LocalWorkspace::capture(&changed, &origin(49123)).unwrap(); + let research = saved.research.unwrap(); + assert!(research.pack_id.is_none() && research.chapter.is_none()); + } + let history = + ResearchReading::selections("history", &"a".repeat(64), page.fragment().unwrap()) + .unwrap(); + assert_eq!(history.mode, "history"); + assert!(history.chapter.is_none()); + assert!(ResearchReading::selections("retired", "", "").is_none()); + } + + #[test] + fn invalid_bookmarks_and_unrelated_preference_fields_are_not_restored() { + let pack = "a".repeat(64); + for chapter in [ + "https://example.org/secret".to_owned(), + format!("case-section-{}-chapter", "c".repeat(64)), + format!("case-section-{pack}-../secret"), + format!("case-section-{pack}-chapter~0"), + format!("case-section-{pack}-chapter~01"), + format!("case-section-{pack}-chapter~100"), + format!("case-section-{pack}-{}", "x".repeat(81)), + ] { + assert!(ResearchReading::selections("case", &pack, &chapter) + .unwrap() + .chapter + .is_none()); + } + let legacy = json!({"version": 1, "goal_id": "example", "view": "research"}); + let saved = LocalWorkspace::from_value(&legacy).unwrap(); + assert!(saved.research.is_none()); + let mut modified = legacy; + modified["research"] = json!({"mode": "case", "pack_id": pack, "chapter": "secret", "url": "https://example.org"}); + let restored = LocalWorkspace::from_value(&modified).unwrap(); + assert!(restored.research.as_ref().unwrap().chapter.is_none()); + assert!(!restored.value().to_string().contains("secret")); + assert!(!restored.value().to_string().contains("example.org")); + } + #[test] fn ordinary_reopen_keeps_selection_across_ports_without_replaying_other_inputs() { let old = origin(49123); diff --git a/apps/presentation/dashboard/package.json b/apps/presentation/dashboard/package.json index 6360cf9020..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", @@ -15,6 +16,7 @@ "build": "tsc --noEmit && vite build && npm run build:chat", "build:chat": "node ../../../scripts/chat_bundle_launcher.mjs build", "build:desktop": "tsc --noEmit && vite build", + "benchmark:explore-timeline": "vite build --ssr smoke/explore-timeline-benchmark.tsx --outDir node_modules/.cache/explore-timeline-benchmark --emptyOutDir && NODE_ENV=production node node_modules/.cache/explore-timeline-benchmark/explore-timeline-benchmark.js", "check:css-custom-properties": "node ../../../scripts/check-css-custom-properties.test.mjs && node ../../../scripts/check-css-custom-properties.mjs dashboard", "dev": "bash ../../../scripts/dashboard-dev.sh", "dev:web": "vite --host 127.0.0.1", @@ -27,6 +29,7 @@ "smoke:capability-configuration": "rm -rf node_modules/.cache/loopx-capability-configuration-smoke && tsc --ignoreConfig --target ES2022 --module NodeNext --moduleResolution NodeNext --types node --skipLibCheck --strict --outDir node_modules/.cache/loopx-capability-configuration-smoke smoke/capability-configuration-smoke.ts src/data/capability-configuration.ts && node node_modules/.cache/loopx-capability-configuration-smoke/smoke/capability-configuration-smoke.js", "smoke:chat-model-menu": "vite build --ssr smoke/chat-model-menu-smoke.mjs --outDir node_modules/.cache/chat-model-menu --emptyOutDir && node node_modules/.cache/chat-model-menu/chat-model-menu-smoke.js", "smoke:chat-route": "vite build --ssr smoke/chat-route-smoke.ts --outDir node_modules/.cache/loopx-chat-route-smoke --emptyOutDir && node node_modules/.cache/loopx-chat-route-smoke/chat-route-smoke.js", + "smoke:explore-timeline-scan": "vite build --ssr smoke/explore-timeline-scan-smoke.tsx --outDir node_modules/.cache/explore-timeline-scan --emptyOutDir && node node_modules/.cache/explore-timeline-scan/explore-timeline-scan-smoke.js", "smoke:chat-stream-stall": "vite build --ssr smoke/chat-stream-stall-smoke.ts --outDir node_modules/.cache/loopx-chat-stream-stall --emptyOutDir && node node_modules/.cache/loopx-chat-stream-stall/chat-stream-stall-smoke.js", "smoke:chat-turn-acceptance-retry": "vite build --ssr smoke/chat-turn-acceptance-retry-smoke.ts --outDir node_modules/.cache/loopx-chat-turn-acceptance-retry --emptyOutDir && node node_modules/.cache/loopx-chat-turn-acceptance-retry/chat-turn-acceptance-retry-smoke.js", "smoke:demo-readiness": "bash ../../../scripts/loopx-python.sh --exec ../../../examples/dashboard-demo-readiness-smoke.py", @@ -43,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/bound-conversation-http-fixture.py b/apps/presentation/dashboard/smoke/bound-conversation-http-fixture.py index 7f6c634bb4..426935f323 100644 --- a/apps/presentation/dashboard/smoke/bound-conversation-http-fixture.py +++ b/apps/presentation/dashboard/smoke/bound-conversation-http-fixture.py @@ -141,15 +141,28 @@ def start(self, server): "position": 1, "content": body}]}} frozen = conversation_reply_context(raw)["context_text"] + "\n\nCurrent user message:\n" + body record.update(reply_context_message=frozen, reply_context_source_text=body) - turn, _ = server.chat_store.create_turn(sid, client_turn_id=f"external-{request}", message=frozen, origin="lark") + queued_reply = "--queued-reply" in sys.argv + if queued_reply: + server.chat_store.create_turn(sid, client_turn_id="synthetic-held-turn", message="An active synthetic task.", origin="web") + create = server.chat_store.create_queued_turn if queued_reply else server.chat_store.create_turn + attachments = [] + if queued_reply: + image = "iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAIAAAASFvFNAAAAEElEQVR4nGP4v0gdghjgLABwBAqxX1jWkgAAAABJRU5ErkJggg==" + attachments = [{"id": "queued-image", "name": "queued-image.png", "mime_type": "image/png", + "size": len(base64.b64decode(image)), "data_url": "data:image/png;base64," + image}] + turn, _ = create(sid, client_turn_id=f"external-{request}", message=frozen, origin="lark", attachments=attachments) correlation = {"request_ref": request, "binding_id": binding["binding_id"], "source": source, "session_id": sid, "turn_id": turn["turn_id"]} for directory, value in (("external-requests", {**correlation, "status": "accepted", "command": None, "message": frozen}), ("lark-private-deliveries", {**record, **correlation, "status": "delivered"})): _atomic_write_json(server.chat_store.root / directory / f"{request}.json", value) - server.chat_store.update_turn(sid, turn["turn_id"], status="completed") - server.chat_store.release_active_turn(sid, turn["turn_id"]) - server.chat_store.append_message(sid, role="agent", text="已保留原要求,当前核验结果待进一步确认。", turn_id=turn["turn_id"]) + if queued_reply: + # Identical prose without admission journals must stay literal. + server.chat_store.create_queued_turn(sid, client_turn_id="synthetic-literal-context", message=frozen, origin="web") + else: + server.chat_store.update_turn(sid, turn["turn_id"], status="completed") + server.chat_store.release_active_turn(sid, turn["turn_id"]) + server.chat_store.append_message(sid, role="agent", text="已保留原要求,当前核验结果待进一步确认。", turn_id=turn["turn_id"]) paths = [server.chat_store.root / directory / f"{request}.json" for directory in ("external-requests", "lark-private-deliveries")] paths.extend([server.chat_store.sessions_root / sid / "messages.jsonl", 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/compaction-memory-retirement-browser-smoke.mjs b/apps/presentation/dashboard/smoke/compaction-memory-retirement-browser-smoke.mjs new file mode 100644 index 0000000000..5d3c9276f8 --- /dev/null +++ b/apps/presentation/dashboard/smoke/compaction-memory-retirement-browser-smoke.mjs @@ -0,0 +1,107 @@ +// Retirement regression: a saved experimental opt-in stays inert and hidden; +// sibling settings retain real preview/apply/readback and stale-write recovery. +// Isolated machine, empty registry, unavailable native host; no model calls. +import assert from "node:assert/strict"; +import {spawn} from "node:child_process"; +import {mkdtemp, mkdir, rm, writeFile} from "node:fs/promises"; +import {tmpdir} from "node:os"; +import {join, resolve} from "node:path"; +import {resolveTestPython} from "../../../../scripts/test-python.mjs"; +import {launchBrowser, loadPlaywright, waitForHttp} from "../../../../examples/dashboard-browser-smoke-support.mjs"; + +const repoRoot = resolve(import.meta.dirname, "../../../.."); +const root = await mkdtemp(join(tmpdir(), "loopx-compaction-preference-")); +const port = Number(process.env.LOOPX_COMPACTION_MEMORY_PORT ?? 5414); +const screenshots = process.env.LOOPX_COMPACTION_MEMORY_SCREENSHOTS; +const registry = join(root, "registry.json"); +await mkdir(join(root, "runtime", "machine"), {recursive: true}); +await writeFile(join(root, "runtime", "machine", "configuration.json"), JSON.stringify({ + schema_version: "loopx_machine_configuration_v0", namespaces: { + compaction_memory: {schema_version: "compaction_memory_machine_defaults_v0", enabled: true}, + }, +})); +await writeFile(registry, '{"goals":[]}'); +await mkdir(join(root, "home")); +if (screenshots) await mkdir(screenshots, {recursive: true}); +const server = spawn(resolveTestPython({repoRoot}), ["-m", "loopx.cli", "--registry", registry, + "--runtime-root", join(root, "runtime"), "chat", "--port", String(port), "--no-open", + "--codex-bin", join(root, "unavailable-native-host"), "--assets-dir", join(repoRoot, "loopx/web/chat")], { + cwd: root, env: {...process.env, HOME: join(root, "home"), PYTHONPATH: repoRoot, LOOPX_USAGE_PING: "0"}, + stdio: ["ignore", "pipe", "pipe"], +}); +let serverError = "", browser; +for (const stream of [server.stdout, server.stderr]) stream.on("data", chunk => {serverError += String(chunk);}); +try { + const base = `http://127.0.0.1:${port}`; + await waitForHttp(`${base}/chat/`).catch(error => {throw new Error(`${error.message}\n${serverError}`);}); + browser = await launchBrowser(loadPlaywright().chromium); + const page = await browser.newPage({locale: "en-US", viewport: {width: 1440, height: 1000}}); + const workRequests = []; + page.on("request", request => { + if (request.method() === "POST") { + const path = new URL(request.url()).pathname; + if (path === "/api/chat/sessions" || /^\/api\/chat\/sessions\/[^/]+\/turns$/u.test(path)) workRequests.push(path); + } + }); + const open = async () => { + await page.goto(`${base}/chat/?settings_scope=machine&settings_tab=capabilities`, {waitUntil: "networkidle"}); + await page.getByText("Progressive context", {exact: true}).first().click(); + assert.equal(await page.getByText("Compaction working memory (experimental)", {exact: true}).count(), 0); + assert.equal(await page.getByRole("switch", {name: "Enable experimental compaction working memory"}).count(), 0); + }; + const progressive = page.getByRole("switch", {name: "Read context progressively"}); + const delta = page.getByRole("switch", {name: "Use cross-turn delta automatically on supported hosts"}); + const configuration = async () => (await (await page.request.get(`${base}/api/chat/machine-configuration`)).json()).machine_configuration; + const capture = async name => { + if (screenshots) await page.screenshot({path: join(screenshots, name)}); + }; + await open(); + assert.equal(await progressive.isChecked(), true); + assert.equal(await delta.isChecked(), true); + assert.equal((await configuration()).namespaces.compaction_memory, undefined); + await capture("desktop-settings.png"); + await page.setViewportSize({width: 430, height: 932}); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true); + await capture("narrow-settings.png"); + await page.setViewportSize({width: 1440, height: 1000}); + + // Keep the actual backend and invalidate only the request's CAS expectation. + const apply = "**/api/chat/machine-configuration/apply"; + await page.route(apply, route => route.continue({postData: JSON.stringify({ + ...route.request().postDataJSON(), expected_plan_revision: `sha256:${"0".repeat(64)}`, + })})); + await progressive.click(); + await page.getByText(/machine-configuration plan revision changed/u).waitFor(); + assert.equal(await progressive.isChecked(), true, "A rejected save retains the confirmed value"); + assert.equal((await configuration()).namespaces.context_delivery, undefined); + await capture("desktop-rejected.png"); + await page.unroute(apply); + await progressive.click(); + await page.getByText("Progressive reads preference saved.", {exact: true}).waitFor(); + assert.equal((await configuration()).namespaces.context_delivery.mode, "off"); + assert.equal(await delta.isChecked(), true); + await delta.click(); + await page.getByText("Cross-turn delta preference saved.", {exact: true}).waitFor(); + assert.equal((await configuration()).namespaces.context_delivery.delta_delivery, "off"); + assert.equal(await progressive.isChecked(), false); + await open(); + assert.equal(await progressive.isChecked(), false); + assert.equal(await delta.isChecked(), false); + assert.equal((await configuration()).namespaces.compaction_memory, undefined); + await page.evaluate(() => localStorage.setItem("loopx-pw-locale", "zh-CN")); + await page.reload({waitUntil: "networkidle"}); + assert.equal(await page.getByText("压缩工作记忆(实验)", {exact: true}).count(), 0); + assert.equal(await page.getByRole("switch", {name: "启用实验性压缩工作记忆"}).count(), 0); + await capture("chinese-settings.png"); + // Existing Workbench entry may create Session metadata; no Turn is dispatched. + assert.equal(workRequests.some(path => path.endsWith("/turns")), false); + console.log("compaction memory retirement: legacy-on hidden; sibling save/reload/stale-write recovery passed"); +} finally { + await browser?.close(); + if (server.exitCode === null) { + const exited = new Promise(resolveExit => server.once("exit", resolveExit)); + server.kill(); + await exited; + } + await rm(root, {recursive: true, force: true}); +} diff --git a/apps/presentation/dashboard/smoke/conversation-reply-browser-smoke.mjs b/apps/presentation/dashboard/smoke/conversation-reply-browser-smoke.mjs index 784a95aa7c..54f1f41596 100644 --- a/apps/presentation/dashboard/smoke/conversation-reply-browser-smoke.mjs +++ b/apps/presentation/dashboard/smoke/conversation-reply-browser-smoke.mjs @@ -12,11 +12,12 @@ import {launchBrowser, loadPlaywright} from "../../../../examples/dashboard-brow const repo = resolve(import.meta.dirname, "../../../.."); const returnedFiles = process.argv.includes("--returned-files"); const historyImages = process.argv.includes("--history-images"); +const queuedReply = process.argv.includes("--queued-reply"); const output = resolve(process.env.LOOPX_REPLY_OUTPUT ?? resolve(repo, "output/playwright/conversation-reply")); await mkdir(output, {recursive: true}); const child = spawn(resolveTestPython({repoRoot: repo}), ["-u", "apps/presentation/dashboard/smoke/bound-conversation-http-fixture.py", returnedFiles ? "--returned-files" : "--reply-context", - ...(historyImages ? ["--history-images"] : [])], + ...(historyImages ? ["--history-images"] : []), ...(queuedReply ? ["--queued-reply"] : [])], {cwd: repo, env: {...process.env, LOOPX_USAGE_PING: "0"}, stdio: ["pipe", "pipe", "pipe"]}); const exited = once(child, "exit"), queue = [], waiting = []; let stderr = "", browser; @@ -80,11 +81,21 @@ async function checkReturnedFiles(ready, page, errors, writes) { } } await page.screenshot({path: resolve(output, `${baseline ? "before" : "after"}-files-desktop.png`), animations: "disabled"}); + const historyPath = `/api/chat/sessions/${ready.sessionId}`; + const readerRequest = page.context().waitForEvent("request", {predicate: request => + new URL(request.url()).pathname === historyPath + && new URL(request.frame().url()).searchParams.get("reportMessageId") === ready.fileMessageId}); const opened = page.context().waitForEvent("page"); await timeline.getByRole("link", {name: "单独阅读完整答复"}).click(); const report = await opened; report.on("pageerror", error => errors.push(error.message)); await report.getByRole("heading", {name: "结果已核验 / Verified result", exact: true}).waitFor(); + const readerQuery = new URL((await readerRequest).url()).searchParams; + if (!baseline) { + assert.equal(readerQuery.get("turn_id"), answer.turn_id, "The saved answer checks its original Turn"); + assert.equal(readerQuery.get("report_message_id"), answer.message_id, "The reader requests only the chosen answer"); + assert.equal(readerQuery.has("message_limit"), false); + } assert.equal(await report.locator("a[download]").count(), baseline ? 0 : ready.files.length); await report.screenshot({path: resolve(output, `${baseline ? "before" : "after"}-files-reader.png`), animations: "disabled"}); if (!baseline) { @@ -109,6 +120,91 @@ async function checkReturnedFiles(ready, page, errors, writes) { const url = ready.origin + answer.attachments[0].data_url; assert.equal((await page.request.get(url.replace(ready.sessionId, "unrelated-session"))).status(), 404); assert.equal((await page.request.get(url, {headers: {Origin: "https://unrelated.example"}})).status(), 403); + + const legacy = new URL(report.url()); + legacy.searchParams.delete("reportTurnId"); + const savedAnswerRequest = url => url.pathname === historyPath && url.searchParams.get("report_message_id") === ready.fileMessageId; + const legacyRead = report.waitForResponse(response => new URL(response.url()).pathname === historyPath); + await report.goto(legacy.toString()); + await report.getByRole("link", {name: "Download file: source.bin", exact: false}).waitFor(); + const legacyResponse = await legacyRead; + assert.ok(savedAnswerRequest(new URL(legacyResponse.url())), "An existing link selects its saved message without loading the transcript"); + const legacySnapshot = await legacyResponse.json(); + assert.deepEqual(legacySnapshot.messages.filter(row => row.role !== "user").map(row => row.message_id), [ready.fileMessageId]); + const legacyAnswer = legacySnapshot.messages.find(row => row.message_id === ready.fileMessageId); + assert.equal(legacyAnswer.text, answer.text); + assert.deepEqual(legacyAnswer.attachments, answer.attachments); + + await report.route(savedAnswerRequest, route => route.fulfill({status: 400, json: {ok: false, error: "invalid history page arguments"}})); + const fallbackRead = report.waitForRequest(request => { + const url = new URL(request.url()); + return url.pathname === historyPath && url.search === ""; + }); + await report.reload(); + await report.getByRole("link", {name: "Download file: source.bin", exact: false}).waitFor(); + await fallbackRead; + + const fallbackTurnRead = report.waitForRequest(request => { + const url = new URL(request.url()); + return url.pathname === historyPath && url.searchParams.get("turn_id") === answer.turn_id && url.searchParams.has("message_limit"); + }); + const withTurn = new URL(legacy); + withTurn.searchParams.set("reportTurnId", answer.turn_id); + await report.goto(withTurn.toString()); + await report.getByRole("link", {name: "Download file: source.bin", exact: false}).waitFor(); + await fallbackTurnRead; + await report.unroute(savedAnswerRequest); + await report.goto(legacy.toString()); + await report.getByRole("link", {name: "Download file: source.bin", exact: false}).waitFor(); + + // Earlier history readers accept unknown query arguments and return their + // complete v1 snapshot. Both existing and Turn-pinned links still open it. + await report.route(savedAnswerRequest, route => route.fulfill({json: snapshot})); + for (const address of [legacy, withTurn]) { + await report.goto(address.toString()); + await report.getByRole("link", {name: "Download file: source.bin", exact: false}).waitFor(); + assert.equal(await report.locator("a[download]").count(), ready.files.length); + } + const wrongTurn = new URL(withTurn); + wrongTurn.searchParams.set("reportTurnId", "unrelated-turn"); + await report.goto(wrongTurn.toString()); + await report.getByText("This answer was not found. It may have been removed, or the link may be incorrect.").waitFor(); + assert.equal(await report.locator("a[download]").count(), 0); + await report.unroute(savedAnswerRequest); + + for (const invalid of [ + {...snapshot, session: {...snapshot.session, session_id: "another-session"}}, + {...snapshot, report_message_id: "another-message"}, + {...snapshot, message_page: {next_cursor: "another-page"}}, + ]) { + await report.route(savedAnswerRequest, route => route.fulfill({json: invalid})); + await report.goto(legacy.toString()); + await report.getByText("Could not load this answer.").waitFor(); + assert.equal(await report.locator("a[download]").count(), 0); + await report.unroute(savedAnswerRequest); + } + + const refusedReads = []; + const observeRefusal = request => { + if (new URL(request.url()).pathname === historyPath) refusedReads.push(new URL(request.url())); + }; + report.on("request", observeRefusal); + for (const [status, error] of [[403, "Source access was revoked"], [400, "invalid Chat journal record"]]) { + refusedReads.length = 0; + await report.route(savedAnswerRequest, route => route.fulfill({status, json: {ok: false, error}})); + await report.reload(); + await report.getByText("Could not load this answer.").waitFor(); + assert.equal(await report.locator("a[download]").count(), 0); + assert.equal(refusedReads.length, 1); + assert.ok(savedAnswerRequest(refusedReads[0]), "A refused or invalid source must never trigger a wider history read"); + await report.unroute(savedAnswerRequest); + } + report.off("request", observeRefusal); + + legacy.searchParams.set("reportTurnId", "unrelated-turn"); + await report.goto(legacy.toString()); + await report.getByText(/This answer was not found|Could not load this answer/).waitFor(); + assert.equal(await report.locator("a[download]").count(), 0); } child.stdin.write("inspect\n"); const inspection = await next(); @@ -184,6 +280,71 @@ async function checkHistoryImages(ready, page, errors, writes) { console.log("history-images-browser: passed (latest, scroll, inline retry and original message link; zero model Turns)"); } +async function checkQueuedReply(ready, page, errors, writes) { + const endpoint = `${ready.origin}/api/chat/sessions/${ready.sessionId}`; + const snapshot = await (await page.request.get(endpoint)).json(); + const original = snapshot.messages.find(row => row.origin === "lark" && row.reply_context); + assert.ok(original.text.startsWith("Referenced message (")); + const body = original.reply_context.source_text; + const queued = await (await page.request.get(`${endpoint}/queue`)).json(); + assert.equal(queued.turns.length, 2); + assert.equal(queued.turns[0].preview, body.slice(0, 240)); + assert.equal(queued.turns[0].character_count, [...body].length); + assert.equal(queued.turns[1].preview, [...original.text].slice(0, 240).join(""), + "An identical unbound literal must not become a source-backed quote"); + await openWhileCheckingOriginalConversation(ready, page); + await page.getByRole("navigation", {name: "管家视图"}).getByRole("button", {name: /^(Chat|对话)$/}).click(); + const queue = page.locator(".personal-conversation-queue"); + const message = queue.locator(":scope > ol > li").first(); + const summary = message.getByLabel("待处理消息 1", {exact: true}); + await summary.waitFor(); + assert.equal(await summary.getByText(body, {exact: true}).count(), 1); + assert.equal(queued.turns[0].attachment_count, 1); + await page.screenshot({path: resolve(output, "queue-default-desktop.png"), animations: "disabled"}); + child.stdin.write("history-unavailable\n"); + assert.equal((await next()).history_available, false); + await summary.focus(); await page.keyboard.press("Enter"); + await message.getByRole("alert").waitFor(); + child.stdin.write("history-available\n"); + assert.equal((await next()).history_available, true); + await message.getByRole("button", {name: "重试", exact: true}).click(); + const context = message.locator(".conversation-reply-context"); + await context.waitFor(); + await page.waitForFunction(() => document.querySelector('.personal-conversation-queue img[alt="queued-image.png"]')?.naturalWidth === 3); + assert.equal(await context.getAttribute("open"), null); + await context.locator("summary").focus(); await page.keyboard.press("Enter"); + await context.getByText("原要求:保留已有结果和失败记录。Original requirement: retain results and failed attempts.", {exact: true}).waitFor(); + assert.equal(await context.locator("section").count(), 1); + assert.equal(await context.locator("blockquote ol").first().evaluate(node => getComputedStyle(node).listStyleType), "decimal"); + assert.deepEqual(await context.locator("blockquote ol").evaluateAll(lists => lists.map(list => list.start)), [1, 2, 3, 7, 0]); + assert.equal(await message.locator(".personal-queue-message").getByText(body, {exact: true}).count(), 1); + await page.screenshot({path: resolve(output, "queue-expanded-desktop.png"), animations: "disabled"}); + await page.setViewportSize({width: 390, height: 844}); + await context.locator("summary").scrollIntoViewIfNeeded(); + assert.ok(await page.locator("body").evaluate(node => node.scrollWidth <= innerWidth + 1)); + await page.screenshot({path: resolve(output, "queue-expanded-narrow.png"), animations: "disabled"}); + const literal = queue.locator(":scope > ol > li").nth(1); + await literal.getByLabel("待处理消息 2", {exact: true}).click(); + await literal.locator(".personal-queue-message").getByText("Referenced message (", {exact: false}).waitFor(); + assert.equal(await literal.locator(".conversation-reply-context").count(), 0); + await page.evaluate(() => localStorage.setItem("loopx-pw-locale", "en")); + await page.reload(); + await queue.getByLabel("Queued message 1", {exact: true}).click(); + await queue.getByText("Reply and thread context", {exact: true}).waitFor(); + assert.deepEqual(errors, []); + assert.ok(!writes.some(path => /\/turns(?:\/|$)|\/queue\/[^/]+\/(?:input|steer)/u.test(path))); + child.stdin.write("inspect\n"); + const inspection = await next(); + assert.equal(inspection.model_turns, 0); + assert.equal(inspection.reply_evidence_unchanged, true); + child.stdin.write("revoke\n"); + assert.equal((await next()).revoked, ready.bindingId); + const denied = await page.request.get(`${endpoint}/queue`); + assert.ok(!denied.ok(), "Queue projection must not bypass revoked source access"); + assert.equal((await denied.json()).turns, undefined); + console.log("queued-reply-browser: passed (real HTTP/source journals, readable preview, full quote/thread, literal parity, read failure/retry, keyboard, narrow/English, no model Turns or queue mutations)"); +} + try { const ready = await next(); browser = await launchBrowser(loadPlaywright().chromium); @@ -196,6 +357,8 @@ try { await checkHistoryImages(ready, page, errors, writes); } else if (returnedFiles) { await checkReturnedFiles(ready, page, errors, writes); + } else if (queuedReply) { + await checkQueuedReply(ready, page, errors, writes); } else { const snapshot = await (await page.request.get(`${ready.origin}/api/chat/sessions/${ready.sessionId}`)).json(); const source = snapshot.messages.find(row => row.role === "user" && row.turn_id); diff --git a/apps/presentation/dashboard/smoke/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/explore-timeline-benchmark.tsx b/apps/presentation/dashboard/smoke/explore-timeline-benchmark.tsx new file mode 100644 index 0000000000..d3434e0c49 --- /dev/null +++ b/apps/presentation/dashboard/smoke/explore-timeline-benchmark.tsx @@ -0,0 +1,88 @@ +import {createHash} from "node:crypto"; +import {mkdirSync, readFileSync, writeFileSync} from "node:fs"; +import {join} from "node:path"; +import {performance} from "node:perf_hooks"; +import {renderToStaticMarkup} from "react-dom/server"; +import {GoalResearchTimeline} from "../src/features/personal-workspace/goal-research-timeline"; +import {groupUnlinkedHistoryQuestions, parseExploreHistoryPage, projectExploreHistory} from "../../../../loopx/control_plane/presentation/explore_history"; +import {buildExploreTimeline} from "../../../../loopx/control_plane/presentation/explore_timeline"; + +const [fixturePath, outputDir] = process.argv.slice(2); +if (!fixturePath || !outputDir) throw new Error("Use --make-fixture or "); +if (fixturePath === "--make-fixture") { + const real = JSON.parse(readFileSync("src/data/fixtures/edgebench-graph-checkpoint-history.json", "utf8")); + const many: Record[] = [], single: Record[] = []; + const start = Date.UTC(2026, 0, 1); + const stamp = (ms: number) => new Date(ms).toISOString().replace(".000Z", "Z"); + for (let index = 0; index < 1200; index++) { + const goal = "synthetic-timeline", parent = `route-${index}-parent`, child = `route-${index}-child`; + const when = start + index * 120_000; + const event = (kind: string, id: string, extra: Record = {}) => ({ + schema_version: "loopx_explore_result_event_v0", event_id: `${kind}-${id}`, goal_id: goal, + event_kind: kind, result_id: id, recorded_at: stamp(when), title: `${kind} ${id}`, ...extra, + }); + many.push(event("node", child, {parent_id: parent, recorded_at: index % 100 === 0 ? "unknown" : stamp(when + 3_600_000), status: "open"})); + many.push(event("node", parent, {status: "exploring"})); + many.push(event("edge", `relation-${index}`, {from_node: parent, to_node: child, + edge_type: index % 3 === 0 ? "refutes" : "supports", summary: "Recorded relationship"})); + if (index % 25 === 0) many.push(event("edge", `dangling-${index}`, {from_node: parent, to_node: `missing-${index}`, edge_type: "supports"})); + if (index % 5 === 0) many.push(event("finding", `finding-${index}`, {node_id: parent, + status: index % 2 === 0 ? "refuted" : "confirmed", recorded_at: index % 50 === 0 ? "unknown" : stamp(when), + summary: index % 10 === 0 + ? "Input revision: fixture Applicability: local rendering Observation: recorded relationship Interpretation: Outcome: changed retained: - source context changed: - next route stopped: - previous route" + : "Recorded finding", evidence_refs: [`evidence:fixture-${index}`]})); + } + for (let index = 0; index < 800; index++) { + const goal = "synthetic-one-route", when = stamp(start + index * 300_000); + single.push({schema_version: "loopx_explore_result_event_v0", event_id: `node-${index}`, goal_id: goal, + event_kind: "node", result_id: `node-${index}`, recorded_at: when, title: `Node ${index}`, + parent_id: index ? `node-${index - 1}` : "", status: "open"}); + if (index) single.push({schema_version: "loopx_explore_result_event_v0", event_id: `edge-${index}`, goal_id: goal, + event_kind: "edge", result_id: `edge-${index}`, recorded_at: when, title: `Edge ${index}`, + from_node: `node-${index - 1}`, to_node: `node-${index}`, edge_type: "supports", summary: "Recorded relationship"}); + } + const fixture = [{name: "public-checkpoint", goal_id: real.goal_id, events: real.events}, + {name: "synthetic-many-routes", goal_id: "synthetic-timeline", events: many}, + {name: "synthetic-one-route", goal_id: "synthetic-one-route", events: single}]; + const bytes = Buffer.from(JSON.stringify(fixture)); + writeFileSync(outputDir, bytes, {flag: "wx"}); + console.log(JSON.stringify({fixture_sha256: createHash("sha256").update(bytes).digest("hex"), cases: fixture.map(row => ({name: row.name, events: row.events.length}))})); + process.exit(0); +} +const fixtureBytes = readFileSync(fixturePath); +const fixtures = JSON.parse(fixtureBytes.toString()) as Array<{name: string; goal_id: string; events: unknown[]}>; +mkdirSync(outputDir); +const cases = []; +for (const fixture of fixtures) { + const events = parseExploreHistoryPage({ok: true, goal_id: fixture.goal_id, total: fixture.events.length, + next_cursor: null, items: fixture.events}, fixture.goal_id).items; + const history = projectExploreHistory(events, fixture.goal_id); + const timeline = buildExploreTimeline(history.nodes, history.edges, history.events); + const dayGroups = groupUnlinkedHistoryQuestions(history.nodes, history.edges).groups; + const render = (zh: boolean, phase: number | null, complete: boolean) => renderToStaticMarkup( + {}} onSelect={() => {}} + onSelectMany={() => {}} onPhase={() => {}} timeLabel={value => new Date(value).toISOString()} + dayLabel={value => new Date(value).toISOString().slice(0, 10)}/>, + ); + const snapshots = []; + for (const [name, zh, phase, complete] of [["zh-all", true, null, true], ["en-phase", false, 1, true], ["zh-partial", true, null, false]] as const) { + const html = render(zh, phase, complete); + writeFileSync(join(outputDir, `${fixture.name}-${name}.html`), html); + snapshots.push({name, bytes: Buffer.byteLength(html), sha256: createHash("sha256").update(html).digest("hex")}); + } + for (let index = 0; index < 3; index++) render(true, null, true); + const samples = []; + for (let index = 0; index < 12; index++) { + const start = performance.now(); + const html = render(true, null, true); + samples.push(performance.now() - start); + if (createHash("sha256").update(html).digest("hex") !== snapshots[0]!.sha256) throw new Error("Repeated render changed output"); + } + const sorted = [...samples].sort((a, b) => a - b); + cases.push({name: fixture.name, events: events.length, nodes: timeline.nodes.size, edges: timeline.edges.length, + routes: timeline.routes.length, snapshots, samples_ms: samples, median_ms: (sorted[5]! + sorted[6]!) / 2}); +} +const report = {node: process.version, node_env: process.env.NODE_ENV, fixture_sha256: createHash("sha256").update(fixtureBytes).digest("hex"), cases}; +writeFileSync(join(outputDir, "report.json"), JSON.stringify(report, null, 2) + "\n"); +console.log(JSON.stringify(report)); diff --git a/apps/presentation/dashboard/smoke/explore-timeline-scan-smoke.tsx b/apps/presentation/dashboard/smoke/explore-timeline-scan-smoke.tsx new file mode 100644 index 0000000000..7b15223c0f --- /dev/null +++ b/apps/presentation/dashboard/smoke/explore-timeline-scan-smoke.tsx @@ -0,0 +1,53 @@ +import assert from "node:assert/strict"; +import {renderToStaticMarkup} from "react-dom/server"; +import {GoalResearchTimeline} from "../src/features/personal-workspace/goal-research-timeline"; +import {parseExploreHistoryPage, projectExploreHistory} from "../../../../loopx/control_plane/presentation/explore_history"; +import {buildExploreTimeline} from "../../../../loopx/control_plane/presentation/explore_timeline"; + +const goalId = "timeline-scan-fixture"; +const events: Record[] = []; +for (let index = 0; index < 40; index++) { + const parent = `parent-${index}`, child = `child-${index}`; + const event = (kind: string, id: string, extra: Record) => ({ + schema_version: "loopx_explore_result_event_v0", goal_id: goalId, event_kind: kind, + event_id: `${kind}-${id}`, result_id: id, title: id, recorded_at: "2026-01-01T00:00:00Z", ...extra, + }); + if (index === 0) { + events.push(event("node", "child-later", {parent_id: parent, recorded_at: "2026-01-01T02:00:00Z"})); + events.push(event("node", "child-unknown", {parent_id: parent, recorded_at: "unknown"})); + } + events.push(event("node", child, {parent_id: parent, recorded_at: "2026-01-01T01:00:00Z"})); + events.push(event("node", parent, {})); + events.push(event("edge", `edge-${index}`, {from_node: parent, to_node: child, edge_type: "supports", summary: `route-edge-${index}`})); + if (index === 0) { + events.push(event("edge", "back", {from_node: child, to_node: parent, edge_type: "refutes", summary: "route-back"})); + events.push(event("edge", "unknown", {from_node: parent, to_node: "child-unknown", edge_type: "supports", summary: "unknown-time-edge"})); + events.push(event("edge", "missing", {from_node: parent, to_node: "missing-node", edge_type: "supports", summary: "missing-node-edge"})); + } +} +const parsed = parseExploreHistoryPage({ok: true, goal_id: goalId, total: events.length, next_cursor: null, items: events}, goalId).items; +const history = projectExploreHistory(parsed, goalId); +const timeline = buildExploreTimeline(history.nodes, history.edges, history.events); +// Count source accesses instead of depending on a machine-specific time limit. +let routeReads = 0, edgeReads = 0; +const nodes = new Map([...timeline.nodes].map(([id, item]) => [id, { + ...item, get routeId() {routeReads++; return item.routeId;}, +}])); +const edges = timeline.edges.map(edge => ({...edge, get from_node() {edgeReads++; return edge.from_node;}})); +const html = renderToStaticMarkup( {}} onSelect={() => {}} onSelectMany={() => {}} + onPhase={() => {}} timeLabel={value => new Date(value).toISOString()} dayLabel={value => new Date(value).toISOString().slice(0, 10)}/>); +const routes = [...html.matchAll(/]*class="research-history-edges"[^>]*>(.*?)<\/svg>/gs)].map(match => match[1]!); +assert.equal(routes.length, 40); +for (const [index, route] of routes.entries()) { + const titles = [...route.matchAll(/(.*?)<\/title>/g)].map(match => match[1]); + assert.deepEqual(titles, index ? [`supports: route-edge-${index}`] : ["supports: route-edge-0", "refutes: route-back"]); +} +const firstParents = [...routes[0]!.matchAll(/class="is-grouping" d="([^"]+)"/g)].map(match => match[1]!); +assert.equal(firstParents.length, 2); +const endpoint = (path: string) => Number(path.match(/ ([\d.]+),26$/)?.[1]); +assert.ok(endpoint(firstParents[0]!) > endpoint(firstParents[1]!), "parent arcs keep source order, not timestamp order"); +assert.doesNotMatch(html, /unknown-time-edge|missing-node-edge/); +assert.ok(routeReads <= 4 * (nodes.size + edges.length), `nodes were repeatedly scanned: ${routeReads}`); +assert.ok(edgeReads <= 4 * edges.length, `edges were repeatedly scanned: ${edgeReads}`); +console.log(`explore timeline: 40 routes retained; ${routeReads} node and ${edgeReads} edge identity reads`); 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<string, unknown>): 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..9ea0e4771e 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); @@ -193,6 +198,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 +250,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/todo-confirmation-browser-smoke.mjs b/apps/presentation/dashboard/smoke/todo-confirmation-browser-smoke.mjs new file mode 100644 index 0000000000..a61bcc617a --- /dev/null +++ b/apps/presentation/dashboard/smoke/todo-confirmation-browser-smoke.mjs @@ -0,0 +1,315 @@ +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { once } from "node:events"; +import { mkdir } from "node:fs/promises"; +import { createRequire } from "node:module"; +import { createInterface } from "node:readline"; +import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { launchBrowser } from "../../../../examples/dashboard-browser-smoke-support.mjs"; +import { resolveTestPython } from "../../../../scripts/test-python.mjs"; + +const root = fileURLToPath(new URL("../../../../", import.meta.url)); +const assetDir = resolve(process.env.LOOPX_CHAT_CONFIRMATION_ASSETS ?? resolve(root, "loopx/web/chat")); +const output = resolve(process.env.LOOPX_CHAT_CONFIRMATION_OUTPUT ?? resolve(root, "output/playwright/todo-confirmation")); +const browser = await launchBrowser(createRequire(import.meta.url)("playwright").chromium); +const textByWidth = {1200: "Reconcile delivery records after an interrupted confirmation", + 390: "Review the incident response guide after an interrupted confirmation"}; + +async function goalTab(page, label) { + const tab = page.getByRole("navigation", {name: /Goal view|Goal 视图/}) + .getByRole("button", {name: label}); + const goal = page.locator(".personal-goal-link:visible").first(); + const nav = page.locator(".personal-mobile-menu:visible").first(); + await tab.or(goal).or(nav).first().waitFor(); + if (!await tab.isVisible()) { + if (await nav.isVisible()) await nav.click(); + await goal.click(); + } + await tab.click(); +} + +async function verifyPendingDisplay({page, post, origin, width, provider, snapshot, fixture = "/__confirmation_fixture/display"}) { + await post(fixture, {hold: true}); + const original = await snapshot(); + const titles = width === 390 + ? ["核对欠付项的责任人与跟进记录", "保留交接文档中的原始验收证据"] + : ["Review follow-up owners in the release checklist", "Preserve evidence for the support handover after release"]; + const operations = []; + for (let i = 0; i < titles.length; i++) { + const [created, preview] = await post("/api/actions/preview", { + action_kind: "todo.create", context: {kind: "goal", goal_id: "goal-a"}, + normalized_parameters: {goal_id: "goal-a", text: titles[i]}, summary: "Create task", + idempotency_key: "display-confirmation-" + width + "-" + i, + }); + assert.equal(created, 201, JSON.stringify(preview)); + const id = preview.proposal.proposal_id; + const path = "/api/actions/" + id; + const [, pending] = await post(path + "/apply"); + assert.equal(pending.proposal.failure.error_code, "canonical_create_projection_pending"); + const createdStep = pending.proposal.checkpoint.steps.todo_created; + assert.equal(createdStep.projection_delivery, "pending"); + operations.push({id, path, title: titles[i], todo: createdStep.todo_id, receipt: createdStep.canonical_receipt.receipt_id}); + assert.equal((await post(path + "/cancel"))[0], 409); + } + const committed = await snapshot(); + assert.equal(committed.ids.length, original.ids.length + 2); + assert.notEqual(operations[0].todo, operations[1].todo); + await page.goto(origin + "/chat/?goal=goal-a"); + await goalTab(page, /^(Overview|概览)$/); + await page.reload(); + await goalTab(page, /^(Overview|概览)$/); + const overview = page.getByRole("region", {name: /Display updates pending|展示待更新/}); + await overview.waitFor(); + for (const {title} of operations) await overview.getByRole("button", {name: title, exact: true}).waitFor(); + await page.screenshot({path: resolve(output, provider + "-" + width + "-display-overview.png")}); + await goalTab(page, /^(Chat|对话)$/); + const cards = page.locator(".personal-proposal-row[data-action-kind='todo.create']"); + const card = title => cards.filter({hasText: title}); + // As with ordinary confirmations, these two persisted records have the + // same action title. Both must remain selectable without first doing IO. + for (const {title} of operations) await card(title).waitFor(); + await page.screenshot({path: resolve(output, provider + "-" + width + "-display-chat.png")}); + const [earlier, later] = operations; + await card(later.title).click(); + const retry = page.getByRole("dialog").getByRole("button", {name: /^(Retry original operation|重试原操作)$/}); + await retry.waitFor(); + // Replace the upstream reply after apply ran. File finishes display, while + // SQLite keeps it pending. Both temporarily lose the two readback routes. + await post(fixture, {hold: provider === "sqlite", gateway_reply: later.id, hold_list: true, hold_detail: true}); + const gateway = page.waitForResponse(response => response.url().endsWith(later.path + "/apply")); + const unavailable = [later.path, "/api/actions"].map(path => page.waitForResponse(response => + response.request().method() === "GET" && new URL(response.url()).pathname === path && response.status() === 503)); + await retry.click(); + const [reply] = await Promise.all([gateway, ...unavailable]); + assert.equal(reply.status(), 502); + assert.match(reply.headers()["content-type"], /^text\/html\b/); + await retry.waitFor(); + assert.ok(await retry.isEnabled()); + assert.equal(await page.getByRole("dialog").getByRole("button", {name: /regenerate|重新生成/i}).count(), 0); + await page.screenshot({path: resolve(output, provider + "-" + width + "-gateway-recovery.png")}); + await post(fixture, {hold: false, hold_list: false, hold_detail: false}); + function checkReceipt(proposal, operation) { + assert.equal(proposal.proposal_id, operation.id); + assert.equal(proposal.receipt.receipt_id, operation.receipt); + assert.equal(proposal.receipt.resource_ids.todo_id, operation.todo); + assert.equal(proposal.receipt.projection_verified, true); + } + async function recover(operation) { + const outcome = page.waitForResponse(response => response.url().endsWith(operation.path + "/apply")); + await retry.click(); + const response = await outcome; + assert.equal(response.status(), 200); + checkReceipt((await response.json()).proposal, operation); + await page.keyboard.press("Escape"); + } + const observed = (await (await fetch(origin + later.path)).json()).proposal; + if (provider === "sqlite") { + assert.equal(observed.failure.error_code, "canonical_create_projection_pending"); + assert.equal(observed.checkpoint.steps.todo_created.canonical_receipt.receipt_id, later.receipt); + } else { + checkReceipt(observed, later); + } + await recover(later); + await goalTab(page, /^(Overview|概览)$/); + await overview.getByRole("button", {name: earlier.title, exact: true}).click(); + // A connection drop with the list unavailable still uses exact readback. + await post(fixture, {drop_reply: earlier.id, hold_list: true}); + const disconnected = page.waitForEvent("requestfailed", { + predicate: request => request.method() === "POST" && request.url().endsWith(earlier.path + "/apply"), + }); + await retry.click(); + await disconnected; + await page.getByRole("dialog").getByRole("button", {name: /^(View updated Goal|查看更新后的 Goal)$/}).waitFor(); + const exact = await fetch(origin + earlier.path); + checkReceipt((await exact.json()).proposal, earlier); + await post(fixture, {hold_list: false}); + await page.keyboard.press("Escape"); + await overview.waitFor({state: "hidden"}); + assert.deepEqual(await snapshot(), committed); + console.log(provider + " " + width + "px: HTML 502 and two failed reads keep the original retry; both receipts recovered"); +} + +async function verify(provider, interruptedStep) { + const child = spawn(resolveTestPython({repoRoot: root}), + ["-u", fileURLToPath(new URL("todo-confirmation-http-fixture.py", import.meta.url)), provider, assetDir, interruptedStep], + {cwd: root, stdio: ["ignore", "pipe", "inherit"]}); + const exited = once(child, "exit"); + const lines = createInterface({input: child.stdout})[Symbol.asyncIterator](); + let timer; + const lostRequest = interruptedStep === "applying"; + const beforeWrite = interruptedStep !== "todo_created"; + const capturePrefix = provider + "-" + interruptedStep; + try { + const origin = await Promise.race([ + (async () => { + for await (const line of { [Symbol.asyncIterator]: () => lines }) { + if (line.startsWith("{")) return JSON.parse(line).origin; + } + throw new Error("Chat test server exited before it reported its port."); + })(), + new Promise((_, reject) => {timer = setTimeout(() => reject(new Error("Chat did not start")), 30_000);}), + ]).finally(() => clearTimeout(timer)); + const post = async (path, body = {}) => { + const response = await fetch(origin + path, {method: "POST", headers: {"Content-Type": "application/json"}, + body: JSON.stringify(body)}); + return [response.status, await response.json()]; + }; + const snapshot = () => fetch(origin + "/__confirmation_fixture").then(response => response.json()); + for (const width of [1200, 390]) { + const page = await browser.newPage({viewport: {width, height: 854}}); + page.setDefaultTimeout(12_000); + try { + const locale = width === 390 ? "zh-CN" : "en"; + await page.addInitScript(value => localStorage.setItem("loopx-pw-locale", value), locale); + const text = textByWidth[width]; + const [status, preview] = await post("/api/actions/preview", { + action_kind: "todo.create", context: {kind: "goal", goal_id: "goal-a"}, + normalized_parameters: {goal_id: "goal-a", text}, summary: text, + idempotency_key: "interrupted-confirmation-" + width, + }); + assert.equal(status, 201, JSON.stringify(preview)); + const id = preview.proposal.proposal_id; + const path = "/api/actions/" + id; + const attempted = []; + page.on("request", request => { + const url = new URL(request.url()); + if (url.pathname.startsWith("/api/actions") && request.method() === "POST") attempted.push(url.pathname); + }); + await page.goto(origin + "/chat/?goal=goal-a"); + async function openConfirmation() { + await goalTab(page, /^(Chat|对话)$/); + const card = page.locator(".personal-proposal-row").filter({hasText: text}); + await card.first().click(); + } + await openConfirmation(); + const drawer = page.getByRole("dialog"); + const initial = await snapshot(); + const injected = lostRequest + ? page.waitForEvent("requestfailed", {predicate: request => request.url().endsWith(path + "/apply")}) + : page.waitForResponse(response => response.url().endsWith(path + "/apply")); + await drawer.getByRole("button", {name: /^(Confirm and apply|确认并应用)$/}).click(); + const failure = await injected; + const saved = lostRequest + ? (await (await fetch(origin + path)).json()).proposal + : (await failure.json()).proposal; + assert.equal(saved.proposal_id, id); + if (lostRequest) { + assert.equal(saved.status, "applying"); + assert.equal(saved.failure, null); + } else { + assert.equal(failure.status(), 424); + assert.equal(saved.failure.error_code, "canonical_action_failed"); + assert.equal(saved.failure.retry_safe, true); + } + const interrupted = await snapshot(); + const lost = interrupted.lost[id]; + if (beforeWrite) { + assert.equal(saved.checkpoint, null); + assert.deepEqual(interrupted, initial); + } else { + assert.ok(lost?.receipt_id && interrupted.ids.includes(lost.todo_id)); + assert.equal(interrupted.ids.length, initial.ids.length + 1); + assert.notEqual(interrupted.provider_revision, initial.provider_revision); + } + const retry = drawer.getByRole("button", {name: /^(Retry original operation|重试原操作)$/}); + for (const alternative of ["cancel", "defer", "reject", "regenerate"]) { + const [code, value] = await post(path + "/" + alternative); + assert.deepEqual([code, value.error_code], [409, "action_conflict"], alternative); + } + await page.reload(); + await openConfirmation(); + await retry.waitFor(); + assert.equal(await drawer.getByRole("button", {name: /regenerate|重新生成/i}).count(), 0); + await page.screenshot({path: resolve(output, capturePrefix + "-" + width + "-recovery.png")}); + const recoveredResponse = page.waitForResponse(response => response.url().endsWith(path + "/apply")); + await retry.click(); + const response = await recoveredResponse; + assert.equal(response.status(), 200); + const {proposal} = await response.json(); + assert.equal(proposal.proposal_id, id); + assert.equal(proposal.receipt.outcome, "todo_added"); + const recovered = await snapshot(); + if (beforeWrite) { + const todoId = proposal.receipt.resource_ids.todo_id; + assert.ok(todoId && proposal.receipt.receipt_id); + assert.deepEqual(recovered.ids, [...initial.ids, todoId].sort()); + assert.notEqual(recovered.provider_revision, initial.provider_revision); + } else { + assert.equal(proposal.receipt.receipt_id, lost.receipt_id); + assert.equal(proposal.receipt.resource_ids.todo_id, lost.todo_id); + assert.deepEqual(recovered, interrupted); + } + assert.deepEqual(attempted, [path + "/apply", path + "/apply"]); + if (lostRequest) { + const [code, replay] = await post(path + "/apply"); + assert.equal(code, 200); + assert.deepEqual(replay.proposal.receipt, proposal.receipt); + assert.deepEqual(await snapshot(), recovered); + } + await drawer.getByRole("button", {name: /^(View updated Goal|查看更新后的 Goal)$/}).waitFor(); + await page.screenshot({path: resolve(output, capturePrefix + "-" + width + "-result.png")}); + console.log(provider + " " + width + "px: " + interruptedStep + "; original proposal and one Todo write across reload"); + if (!beforeWrite) await verifyPendingDisplay({page, post, origin, width, provider, snapshot}); + } catch (error) { + await page.screenshot({path: resolve(output, capturePrefix + "-" + width + "-failure.png")}); + error.message += "\n" + (await page.locator("body").innerText()).slice(0, 1000); + throw error; + } finally { await page.close(); } + } + const intent = {action_kind: "todo.create", context: {kind: "goal", goal_id: "goal-a"}, + normalized_parameters: {goal_id: "goal-a", text: "Refresh a preview that was never confirmed"}, + summary: "Refresh a preview", idempotency_key: "unsubmitted-preview"}; + const preview = (await post("/api/actions/preview", intent))[1].proposal; + // The fixture advances the real revision through a separate Todo. + await post("/__confirmation_fixture/advance"); + const path = "/api/actions/" + preview.proposal_id; + const [code, rejected] = await post(path + "/apply"); + assert.equal(code, 409); + assert.equal(rejected.proposal.status, "stale"); + assert.equal(rejected.proposal.checkpoint, null); + const [created, successor] = await post(path + "/regenerate"); + assert.equal(created, 201); + assert.equal(successor.proposal.regenerated_from, preview.proposal_id); + assert.notEqual(successor.proposal.proposal_id, preview.proposal_id); + if (interruptedStep === "todo_created") { + const display = "/__confirmation_fixture/display"; + const [previewCode, monitor] = await post("/api/actions/preview", { + action_kind: "monitor.create", context: {kind: "goal", goal_id: "goal-a"}, + normalized_parameters: {goal_id: "goal-a", agent_id: "agent-a", target: "Review release readiness", + target_key: "release-readiness", cadence: "2h", timezone: "UTC", stop_condition: "watch_only"}, + summary: "Review release readiness", idempotency_key: "monitor-display-recovery", + }); + assert.equal(previewCode, 201); + const monitorPath = "/api/actions/" + monitor.proposal.proposal_id; + const original = await snapshot(); + await post(display, {hold: true}); + const [, pending] = await post(monitorPath + "/apply"); + const saved = pending.proposal.checkpoint.steps.todo_created; + assert.equal(pending.proposal.failure.error_code, "canonical_create_projection_pending"); + const committed = await snapshot(); + assert.deepEqual(committed.ids, [...original.ids, saved.todo_id].sort()); + assert.equal((await post(monitorPath + "/cancel"))[0], 409); + assert.deepEqual(await snapshot(), committed); + await post(display, {hold: false}); + const [applied, recovered] = await post(monitorPath + "/apply"); + assert.equal(applied, 200); + assert.equal(recovered.proposal.receipt.resource_ids.todo_id, saved.todo_id); + assert.equal(recovered.proposal.receipt.projection_verified, true); + assert.deepEqual(await snapshot(), committed); + console.log(provider + ": the Monitor cancel returns 409 and the original confirmation recovers its display"); + } + } finally { + child.kill("SIGINT"); + await exited; + } +} + +try { + await mkdir(output, {recursive: true}); + for (const interruptedStep of ["applying", "todo_create_prepared", "todo_created"]) { + for (const provider of ["file", "sqlite"]) await verify(provider, interruptedStep); + } +} finally { + await browser.close(); +} diff --git a/apps/presentation/dashboard/smoke/todo-confirmation-http-fixture.py b/apps/presentation/dashboard/smoke/todo-confirmation-http-fixture.py new file mode 100644 index 0000000000..66eafc7c40 --- /dev/null +++ b/apps/presentation/dashboard/smoke/todo-confirmation-http-fixture.py @@ -0,0 +1,131 @@ +"""Packaged Chat confirmation recovery on a disposable authority.""" + +from pathlib import Path +import json +import socket +import sys +from tempfile import TemporaryDirectory + +import pytest + +REPO = Path(__file__).resolve().parents[4] + + +class InterruptedConfirmation(BaseException): + """End the request before Chat can persist a failure response.""" + + +def main(provider, assets_dir, interrupted_step): + # Run against this checkout when the smoke is launched as a standalone script. + sys.path[:0] = [str(REPO), str(REPO / "tests/control_plane")] + from canonical_authority_fixture import isolate_sqlite_runtime, promoted_create_fixture + from loopx import chat_server + from loopx.chat_action_store import ChatActionStore + from loopx.control_plane.coordination.local_authority import read_canonical_todos_if_promoted + from loopx.control_plane.effect_runtime import restart_effect_runtime + from loopx.control_plane.todos import provider_projection + from loopx.control_plane.todos.mutation_api import add_goal_todo + + with TemporaryDirectory(prefix="loopx-confirmation-fixture-") as directory, pytest.MonkeyPatch.context() as patch: + scratch = Path(directory) + isolate_sqlite_runtime(scratch, patch) + registry, runtime, _ = promoted_create_fixture(scratch, provider=provider) + lost = {} + interrupted = set() + display = {"hold": False, "drop_reply": None, "gateway_reply": None, "hold_list": False, "hold_detail": False} + write_state = provider_projection.atomic_write_state_text + checkpoint = ChatActionStore.save_checkpoint + for content in ("Review release checklist", "Verify documentation links", "Check failure handling"): + add_goal_todo(registry_path=registry, goal_id="goal-a", role="agent", text=content) + + def interrupt(self, proposal_id, *, step, receipt, **kwargs): + if interrupted_step == "applying" and step == "todo_create_prepared" and proposal_id not in interrupted: + interrupted.add(proposal_id) + raise InterruptedConfirmation() + if step == interrupted_step and proposal_id not in interrupted and not display["hold"]: + interrupted.add(proposal_id) + if step == "todo_created": + lost[proposal_id] = receipt["canonical_receipt"] + raise OSError("test: first create checkpoint write interrupted") + return checkpoint(self, proposal_id, step=step, receipt=receipt, **kwargs) + + def render(path, text, **kwargs): + if display["hold"]: + raise PermissionError("test: display disabled after authority commits") + return write_state(path, text, **kwargs) + + class FixtureHandler(chat_server.ChatRequestHandler): + def do_POST(self): + if self.path == "/__confirmation_fixture/display": + patch_update = self._read_json() + for name in display.keys() & patch_update.keys(): + display[name] = patch_update[name] + self._send_json({"ok": True}) + return + if self.path != "/__confirmation_fixture/advance": + try: + return super().do_POST() + except (BrokenPipeError, ConnectionResetError): + return + except InterruptedConfirmation: + self.close_connection = True + return + self._read_json() + add_goal_todo(registry_path=registry, goal_id="goal-a", role="agent", text="Independent authority update") + self._send_json({"ok": True}) + + def do_GET(self): + if self.path != "/__confirmation_fixture": + route = self.path.split("?", 1)[0] + if ((display["hold_list"] and route == "/api/actions") + or (display["hold_detail"] and route.startswith("/api/actions/"))): + self._send_json({"error": "test: list unavailable"}, status=503) + return + try: + return super().do_GET() + except (BrokenPipeError, ConnectionResetError): + return + snapshot = read_canonical_todos_if_promoted(runtime_root=runtime, goal_id="goal-a") + self._send_json({"provider_revision": snapshot["provider_revision"], + "ids": sorted(todo["todo_id"] for todo in snapshot["todos"]), + "lost": lost}) + + def _send_json(self, payload, *, status=200): + gateway = display["gateway_reply"] + if gateway and self.path == f"/api/actions/{gateway}/apply": + display["gateway_reply"] = None + body = b"<html><title>Bad Gateway" + self.send_response(502) + self.send_header("Content-Type", "text/html") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + return + operation = display["drop_reply"] + if operation and self.path == f"/api/actions/{operation}/apply": + display["drop_reply"] = None + self.close_connection = True + self.connection.shutdown(socket.SHUT_WR) + return + return super()._send_json(payload, status=status) + + serve = chat_server.ChatHTTPServer.serve_forever + + def ready(server): + print(json.dumps({"origin": f"http://127.0.0.1:{server.server_address[1]}"}), flush=True) + return serve(server) + + patch.setattr(chat_server, "ChatRequestHandler", FixtureHandler) + patch.setattr(chat_server.ChatHTTPServer, "serve_forever", ready) + patch.setattr(ChatActionStore, "save_checkpoint", interrupt) + patch.setattr(provider_projection, "atomic_write_state_text", render) + try: + chat_server.serve_chat(registry_path=registry, runtime_root_override=runtime, scan_roots=[scratch], + lark_cli_bin="unavailable-test-lark-cli", codex_bin="unavailable-test-codex", + port=0, goal_id="goal-a", assets_dir=assets_dir) + finally: + restart_effect_runtime(wait_for_exit=True) + + +if __name__ == "__main__": + main(sys.argv[1], Path(sys.argv[2]), sys.argv[3]) 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 79bbd8946f..77f25bff4b 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"; @@ -16,7 +17,6 @@ import { type CollaborationReadback, type LoopXModeSettings, type TodoApplyResult, - type TodoPreview, } from "./chat-model.js"; import type {DelegationPreflight} from "./delegation-preflight.js"; @@ -471,11 +471,13 @@ 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(), error: z.record(z.string(), z.unknown()).nullable().optional(), checkpoint: z.record(z.string(), z.unknown()).nullable().optional(), + creation_retry_available: z.literal(true).optional(), failure: z.record(z.string(), z.unknown()).nullable().optional(), canonical_update_basis: actionSourceBasisSchema.optional(), // The workspace a Goal creation resolved to, named for the owner's review. @@ -972,6 +974,32 @@ export async function fetchChatSession(sessionId: string, signal?: AbortSignal) return requestJson(`/api/chat/sessions/${encodeURIComponent(sessionId)}`, { signal }); } +export async function fetchSavedChatAnswer(sessionId: string, messageId: string, signal: AbortSignal, turnId?: string) { + const query = new URLSearchParams({report_message_id: messageId}); + if (turnId !== undefined) query.set("turn_id", turnId); + const path = `/api/chat/sessions/${encodeURIComponent(sessionId)}?${query}`; + try { + const snapshot = await requestJson(path, {signal}); + // A legacy service can ignore the selector and return its complete v1 + // snapshot. A conflicting marker or a partial history remains invalid. + if (Object.hasOwn(snapshot, "report_message_id")) { + if (snapshot.report_message_id !== messageId) throw new Error("The saved answer selection changed during read."); + } else if ("message_page" in snapshot || "history_resume" in snapshot) { + throw new Error("The saved answer history is incomplete."); + } + return snapshot; + } catch (error) { + // Older Chat builds reject unknown history selectors before reading the + // Session. Only that response enables the earlier history read paths. + if (!(error instanceof ChatApiError) || error.payload.http_status !== 400 + || error.message !== "invalid history page arguments") throw error; + signal.throwIfAborted(); + return turnId === undefined + ? fetchChatSession(sessionId, signal) + : fetchChatSessionHistory(sessionId, signal, turnId); + } +} + export const chatQueueInputRequestSchema = z.discriminatedUnion("action", [ z.object({action: z.literal("edit"), operation_id: z.string().min(1).max(160), expected_revision: z.number().int().nonnegative(), message: z.string().min(1).max(24000)}).strict(), @@ -983,15 +1011,16 @@ const chatQueuedInputSchema = z.object({input_revision: z.number().int().nonnega attachments: z.array(z.object({id: z.string(), name: z.string(), size: z.number(), mime_type: z.string(), data_url: z.string()})), }); -export type ChatQueuedInput = z.infer; +export type ChatQueuedInput = z.infer & Pick; export async function fetchQueuedChatInput(sessionId: string, turnId: string, signal?: AbortSignal) { // Keep original-source audience projection and complete paging. The visible // input and its revision come from one canonical user row, never raw model context. const history = await fetchChatSessionHistory(sessionId, signal, turnId); const original = history.messages.find(row => row.role === "user" && row.turn_id === turnId); if (!original) throw new Error("Original queued input is unavailable"); - return chatQueuedInputSchema.parse({input_revision: original.queue_input_revision ?? 0, - message: original.reply_context?.source_text ?? original.text, attachments: original.attachments ?? []}); + return {...chatQueuedInputSchema.parse({input_revision: original.queue_input_revision ?? 0, + message: original.reply_context?.source_text ?? original.text, attachments: original.attachments ?? []}), + reply_context: original.reply_context}; } const chatQueueSchema = z.object({ ok: z.literal(true), schema_version: z.literal("loopx_chat_store_v1"), session_id: z.string().min(1), @@ -1001,6 +1030,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), @@ -1701,7 +1731,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), @@ -1716,7 +1747,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(), @@ -1724,6 +1756,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}` @@ -1754,6 +1815,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; } @@ -3131,12 +3201,16 @@ export async function updateGoalOwnership(body: { goal_id: string; mode: Executi const privateAgentSessionSchema = z.object({session_id: z.string(), goal_id: z.string(), agent_id: z.string(), executor_endpoint_id: z.string()}); const privateAgentTargetSchema = privateAgentSessionSchema.extend({target_ref: z.string(), host_ref: z.string(), goal_instance_id: z.string().nullable()}); -const privateConversationSchema = z.object({ +const privateConversationSettingsRowSchema = z.object({ binding_id: z.string(), app_ref: z.string(), context_kind: z.enum(["project", "steward"]), project_ref: z.string(), project_title: z.string(), context_available: z.boolean(), executor_endpoint_id: z.string(), - grant: z.enum(["workspace_read", "workspace_write", "portfolio_read"]), goal_count: z.number().int().default(0), listener_status: z.string(), + grant: z.enum(["workspace_read", "workspace_write", "portfolio_read"]), goal_count: z.number().int().default(0), goal_scope: z.enum(["all_registered", "selected"]).nullable().optional(), audience: z.enum(["owner", "group"]).default("owner"), group_count: z.number().int().default(0), + agent_targets: z.array(privateAgentTargetSchema).default([]), +}); +const privateConversationDiagnosticsRowSchema = z.object({ + binding_id: z.string(), listener_status: z.string(), pending_count: z.number().int(), recovery_count: z.number().int(), ingress: z.object({status: z.enum(["unobserved", "verified", "gap", "unavailable"]), last_checked_at: z.number().nullable(), last_complete_at: z.number().nullable(), @@ -3169,14 +3243,21 @@ const privateConversationSchema = z.object({ z.object({available: z.literal(false), error_code: z.string(), execution_available: z.boolean().optional(), execution_error_code: z.string().optional()}), ]).optional(), - agent_candidates: z.array(privateAgentSessionSchema).default([]), agent_targets: z.array(privateAgentTargetSchema).default([]), + agent_candidates: z.array(privateAgentSessionSchema).default([]), }); +const privateConversationSchema = privateConversationSettingsRowSchema.extend(privateConversationDiagnosticsRowSchema.shape); const privateConversationStopRecoverySchema = z.object({binding_id: z.string(), project_ref: z.string(), project_title: z.string(), pending_count: z.number().int().positive()}); export type PrivateConversationStopRecovery = z.infer; -const privateConversationsSchema = z.object({ok: z.literal(true), revision: z.number().int(), +const privateConversationSettingsSchema = z.object({ok: z.literal(true), revision: z.number().int(), app_steward_binding_id: z.string().regex(/^[a-f0-9]{24}$/).nullable().default(null), + connections: z.array(privateConversationSettingsRowSchema)}); +const privateConversationDiagnosticsSchema = z.object({ok: z.literal(true), revision: z.number().int(), + connections: z.array(privateConversationDiagnosticsRowSchema), stop_recoveries: z.array(privateConversationStopRecoverySchema)}); +const privateConversationsSchema = privateConversationSettingsSchema.extend({ connections: z.array(privateConversationSchema), stop_recoveries: z.array(privateConversationStopRecoverySchema).default([])}); +export type PrivateConversationSettings = z.infer; +export type PrivateConversationDiagnostics = z.infer; export type PrivateConversation = z.infer; const boundConversationSourceSchema = privateConversationSchema.pick({ binding_id: true, app_ref: true, context_kind: true, project_title: true, executor_endpoint_id: true, @@ -3199,6 +3280,23 @@ export async function resolveBoundConversation(target: BoundConversationTarget, export async function fetchPrivateConversations(signal?: AbortSignal) { return privateConversationsSchema.parse(await requestJson("/api/chat/lark/private-conversations", { signal })); } + +export async function fetchPrivateConversationSettings(signal: AbortSignal) { + return privateConversationSettingsSchema.parse( + await requestJson("/api/chat/lark/private-conversations?view=settings", {signal})); +} + +export async function fetchPrivateConversationDiagnostics(settings: PrivateConversationSettings, signal: AbortSignal) { + const diagnostics = privateConversationDiagnosticsSchema.parse(await requestJson( + `/api/chat/lark/private-conversations?view=diagnostics&revision=${settings.revision}`, {signal})); + const observedBindingIds = new Set(diagnostics.connections.map(row => row.binding_id)); + if (diagnostics.revision !== settings.revision || diagnostics.connections.length !== settings.connections.length + || observedBindingIds.size !== diagnostics.connections.length + || !settings.connections.every(row => observedBindingIds.has(row.binding_id))) { + throw new Error("Conversation bindings changed during the read"); + } + return diagnostics; +} const appStewardTargetSchema = z.union([ z.object({ok: z.literal(true), binding_id: z.null(), session_id: z.null()}), z.object({ok: z.literal(true), binding_id: z.string().regex(/^[a-f0-9]{24}$/), @@ -3216,7 +3314,7 @@ export async function selectAppSteward(bindingId: string | null, revision: numbe return result; } export async function connectPrivateConversation(appRef: string, projectRef: string, executor: string, contextKind: "project" | "steward" = "project", projectGrant: "workspace_read" | "workspace_write" = "workspace_write", groupIds?: string[]) { - return privateConversationsSchema.parse(await requestJson("/api/chat/lark/private-conversations", { + return z.object({ok: z.literal(true)}).parse(await requestJson("/api/chat/lark/private-conversations?response=minimal", { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({app_ref: appRef, project_ref: projectRef, executor_endpoint_id: executor, context_kind: contextKind, project_grant: projectGrant, ...(contextKind === "steward" ? {goal_scope: "all_registered"} : {}), @@ -3224,7 +3322,7 @@ export async function connectPrivateConversation(appRef: string, projectRef: str })); } export async function disconnectPrivateConversation(bindingId: string, revision: number) { - return privateConversationsSchema.parse(await requestJson("/api/chat/lark/private-conversations", { + return z.object({ok: z.literal(true)}).parse(await requestJson("/api/chat/lark/private-conversations?response=minimal", { method: "DELETE", headers: {"Content-Type": "application/json"}, body: JSON.stringify({binding_id: bindingId, revision}), })); } @@ -3299,6 +3397,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/delivery-review.ts b/apps/presentation/dashboard/src/data/delivery-review.ts index 4986e2f37a..39781a7e42 100644 --- a/apps/presentation/dashboard/src/data/delivery-review.ts +++ b/apps/presentation/dashboard/src/data/delivery-review.ts @@ -1,5 +1,5 @@ import { z } from "zod"; -import { hasConfiguredGoalChecks, type GoalAcceptanceChecks, goalAcceptanceDisplayStatus, goalAcceptanceObservationSchema, projectGoalAcceptanceCriteria, type GoalAcceptanceContract } from "./goal-acceptance-observation.js"; +import { hasConfiguredGoalChecks, type GoalAcceptanceChecks, goalAcceptanceDisplayStatus, goalAcceptanceObservationSchema, projectGoalAcceptanceCriteria } from "./goal-acceptance-observation.js"; // Consumer validation only; freshness and coverage remain kernel decisions. const projectionEnvelopeSchema = z.object({ 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/goal-channel-frontstage.ts b/apps/presentation/dashboard/src/data/goal-channel-frontstage.ts index 66374f9adb..4dfa2baca4 100644 --- a/apps/presentation/dashboard/src/data/goal-channel-frontstage.ts +++ b/apps/presentation/dashboard/src/data/goal-channel-frontstage.ts @@ -401,13 +401,6 @@ export function leaseStatusTone(status?: string | null): BadgeTone { return LEASE_STATUS_TONES[normalizeToken(status)] ?? "neutral"; } -function stringifySourceRef(value: string | number | boolean | null | undefined): string { - if (value === null || value === undefined) { - return "n/a"; - } - return String(value); -} - export function deriveOperatorStateSignals( projection: GoalChannelProjection, ): OperatorStateSignal[] { diff --git a/apps/presentation/dashboard/src/data/status.ts b/apps/presentation/dashboard/src/data/status.ts index b79f89b55d..60d10a7ace 100644 --- a/apps/presentation/dashboard/src/data/status.ts +++ b/apps/presentation/dashboard/src/data/status.ts @@ -533,8 +533,15 @@ 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), + 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,8 +613,7 @@ 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"), 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/answer-report-page.tsx b/apps/presentation/dashboard/src/features/personal-workspace/answer-report-page.tsx index 5f38dc2034..167c0a129c 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/answer-report-page.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/answer-report-page.tsx @@ -1,6 +1,6 @@ import {useEffect, useMemo, useRef, useState} from "react"; -import {fetchChatSession, type ChatSessionSnapshot, type ChatVisibleMessage} from "../../data/chat"; +import {fetchSavedChatAnswer, type ChatSessionSnapshot, type ChatVisibleMessage} from "../../data/chat"; import {visibleAgentMessage} from "./answer-text"; import {readWorkspaceLocale} from "./i18n"; import {resolveConversationScope} from "../../../../../../loopx/control_plane/collaboration/conversation_scope"; @@ -24,7 +24,8 @@ export function AnswerReportPage({sessionId, messageId, statusUrl}: { messageId: string; statusUrl: string; }) { - const scope = JSON.stringify([statusUrl || "/status.json", sessionId, messageId]); + const turnId = new URLSearchParams(window.location.search).get("reportTurnId"); + const scope = JSON.stringify([statusUrl || "/status.json", sessionId, messageId, turnId]); const [loaded, setLoaded] = useState<{scope: string; value: ReportState} | null>(null); // A late read from the preceding source never appears in the new reader. const state: ReportState = loaded?.scope === scope ? loaded.value : {kind: "loading"}; @@ -44,16 +45,18 @@ export function AnswerReportPage({sessionId, messageId, statusUrl}: { setLoaded({scope, value: {kind: "loading"}}); setCopied(false); setCopyFailed(false); - void fetchChatSession(sessionId, controller.signal).then((snapshot) => { + const read = fetchSavedChatAnswer(sessionId, messageId, controller.signal, turnId ?? undefined); + void read.then((snapshot) => { if (!live) return; if (snapshot.ok !== true || snapshot.schema_version !== "loopx_chat_store_v1" || snapshot.session.session_id !== sessionId) throw new Error("The saved Session changed during read."); const message = snapshot.messages.find((item) => item.message_id === messageId - && ["agent", "assistant"].includes(item.role)); + && ["agent", "assistant"].includes(item.role) + && (turnId === null || item.turn_id === turnId)); setLoaded({scope, value: message ? {kind: "ready", snapshot, message} : {kind: "missing", snapshot}}); }).catch(() => { if (live) setLoaded({scope, value: {kind: "error"}}); }); return () => {live = false; controller.abort(); copyAttempt.current += 1; document.title = previousTitle;}; - }, [scope, sessionId, messageId, zh, readRevision]); + }, [scope, sessionId, messageId, turnId, zh, readRevision]); const navigation = answerReportNavigation( (state.kind === "ready" || state.kind === "missing") ? state.snapshot.session : null, window.location.href, statusUrl, zh, @@ -180,6 +183,7 @@ export function answerReportNavigation( const managed = scope.kind === "owner_goal" && session?.managed_agent_id; url.searchParams.delete("reportSessionId"); url.searchParams.delete("reportMessageId"); + url.searchParams.delete("reportTurnId"); url.searchParams.delete("todo"); url.searchParams.delete("messageSession"); url.searchParams.delete("message"); diff --git a/apps/presentation/dashboard/src/features/personal-workspace/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-timeline.tsx b/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx index a895b0b681..3390c06c70 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx @@ -21,12 +21,14 @@ 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) { +function answerLink(sessionId: string, messageId: string, turnId?: string) { const url = new URL(window.location.href); url.searchParams.set("reportSessionId", sessionId); url.searchParams.set("reportMessageId", messageId); + if (turnId) url.searchParams.set("reportTurnId", turnId); + else url.searchParams.delete("reportTurnId"); url.searchParams.set("view", "conversation"); url.hash = ""; return url.toString(); @@ -66,7 +68,7 @@ export const ChannelTimeline = memo(function ChannelTimeline({ onApplyGoalDraft, goalDraftPreparationContext, onSuggestReply, - onOpenGoalEvidence, + onOpenGoalChat, onInterruptTurn, onAdjustTurn, onCancelPreparation, @@ -94,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; }) { @@ -116,12 +118,10 @@ export const ChannelTimeline = memo(function ChannelTimeline({ useLayoutEffect(() => { if (!findMessageId) return; readMessage(); - const frame = requestAnimationFrame(() => { - const row = Array.from(timeline.current?.querySelectorAll("[data-timeline-id]") ?? []) - .find(node => node.dataset.timelineId === findMessageId); - row?.scrollIntoView({block: "start"}); - }); - return () => cancelAnimationFrame(frame); + // Keep the scroll with the selection so a later user scroll stays put. + const row = Array.from(timeline.current?.querySelectorAll("[data-timeline-id]") ?? []) + .find(node => node.dataset.timelineId === findMessageId); + row?.scrollIntoView({block: "start"}); }, [findMessageId, findNavigation]); const presentedItems = items.filter(item => { // The visible draft already owns this confirmation and recovery entry. @@ -248,19 +248,21 @@ export const ChannelTimeline = memo(function ChannelTimeline({ const appliedTeamPlan = item.proposal.actionKind === "team.plan" && item.proposal.status === "applied"; const taskReceipt = item.proposal.reviewPlan?.taskExecution; const pendingOperation = item.proposal.reviewPlan?.operationFrame?.kind === "pending"; + const pendingDisplay = item.proposal.reviewPlan?.reason === "canonical_create_projection_pending"; return ( {showManagerTeamResults && onOpenGoalEvidence && appliedTeamPlan + {showManagerTeamResults && onOpenGoalChat && appliedTeamPlan && item.proposal.goalId && item.proposal.teamPlanTodoIds?.length - ? + ? : null} ); } @@ -290,12 +292,12 @@ export const ChannelTimeline = memo(function ChannelTimeline({ {item.message.role === "assistant" && !item.message.pending && item.message.text.length >= MIN_SEPARATE_ANSWER_LENGTH && item.message.sourceSessionId && item.message.sourceMessageId - ? {locale === "zh-CN" ? "单独阅读完整答复" : "Read full answer separately"} : null} {item.message.role !== "user" && (item.message.pending || item.message.sourceTurnId || item.message.activity?.length || item.message.steps?.length) ? : null} {item.message.role === "assistant" && !item.message.pending && item.message.goalDraft - ? : null} + ? : null} 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..a1228c05b1 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx @@ -54,6 +54,45 @@ import { formatMonitorDate } from "./monitor-readback"; import { parseTodoCompletionProof } from "./todo-completion-feedback"; import { useDrawerOverlay } from "./workspace-shell"; +import { GoalStrategyDocument } from "./goal-source-strategies"; + +function SourceRunHistory({ goal, heading = false }: { goal: WorkspaceGoal; heading?: boolean }) { + const { t, locale } = useWorkspaceI18n(); + const history = goal.sourceRunHistory; + const recent = history?.recent ?? []; + const total = history?.total ?? null; + return
+ {heading ?

{t("drawer.sourceRunHistory")}

: null} + {goal.sourceAccess?.label} · {t("common.readOnly")} +
+
{t("drawer.sourceRunOriginalGoal")}
{goal.sourceAccess?.original_goal_id ?? goal.goalId}
+
+ {recent.length ? <> +

{total === null ? t("drawer.sourceRunRecent", {shown: recent.length}) + : t("drawer.sourceRunCount", {shown: recent.length, count: total})}

+
    {recent.map((run, index) =>
  1. +
    + +
    + {run.classification ?
    {t("drawer.sourceRunRecordType")}
    {run.classification}
    : null} +
    {t("drawer.sourceRunOriginalTurn")}
    + {run.turn_instance_id ? {run.turn_instance_id} : t("drawer.sourceRunUnrecorded")} +
    +
    {t("drawer.sourceRunCheckpoint")}
    + {run.vision_checkpoint ? {run.vision_checkpoint.decision} : t("drawer.sourceRunUnrecorded")} +
    +
    + {run.agent_vision ? + :

    {t("drawer.sourceRunDecisionUnavailable")}

    } +
    +
  2. )}
+ :

{t(total === 0 ? "drawer.noExecutionHistory" : "drawer.sourceRunUnavailable")}

} +
; +} + function subagentModelRequest(include: boolean, model: string, effort: string) { if (!include) return {}; if (!model.trim()) return { modelConfig: null }; @@ -186,6 +225,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 @@ -346,11 +392,19 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention const operationUnknown = selection.kind === "proposal" && selection.item.reviewPlan?.operationFrame?.kind === "result" && selection.item.reviewPlan.operationFrame.resultKind === "unknown"; + const completedTaskCreation = selection.kind === "proposal" + && (selection.item.actionKind === "todo.create" || selection.item.actionKind === "monitor.create") + && selection.item.reviewPlan?.interaction === "completed"; 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 +720,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 +1127,8 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention ) : null} - {selection.kind === "run" ? ( + {sourceRunGoal ? : null} + {selection.kind === "run" && !sourceRunGoal ? ( <>
@@ -1224,15 +1281,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 +1306,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")} @@ -1258,18 +1319,31 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention taskExecution.sessionId, taskExecution.turnId])} receipt={taskExecution} /> : selection.item.createdManagedSession?.invalid ?

{t("proposal.goalSessionUnavailable")}

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

{t("drawer.proposalStale")}

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

{t(selection.item.reviewPlan?.prohibitRegeneration ? "drawer.todoCreationStale" : "drawer.proposalStale")}

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

{t("drawer.proposalRejected")}

: null} {selection.item.reviewPlan?.operationFrame?.kind === "result" && selection.item.reviewPlan.operationFrame.resultKind === "cancelled" ?

{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", "todo.create", "monitor.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 +1388,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") ? ( <>

: !message ?

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

- : <>

{message.message}

+ : <> {message.attachments?.map(attachment => isTextDocument(attachment.mime_type) ? : {attachment.name}/)}}
: 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/composer-touch-focus.spec.mjs b/apps/workbench/packages/e2e/test/composer-touch-focus.spec.mjs new file mode 100644 index 0000000000..1265a04c0a --- /dev/null +++ b/apps/workbench/packages/e2e/test/composer-touch-focus.spec.mjs @@ -0,0 +1,69 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdirSync } from 'node:fs'; +import { join } from 'node:path'; +import { openCollaboration, startDaemon, openUi, api, launchBrowser } from '../harness.mjs'; + +test('touching collaboration keeps the empty composer mounted when taps do not focus buttons', 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(); + }; + try { + for (const mobile of [true, false]) for (const colorScheme of ['light', 'dark']) { + const title = `协作点击 ${mobile}-${colorScheme}`; + const thread = await post('/api/threads', { agent: 'pi', cwd: daemon.workdir, title }); + await post(`/api/threads/${thread.id}/coordination`, { directories: [daemon.workdir] }); + const context = await browser.newContext({ viewport: mobile ? { width: 390, height: 844 } : { width: 1440, height: 1000 }, isMobile: mobile, hasTouch: mobile, colorScheme }); + try { + const page = await context.newPage(); + await openUi(page, daemon); + if (mobile) await page.locator('.menu-btn').click(); + await page.locator('.thread-row').filter({ hasText: title }).click(); + // Model the no-native-button-focus path: pressing a button blurs the previous field, + // but does not focus the button. Chromium's normal touch behaviour misses this case. + if (mobile) await page.evaluate(() => { + document.addEventListener('mousedown', event => { + const button = event.target.closest?.('.composer button'); + if (!button) return; + event.preventDefault(); + if (document.activeElement !== button && document.activeElement instanceof HTMLElement) document.activeElement.blur(); + }, true); + }); + const input = page.locator('.composer textarea'); + const panel = page.getByRole('menu', { name: '协作', exact: true }); + const tap = async locator => mobile ? locator.tap() : locator.click(); + for (const running of [false, true]) { + if (running) await post(`/api/threads/${thread.id}/turns`, { text: 'slow' }); + await input.focus(); + await openCollaboration(page); + await page.waitForTimeout(300); + assert.ok(await panel.isVisible(), 'the menu survives blur and pointer release'); + assert.equal(await page.locator('.composer-box.collapsed').count(), 0); + await tap(panel.locator('.coord-picker-head button')); + await page.waitForTimeout(100); + assert.ok(await panel.locator('.coord-setup').isVisible(), 'settings remain usable with the same focus behaviour'); + 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, `collab-${mobile ? 'phone' : 'desktop'}-${colorScheme}-${running ? 'running' : 'idle'}.png`) }); + } + if (mobile) await page.locator('.topbar').tap({ position: { x: 150, y: 3 } }); + else await page.keyboard.press('Escape'); + await panel.waitFor({ state: 'detached' }); + // Ordinary focus leaving the composer still folds it; draft text still keeps it open. + await input.focus(); + await input.blur(); + if (mobile) await page.locator('.composer-box.collapsed').waitFor(); + await input.fill('保留草稿'); + await input.blur(); + assert.equal(await page.locator('.composer-box.collapsed').count(), 0); + await input.fill(''); + if (running) await post(`/api/threads/${thread.id}/cancel`, {}); + } + } finally { await context.close(); } + } + } finally { await browser.close(); await daemon.stop(); } +}); diff --git a/apps/workbench/packages/e2e/test/composer-touch-send.spec.mjs b/apps/workbench/packages/e2e/test/composer-touch-send.spec.mjs new file mode 100644 index 0000000000..39f60a1736 --- /dev/null +++ b/apps/workbench/packages/e2e/test/composer-touch-send.spec.mjs @@ -0,0 +1,248 @@ +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(); }); + +/** Each case gets an idle fake-agent thread and a fresh draft. */ +async function withComposer(run, { mobile = true, colorScheme = 'light' } = {}) { + const title = `输入法发送 ${Date.now()}-${colorScheme}`; + const created = await api(daemon, '/api/threads', { method: 'POST', body: JSON.stringify({ agent: 'pi', cwd: daemon.workdir, title }) }); + assert.ok(created.ok, await created.clone().text()); + const thread = await created.json(); + const context = await browser.newContext({ viewport: mobile ? { width: 390, height: 844 } : { width: 1440, height: 1000 }, isMobile: mobile, hasTouch: mobile, colorScheme }); + try { + const page = await context.newPage(); + await openUi(page, daemon); + if (mobile) await page.locator('.menu-btn').tap(); + await page.locator('.thread-row').filter({ hasText: title }).click(); + const requests = []; + const turns = `**/api/threads/${thread.id}/turns`; + page.on('request', request => { + if (request.method() === 'POST' && request.url().endsWith(`/api/threads/${thread.id}/turns`)) requests.push(request.postDataJSON()); + }); + await run({ page, input: page.locator('.composer textarea'), send: page.locator('.composer .send-btn:not(.stop)'), requests, turns }); + } finally { await context.close(); } +} + +/** Headless Chromium has no OS keyboard; shrink the visual viewport as a phone keyboard does. */ +async function keyboardHeight(page, height) { + await page.evaluate(height => { + const vv = window.visualViewport; + Object.defineProperty(vv, 'height', { configurable: true, get: () => height }); + vv.dispatchEvent(new Event('resize')); + }, height); +} + +/** Model an IME whose final input follows compositionend, including a native value change. */ +async function composingDraft(input, finalText, commitOnBlur = false) { + await input.focus(); + await input.evaluate((el, { finalText, commitOnBlur }) => { + window.imeEvents = []; + const setValue = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value').set; + window.commitIme = () => { + window.imeEvents.push('compositionend'); + el.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true, data: finalText })); + // The trailing input must reach React before the retained tap reads its submit callback. + setValue.call(el, finalText); + el.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText', data: finalText, isComposing: false })); + window.imeEvents.push('final-input'); + }; + if (commitOnBlur) el.addEventListener('blur', () => { + window.imeEvents.push('blur'); + if (commitOnBlur === true) queueMicrotask(window.commitIme); + }, { once: true }); + document.addEventListener('pointerup', () => window.imeEvents.push('release'), { once: true, capture: true }); + el.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true })); + setValue.call(el, 'zhongwen'); + el.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertCompositionText', data: 'zhongwen', isComposing: true })); + }, { finalText, commitOnBlur }); +} + +async function holdSend(page, turns) { + let release; + const gate = new Promise(resolve => { release = resolve; }); + await page.route(turns, async route => { await gate; await route.continue().catch(() => undefined); }); + return release; +} + +test('touching send submits even when the keyboard blur swallows the click', async () => { + await withComposer(async ({ page, input, send, requests }) => { + await page.evaluate(() => { + document.addEventListener('pointerdown', event => { + const button = event.target instanceof Element ? event.target.closest('.composer .send-btn:not(.stop)') : null; + if (!button) return; + // Some mobile browsers first let the focused input lose focus, which closes the keyboard. + if (document.activeElement instanceof HTMLElement) document.activeElement.blur(); + }, true); + document.addEventListener('click', event => { + const button = event.target instanceof Element ? event.target.closest('.composer .send-btn:not(.stop)') : null; + if (!button) return; + event.preventDefault(); + event.stopImmediatePropagation(); + }, true); + }); + await input.tap(); + await input.fill('mobile first tap send'); + await send.tap(); + await page.getByText('hi there mobile first tap send').waitFor({ timeout: 15_000 }); + assert.deepEqual(requests.map(r => r.text), ['mobile first tap send']); + assert.equal(await input.inputValue(), ''); + }); +}); + +for (const colorScheme of ['light', 'dark']) test(`finalized native Chinese sends once with the keyboard up and keeps focus (${colorScheme})`, async () => { + await withComposer(async ({ page, input, send, requests }) => { + await input.tap(); + const cdp = await page.context().newCDPSession(page); + await cdp.send('Input.imeSetComposition', { text: 'zhongwen', selectionStart: 8, selectionEnd: 8 }); + await cdp.send('Input.insertText', { text: '中文消息' }); + await keyboardHeight(page, 500); + await send.tap(); + await page.getByText('hi there 中文消息').waitFor({ timeout: 15_000 }); + await page.waitForTimeout(550); + assert.deepEqual(requests.map(r => r.text), ['中文消息']); + assert.equal(await input.inputValue(), ''); + assert.ok(await input.evaluate(el => document.activeElement === el)); + await cdp.detach(); + }, { colorScheme }); +}); + +test('one tap finishes active composition after release and sends the trailing final input once', async () => { + await withComposer(async ({ page, input, send, requests, turns }) => { + const release = await holdSend(page, turns); + try { + await composingDraft(input, '中文已定稿', 'manual'); + await keyboardHeight(page, 500); + await send.tap(); + await page.waitForTimeout(100); + assert.deepEqual(requests, [], 'no request may snapshot text before compositionend and final input'); + assert.deepEqual(await page.evaluate(() => window.imeEvents), ['release', 'blur']); + const sent = page.waitForRequest(request => request.method() === 'POST' && request.url().endsWith('/turns')); + await page.evaluate(() => window.commitIme()); + await sent; + assert.deepEqual(requests.map(r => r.text), ['中文已定稿'], 'the same tap sends final Chinese, never interim spelling'); + assert.deepEqual(await page.evaluate(() => window.imeEvents), ['release', 'blur', 'compositionend', 'final-input']); + await send.dispatchEvent('click', { detail: 1 }); + } finally { release(); } + await page.getByText('hi there 中文已定稿').waitFor({ timeout: 15_000 }); + await page.waitForTimeout(550); + assert.deepEqual(requests.map(r => r.text), ['中文已定稿']); + assert.equal(await input.inputValue(), ''); + assert.ok(await input.evaluate(el => document.activeElement === el)); + }); +}); + +test('active native composition finishes on the same tap even when compositionend has no trailing input', async () => { + await withComposer(async ({ page, input, send, requests, turns }) => { + const release = await holdSend(page, turns); + try { + await input.tap(); + const cdp = await page.context().newCDPSession(page); + await input.evaluate(el => { + window.nativeImeEnded = false; + el.addEventListener('compositionend', () => { window.nativeImeEnded = true; }, { once: true }); + }); + await cdp.send('Input.imeSetComposition', { text: '中文候选', selectionStart: 4, selectionEnd: 4 }); + await send.tap(); + await page.waitForTimeout(100); + assert.ok(await page.evaluate(() => window.nativeImeEnded), 'send explicitly terminates the active native composition'); + assert.deepEqual(requests.map(r => r.text), ['中文候选']); + await cdp.detach(); + } finally { release(); } + await page.getByText('hi there 中文候选').waitFor({ timeout: 15_000 }); + assert.equal(await input.inputValue(), ''); + assert.ok(await input.evaluate(el => document.activeElement === el)); + }); +}); + +test('a slow successful send preserves Chinese committed while the request was pending', async () => { + await withComposer(async ({ page, input, send, requests, turns }) => { + const release = await holdSend(page, turns); + const completed = page.waitForResponse(response => response.request().method() === 'POST' && response.url().endsWith('/turns')); + try { + await input.fill('first finalized message'); + await send.tap(); + await page.waitForTimeout(100); + assert.deepEqual(requests.map(r => r.text), ['first finalized message']); + await composingDraft(input, '稍后提交的中文'); + await page.evaluate(() => window.commitIme()); + } finally { release(); } + await completed; + await page.getByText('hi there first finalized message').waitFor({ timeout: 15_000 }); + await page.waitForTimeout(100); + assert.equal(await input.inputValue(), '稍后提交的中文', 'an earlier send must not clear a later IME commit'); + const stored = await page.evaluate(() => JSON.parse(localStorage.getItem('calli.drafts') ?? '{}')); + assert.ok(Object.values(stored).some(draft => draft.text === '稍后提交的中文'), 'the surviving draft is durable too'); + }); +}); + +test('a failed send from an active composition keeps the finalized draft for retry', async () => { + await withComposer(async ({ page, input, send, requests, turns }) => { + await page.route(turns, route => route.fulfill({ status: 503, json: { error: 'fake send failed' } })); + await composingDraft(input, '失败后保留中文', true); + await send.tap(); + await page.getByText('fake send failed', { exact: true }).waitFor(); + assert.deepEqual(requests.map(r => r.text), ['失败后保留中文']); + assert.equal(await input.inputValue(), '失败后保留中文'); + assert.ok(await input.evaluate(el => document.activeElement === el)); + }); +}); + +for (const ending of ['slide', 'cancel']) test(`a previous suppression timer cannot send a later ${ending} gesture through a compatibility click`, async () => { + await withComposer(async ({ page, input, send, requests }) => { + await input.fill('gesture draft'); + await page.clock.install({ time: new Date('2026-01-01T00:00:00Z') }); + await page.clock.pauseAt(new Date('2026-01-01T00:00:01Z')); + await send.evaluate(button => { + // Synthetic pointer IDs let the two gestures and old timeout overlap deterministically. + button.setPointerCapture = () => undefined; + button.hasPointerCapture = () => false; + window.sendGesture = (type, pointerId, offset = 0) => { + const rect = button.getBoundingClientRect(); + button.dispatchEvent(new PointerEvent(type, { bubbles: true, cancelable: true, pointerType: 'touch', pointerId, + clientX: rect.x + rect.width / 2 + offset, clientY: rect.y + rect.height / 2 })); + }; + }); + await page.evaluate(() => { + window.sendGesture('pointerdown', 1); + window.sendGesture('pointermove', 1, 20); + window.sendGesture('pointerup', 1); + }); + await page.clock.runFor(400); + await page.evaluate(ending => { + window.sendGesture('pointerdown', 2); + if (ending === 'slide') { + window.sendGesture('pointermove', 2, 20); + window.sendGesture('pointerup', 2); + } else window.sendGesture('pointercancel', 2); + }, ending); + await page.clock.runFor(100); + await send.dispatchEvent('click', { detail: 1 }); + await page.waitForTimeout(100); + assert.deepEqual(requests, [], 'a canceled or slid gesture and its compatibility click send nothing'); + assert.equal(await input.inputValue(), 'gesture draft'); + // Keyboard and assistive activation have detail=0 and remain available during suppression. + await send.dispatchEvent('click', { detail: 0 }); + await page.waitForTimeout(100); + assert.deepEqual(requests.map(r => r.text), ['gesture draft']); + }); +}); + +test('desktop Enter keeps native IME guards and Shift+Enter behavior', async () => { + await withComposer(async ({ page, input, requests }) => { + await input.fill('desktop 中文'); + await input.dispatchEvent('keydown', { key: 'Enter', code: 'Enter', isComposing: true }); + await input.dispatchEvent('keydown', { key: 'Enter', code: 'Enter', keyCode: 229 }); + await page.waitForTimeout(100); + assert.deepEqual(requests, []); + await input.press('Shift+Enter'); + assert.equal(await input.inputValue(), 'desktop 中文\n'); + await input.press('Control+Enter'); + await page.getByText('hi there desktop 中文').waitFor({ timeout: 15_000 }); + assert.deepEqual(requests.map(r => r.text), ['desktop 中文']); + }, { mobile: false }); +}); diff --git a/apps/workbench/packages/e2e/test/context-controls.spec.mjs b/apps/workbench/packages/e2e/test/context-controls.spec.mjs new file mode 100644 index 0000000000..1b5631dc32 --- /dev/null +++ b/apps/workbench/packages/e2e/test/context-controls.spec.mjs @@ -0,0 +1,248 @@ +import { test, before, after } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdirSync } from 'node:fs'; +import { join } from 'node:path'; +import { startDaemon, openUi, api, launchBrowser, repoRoot } from '../harness.mjs'; + +let daemon; +let browser; +before(async () => { + daemon = await startDaemon({ + FAKE_CODEX_WEEKLY_ONLY: '1', FAKE_CODEX_NO_EFFORT_MODEL: '1', + LOOCHAT_AGENTS_JSON: JSON.stringify({ agents: ['claude', 'codex', 'pi'].map((id) => ({ + id, adapter: id, command: [process.execPath, join(repoRoot, 'daemon/test/fixtures', `fake-${id === 'claude' ? 'acp' : id}.mjs`)], + })) }), + }); + browser = await launchBrowser(); +}); +after(async () => { await browser?.close(); await daemon?.stop(); }); +const waitFor = async (fn) => { + for (let i = 0; i < 160; i++) { if (await fn()) return; await new Promise((r) => setTimeout(r, 50)); } + assert.fail('state did not settle'); +}; +const read = async (thread) => (await api(daemon, `/api/threads/${thread.id}`)).json(); +const send = async (thread, text) => { + const res = await api(daemon, `/api/threads/${thread.id}/turns`, { method: 'POST', body: JSON.stringify({ text }) }); + assert.ok(res.ok, await res.clone().text()); +}; +async function makeThread(title, agent = 'codex') { + const response = await api(daemon, '/api/threads', { method: 'POST', body: JSON.stringify({ agent, cwd: daemon.workdir, title }) }); + assert.equal(response.status, 201); + const thread = await response.json(); + await send(thread, 'usage'); + await waitFor(async () => { + const value = await read(thread); + return value.status === 'idle' && !['checking', 'preparing', 'countdown'].includes(value.autoHandover?.state); + }); + return thread; +} +async function select(page, thread, mobile = false) { + await openUi(page, daemon); + if (mobile) await page.locator('.menu-btn').click(); + await page.locator('.thread-title', { hasText: thread.title }).first().click(); + // On a phone an empty box is one line until it is touched; the controls are on its second. + if (mobile) await page.locator('.composer textarea').tap(); + await page.locator('.model-control-trigger:visible').waitFor(); +} +async function shot(page, name) { + await page.waitForTimeout(350); + 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`) }); +} +async function fits(page, locator) { + const bounds = await locator.boundingBox(); + assert.ok(bounds && bounds.x >= 0 && bounds.y >= 0 && bounds.x + bounds.width <= page.viewportSize().width + 1 && bounds.y + bounds.height <= page.viewportSize().height + 1); +} + +test('effort slider, model subview, reset and compression work in both themes and viewport sizes', async () => { + for (const mobile of [false, true]) for (const colorScheme of ['light', 'dark']) { + const tag = `${mobile ? 'phone' : 'desktop'}-${colorScheme}`; + const thread = await makeThread(`上下文操作 ${tag}`); + const context = await browser.newContext({ viewport: mobile ? { width: 390, height: 844 } : { width: 1400, height: 900 }, isMobile: mobile, hasTouch: mobile, colorScheme }); + try { + const page = await context.newPage(); + await select(page, thread, mobile); + await page.locator('.model-control-trigger').click(); + const slider = page.getByRole('slider', { name: '思考强度' }); + await slider.waitFor(); + const modelPanel = page.locator('.model-control-panel'); + assert.equal(await modelPanel.locator('.model-context, .context-percent').count(), 0); + assert.equal(await modelPanel.getByText('上下文', { exact: true }).count(), 0); + assert.equal(await modelPanel.getByRole('button', { name: /压缩/ }).count(), 0); + await slider.press('Home'); + await waitFor(async () => (await read(thread)).effort === null); + await page.waitForTimeout(350); + assert.equal(await slider.getAttribute('aria-valuemax'), '3'); + const rail = await slider.locator('.effort-rail').boundingBox(); + if (mobile) await page.touchscreen.tap(rail.x + rail.width, rail.y + rail.height / 2); + else { + let patches = 0; + page.on('request', (request) => { if (request.method() === 'PATCH' && request.url().endsWith(`/threads/${thread.id}`)) patches++; }); + await page.mouse.move(rail.x, rail.y + rail.height / 2); + await page.mouse.down(); + await page.mouse.move(rail.x + rail.width, rail.y + rail.height / 2, { steps: 8 }); + assert.equal(patches, 0, 'dragging only previews the selection'); + await page.mouse.up(); + await waitFor(async () => (await read(thread)).effort === 'max'); + await waitFor(async () => patches === 1); + assert.equal(patches, 1, 'releasing writes once'); + } + await waitFor(async () => (await read(thread)).effort === 'max'); + await shot(page, `effort-${tag}`); + await fits(page, page.locator('.model-control-panel')); + assert.equal(await slider.getAttribute('aria-valuetext'), '最大'); + await slider.press('ArrowLeft'); + await waitFor(async () => (await read(thread)).effort === 'high'); + await slider.press('End'); + await waitFor(async () => (await read(thread)).effort === 'max'); + // The button shows the level as a dial; its name says it in words. A phone shows the dial alone. + await waitFor(async () => (await page.locator('.model-control-trigger').getAttribute('aria-label')) === '模型与思考强度:GPT Big · 最大'); + assert.equal(await page.locator('.model-control-trigger').getAttribute('aria-label'), '模型与思考强度:GPT Big · 最大'); + assert.equal(await page.locator('.model-control-trigger .model-trigger-name').count(), mobile ? 0 : 1); + if (mobile) { + assert.equal(await page.locator('.model-control-trigger.dial-only .model-trigger-gauge svg').count(), 1); + assert.equal(await page.locator('.model-control-trigger.usage, .model-control-trigger .usage-track').count(), 0, 'the effort dial is not the context ring'); + const dial = await page.locator('.model-control-trigger').boundingBox(); + assert.equal(Math.round(dial.width), Math.round(dial.height), `the dial button is a circle (${dial.width}×${dial.height})`); + } + await page.getByRole('button', { name: '恢复默认强度' }).click(); + await waitFor(async () => (await read(thread)).effort === null); + await page.getByRole('button', { name: /切换模型/ }).click(); + assert.equal(await modelPanel.getByRole('button', { name: /压缩/ }).count(), 0); + assert.equal(await modelPanel.getByText('上下文', { exact: true }).count(), 0); + await page.getByRole('menuitemradio', { name: 'GPT Small', exact: true }).click(); + await waitFor(async () => (await read(thread)).model === 'gpt-small'); + await waitFor(async () => (await slider.getAttribute('aria-valuemax')) === '2'); + assert.equal(await slider.getAttribute('aria-valuemax'), '2'); + await slider.press('End'); + await waitFor(async () => (await read(thread)).effort === 'high'); + await page.getByRole('button', { name: /切换模型/ }).click(); + await page.getByRole('menuitemradio', { name: 'GPT Basic', exact: true }).click(); + await page.getByText('当前模型不提供思考强度设置。').waitFor(); + assert.equal(await slider.count(), 0); + await page.keyboard.press('Escape'); + await page.locator('.model-control-trigger').click(); + await page.getByRole('menuitemradio', { name: /GPT Big/ }).last().click(); + await slider.waitFor(); + await page.keyboard.press('Escape'); + const input = page.locator('.composer textarea'); + await input.fill('这段草稿需要保留'); + const usage = page.locator('.composer .usage'); + await usage.click(); + const usagePanel = page.locator('.context-usage-panel'); + await usagePanel.waitFor(); + assert.equal(await modelPanel.count(), 0); + assert.equal(await usagePanel.getByRole('slider', { name: '思考强度' }).count(), 0); + await shot(page, `compact-${tag}`); + await fits(page, usagePanel); + await usagePanel.getByRole('button', { name: '压缩', exact: true }).click(); + await usagePanel.waitFor({ state: 'hidden' }); + assert.equal(await usage.getAttribute('aria-expanded'), 'false'); + await page.getByText('上下文压缩完成。', { exact: true }).waitFor(); + assert.equal(await input.inputValue(), '这段草稿需要保留'); + await input.fill('/usage'); + await input.press('Enter'); + const list = page.getByRole('region', { name: '额度', exact: true }); + await list.getByRole('button', { name: '查看 Codex 的额度详情', exact: true }).click(); + const quota = page.getByRole('region', { name: 'Codex', exact: true }); + await quota.getByText('本次仅返回每周额度,服务端未提供 5 小时窗口。').waitFor(); + assert.equal(await quota.getByRole('meter').count(), 1); + assert.match(await quota.getByRole('meter').getAttribute('aria-label'), /^每周/); + await shot(page, `quota-weekly-${tag}`); + } finally { await context.close(); } + } +}); + +test('the effort slider follows the finger and does not snap back while the change is saved', async () => { + const thread = await makeThread('强度滑块不跳'); + const context = await browser.newContext({ viewport: { width: 1400, height: 900 } }); + try { + const page = await context.newPage(); + // The server answers slowly, then not at all: the slider must not wait for it either way. + let held = null; + let fail = false; + await page.route(`**/api/threads/${thread.id}`, async (route) => { + if (route.request().method() !== 'PATCH') return route.continue(); + await new Promise((resolve) => { held = resolve; }); + if (fail) await route.fulfill({ status: 500, json: { error: 'nope' } }); + else await route.continue(); + }); + await select(page, thread); + await page.locator('.model-control-trigger').click(); + const slider = page.getByRole('slider', { name: '思考强度' }); + await slider.waitFor(); + const rail = await slider.locator('.effort-rail').boundingBox(); + const thumbX = async () => { const b = await slider.locator('.effort-thumb').boundingBox(); return b.x + b.width / 2; }; + const y = rail.y + rail.height / 2; + + // Between two levels the thumb is under the finger, not on a dot; the label is the nearest level. + await page.mouse.move(rail.x, y); + await page.mouse.down(); + await page.mouse.move(rail.x + rail.width * 0.6, y, { steps: 6 }); + assert.ok(Math.abs((await thumbX()) - (rail.x + rail.width * 0.6)) < 2, 'the thumb is under the finger'); + assert.equal(await page.locator('.effort-value').innerText(), '高'); + await page.mouse.move(rail.x + rail.width, y, { steps: 4 }); + await page.mouse.up(); + + // Let go, the server has not answered yet: the slider stays where it was put. + await waitFor(async () => held !== null); + assert.equal(await slider.getAttribute('aria-valuetext'), '最大'); + assert.equal(await page.locator('.effort-value').innerText(), '最大'); + await page.waitForTimeout(300); + assert.ok(Math.abs((await thumbX()) - (rail.x + rail.width)) < 2, 'the thumb stays at the end'); + held(); + await waitFor(async () => (await read(thread)).effort === 'max'); + + // A change the server refuses goes back to what was there. + fail = true; + held = null; + await slider.press('ArrowLeft'); + await waitFor(async () => held !== null); + assert.equal(await slider.getAttribute('aria-valuetext'), '高'); + held(); + await waitFor(async () => (await slider.getAttribute('aria-valuetext')) === '最大'); + assert.equal((await read(thread)).effort, 'max'); + } finally { await context.close(); } +}); + +test('compression queues once during a turn and preserves a draft; pi uses its own compact command', async () => { + const thread = await makeThread('排队压缩'); + const context = await browser.newContext(); + try { + const page = await context.newPage(); + await page.route('**/api/agents', async (route) => { + const response = await route.fetch(); + const agents = await response.json(); + for (const agent of agents) delete agent.capabilities.compact; + await route.fulfill({ response, json: agents }); + }); + await send(thread, 'delayed'); + await select(page, thread); + await page.locator('.composer textarea').fill('下一轮草稿'); + await page.getByRole('button', { name: '停止', exact: true }).waitFor(); + const usage = page.locator('.composer .usage'); + const usagePanel = page.locator('.context-usage-panel'); + await usage.click(); + await usagePanel.getByRole('button', { name: '本轮后压缩', exact: true }).click(); + await usagePanel.waitFor({ state: 'hidden' }); + assert.equal(await usage.getAttribute('aria-expanded'), 'false'); + await waitFor(async () => (await read(thread)).queued.length === 1); + // A successful submission closes the menu; reopen it to inspect the queued action. + await usage.click(); + const queuedCompact = usagePanel.getByRole('button', { name: /已排队压缩/ }); + await queuedCompact.waitFor(); + assert.ok(await queuedCompact.isDisabled()); + assert.equal((await read(thread)).queued.length, 1); + await page.keyboard.press('Escape'); + await page.getByText('上下文压缩完成。', { exact: true }).waitFor(); + assert.equal(await page.locator('.composer textarea').inputValue(), '下一轮草稿'); + const pi = await makeThread('pi 压缩操作', 'pi'); + await select(page, pi); + await usage.click(); + await usagePanel.getByRole('button', { name: '压缩', exact: true }).click(); + await usagePanel.waitFor({ state: 'hidden' }); + assert.equal(await usage.getAttribute('aria-expanded'), 'false'); + await page.getByText('已压缩上下文:150.0k → 约 32.0k tokens。', { exact: true }).waitFor(); + } finally { await context.close(); } +}); diff --git a/apps/workbench/packages/e2e/test/context-references.spec.mjs b/apps/workbench/packages/e2e/test/context-references.spec.mjs new file mode 100644 index 0000000000..9a54633175 --- /dev/null +++ b/apps/workbench/packages/e2e/test/context-references.spec.mjs @@ -0,0 +1,118 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdirSync } from 'node:fs'; +import { join } from 'node:path'; +import { startDaemon, openUi, api, launchBrowser } from '../harness.mjs'; + +test('compact references coexist with notes, survive reload/failure/queue editing, and work on four layouts', { timeout: 180000 }, async () => { + const daemon = await startDaemon(); + const browser = await launchBrowser(); + const shots = process.env.LOOCHAT_REFERENCE_SHOTS; + if (shots) mkdirSync(shots, { recursive: true }); + const post = async (path, body) => { + const response = await api(daemon, path, { method: 'POST', body: JSON.stringify(body) }); + assert.ok(response.ok, `${path}: ${await response.clone().text()}`); + return response.json(); + }; + const idle = async id => { + for (let i = 0; i < 100; i++) { + if ((await (await api(daemon, `/api/threads/${id}`)).json()).status !== 'running') return; + await new Promise(resolve => setTimeout(resolve, 50)); + } + throw new Error('agent did not finish'); + }; + try { + const source = await post('/api/threads', { agent: 'pi', cwd: daemon.workdir, title: 'Reference source' }); + await post(`/api/threads/${source.id}/turns`, { text: 'Reference source question' }); + await idle(source.id); + for (const mobile of [false, true]) for (const theme of ['light', 'dark']) { + const thread = await post('/api/threads', { agent: 'pi', cwd: daemon.workdir, title: `References ${mobile} ${theme}` }); + await post(`/api/threads/${thread.id}/turns`, { text: 'Please explain the design.' }); + await idle(thread.id); + const context = await browser.newContext({ viewport: mobile ? { width: 390, height: 844 } : { width: 1440, height: 1000 }, isMobile: mobile, hasTouch: mobile }); + const page = await context.newPage(); + const errors = []; + page.on('pageerror', error => errors.push(error.message)); + await openUi(page, daemon); + await page.evaluate(({ id, theme }) => { document.documentElement.dataset.theme = theme; location.hash = `#/thread/${id}`; }, { id: thread.id, theme }); + const composer = page.locator('.composer'); + const input = composer.locator('textarea').last(); + await page.getByRole('button', { name: '引用整条回复', exact: true }).last().click(); + await composer.locator('.note-strip').waitFor(); + await input.fill('Please use @'); + await page.locator('.reference-picker').waitFor(); + // One kind of reference at a time: folders wait in their own tab, not below the chats. + assert.equal(await page.getByRole('tab').count(), 3); + assert.equal(await page.getByRole('button', { name: '引用此目录', exact: true }).count(), 0); + await page.locator('.reference-option', { hasText: 'Reference source' }).click(); + await composer.locator('.context-reference').waitFor(); + assert.equal(await input.inputValue(), 'Please use '); + await composer.getByRole('button', { name: '引用会话或目录', exact: true }).click(); + await page.getByRole('tab', { name: /目录/ }).click(); + await page.getByRole('button', { name: '引用此目录', exact: true }).click(); + await composer.locator('.context-reference').nth(1).waitFor(); + assert.equal(await composer.locator('.context-reference').count(), 2); + await input.fill('Compare these references and follow note 1.'); + await page.waitForTimeout(500); + await page.reload(); + await page.locator('.sidebar-inner').waitFor({ state: 'attached' }); + await page.evaluate(id => { location.hash = `#/thread/${id}`; }, thread.id); + await composer.locator('.context-reference').nth(1).waitFor(); + await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme); + assert.equal(await composer.locator('.note-strip').count(), 1); + await composer.locator('.context-reference button').first().click(); + await page.getByRole('dialog').waitFor(); + await page.waitForTimeout(250); + assert.ok(await page.getByRole('dialog').evaluate(element => { + const rect = element.getBoundingClientRect(); + return rect.top >= 0 && rect.bottom <= innerHeight && rect.left >= 0 && rect.right <= innerWidth; + }), 'reference details stay inside the viewport'); + if (shots) await page.screenshot({ path: join(shots, `${mobile ? 'mobile' : 'desktop'}-${theme}-details.png`) }); + await page.getByRole('button', { name: '关闭', exact: true }).last().click(); + if (shots) await page.screenshot({ path: join(shots, `${mobile ? 'mobile' : 'desktop'}-${theme}-composer.png`) }); + await composer.getByRole('button', { name: '引用会话或目录', exact: true }).click(); + await page.locator('.reference-picker').waitFor(); + await page.getByRole('tab', { name: /目录/ }).click(); + await page.getByRole('button', { name: '引用此目录', exact: true }).waitFor(); + await page.waitForTimeout(250); + if (shots) await page.screenshot({ path: join(shots, `${mobile ? 'mobile' : 'desktop'}-${theme}-picker.png`) }); + await page.keyboard.press('Escape'); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true); + // A refused send must leave references and notes editable. + await page.route('**/turns', route => route.fulfill({ status: 503, contentType: 'application/json', body: JSON.stringify({ error: 'test send failed' }) }), { times: 1 }); + await composer.locator('.send-btn:not(.stop)').click(); + await page.getByText('test send failed', { exact: true }).waitFor(); + await composer.locator('.context-reference').nth(1).waitFor(); + assert.equal(await composer.locator('.context-reference').count(), 2); + assert.equal(await composer.locator('.note-strip').count(), 1); + // Queue and take back the same message; structured UI must recover from the wire text. + await post(`/api/threads/${thread.id}/turns`, { text: 'slow' }); + await composer.locator('.send-btn.stop').waitFor(); + await composer.locator('.send-btn:not(.stop)').click(); + await composer.locator('.queue-item').waitFor(); + assert.equal(await composer.locator('.context-reference').count(), 0); + assert.ok(!(await composer.locator('.queue-item').innerText()).includes('loochat-references')); + await composer.locator('.queue-item').getByRole('button', { name: /编辑/ }).click(); + await composer.locator('.context-reference').nth(1).waitFor(); + assert.equal(await composer.locator('.note-strip').count(), 1); + await composer.locator('.send-btn.stop').click(); + await idle(thread.id); + await composer.locator('.send-btn:not(.stop)').click(); + await page.locator('.row.user .context-reference').nth(1).waitFor(); + assert.equal(await composer.locator('.note-strip').count(), 0); + const events = await (await api(daemon, `/api/threads/${thread.id}/events`)).json(); + const started = events.findLast(event => event.type === 'turn.started'); + assert.match(started.data.text, /loochat references/); + assert.match(started.data.text, /\[注释 1\]/); + assert.ok(!started.data.displayText.includes('loochat-reference-reader')); + await idle(thread.id); + await page.locator('.row.user').last().getByRole('button', { name: '编辑这条消息', exact: true }).click(); + const edit = page.locator('.message-edit'); + assert.equal(await edit.locator('.context-reference').count(), 2); + assert.ok(!(await edit.locator('textarea').inputValue()).includes('loochat-references')); + await edit.getByRole('button', { name: '取消', exact: true }).click(); + assert.deepEqual(errors, []); + await context.close(); + } + } finally { await browser.close(); await daemon.stop(); } +}); diff --git a/apps/workbench/packages/e2e/test/conversation.spec.mjs b/apps/workbench/packages/e2e/test/conversation.spec.mjs new file mode 100644 index 0000000000..744d8c17dd --- /dev/null +++ b/apps/workbench/packages/e2e/test/conversation.spec.mjs @@ -0,0 +1,137 @@ +// How a turn is shown: thinking as its own collapsible section, tool rows with verbs and +// durations, the work group collapsing once the turn is done. +import { test, before, after } from 'node:test'; +import assert from 'node:assert/strict'; +import { startDaemon, openUi, launchBrowser } from '../harness.mjs'; + +let daemon; +let browser; +let page; + +before(async () => { + daemon = await startDaemon(); + browser = await launchBrowser(); + const ctx = await browser.newContext({ viewport: { width: 1400, height: 900 } }); + page = await ctx.newPage(); +}); + +after(async () => { + await browser?.close(); + await daemon?.stop(); +}); + +test('a turn shows thinking, verb-first tool rows, and folds its work away when done', async () => { + await openUi(page, daemon); + await page.locator('.composer .context-btn').first().click(); + await page.getByRole('menuitemradio', { name: /^pi/ }).click(); + await page.locator('.composer textarea').click(); + await page.keyboard.type('slowthink'); + await page.keyboard.press('Enter'); + + // While it runs: the work group is open, thinking is expanded and says so. + await page.locator('.thinking').waitFor({ timeout: 10_000 }); + assert.match(await page.locator('.thinking-toggle').innerText(), /思考中/); + + // Tool rows appear while the turn is still running, verb first; the one in flight says so. + await page.locator('.step').first().waitFor({ timeout: 10_000 }); + assert.match(await page.locator('.step-title').first().innerText(), /^运行了\s+ls/); + const inFlight = page.locator('.step', { hasText: 'npm test' }); + await inFlight.waitFor({ timeout: 10_000 }); + assert.equal((await inFlight.locator('.step-status').innerText()).trim(), '运行中'); + + // Once the turn is done the work folds to one line and thinking collapses with a duration. + await page.getByText('hi there slowthink').waitFor({ timeout: 15_000 }); + await page.locator('.work-toggle', { hasText: '用时' }).first().waitFor({ timeout: 10_000 }); + const toggle = await page.locator('.work-toggle').first().innerText(); + assert.match(toggle, /用时/); + assert.match(toggle, /2 步/); + + // Expanding the work group again: what was said in between became the answer, so the two calls + // are one run now, and a run of calls is one line that counts them. Opened, thinking is one + // collapsed line and the steps are there. + await page.locator('.work-toggle').first().click(); + const run = page.locator('.work-body .run-head'); + assert.equal((await run.innerText()).trim(), '已运行 2 条命令'); + assert.equal(await page.locator('.step').count(), 0); + await run.click(); + await page.locator('.step').first().waitFor({ state: 'visible' }); + assert.equal(await page.locator('.run-body .step').count(), 2); + assert.match(await page.locator('.thinking-toggle').innerText(), /^思考/); + assert.equal(await page.locator('.thinking-para').count(), 0); + + // Thinking itself expands into its paragraphs. + await page.locator('.thinking-toggle').first().click(); + await page.locator('.thinking-para').first().waitFor({ state: 'visible' }); + assert.match(await page.locator('.thinking-para').first().innerText(), /hmm/); +}); + +test('while a turn runs its steps stay the story: no changes card until it ends', async () => { + await page.locator('.side-nav').getByRole('button', { name: '新对话', exact: true }).click(); + await page.locator('.composer .context-btn').first().click(); + await page.getByRole('menuitemradio', { name: /^pi/ }).click(); + await page.locator('.composer textarea').click(); + await page.keyboard.type('forkflow'); + await page.keyboard.press('Enter'); + + // Mid-run: the edit has landed and the long command is in flight. The steps stay visible and + // nothing reads as an ending the turn has not had — in particular no card of changed files. + const longRun = page.locator('.step', { hasText: 'npm test' }); + await longRun.waitFor({ timeout: 10_000 }); + await page.waitForTimeout(300); + assert.equal(await page.getByText('工作中…', { exact: true }).count(), 0, 'no duplicate status above the composer'); + assert.equal(await page.locator('.changes').count(), 0, 'no changes card while the turn runs'); + assert.equal((await longRun.locator('.step-status').innerText()).trim(), '运行中'); + + // Ended: the work folds to its duration, the answer stands after it, and the card appears. + await page.locator('.work-toggle', { hasText: '用时' }).first().waitFor({ timeout: 15_000 }); + await page.getByText('now the long run').waitFor({ timeout: 5_000 }); + const card = page.locator('.changes'); + await card.waitFor({ timeout: 5_000 }); + assert.match(await card.locator('.changes-head').innerText(), /已更改 1 个文件/); + assert.equal(await card.locator('.changes-head').getAttribute('aria-expanded'), 'false'); + assert.equal(await card.locator('.changes-file').count(), 0); + await card.locator('.changes-head').click(); + assert.match(await card.innerText(), /demo\.ts/); +}); + +test('a run of calls folds into one line that counts them, and opens to the calls', async () => { + await page.locator('.side-nav').getByRole('button', { name: '新对话', exact: true }).click(); + await page.locator('.composer .context-btn').first().click(); + await page.getByRole('menuitemradio', { name: /^pi/ }).click(); + await page.locator('.composer textarea').click(); + await page.keyboard.type('manysteps'); + await page.keyboard.press('Enter'); + + // Mid-run: the four calls before the remark are one line. After the remark one call is over and + // one is in flight; that is not worth a count yet, so both show as themselves. + const inFlight = page.locator('.step', { hasText: 'npm test' }); + await inFlight.waitFor({ timeout: 10_000 }); + const runs = page.locator('.work-body .run-head'); + assert.equal(await runs.count(), 1); + assert.equal((await runs.first().innerText()).trim(), '已浏览 2 个文件,搜索 1 次,运行 1 条命令'); + assert.equal(await page.locator('.step', { hasText: 'src/a.ts' }).count(), 0, 'folded: its calls are not on screen'); + assert.equal((await inFlight.locator('.step-status').innerText()).trim(), '运行中'); + assert.equal(await page.locator('.work-body > .step', { hasText: 'npm run lint' }).count(), 1); + + // The line opens to its calls, in the order they were made, and closes again. + await runs.first().click(); + const opened = await page.locator('.run-body .step-title').allInnerTexts(); + assert.equal(opened.length, 4); + assert.match(opened[0], /^读取了\s+src\/a\.ts/); + assert.match(opened[3], /^运行了\s+ls src/); + await runs.first().click(); + assert.equal(await page.locator('.run-body').count(), 0); + + // Done: the turn's work folds to its one line as before. Opened, both runs are counts now. + await page.locator('.row.assistant', { hasText: 'all good' }).waitFor({ timeout: 15_000 }); + const toggle = page.locator('.work-toggle', { hasText: '用时' }); + await toggle.waitFor({ timeout: 10_000 }); + assert.match(await toggle.innerText(), /6 步/); + assert.equal(await page.locator('.work-body').count(), 0); + await toggle.click(); + assert.deepEqual( + (await runs.allInnerTexts()).map((t) => t.trim()), + ['已浏览 2 个文件,搜索 1 次,运行 1 条命令', '已运行 2 条命令'], + ); + assert.equal(await page.locator('.work-body .step').count(), 0, 'nothing is laid out until a line is opened'); +}); diff --git a/apps/workbench/packages/e2e/test/coordination-compact.spec.mjs b/apps/workbench/packages/e2e/test/coordination-compact.spec.mjs new file mode 100644 index 0000000000..bfd2365845 --- /dev/null +++ b/apps/workbench/packages/e2e/test/coordination-compact.spec.mjs @@ -0,0 +1,40 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdirSync } from 'node:fs'; +import { join } from 'node:path'; +import { openCollaboration, startDaemon, openUi, api, launchBrowser, repoRoot } from '../harness.mjs'; + +test('compact works from a collaboration composer on desktop and phone in both themes', async () => { + const daemon = await startDaemon({ LOOCHAT_AGENTS_JSON: JSON.stringify({ agents: [{ + id: 'codex', adapter: 'codex', command: [process.execPath, join(repoRoot, 'daemon/test/fixtures/fake-codex.mjs')], + }] }) }); + let browser; + try { + browser = await launchBrowser(); + for (const mobile of [false, true]) for (const colorScheme of ['light', 'dark']) { + const title = `协作压缩 ${mobile ? '手机' : '桌面'} ${colorScheme}`; + const response = await api(daemon, '/api/threads', { method: 'POST', body: JSON.stringify({ agent: 'codex', cwd: daemon.workdir, title }) }); + assert.equal(response.status, 201); + const context = await browser.newContext({ viewport: mobile ? { width: 390, height: 844 } : { width: 1440, height: 1000 }, isMobile: mobile, hasTouch: mobile, colorScheme }); + try { + const page = await context.newPage(); + await openUi(page, daemon); + if (mobile) await page.locator('.menu-btn').click(); + await page.locator('.thread-title', { hasText: title }).first().click(); + await openCollaboration(page); + await page.getByRole('button', { name: '协作设置', exact: true }).click(); + await page.getByRole('button', { name: '启用协作', exact: true }).click(); + await page.locator('.composer-add.on').waitFor(); + await page.locator('.composer textarea').fill('/compact'); + await page.getByRole('button', { name: '发送', exact: true }).click(); + await page.getByText('上下文压缩完成。', { exact: true }).waitFor(); + await page.getByRole('button', { name: '发送', exact: true }).waitFor(); + assert.equal(await page.getByText('/compact 不接受参数或图片。', { exact: true }).count(), 0); + 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, `coordination-compact-${mobile ? 'phone' : 'desktop'}-${colorScheme}.png`) }); + } + } finally { await context.close(); } + } + } finally { await browser?.close(); await daemon.stop(); } +}); diff --git a/apps/workbench/packages/e2e/test/coordination-queue.spec.mjs b/apps/workbench/packages/e2e/test/coordination-queue.spec.mjs new file mode 100644 index 0000000000..1d90a49e4a --- /dev/null +++ b/apps/workbench/packages/e2e/test/coordination-queue.spec.mjs @@ -0,0 +1,49 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdirSync } from 'node:fs'; +import { openCollaboration, startDaemon, openUi, api, launchBrowser } from '../harness.mjs'; + +test('queued collaboration restores text and target tasks separately in all viewports', async () => { + const daemon = await startDaemon(); + const browser = await launchBrowser(); + const post = async (path, body) => { const res = await api(daemon, path, { method: 'POST', body: JSON.stringify(body) }); assert.ok(res.ok, await res.clone().text()); return res.json(); }; + try { + for (const phone of [false, true]) for (const colorScheme of ['light', 'dark']) { + const context = await browser.newContext({ viewport: phone ? { width: 390, height: 844 } : { width: 1440, height: 1000 }, isMobile: phone, hasTouch: phone, colorScheme }); + try { + const title = `协作撤回 ${phone}-${colorScheme}`; + const thread = await post('/api/threads', { agent: 'pi', cwd: daemon.workdir, title }); + const page = await context.newPage(); + await openUi(page, daemon); + if (phone) await page.locator('.menu-btn').click(); + await page.locator('.thread-row', { hasText: title }).click(); + await openCollaboration(page); + await page.getByRole('button', { name: '协作设置', exact: true }).click(); + await page.getByRole('button', { name: '启用协作', exact: true }).click(); + await page.locator('.composer-add.on').waitFor(); + await post(`/api/threads/${thread.id}/turns`, { text: 'slow' }); + const mentions = [{ id: 'claude', label: 'Claude Code', kind: 'agent', cwd: daemon.workdir, task: '总结经验,先不要自己做' }]; + await post(`/api/threads/${thread.id}/turns`, { text: '让 Claude 参与分析', mentions, queue: true }); + const box = page.getByRole('textbox', { name: '消息', exact: true }); + await box.fill('已有草稿'); + await page.getByRole('button', { name: '撤回到输入框里编辑', exact: true }).click(); + const task = page.getByRole('textbox', { name: '给 Claude Code 的任务', exact: true }); + await task.waitFor(); + assert.equal(await task.inputValue(), mentions[0].task); + assert.equal(await box.inputValue(), '让 Claude 参与分析\n\n已有草稿'); + await task.fill('修改后只给建议'); + const sent = page.waitForRequest(r => r.url().endsWith(`/threads/${thread.id}/turns`) && r.method() === 'POST'); + await page.getByRole('button', { name: '排队发送', exact: true }).click(); + const body = (await sent).postDataJSON(); + assert.equal(body.text.includes('[指定协作对象]'), false); + assert.equal(body.mentions[0].task, '修改后只给建议'); + await page.getByRole('button', { name: '撤回到输入框里编辑', exact: true }).click(); + await task.waitFor(); + await page.waitForTimeout(500); + mkdirSync('/tmp/mention-queue-shots', { recursive: true }); + await page.screenshot({ path: `/tmp/mention-queue-shots/${phone ? 'phone' : 'desktop'}-${colorScheme}.png` }); + await api(daemon, `/api/threads/${thread.id}/cancel`, { method: 'POST' }); + } finally { await context.close(); } + } + } finally { await browser.close(); await daemon.stop(); } +}); diff --git a/apps/workbench/packages/e2e/test/coordination.spec.mjs b/apps/workbench/packages/e2e/test/coordination.spec.mjs new file mode 100644 index 0000000000..4e09bba024 --- /dev/null +++ b/apps/workbench/packages/e2e/test/coordination.spec.mjs @@ -0,0 +1,284 @@ +import { test, before, after } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdirSync } from 'node:fs'; +import { openCollaboration, startDaemon, openUi, api, launchBrowser } from '../harness.mjs'; + +let daemon, browser; +before(async () => { daemon = await startDaemon(); browser = await launchBrowser(); }); +after(async () => { await browser?.close(); await daemon?.stop(); }); +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 waitIdle = async id => { + for (let n = 0; n < 200; n++) { + const thread = await (await api(daemon, `/api/threads/${id}`)).json(); + if (thread.status !== 'running' && !['checking', 'preparing', 'countdown'].includes(thread.autoHandover?.state)) return; + await new Promise(r => setTimeout(r, 50)); + } + throw new Error('thread did not finish'); +}; + +for (const phone of [false, true]) for (const colorScheme of ['light', 'dark']) { + test(`collaboration picker, output and draft preservation: ${phone ? 'phone' : 'desktop'} ${colorScheme}`, async () => { + const context = await browser.newContext({ viewport: phone ? { width: 390, height: 844 } : { width: 1440, height: 1000 }, isMobile: phone, hasTouch: phone, colorScheme }); + const page = await context.newPage(); + const errors = []; page.on('pageerror', e => errors.push(e.message)); + try { + const title = `文档协作 ${phone ? '手机' : '桌面'} ${colorScheme}`; + const root = await post('/api/threads', { agent: 'pi', cwd: daemon.workdir, title }); + await openUi(page, daemon); + if (phone) await page.locator('.menu-btn').click(); + await page.locator('.thread-row', { hasText: title }).click(); + // Desktop can enable collaboration first; choosing a collaborator also starts it on phones. + if (!phone) { + await openCollaboration(page); + await page.locator('.coord-picker-head button').click(); + await page.getByRole('button', { name: '启用协作', exact: true }).click(); + // Nobody is in the team yet: the button says it is on, and no line is added above the box. + await page.locator('.composer-add.on').waitFor(); + assert.equal(await page.locator('.coord-bar').count(), 0); + } + const box = page.getByRole('textbox', { name: '消息', exact: true }); + await box.fill('Keep this draft while choosing a collaborator'); + await openCollaboration(page); + const list = page.getByRole('menu', { name: '协作', exact: true }); + 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 = 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'); + // The agent gets a line of its own, and the caret is there for its task; Enter goes back to the message. + const row = page.locator('.coord-row'); + assert.match(await row.innerText(), /claude/i); + const task = row.getByRole('textbox'); + assert.ok(await task.evaluate(el => el === document.activeElement)); + await task.fill('只看异常处理'); + // The model its member starts with is a quiet mark at the end of the line, worded once chosen. + const quiet = row.getByRole('button', { name: /的模型与思考强度$/ }); + assert.equal(await quiet.getAttribute('aria-haspopup'), 'menu'); + await quiet.click(); + const control = page.locator('.model-control-panel'); + const toModels = control.getByRole('button', { name: /切换模型/ }); + await control.getByRole('menuitemradio').or(toModels).first().waitFor(); + if (await toModels.count()) await toModels.click(); + const choice = control.getByRole('menuitemradio').nth(1); + const picked = (await choice.locator('.pop-item-label').innerText()).trim(); + await choice.click(); + await page.keyboard.press('Escape'); + await control.waitFor({ state: 'detached' }); + await row.locator('.member-model.set', { hasText: picked }).waitFor(); + // Its level sits beside the model: full access unless changed, here to asking first. + const level = row.getByRole('button', { name: /的权限$/ }); + assert.match(await level.getAttribute('title'), /不再询问/); + await level.click(); + await page.getByRole('menuitemradio', { name: /^请求批准/ }).click(); + await row.locator('button[title*="都先询问"]').waitFor(); + await task.press('Enter'); + assert.ok(await box.evaluate(el => el === document.activeElement)); + await box.fill('请审查接口文档'); + await page.screenshot({ path: `${shots}/${phone ? 'phone' : 'desktop'}-${colorScheme}-rows.png` }); + const sent = page.waitForRequest(req => req.url().endsWith(`/threads/${root.id}/turns`) && req.method() === 'POST'); + await page.getByRole('button', { name: '发送', exact: true }).click(); + const mention = (await sent).postDataJSON().mentions[0]; + assert.equal(mention.id, 'claude'); + assert.equal(mention.task, '只看异常处理'); + await waitIdle(root.id); + await page.waitForFunction(() => document.querySelector('.composer textarea')?.value === ''); + await page.locator('.composer-add.on').waitFor(); + await page.locator('.coord-row').waitFor({ state: 'detached' }); + const asked = page.locator('.row.user .bubble', { hasText: '请审查接口文档' }); + await asked.waitFor(); + assert.ok(!(await asked.innerText()).includes('[指定协作对象]'), 'protocol instructions stay out of the visible message'); + + // The fixture invokes the actual injected CLI, creating a normal member thread. + const directive = Buffer.from(JSON.stringify({ args: ['spawn', '--agent', 'claude', '--name', '文档审查', '--message-file', '-', '--request-id', 'review'], text: '检查接口与异常处理 LOOCHAT_REPORT' })).toString('base64'); + await post(`/api/threads/${root.id}/turns`, { text: `LOOCHAT_COMMAND:${directive}` }); + await box.fill('保留这段主对话草稿'); + await openCollaboration(page); + await page.getByRole('button', { name: '协作设置', exact: true }).click(); + await page.getByRole('button', { name: '查看智能体', exact: true }).click(); + const panel = page.getByRole('region', { name: '智能体面板' }); + const card = panel.locator('.agent-member', { hasText: '文档审查' }); + await card.waitFor(); + await page.waitForFunction(() => document.querySelector('.agent-member')?.textContent?.includes('已返回')); + const team = await (await api(daemon, `/api/threads/${root.id}/coordination`)).json(); + const child = team.members[0].id; + if (!phone) { + // Members are rows under their lead in the sidebar, saying what they did, not threads of their own. + const lead = page.locator('.sidebar .team-group', { has: page.locator('.thread-title', { hasText: title }) }); + await lead.waitFor(); + if (!(await lead.locator('.handover-member').count())) await lead.locator('.handover-toggle').click(); + await lead.locator('.handover-member', { hasText: '文档审查完成' }).waitFor(); + assert.equal(await page.locator('.sidebar .thread-row').filter({ hasText: '文档审查完成' }).count(), 0); + await page.screenshot({ path: `${shots}/desktop-${colorScheme}-sidebar-team.png` }); + } + // The member was made with what was chosen on its line, whether the team existed yet or not. + // The member runs at the level chosen on its line, not the team's full access. + assert.equal((await (await api(daemon, `/api/threads/${child}`)).json()).permissionMode, 'ask'); + const offered = await (await api(daemon, '/api/agents/claude/models')).json(); + assert.equal((await (await api(daemon, `/api/threads/${child}`)).json()).model, offered.find(m => m.label === picked).id); + if (!phone) { + // On a wide screen the panel's edge drags; a double click gives the width back. + const edge = panel.getByRole('separator', { name: '调整宽度' }); + const wide = async () => Math.round((await panel.boundingBox()).width); + const usual = await wide(); + const at = await edge.boundingBox(); + await page.mouse.move(at.x + 2, at.y + 200); + await page.mouse.down(); + await page.mouse.move(at.x - 118, at.y + 200, { steps: 4 }); + await page.mouse.up(); + assert.ok(Math.abs((await wide()) - usual - 120) <= 2, `the panel grew by the drag (${usual} to ${await wide()})`); + await edge.dblclick(); + assert.equal(await wide(), usual); + } + const before = await (await api(daemon, `/api/threads/${child}/events`)).json(); + // The detail retries even if its first history request fails. + 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(); + 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 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(); + await page.waitForTimeout(250); + const shown = await ownPanel.boundingBox(); + const screen = page.viewportSize(); + assert.ok(shown.y >= 0 && shown.x >= 0 && shown.y + shown.height <= screen.height + 1 && shown.x + shown.width <= screen.width + 1, `the setting fits the screen (${JSON.stringify(shown)})`); + 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'), '发给 文档审查…'); + assert.equal(await page.evaluate(() => document.documentElement.dataset.theme), colorScheme); + if (phone) { + const rect = await panel.boundingBox(); + 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' }); + await page.screenshot({ path: `${shots}/${phone ? 'phone' : 'desktop'}-${colorScheme}-list.png` }); + // The team's messages read like a chat: the task with who sent it, and its answer folded under it. + await panel.getByRole('tab', { name: /^消息/ }).click(); + const talk = panel.locator('.talk'); + assert.equal(await talk.count(), 1); + assert.match(await talk.locator('.talk-said').first().innerText(), /主智能体[\s\S]*发给 文档审查[\s\S]*检查接口与异常处理/); + assert.equal(await talk.locator('.talk-mark svg').first().count(), 1); + const replies = talk.getByRole('button', { name: /1 条回复/ }); + assert.equal(await replies.getAttribute('aria-expanded'), 'true'); + assert.match(await talk.locator('.talk-thread').innerText(), /文档审查[\s\S]*文档审查完成。/); + await page.screenshot({ path: `${shots}/${phone ? 'phone' : 'desktop'}-${colorScheme}-talk.png` }); + await replies.click(); + assert.equal(await talk.locator('.talk-thread').count(), 0); + await panel.getByRole('tab', { name: /^成员/ }).click(); + await card.waitFor(); + await panel.getByRole('button', { name: '关闭智能体面板' }).click(); + await panel.waitFor({ state: 'detached' }); + assert.equal(await box.inputValue(), '保留这段主对话草稿'); + // What the member returned sits in the thread as a folded card, opened to its text as Markdown. + const delivered = page.locator('.row.delivered', { hasText: '文档审查' }); + await delivered.waitFor(); + assert.equal(await delivered.locator('.delivered-body').count(), 0); + assert.match(await delivered.locator('.delivered-sum').innerText(), /^文档审查完成。/); + await page.screenshot({ path: `${shots}/${phone ? 'phone' : 'desktop'}-${colorScheme}-result.png` }); + await delivered.getByRole('button').click(); + assert.equal(await delivered.locator('.delivered-body p').count(), 2); + await page.screenshot({ path: `${shots}/${phone ? 'phone' : 'desktop'}-${colorScheme}-result-open.png` }); + const after = await (await api(daemon, `/api/threads/${child}/events`)).json(); + assert.equal(after.filter(e => e.type === 'turn.started').length, before.filter(e => e.type === 'turn.started').length, 'viewing output does not start work'); + await openCollaboration(page); + await page.getByRole('button', { name: '协作设置', exact: true }).click(); + await page.getByRole('button', { name: '查看智能体', exact: true }).click(); + await card.click(); + if (phone) { + await page.goBack(); + await card.waitFor(); + await page.goBack(); + await panel.waitFor({ state: 'detached' }); + } else { + await page.keyboard.press('Escape'); + await panel.waitFor({ state: 'detached' }); + } + + // Written to directly: the member answers in its own thread, and the lead is not woken. + const leadTurns = async () => (await (await api(daemon, `/api/threads/${root.id}/events`)).json()).filter(e => e.type === 'turn.started').length; + const leadBefore = await leadTurns(); + await openCollaboration(page); + await page.getByRole('button', { name: '协作设置', exact: true }).click(); + await page.getByRole('button', { name: '查看智能体', exact: true }).click(); + await card.click(); + const direct = panel.getByRole('textbox', { name: '消息', exact: true }); + await direct.fill('slow 把结论压到三条'); + const toMember = page.waitForRequest(req => req.url().endsWith(`/threads/${child}/turns`) && req.method() === 'POST'); + await panel.getByRole('button', { name: '发送', exact: true }).click(); + await toMember; + await panel.locator('.row.user .bubble', { hasText: '把结论压到三条' }).waitFor(); + // Running, more is queued behind the turn, with stop where the lead's box has it. + await page.waitForFunction(() => document.querySelector('.agent-panel textarea')?.getAttribute('placeholder')?.includes('这一轮结束后')); + await direct.fill('再补一条风险'); + await panel.getByRole('button', { name: /^排队发送|^发送/ }).click(); + await panel.locator('.queue-item', { hasText: '再补一条风险' }).waitFor(); + await direct.fill('先写一半'); + await page.screenshot({ path: `${shots}/${phone ? 'phone' : 'desktop'}-${colorScheme}-direct-running.png` }); + await panel.getByRole('button', { name: '停止', exact: true }).click(); + // The stop hands what was waiting back to the box, ahead of what was being written. + await page.waitForFunction(() => document.querySelector('.agent-panel textarea')?.value.includes('再补一条风险')); + assert.match(await direct.inputValue(), /再补一条风险[\s\S]*先写一半/); + await waitIdle(child); + assert.equal(await leadTurns(), leadBefore, 'talking to a member does not wake the lead'); + await panel.getByRole('button', { name: '返回智能体列表' }).click(); + await panel.getByRole('tab', { name: /^消息/ }).click(); + assert.match(await panel.locator('.talk').last().innerText(), /你[\s\S]*发给 文档审查[\s\S]*把结论压到三条/); + await page.screenshot({ path: `${shots}/${phone ? 'phone' : 'desktop'}-${colorScheme}-direct-talk.png` }); + await panel.getByRole('tab', { name: /^成员/ }).click(); + await card.click(); + await direct.fill('补一条测试要求'); + await page.screenshot({ path: `${shots}/${phone ? 'phone' : 'desktop'}-${colorScheme}-direct-idle.png` }); + // Going through the lead instead carries the words along, and leaves the member's box empty. + await panel.getByRole('button', { name: '让主智能体调整', exact: true }).click(); + await panel.waitFor({ state: 'detached' }); + // The words land in the lead's box a render after the panel goes. + const carried = '请调整「文档审查」的任务:补一条测试要求\n\n保留这段主对话草稿'; + for (let n = 0; n < 50 && await box.inputValue() !== carried; n++) await page.waitForTimeout(50); + assert.equal(await box.inputValue(), carried); + await page.screenshot({ path: `${shots}/${phone ? 'phone' : 'desktop'}-${colorScheme}-via-lead.png` }); + await openCollaboration(page); + await page.getByRole('button', { name: '协作设置', exact: true }).click(); + 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/demo.spec.mjs b/apps/workbench/packages/e2e/test/demo.spec.mjs new file mode 100644 index 0000000000..30964564ac --- /dev/null +++ b/apps/workbench/packages/e2e/test/demo.spec.mjs @@ -0,0 +1,94 @@ +// Before it is connected the page shows a made-up workspace instead of asking for a token. It +// talks to no daemon; anything that would change something opens the connect dialog, which tries +// a token before keeping it. +import { test, before, after } from 'node:test'; +import assert from 'node:assert/strict'; +import { startDaemon, launchBrowser } from '../harness.mjs'; + +let daemon; +let browser; +let page; +const apiCalls = []; + +before(async () => { + daemon = await startDaemon(); + browser = await launchBrowser(); + const ctx = await browser.newContext({ viewport: { width: 1400, height: 900 } }); + page = await ctx.newPage(); + page.on('request', (req) => { + if (new URL(req.url()).pathname.startsWith('/api/')) apiCalls.push(req.url()); + }); +}); + +after(async () => { + await browser?.close(); + await daemon?.stop(); +}); + +const savedToken = () => page.evaluate(() => localStorage.getItem('calli.token')); +const dialog = () => page.getByRole('dialog', { name: '连接到 hub' }); + +test('without a token the page opens on the demo, and asks the daemon nothing', async () => { + await page.goto(daemon.base + '/'); + await page.locator('.demo-bar').waitFor({ timeout: 15_000 }); + await page.locator('.sidebar').getByText('设置页加深色模式').click(); + // The finished turn: the answer and the files it changed. + await page.getByText('设置页「语言」下面多了一行「外观」').waitFor({ timeout: 5000 }); + await page.locator('.thread').getByText('src/theme.ts').first().waitFor(); + // The one waiting on an approval. + await page.locator('.sidebar').getByText('修复商品列表滚动跳动').click(); + await page.getByText('npm run e2e -- product-list').first().waitFor(); + assert.deepEqual(apiCalls, [], 'the demo is all in the page'); +}); + +test('sending asks to connect, and the draft stays', async () => { + await page.locator('.sidebar').getByText('设置页加深色模式').click(); + const box = page.locator('.composer textarea'); + await box.click(); + await page.keyboard.type('再加一个高对比度'); + await page.keyboard.press('Enter'); + await dialog().waitFor({ timeout: 5000 }); + await dialog().getByText('连接后再发送').waitFor(); + assert.equal(await box.inputValue(), '再加一个高对比度'); + assert.deepEqual(apiCalls, [], 'nothing was sent anywhere'); + await dialog().getByRole('button', { name: '取消' }).click(); + await dialog().waitFor({ state: 'detached' }); +}); + +test('a wrong token is said in the dialog and not kept', async () => { + await page.locator('.demo-bar-btn').click(); + await page.getByLabel('访问 token').fill('not-the-token-at-all'); + await page.getByRole('button', { name: '连接', exact: true }).click(); + await dialog().getByText('token 不对').waitFor({ timeout: 5000 }); + assert.equal(await savedToken(), null); + assert.equal(await page.locator('.demo-bar').count(), 1, 'still the demo'); +}); + +test('the right token connects, and the demo is gone', async () => { + await page.getByLabel('访问 token').fill(daemon.token); + await page.getByRole('button', { name: '连接', exact: true }).click(); + await page.locator('.demo-bar').waitFor({ state: 'detached', timeout: 15_000 }); + assert.equal(await savedToken(), daemon.token); + assert.equal(await page.locator('.sidebar').getByText('设置页加深色模式').count(), 0, 'no demo thread is left over'); + assert.equal(await page.locator('.composer textarea').getAttribute('placeholder').then((p) => p?.includes('连接 hub')), false); +}); + +test('a token that stops working goes back to the demo with the dialog saying why', async () => { + await page.evaluate(() => localStorage.setItem('calli.token', 'an-old-token-0123456789')); + await page.reload(); + await dialog().getByText('token 无效或已过期').waitFor({ timeout: 15_000 }); + assert.equal(await savedToken(), null); + await page.locator('.demo-bar').waitFor(); +}); + +test('signing out goes back to the demo without asking for a token', async () => { + await page.getByLabel('访问 token').fill(daemon.token); + await page.getByRole('button', { name: '连接', exact: true }).click(); + await page.locator('.demo-bar').waitFor({ state: 'detached', timeout: 15_000 }); + await page.getByRole('button', { name: '配置' }).click(); + await page.locator('.settings-nav').getByRole('button', { name: '退出' }).click(); + await page.getByRole('dialog').getByRole('button', { name: '退出' }).click(); + await page.locator('.demo-bar').waitFor({ timeout: 5000 }); + assert.equal(await dialog().count(), 0); + assert.equal(await savedToken(), null); +}); diff --git a/apps/workbench/packages/e2e/test/desk-pet.spec.mjs b/apps/workbench/packages/e2e/test/desk-pet.spec.mjs new file mode 100644 index 0000000000..09f6200d28 --- /dev/null +++ b/apps/workbench/packages/e2e/test/desk-pet.spec.mjs @@ -0,0 +1,198 @@ +import { describe, test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { build } from 'esbuild'; +import { launchBrowser } from '../harness.mjs'; + +describe('legacy desk pet', { skip: 'LoopX Workbench does not mount the legacy Pet or DeskPage components.' }, () => { + +test('a pet reply naming a child opens its parent pile, and an unconfigured delegate opens settings', { timeout: 30_000 }, async () => { + // Check the Desk/Pet contract independently of the Router transport and sprite installation. The pet + // sits above every page now, so the two are wired the way App wires them: her reply names a matter, + // the desk opens the pile it belongs to, and the pile owns the keyboard while it is spread out. + const bundle = await build({ + stdin: { contents: ` + import { createRoot } from 'react-dom/client'; + import { useState } from 'react'; + import { DeskPage } from './components/DeskPage'; + import { Pet } from './components/Pet'; + const createdAt = new Date().toISOString(); + const base = { done:false, position:0, createdAt, doneAt:null, threads:[] }; + const todos = [ + { ...base, id:'parent', text:'Review experiment', parentId:null, lane:'later' }, + { ...base, id:'child', text:'Check control group', parentId:'parent' }, + ]; + const api = { + pet: async () => ({installed:true, installing:false, error:null, id:'dafeiyu', commit:'test', clips:{idle:1}, frameMs:84}), + petFrame: () => 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=', + petRouter: async () => ({threadId:'router', status:'idle', lastReply:'Next: Check control group', lastReplyAt:createdAt}), + todoNote: async () => ({text:'',updatedAt:null,threadId:null,rev:0}), + workdirs: async () => ({workdirs:[]}), + personalProfile: async () => ({text:'', updatedAt:null, path:'profile.md', isTemplate:false, rev:1}), + lastPersonalBrief: async () => null, + pushStatus: async () => ({records:[]}), + briefSettings: async () => ({enabled:false, morning:'09:00', evening:'19:00'}), + proactiveSettings: async () => ({settings:{mode:'off', repos:[], enabled:false}}), + pushSettings: async () => ({enabled:false}), + larkChannel: async () => ({enabled:false, people:[], chats:[], intervalMin:30}), + larkStatus: async () => ({cli:false, loggedIn:false, lastRunAt:null, nextRunAt:null, lastError:null, lastSignals:0}), + }; + localStorage.setItem('calli.pet.pending', JSON.stringify({since:null,threadId:'router',sentAt:Date.now(),text:'What next?'})); + function TestApp() { + const [revealTodoId, setRevealTodoId] = useState(null); + const [spread, setSpread] = useState(false); + return <> + {}} + onPersonalChange={() => {}} onPersonalRetry={() => {}} onOpenThread={() => {}} onOpenPlans={() => {}} + onSpreadChange={setSpread} revealTodoId={revealTodoId} onRevealTodo={() => setRevealTodoId(null)} /> + {}} todos={todos.filter(todo => !todo.done)} onOpenTodo={id => setRevealTodoId(id)} /> + ; + } + createRoot(document.getElementById('root')).render(); + `, loader:'tsx', resolveDir:fileURLToPath(new URL('../../web/src/', import.meta.url)) }, + bundle:true, write:false, format:'iife', platform:'browser', jsx:'automatic', + }); + const css = readFileSync(new URL('../../web/src/styles.css', import.meta.url), 'utf8'); + const server = createServer((_req, res) => res.end('
')); + let browser; + try { + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + browser = await launchBrowser(); + const page = await browser.newPage({ reducedMotion:'reduce', locale:'zh-CN' }); + const errors = []; page.on('pageerror', error => errors.push(error.message)); + await page.goto(`http://127.0.0.1:${server.address().port}`); + await page.addStyleTag({ content:css }); + await page.addScriptTag({ content:bundle.outputFiles[0].text }); + await page.locator('.desk-week.quiet').waitFor(); + assert.ok((await page.locator('.desk-week').boundingBox()).height < 120, 'zero completions use a compact, explicit empty week'); + assert.equal(await page.locator('.desk-week .desk-chart-day').count(), 7); + // Her reply names a matter: the word in the bubble spreads that pile on the desk below. + await page.locator('.pet-bub', { hasText:'Next' }).waitFor(); + await page.locator('.pet-bub-act', { hasText:'Check control group' }).click(); + await page.locator('#desk-spread-title', { hasText:'Review experiment' }).waitFor(); + assert.equal(await page.locator('.pet-bub').count(), 0, 'opening the matter clears the reply bubble'); + await page.getByRole('checkbox', { name:'Check control group' }).waitFor(); + // While the pile is spread she steps back, and a tap talks to her in one thin line. + assert.equal(await page.locator('.pet-back').count(), 1); + await page.locator('.pet-body').click(); + await page.locator('.pet-qc input').waitFor(); + await page.keyboard.press('Tab'); + assert.equal(await page.evaluate(() => Boolean(document.activeElement.closest('.pet-qc'))), false, 'the spread takes keyboard focus from another dialog'); + await page.locator('.pet-qc input').focus(); + await page.keyboard.press('Escape'); + await page.locator('.pet-qc').waitFor({ state:'detached' }); + assert.equal(await page.locator('.desk-spread').count(), 1); + const delegate = page.getByRole('button', { name:'交给 agent', exact:true }); + assert.equal(await delegate.isEnabled(), true); + assert.equal(await delegate.getAttribute('title'), '先在私人设置里选 agent'); + await delegate.click(); + await page.locator('.personal-settings').waitFor(); + await page.keyboard.press('Escape'); + await page.locator('.personal-settings').waitFor({ state:'detached' }); + assert.equal(await page.locator('.desk-spread').count(), 1); + await page.keyboard.press('Escape'); + await page.locator('.desk-spread').waitFor({ state:'detached' }); + await page.waitForFunction(() => document.activeElement.id === 'desk-stack-later'); + assert.deepEqual(errors, []); + } finally { + await browser?.close(); + server.close(); + } +}); + +test('the pet clears a growing composer and phone switcher, preserves dragged positions, and only renders a tucked avatar', { timeout: 30_000 }, async () => { + const bundle = await build({ + stdin: { contents: ` + import { createRoot } from 'react-dom/client'; + import { useState } from 'react'; + import { Pet, savePetPresence } from './components/Pet'; + const api = { + pet: async () => ({installed:true, id:'test', commit:'test', clips:{idle:1}, frameMs:84}), + petFrame: () => 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=', + personalProfile: async () => ({isTemplate:false}), + }; + function App() { + const [text, setText] = useState(''); + const [attached, setAttached] = useState(false); + return <> + +
+
+ {attached &&
Attachment
} +