Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
refactor(ci): use native selection and shared build artifacts (#1156)
Gener8e94e4c45e2f
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.mdindex 9198afb65..959d66b56 100644--- a/.github/PULL_REQUEST_TEMPLATE.md+++ b/.github/PULL_REQUEST_TEMPLATE.md@@ -5,8 +5,8 @@...## Checklist-- [ ] Tests added/updated as needed-- [ ] All CI checks pass+- [ ] Changed risks have effective tests; removed/merged tests name their remaining guard+- [ ] Applicable CI gates pass; selected, skipped and unrun checks are stated- [ ] PR targets the correct branch## Impact Areasdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex be3a846dd..8ffe4c67a 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -41,7 +41,7 @@ permissions:pull-requests: readconcurrency:- group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.event.merge_group.head_sha || github.ref }}+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.event.merge_group.head_sha || github.ref }}-${{ (github.event_name == 'workflow_dispatch' || startsWith(github.event.head_commit.message, 'release:')) && github.run_id || 'latest' }}cancel-in-progress: truejobs:@@ -50,16 +50,21 @@ jobs:runs-on: ubuntu-latesttimeout-minutes: 5outputs:- execution_plan: ${{ steps.scope.outputs.execution_plan }}+ plan_artifact_name: execution-plan-${{ github.run_id }}-${{ github.run_attempt }}plan_hash: ${{ steps.scope.outputs.plan_hash }}plan_schema_version: ${{ steps.scope.outputs.plan_schema_version }}full: ${{ steps.scope.outputs.full }}+ execution_mode: ${{ steps.scope.outputs.execution_mode }}base_sha: ${{ steps.scope.outputs.base_sha }}head_sha: ${{ steps.scope.outputs.head_sha }}auth_only: ${{ steps.scope.outputs.auth_only }}blog_only: ${{ steps.scope.outputs.blog_only }}run_auth_build: ${{ steps.scope.outputs.run_auth_build }}run_blog_build: ${{ steps.scope.outputs.run_blog_build }}+ run_worker_build: ${{ steps.scope.outputs.run_worker_build }}+ worker_zones: ${{ steps.scope.outputs.worker_zones }}+ browser_zones: ${{ steps.scope.outputs.browser_zones }}+ worker_build_image: ${{ steps.scope.outputs.worker_build_image }}run_code_checks: ${{ steps.scope.outputs.run_code_checks }}run_static_checks: ${{ steps.scope.outputs.run_static_checks }}run_linux: ${{ steps.scope.outputs.run_linux }}@@ -71,10 +76,16 @@ jobs:run_lighthouse: ${{ steps.scope.outputs.run_lighthouse }}run_knip: ${{ steps.scope.outputs.run_knip }}run_app_packed_artifact: ${{ steps.scope.outputs.run_app_packed_artifact }}+ static_tasks: ${{ steps.scope.outputs.static_tasks }}+ build_tasks: ${{ steps.scope.outputs.build_tasks }}+ knip_tasks: ${{ steps.scope.outputs.knip_tasks }}+ unit_tasks: ${{ steps.scope.outputs.unit_tasks }}+ unit_build_tasks: ${{ steps.scope.outputs.unit_build_tasks }}static_packages: ${{ steps.scope.outputs.static_packages }}build_packages: ${{ steps.scope.outputs.build_packages }}knip_packages: ${{ steps.scope.outputs.knip_packages }}unit_test_roots: ${{ steps.scope.outputs.unit_test_roots }}+ smoke_test_files: ${{ steps.scope.outputs.smoke_test_files }}windows_suites: ${{ steps.scope.outputs.windows_suites }}integration_suites: ${{ steps.scope.outputs.integration_suites }}linux_suites: ${{ steps.scope.outputs.linux_suites }}@@ -87,6 +98,12 @@ jobs:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7with:fetch-depth: 0+ - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7+ with:+ node-version: 22+ cache: pnpm+ - run: pnpm install --frozen-lockfile --ignore-scripts- id: scopeenv:EVENT_NAME: ${{ github.event_name }}@@ -95,6 +112,7 @@ jobs:PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}MERGE_BASE_SHA: ${{ github.event.merge_group.base_sha }}PUSH_BASE_SHA: ${{ github.event.before }}+ HEAD_COMMIT_MESSAGE: ${{ github.event.head_commit.message }}DISPATCH_MODE: ${{ inputs.mode }}CANDIDATE_PR: ${{ inputs.candidate_pr }}CANDIDATE_SHA: ${{ inputs.candidate_sha }}@@ -122,8 +140,10 @@ jobs:args+=(--base "$PR_BASE_SHA" --head "$PR_HEAD_SHA")elif [[ "$EVENT_NAME" == "merge_group" ]]; thenargs+=(--base "$MERGE_BASE_SHA" --head "$EVENT_SHA")+ elif [[ "$EVENT_NAME" == "push" && "$HEAD_COMMIT_MESSAGE" == release:* ]]; then+ args+=(--base "$PUSH_BASE_SHA" --head "$EVENT_SHA" --force-full)elif [[ "$EVENT_NAME" == "push" ]]; then- args+=(--base "$PUSH_BASE_SHA" --head "$EVENT_SHA" --full-unless-benchmark-only)+ args+=(--base "$PUSH_BASE_SHA" --head "$EVENT_SHA" --main-smoke)elseargs+=(--base "$EVENT_SHA" --head "$EVENT_SHA" --force-full)fi@@ -143,9 +163,16 @@ jobs:timeout-minutes: 10steps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - name: Download execution plan+ if: needs.scope.result == 'success'+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8+ with:+ name: ${{ needs.scope.outputs.plan_artifact_name }}+ path: .ci- name: Validate execution plan+ if: needs.scope.result == 'success'env:- CI_EXECUTION_PLAN: ${{ needs.scope.outputs.execution_plan }}+ CI_EXECUTION_PLAN_FILE: .ci/execution-plan.jsonCI_PLAN_HASH: ${{ needs.scope.outputs.plan_hash }}CI_PROJECTION_NAME: run_auth_buildCI_PROJECTION_VALUE: ${{ needs.scope.outputs.run_auth_build }}@@ -166,15 +193,30 @@ jobs:blog-build:name: Blog build- needs: scope+ needs: [scope, ui-e2e-build]if: needs.scope.outputs.run_blog_build == 'true'runs-on: ubuntu-latest+ container:+ image: ${{ needs.scope.outputs.worker_build_image }}+ options: --init --ipc=host --user 1001+ defaults:+ run:+ shell: bash+ env:+ NEXT_PUBLIC_WS_DO_PORT: "3000"timeout-minutes: 10steps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - name: Download execution plan+ if: needs.scope.result == 'success'+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8+ with:+ name: ${{ needs.scope.outputs.plan_artifact_name }}+ path: .ci- name: Validate execution plan+ if: needs.scope.result == 'success'env:- CI_EXECUTION_PLAN: ${{ needs.scope.outputs.execution_plan }}+ CI_EXECUTION_PLAN_FILE: .ci/execution-plan.jsonCI_PLAN_HASH: ${{ needs.scope.outputs.plan_hash }}CI_PROJECTION_NAME: run_blog_buildCI_PROJECTION_VALUE: ${{ needs.scope.outputs.run_blog_build }}@@ -192,10 +234,21 @@ jobs:turbo-${{ runner.os }}-${{ runner.arch }}-${{ github.job }}-- run: pnpm install --frozen-lockfile- run: pnpm --filter @alook/web validate:blog- - run: pnpm --filter @alook/web exec tsc --noEmit -p blog/tsconfig.json- - run: pnpm --filter @alook/web exec eslint blog/- - run: pnpm --filter @alook/web exec vitest run --config vitest.workspace.config.ts --project=web-node --project=web-dom blog- - run: pnpm --filter @alook/web build:blog+ - run: printf 'BETTER_AUTH_SECRET=ci-e2e-ui-secret\nBETTER_AUTH_URL=http://localhost:3000\nENCRYPTION_KEY=ci-e2e-encryption-key-32chars!!\nDEV_WS_DO_URL=http://localhost:3000\nNODE_ENV=development\n' > src/web/.dev.vars+ - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8+ with:+ name: ${{ needs.ui-e2e-build.outputs.artifact_name }}+ path: .ci/ui-e2e-build+ - name: Verify exact-head build artifact+ env:+ WORKER_ZONES: ${{ needs.scope.outputs.worker_zones }}+ run: |+ zones=$(node -e 'console.log(JSON.parse(process.env.WORKER_ZONES).join(","))')+ node scripts/ci/e2e-build-artifact.mjs verify \+ --directory .ci/ui-e2e-build \+ --run-id "${{ github.run_id }}" \+ --attempt "${{ needs.ui-e2e-build.outputs.artifact_attempt }}" \+ --head-sha "${{ github.sha }}" --zones "$zones"- run: pnpm --filter @alook/web verify:blog-dry-runstatic-checks:@@ -203,6 +256,9 @@ jobs:needs: scopeif: needs.scope.outputs.run_static_checks == 'true'runs-on: ubuntu-latest+ env:+ CI_EXECUTION_PLAN_FILE: .ci/execution-plan.json+ CI_PLAN_HASH: ${{ needs.scope.outputs.plan_hash }}timeout-minutes: 20steps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7@@ -221,46 +277,31 @@ jobs:restore-keys: |turbo-${{ runner.os }}-${{ runner.arch }}-${{ github.job }}-- run: pnpm install --frozen-lockfile+ - name: Download execution plan+ if: needs.scope.result == 'success'+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8+ with:+ name: ${{ needs.scope.outputs.plan_artifact_name }}+ path: .ci- name: Validate execution plan+ if: needs.scope.result == 'success'env:- CI_EXECUTION_PLAN: ${{ needs.scope.outputs.execution_plan }}+ CI_EXECUTION_PLAN_FILE: .ci/execution-plan.jsonCI_PLAN_HASH: ${{ needs.scope.outputs.plan_hash }}- CI_PROJECTION_NAME: static_packages- CI_PROJECTION_VALUE: ${{ needs.scope.outputs.static_packages }}+ CI_PROJECTION_NAME: static_tasks+ CI_PROJECTION_VALUE: ${{ needs.scope.outputs.static_tasks }}run: node scripts/ci/validate-execution-plan.mjs- - name: Typecheck selected packages- env:- SELECTED_PACKAGES: ${{ needs.scope.outputs.static_packages }}- run: |- mapfile -t packages < <(node -e 'for (const value of JSON.parse(process.env.SELECTED_PACKAGES)) console.log(value)')- filters=(); for package in "${packages[@]}"; do filters+=("--filter=$package"); done- pnpm turbo run typecheck "${filters[@]}"- - name: Lint selected packages- env:- SELECTED_PACKAGES: ${{ needs.scope.outputs.static_packages }}- run: |- mapfile -t packages < <(node -e 'for (const value of JSON.parse(process.env.SELECTED_PACKAGES)) console.log(value)')- filters=(); for package in "${packages[@]}"; do filters+=("--filter=$package"); done- pnpm turbo run lint "${filters[@]}"+ - name: Check selected application tasks+ run: node scripts/ci/run-turbo.mjs --plan-group static_tasks- run: pnpm typegrep:ws- run: pnpm typegrep:agent-driver- - name: Build selected packages- if: needs.scope.outputs.build_packages != '[]'- env:- SELECTED_PACKAGES: ${{ needs.scope.outputs.build_packages }}- run: |- mapfile -t packages < <(node -e 'for (const value of JSON.parse(process.env.SELECTED_PACKAGES)) console.log(value)')- filters=(); for package in "${packages[@]}"; do filters+=("--filter=$package"); done- pnpm turbo run build "${filters[@]}"- - name: Dead code detection for selected packages- if: needs.scope.outputs.knip_packages != '[]'+ - name: Build selected non-Web tasks+ if: needs.scope.outputs.build_tasks != '[]'+ run: node scripts/ci/run-turbo.mjs --plan-group build_tasks --filter=!@alook/web+ - name: Dead code detection for selected tasks+ if: needs.scope.outputs.knip_tasks != '[]'continue-on-error: true- env:- SELECTED_PACKAGES: ${{ needs.scope.outputs.knip_packages }}- run: |- mapfile -t packages < <(node -e 'for (const value of JSON.parse(process.env.SELECTED_PACKAGES)) console.log(value)')- filters=(); for package in "${packages[@]}"; do filters+=("--filter=$package"); done- pnpm turbo run knip "${filters[@]}"+ run: node scripts/ci/run-turbo.mjs --plan-group knip_taskstest-linux:name: Tests & Coverage (ubuntu-latest)@@ -269,7 +310,9 @@ jobs:runs-on: ubuntu-latesttimeout-minutes: 45env:- RUN_COVERAGE: ${{ github.event_name != 'push' || startsWith(github.event.head_commit.message, 'release:') }}+ CI_EXECUTION_PLAN_FILE: .ci/execution-plan.json+ CI_PLAN_HASH: ${{ needs.scope.outputs.plan_hash }}+ RUN_COVERAGE: ${{ needs.scope.outputs.execution_mode != 'main-smoke' }}steps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0@@ -287,103 +330,50 @@ jobs:restore-keys: |turbo-${{ runner.os }}-${{ runner.arch }}-${{ github.job }}-- run: pnpm install --frozen-lockfile+ - name: Download execution plan+ if: needs.scope.result == 'success'+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8+ with:+ name: ${{ needs.scope.outputs.plan_artifact_name }}+ path: .ci- name: Validate execution plan+ if: needs.scope.result == 'success'env:- CI_EXECUTION_PLAN: ${{ needs.scope.outputs.execution_plan }}+ CI_EXECUTION_PLAN_FILE: .ci/execution-plan.jsonCI_PLAN_HASH: ${{ needs.scope.outputs.plan_hash }}CI_PROJECTION_NAME: unit_test_rootsCI_PROJECTION_VALUE: ${{ needs.scope.outputs.unit_test_roots }}run: node scripts/ci/validate-execution-plan.mjs- - name: Build selected agent-driver fixture- if: >-- contains(fromJSON(needs.scope.outputs.unit_test_roots), 'src/daemon/agent-driver') ||- contains(fromJSON(needs.scope.outputs.unit_test_roots), 'src/daemon') ||- contains(fromJSON(needs.scope.outputs.linux_suites), 'agent-driver-packed') ||- contains(fromJSON(needs.scope.outputs.linux_suites), 'daemon-packed') ||- contains(fromJSON(needs.scope.outputs.linux_suites), 'daemon-real')- run: pnpm --filter @alook/agent-driver build- - name: Run selected unit tests+ - name: Build native unit prerequisites+ if: needs.scope.outputs.unit_build_tasks != '[]'+ run: node scripts/ci/run-turbo.mjs --plan-group unit_build_tasks+ - name: Run selected unit filesenv:- UNIT_ROOTS: ${{ needs.scope.outputs.unit_test_roots }}- COVERAGE_ROOTS: ${{ needs.scope.outputs.coverage_include_roots }}+ CI_EXECUTION_PLAN_FILE: .ci/execution-plan.json+ CI_PLAN_HASH: ${{ needs.scope.outputs.plan_hash }}run: |- set -euo pipefail- mapfile -t roots < <(node -e 'for (const value of JSON.parse(process.env.UNIT_ROOTS)) console.log(value)')- mapfile -t coverage_roots < <(node -e 'for (const value of JSON.parse(process.env.COVERAGE_ROOTS)) console.log(value)')- daemon=false; non_daemon=(); daemon_coverage=()- for root in "${roots[@]}"; do- if [[ "$root" == "src/daemon" ]]; then daemon=true; else non_daemon+=("$root"); fi- done- for root in "${coverage_roots[@]}"; do- if [[ "$root" == src/daemon/src/* || "$root" == src/daemon/scripts/* ]]; then- daemon_coverage+=("--coverage.include=$root")- fi- done- report_dir="$PWD/.vitest-reports"- coverage_dir="$RUNNER_TEMP/vitest-coverage"- mkdir -p "$report_dir"- mkdir -p "$coverage_dir"- root_index=0- for root in "${non_daemon[@]}"; do- ((root_index += 1))- root_coverage=()- report_stem=${root//\//-}- if [[ "$RUN_COVERAGE" == "true" ]]; then- for include in "${coverage_roots[@]}"; do- if [[ "$include" == "$root/"* ]]; then- root_coverage+=("--coverage.include=$include")- fi- done- if (( ${#root_coverage[@]} )); then- root_coverage=(- --coverage- --coverage.reporter=json- "--coverage.reportsDirectory=$coverage_dir/root-${root_index}-${report_stem}"- "${root_coverage[@]}"- )- fi- fi- case "$root" in- scripts/ci) projects=(ci-scripts) ;;- src/email-worker) projects=(email-worker-node email-worker-runtime) ;;- src/queue-worker) projects=(queue-worker-node queue-worker-runtime) ;;- src/web) projects=(web-node web-dom web-runtime auth-node auth-runtime) ;;- src/ws-do) projects=(ws-do-node ws-do-runtime) ;;- *) projects=("$(node -e 'console.log(require("./" + process.argv[1] + "/package.json").name)' "$root")") ;;- esac- project_args=()- for project in "${projects[@]}"; do project_args+=("--project=$project"); done- vitest_args=("${project_args[@]}")- if (( ${#root_coverage[@]} )); then vitest_args+=("${root_coverage[@]}"); fi- pnpm vitest run "${vitest_args[@]}" \- --reporter=default --reporter=blob \- --outputFile.blob="$report_dir/root-${root_index}-${report_stem}.blob" \- --exclude src/pack.test.ts- done- if [[ "$daemon" == "true" ]]; then- coverage=(); if [[ "$RUN_COVERAGE" == "true" ]]; then coverage=(--coverage); fi- VITEST_MAX_WORKERS=1 pnpm vitest run --project=daemon-node src/daemon "${coverage[@]}" \- "${daemon_coverage[@]}" --reporter=default --reporter=blob \- --outputFile.blob="$report_dir/daemon.blob" \- --exclude src/cli/daemonLifecycle.real.test.ts \- --exclude src/cli/diagnosticsLifecycle.real.test.ts \- --exclude src/cli/daemonStop.test.ts \- --exclude src/version.packed.test.ts \- --exclude src/agent-driver-bundle.packed.test.ts \- --exclude src/cli/daemonSelfUpdate.real.test.ts- fi- - name: Merge and verify selected coverage- if: env.RUN_COVERAGE == 'true'+ args=(--ci --receipt .ci/unit-execution.json)+ if [[ "$RUN_COVERAGE" == "true" ]]; then args+=(--coverage); fi+ node scripts/ci/run-unit-tests.mjs "${args[@]}"+ - name: Verify selected coverage+ if: always() && env.RUN_COVERAGE == 'true'env:- CI_EXECUTION_PLAN: ${{ needs.scope.outputs.execution_plan }}+ CI_EXECUTION_PLAN_FILE: .ci/execution-plan.jsonrun: |- printf '%s\n' "$CI_EXECUTION_PLAN" > "$RUNNER_TEMP/execution-plan.json"- pnpm vitest run --coverage --coverage.reporter=json --coverage.reporter=text \- --merge-reports=.vitest-reportsnode scripts/ci/verify-coverage-plan.mjs \- --plan "$RUNNER_TEMP/execution-plan.json" \+ --plan "$CI_EXECUTION_PLAN_FILE" \--report coverage/coverage-final.json \--output "$RUNNER_TEMP/coverage-target-manifest.json"+ - name: Upload unit execution evidence+ if: always()+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7+ with:+ name: unit-execution-${{ github.run_id }}-${{ github.run_attempt }}+ path: |+ .ci/unit-execution.json+ .vitest-reports/unit.blob+ if-no-files-found: error+ retention-days: 14- name: Run selected daemon real-process testsif: contains(fromJSON(needs.scope.outputs.linux_suites), 'daemon-real')run: |@@ -409,12 +399,12 @@ jobs:files: ./coverage/coverage-final.jsonfail_ci_if_error: true- name: Upload coverage plan evidence- if: env.RUN_COVERAGE == 'true'+ if: always() && env.RUN_COVERAGE == 'true'uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7with:name: coverage-plan-${{ github.run_id }}-${{ github.run_attempt }}path: |- ${{ runner.temp }}/execution-plan.json+ .ci/execution-plan.json${{ runner.temp }}/coverage-target-manifest.jsoncoverage/coverage-final.jsonif-no-files-found: error@@ -443,9 +433,16 @@ jobs:restore-keys: |turbo-${{ runner.os }}-${{ runner.arch }}-${{ github.job }}-- run: pnpm install --frozen-lockfile+ - name: Download execution plan+ if: needs.scope.result == 'success'+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8+ with:+ name: ${{ needs.scope.outputs.plan_artifact_name }}+ path: .ci- name: Validate execution plan+ if: needs.scope.result == 'success'env:- CI_EXECUTION_PLAN: ${{ needs.scope.outputs.execution_plan }}+ CI_EXECUTION_PLAN_FILE: .ci/execution-plan.jsonCI_PLAN_HASH: ${{ needs.scope.outputs.plan_hash }}CI_PROJECTION_NAME: windows_suitesCI_PROJECTION_VALUE: ${{ needs.scope.outputs.windows_suites }}@@ -487,7 +484,7 @@ jobs:filters+=("--filter=@alook/$suite")fidone- pnpm turbo run test "${filters[@]}"+ node scripts/ci/run-turbo.mjs run test "${filters[@]}"app-packed-artifact:name: App Packed Artifact@@ -497,9 +494,16 @@ jobs:timeout-minutes: 15steps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - name: Download execution plan+ if: needs.scope.result == 'success'+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8+ with:+ name: ${{ needs.scope.outputs.plan_artifact_name }}+ path: .ci- name: Validate execution plan+ if: needs.scope.result == 'success'env:- CI_EXECUTION_PLAN: ${{ needs.scope.outputs.execution_plan }}+ CI_EXECUTION_PLAN_FILE: .ci/execution-plan.jsonCI_PLAN_HASH: ${{ needs.scope.outputs.plan_hash }}CI_PROJECTION_NAME: run_app_packed_artifactCI_PROJECTION_VALUE: ${{ needs.scope.outputs.run_app_packed_artifact }}@@ -540,7 +544,7 @@ jobs:e2e:name: E2E Testsneeds: scope- if: needs.scope.outputs.run_e2e == 'true' && github.event_name != 'push'+ if: needs.scope.outputs.run_e2e == 'true'runs-on: ubuntu-latesttimeout-minutes: 15env:@@ -554,9 +558,16 @@ jobs:node-version: 22cache: pnpm- run: pnpm install --frozen-lockfile+ - name: Download execution plan+ if: needs.scope.result == 'success'+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8+ with:+ name: ${{ needs.scope.outputs.plan_artifact_name }}+ path: .ci- name: Validate execution plan+ if: needs.scope.result == 'success'env:- CI_EXECUTION_PLAN: ${{ needs.scope.outputs.execution_plan }}+ CI_EXECUTION_PLAN_FILE: .ci/execution-plan.jsonCI_PLAN_HASH: ${{ needs.scope.outputs.plan_hash }}CI_PROJECTION_NAME: integration_suitesCI_PROJECTION_VALUE: ${{ needs.scope.outputs.integration_suites }}@@ -615,10 +626,16 @@ jobs:RUSTFLAGS: -D warningssteps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - name: Download execution plan+ if: needs.scope.result == 'success'+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8+ with:+ name: ${{ needs.scope.outputs.plan_artifact_name }}+ path: .ci- name: Validate execution planworking-directory: ${{ github.workspace }}env:- CI_EXECUTION_PLAN: ${{ needs.scope.outputs.execution_plan }}+ CI_EXECUTION_PLAN_FILE: .ci/execution-plan.jsonCI_PLAN_HASH: ${{ needs.scope.outputs.plan_hash }}CI_PROJECTION_NAME: run_rustCI_PROJECTION_VALUE: ${{ needs.scope.outputs.run_rust }}@@ -645,7 +662,7 @@ jobs:lighthouse:name: Lighthouse SEOneeds: scope- if: needs.scope.outputs.run_lighthouse == 'true' && github.event_name != 'push'+ if: needs.scope.outputs.run_lighthouse == 'true'runs-on: ubuntu-latesttimeout-minutes: 10env:@@ -653,9 +670,16 @@ jobs:BETTER_AUTH_URL: http://localhost:3000steps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - name: Download execution plan+ if: needs.scope.result == 'success'+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8+ with:+ name: ${{ needs.scope.outputs.plan_artifact_name }}+ path: .ci- name: Validate execution plan+ if: needs.scope.result == 'success'env:- CI_EXECUTION_PLAN: ${{ needs.scope.outputs.execution_plan }}+ CI_EXECUTION_PLAN_FILE: .ci/execution-plan.jsonCI_PLAN_HASH: ${{ needs.scope.outputs.plan_hash }}CI_PROJECTION_NAME: run_lighthouseCI_PROJECTION_VALUE: ${{ needs.scope.outputs.run_lighthouse }}@@ -672,28 +696,38 @@ jobs:run: npx @lhci/cli autorun --config=lighthouserc.json && node scripts/print-lighthouse-scores.mjsui-e2e-build:- name: UI Playwright E2E build+ name: Web and Blog OpenNext artifactsneeds: scopeoutputs:artifact_name: ${{ steps.artifact_identity.outputs.artifact_name }}artifact_attempt: ${{ steps.artifact_identity.outputs.artifact_attempt }}- if: needs.scope.outputs.run_ui_e2e == 'true' && github.event_name != 'push'+ if: needs.scope.outputs.run_worker_build == 'true'runs-on: ubuntu-latestcontainer:- image: ${{ fromJSON(needs.scope.outputs.e2e_matrix).include[0].image }}+ image: ${{ needs.scope.outputs.worker_build_image }}options: --init --ipc=host --user 1001defaults:run:shell: bash+ env:+ NEXT_PUBLIC_WS_DO_PORT: "3000"+ WORKER_ZONES: ${{ needs.scope.outputs.worker_zones }}timeout-minutes: 20steps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - name: Download execution plan+ if: needs.scope.result == 'success'+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8+ with:+ name: ${{ needs.scope.outputs.plan_artifact_name }}+ path: .ci- name: Validate execution plan+ if: needs.scope.result == 'success'env:- CI_EXECUTION_PLAN: ${{ needs.scope.outputs.execution_plan }}+ CI_EXECUTION_PLAN_FILE: .ci/execution-plan.jsonCI_PLAN_HASH: ${{ needs.scope.outputs.plan_hash }}- CI_PROJECTION_NAME: e2e_matrix- CI_PROJECTION_VALUE: ${{ needs.scope.outputs.e2e_matrix }}+ CI_PROJECTION_NAME: worker_zones+ CI_PROJECTION_VALUE: ${{ needs.scope.outputs.worker_zones }}run: node scripts/ci/validate-execution-plan.mjs- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7@@ -707,19 +741,22 @@ jobs:printf 'artifact_name=ui-e2e-build-%s-%s\n' "${{ github.run_id }}" "${{ github.run_attempt }}" >> "$GITHUB_OUTPUT"printf 'artifact_attempt=%s\n' "${{ github.run_attempt }}" >> "$GITHUB_OUTPUT"- run: printf 'BETTER_AUTH_SECRET=ci-e2e-ui-secret\nBETTER_AUTH_URL=http://localhost:3000\nENCRYPTION_KEY=ci-e2e-encryption-key-32chars!!\nDEV_WS_DO_URL=http://localhost:3000\nNODE_ENV=development\n' > src/web/.dev.vars- - name: Build Web and Blog OpenNext workers- env:- NEXT_PUBLIC_WS_DO_PORT: "3000"+ - name: Build selected OpenNext workers oncerun: |- pnpm --filter @alook/web exec opennextjs-cloudflare build- pnpm --filter @alook/web build:blog+ mapfile -t zones < <(node -e 'for (const value of JSON.parse(process.env.WORKER_ZONES)) console.log(value)')+ tasks=(); for zone in "${zones[@]}"; do+ if [[ "$zone" == web ]]; then tasks+=("@alook/web#build"); else tasks+=("@alook/web#build:blog"); fi+ done+ node scripts/ci/run-turbo.mjs run "${tasks[@]}" --concurrency=1+ if [[ "$WORKER_ZONES" == '["web","blog"]' ]]; then pnpm --filter @alook/web verify:zone-output; fi- name: Create exact-head build artifactrun: |+ zones=$(node -e 'console.log(JSON.parse(process.env.WORKER_ZONES).join(","))')node scripts/ci/e2e-build-artifact.mjs create \--directory .ci/ui-e2e-build \--run-id "${{ github.run_id }}" \--attempt "${{ steps.artifact_identity.outputs.artifact_attempt }}" \- --head-sha "${{ github.sha }}"+ --head-sha "${{ github.sha }}" --zones "$zones"- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7with:name: ${{ steps.artifact_identity.outputs.artifact_name }}@@ -733,7 +770,7 @@ jobs:e2e-ui:name: UI Playwright E2E (${{ matrix.shard }}/${{ matrix.total }})needs: [scope, ui-e2e-build]- if: needs.scope.outputs.run_ui_e2e == 'true' && github.event_name != 'push'+ if: needs.scope.outputs.run_ui_e2e == 'true'runs-on: ubuntu-latestcontainer:image: ${{ matrix.image }}@@ -746,19 +783,29 @@ jobs:fail-fast: falsematrix: ${{ fromJSON(needs.scope.outputs.e2e_matrix) }}env:+ NEXT_PUBLIC_WS_DO_PORT: "3000"+ WORKER_ZONES: ${{ needs.scope.outputs.worker_zones }}BETTER_AUTH_SECRET: ci-e2e-ui-secretBETTER_AUTH_URL: http://localhost:3000steps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - name: Download execution plan+ if: needs.scope.result == 'success'+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8+ with:+ name: ${{ needs.scope.outputs.plan_artifact_name }}+ path: .ci- name: Validate execution plan+ if: needs.scope.result == 'success'env:- CI_EXECUTION_PLAN: ${{ needs.scope.outputs.execution_plan }}+ CI_EXECUTION_PLAN_FILE: .ci/execution-plan.jsonCI_PLAN_HASH: ${{ needs.scope.outputs.plan_hash }}CI_PROJECTION_NAME: e2e_matrixCI_PROJECTION_VALUE: ${{ needs.scope.outputs.e2e_matrix }}run: node scripts/ci/validate-execution-plan.mjs- env:E2E_SPECS: ${{ toJSON(matrix.specs) }}+ E2E_CASE_KEYS: ${{ toJSON(matrix.case_keys) }}run: |node scripts/ci/e2e-shard-artifacts.mjs write-manifest \--output src/web/e2e-shard-manifest/shard-manifest.json \@@ -766,7 +813,9 @@ jobs:--attempt "${{ github.run_attempt }}" \--sha "${{ github.sha }}" \--shard "${{ matrix.shard }}" \- --total "${{ matrix.total }}"+ --total "${{ matrix.total }}" \+ --native-shard "${{ matrix.native_shard }}" \+ --native-total "${{ matrix.native_total }}"- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:@@ -780,17 +829,24 @@ jobs:path: .ci/ui-e2e-build- name: Verify exact-head build artifactrun: |+ zones=$(node -e 'console.log(JSON.parse(process.env.WORKER_ZONES).join(","))')node scripts/ci/e2e-build-artifact.mjs verify \--directory .ci/ui-e2e-build \--run-id "${{ github.run_id }}" \--attempt "${{ needs.ui-e2e-build.outputs.artifact_attempt }}" \- --head-sha "${{ github.sha }}"- - env:+ --head-sha "${{ github.sha }}" --zones "$zones"+ - name: Run native Playwright partition+ timeout-minutes: 14+ env:ALOOK_E2E_PREBUILT: "1"- E2E_SPECS: ${{ toJSON(matrix.specs) }}+ ALOOK_E2E_ZONES: ${{ toJSON(matrix.zones) }}+ E2E_SPECS: ${{ needs.scope.outputs.ui_specs }}run: |- mapfile -t specs < <(node -e 'for (const spec of JSON.parse(process.env.E2E_SPECS)) console.log(spec)')- pnpm --filter @alook/web exec playwright test "${specs[@]}"+ mapfile -t specs < <(node -e 'for (const spec of JSON.parse(process.env.E2E_SPECS)) if (spec !== "all") console.log("src/test/e2e-ui/" + spec)')+ pnpm --filter @alook/web exec playwright test "${specs[@]}" --shard=${{ matrix.native_shard }}/${{ matrix.native_total }}+ - name: Restore browser services+ if: ${{ always() }}+ run: pnpm --filter @alook/web exec tsx -e 'import teardown from "./src/test/e2e-ui/_setup/global-teardown.ts"; teardown().catch(error => { console.error(error); process.exitCode = 1 })'- if: ${{ !cancelled() }}uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7with:@@ -815,7 +871,7 @@ jobs:resizable-panels-compat:name: Resizable panels compatibilityneeds: [scope, ui-e2e-build]- if: needs.scope.outputs.run_resizable_panels_compat == 'true' && github.event_name != 'push'+ if: needs.scope.outputs.run_resizable_panels_compat == 'true'runs-on: ubuntu-latestcontainer:image: ${{ fromJSON(needs.scope.outputs.e2e_matrix).include[0].image }}@@ -825,13 +881,22 @@ jobs:shell: bashtimeout-minutes: 15env:+ NEXT_PUBLIC_WS_DO_PORT: "3000"+ WORKER_ZONES: ${{ needs.scope.outputs.worker_zones }}BETTER_AUTH_SECRET: ci-e2e-ui-secretBETTER_AUTH_URL: http://localhost:3000steps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - name: Download execution plan+ if: needs.scope.result == 'success'+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8+ with:+ name: ${{ needs.scope.outputs.plan_artifact_name }}+ path: .ci- name: Validate execution plan+ if: needs.scope.result == 'success'env:- CI_EXECUTION_PLAN: ${{ needs.scope.outputs.execution_plan }}+ CI_EXECUTION_PLAN_FILE: .ci/execution-plan.jsonCI_PLAN_HASH: ${{ needs.scope.outputs.plan_hash }}CI_PROJECTION_NAME: e2e_matrixCI_PROJECTION_VALUE: ${{ needs.scope.outputs.e2e_matrix }}@@ -849,14 +914,16 @@ jobs:path: .ci/ui-e2e-build- name: Verify exact-head build artifactrun: |+ zones=$(node -e 'console.log(JSON.parse(process.env.WORKER_ZONES).join(","))')node scripts/ci/e2e-build-artifact.mjs verify \--directory .ci/ui-e2e-build \--run-id "${{ github.run_id }}" \--attempt "${{ needs.ui-e2e-build.outputs.artifact_attempt }}" \- --head-sha "${{ github.sha }}"+ --head-sha "${{ github.sha }}" --zones "$zones"- name: Run responsive shell compatibility journeysenv:ALOOK_E2E_PREBUILT: "1"+ ALOOK_E2E_ZONES: '["web"]'run: |pnpm --filter @alook/web exec playwright test \src/test/e2e-ui/53-mobile-inbox-surface.spec.ts \@@ -876,14 +943,21 @@ jobs:merge-reports:name: Merge Playwright Reportsneeds: [scope, e2e-ui]- if: ${{ !cancelled() && needs.scope.outputs.run_ui_e2e == 'true' && github.event_name != 'push' }}+ if: ${{ !cancelled() && needs.scope.outputs.run_ui_e2e == 'true' }}runs-on: ubuntu-latesttimeout-minutes: 5steps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - name: Download execution plan+ if: needs.scope.result == 'success'+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8+ with:+ name: ${{ needs.scope.outputs.plan_artifact_name }}+ path: .ci- name: Validate execution plan+ if: needs.scope.result == 'success'env:- CI_EXECUTION_PLAN: ${{ needs.scope.outputs.execution_plan }}+ CI_EXECUTION_PLAN_FILE: .ci/execution-plan.jsonCI_PLAN_HASH: ${{ needs.scope.outputs.plan_hash }}CI_PROJECTION_NAME: e2e_matrixCI_PROJECTION_VALUE: ${{ needs.scope.outputs.e2e_matrix }}@@ -955,15 +1029,22 @@ jobs:{"name":"test-linux","expected":${{ needs.scope.outputs.run_linux == 'true' }},"result":"${{ needs.test-linux.result }}"},{"name":"test-windows","expected":${{ needs.scope.outputs.run_windows == 'true' }},"result":"${{ needs.test-windows.result }}"},{"name":"app-packed-artifact","expected":${{ needs.scope.outputs.run_app_packed_artifact == 'true' }},"result":"${{ needs.app-packed-artifact.result }}"},- {"name":"e2e","expected":${{ needs.scope.outputs.run_e2e == 'true' && github.event_name != 'push' }},"result":"${{ needs.e2e.result }}"},+ {"name":"e2e","expected":${{ needs.scope.outputs.run_e2e == 'true' }},"result":"${{ needs.e2e.result }}"},{"name":"desktop-rust","expected":${{ needs.scope.outputs.run_rust == 'true' }},"result":"${{ needs.desktop-rust.result }}"},- {"name":"lighthouse","expected":${{ needs.scope.outputs.run_lighthouse == 'true' && github.event_name != 'push' }},"result":"${{ needs.lighthouse.result }}"}+ {"name":"lighthouse","expected":${{ needs.scope.outputs.run_lighthouse == 'true' }},"result":"${{ needs.lighthouse.result }}"}]steps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - name: Download execution plan+ if: needs.scope.result == 'success'+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8+ with:+ name: ${{ needs.scope.outputs.plan_artifact_name }}+ path: .ci- name: Validate execution plan+ if: needs.scope.result == 'success'env:- CI_EXECUTION_PLAN: ${{ needs.scope.outputs.execution_plan }}+ CI_EXECUTION_PLAN_FILE: .ci/execution-plan.jsonCI_PLAN_HASH: ${{ needs.scope.outputs.plan_hash }}run: node scripts/ci/validate-execution-plan.mjs- run: node scripts/ci/assert-gate.mjs@@ -978,16 +1059,23 @@ jobs:CI_GATE_RESULTS: >-[{"name":"scope","expected":true,"result":"${{ needs.scope.result }}"},- {"name":"ui-e2e-build","expected":${{ needs.scope.outputs.run_ui_e2e == 'true' && github.event_name != 'push' }},"result":"${{ needs.ui-e2e-build.result }}"},- {"name":"e2e-ui","expected":${{ needs.scope.outputs.run_ui_e2e == 'true' && github.event_name != 'push' }},"result":"${{ needs.e2e-ui.result }}"},- {"name":"resizable-panels-compat","expected":${{ needs.scope.outputs.run_resizable_panels_compat == 'true' && github.event_name != 'push' }},"result":"${{ needs.resizable-panels-compat.result }}"},- {"name":"merge-reports","expected":${{ needs.scope.outputs.run_ui_e2e == 'true' && github.event_name != 'push' }},"result":"${{ needs.merge-reports.result }}"}+ {"name":"ui-e2e-build","expected":${{ needs.scope.outputs.run_worker_build == 'true' }},"result":"${{ needs.ui-e2e-build.result }}"},+ {"name":"e2e-ui","expected":${{ needs.scope.outputs.run_ui_e2e == 'true' }},"result":"${{ needs.e2e-ui.result }}"},+ {"name":"resizable-panels-compat","expected":${{ needs.scope.outputs.run_resizable_panels_compat == 'true' }},"result":"${{ needs.resizable-panels-compat.result }}"},+ {"name":"merge-reports","expected":${{ needs.scope.outputs.run_ui_e2e == 'true' }},"result":"${{ needs.merge-reports.result }}"}]steps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - name: Download execution plan+ if: needs.scope.result == 'success'+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8+ with:+ name: ${{ needs.scope.outputs.plan_artifact_name }}+ path: .ci- name: Validate execution plan+ if: needs.scope.result == 'success'env:- CI_EXECUTION_PLAN: ${{ needs.scope.outputs.execution_plan }}+ CI_EXECUTION_PLAN_FILE: .ci/execution-plan.jsonCI_PLAN_HASH: ${{ needs.scope.outputs.plan_hash }}run: node scripts/ci/validate-execution-plan.mjs- run: node scripts/ci/assert-gate.mjsdiff --git a/.github/workflows/publish-app.yml b/.github/workflows/publish-app.ymlindex 07e8b736b..de7b10d09 100644--- a/.github/workflows/publish-app.yml+++ b/.github/workflows/publish-app.yml@@ -60,17 +60,13 @@ jobs:- run: pnpm install --frozen-lockfileif: steps.check.outputs.skip == 'false'- - name: Build packages- if: steps.check.outputs.skip == 'false'- run: pnpm build --filter=@alook/shared --filter=@alook/web --filter=@alook/daemon --filter=@alook/email-worker --filter=@alook/ws-do --filter=@alook/queue-worker-- - name: Bundle app (pre-build workers)+ - name: Build and bundle workers onceif: steps.check.outputs.skip == 'false'run: pnpm -C src/app run bundle- name: Build app CLIif: steps.check.outputs.skip == 'false'- run: pnpm -C src/app run build+ run: node scripts/ci/run-turbo.mjs run @alook/app#build- name: Publish to npm (OIDC)if: steps.check.outputs.skip == 'false'diff --git a/.github/workflows/publish-daemon.yml b/.github/workflows/publish-daemon.ymlindex 0506c97ed..fdb6dc62a 100644--- a/.github/workflows/publish-daemon.yml+++ b/.github/workflows/publish-daemon.yml@@ -60,13 +60,9 @@ jobs:- run: pnpm install --frozen-lockfileif: steps.check.outputs.skip == 'false'- - name: Build bundled agent driver+ - name: Build daemon and its native prerequisitesif: steps.check.outputs.skip == 'false'- run: pnpm -C src/daemon/agent-driver run build-- - name: Build daemon bundle- if: steps.check.outputs.skip == 'false'- run: pnpm -C src/daemon run build+ run: node scripts/ci/run-turbo.mjs run @alook/daemon#build- name: Publish to npm (OIDC)if: steps.check.outputs.skip == 'false'diff --git a/.github/workflows/windows-runtime.yml b/.github/workflows/windows-runtime.ymlindex 4f0ba3543..11c2add6a 100644--- a/.github/workflows/windows-runtime.yml+++ b/.github/workflows/windows-runtime.yml@@ -4,7 +4,16 @@ on:pull_request:branches: [main]paths:- - src/daemon/agent-driver/**+ - src/daemon/**+ - src/shared/**+ - tests/utils/**+ - package.json+ - pnpm-lock.yaml+ - pnpm-workspace.yaml+ - turbo.json+ - tsconfig.json+ - vitest.config.ts+ - scripts/ci/**- .github/workflows/windows-runtime.ymlworkflow_dispatch:diff --git a/.gitignore b/.gitignoreindex e94563ba3..a104f3bb9 100644--- a/.gitignore+++ b/.gitignore@@ -34,3 +34,5 @@ src/daemon/LICENSE.superpowers/src/web/blog/public/blog/_generated/+.ci/+.vitest/diff --git a/AGENTS.md b/AGENTS.mdindex 4a8205263..a2fbfc0a4 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -12,7 +12,7 @@ Alook's main purpose is to make the cli agent always on, and give it a email add## MUST- Don't write comment: comment may be outdated, code never. Unless the comment are specs and rules.-- run `pnpm typecheck`, `pnpm test` as the final check when you think the code is ready.+- Run `pnpm check` before delivery. It uses the canonical impact plan and normal repository checks. Use `pnpm check:full` for an explicit complete check; policy, unknown or unresolved inputs fall back to full automatically. Record actual selected and executed checks, not a blanket all-tests claim.- service must be STATELESS! All the state must be in DB or local, never put important states in memory.- scope the queries before, not check the ownership after. don't query data then check if the data belongs to a workspace, use workspace id ahead to query the data.- respect others' works, don't reset any other git changes just because it's not done by you, others may working at the same time, never revert anything without asking the user.@@ -29,7 +29,7 @@ pnpm bump patch --desktop # trigger desktop buildThis updates every `src/*/package.json` and commits `release: vX.Y.Z`.Add `--min-cli` when the release contains breaking changes that require users to update their CLI.Add `--desktop` when the release includes desktop app changes that need a new build.-Mobile store releases are not configured; add current signing accounts and rebuild the release workflow before exposing a mobile release flag.+Add `--mobile` to trigger the existing iOS TestFlight upload and Android artifact workflow. Upload, store processing and review acceptance are separate outcomes.After reviewing the commit:```bash@@ -37,16 +37,17 @@ git push origin main```This triggers:-- **CI** — typecheck, lint, tests, coverage (uploaded to Codecov)+- **CI** — the complete regression for release commits; ordinary main commits use key smoke checks and relevant artifacts- **Auto-Tag & Release** — CI detects the `release: vX.Y.Z` commit message, creates the git tag, and creates a GitHub Release with generated changelog (`auto-tag-release.yml`)- **@alook/app** → auto-published to npm via `publish-app.yml` (watches `src/app/package.json`)- **@alook/daemon** → auto-published to npm via `publish-daemon.yml` (watches `src/daemon/package.json`)-- **CF Workers** → each module redeploys when its own `package.json` changes+- **CF Workers** → existing Cloudflare Git integration and watch rules determine deployments; GitHub CI is not an external deployment gate-### E2E UI (browser tests)-Playwright browser E2E for the web UI lives in `src/web/src/test/e2e-ui/`. The `e2e-ui.yml` workflow starts for every PR and merge-queue check, then runs the browser matrix only when the diff touches `src/web`/`src/shared`/`src/ws-do`; blog-only and unrelated changes finish through the lightweight scope and gate jobs. The workflow also supports manual full runs, but does not run after pushes to `main`. It is deliberately NOT tied to the release chain: a `release:` bump only changes version numbers, so gating there would test nothing, and the production web app deploys via Cloudflare's own Git integration (outside GitHub Actions) which a workflow gate can't block anyway. Run locally with `pnpm test:e2e-ui` (backs up and restores your local `.wrangler/state`).+### CI and browser tests-> Branch protection may require the stable `UI E2E Gate` check. Do not require the individual `UI Playwright E2E (n/N)` matrix jobs, because skipped shards are expected for changes outside the UI scope.+`.github/workflows/ci.yml` owns one canonical impact plan. PR and merge-queue checks use native Turbo affected tasks and Vitest related files plus key browser paths and matched feature groups. Web, Blog and Auth retain separate task/project inputs. Structural, nonmodule/configuration and graph-error boundaries run complete selected projects; keep selection/execution receipts. Core, policy, unknown and unresolved inputs retain full fallback. Ordinary main pushes run the small behavior smoke set and relevant artifacts; release commits and manual full dispatch run the full regression. See [CONTRIBUTING.md](CONTRIBUTING.md#ci-trigger-and-test-responsibilities) for the matrix and explicit commands.++Browser specs remain in `src/web/src/test/e2e-ui/`. Reuse the zone-aware build-once artifact, native Playwright file partitions and exact case/report verification. Freeze native discovery once in the plan; consumers run the entire selected file set with the original native shard pair. Keep one worker, zero retries and existing case limits;240 seconds is a measurement target, not a prediction. Keep stable `CI Gate` and `UI E2E Gate` checks; skipped out-of-scope jobs are expected, so do not require individual shards. No daily schedule is implied. Browser tests do not contribute to Vitest coverage. Codecov project and patch percentages are informational; neither hosted status nor the repository verifier enforces a percentage minimum. Failed tests, missing required instrumentation, malformed reports and upload errors still fail.## Plan-driven Development- You must make a markdown plan at `plans/` before you implement any my request, otherwise I will reject your implementation.@@ -58,17 +59,16 @@ Playwright browser E2E for the web UI lives in `src/web/src/test/e2e-ui/`. The `- in `new deps` section, you must list all the new external dependencies that will be added.- use checklist in `TODOS` section, for each checkbox, you must have a clear description of what to do and list all the files that will be modified.- at the end of TODOS, you must include `test cases` sub section, use checklist format to list all the test cases that should be covered.- - `QA tests` section is REQUIRED. It must be a checklist of end-to-end user journeys the `alook-c-qa` agent will drive after implementation lands. For each journey: name it, list the routes/testids it exercises, and state the backend signal (D1 row, WS frame, worker log) that proves it worked. This section is the QA agent's brief — it will fail if the section is missing or vague.+ - `QA tests` is required. For changed app behavior, name each necessary journey, its routes/testids and confirming backend signal. For tooling, name the real command/event, expected output and failure/cleanup signal. Reuse existing tests; do not invent a UI journey for a documentation or CI-only change. Name the assigned executor and state unrun or out-of-scope evidence explicitly.-## QA after every new /c feature-- After any change that touches `src/web` (especially the `/c` surface), `src/ws-do`, or `src/shared` community queries/schema, you MUST launch the `alook-c-qa` subagent to verify the feature end-to-end before reporting the task complete. Typecheck + unit tests are necessary but not sufficient — a green build with a broken user journey is still a broken feature.-- The QA agent lives at `.claude/agents/alook-c-qa.md`. Invoke it via the Agent tool with `subagent_type: alook-c-qa` and hand it the `QA tests` checklist from the plan. It boots (or reuses) the local dev stack, drives the browser, correlates against D1 + WS + worker logs, and reports PASS/FAIL/BLOCKED with evidence.-- If the QA agent returns FAIL or BLOCKED, treat that as an unfinished task — fix the defect and re-run the QA agent. Do not mark the plan checkbox complete on a failing journey. If a journey is genuinely out of scope for a change, say so in the report and skip it explicitly, don't silently drop it.-- The QA agent is scoped to `/c` (community). For changes elsewhere in `src/web` (blog, marketing, calendar, etc.) it is not the right tool — run the relevant unit/E2E tests directly.+## Behavioral tests and QA-## Always WRITE/RUN TESTS!-- never report to me about your code changes without running tests first.-- always write tests for your code changes, only when your code changes are already covered by the current tests.+- Select the lowest layer that proves the risk: pure/module tests for logic, DOM for visible state and events, native database/Worker/process integration for platform contracts, and browser E2E for key user journeys and changed integration boundaries.+- A `/c` behavior change needs the relevant existing key/feature journeys. A source-path touch alone does not require another complete browser run. CI/test-only changes need real tooling/selection checks, not an invented product journey.+- Use the task's assigned QA executor. If no executor is assigned and community runtime QA is needed, use `.claude/agents/alook-c-qa.md` with the plan's actual journey checklist. Do not duplicate an already assigned independent QA owner. Non-community surfaces use their relevant tests.+- Keep authentication, permission, message consistency, durable writes and process cleanup assertions. A QA FAIL/BLOCKED remains unfinished unless the owner explicitly accepts that scoped gap; discovery, compile, cached replay and actual runtime execution are different evidence.+- Add or change a test only when it independently proves changed behavior or an uncovered risk. Do not copy implementation text, mirror a complete internal props definition, add arbitrary line-count limits or manufacture a private exception to raise coverage. When removing or combining a test, state its former risk, the exact remaining executable guard and any coverage loss.+- Review test value again before freezing a candidate. Preserve distinct negative, concurrency and failure cases; two layers with different real boundaries are not duplicates merely because their names match. Do not weaken assertions, retries, budgets, source identity or cleanup to reduce runtime.## Don't use plan MODE, try to write the plan md directlydiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 578586ec1..dae42849f 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -21,7 +21,7 @@ pnpm devThis starts the web app and workers locally. To work on the CLI separately:```bash-pnpm dev:cli+pnpm dev:app```### Frontend telemetry build configuration@@ -67,18 +67,20 @@ A few ground rules:### 3. Validate before pushing```bash-pnpm typecheck-pnpm lint-pnpm test+pnpm check # canonical affected checks; shared Turbo cache+pnpm check --plan # inspect source scope and commands without running them+pnpm check:full # explicit complete six-check contract```-All three must pass. A pre-commit hook runs lint and test automatically.+The normal pre-commit hook runs `pnpm check` too. Both entries use the existing impact closure and normal package scripts; Turbo may replay identical tasks. Policy, unknown paths and unresolved Git inputs fall back to the full contract. The local entry includes branch commits, staged/unstaged changes and untracked source. It keeps driver builds/tests ordered and stops at the first failed child. Individual `pnpm typecheck`, `pnpm lint` and `pnpm test` commands remain available.++Report the checks actually selected and run, including cache replay, skipped groups and original failures. Do not rerun a full suite only to obtain another copy of the same result.### 4. Open a PR- Target the `main` branch- Fill out the PR template — link the issue, describe what changed, check the impact areas-- CI runs typecheck, lint, tests (Ubuntu + Windows), e2e, build, and Lighthouse+- CI follows the trigger and impact matrix below; stable CI/UI gates must finish for their applicable jobs## Commit Messages@@ -156,15 +158,40 @@ Use the normal Web Vitest configs and repository gates. Real QA must also bind t- **Framework:** Vitest- **E2E:** Playwright (web package)- **Run all:** `pnpm test`-- **Run by package:** `pnpm test:shared`, `pnpm test:cli`, `pnpm test:web`, `pnpm test:e2e`+- **Run by package:** `pnpm test:shared`, `pnpm test:daemon`, `pnpm test:web`, `pnpm test:e2e`++Affected platform-specific contracts run on their relevant CI platforms. A Windows process or installed-package test is not replaced by a Linux mock.++### CI trigger and test responsibilities++| Trigger | Checks |+| --- | --- |+| PR / merge group | Native Turbo affected tasks, Vitest related files, key browser paths and matched feature groups |+| Ordinary main | Small existing behavior smoke set plus relevant build/artifact checks |+| Release main (`release:` commit) | Full package/platform, API/browser and artifact regression |+| Manual CI `full` | Full regression; diagnostic dispatch keeps its existing exact-source guard |+| Docs / benchmark only | No unrelated product checks; stable gates report applicable skips |+| Policy, core/unknown classification or unresolved diff | Conservative full fallback; no silent narrowing |++Turbo owns task inputs, dependencies and cache outputs. Web, Blog and Auth are separate tasks/projects inside the Web package. The unit entry uses Vitest's native related analysis, unions directly changed tests, and runs the complete selected project for structural contracts, nonmodule/configuration inputs or analysis errors. Selection receipts distinguish discovered, selected and executed files; a graph failure cannot become an empty success. Full commands remain available through `pnpm check:full` and `pnpm test`.++Package boundaries, smoke files and UI feature paths/specs live in `scripts/ci/change-scope-manifest.json`. All consumers use the same validated execution plan. A localized rule applies only when every relevant runtime path is covered; shared helpers and unclassified runtime changes expand to the full browser inventory. Renames include both sides, and deleted specs do not silently disappear. Full manual/release runs retain every discovered browser spec. No daily schedule is added.++Keep production permission, session, persistence, message replay and process-authority tests. Test observable outcomes at the layer that owns the risk; do not require a second implementation-text snapshot for behavior already tested through the real component. A source-reading test can still guard an actual architecture, package or native-code boundary. Each deletion or merge must name its remaining executable guard and its limits.++Codecov project and patch statuses and the optional `node scripts/ci/report-changed-patch-coverage.mjs --base <ref> --report <coverage-json>` output are review information. No coverage percentage is a minimum gate, including in the repository verifier; valid zero-coverage reports still retain their actual counts and percentages. Failed tests, invalid reports, missing required instrumentation and failed uploads remain errors. Named project path groups and report completeness remain checked. Browser E2E is not part of Vitest coverage.++The Web/Blog OpenNext producer builds each required zone once. Blog dry-run and browser jobs verify source, native task hashes, toolchain, environment and archived output identity before consuming it. Web-only browser jobs omit Blog build/start. Lighthouse, Auth, packed artifacts and native platforms keep their own contracts.++Playwright owns discovery and file sharding. The signed plan freezes actual case identities and native partition pairs; each job runs the complete selected file set with its native `--shard` pair. Empty native partitions create no job. One worker, zero retries and existing case/expect limits remain. The 240-second target is measured separately from the command/job deadlines; no duration table or predicted bound is used. An always-run teardown restores the existing service owner before report collection.-Tests run on both Ubuntu and Windows in CI.+The browser workflow reuses one exact-source build across selected shards and verifies their reports. Stable `CI Gate` and `UI E2E Gate` checks are the integration boundary; individual out-of-scope shards may be skipped. Selection and discovery do not prove execution. Release CI also does not gate an independent Cloudflare Git deployment or imply that a store accepted a build.### UI browser E2E and formal local QARun `pnpm test:e2e-ui` from the repository root. Local runs and CI use thesame built Worker graph: one pinned Wrangler loads Web, WS and the real-queue worker; Blog runs separately with its own storage. The public ingress+queue worker; Blog runs separately with its own storage when selected. Local full runs select both Web and Blog. The public ingressis `http://localhost:3000`, with Web on port 3001 and Blog on port 3002. Stop other devstacks before this run. The runner does not reuse a stack based on healthresponses and does not stop listeners owned by another worktree.@@ -232,7 +259,7 @@ outside this change.|---------|-------------|| `pnpm dev` | Start all dev servers (except CLI) || `pnpm dev:web` | Next.js on :3000 |-| `pnpm dev:cli` | CLI daemon |+| `pnpm dev:app` | CLI daemon || `pnpm dev:email` | Email worker on :8787 || `pnpm typecheck` | Typecheck all packages || `pnpm lint` | Lint all packages |diff --git a/codecov.yml b/codecov.ymlindex fb913a1c9..3fe1a9dcc 100644--- a/codecov.yml+++ b/codecov.yml@@ -2,25 +2,29 @@ coverage:status:project:shared:- target: 50%+ informational: true+ target: autopaths:- src/shared/**email-worker:- target: 70%+ informational: true+ target: autopaths:- src/email-worker/**ws-do:- target: 70%+ informational: true+ target: autopaths:- src/ws-do/**web:- target: 30%+ informational: true+ target: autopaths:- src/web/**patch:default:- target: 100%- threshold: 0%+ informational: true+ target: autoignore:- "src/web/src/components/home/**"diff --git a/package.json b/package.jsonindex d1d50813c..d7d6168fc 100644--- a/package.json+++ b/package.json@@ -3,16 +3,16 @@"private": true,"packageManager": "[email protected]","scripts": {- "build": "turbo run build",- "test": "pnpm --filter @alook/agent-driver build && turbo run test --filter=!@alook/agent-driver && pnpm --filter @alook/agent-driver test && vitest run --project ci-scripts",- "predev": "[ -f src/web/.dev.vars ] || (cp src/web/.dev.vars.example src/web/.dev.vars && sed -i '' \"s|^BETTER_AUTH_SECRET=$|BETTER_AUTH_SECRET=$(openssl rand -base64 32)|\" src/web/.dev.vars && sed -i '' \"s|^ENCRYPTION_KEY=$|ENCRYPTION_KEY=$(openssl rand -base64 32)|\" src/web/.dev.vars && echo '✓ Generated src/web/.dev.vars (fill in OAuth keys if needed)'); [ -f src/email-worker/.dev.vars ] || cp src/email-worker/.dev.vars.example src/email-worker/.dev.vars; ALOOK_ENCRYPTION_KEY=$(grep '^ENCRYPTION_KEY=' src/web/.dev.vars | cut -d= -f2-); sed -i '' \"s|^ENCRYPTION_KEY=.*$|ENCRYPTION_KEY=$ALOOK_ENCRYPTION_KEY|\" src/email-worker/.dev.vars; [ -f src/queue-worker/.dev.vars ] || cp src/queue-worker/.dev.vars.example src/queue-worker/.dev.vars; sed -i '' \"s|^ENCRYPTION_KEY=.*$|ENCRYPTION_KEY=$ALOOK_ENCRYPTION_KEY|\" src/queue-worker/.dev.vars; echo '✓ Synced ENCRYPTION_KEY to email-worker and queue-worker'",- "dev": "turbo run dev --filter=@alook/web --filter=@alook/email-worker --filter=@alook/ws-do --filter=@alook/queue-worker --filter=@alook/shared",+ "build": "node scripts/ci/run-turbo.mjs run build",+ "test": "node scripts/ci/run-turbo.mjs run test test:contracts test:tooling test:runtime test:blog test:auth test:auth:runtime --filter=!@alook/agent-driver && node scripts/ci/run-turbo.mjs run @alook/agent-driver#test && vitest run --project ci-scripts",+ "predev": "[ -f src/web/.dev.vars ] || (cp src/web/.dev.vars.example src/web/.dev.vars && sed -i '' \"s|^BETTER_AUTH_SECRET=$|BETTER_AUTH_SECRET=$(openssl rand -base64 32)|\" src/web/.dev.vars && sed -i '' \"s|^ENCRYPTION_KEY=$|ENCRYPTION_KEY=$(openssl rand -base64 32)|\" src/web/.dev.vars && echo '\u2713 Generated src/web/.dev.vars (fill in OAuth keys if needed)'); [ -f src/email-worker/.dev.vars ] || cp src/email-worker/.dev.vars.example src/email-worker/.dev.vars; ALOOK_ENCRYPTION_KEY=$(grep '^ENCRYPTION_KEY=' src/web/.dev.vars | cut -d= -f2-); sed -i '' \"s|^ENCRYPTION_KEY=.*$|ENCRYPTION_KEY=$ALOOK_ENCRYPTION_KEY|\" src/email-worker/.dev.vars; [ -f src/queue-worker/.dev.vars ] || cp src/queue-worker/.dev.vars.example src/queue-worker/.dev.vars; sed -i '' \"s|^ENCRYPTION_KEY=.*$|ENCRYPTION_KEY=$ALOOK_ENCRYPTION_KEY|\" src/queue-worker/.dev.vars; echo '\u2713 Synced ENCRYPTION_KEY to email-worker and queue-worker'",+ "dev": "node scripts/ci/run-turbo.mjs run dev --filter=@alook/web --filter=@alook/email-worker --filter=@alook/ws-do --filter=@alook/queue-worker --filter=@alook/shared","clean": "rm -rf node_modules src/*/node_modules src/*/dist src/*/.turbo src/daemon/agent-driver/node_modules src/daemon/agent-driver/dist src/daemon/agent-driver/.turbo .turbo src/web/.next src/web/.open-next src/web/blog/.next src/web/blog/.open-next src/*/.wrangler .alook","clean:builds": "rm -rf src/*/dist src/daemon/agent-driver/dist src/web/.next src/web/.open-next src/web/blog/.next src/web/blog/.open-next .turbo src/*/.turbo src/daemon/agent-driver/.turbo","reinstall": "pnpm run clean && pnpm install",- "typecheck": "turbo run typecheck",- "lint": "turbo run lint",- "knip": "turbo run knip",+ "typecheck": "node scripts/ci/run-turbo.mjs run typecheck typecheck:blog typecheck:auth",+ "lint": "node scripts/ci/run-turbo.mjs run lint lint:blog lint:auth",+ "knip": "node scripts/ci/run-turbo.mjs run knip","dev:web": "pnpm --filter @alook/web dev","daemon": "pnpm --filter @alook/daemon exec tsx src/cli/index.ts daemon","daemon-use": "pnpm --filter @alook/daemon exec tsx src/cli/index.ts use",@@ -46,26 +46,24 @@"readme:capture": "node src/web/readme-capture/capture.mjs","app-store:capture": "node src/web/app-store-capture/capture.mjs","app-store:creative": "node src/web/app-store-capture/creative/capture.mjs",- "prepare": "simple-git-hooks"+ "prepare": "simple-git-hooks",+ "check": "node scripts/ci/check-local.mjs",+ "check:full": "node scripts/ci/check-local.mjs --full"},"simple-git-hooks": {- "pre-commit": "pnpm typecheck && pnpm lint && pnpm test && pnpm typegrep:ws && pnpm typegrep:agent-driver && pnpm knip"+ "pre-commit": "pnpm check"},"devDependencies": {- "@vitest/coverage-istanbul": "4.1.12",+ "@vitest/coverage-istanbul": "5.1.0","badge-maker": "6.0.0","sharp": "^0.35.5","simple-git-hooks": "^2.14.0","turbo": "^2.11.10","typescript": "^6.0.3",- "vitest": "4.1.12",+ "vitest": "5.1.0","wrangler": "4.152.0"},"pnpm": {- "overrides": {- "@vitest/runner": "4.1.11",- "@vitest/snapshot": "4.1.11"- },"patchedDependencies": {"@opennextjs/[email protected]": "patches/@[email protected]","@base-ui/[email protected]": "patches/@[email protected]"diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 9cbe4c04c..32d07667d 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -4,10 +4,6 @@ settings:autoInstallPeers: trueexcludeLinksFromLockfile: false-overrides:- '@vitest/runner': 4.1.11- '@vitest/snapshot': 4.1.11-patchedDependencies:'@base-ui/[email protected]':hash: 51d33f6e4f128a90fe02d40ba5c0f2cd5614eabbab780845f28186dc473cab0a@@ -21,8 +17,8 @@ importers:.:devDependencies:'@vitest/coverage-istanbul':- specifier: 4.1.12- version: 4.1.12([email protected])+ specifier: 5.1.0+ version: 5.1.0([email protected])badge-maker:specifier: 6.0.0version: 6.0.0@@ -39,8 +35,8 @@ importers:specifier: ^6.0.3version: 6.0.3vitest:- specifier: 4.1.12- version: 4.1.12(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ specifier: 5.1.0+ version: 5.1.0(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))wrangler:specifier: 4.152.0version: 4.152.0(@cloudflare/[email protected])(@types/[email protected])@@ -79,8 +75,8 @@ importers:specifier: ^8.72.0vitest:- specifier: 4.1.12- version: 4.1.12(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ specifier: 5.1.0+ version: 5.1.0(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))src/daemon:dependencies:@@ -125,8 +121,8 @@ importers:specifier: ^8.72.0vitest:- specifier: 4.1.12- version: 4.1.12(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ specifier: 5.1.0+ version: 5.1.0(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))zod:specifier: ^4.6.7version: 4.6.7@@ -137,8 +133,8 @@ importers:specifier: ^20.0.0version: 20.19.43'@vitest/coverage-v8':- specifier: 4.1.12- version: 4.1.12([email protected])+ specifier: 5.1.0+ version: 5.1.0([email protected])eslint:specifier: ^9.39.5version: 9.39.5([email protected])@@ -152,8 +148,8 @@ importers:specifier: ^8.72.0vitest:- specifier: 4.1.12- version: 4.1.12(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ specifier: 5.1.0+ version: 5.1.0(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))src/desktop:devDependencies:@@ -178,7 +174,7 @@ importers:devDependencies:'@cloudflare/vitest-plugin':specifier: 1.4.7'@cloudflare/workers-types':specifier: ^5.20261023.1version: 5.20261023.1@@ -192,8 +188,8 @@ importers:specifier: ^6.0.3version: 6.0.3vitest:- specifier: 4.1.12- version: 4.1.12(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ specifier: 5.1.0+ version: 5.1.0(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))wrangler:specifier: 4.152.0version: 4.152.0(@cloudflare/[email protected])(@types/[email protected])@@ -206,7 +202,7 @@ importers:devDependencies:'@cloudflare/vitest-plugin':specifier: 1.4.7'@cloudflare/workers-types':specifier: ^5.20261023.1version: 5.20261023.1@@ -220,8 +216,8 @@ importers:specifier: ^6.0.3version: 6.0.3vitest:- specifier: 4.1.12- version: 4.1.12(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ specifier: 5.1.0+ version: 5.1.0(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))wrangler:specifier: 4.152.0version: 4.152.0(@cloudflare/[email protected])(@types/[email protected])@@ -260,8 +256,8 @@ importers:specifier: ^6.0.3version: 6.0.3vitest:- specifier: 4.1.12- version: 4.1.12(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ specifier: 5.1.0+ version: 5.1.0(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))src/web:dependencies:@@ -393,7 +389,7 @@ importers:version: 0.7.0better-auth:specifier: 1.7.12- version: 1.7.12(@opentelemetry/[email protected])([email protected](@cloudflare/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected])+ version: 1.7.12(@opentelemetry/[email protected])([email protected](@cloudflare/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected])class-variance-authority:specifier: ^0.7.1version: 0.7.1@@ -559,10 +555,13 @@ importers:version: link:../../tests/utils'@cloudflare/vitest-plugin':specifier: 1.4.7'@lhci/cli':specifier: ^0.15.1version: 0.15.1+ '@mdx-js/rollup':+ specifier: 3.1.1+ version: 3.1.1([email protected])'@playwright/test':specifier: ^1.64.1version: 1.64.1@@ -580,7 +579,7 @@ importers:version: 5.104.5(@tanstack/[email protected](@types/[email protected])([email protected]))(@types/[email protected])([email protected])([email protected])'@testing-library/jest-dom':specifier: 7.0.1- version: 7.0.1(@testing-library/[email protected])([email protected])+ version: 7.0.1(@testing-library/[email protected])([email protected])'@testing-library/react':specifier: 16.3.3version: 16.3.3(@testing-library/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])@@ -631,7 +630,7 @@ importers:version: 16.0.1react-scan:specifier: 0.5.7- version: 0.5.7(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 0.5.7(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))serwist:specifier: 9.5.13version: 9.5.13([email protected])([email protected])@@ -651,8 +650,8 @@ importers:specifier: 8.72.0vitest:- specifier: 4.1.12- version: 4.1.12(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ specifier: 5.1.0+ version: 5.1.0(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))wrangler:specifier: 4.152.0version: 4.152.0(@cloudflare/[email protected])(@types/[email protected])@@ -665,7 +664,7 @@ importers:devDependencies:'@cloudflare/vitest-plugin':specifier: 1.4.7'@cloudflare/workers-types':specifier: ^5.20261023.1version: 5.20261023.1@@ -679,8 +678,8 @@ importers:specifier: ^6.0.3version: 6.0.3vitest:- specifier: 4.1.12- version: 4.1.12(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ specifier: 5.1.0+ version: 5.1.0(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))wrangler:specifier: 4.152.0version: 4.152.0(@cloudflare/[email protected])(@types/[email protected])@@ -704,8 +703,8 @@ importers:specifier: ^6.0.3version: 6.0.3vitest:- specifier: 4.1.12- version: 4.1.12(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ specifier: 5.1.0+ version: 5.1.0(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages:@@ -1967,6 +1966,11 @@ packages:'@types/react': '>=16'react: '>=16'+ '@mdx-js/[email protected]':+ resolution: {integrity: sha512-v8satFmBB+DqDzYohnm1u2JOvxx6Hl3pUvqzJvfs2Zk/ngZ1aRUhsWpXvwPkNeGN9c2NCm/38H29ZqXQUjf8dw==}+ peerDependencies:+ rollup: '>=2'+'@mermaid-js/[email protected]':resolution: {integrity: sha512-n12NohV3mrUyUL2o93IgG/ifeW9FTyeJn3zDxkhwa8MJ9Fxg3HQMlA3RiGmD/3UnJvheztkjjQAjA2T4LmUcpw==}@@ -2059,6 +2063,13 @@ packages:resolution: {integrity: sha512-V+qptzsGnPMFxEbhwc6eDNMe5eDrfiBIp8qGpuRjAVIX4Kn2zxvwQ1Xco6Fwe+3tYIe3iLW8LM9D+SvjyJhqbQ==}engines: {node: '>= 10'}+ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==}+ engines: {node: ^22.20 || ^24.12 || >=25}+ cpu: [x64]+ os: [linux]+ libc: [glibc]+'@napi-rs/[email protected]':resolution: {integrity: sha512-UMduMbqO5s5zF2NkNacMT/yK5Y5QiKvWr2+50bzIIxFDwVJ2h49b+oyjaCGPhJxd2/gC2x39EHv/gHVuu36x2Q==}engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0}@@ -2587,6 +2598,9 @@ packages:'@oxc-project/[email protected]':resolution: {integrity: sha512-Nm4s/jB+4FpFsPhWGEC4h7rzksesmtnMXomo6rCMcg/b8zLQuOziRgkCS1fxDCXOlJB/6Q8oABOZ/OP6RIPj9A==}+ '@oxc-project/[email protected]':+ resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==}+'@oxc-resolver/[email protected]':resolution: {integrity: sha512-y09e0L0SRI2OA2tUIrjBgoV3eH5hvUKXNkJqXmNo5V2WxIjyC7I7aJfRLMEVpA8yi95f90gFDvO0VMgrDw+vwA==}cpu: [arm]@@ -2863,36 +2877,72 @@ packages:resolution: {integrity: sha512-LVfA+j5cFT0Szd958WRD8W/B8ucCtz4ViiveDKWLqAwBkZFW9VRW1ZvwOUhp/M3SmVPtjDaRkW12GvAuTArP+Q==}hasBin: true+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-ia3DwAs0OsMGS7+IConptSiyk9pEXkOx/AbJ2n/lAGxH3QkWQus1t8d7gnAT38FCU2sQu8lUbeR6AiZFv4JxaA==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm]+ os: [android]+'@rolldown/[email protected]':resolution: {integrity: sha512-YYe6aWruPZDtHNpwu7+qAHEMbQ/yRl6atqb/AhznLTnD3UY99Q1jE7ihLSahNWkF4EqRPVC4SiR4O0UkLK02tA==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [arm64]os: [android]+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm64]+ os: [android]+'@rolldown/[email protected]':resolution: {integrity: sha512-oArR/ig8wNTPYsXL+Mzhs0oxhxfuHRfG7Ikw7jXsw8mYOtk71W0OkF2VEVh699pdmzjPQsTjlD1JIOoHkLP1Fg==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [arm64]os: [darwin]+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm64]+ os: [darwin]+'@rolldown/[email protected]':resolution: {integrity: sha512-YzeVqOqjPYvUbJSWJ4EDL8ahbmsIXQpgL3JVipmN+MX0XnXMeWomLN3Fb+nwCmP/jfyqte5I3XRSm7OfQrbyxw==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [x64]os: [darwin]+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [x64]+ os: [darwin]+'@rolldown/[email protected]':resolution: {integrity: sha512-9Erhx956jeQ0nNTyif1+QWAXDRD38ZNjr//bSHrt6wDwB+QkAfl2q6Mn1k6OBPerznjRmbM10lgRb1Pli4xZPw==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [x64]os: [freebsd]+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [x64]+ os: [freebsd]+'@rolldown/[email protected]':resolution: {integrity: sha512-cVwk0w8QbZJGTnP/AHQBs5yNwmpgGYStL88t4UIaqcvYJWBfS0s3oqVLZPwsPU6M0zlW4GqjP0Zq5MnAGwFeGA==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [arm]os: [linux]+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm]+ os: [linux]+'@rolldown/[email protected]':resolution: {integrity: sha512-eBZ/u8iAK9SoHGanqe/jrPnY0JvBN6iXbVOsbO38mbz+ZJsaobExAm1Iu+rxa4S1l2FjG0qEZn4Rc6X8n+9M+w==}engines: {node: ^20.19.0 || >=22.12.0}@@ -2900,6 +2950,13 @@ packages:os: [linux]libc: [glibc]+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm64]+ os: [linux]+ libc: [glibc]+'@rolldown/[email protected]':resolution: {integrity: sha512-ZvRYMGrAklV9PEkgt4LQM6MjQX2P58HPAuecwYObY2DhS2t35R0I810bKi0wmaYORt6m/2Sm+Z+nFgb0WhXNcQ==}engines: {node: ^20.19.0 || >=22.12.0}@@ -2907,6 +2964,13 @@ packages:os: [linux]libc: [musl]+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm64]+ os: [linux]+ libc: [musl]+'@rolldown/[email protected]':resolution: {integrity: sha512-VDpgGBzgfg5hLg+uBpCLoFG5kVvEyafmfxGUV0UHLcL5irxAK7PKNeC2MwClgk6ZAiNhmo9FLhRYgvMmedLtnQ==}engines: {node: ^20.19.0 || >=22.12.0}@@ -2914,6 +2978,13 @@ packages:os: [linux]libc: [glibc]+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [ppc64]+ os: [linux]+ libc: [glibc]+'@rolldown/[email protected]':resolution: {integrity: sha512-y1uXY3qQWCzcPgRJATPSOUP4tCemh4uBdY7e3EZbVwCJTY3gLJWnQABgeUetvED+bt1FQ01OeZwvhLS2bpNrAQ==}engines: {node: ^20.19.0 || >=22.12.0}@@ -2921,6 +2992,13 @@ packages:os: [linux]libc: [glibc]+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [s390x]+ os: [linux]+ libc: [glibc]+'@rolldown/[email protected]':resolution: {integrity: sha512-023bTPBod7J3Y/4fzAN6QtpkSABR0rigtrwaP+qSEabUh5zf6ELr9Nc7GujaROuPY3uwdSIXWrvhn1KxOvurWA==}engines: {node: ^20.19.0 || >=22.12.0}@@ -2928,6 +3006,13 @@ packages:os: [linux]libc: [glibc]+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [x64]+ os: [linux]+ libc: [glibc]+'@rolldown/[email protected]':resolution: {integrity: sha512-witB2O0/hU4CgfOOKUoeFgQ4GktPi1eEbAhaLAIpgD6+ZnhcPkUtPsoKKHRzmOoWPZue46IThdSgdo4XneOLYw==}engines: {node: ^20.19.0 || >=22.12.0}@@ -2935,12 +3020,25 @@ packages:os: [linux]libc: [musl]+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [x64]+ os: [linux]+ libc: [musl]+'@rolldown/[email protected]':resolution: {integrity: sha512-UCL68NJ0Ud5zRipXZE9dF5PmirzJE4E4BCIOOssEnM7wLDsxjc6Qb0sGDxTNRTP53I6MZpygyCpY8Aa8sPfKPg==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [arm64]os: [openharmony]+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm64]+ os: [openharmony]+'@rolldown/[email protected]':resolution: {integrity: sha512-ApLruZq/ig+nhaE7OJm4lDjayUnOHVUa77zGeqnqZ9pn0ovdVbbNPerVibLXDmWeUZXjIYIT8V3xkT58Rm9u5Q==}engines: {node: '>=14.0.0'}@@ -2952,15 +3050,30 @@ packages:cpu: [arm64]os: [win32]+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm64]+ os: [win32]+'@rolldown/[email protected]':resolution: {integrity: sha512-3P2A8L+x75qavWLe/Dll3EYBJLQmtkJN8rfh+U/eR3MqMgL/h98PhYI+JFfXuDPgPeCB7iZAKiqii5vqOvnA0g==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [x64]os: [win32]+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [x64]+ os: [win32]+'@rolldown/[email protected]':resolution: {integrity: sha512-UromN0peaE53IaBRe9W7CjrZgXl90fqGpK+mIZbA3qSTeYqg3pqpROBdIPvOG3F5ereDHNwoHBI2e50n1BDr1g==}+ '@rolldown/[email protected]':+ resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==}+'@rollup/[email protected]':resolution: {integrity: sha512-MfPp06CjRLfXQ3wY0R8vJDYBy/MvVcc9OulEfR0B8Iv9ko+GCNaRZ+EpJYFl27LhKsZK0o420sYCRHCjfCgeUg==}engines: {node: '>=14.0.0'}@@ -2970,6 +3083,149 @@ packages:rollup:optional: true+ '@rollup/[email protected]':+ resolution: {integrity: sha512-/v/pUAPOcwp+r1Hjjdg0cBV1TE89CzGKrKh2FgkIQw2QBcIMmVPOCSfuOZStCn4Xh/98HXfo/ht6ztcssctPNg==}+ cpu: [arm]+ os: [android]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-6tmmB/P52Vt167FXXEw5auiEUgTtZz7aqUgWHqYXToIUE0HFDY6fTdAyeekjjsNk6O/8dtpSKtClxSj1mMneKQ==}+ cpu: [arm64]+ os: [android]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-8Z9Q4RmotVmuL4llOvqX814JNiOK1oqoBv+glG5KbpRfUiypqzz2/fxIzK4Pq129l4dT5a8Gszmpc0/XPYoFuQ==}+ cpu: [x64]+ os: [android]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-pnq6hssxTtwuRAl6Kdi/+IDY+b1IhkUetjhUkdLAAJCssjfqtL2Oqy/FXJVJFtAWOu1oRlArIvf0Yk1O92x2HQ==}+ cpu: [arm64]+ os: [darwin]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-BeIrGZvHMVdJg/N+ohZfFywG/gF41684YhDj2wBvouj7m9ziP1tZDUNwzXRiDY+3WIKngaC4hiUBqVtBPGP5og==}+ cpu: [x64]+ os: [darwin]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-fRFX/oqNg/g780DKoS8RIfYcZD59Ru5O/bSeK1N7gQljBFrTxJY/q5EX4eMs5SrJf32VgVBVVYCdfPpzAwPPnQ==}+ cpu: [arm64]+ os: [freebsd]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-bSrBRopG1q+0RuOsW0NtYTtIODlvNA3T3ebx5WnQVdSxWIoXFmj+rZdHUHdSLgFdZ5M6VGmekYE7r4RMGQXjfg==}+ cpu: [x64]+ os: [freebsd]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-L8IvdrJVtl65g1ozwDSyjGPG+FmibhCdFUwmqTItJLw0S3+Oj4QzFs7rfgTUiK7rsPjkCLdG1/GApFxoynXFJQ==}+ cpu: [arm]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-h7PcoQOzC31jshNpQ48J0akB9tsghjkSjSl5AZ6XsVGTxVsln7t7C4SQyw62tNVSaz2SeHgk4VT2ELbL17BSHQ==}+ cpu: [arm]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-KSPuOBNHoOl7AsVjeY1KZci8+0up0U4TFAHU5IzBYN8P+Z6cB9DZq28+JQycZW7f6WLLa/tSzhV7Rdy95bVi+g==}+ cpu: [arm64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-0E/mKmVk1PlQeQYygIwQm0jlwjANTzGSiNBMPrFx+rdFGFj/2Axh4p6XwcrystQIqXZVudTaGsdbDpzYgJ4wSA==}+ cpu: [arm64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-Fvw7dOSc2Sa9UOipRZVI0zOgdLCzsjVyD/6JuHXzUHTXFu7mMgmeX/0/bCVBIut1dz+nWz3pV4WpS/Qg0XVnxw==}+ cpu: [loong64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-jzxbVHaE7V3F+P0wEK7UydQtvv7Twfdtx58jI5/3VRx1jJxyrn+qFwfXmqjVFxPhBl+zjaRs+ZJMFJw7vdHaQA==}+ cpu: [loong64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-fhtrzp9p4GjEJVaigaap9g6X9nP6xgJtKiLLXSDgpE18HXufA5aqfltGn+KAqMtVZReJZfOrXm//y5YSA9BWbA==}+ cpu: [ppc64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-uynaF7IUHwAckV0S+yC1f5esy9gB+aqCBsPH5BOck32TYdCuAn2lVG5tvUcFnEsrviGEmRZxE1NHSOieUPYJEg==}+ cpu: [ppc64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-uaqRFdfb8eIa2bVHN/FE3ndCvR0zV2xv0AwjCfxrqSu6l6fp/54VhjfhslKlf2RIik9L1jwlt4E56PeVX6tQtQ==}+ cpu: [riscv64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-JZRow7kmxUDEASnxHuVG5itTm+nTXi9BQUABcVUnUEngC+OPwMrpx1uJ9hIA/v+IcAEBL52ktCSPXk5OJn9Jqg==}+ cpu: [riscv64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-rdrh4e+Lq9fCNKoDPaCqeHXbQCe7yl77Ukl45tlSClwYdZ1gpFGZz1XLJdYtY++FRlfL5aHvb6/0n3GDW/Nxsw==}+ cpu: [s390x]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-wL7MS4r0fYcxluF3ne2plofHZiB/LsqNCnyaUlyiKpAJLb6agPSFz7DEFCfkonWAZXMrLwCmC08b2ZEnEdJkog==}+ cpu: [x64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-4H0XHfd2VufGjX7NjUyeue78sD0bRIoKSGjGqO+F5nSvL6jN48NAU7esdmtFEYxZXwObLtt3MJ/kHS0jASMW3g==}+ cpu: [x64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-osRHQbE55pZpCLetpMsFmhkapyZnAUH73qRKMh+npi3boUom6u6hdaTTPSxlInXxwJHsn9r2uDhdz0V7Yoxx2A==}+ cpu: [x64]+ os: [openbsd]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-95+exYEyOwrZePsE0czi4q7X5lxKPa21+lmyAZlwbYENITQ0Unk4HAQAFp/p+KhXBHBx9mUABXRYjOC5A1wY3Q==}+ cpu: [arm64]+ os: [openharmony]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-FOXOcKhNQpO4Po+Ynan6IbtM67SrXZbgpRJWVYwz53CT5veI7sVzDwVBmWS65N5Imv+wK3SVhIPAl+C5DXXNCg==}+ cpu: [arm64]+ os: [win32]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-cklKh0gJOkAZQcWziQa3hrjxZKN+PCHZ7SPTyGJDAiBVr05ZXlEjGFCG7zFJMaVibxsmzAe1FimN4u/HBns9+Q==}+ cpu: [ia32]+ os: [win32]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-AegwxJPc9bvUp8fQtlsUHkFMOMkGylWU7glyL+YD4vwG+QaYoGXYLSsQoeTD7kvoLZrVlMWNVhTg1dedY5C1VQ==}+ cpu: [x64]+ os: [win32]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-RJZnrwTWj7Iq2ooBwoGbDdC65tDwYawneGcAfFMJqVUrRZMcskka6nTkBpXR/47G7kzn3EW2qupExnaBy11vwg==}+ cpu: [x64]+ os: [win32]+'@rtsao/[email protected]':resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==}@@ -4099,6 +4355,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==}+ '@types/[email protected]':+ resolution: {integrity: sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==}+'@types/[email protected]':resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==}@@ -4369,27 +4628,40 @@ packages:'@upsetjs/[email protected]':resolution: {integrity: sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==}- '@vitest/[email protected]':- resolution: {integrity: sha512-f98TiCqF7IriBQEpm6usi56wyD4G1cRYabI15f3Jm7R355q9tlwqJ0j1oPf+tWZ7D0LPnCh3dU70duRt10erHg==}+ '@vitest/[email protected]':+ resolution: {integrity: sha512-XRAUYsfdho+Az4K2eEWOVPedtIzUZbCl2eO9pOjNH5L1/niuy8cYwlK2W9RUtfwYZumoqic+4pRGqAvch/JSzg==}peerDependencies:- vitest: 4.1.12+ vitest: 5.1.0- '@vitest/[email protected]':- resolution: {integrity: sha512-6S7/iVknKglLAxMFxQGNppBI0iqJS2NgM6FBxavitj7KaDq/vywOWGf6dGu7F2L1Qy0G6S3uTp7aGshHrzK8JA==}+ '@vitest/[email protected]':+ resolution: {integrity: sha512-OY9aShBQG5KOIw2zCo9fDoCHI9RHliNHJ//nM7m6jGg41Hyke9JOGWmeMlK74xYErsxMoK8mIB3gAeEyFVA7LA==}peerDependencies:- '@vitest/browser': 4.1.12- vitest: 4.1.12+ '@vitest/browser': 5.1.0+ vitest: 5.1.0peerDependenciesMeta:'@vitest/browser':optional: true- '@vitest/[email protected]':- resolution: {integrity: sha512-vFlTt+YEu9WBpNjdGayNmlMVzrWPi1+sv853/7t2FU7hpO5gAFBKHzQmkCq5Xjpr+evegF2994LQT3hF3mRlqQ==}+ '@vitest/[email protected]':+ resolution: {integrity: sha512-WOjuS+xcjSIy7ruYBQ+9BUcV7XZQ0FyVcbWbWxW9TRx/kLGx5SQaeFRIFDJxjNplb6YsT7SpKo2zuXXUo91OIQ==}+ engines: {node: '>=22'}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-lMhFnfKPkueJQealWtkRWv0E95gO14OQg/ZzVT4tqDRXLxn6teAZKBe1uXg9jNB2AI5WPk4vF52R+59LAUgQUA==}+ engines: {node: '>=22'}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-+ZFta25nWtGCOBG9/IET8w1RO5Oawsd6H8Uf6AJ9EA/StFuKVtKAEJEJ6uRt84OH+T4YkI0ASmIHAhRA+0KVxw==}+ engines: {node: '>=22'}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-X+fmmI1SEiJZc/nmMUllliP8qaLgi4xMcDd0HwTBMdaanbRcCu/+IKo+iq7wbjJXtAEBWQrGyI18wfSWIqyDpw==}+ engines: {node: '>=22'}- '@vitest/[email protected]':- resolution: {integrity: sha512-fKShNpKZzupWZuY0z7egydvL0sqW4INEZBEExMBMAa6izlENEVHwoXgdaTCaBZ5fwlr4xf2o1wXC83n9RpO+NA==}+ '@vitest/[email protected]':+ resolution: {integrity: sha512-5umB9/jlWcqVS6fsrFmv5Gdnpu6wAUio/lEOwAmvB7v+lFo/IW2B9FhAD0p19GCULTgMzLCdUmuCDCnAzWgppQ==}peerDependencies:- msw: ^2.4.9+ msw: ^2.4.9 || ^3.0.0vite: ^6.0.0 || ^7.0.0 || ^8.0.0peerDependenciesMeta:msw:@@ -4397,26 +4669,8 @@ packages:vite:optional: true- '@vitest/[email protected]':- resolution: {integrity: sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==}-- '@vitest/[email protected]':- resolution: {integrity: sha512-XW9O8+Mxx4VpCtkYdMJLZQQwsVryP9wk7cPKDxtXFfwSak6yRh5+2fep/Y0XF/ElBvJHq8bcYdi6aeuai0opZA==}-- '@vitest/[email protected]':- resolution: {integrity: sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==}-- '@vitest/[email protected]':- resolution: {integrity: sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==}-- '@vitest/[email protected]':- resolution: {integrity: sha512-RGq9x4JNGNTZHEJxvN0oSiJjeSCExm0n2gZKKJZHY9cX5AVA6M7VJILBT3ZJ/tJ/0J9uWT7fETV9/btoi//vSg==}-- '@vitest/[email protected]':- resolution: {integrity: sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==}-- '@vitest/[email protected]':- resolution: {integrity: sha512-Q3awXrwOfEV+qc3WmO5ONyE0yO7Q1gQ9/oyHxGLZ/pl7N3NO/ZztqQwKLuwMkV+CA1JYSIeO3gkHnRDIo4AVaA==}+ '@vitest/[email protected]':+ resolution: {integrity: sha512-2DPO5OMHWKrBngC+fCmTQqemNF0gidRhp3lxbBmRhW+M1XJrfgPpqNqWVevXtn2f2ufD5ZaR1B6B641aAlcX5A==}resolution: {integrity: sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==}@@ -6401,9 +6655,6 @@ packages:resolution: {integrity: sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==}engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}- resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==}-resolution: {integrity: sha512-cuOPoI7WApyhBElTTb9oqsawRvZ0rHhaHwghRLlTuffoD1B2aDemlCruLeZrUIIdvG7gs9xeELEPm6PhuASqrg==}@@ -6761,18 +7012,6 @@ packages:resolution: {integrity: sha512-qvUtwJ3j6qwsF3jLxkZ72qCgjMysPzDfeV240JHiGZsANBYd+EEuu35v7dfrJ9Up0Ak07D7GGSkGhCHTqg/5wA==}- resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==}- engines: {node: '>=8'}-- resolution: {integrity: sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==}- engines: {node: '>=10'}-- resolution: {integrity: sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==}- engines: {node: '>=8'}-resolution: {integrity: sha512-H0dkQoCa3b2VEeKQBOxFph+JAbcrQdE7KC0UkqwpLmv2EC4P41QXP+rqo9wYodACiG5/WM5s9oDApTU8utwj9g==}engines: {node: '>= 0.4'}@@ -6915,8 +7154,8 @@ packages:resolution: {integrity: sha512-dp3s92+uNI1hWIpPGH3jK2kxE2lMjdXdr+DH8ynZHpd6PUlH6x6cbuXnoMmiNumznqaNO31xu9e79F0uuZ0JFg==}- resolution: {integrity: sha512-1r6MT4dVaJyXt4G07Cm2cQ0AUaLJdefiEp4SmIAylA++gnEQ82YvmzE58RkM5EP0fk5hROLCslUPGnwIYdZQVA==}+ resolution: {integrity: sha512-UTmeKBVxnfJcpmpOvzzNnLsQT99BXHpPlc/ZKddIRmWmrR0fw6335I3lq4+sJoP60UTbBNaYsGYVPc65YB1x3A==}resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==}@@ -7168,6 +7407,9 @@ packages:resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}+ resolution: {integrity: sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==}+resolution: {integrity: sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==}@@ -7175,10 +7417,6 @@ packages:resolution: {integrity: sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==}engines: {node: '>=8'}- resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==}- engines: {node: '>=10'}-resolution: {integrity: sha512-o5vL7aDWatOTX8LzaS1WMoaoxIiLRQJuIKKe2wAw6IeULDHaqbiqiggmx+pKvZDb1Sj+pE46Sn1T7lCqfFtg1Q==}engines: {node: '>=16'}@@ -7733,8 +7971,8 @@ packages:resolution: {integrity: sha512-9WXswnqINnnhOG/5SLimUlzuU1hFJUc8zkwyD59Sd+dPOMf05PmnYG/d6Q7HZ+KmgkZJa1PxRso6QdM3sTNHig==}- resolution: {integrity: sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==}+ resolution: {integrity: sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==}engines: {node: '>=12.20.0'}@@ -7819,8 +8057,8 @@ packages:resolution: {integrity: sha512-FY91FiDBj7ls5MsFS9jN3tjz2o0/zsdSsymlakySaBwVJZorHhkWyICLZMKxlu1R9vYo+sd3z1jwb4J8x7bNDw==}- resolution: {integrity: sha512-1mfeb/jzXnduWOZJxrvdJjvKT0pFNKrNFYcPO4ncpFAnfW41M0mLz/23lAFzHb0knNLYayEgIQ5DjI4ZfFe+DQ==}+ resolution: {integrity: sha512-kf9MwCpK3YlAWYUyX5Zx7XYrdIbA/4lQD2QREIqC8DvmNb2I+wP8zyjL4NeGl2FO2EC1sLuYvW8ir4Ooq1Xd2A==}engines: {node: ^20.19.0 || >=22.13.0}@@ -8212,8 +8450,8 @@ packages:'@types/react':optional: true- resolution: {integrity: sha512-4Ach00KtfnfjTBGgr2PyPgHua85vT/UfPY5sR0bHgRAc/QSu0JInA0GHCL6a7WFGMeGUrxtGnI8oqZinG44BOA==}+ resolution: {integrity: sha512-SyZOIl61VMCZ3sN7v7Vr2zCsPlyy7nNnBshtIrl0B/X+uY+rL9MGfyNhTmp/FLXfuDKEv61Y6xMguya7vn1Ulg==}engines: {node: ^20.19.0 || >=22.13.0}hasBin: true@@ -8466,6 +8704,16 @@ packages:engines: {node: ^20.19.0 || >=22.12.0}hasBin: true+ resolution: {integrity: sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==}+ engines: {node: ^20.19.0 || >=22.12.0}+ hasBin: true++ resolution: {integrity: sha512-Lsv3oKcz5jgOQJej/p7nfwbVEdAbDT+z6OPf/SCdI+nF+q2ENp0pTKT35ZwXAmH8g45mfrIiJeEyAqKYSYoL9Q==}+ engines: {node: '>=18.0.0', npm: '>=8.0.0'}+ hasBin: true+resolution: {integrity: sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ==}@@ -8636,9 +8884,6 @@ packages:resolution: {integrity: sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==}engines: {node: '>= 0.4'}- resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}-resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==}@@ -8740,9 +8985,6 @@ packages:resolution: {integrity: sha512-+L3ccpzibovGXFK+Ap/f8LOS0ahMrHTf3xu7mMLSpEGU0EO9ucaysSylKo9eRDFNhWve/y275iPmIZ4z39a9iA==}- resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}-resolution: {integrity: sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==}@@ -9012,8 +9254,9 @@ packages:resolution: {integrity: sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==}- resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}+ resolution: {integrity: sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==}+ engines: {node: '>=20.0.0'}resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==}@@ -9421,23 +9664,23 @@ packages:yaml:optional: true- resolution: {integrity: sha512-5eWdz2yb3ajxWF3C8C4TjkXl7FGm3n2E/VlazALrQHzK7nYMSGFnCZto0bbPNl77AwkOZVLk0YnBAejUu0NiWA==}- engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0}+ resolution: {integrity: sha512-MzmNFnrwa8v8lF1bLxw3UJ4EREwVOVb75VqJZmUDRjJ6EluK/x9th7qTbaeDk41WxE1GxWqmTXcdsfobfH5sOA==}+ engines: {node: ^22.12.0 || ^24.0.0 || >=26.0.0}hasBin: truepeerDependencies:'@edge-runtime/vm': '*''@opentelemetry/api': ^1.9.0- '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0- '@vitest/browser-playwright': 4.1.12- '@vitest/browser-preview': 4.1.12- '@vitest/browser-webdriverio': ^4.1.11- '@vitest/coverage-istanbul': 4.1.12- '@vitest/coverage-v8': 4.1.12- '@vitest/ui': 4.1.12+ '@types/node': ^22.0.0 || >=24.0.0+ '@vitest/browser-playwright': 5.1.0+ '@vitest/browser-preview': 5.1.0+ '@vitest/browser-webdriverio': ^5.0.0-beta.5 || >=5.0.0+ '@vitest/coverage-istanbul': 5.1.0+ '@vitest/coverage-v8': 5.1.0+ '@vitest/ui': 5.1.0happy-dom: '*'jsdom: '*'- vite: ^6.0.0 || ^7.0.0 || ^8.0.0+ vite: ^6.4.0 || ^7.0.0 || ^8.0.0peerDependenciesMeta:'@edge-runtime/vm':optional: true@@ -9542,9 +9785,9 @@ packages:engines: {node: ^16.13.0 || >=18.0.0}hasBin: true- resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}- engines: {node: '>=8'}+ resolution: {integrity: sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==}+ engines: {node: '>=20.11'}hasBin: true@@ -10641,12 +10884,12 @@ snapshots:optionalDependencies:workerd: 1.20261019.1- '@cloudflare/[email protected](@cloudflare/[email protected])(@types/[email protected])([email protected])':+ '@cloudflare/[email protected](@cloudflare/[email protected])(@types/[email protected])([email protected])':dependencies:cjs-module-lexer: 1.2.3esbuild: 0.28.2miniflare: 5.20261019.2-beta(@types/[email protected])- vitest: 4.1.12(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ vitest: 5.1.0(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))wrangler: 4.152.0(@cloudflare/[email protected])(@types/[email protected])zod: 4.6.5transitivePeerDependencies:@@ -11403,6 +11646,16 @@ snapshots:'@types/react': 19.3.0react: 19.3.1+ '@mdx-js/[email protected]([email protected])':+ dependencies:+ '@mdx-js/mdx': 3.1.1+ '@rollup/pluginutils': 5.4.0([email protected])+ rollup: 4.67.4+ source-map: 0.7.6+ vfile: 6.0.3+ transitivePeerDependencies:+ - supports-color+'@mermaid-js/[email protected]':dependencies:'@chevrotain/types': 11.1.2@@ -11487,6 +11740,9 @@ snapshots:'@napi-rs/canvas-win32-x64-msvc': 1.0.10optional: true+ '@napi-rs/[email protected]':+ optional: true+dependencies:'@emnapi/core': 1.11.2@@ -11902,6 +12158,8 @@ snapshots:'@oxc-project/[email protected]': {}+ '@oxc-project/[email protected]': {}+'@oxc-resolver/[email protected]':optional: true@@ -12022,7 +12280,7 @@ snapshots:'@paulirish/[email protected]':dependencies:- legacy-javascript: 0.0.3+ legacy-javascript: 0.0.4third-party-web: 0.30.0'@pkgjs/[email protected]':@@ -12085,42 +12343,81 @@ snapshots:prompts: 2.4.2tinyexec: 1.3.1+ '@rolldown/[email protected]':+ optional: true+'@rolldown/[email protected]':optional: true+ '@rolldown/[email protected]':+ optional: true+'@rolldown/[email protected]':optional: true+ '@rolldown/[email protected]':+ optional: true+'@rolldown/[email protected]':optional: true+ '@rolldown/[email protected]':+ optional: true+'@rolldown/[email protected]':optional: true+ '@rolldown/[email protected]':+ optional: true+'@rolldown/[email protected]':optional: true+ '@rolldown/[email protected]':+ optional: true+'@rolldown/[email protected]':optional: true+ '@rolldown/[email protected]':+ optional: true+'@rolldown/[email protected]':optional: true+ '@rolldown/[email protected]':+ optional: true+'@rolldown/[email protected]':optional: true+ '@rolldown/[email protected]':+ optional: true+'@rolldown/[email protected]':optional: true+ '@rolldown/[email protected]':+ optional: true+'@rolldown/[email protected]':optional: true+ '@rolldown/[email protected]':+ optional: true+'@rolldown/[email protected]':optional: true+ '@rolldown/[email protected]':+ optional: true+'@rolldown/[email protected]':optional: true+ '@rolldown/[email protected]':+ optional: true+'@rolldown/[email protected]':dependencies:'@emnapi/core': 1.9.2@@ -12131,16 +12428,104 @@ snapshots:'@rolldown/[email protected]':optional: true+ '@rolldown/[email protected]':+ optional: true+'@rolldown/[email protected]':optional: true+ '@rolldown/[email protected]':+ optional: true+'@rolldown/[email protected]': {}- '@rollup/[email protected]':+ '@rolldown/[email protected]': {}++ '@rollup/[email protected]([email protected])':dependencies:'@types/estree': 1.0.9estree-walker: 2.0.2picomatch: 4.0.7+ optionalDependencies:+ rollup: 4.67.4++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true'@rtsao/[email protected]': {}@@ -12945,7 +13330,7 @@ snapshots:picocolors: 1.1.1pretty-format: 27.5.1dependencies:'@adobe/css-tools': 4.5.0'@testing-library/dom': 10.4.1@@ -12955,7 +13340,7 @@ snapshots:picocolors: 1.1.1redent: 3.0.0optionalDependencies:- vitest: 4.1.12(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ vitest: 5.1.0(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))'@testing-library/[email protected](@testing-library/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':dependencies:@@ -13342,6 +13727,8 @@ snapshots:dependencies:'@types/estree': 1.0.9+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]': {}@@ -13593,105 +13980,81 @@ snapshots:d3-selection: 3.0.0d3-transition: 3.0.1([email protected])- '@vitest/[email protected]([email protected])':+ '@vitest/[email protected]([email protected])':dependencies:- '@babel/core': 7.29.7- '@istanbuljs/schema': 0.1.6- '@jridgewell/gen-mapping': 0.3.13- '@jridgewell/trace-mapping': 0.3.31- istanbul-lib-coverage: 3.2.2- istanbul-lib-report: 3.0.1- istanbul-reports: 3.2.0+ '@vitest/istanbul-lib-coverage': 2.1.0+ '@vitest/istanbul-lib-instrument': 2.1.0+ '@vitest/istanbul-lib-report': 2.1.0+ '@vitest/istanbul-lib-source-maps': 2.1.0magicast: 0.5.5- obug: 2.2.1+ obug: 3.0.0tinyrainbow: 3.2.0- vitest: 4.1.12(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))- transitivePeerDependencies:- - supports-color+ vitest: 5.1.0(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))- '@vitest/[email protected]([email protected])':+ '@vitest/[email protected]([email protected])':dependencies:'@bcoe/v8-coverage': 1.0.2- '@vitest/utils': 4.1.12+ '@vitest/istanbul-lib-coverage': 2.1.0+ '@vitest/istanbul-lib-report': 2.1.0ast-v8-to-istanbul: 1.0.7- istanbul-lib-coverage: 3.2.2- istanbul-lib-report: 3.0.1- istanbul-reports: 3.2.0magicast: 0.5.5- obug: 2.2.1+ obug: 3.0.0std-env: 4.3.0tinyrainbow: 3.2.0- vitest: 4.1.12(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ vitest: 5.1.0(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))++ '@vitest/[email protected]': {}- '@vitest/[email protected]':+ '@vitest/[email protected]':dependencies:- '@standard-schema/spec': 1.1.0- '@types/chai': 5.2.3- '@vitest/spy': 4.1.12- '@vitest/utils': 4.1.12- chai: 6.3.0- tinyrainbow: 3.2.0+ '@istanbuljs/schema': 0.1.6+ '@jridgewell/remapping': 2.3.5+ '@jridgewell/trace-mapping': 0.3.31+ '@vitest/istanbul-lib-coverage': 2.1.0+ magic-string: 1.4.5+ rolldown: 1.2.16++ '@vitest/[email protected]':+ dependencies:+ '@vitest/istanbul-lib-coverage': 2.1.0- '@vitest/[email protected]([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':+ '@vitest/[email protected]':dependencies:- '@vitest/spy': 4.1.12+ '@jridgewell/trace-mapping': 0.3.31+ '@vitest/istanbul-lib-coverage': 2.1.0+ obug: 3.0.0++ '@vitest/[email protected]([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':+ dependencies:+ '@jridgewell/trace-mapping': 0.3.31+ '@vitest/spy': 5.1.0estree-walker: 3.0.3- magic-string: 0.30.21+ magic-string: 1.4.5optionalDependencies:msw: 2.14.6(@types/[email protected])([email protected])vite: 8.0.8(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- '@vitest/[email protected]([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':+ '@vitest/[email protected]([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:- '@vitest/spy': 4.1.12+ '@jridgewell/trace-mapping': 0.3.31+ '@vitest/spy': 5.1.0estree-walker: 3.0.3- magic-string: 0.30.21+ magic-string: 1.4.5optionalDependencies:msw: 2.14.6(@types/[email protected])([email protected])vite: 8.0.8(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- '@vitest/[email protected]([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':+ '@vitest/[email protected]([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:- '@vitest/spy': 4.1.12+ '@jridgewell/trace-mapping': 0.3.31+ '@vitest/spy': 5.1.0estree-walker: 3.0.3- magic-string: 0.30.21+ magic-string: 1.4.5optionalDependencies:msw: 2.14.6(@types/[email protected])([email protected])vite: 8.0.8(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- '@vitest/[email protected]':- dependencies:- tinyrainbow: 3.2.0-- '@vitest/[email protected]':- dependencies:- tinyrainbow: 3.2.0-- '@vitest/[email protected]':- dependencies:- '@vitest/utils': 4.1.11- pathe: 2.0.3-- '@vitest/[email protected]':- dependencies:- '@vitest/pretty-format': 4.1.11- '@vitest/utils': 4.1.11- magic-string: 0.30.21- pathe: 2.0.3-- '@vitest/[email protected]': {}-- '@vitest/[email protected]':- dependencies:- '@vitest/pretty-format': 4.1.11- convert-source-map: 2.0.0- tinyrainbow: 3.2.0-- '@vitest/[email protected]':- dependencies:- '@vitest/pretty-format': 4.1.12- convert-source-map: 2.0.0- tinyrainbow: 3.2.0+ '@vitest/[email protected]': {}dependencies:@@ -13972,7 +14335,7 @@ snapshots:- [email protected](@opentelemetry/[email protected])([email protected](@cloudflare/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected]):+ [email protected](@opentelemetry/[email protected])([email protected](@cloudflare/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected]):dependencies:'@better-auth/core': 1.7.12(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])'@better-auth/drizzle-adapter': 1.7.12(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])([email protected](@cloudflare/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]))@@ -13997,7 +14360,7 @@ snapshots:react: 19.3.1react-dom: 19.3.1([email protected])solid-js: 1.9.17- vitest: 4.1.12(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ vitest: 5.1.0(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))transitivePeerDependencies:- '@opentelemetry/api'@@ -15954,8 +16317,6 @@ snapshots:transitivePeerDependencies:- '@noble/hashes'- [email protected]: {}-@@ -16283,19 +16644,6 @@ snapshots:transitivePeerDependencies:- encoding- [email protected]: {}-- dependencies:- istanbul-lib-coverage: 3.2.2- make-dir: 4.0.0- supports-color: 7.2.0-- dependencies:- html-escaper: 2.0.2- istanbul-lib-report: 3.0.1-dependencies:define-data-property: 1.1.4@@ -16459,7 +16807,7 @@ snapshots:- [email protected]: {}+ [email protected]: {}dependencies:@@ -16691,6 +17039,10 @@ snapshots:dependencies:'@jridgewell/sourcemap-codec': 1.6.0+ dependencies:+ '@jridgewell/sourcemap-codec': 1.6.0+dependencies:'@babel/parser': 7.29.9@@ -16701,10 +17053,6 @@ snapshots:dependencies:semver: 6.3.1- dependencies:- semver: 7.8.5-@@ -17630,7 +17978,7 @@ snapshots:- [email protected]: {}+ [email protected]: {}dependencies:@@ -17802,7 +18150,7 @@ snapshots:'@oxc-resolver/binding-win32-arm64-msvc': 11.24.2'@oxc-resolver/binding-win32-x64-msvc': 11.24.2dependencies:'@shaderfrog/glsl-parser': 7.0.1'@typescript-eslint/types': 8.72.0@@ -18265,7 +18613,7 @@ snapshots:'@types/node': 25.9.4'@types/react': 19.3.0- [email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))([email protected]):+ [email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))([email protected]):dependencies:'@astrojs/compiler': 4.0.0'@sentry/node': 10.76.2(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))@@ -18280,7 +18628,7 @@ snapshots:oxc-parser: 0.148.0oxc-resolver: 11.24.2oxlint: 1.81.0- oxlint-plugin-react-doctor: 0.9.18+ oxlint-plugin-react-doctor: 0.9.22playwright-core: 1.64.1prompts: 2.4.2typescript: 5.9.3@@ -18322,24 +18670,24 @@ snapshots:react: 19.3.1react-dom: 19.3.1([email protected])- [email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@babel/core': 7.29.7'@babel/types': 7.29.7'@preact/signals': 2.10.0([email protected])- '@rollup/pluginutils': 5.4.0+ '@rollup/pluginutils': 5.4.0([email protected])bippy: 0.5.43([email protected])commander: 14.0.3picocolors: 1.1.1preact: 10.29.7prompts: 2.4.2react: 19.3.1- react-doctor: 0.9.18(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))([email protected])+ react-doctor: 0.9.22(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))([email protected])react-dom: 19.3.1([email protected])react-grab: 0.2.0([email protected])optionalDependencies:esbuild: 0.28.2- unplugin: 3.3.0([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ unplugin: 3.3.0([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))transitivePeerDependencies:- '@farmfe/core'- '@opentelemetry/core'@@ -18680,6 +19028,60 @@ snapshots:'@rolldown/binding-win32-arm64-msvc': 1.0.0-rc.15'@rolldown/binding-win32-x64-msvc': 1.0.0-rc.15+ dependencies:+ '@oxc-project/types': 0.156.0+ '@rolldown/pluginutils': 1.0.1+ optionalDependencies:+ '@rolldown/binding-android-arm-eabi': 1.2.16+ '@rolldown/binding-android-arm64': 1.2.16+ '@rolldown/binding-darwin-arm64': 1.2.16+ '@rolldown/binding-darwin-x64': 1.2.16+ '@rolldown/binding-freebsd-x64': 1.2.16+ '@rolldown/binding-linux-arm-gnueabihf': 1.2.16+ '@rolldown/binding-linux-arm64-gnu': 1.2.16+ '@rolldown/binding-linux-arm64-musl': 1.2.16+ '@rolldown/binding-linux-ppc64-gnu': 1.2.16+ '@rolldown/binding-linux-s390x-gnu': 1.2.16+ '@rolldown/binding-linux-x64-gnu': 1.2.16+ '@rolldown/binding-linux-x64-musl': 1.2.16+ '@rolldown/binding-openharmony-arm64': 1.2.16+ '@rolldown/binding-win32-arm64-msvc': 1.2.16+ '@rolldown/binding-win32-x64-msvc': 1.2.16++ dependencies:+ '@types/estree': 1.0.10+ optionalDependencies:+ '@napi-rs/lzma-linux-x64-gnu': 1.5.1+ '@rollup/rollup-android-arm-eabi': 4.67.4+ '@rollup/rollup-android-arm64': 4.67.4+ '@rollup/rollup-android-x64': 4.67.4+ '@rollup/rollup-darwin-arm64': 4.67.4+ '@rollup/rollup-darwin-x64': 4.67.4+ '@rollup/rollup-freebsd-arm64': 4.67.4+ '@rollup/rollup-freebsd-x64': 4.67.4+ '@rollup/rollup-linux-arm-gnueabihf': 4.67.4+ '@rollup/rollup-linux-arm-musleabihf': 4.67.4+ '@rollup/rollup-linux-arm64-gnu': 4.67.4+ '@rollup/rollup-linux-arm64-musl': 4.67.4+ '@rollup/rollup-linux-loong64-gnu': 4.67.4+ '@rollup/rollup-linux-loong64-musl': 4.67.4+ '@rollup/rollup-linux-ppc64-gnu': 4.67.4+ '@rollup/rollup-linux-ppc64-musl': 4.67.4+ '@rollup/rollup-linux-riscv64-gnu': 4.67.4+ '@rollup/rollup-linux-riscv64-musl': 4.67.4+ '@rollup/rollup-linux-s390x-gnu': 4.67.4+ '@rollup/rollup-linux-x64-gnu': 4.67.4+ '@rollup/rollup-linux-x64-musl': 4.67.4+ '@rollup/rollup-openbsd-x64': 4.67.4+ '@rollup/rollup-openharmony-arm64': 4.67.4+ '@rollup/rollup-win32-arm64-msvc': 4.67.4+ '@rollup/rollup-win32-ia32-msvc': 4.67.4+ '@rollup/rollup-win32-x64-gnu': 4.67.4+ '@rollup/rollup-win32-x64-msvc': 4.67.4+ fsevents: 2.3.3+@@ -19045,8 +19447,6 @@ snapshots:side-channel-map: 1.0.1side-channel-weakmap: 1.0.2- [email protected]: {}-@@ -19136,8 +19536,6 @@ snapshots:- [email protected]: {}-dependencies:'@stablelib/base64': 1.0.1@@ -19463,7 +19861,7 @@ snapshots:- [email protected]: {}+ [email protected]: {}@@ -19740,13 +20138,15 @@ snapshots:- [email protected]([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected]([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@jridgewell/remapping': 2.3.5picomatch: 4.0.7webpack-virtual-modules: 0.6.2optionalDependencies:esbuild: 0.28.2+ rolldown: 1.2.16+ rollup: 4.67.4vite: 8.0.8(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])optional: true@@ -19881,126 +20281,102 @@ snapshots:tsx: 4.23.15yaml: 2.9.1- [email protected](@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected](@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:- '@vitest/expect': 4.1.12- '@vitest/mocker': 4.1.12([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))- '@vitest/pretty-format': 4.1.12- '@vitest/runner': 4.1.11- '@vitest/snapshot': 4.1.11- '@vitest/spy': 4.1.12- '@vitest/utils': 4.1.12+ '@types/chai': 5.2.3+ '@vitest/mocker': 5.1.0([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ chai: 6.3.0es-module-lexer: 2.3.2expect-type: 1.4.0- magic-string: 0.30.21- obug: 2.2.1- pathe: 2.0.3+ magic-string: 1.4.5+ obug: 3.0.0picomatch: 4.0.7std-env: 4.3.0- tinybench: 2.9.0+ tinybench: 6.2.3tinyexec: 1.3.1tinyglobby: 0.2.17- tinyrainbow: 3.2.0vite: 8.0.8(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- why-is-node-running: 2.3.0+ why-is-node-running: 3.2.1optionalDependencies:'@opentelemetry/api': 1.10.0'@types/node': 20.19.43- '@vitest/coverage-istanbul': 4.1.12([email protected])- '@vitest/coverage-v8': 4.1.12([email protected])+ '@vitest/coverage-istanbul': 5.1.0([email protected])+ '@vitest/coverage-v8': 5.1.0([email protected])jsdom: 29.1.1(@noble/[email protected])transitivePeerDependencies:- msw- [email protected](@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected](@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:- '@vitest/expect': 4.1.12- '@vitest/mocker': 4.1.12([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))- '@vitest/pretty-format': 4.1.12- '@vitest/runner': 4.1.11- '@vitest/snapshot': 4.1.11- '@vitest/spy': 4.1.12- '@vitest/utils': 4.1.12+ '@types/chai': 5.2.3+ '@vitest/mocker': 5.1.0([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ chai: 6.3.0es-module-lexer: 2.3.2expect-type: 1.4.0- magic-string: 0.30.21- obug: 2.2.1- pathe: 2.0.3+ magic-string: 1.4.5+ obug: 3.0.0picomatch: 4.0.7std-env: 4.3.0- tinybench: 2.9.0+ tinybench: 6.2.3tinyexec: 1.3.1tinyglobby: 0.2.17- tinyrainbow: 3.2.0vite: 8.0.8(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- why-is-node-running: 2.3.0+ why-is-node-running: 3.2.1optionalDependencies:'@opentelemetry/api': 1.10.0'@types/node': 25.9.4- '@vitest/coverage-istanbul': 4.1.12([email protected])- '@vitest/coverage-v8': 4.1.12([email protected])+ '@vitest/coverage-istanbul': 5.1.0([email protected])+ '@vitest/coverage-v8': 5.1.0([email protected])jsdom: 29.1.1(@noble/[email protected])transitivePeerDependencies:- msw- [email protected](@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected](@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:- '@vitest/expect': 4.1.12- '@vitest/mocker': 4.1.12([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))- '@vitest/pretty-format': 4.1.12- '@vitest/runner': 4.1.11- '@vitest/snapshot': 4.1.11- '@vitest/spy': 4.1.12- '@vitest/utils': 4.1.12+ '@types/chai': 5.2.3+ '@vitest/mocker': 5.1.0([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ chai: 6.3.0es-module-lexer: 2.3.2expect-type: 1.4.0- magic-string: 0.30.21- obug: 2.2.1- pathe: 2.0.3+ magic-string: 1.4.5+ obug: 3.0.0picomatch: 4.0.7std-env: 4.3.0- tinybench: 2.9.0+ tinybench: 6.2.3tinyexec: 1.3.1tinyglobby: 0.2.17- tinyrainbow: 3.2.0vite: 8.0.8(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- why-is-node-running: 2.3.0+ why-is-node-running: 3.2.1optionalDependencies:'@opentelemetry/api': 1.10.0'@types/node': 26.6.5- '@vitest/coverage-istanbul': 4.1.12([email protected])- '@vitest/coverage-v8': 4.1.12([email protected])+ '@vitest/coverage-istanbul': 5.1.0([email protected])+ '@vitest/coverage-v8': 5.1.0([email protected])jsdom: 29.1.1(@noble/[email protected])transitivePeerDependencies:- msw- [email protected](@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected](@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:- '@vitest/expect': 4.1.12- '@vitest/mocker': 4.1.12([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))- '@vitest/pretty-format': 4.1.12- '@vitest/runner': 4.1.11- '@vitest/snapshot': 4.1.11- '@vitest/spy': 4.1.12- '@vitest/utils': 4.1.12+ '@types/chai': 5.2.3+ '@vitest/mocker': 5.1.0([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ chai: 6.3.0es-module-lexer: 2.3.2expect-type: 1.4.0- magic-string: 0.30.21- obug: 2.2.1- pathe: 2.0.3+ magic-string: 1.4.5+ obug: 3.0.0picomatch: 4.0.7std-env: 4.3.0- tinybench: 2.9.0+ tinybench: 6.2.3tinyexec: 1.3.1tinyglobby: 0.2.17- tinyrainbow: 3.2.0vite: 8.0.8(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- why-is-node-running: 2.3.0+ why-is-node-running: 3.2.1optionalDependencies:'@opentelemetry/api': 1.9.1'@types/node': 25.9.4- '@vitest/coverage-istanbul': 4.1.12([email protected])- '@vitest/coverage-v8': 4.1.12([email protected])+ '@vitest/coverage-istanbul': 5.1.0([email protected])+ '@vitest/coverage-v8': 5.1.0([email protected])jsdom: 29.1.1(@noble/[email protected])transitivePeerDependencies:- msw@@ -20098,10 +20474,7 @@ snapshots:dependencies:isexe: 3.1.5- dependencies:- siginfo: 2.0.0- stackback: 0.0.2+ [email protected]: {}diff --git a/scripts/ci/change-scope-manifest.json b/scripts/ci/change-scope-manifest.jsonindex f18ef4142..47c4d13a8 100644--- a/scripts/ci/change-scope-manifest.json+++ b/scripts/ci/change-scope-manifest.json@@ -1,6 +1,6 @@{- "schema_version": 1,- "policy_version": 1,+ "schema_version": 2,+ "policy_version": 3,"packages": [{"name": "@alook/agent-driver",@@ -9,10 +9,16 @@"build": false,"knip": true,"unit_root": "src/daemon/agent-driver",- "coverage_roots": ["src/daemon/agent-driver/**/*.{ts,tsx,js,jsx}"],- "windows_suites": ["agent-driver"],+ "coverage_roots": [+ "src/daemon/agent-driver/**/*.{ts,tsx,js,jsx}"+ ],+ "windows_suites": [+ "agent-driver"+ ],"integration_suites": [],- "linux_suites": ["agent-driver-packed"],+ "linux_suites": [+ "agent-driver-packed"+ ],"ui": false,"lighthouse": false,"app_artifact": true@@ -24,8 +30,12 @@"build": false,"knip": true,"unit_root": "src/app",- "coverage_roots": ["src/app/**/*.{ts,tsx,js,jsx}"],- "windows_suites": ["app"],+ "coverage_roots": [+ "src/app/**/*.{ts,tsx,js,jsx}"+ ],+ "windows_suites": [+ "app"+ ],"integration_suites": [],"linux_suites": [],"ui": false,@@ -43,9 +53,16 @@"src/daemon/scripts/**/*.{ts,tsx,js,jsx}","src/daemon/src/**/*.{ts,tsx,js,jsx}"],- "windows_suites": ["daemon"],- "integration_suites": ["daemon"],- "linux_suites": ["daemon-packed", "daemon-real"],+ "windows_suites": [+ "daemon"+ ],+ "integration_suites": [+ "daemon"+ ],+ "linux_suites": [+ "daemon-packed",+ "daemon-real"+ ],"ui": false,"lighthouse": false,"app_artifact": true@@ -73,10 +90,14 @@"build": true,"knip": true,"unit_root": "src/email-worker",- "coverage_roots": ["src/email-worker/**/*.{ts,tsx,js,jsx}"],+ "coverage_roots": [+ "src/email-worker/**/*.{ts,tsx,js,jsx}"+ ],"codecov_target": "email-worker","windows_suites": [],- "integration_suites": ["web"],+ "integration_suites": [+ "web"+ ],"linux_suites": [],"ui": false,"lighthouse": false,@@ -89,9 +110,13 @@"build": true,"knip": true,"unit_root": "src/shared",- "coverage_roots": ["src/shared/**/*.{ts,tsx,js,jsx}"],+ "coverage_roots": [+ "src/shared/**/*.{ts,tsx,js,jsx}"+ ],"codecov_target": "shared",- "windows_suites": ["shared"],+ "windows_suites": [+ "shared"+ ],"integration_suites": [],"linux_suites": [],"ui": false,@@ -120,9 +145,13 @@"build": true,"knip": true,"unit_root": "src/queue-worker",- "coverage_roots": ["src/queue-worker/**/*.{ts,tsx,js,jsx}"],+ "coverage_roots": [+ "src/queue-worker/**/*.{ts,tsx,js,jsx}"+ ],"windows_suites": [],- "integration_suites": ["web"],+ "integration_suites": [+ "web"+ ],"linux_suites": [],"ui": false,"lighthouse": false,@@ -135,10 +164,14 @@"build": true,"knip": true,"unit_root": "src/web",- "coverage_roots": ["src/web/**/*.{ts,tsx,js,jsx}"],+ "coverage_roots": [+ "src/web/**/*.{ts,tsx,js,jsx}"+ ],"codecov_target": "web","windows_suites": [],- "integration_suites": ["web"],+ "integration_suites": [+ "web"+ ],"linux_suites": [],"ui": true,"lighthouse": true,@@ -151,10 +184,14 @@"build": true,"knip": true,"unit_root": "src/ws-do",- "coverage_roots": ["src/ws-do/**/*.{ts,tsx,js,jsx}"],+ "coverage_roots": [+ "src/ws-do/**/*.{ts,tsx,js,jsx}"+ ],"codecov_target": "ws-do","windows_suites": [],- "integration_suites": ["web"],+ "integration_suites": [+ "web"+ ],"linux_suites": [],"ui": true,"lighthouse": false,@@ -162,29 +199,217 @@}],"suites": {- "windows": ["agent-driver", "app", "daemon", "shared"],- "integration": ["daemon", "web"],- "linux": ["agent-driver-packed", "daemon-packed", "daemon-real"]+ "windows": [+ "agent-driver",+ "app",+ "daemon",+ "shared"+ ],+ "integration": [+ "daemon",+ "web"+ ],+ "linux": [+ "agent-driver-packed",+ "daemon-packed",+ "daemon-real"+ ]},"path_suites": [- { "root": "tests/integration/daemon", "integration_suites": ["daemon"] }+ {+ "root": "tests/integration/daemon",+ "integration_suites": [+ "daemon"+ ]+ }],"ui": {"root": "src/web/src/test/e2e-ui","all": "all","contracts": {- "blog": ["54-blog-multizone.spec.ts"],+ "blog": [+ "54-blog-multizone.spec.ts",+ "66-public-static-resource-cache.spec.ts"+ ],"resizable_panels": ["53-mobile-inbox-surface.spec.ts","60-desktop-default-user-bar-width.spec.ts"+ ],+ "smoke": [+ "01-auth.spec.ts",+ "03-realtime-multiuser.spec.ts",+ "06-channel-member-admin.spec.ts"]- }+ },+ "groups": [+ {+ "name": "auth",+ "prefixes": [+ "src/web/src/app/(auth)/",+ "src/web/src/components/authenticated-context-menu-boundary",+ "src/web/src/lib/native-oauth"+ ],+ "specs": [+ "01-auth.spec.ts",+ "10-eject-nav-auth.spec.ts",+ "54-authenticated-context-menu-policy.spec.ts"+ ]+ },+ {+ "name": "marketing",+ "prefixes": [+ "src/web/src/components/home/",+ "src/web/src/components/download/",+ "src/web/src/app/(home)/",+ "src/web/src/app/landing-legacy/",+ "src/web/src/app/download/",+ "src/web/src/app/og/",+ "src/web/src/app/_og/",+ "src/web/src/lib/seo/"+ ],+ "specs": [+ "19-marketing-seo.spec.ts",+ "31-machine-guide-motion.spec.ts",+ "51-share-image-assets.spec.ts"+ ]+ },+ {+ "name": "user-bar",+ "prefixes": [+ "src/web/src/components/community/shell/user-bar",+ "src/web/src/components/community/shell/use-user-bar"+ ],+ "specs": [+ "11-profile-ui-stability.spec.ts",+ "34-inbox-read-race.spec.ts",+ "41-community-initial-load-module-skeletons.spec.ts",+ "50-daemon-update-notice.spec.ts",+ "53-mobile-inbox-surface.spec.ts",+ "56-inbox-friend-requests.spec.ts",+ "60-desktop-default-user-bar-width.spec.ts"+ ]+ },+ {+ "name": "social",+ "prefixes": [+ "src/web/src/components/community/social/",+ "src/web/src/hooks/community/use-profile"+ ],+ "specs": [+ "07-invite.spec.ts",+ "11-profile-ui-stability.spec.ts",+ "12-friends.spec.ts",+ "29-community-bot-avatar-cleanup.spec.ts",+ "30-activity-older-pages.spec.ts",+ "30-activity-recovery.spec.ts",+ "30-audit-hover-touch.spec.ts",+ "30-bot-lifecycle-audit-modal.spec.ts",+ "30-bot-profile-bounds.spec.ts",+ "30-sheet-footer-geometry.spec.ts",+ "35-bot-token-usage-quota.spec.ts",+ "42-versioned-avatar-identity.spec.ts",+ "56-inbox-friend-requests.spec.ts",+ "68-bot-memberships.spec.ts"+ ]+ },+ {+ "name": "forum",+ "prefixes": [+ "src/web/src/components/community/channels/forum-",+ "src/web/src/hooks/community/use-forum-",+ "src/web/src/lib/community/forum-"+ ],+ "specs": [+ "09-forum-thread.spec.ts",+ "14-forum-post-tags-presence.spec.ts",+ "17-forum-sidebar-stage-b.spec.ts",+ "26-mobile-forum-post-actions.spec.ts",+ "27-canonical-forum-post-delete.spec.ts",+ "28-thread-realtime-audiences.spec.ts",+ "51-mobile-forum-tag-editor.spec.ts",+ "67-text-sidebar-threads.spec.ts"+ ]+ },+ {+ "name": "messages",+ "prefixes": [+ "src/web/src/components/community/messages/",+ "src/web/src/app/api/community/channels/[id]/messages/",+ "src/web/src/app/api/community/messages/"+ ],+ "specs": [+ "02-server-channel-message.spec.ts",+ "03-realtime-multiuser.spec.ts",+ "04-dm.spec.ts",+ "08-mobile.spec.ts",+ "13-mentions.spec.ts",+ "15-mention-scope.spec.ts",+ "16-jump-to-present.spec.ts",+ "18-new-divider-scroll.spec.ts",+ "20-community-attachment-thumbnails.spec.ts",+ "21-mobile-message-layout.spec.ts",+ "22-committed-message-delivery.spec.ts",+ "23-message-selection-context-menu.spec.ts",+ "24-composer-overflow.spec.ts",+ "25-composer-accessory-rail-occupancy.spec.ts",+ "31-mention-candidate-pagination.spec.ts",+ "33-picker-async-layout.spec.ts",+ "39-mobile-composer-send.spec.ts",+ "39-mobile-message-interactions.spec.ts",+ "43-composer-attachment-drafts.spec.ts",+ "44-mobile-reaction-details.spec.ts",+ "45-desktop-thread-split-view.spec.ts",+ "52-chat-composer-ordered-list.spec.ts",+ "55-composer-resize-anchors.spec.ts",+ "55-dm-composer-viewport.spec.ts",+ "55-draft-optimistic-viewport.spec.ts",+ "55-history-local-remote-owners.spec.ts",+ "55-jump-peer-tail-follow.spec.ts",+ "55-peer-bottom-clamp-follow.spec.ts",+ "55-reaction-backward-reading.spec.ts",+ "55-scroll-loading-prepend-jump.spec.ts",+ "55-upward-release-resize.spec.ts",+ "59-message-pagination-anchor.spec.ts",+ "66-grouped-message-toolbar.spec.ts",+ "69-table-fullscreen-scroll.spec.ts",+ "70-renderer-action-themes.spec.ts",+ "native-keyboard-viewport-projection.spec.ts"+ ]+ },+ {+ "name": "billing",+ "prefixes": [+ "src/web/src/components/community/billing/",+ "src/web/src/hooks/community/use-billing",+ "src/web/src/app/api/community/billing/",+ "src/web/src/app/contact/"+ ],+ "specs": [+ "35-bot-token-usage-quota.spec.ts",+ "64-billing-contact.spec.ts"+ ]+ }+ ],+ "full_prefixes": [+ "src/web/src/components/community/messages/message-list",+ "src/web/src/components/community/messages/message-channel-controller",+ "src/web/src/app/api/community/channels/[id]/messages/",+ "src/web/src/app/api/community/messages/"+ ]},"codecov_targets": {- "shared": { "path": "src/shared", "target": 50 },- "email-worker": { "path": "src/email-worker", "target": 70 },- "ws-do": { "path": "src/ws-do", "target": 70 },- "web": { "path": "src/web", "target": 30 }+ "shared": {+ "path": "src/shared"+ },+ "email-worker": {+ "path": "src/email-worker"+ },+ "ws-do": {+ "path": "src/ws-do"+ },+ "web": {+ "path": "src/web"+ }},"integrity_paths": [".github/workflows/ci.yml",@@ -212,5 +437,115 @@"src/web/package.json","src/ws-do/package.json","tests/utils/package.json"- ]+ ],+ "smoke_tests": [+ "scripts/ci/assert-gate.test.ts",+ "src/shared/test/queries/session-identity.test.ts",+ "src/web/src/app/api/community/channels/[id]/messages/route.atomic-replay.test.ts",+ "src/web/src/lib/session.test.ts",+ "src/web/src/test/e2e-service-lifecycle.test.ts",+ "src/web/src/test/e2e-fixture-isolation.test.ts"+ ],+ "unit_tasks": {+ "@alook/shared#test": {+ "projects": [+ "@alook/shared"+ ]+ },+ "@alook/app#test": {+ "projects": [+ "@alook/app"+ ],+ "selection": "project"+ },+ "@alook/agent-driver#test": {+ "projects": [+ "@alook/agent-driver"+ ]+ },+ "@alook/daemon#test": {+ "projects": [+ "daemon-node"+ ]+ },+ "@alook/test-utils#test": {+ "projects": [+ "@alook/test-utils"+ ]+ },+ "@alook/web#test": {+ "projects": [+ "web-node",+ "web-dom"+ ]+ },+ "@alook/web#test:contracts": {+ "projects": [+ "web-contracts"+ ],+ "selection": "project"+ },+ "@alook/web#test:tooling": {+ "projects": [+ "web-tooling"+ ],+ "selection": "project"+ },+ "@alook/web#test:blog": {+ "projects": [+ "blog-node",+ "blog-dom"+ ]+ },+ "@alook/web#test:auth": {+ "projects": [+ "auth-node"+ ]+ },+ "@alook/web#test:runtime": {+ "projects": [+ "web-runtime"+ ],+ "selection": "project"+ },+ "@alook/web#test:auth:runtime": {+ "projects": [+ "auth-runtime"+ ],+ "selection": "project"+ },+ "@alook/ws-do#test": {+ "projects": [+ "ws-do-node"+ ]+ },+ "@alook/ws-do#test:runtime": {+ "projects": [+ "ws-do-runtime"+ ],+ "selection": "project"+ },+ "@alook/email-worker#test": {+ "projects": [+ "email-worker-node"+ ]+ },+ "@alook/email-worker#test:runtime": {+ "projects": [+ "email-worker-runtime"+ ],+ "selection": "project"+ },+ "@alook/queue-worker#test": {+ "projects": [+ "queue-worker-node"+ ]+ },+ "@alook/queue-worker#test:runtime": {+ "projects": [+ "queue-worker-runtime"+ ],+ "selection": "project"+ }+ }}diff --git a/scripts/ci/changed-scopes.mjs b/scripts/ci/changed-scopes.mjsindex 19dffaf1e..ce50597e5 100644--- a/scripts/ci/changed-scopes.mjs+++ b/scripts/ci/changed-scopes.mjs@@ -3,11 +3,13 @@ import { createHash } from "node:crypto"import {appendFileSync,readFileSync,+ statSync,writeFileSync,} from "node:fs"import { resolve } from "node:path"import { fileURLToPath } from "node:url"-import { createE2eMatrix, discoverE2eSpecs } from "./e2e-shards.mjs"+import { createE2eMatrix, queryNativeUiFacts, resolvePlaywrightImage, validateNativeUiFacts } from "./e2e-shards.mjs"+import { isolatedRepositoryGitEnvironment } from "./report-changed-patch-coverage.mjs"const ROOT = resolve(fileURLToPath(new URL("../..", import.meta.url)))const MANIFEST_URL = new URL("./change-scope-manifest.json", import.meta.url)@@ -33,6 +35,7 @@ const COVERAGE_EXCLUDES = [// excluded by Vitest itself; their behavior is enforced by contract tests./(?:^|\/)vitest(?:\.[^/]+)?\.config\.[cm]?[jt]sx?$/,/^src\/web\/open-next\.config\.ts$/,+ /^src\/web\/public\/(?:sw\.js(?:\.map)?$|community-shell\/)/,/(?:^|\/)node_modules\//,/(?:^|\/)(?:\.next|\.open-next|\.wrangler|dist|bundled|__mocks__)\//,/(?:^|\/)test-runtime\//,@@ -135,24 +138,52 @@ function packageManifest(scopePackage, root = ROOT) {return JSON.parse(readFileSync(resolve(root, scopePackage.root, "package.json"), "utf8"))}-function workspaceGraph(manifest, root = ROOT) {- const names = new Set(manifest.packages.map((entry) => entry.name))- const dependents = new Map(manifest.packages.map((entry) => [entry.name, new Set()]))- for (const entry of manifest.packages) {- const workspacePackage = packageManifest(entry, root)- const dependencies = {- ...workspacePackage.dependencies,- ...workspacePackage.devDependencies,- ...workspacePackage.optionalDependencies,- ...workspacePackage.peerDependencies,- }- for (const [dependency, version] of Object.entries(dependencies)) {- if (names.has(dependency) && String(version).startsWith("workspace:")) {- dependents.get(dependency).add(entry.name)- }- }+const CHECK_TASKS = [+ "typecheck", "typecheck:blog", "typecheck:auth",+ "lint", "lint:blog", "lint:auth", "knip",+ "test", "test:contracts", "test:tooling", "test:blog", "test:auth", "test:runtime", "test:auth:runtime",+ "build", "build:blog", "build:auth",+]++function checkTasks(items, manifest) {+ const packages = new Map(manifest.packages.map((entry) => [entry.name, entry]))+ return items.filter((task) => {+ const owner = packages.get(task.package.name)+ if (!owner || !task.command || !CHECK_TASKS.includes(task.name)) return false+ if (task.name === "build") return owner.build || owner.app_artifact+ if (task.name.startsWith("typecheck") || task.name.startsWith("lint")) return owner.static+ if (task.name === "knip") return owner.knip+ return true+ }).sort((left, right) => left.fullName.localeCompare(right.fullName))+}++export function queryNativeTasks({ root = ROOT, baseSha, headSha, manifest = loadScopeManifest(), execute = execFileSync } = {}) {+ const fields = "fullName name command package { name path } allDependencies { items { fullName } }"+ const query = (source) => {+ const result = JSON.parse(execute(process.platform === "win32" ? "pnpm.cmd" : "pnpm",+ ["exec", "turbo", "query", source], {+ cwd: root, encoding: "utf8", maxBuffer: 16 * 1024 * 1024,+ env: { ...isolatedRepositoryGitEnvironment(), GIT_OPTIONAL_LOCKS: "0" },+ stdio: ["ignore", "pipe", "pipe"],+ }))+ if (result.errors?.length || !result.data) throw new Error("native Turbo task query failed")+ return result.data+ }+ const packagesQuery = "packages { items { tasks { items { " + fields + " } } } }"+ const affectedQuery = baseSha && headSha+ ? "affectedTasks(base: " + JSON.stringify(baseSha) + ", head: " + JSON.stringify(headSha)+ + ", tasks: " + JSON.stringify(CHECK_TASKS)+ + ") { items { " + fields + " reason { __typename ... on TaskAllChanged { description } } } }"+ : ""+ const selection = query("query { " + packagesQuery + " " + affectedQuery + " }")+ const inventory = checkTasks(selection.packages.items.flatMap((entry) => entry.tasks.items), manifest)+ if (!inventory.length) throw new Error("native Turbo task inventory is empty")+ if (!affectedQuery) return { inventory, affected: inventory, reason: "unresolved_native_base" }+ const fallback = selection.affectedTasks.items.find(task => task.reason?.__typename === "TaskAllChanged" && task.reason.description === "conservative affectedness fallback")+ return { inventory, affected: checkTasks(selection.affectedTasks.items, manifest),+ reason: fallback ? "native_affected_fallback" : null,+ ...(fallback ? { detail: fallback.reason.description } : {}),}- return dependents}function validateCodecovTargets(manifest, root) {@@ -170,7 +201,7 @@ function validateCodecovTargets(manifest, root) {const escapedName = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")const escapedPath = target.path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")const contract = new RegExp(- `^[ ]{6}${escapedName}:\\n[ ]{8}target: ${target.target}%\\n[ ]{8}paths:\\n[ ]{10}- ${escapedPath}/\\*\\*$`,+ `^[ ]{6}${escapedName}:\\n[ ]{8}informational: true\\n[ ]{8}target: auto\\n[ ]{8}paths:\\n[ ]{10}- ${escapedPath}/\\*\\*$`,"m",)if (!contract.test(projectSection)) {@@ -181,8 +212,8 @@ function validateCodecovTargets(manifest, root) {export function validateScopeManifest(manifest, options = {}) {const root = options.root || ROOT- if (manifest.schema_version !== 1 || manifest.policy_version !== 1) {- throw new Error("scope manifest schema/policy version must be 1")+ if (manifest.schema_version !== 2 || manifest.policy_version !== 3) {+ throw new Error("scope manifest schema/policy version must be 1/2")}if (!Array.isArray(manifest.packages) || manifest.packages.length === 0) {throw new Error("scope manifest packages are required")@@ -239,15 +270,52 @@ export function validateScopeManifest(manifest, options = {}) {}}- const specs = options.specs || discoverE2eSpecs(resolve(root, manifest.ui.root))+ const knownSpec = (spec) => typeof spec === "string" && !spec.includes("..") && !spec.includes("\\")+ && spec.endsWith(".spec.ts") && (options.specs+ ? options.specs.includes(spec)+ : statSync(resolve(root, manifest.ui.root, spec), { throwIfNoEntry: false })?.isFile())for (const contractSpecs of Object.values(manifest.ui.contracts)) {for (const spec of contractSpecs) {- if (!specs.includes(spec)) throw new Error(`unknown UI spec: ${spec}`)+ if (!knownSpec(spec)) throw new Error(`unknown UI spec: ${spec}`)+ }+ }+ const groups = manifest.ui.groups+ if (!Array.isArray(manifest.ui.full_prefixes) || manifest.ui.full_prefixes.length === 0+ || manifest.ui.full_prefixes.some((prefix) => typeof prefix !== "string"+ || !prefix.startsWith("src/") || prefix.includes("..") || prefix.includes("\\"))) {+ throw new Error("UI full-scope prefixes must be repository source paths")+ }+ if (!Array.isArray(groups) || new Set(groups.map((group) => group.name)).size !== groups.length) {+ throw new Error("UI feature group names must be unique")+ }+ for (const group of groups) {+ if (!group.name || !Array.isArray(group.prefixes) || group.prefixes.length === 0+ || !Array.isArray(group.specs) || group.specs.length === 0) {+ throw new Error("UI feature groups require a name, prefixes and specs")+ }+ for (const prefix of group.prefixes) {+ if (typeof prefix !== "string" || !/^src\/(?:web|ws-do)\//.test(prefix)+ || prefix.includes("..") || prefix.includes("\\")) {+ throw new Error(`invalid UI feature prefix: ${prefix}`)+ }+ }+ for (const spec of group.specs) {+ if (!knownSpec(spec)) throw new Error(`unknown UI spec: ${spec}`)+ }+ }+ if (!Array.isArray(manifest.smoke_tests) || manifest.smoke_tests.length === 0+ || new Set(manifest.smoke_tests).size !== manifest.smoke_tests.length+ || manifest.smoke_tests.some((path) => typeof path !== "string" || path.includes("..")+ || !/^(?:scripts\/ci|src\/(?:shared|web))\/.+\.test\.[cm]?[jt]sx?$/.test(path))) {+ throw new Error("main smoke tests must be unique repository test paths")+ }+ for (const path of manifest.smoke_tests) {+ if (!statSync(resolve(root, path), { throwIfNoEntry: false })?.isFile()) {+ throw new Error(`missing main smoke test: ${path}`)}}validateCodecovTargets(manifest, root)sorted(manifest.integrity_paths)- workspaceGraph(manifest, root)return manifest}@@ -257,34 +325,6 @@ function findPackage(path, manifest) {.find((entry) => pathWithin(path, entry.root))}-function affectedClosure(directNames, manifest) {- const graph = workspaceGraph(manifest)- const affected = new Set(directNames)- const queue = [...directNames]- while (queue.length > 0) {- const current = queue.shift()- for (const dependent of graph.get(current) || []) {- if (affected.has(dependent)) continue- affected.add(dependent)- queue.push(dependent)- }- }- return sorted([...affected])-}--function loadBlogSharedInputs() {- const sourcePaths = JSON.parse(- readFileSync(resolve(ROOT, "src/web/blog/shared-build-inputs.json"), "utf8"),- ).sourcePaths- return sourcePaths.map((path) => `src/web/${path}`)-}--function isBlogBuildInput(path, sharedInputs) {- return BLOG_ROOT.test(path) || sharedInputs.some((input) => (- input.endsWith("/") ? path.startsWith(input) : path === input- ))-}-function isKnownPath(path, manifest) {return isMarkdown(path)|| GLOBAL_PATHS.has(path)@@ -293,9 +333,9 @@ function isKnownPath(path, manifest) {|| KNOWN_PREFIXES.some((prefix) => path.startsWith(prefix))}-function fullReason(paths, { forceFull, fullUnlessBenchmarkOnly, benchmarkOnly, fallbackReason }) {+function fullReason(paths, { forceFull, benchmarkOnly, fallbackReason }) {if (fallbackReason) return "classifier_error"- if (forceFull || (fullUnlessBenchmarkOnly && !benchmarkOnly)) return "forced"+ if (forceFull) return "forced"if (benchmarkOnly) return nullif (paths.length === 0) return "empty_diff"const docsOnly = paths.every(isMarkdown)@@ -315,6 +355,7 @@ function emptyJobs() {return {app_packed_artifact: false,auth_build: false,+ worker_build: false,blog_build: false,e2e: false,lighthouse: false,@@ -355,6 +396,30 @@ function requiredCoverageFiles(changes, coverageRoots) {}))}+function affectedUiSpecs(paths, manifest) {+ const selected = new Set(manifest.ui.contracts.smoke)+ const relevant = paths.filter((path) => {+ const owner = findPackage(path, manifest)?.name+ return ["@alook/web", "@alook/ws-do", "@alook/shared", "@alook/test-utils"].includes(owner)+ && !isMarkdown(path)+ && (!/\.(?:test|spec)\.[cm]?[jt]sx?$/.test(path) || pathWithin(path, manifest.ui.root))+ })+ if (relevant.length === 0) return []+ for (const path of relevant) {+ if (pathWithin(path, manifest.ui.root)) {+ const spec = path.slice(manifest.ui.root.length + 1)+ if (!spec.endsWith(".spec.ts") || !statSync(resolve(ROOT, path), { throwIfNoEntry: false })?.isFile()) return [manifest.ui.all]+ selected.add(spec)+ continue+ }+ if (manifest.ui.full_prefixes.some((prefix) => path.startsWith(prefix))) return [manifest.ui.all]+ const groups = manifest.ui.groups.filter((group) => group.prefixes.some((prefix) => path.startsWith(prefix)))+ if (groups.length === 0) return [manifest.ui.all]+ for (const group of groups) for (const spec of group.specs) selected.add(spec)+ }+ return sorted([...selected])+}+function planClass({ full, benchmarkOnly, docsOnly, blogPathsOnly, authPathsOnly, direct }) {if (full) return "full"if (benchmarkOnly) return "benchmark"@@ -366,6 +431,11 @@ function planClass({ full, benchmarkOnly, docsOnly, blogPathsOnly, authPathsOnlyreturn "mixed"}+function browserZonesForSpecs(specs, manifest) {+ const names = specs.map(spec => spec.replace(/^src\/test\/e2e-ui\//, ""))+ return names.length ? ["web", ...(names.includes(manifest.ui.all) || names.some(spec => manifest.ui.contracts.blog.includes(spec)) ? ["blog"] : [])] : []+}+export function buildExecutionPlan(inputChanges, options = {}) {const manifest = validateScopeManifest(options.manifest || loadScopeManifest())const changes = normalizedChanges(inputChanges)@@ -377,19 +447,46 @@ export function buildExecutionPlan(inputChanges, options = {}) {const blogPathsOnly = paths.length > 0 && paths.every((path) => BLOG_ROOT.test(path))const authPathsOnly = paths.length > 0 && paths.every((path) => AUTH_ROOT.test(path))const unknown = paths.some((path) => !isKnownPath(path, manifest))+ const nativeTasks = options.nativeTasks+ const nativeUnavailable = !nativeTasks && !docsOnly && !benchmarkOnlyconst reason = fullReason(paths, { ...options, benchmarkOnly }) || (unknown ? "unknown_path" : null)+ || (nativeUnavailable ? "native_tasks_unavailable" : nativeTasks?.reason || null)const full = reason !== null+ const executionMode = full ? "full" : options.mainSmoke === true ? "main-smoke" : "affected"+ const mainSmoke = executionMode === "main-smoke" && !docsOnly && !benchmarkOnlyconst direct = sorted(paths.map((path) => findPackage(path, manifest)?.name).filter(Boolean))let affectedNamesif (full) affectedNames = sorted(manifest.packages.map((entry) => entry.name))- else if (docsOnly || blogContentOnly) affectedNames = []- else affectedNames = affectedClosure(direct, manifest)+ else if (docsOnly || benchmarkOnly) affectedNames = []+ else affectedNames = sorted(nativeTasks.affected.map((task) => task.package.name))const byName = new Map(manifest.packages.map((entry) => [entry.name, entry]))const affectedPackages = affectedNames.map((name) => byName.get(name))+ const selectedTasks = full ? nativeTasks?.inventory || [] : docsOnly || benchmarkOnly ? [] : nativeTasks.affectedconst suites = packageSets(affectedPackages)- const coverage = coverageSets(affectedPackages)+ const tasks = (prefix) => selectedTasks.filter((task) => task.name === prefix || task.name.startsWith(prefix + ":"))+ suites.static_tasks = tasks("typecheck").concat(tasks("lint")).map((task) => task.fullName)+ suites.build_tasks = tasks("build").map((task) => task.fullName)+ suites.knip_tasks = tasks("knip").map((task) => task.fullName)+ suites.unit_tasks = tasks("test").map((task) => task.fullName)+ const unitDependencies = new Set(tasks("test").flatMap((task) => task.allDependencies?.items.map((dependency) => dependency.fullName) || []))+ suites.unit_build_tasks = (nativeTasks?.inventory || []).filter((task) => unitDependencies.has(task.fullName)+ && (task.name === "build" || task.name.startsWith("build:"))).map((task) => task.fullName)+ if (nativeTasks) {+ suites.static = sorted(tasks("typecheck").concat(tasks("lint")).map((task) => task.package.name))+ suites.build = sorted(tasks("build").map((task) => task.package.name))+ suites.knip = sorted(tasks("knip").map((task) => task.package.name))+ suites.unit = sorted(tasks("test").map((task) => task.package.path))+ }+ suites.smoke = []+ const testOwners = nativeTasks+ ? new Set(tasks("test").map((task) => task.package.name))+ : new Set(affectedNames)+ const testedPackages = affectedPackages.filter((entry) => testOwners.has(entry.name))+ const testSuites = packageSets(testedPackages)+ for (const kind of ["windows", "integration", "linux"]) suites[kind] = testSuites[kind]+ const coverage = coverageSets(testedPackages)suites.integration = sorted([...suites.integration,...manifest.path_suites@@ -401,7 +498,6 @@ export function buildExecutionPlan(inputChanges, options = {}) {coverage.include_roots = sorted([...coverage.include_roots, "scripts/ci/**/*.mjs"])}const jobs = emptyJobs()- const sharedInputs = loadBlogSharedInputs()let uiSpecs = []if (full) {@@ -411,8 +507,8 @@ export function buildExecutionPlan(inputChanges, options = {}) {suites.integration = blogPathsOnly && !blogContentOnly ? [] : suites.integration} else if (authPathsOnly) {suites.integration = []- } else if (affectedPackages.some((entry) => entry.ui)) {- uiSpecs = [manifest.ui.all]+ } else if ([...affectedPackages, ...direct.map((name) => byName.get(name))].some((entry) => entry.ui)) {+ uiSpecs = affectedUiSpecs(paths, manifest)}if (blogPathsOnly && !blogContentOnly) {@@ -421,30 +517,56 @@ export function buildExecutionPlan(inputChanges, options = {}) {suites.linux = []}- const authBuild = full || paths.some((path) => AUTH_ROOT.test(path))- const blogBuild = full || paths.some((path) => isBlogBuildInput(path, sharedInputs))+ const authBuild = full || suites.build_tasks.includes("@alook/web#build:auth")+ const blogBuild = full || suites.build_tasks.includes("@alook/web#build:blog")+ if (!full && blogBuild && uiSpecs.length > 0 && !uiSpecs.includes(manifest.ui.all)+ && paths.some((path) => !/\.(?:test|spec)\.[cm]?[jt]sx?$/.test(path))) {+ uiSpecs = sorted([...uiSpecs, ...manifest.ui.contracts.blog])+ }const directWebRuntime = paths.some((path) => (pathWithin(path, "src/web") && !BLOG_ROOT.test(path) && !AUTH_ROOT.test(path)))const lighthouse = full || (blogPathsOnly && !blogContentOnly) || directWebRuntime- const rust = full || affectedPackages.some((entry) => entry.rust)+ const rust = full || [...affectedPackages, ...direct.map((name) => byName.get(name))].some((entry) => entry.rust)const directPackages = direct.map((name) => byName.get(name))const appArtifact = full || (!blogPathsOnly && !authPathsOnly && [...affectedPackages, ...directPackages].some((entry) => entry.app_artifact))const requiredChangedFiles = requiredCoverageFiles(changes, coverage.include_roots)+ if (mainSmoke) {+ suites.static = []+ suites.build = []+ suites.knip = []+ suites.unit = []+ suites.windows = []+ suites.integration = []+ suites.linux = []+ for (const key of ["static_tasks", "build_tasks", "knip_tasks", "unit_tasks", "unit_build_tasks"]) suites[key] = []+ suites.smoke = [...manifest.smoke_tests]+ coverage.targets = []+ coverage.include_roots = []+ requiredChangedFiles.length = 0+ uiSpecs = uiSpecs.length > 0+ ? blogPathsOnly ? [...manifest.ui.contracts.blog] : [...manifest.ui.contracts.smoke]+ : []+ }+jobs.auth_build = authBuildjobs.blog_build = blogBuildjobs.static_checks = suites.static.length > 0- jobs.test_linux = suites.unit.length > 0 || suites.linux.length > 0+ jobs.test_linux = suites.unit.length > 0 || suites.linux.length > 0 || suites.smoke.length > 0jobs.test_windows = suites.windows.length > 0jobs.app_packed_artifact = appArtifactjobs.e2e = suites.integration.length > 0jobs.rust = rust- jobs.lighthouse = lighthouse+ jobs.lighthouse = lighthouse && !mainSmokejobs.ui_e2e = uiSpecs.length > 0jobs.merge_reports = jobs.ui_e2e- jobs.resizable_panels_compat = options.resizablePanelsChanged === true+ const browserZones = browserZonesForSpecs(uiSpecs, manifest)+ const workerZones = ["web", "blog"].filter(zone => browserZones.includes(zone)+ || (zone === "web" ? suites.build_tasks.includes("@alook/web#build") : blogBuild))+ jobs.worker_build = workerZones.length > 0+ jobs.resizable_panels_compat = options.resizablePanelsChanged === true && !mainSmokeconst basePlan = {schema_version: manifest.schema_version,@@ -452,24 +574,28 @@ export function buildExecutionPlan(inputChanges, options = {}) {base_sha: options.baseSha || "",head_sha: options.headSha || "",diagnostic_only: options.diagnosticOnly === true,+ execution_mode: executionMode,changes,paths: allPaths,change_class: planClass({ full, benchmarkOnly, docsOnly, blogPathsOnly, authPathsOnly, direct }),full,full_reason: reason,+ fallback_detail: options.fallbackReason || nativeTasks?.detail || nativeTasks?.reason || "",docs_only: docsOnly && !full,auth_only: authPathsOnly && !full,blog_only: blogContentOnly && !full,compatibility: {- resizable_panels: options.resizablePanelsChanged === true,+ resizable_panels: options.resizablePanelsChanged === true && !mainSmoke,},workflow_changed: paths.some((path) => WORKFLOW.test(path)),+ native_tasks: nativeTasks || null,packages: {direct,affected: affectedNames,},suites,- ui: { specs: sorted(uiSpecs) },+ ui: { specs: sorted(uiSpecs), zones: browserZones, native: options.nativeUi || null },+ artifacts: { worker_zones: workerZones },coverage: {...coverage,required_changed_files: requiredChangedFiles,@@ -492,6 +618,32 @@ export function validateExecutionPlan(plan, options = {}) {throw new Error("execution plan schema/policy version mismatch")}if (hashPlan(plan) !== plan.plan_hash) throw new Error("execution plan hash mismatch")+ if (!["affected", "main-smoke", "full"].includes(plan.execution_mode)+ || (plan.execution_mode === "full") !== plan.full) {+ throw new Error("execution plan mode does not match its full-scope decision")+ }+ if (!Array.isArray(plan.suites.smoke)+ || plan.suites.smoke.some((path) => !manifest.smoke_tests.includes(path))+ || (plan.execution_mode !== "main-smoke" && plan.suites.smoke.length > 0)) {+ throw new Error("execution plan smoke tests do not match its mode")+ }+ if (plan.execution_mode === "main-smoke" && !plan.docs_only && plan.change_class !== "benchmark") {+ if (JSON.stringify(plan.suites.smoke) !== JSON.stringify(manifest.smoke_tests)+ || ["static", "build", "knip", "unit", "windows", "integration", "linux"].some((kind) => plan.suites[kind].length > 0)+ || plan.coverage.targets.length > 0 || plan.coverage.include_roots.length > 0) {+ throw new Error("main smoke plan must keep the complete smoke set without full package suites")+ }+ const sourcePlan = buildExecutionPlan(plan.changes, { nativeTasks: plan.native_tasks })+ const expectedUi = sourcePlan.ui.specs.length > 0+ ? sorted(sourcePlan.change_class === "blog" ? manifest.ui.contracts.blog : manifest.ui.contracts.smoke) : []+ if (JSON.stringify(plan.ui.specs) !== JSON.stringify(expectedUi)+ || sourcePlan.full || stablePlanJson(plan.packages) !== stablePlanJson(sourcePlan.packages)+ || !plan.jobs.test_linux || plan.jobs.static_checks || plan.jobs.test_windows+ || plan.jobs.e2e || plan.jobs.lighthouse || plan.jobs.resizable_panels_compat+ || plan.jobs.ui_e2e !== (expectedUi.length > 0) || plan.jobs.merge_reports !== (expectedUi.length > 0)) {+ throw new Error("main smoke jobs must execute the complete selected behavior checks")+ }+ }if (typeof plan.compatibility?.resizable_panels !== "boolean") {throw new Error("execution plan resizable-panels compatibility flag is required")}@@ -512,28 +664,48 @@ export function validateExecutionPlan(plan, options = {}) {for (const suite of plan.suites.linux) {if (!manifest.suites.linux.includes(suite)) throw new Error(`unknown execution-plan linux suite: ${suite}`)}- const inventory = discoverE2eSpecs(resolve(ROOT, manifest.ui.root))for (const spec of plan.ui.specs) {- if (spec !== manifest.ui.all && !inventory.includes(spec)) throw new Error(`unknown execution-plan UI spec: ${spec}`)- }+ if (spec !== manifest.ui.all && (!spec.endsWith(".spec.ts") || spec.includes("..") || !statSync(resolve(ROOT, manifest.ui.root, spec), { throwIfNoEntry: false })?.isFile())) throw new Error(`unknown execution-plan UI spec: ${spec}`)+ }+ if (plan.ui.native) validateNativeUiFacts(plan.ui.native, plan.ui.specs)+ if (!plan.jobs.ui_e2e && plan.ui.native) throw new Error("inactive UI plan contains native partitions")+ const expected = buildExecutionPlan(plan.changes, {+ manifest,+ nativeTasks: plan.native_tasks,+ nativeUi: plan.ui.native,+ baseSha: plan.base_sha,+ headSha: plan.head_sha,+ forceFull: plan.full_reason === "forced",+ fallbackReason: plan.full_reason === "classifier_error" ? plan.fallback_detail || "classifier failure" : "",+ mainSmoke: plan.execution_mode === "main-smoke",+ diagnosticOnly: plan.diagnostic_only,+ resizablePanelsChanged: plan.compatibility.resizable_panels,+ })+ if (stablePlanJson(expected) !== stablePlanJson(plan)) throw new Error("execution plan projections do not match native tasks and event policy")return plan}export function projectPlan(plan) {validateExecutionPlan(plan)- const uiSpecs = plan.ui.specs.includes("all") ? discoverE2eSpecs() : plan.ui.specs- const e2eMatrix = uiSpecs.length > 0 ? createE2eMatrix(uiSpecs) : { include: [] }+ if (plan.jobs.ui_e2e && !plan.ui.native) throw new Error("UI execution requires native partitions")+ const e2eMatrix = plan.ui.native ? createE2eMatrix(plan.ui.native) : { include: [] }+ const manifest = loadScopeManifest()+ e2eMatrix.include = e2eMatrix.include.map(entry => ({ ...entry, zones: browserZonesForSpecs(entry.specs, manifest) }))return {- execution_plan: stablePlanJson(plan),plan_hash: plan.plan_hash,plan_schema_version: String(plan.schema_version),full: String(plan.full),+ execution_mode: plan.execution_mode,base_sha: plan.base_sha,head_sha: plan.head_sha,auth_only: String(plan.auth_only),blog_only: String(plan.blog_only),run_auth_build: String(plan.jobs.auth_build),run_blog_build: String(plan.jobs.blog_build),+ run_worker_build: String(plan.jobs.worker_build),+ worker_zones: JSON.stringify(plan.artifacts.worker_zones),+ browser_zones: JSON.stringify(plan.ui.zones),+ worker_build_image: resolvePlaywrightImage(),run_code_checks: String(plan.jobs.static_checks || plan.jobs.test_linux),run_static_checks: String(plan.jobs.static_checks),run_linux: String(plan.jobs.test_linux),@@ -545,10 +717,16 @@ export function projectPlan(plan) {run_lighthouse: String(plan.jobs.lighthouse),run_knip: String(plan.suites.knip.length > 0),run_app_packed_artifact: String(plan.jobs.app_packed_artifact),+ static_tasks: JSON.stringify(plan.suites.static_tasks),+ build_tasks: JSON.stringify(plan.suites.build_tasks),+ knip_tasks: JSON.stringify(plan.suites.knip_tasks),+ unit_tasks: JSON.stringify(plan.suites.unit_tasks),+ unit_build_tasks: JSON.stringify(plan.suites.unit_build_tasks),static_packages: JSON.stringify(plan.suites.static),build_packages: JSON.stringify(plan.suites.build),knip_packages: JSON.stringify(plan.suites.knip),unit_test_roots: JSON.stringify(plan.suites.unit),+ smoke_test_files: JSON.stringify(plan.suites.smoke),windows_suites: JSON.stringify(plan.suites.windows),integration_suites: JSON.stringify(plan.suites.integration),linux_suites: JSON.stringify(plan.suites.linux),@@ -627,8 +805,8 @@ function parseArgs(argv) {args.forceFull = truecontinue}- if (arg === "--full-unless-benchmark-only") {- args.fullUnlessBenchmarkOnly = true+ if (arg === "--main-smoke") {+ args.mainSmoke = truecontinue}if (arg === "--diagnostic-only") {@@ -670,9 +848,10 @@ export function runCli(argv) {baseSha: args.base || "",headSha: args.head || "",forceFull: args.forceFull,- fullUnlessBenchmarkOnly: args.fullUnlessBenchmarkOnly,+ mainSmoke: args.mainSmoke,diagnosticOnly: args.diagnosticOnly,resizablePanelsChanged: resizablePanelsVersionChanged(args),+ nativeTasks: queryNativeTasks({ baseSha: args.base, headSha: args.head }),})} catch (error) {fallbackReason = error instanceof Error ? error.message : String(error)@@ -681,10 +860,17 @@ export function runCli(argv) {headSha: args.head || "",forceFull: true,fallbackReason,+ nativeTasks: queryNativeTasks(),diagnosticOnly: args.diagnosticOnly,resizablePanelsChanged: true,})}+ if (plan.jobs.ui_e2e) {+ const nativeUi = queryNativeUiFacts(plan.ui.specs, { shardCount: args.uiShards })+ const { plan_hash: _ignored, ...unsigned } = plan+ unsigned.ui = { ...plan.ui, native: nativeUi }+ plan = { ...unsigned, plan_hash: hashPlan(unsigned) }+ }validateExecutionPlan(plan)const projection = projectPlan(plan)if (args.output) writeOutputs(args.output, projection)diff --git a/scripts/ci/changed-scopes.test.ts b/scripts/ci/changed-scopes.test.tsindex 9db96b731..e351fe39e 100644--- a/scripts/ci/changed-scopes.test.ts+++ b/scripts/ci/changed-scopes.test.ts@@ -1,21 +1,130 @@import { execFileSync } from "node:child_process"import { createHash } from "node:crypto"-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs"import { tmpdir } from "node:os"-import { join } from "node:path"-import { describe, expect, it, vi } from "vitest"+import { dirname, join, resolve } from "node:path"+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"import {- buildExecutionPlan,- classifyPaths,+ buildExecutionPlan as createExecutionPlan,+ queryNativeTasks,loadScopeManifest,packageDependencyVersionChanged,parseNameStatus,projectPlan,- runCli,stablePlanJson,validateExecutionPlan,validateScopeManifest,} from "./changed-scopes.mjs"+import { queryNativeUiFacts, validateNativeUiFacts } from "./e2e-shards.mjs"++let nativeFixture: { root: string; base: string; compatibilityBase: string } | undefined+let nativeInventory: ReturnType<typeof queryNativeTasks>["inventory"]++function nativeRepository() {+ if (nativeFixture) return nativeFixture+ const source = resolve(import.meta.dirname, "../..")+ const { root } = workspaceFixture()+ const paths = execFileSync("git", ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], { cwd: source, encoding: "utf8", env: cleanGitEnvironment() }).split("\0").filter(Boolean)+ for (const file of paths) {+ if (!existsSync(join(source, file))) continue+ const target = join(root, file)+ mkdirSync(dirname(target), { recursive: true })+ const metadata = /(?:^|\/)package\.json$/.test(file) || /\.json$/.test(file)+ || ["package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml", "turbo.json", ".gitignore", "codecov.yml"].includes(file)+ || /^scripts\/ci\/.*\.mjs$/.test(file)+ writeFileSync(target, metadata ? readFileSync(join(source, file)) : "")+ }+ symlinkSync(join(source, "node_modules"), join(root, "node_modules"), process.platform === "win32" ? "junction" : "dir")+ symlinkSync(join(source, "src/web/node_modules"), join(root, "src/web/node_modules"), process.platform === "win32" ? "junction" : "dir")+ writeFileSync(join(root, "src/web/playwright.config.ts"), 'export default { testDir: "./src/test/e2e-ui", fullyParallel: false, workers: 1, retries: 0, projects: [{ name: "chromium" }] }')+ for (const file of paths.filter(path => /^src\/web\/src\/test\/e2e-ui\/.+\.spec\.ts$/.test(path))) {+ if (existsSync(join(source, file))) writeFileSync(join(root, file), 'import { test } from "@playwright/test"; test(' + JSON.stringify(file) + ', () => {})')+ }+ const git = (...args: string[]) => execFileSync("git", args, { cwd: root, encoding: "utf8", env: cleanGitEnvironment() })+ git("init", "--quiet")+ writeFileSync(join(root, ".git/info/exclude"), "/node_modules\n/src/web/node_modules\n")+ git("config", "user.name", "Native task fixture")+ git("config", "user.email", "[email protected]")+ git("config", "commit.gpgsign", "false")+ mkdirSync(join(root, "fixture-hooks"))+ git("config", "core.hooksPath", join(root, "fixture-hooks"))+ git("add", ".")+ git("commit", "--quiet", "-m", "native task input baseline")+ const base = git("rev-parse", "HEAD").trim()+ nativeFixture = { root, base, compatibilityBase: base }+ const packagePath = join(root, "src/web/package.json")+ const pkg = JSON.parse(readFileSync(packagePath, "utf8"))+ pkg.dependencies["react-resizable-panels"] = "4.12.3"+ writeFileSync(packagePath, JSON.stringify(pkg))+ git("add", "src/web/package.json")+ git("commit", "--quiet", "-m", "baseline compatibility version")+ nativeFixture.compatibilityBase = git("rev-parse", "HEAD").trim()+ git("reset", "--hard", "--quiet", base)+ nativeInventory = queryNativeTasks({ root, baseSha: base, headSha: base }).inventory+ return nativeFixture+}++const nativeObservations = new Map<string, ReturnType<typeof queryNativeTasks>>()+function nativeFacts(changes) {+ const observationKey = JSON.stringify(changes)+ if (nativeObservations.has(observationKey)) return structuredClone(nativeObservations.get(observationKey))+ const { root, base } = nativeRepository()+ const saved = new Map<string, Buffer | null>()+ try {+ for (const change of changes) {+ for (const original of [change.old_path, change.path].filter(Boolean)) {+ const file = resolve(root, String(original).replaceAll("\\", "/"))+ if (!file.startsWith(root + "/")+ || ["turbo.json", "pnpm-lock.yaml", "pnpm-workspace.yaml"].some(name => file === join(root, name))) continue+ if (!saved.has(file)) saved.set(file, existsSync(file) ? readFileSync(file) : null)+ if (original === change.old_path || change.status?.startsWith("D")) {+ if (existsSync(file)) unlinkSync(file)+ } else {+ mkdirSync(dirname(file), { recursive: true })+ writeFileSync(file, file.endsWith("/package.json") ? JSON.stringify({ ...JSON.parse(readFileSync(file, "utf8")), nativeFixtureChange: true }) : "native task fixture changed bytes\n")+ }+ }+ }+ const facts = queryNativeTasks({ root, baseSha: base, headSha: base })+ nativeObservations.set(observationKey, structuredClone(facts))+ return facts+ } finally {+ for (const [file, bytes] of saved) {+ if (bytes) writeFileSync(file, bytes)+ else if (existsSync(file)) unlinkSync(file)+ }+ }+}++// Policy projections share one real observation of this immutable one-case-per-file,+// single-partition fixture. Native selection and CLI integration tests below still+// invoke the collector independently; this helper does not predict native shards.+let browserFacts: ReturnType<typeof queryNativeUiFacts>+function buildExecutionPlan(changes, options = {}) {+ const settings = { nativeTasks: nativeFacts(changes), ...options }+ const draft = createExecutionPlan(changes, settings)+ if (!draft.jobs.ui_e2e) return draft+ const selection = [...draft.ui.specs].sort()+ const files = selection[0] === "all" ? browserFacts.files : selection+ const cases = browserFacts.cases.filter(test => files.includes(test.file))+ const nativeUi = validateNativeUiFacts({+ ...browserFacts,+ selection,+ files,+ cases,+ shards: [{ current: 1, total: 1, files, cases: cases.map(test => test.key) }],+ }, draft.ui.specs)+ return createExecutionPlan(changes, { ...settings, nativeUi })+}++function classifyPaths(paths, options = {}) {+ return buildExecutionPlan(paths.map(path => ({ status: "M", path })), options)+}++beforeAll(() => {+ browserFacts = queryNativeUiFacts(["all"], { root: nativeRepository().root, shardCount: 1 })+})+afterAll(() => { if (nativeFixture) rmSync(nativeFixture.root, { recursive: true, force: true }) })const sha = (character: string) => character.repeat(40)const modified = (...paths: string[]) => paths.map((path) => ({ status: "M", path }))@@ -57,6 +166,10 @@ function workspaceFixture({readFileSync(join(scopePackage.root, "package.json"), "utf8"),)}+ for (const path of manifest.smoke_tests) {+ mkdirSync(dirname(join(root, path)), { recursive: true })+ writeFileSync(join(root, path), "")+ }return { manifest, root }}@@ -72,46 +185,202 @@ function cleanGitEnvironment() {return environment}+function runFixtureCli(args: string[], root = nativeRepository().root) {+ return execFileSync(process.execPath, [realpathSync(join(root, "scripts/ci/changed-scopes.mjs")), ...args], {+ cwd: root, env: cleanGitEnvironment(), encoding: "utf8", maxBuffer: 4 * 1024 * 1024,+ })+}+function gitDiffFixture(changedPath = "src/app/src/commands/inbox.ts") {+ const baseline = nativeRepository()const root = mkdtempSync(join(tmpdir(), "alook-ci-git-"))- const runGit = (...args: string[]) => execFileSync("git", args, {- cwd: root,- env: cleanGitEnvironment(),- stdio: "ignore",- })- const commit = (message: string) => runGit(- "-c", "user.name=Alook CI",- "-c", "[email protected]",- "-c", "commit.gpgsign=false",- "commit", "--quiet", "-m", message,- )-- runGit("init", "--quiet")- writeFileSync(join(root, "README.md"), "baseline\n")- mkdirSync(join(root, "src/web"), { recursive: true })- writeFileSync(- join(root, "src/web/package.json"),- JSON.stringify({ dependencies: { "react-resizable-panels": "4.12.3" } }),- )- runGit("add", "README.md", "src/web/package.json")- commit("baseline")-+ execFileSync("git", ["worktree", "add", "--quiet", "--detach", root, baseline.compatibilityBase], { cwd: baseline.root, env: cleanGitEnvironment(), stdio: "ignore" })+ if (!existsSync(join(root, "node_modules"))) symlinkSync(resolve(import.meta.dirname, "../../node_modules"), join(root, "node_modules"), process.platform === "win32" ? "junction" : "dir")+ symlinkSync(resolve(import.meta.dirname, "../../src/web/node_modules"), join(root, "src/web/node_modules"), process.platform === "win32" ? "junction" : "dir")+ const runGit = (...args: string[]) => execFileSync("git", args, { cwd: root, env: cleanGitEnvironment(), stdio: "ignore" })+ const commit = (message: string) => runGit("-c", "user.name=Alook CI", "-c", "[email protected]",+ "-c", "commit.gpgsign=false", "commit", "--quiet", "-m", message)+ const packagePath = join(root, "src/web/package.json")+ const pkg = JSON.parse(readFileSync(packagePath, "utf8"))if (changedPath === "src/web/package.json") {- writeFileSync(- join(root, changedPath),- JSON.stringify({ dependencies: { "react-resizable-panels": "4.12.4" } }),- )+ pkg.dependencies["react-resizable-panels"] = "4.12.4"+ writeFileSync(packagePath, JSON.stringify(pkg))} else {- mkdirSync(join(root, changedPath.split("/").slice(0, -1).join("/")), { recursive: true })- writeFileSync(join(root, changedPath), "export const fixture = true\n")+ mkdirSync(dirname(join(root, changedPath)), { recursive: true })+ writeFileSync(join(root, changedPath), "export const fixture = true\\n")}runGit("add", changedPath)- commit("change app")-- return { changedPath, root }+ commit("changed input")+ const gitDir = execFileSync("git", ["rev-parse", "--absolute-git-dir"], { cwd: root, env: cleanGitEnvironment(), encoding: "utf8" }).trim()+ return { changedPath, root, gitDir, cleanup: () => execFileSync("git", ["worktree", "remove", "--force", root], { cwd: baseline.root, env: cleanGitEnvironment(), stdio: "ignore" }) }}describe("canonical execution plan", () => {+ it.each([+ {+ path: "src/web/src/hooks/community/use-friends.ts",+ owner: "@alook/web",+ unitRoot: "src/web",+ consumers: ["04-dm.spec.ts", "07-invite.spec.ts"],+ },+ {+ path: "src/web/src/hooks/community/community-ws/presence-machine-events.ts",+ owner: "@alook/web",+ unitRoot: "src/web",+ consumers: ["07-invite.spec.ts", "30-bot-profile-bounds.spec.ts"],+ },+ {+ path: "src/ws-do/src/ws-durable/presence-typing.ts",+ owner: "@alook/ws-do",+ unitRoot: "src/ws-do",+ consumers: ["07-invite.spec.ts"],+ },+ ])("keeps cross-feature browser consumers for $path through the existing full UI fallback", ({ path, owner, unitRoot, consumers }) => {+ const result = plan([path])+ expect(result.full).toBe(false)+ expect(result.execution_mode).toBe("affected")+ expect(result.packages.direct).toEqual([owner])+ expect(result.suites.unit).toContain(unitRoot)+ expect(result.ui.specs).toEqual(["all"])+ const matrix = JSON.parse(projectPlan(result).e2e_matrix)+ expect(matrix.include.flatMap((entry) => entry.specs)).toEqual(expect.arrayContaining(+ consumers.map((spec) => `src/test/e2e-ui/${spec}`),+ ))+ expect(plan(["src/web/src/components/community/shell/user-bar.tsx", path]).ui.specs).toEqual(["all"])+ const main = plan([path], { mainSmoke: true })+ expect(main.execution_mode).toBe("main-smoke")+ expect(main.ui.specs).toEqual([...loadScopeManifest().ui.contracts.smoke].sort())+ })++ it.each([+ ["src/web/src/components/authenticated-context-menu-boundary.tsx", "54-authenticated-context-menu-policy.spec.ts"],+ ["src/web/src/app/(auth)/sign-in/sign-in-client.tsx", "10-eject-nav-auth.spec.ts"],+ ["src/web/src/components/download/download-current-platform.tsx", "19-marketing-seo.spec.ts"],+ ["src/web/src/app/(home)/page.tsx", "19-marketing-seo.spec.ts"],+ ["src/web/src/app/og/route.tsx", "51-share-image-assets.spec.ts"],+ ["src/web/src/app/_og/render-og-image.tsx", "51-share-image-assets.spec.ts"],+ ["src/web/src/app/api/community/billing/route.ts", "64-billing-contact.spec.ts"],+ ["src/web/src/hooks/community/use-billing.ts", "64-billing-contact.spec.ts"],+ ["src/web/src/app/contact/page.tsx", "64-billing-contact.spec.ts"],+ ])("maps real feature path %s to its existing HTTP/browser journey", (path, consumer) => {+ const result = plan([path])+ expect(result.full).toBe(false)+ expect(result.ui.specs).not.toContain("all")+ expect(result.ui.specs).toContain(consumer)+ expect(JSON.parse(projectPlan(result).e2e_matrix).include.flatMap(entry => entry.specs)).toContain("src/test/e2e-ui/" + consumer)+ expect(plan([path, "src/web/src/lib/billing/service.ts"]).ui.specs).toEqual(["all"])+ })++ it("selects the real invite journey for the localized invitation dialog", () => {+ const result = plan(["src/web/src/components/community/social/invite-dialog.tsx"])+ expect(result.full).toBe(false)+ expect(result.ui.specs).not.toContain("all")+ expect(result.ui.specs).toContain("07-invite.spec.ts")+ expect(JSON.parse(projectPlan(result).e2e_matrix).include.flatMap((entry) => entry.specs))+ .toContain("src/test/e2e-ui/07-invite.spec.ts")+ })++ it("unions localized UI features with key journeys without selecting unrelated browser groups", () => {+ const source = "src/web/src/components/community/shell/user-bar.tsx"+ const result = plan([source])+ expect(result.full).toBe(false)+ expect(result.ui.specs).toEqual(expect.arrayContaining([+ "01-auth.spec.ts", "03-realtime-multiuser.spec.ts", "06-channel-member-admin.spec.ts",+ "50-daemon-update-notice.spec.ts", "53-mobile-inbox-surface.spec.ts", "60-desktop-default-user-bar-width.spec.ts",+ ]))+ expect(result.ui.specs).not.toContain("all")+ expect(result.ui.specs.some(spec => spec.startsWith("55-"))).toBe(false)+ const mixed = plan([source, "src/web/src/components/home/landing-workspace-skeleton.tsx"])+ expect(mixed.ui.specs).toEqual(expect.arrayContaining([+ ...result.ui.specs, "19-marketing-seo.spec.ts", "51-share-image-assets.spec.ts",+ ]))+ expect(new Set(mixed.ui.specs).size).toBe(mixed.ui.specs.length)+ expect(projectPlan(mixed).e2e_matrix).not.toContain('"all"')+ })++ it("keeps direct browser edits and expands removed specs, shared helpers and unclassified runtime inputs", () => {+ const spec = "src/web/src/test/e2e-ui/64-billing-contact.spec.ts"+ const nativeTasks = nativeFacts(modified(spec))+ const uiPlan = (changes) => createExecutionPlan(changes, { nativeTasks })+ expect(uiPlan(modified(spec)).ui.specs).toContain("64-billing-contact.spec.ts")+ expect(uiPlan(modified("src/web/src/components/community/shell/user-bar.test.ts")).ui.specs).toEqual([])+ for (const path of [+ "src/web/src/test/e2e-ui/_fixtures/actions.ts",+ "src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts",+ "src/web/src/lib/community/community-db/sync.ts",+ "src/web/src/components/community/messages/message-list.tsx",+ "src/web/src/app/api/community/channels/[id]/messages/route.ts",+ "src/web/src/app/globals.css",+ "src/shared/src/schema.ts",+ ]) expect(uiPlan(modified(path)).ui.specs, path).toEqual(["all"])+ const removed = uiPlan([{ status: "D", path: "src/web/src/test/e2e-ui/retired.spec.ts" }])+ expect(removed.ui.specs).toEqual(["all"])+ const renamed = uiPlan([{ status: "R100", old_path: spec, path: "src/web/src/lib/moved-runtime.ts" }])+ expect(renamed.ui.specs).toEqual(["all"])+ })++ it("starts Blog for the native partition containing66 and keeps Web-only consumers isolated", () => {+ const blog = plan(["src/web/src/test/e2e-ui/66-public-static-resource-cache.spec.ts"])+ expect(blog.ui.zones).toEqual(["web", "blog"])+ expect(JSON.parse(projectPlan(blog).e2e_matrix).include).toEqual([+ expect.objectContaining({ specs: expect.arrayContaining(["src/test/e2e-ui/66-public-static-resource-cache.spec.ts"]), zones: ["web", "blog"] }),+ ])+ const web = plan(["src/web/src/test/e2e-ui/64-billing-contact.spec.ts"])+ expect(web.ui.zones).toEqual(["web"])+ expect(JSON.parse(projectPlan(web).e2e_matrix).include).toEqual([+ expect.objectContaining({ specs: expect.arrayContaining(["src/test/e2e-ui/64-billing-contact.spec.ts"]), zones: ["web"] }),+ ])+ })++ it("runs the complete small main smoke set without repeating full package or platform suites", () => {+ const result = plan(["src/web/src/components/community/shell/user-bar.tsx"], { mainSmoke: true })+ const manifest = loadScopeManifest()+ expect(result.execution_mode).toBe("main-smoke")+ expect(result.suites.smoke).toEqual(manifest.smoke_tests)+ for (const kind of ["static", "build", "knip", "unit", "windows", "integration", "linux"]) {+ expect(result.suites[kind], kind).toEqual([])+ }+ expect(result.ui.specs).toEqual([...manifest.ui.contracts.smoke].sort())+ expect(result.jobs.test_linux).toBe(true)+ expect(result.jobs.ui_e2e).toBe(true)+ expect(result.jobs.e2e).toBe(false)+ expect(result.jobs.lighthouse).toBe(false)+ expect(result.coverage.targets).toEqual([])+ expect(result.coverage.required_changed_files).toEqual([])+ expect(validateExecutionPlan(result)).toEqual(result)+ expect(projectPlan(result).smoke_test_files).toBe(JSON.stringify(manifest.smoke_tests))+ expect(plan(["src/web/src/components/community/shell/user-bar.test.ts"], { mainSmoke: true }).ui.specs).toEqual([])+ expect(plan(["src/web/blog/src/content/example.mdx"], { mainSmoke: true }).ui.specs).toEqual(manifest.ui.contracts.blog)+ })++ it("preserves full fallback and explicit release/manual regression instead of labelling it smoke", () => {+ for (const options of [{ forceFull: true }, { mainSmoke: true, fallbackReason: "diff failed" }]) {+ const result = plan(["src/web/src/components/home/hero.tsx"], options)+ expect(result.execution_mode).toBe("full")+ expect(result.ui.specs).toEqual(["all"])+ expect(result.suites.integration).toContain("web")+ expect(result.suites.smoke).toEqual([])+ }+ for (const path of ["unknown/runtime.ts", "scripts/ci/changed-scopes.mjs", "pnpm-lock.yaml"]) {+ expect(plan([path], { mainSmoke: true }).execution_mode).toBe("full")+ }+ })++ it("rejects a correctly rehashed plan that drops smoke or claims an inconsistent execution mode", () => {+ const original = plan(["src/web/src/components/home/hero.tsx"], { mainSmoke: true })+ const dropped = structuredClone(original)+ dropped.suites.smoke.pop()+ expect(() => validateExecutionPlan(resignPlan(dropped))).toThrow("complete smoke set")+ const wrongMode = { ...original, execution_mode: "full" }+ expect(() => validateExecutionPlan(resignPlan(wrongMode))).toThrow("mode")+ const unknown = structuredClone(original)+ unknown.suites.smoke.push("unknown.test.ts")+ expect(() => validateExecutionPlan(resignPlan(unknown))).toThrow("smoke tests")+ const skipped = structuredClone(original)+ skipped.jobs.test_linux = false+ expect(() => validateExecutionPlan(resignPlan(skipped))).toThrow("complete selected behavior")+ })+it("keeps benchmark-only changes out of product jobs while retaining diff evidence", () => {const changes = [{ status: "A", path: "src/benchmark/package.json" },@@ -131,17 +400,22 @@ describe("canonical execution plan", () => {expect(validateExecutionPlan(result)).toEqual(result)})- it("preserves existing product contracts when benchmark changes are mixed in", () => {- for (const product of ["src/app/src/commands/inbox.ts", "src/daemon/src/index.ts", "src/web/src/app/page.tsx", "src/web/auth/index.ts", "src/web/blog/src/app/page.tsx", "src/web/blog/src/content/example.mdx", "src/shared/src/schema.ts"]) {- const expected = plan([product])- const mixed = plan([product, "src/benchmark/src/runner.mjs"])- for (const field of ["change_class", "full", "packages", "suites", "jobs", "coverage", "ui", "auth_only", "blog_only"]) expect(mixed[field]).toEqual(expected[field])- }- for (const [old_path, path] of [["src/web/auth/index.ts", "src/benchmark/index.ts"], ["src/benchmark/index.ts", "src/web/auth/index.ts"]]) {- const result = buildExecutionPlan([{ status: "R100", old_path, path }])- expect(result.jobs).toEqual(plan(["src/web/auth/index.ts"]).jobs)- expect(result.paths).toEqual(["src/benchmark/index.ts", "src/web/auth/index.ts"])- }+ it.each([+ "src/app/src/commands/inbox.ts", "src/daemon/src/index.ts", "src/web/src/app/page.tsx",+ "src/web/auth/index.ts", "src/web/blog/src/app/page.tsx", "src/web/blog/src/content/example.mdx", "src/shared/src/schema.ts",+ ])("preserves the product contract for %s when benchmark changes are mixed in", (product) => {+ const expected = plan([product])+ const mixed = plan([product, "src/benchmark/src/runner.mjs"])+ for (const field of ["change_class", "full", "packages", "suites", "jobs", "coverage", "ui", "auth_only", "blog_only"]) expect(mixed[field]).toEqual(expected[field])+ })++ it.each([+ ["src/web/auth/index.ts", "src/benchmark/index.ts"],+ ["src/benchmark/index.ts", "src/web/auth/index.ts"],+ ])("preserves both sides of a product/benchmark rename from %s to %s", (old_path, path) => {+ const result = buildExecutionPlan([{ status: "R100", old_path, path }])+ expect(result.jobs).toEqual(plan(["src/web/auth/index.ts"]).jobs)+ expect(result.paths).toEqual(["src/benchmark/index.ts", "src/web/auth/index.ts"])})it("keeps unknown, policy, empty and explicit full changes fail-closed", () => {@@ -149,11 +423,11 @@ describe("canonical execution plan", () => {expect(plan([]).full).toBe(true)expect(plan(["src/benchmark/src/runner.mjs"], { forceFull: true }).full).toBe(true)expect(plan(["src/benchmark/src/runner.mjs"], { fallbackReason: "diff failed" }).full).toBe(true)- expect(plan(["src/benchmark/src/runner.mjs"], { fullUnlessBenchmarkOnly: true }).full).toBe(false)- for (const paths of [[], ["README.md"], ["src/web/auth/index.ts", "src/benchmark/src/runner.mjs"]]) expect(plan(paths, { fullUnlessBenchmarkOnly: true }).full).toBe(true)+ expect(plan(["src/benchmark/src/runner.mjs"], { mainSmoke: true }).full).toBe(false)+ expect(plan(["README.md"], { mainSmoke: true }).suites.smoke).toEqual([])})- it("routes Blog runtime through the complete Web contract and only UI spec 54", () => {+ it("routes Blog runtime through its independent tasks and cross-zone consumers", () => {const result = plan(["src/web/blog/src/app/page.tsx"])expect(result.change_class).toBe("blog")@@ -162,7 +436,7 @@ describe("canonical execution plan", () => {expect(result.suites.unit).toEqual(["src/web"])expect(result.coverage.targets).toEqual(["web"])expect(result.coverage.include_roots).toEqual(["src/web/**/*.{ts,tsx,js,jsx}"])- expect(result.ui.specs).toEqual(["54-blog-multizone.spec.ts"])+ expect(result.ui.specs).toEqual(["54-blog-multizone.spec.ts", "66-public-static-resource-cache.spec.ts"])expect(result.suites.integration).toEqual([])expect(result.suites.windows).toEqual([])expect(result.jobs.blog_build).toBe(true)@@ -170,7 +444,7 @@ describe("canonical execution plan", () => {expect(result.jobs.app_packed_artifact).toBe(false)})- it("keeps Blog content on build and its cross-worker contract without package coverage", () => {+ it("selects Blog unit tasks and its cross-worker contract for content", () => {const result = plan(["src/web/blog/src/content/example.mdx","src/web/blog/public/blog/example/hero.webp",@@ -179,10 +453,12 @@ describe("canonical execution plan", () => {expect(result.change_class).toBe("blog")expect(result.blog_only).toBe(true)expect(result.packages.direct).toEqual(["@alook/web"])- expect(result.packages.affected).toEqual([])- expect(result.suites.unit).toEqual([])- expect(result.coverage.include_roots).toEqual([])- expect(result.ui.specs).toEqual(["54-blog-multizone.spec.ts"])+ expect(result.packages.affected).toEqual(["@alook/web"])+ expect(result.suites.unit).toEqual(["src/web"])+ expect(result.suites.unit_tasks).toContain("@alook/web#test:blog")+ expect(result.suites.unit_tasks).not.toContain("@alook/web#test")+ expect(result.coverage.include_roots).toEqual(["src/web/**/*.{ts,tsx,js,jsx}"])+ expect(result.ui.specs).toEqual(["54-blog-multizone.spec.ts", "66-public-static-resource-cache.spec.ts"])expect(result.jobs.blog_build).toBe(true)})@@ -206,7 +482,7 @@ describe("canonical execution plan", () => {it("selects the active app package without retired CLI suites", () => {const result = plan(["src/app/src/commands/inbox.ts"])expect(result.change_class).toBe("package")- expect(result.packages.affected).toEqual(["@alook/app"])+ expect(result.packages.affected).toEqual(["@alook/agent-driver", "@alook/app", "@alook/daemon"])expect(result.suites.static).toEqual(["@alook/app"])expect(result.suites.unit).toEqual(["src/app"])expect(result.suites.integration).toEqual([])@@ -245,11 +521,12 @@ describe("canonical execution plan", () => {expect(canonicalized.suites.integration).toEqual(["daemon"])})- it("expands shared changes through the complete workspace dependent closure", () => {+ it("uses native shared task owners and their declared build prerequisites", () => {const result = plan(["src/shared/src/schema.ts"])expect(result.change_class).toBe("shared")expect(result.packages.affected).toEqual([+ "@alook/agent-driver","@alook/app","@alook/daemon","@alook/email-worker",@@ -322,7 +599,6 @@ describe("canonical execution plan", () => {expect(stablePlanJson(first)).toBe(stablePlanJson(second))expect(validateExecutionPlan(first)).toEqual(first)const projection = projectPlan(first)- expect(JSON.parse(projection.execution_plan)).toEqual(first)expect(projection.plan_hash).toBe(first.plan_hash)expect(JSON.parse(projection.static_packages)).toEqual(first.suites.static)expect(JSON.parse(projection.integration_suites)).toEqual(first.suites.integration)@@ -358,7 +634,7 @@ describe("canonical execution plan", () => {it("rejects every stale identifier in an otherwise authentic signed plan", () => {const current = plan(["src/shared/src/schema.ts"])- expect(() => validateExecutionPlan({ ...current, schema_version: 2 }))+ expect(() => validateExecutionPlan({ ...current, schema_version: current.schema_version + 1 })).toThrow("schema/policy")for (const [section, key, expected] of [@@ -416,6 +692,9 @@ describe("coverage name-status contract", () => {})it("requires only files selected by the actual coverage globs", () => {+ const coveragePlan = (path: string) => createExecutionPlan(modified(path), {+ forceFull: true, nativeTasks: { inventory: nativeInventory, affected: nativeInventory },+ })for (const path of ["src/app/scripts/app-packed-artifact.mjs","src/app/scripts/bundle-daemon.mjs",@@ -426,10 +705,10 @@ describe("coverage name-status contract", () => {"src/web/vitest.workspace.config.ts","src/web/src/components/community/bots/bot-list-types.ts",]) {- expect(plan([path]).coverage.required_changed_files).toEqual([])+ expect(coveragePlan(path).coverage.required_changed_files).toEqual([])}- expect(plan(["scripts/ci/changed-scopes.mjs"]).coverage.required_changed_files)+ expect(coveragePlan("scripts/ci/changed-scopes.mjs").coverage.required_changed_files).toEqual(["scripts/ci/changed-scopes.mjs"])})@@ -439,7 +718,7 @@ describe("coverage name-status contract", () => {"src/web/src/lib/runtime-lookalike.config.ts",])- expect(result.packages.affected).toEqual(["@alook/web"])+ expect(result.packages.affected).toEqual(["@alook/app", "@alook/web"])expect(result.coverage.targets).toEqual(["web"])expect(result.coverage.required_changed_files).toEqual(["src/web/src/lib/runtime-lookalike.config.ts",@@ -485,17 +764,34 @@ describe("coverage name-status contract", () => {})describe("scope manifest", () => {+ it("rejects broken smoke and feature definitions before selecting jobs", () => {+ const original = loadScopeManifest()+ const noFallback = structuredClone(original)+ noFallback.ui.full_prefixes = []+ expect(() => validateScopeManifest(noFallback)).toThrow("full-scope prefixes")+ const missingSpec = structuredClone(original)+ missingSpec.ui.groups[0].specs.push("missing.spec.ts")+ expect(() => validateScopeManifest(missingSpec)).toThrow("unknown UI spec")+ const duplicatedGroup = structuredClone(original)+ duplicatedGroup.ui.groups.push(structuredClone(duplicatedGroup.ui.groups[0]))+ expect(() => validateScopeManifest(duplicatedGroup)).toThrow("group names")+ const outside = structuredClone(original)+ outside.smoke_tests.push("../outside.test.ts")+ expect(() => validateScopeManifest(outside)).toThrow("main smoke tests")+ const missingSmoke = structuredClone(original)+ missingSmoke.smoke_tests.push("src/web/src/missing-main-smoke.test.ts")+ expect(() => validateScopeManifest(missingSmoke)).toThrow("missing main smoke test")+ })it("matches workspace package manifests and the complete UI inventory", () => {const manifest = loadScopeManifest()expect(() => validateScopeManifest(manifest)).not.toThrow()- expect(manifest.schema_version).toBe(1)- expect(manifest.ui.contracts.blog).toEqual(["54-blog-multizone.spec.ts"])+ expect(manifest.schema_version).toBe(2)})it("rejects invalid versions, registries, packages, paths, targets, and specs", () => {const manifest = loadScopeManifest()- expect(() => validateScopeManifest({ ...manifest, schema_version: 2 }))+ expect(() => validateScopeManifest({ ...manifest, schema_version: manifest.schema_version + 1 })).toThrow("schema/policy")expect(() => validateScopeManifest({ ...manifest, packages: [] })).toThrow("packages are required")@@ -543,7 +839,7 @@ describe("scope manifest", () => {expect(() => validateScopeManifest(unknownCodecov)).toThrow("unknown Codecov target")const codecovDrift = structuredClone(manifest)- codecovDrift.codecov_targets.shared.target = 51+ codecovDrift.codecov_targets.shared.path = "src/other-shared"expect(() => validateScopeManifest(codecovDrift)).toThrow("Codecov target")expect(() => validateScopeManifest(manifest, { specs: [] })).toThrow("unknown UI spec")@@ -556,7 +852,7 @@ describe("scope manifest", () => {try {expect(() => validateScopeManifest(manifest, {root,- specs: Object.values(manifest.ui.contracts).flat(),+ specs: [...Object.values(manifest.ui.contracts).flat(), ...manifest.ui.groups.flatMap((group) => group.specs)],})).not.toThrow()} finally {rmSync(root, { recursive: true, force: true })@@ -567,12 +863,13 @@ describe("scope manifest", () => {for (const codecov of [(source: string) => source.replace(" project:", " projects:"),(source: string) => source.replace(/^ ([^:\n]+):$/m, " future:"),+ (source: string) => source.replace("informational: true", "informational: false"),]) {const { manifest, root } = workspaceFixture({ codecov })try {expect(() => validateScopeManifest(manifest, {root,- specs: Object.values(manifest.ui.contracts).flat(),+ specs: [...Object.values(manifest.ui.contracts).flat(), ...manifest.ui.groups.flatMap((group) => group.specs)],})).toThrow("codecov.yml")} finally {rmSync(root, { recursive: true, force: true })@@ -589,7 +886,7 @@ describe("scope manifest", () => {writeFileSync(packagePath, JSON.stringify(packageManifest))expect(() => validateScopeManifest(manifest, {root,- specs: Object.values(manifest.ui.contracts).flat(),+ specs: [...Object.values(manifest.ui.contracts).flat(), ...manifest.ui.groups.flatMap((group) => group.specs)],})).toThrow("declares test scope")} finally {rmSync(root, { recursive: true, force: true })@@ -598,6 +895,157 @@ describe("scope manifest", () => {})describe("compatibility and CLI fail-closed behavior", () => {+ it("keeps Blog hashes independent of generated images while retaining canonical image inputs", () => {+ const fixture = gitDiffFixture()+ const dry = () => JSON.parse(execFileSync(process.execPath, [realpathSync(join(fixture.root, "scripts/ci/run-turbo.mjs")), "run", "@alook/web#build:blog", "--dry=json"], { cwd: fixture.root, env: cleanGitEnvironment(), encoding: "utf8" })).tasks.find(task => task.taskId === "@alook/web#build:blog")+ try {+ const before = dry()+ const generated = join(fixture.root, "src/web/blog/public/blog/_generated")+ const manifest = join(fixture.root, "src/web/blog/src/lib/blog/image-assets.json")+ const canonical = Object.keys(JSON.parse(readFileSync(manifest, "utf8")))[0]!+ mkdirSync(generated, { recursive: true })+ writeFileSync(join(generated, "derived.webp"), "generated output bytes")+ writeFileSync(manifest, '{"derived":true}\n')+ expect(dry().hash).toBe(before.hash)+ writeFileSync(join(fixture.root, "src/web/blog/public", canonical), "changed canonical image bytes")+ expect(dry().hash).not.toBe(before.hash)+ } finally { fixture.cleanup() }+ })++ it.each([+ "src/web/src/lib/worker-runtime.ts",+ "src/web/src/lib/observability/trace-response.ts",+ "src/web/package.json",+ ])("selects and invalidates the App filesystem contract for %s", path => {+ const fixture = gitDiffFixture()+ const dry = () => JSON.parse(execFileSync(process.execPath, [realpathSync(join(fixture.root, "scripts/ci/run-turbo.mjs")), "run", "@alook/app#test", "--dry=json"], { cwd: fixture.root, env: cleanGitEnvironment(), encoding: "utf8" })).tasks.find(task => task.taskId === "@alook/app#test")+ try {+ const head = execFileSync("git", ["rev-parse", "HEAD"], { cwd: fixture.root, env: cleanGitEnvironment(), encoding: "utf8" }).trim()+ const before = dry()+ const file = join(fixture.root, path)+ const bytes = readFileSync(file, "utf8")+ writeFileSync(file, path.endsWith("package.json") ? JSON.stringify({ ...JSON.parse(bytes), nativeAppContractFixture: true }) : bytes + "\n// changed borrowed runtime source\n")+ const facts = queryNativeTasks({ root: fixture.root, baseSha: head, headSha: head })+ expect(facts.reason).toBeNull()+ expect(facts.affected.map(task => task.fullName)).toContain("@alook/app#test")+ expect(dry().hash).not.toBe(before.hash)+ expect(createExecutionPlan([{ status: "M", path }], { nativeTasks: facts }).suites.unit_tasks).toContain("@alook/app#test")+ } finally { fixture.cleanup() }+ })++ it("keeps an unrelated Web component outside the App filesystem task and cache", () => {+ const fixture = gitDiffFixture()+ const dry = () => JSON.parse(execFileSync(process.execPath, [realpathSync(join(fixture.root, "scripts/ci/run-turbo.mjs")), "run", "@alook/app#test", "--dry=json"], { cwd: fixture.root, env: cleanGitEnvironment(), encoding: "utf8" })).tasks.find(task => task.taskId === "@alook/app#test")+ try {+ const head = execFileSync("git", ["rev-parse", "HEAD"], { cwd: fixture.root, env: cleanGitEnvironment(), encoding: "utf8" }).trim()+ const before = dry()+ writeFileSync(join(fixture.root, "src/web/src/components/home/landing-content.ts"), "export const unrelated = true\n")+ const facts = queryNativeTasks({ root: fixture.root, baseSha: head, headSha: head })+ expect(facts.reason).toBeNull()+ expect(facts.affected.map(task => task.fullName)).not.toContain("@alook/app#test")+ expect(dry().hash).toBe(before.hash)+ } finally { fixture.cleanup() }+ })++ it("hashes the real Worker-CI telemetry release input in both builds", () => {+ const fixture = gitDiffFixture("src/web/src/lib/worker-source-input-fixture.ts")+ const previous = process.env.WORKERS_CI_COMMIT_SHA+ const dry = () => JSON.parse(execFileSync(process.execPath, [realpathSync(join(fixture.root, "scripts/ci/run-turbo.mjs")), "run", "@alook/web#build", "@alook/web#build:blog", "--dry=json"], { cwd: fixture.root, env: cleanGitEnvironment(), encoding: "utf8" })).tasks+ try {+ process.env.WORKERS_CI_COMMIT_SHA = "a".repeat(40)+ const before = dry()+ process.env.WORKERS_CI_COMMIT_SHA = "b".repeat(40)+ const after = dry()+ for (const id of ["@alook/web#build", "@alook/web#build:blog"]) {+ expect(after.find(task => task.taskId === id).hash).not.toBe(before.find(task => task.taskId === id).hash)+ }+ } finally {+ if (previous === undefined) delete process.env.WORKERS_CI_COMMIT_SHA+ else process.env.WORKERS_CI_COMMIT_SHA = previous+ fixture.cleanup()+ }+ })++ it("invalidates the driver build for root LICENSE and declares its ignored license output", () => {+ const fixture = gitDiffFixture("src/daemon/agent-driver/src/license-input-fixture.ts")+ const dry = () => JSON.parse(execFileSync(process.execPath, [realpathSync(join(fixture.root, "scripts/ci/run-turbo.mjs")), "run", "@alook/agent-driver#build", "--dry=json"], { cwd: fixture.root, env: cleanGitEnvironment(), encoding: "utf8" })).tasks.find(task => task.taskId === "@alook/agent-driver#build")+ try {+ const before = dry()+ writeFileSync(join(fixture.root, "LICENSE"), "changed root license input")+ const after = dry()+ expect(after.hash).not.toBe(before.hash)+ expect(after.outputs).toEqual(expect.arrayContaining(["dist/**", "LICENSE"]))+ } finally { fixture.cleanup() }+ })++ it("reports native conservative fallback as full instead of a successful localized query", () => {+ const fixture = gitDiffFixture("src/web/src/lib/native-fallback-fixture.ts")+ try {+ const file = join(fixture.root, "turbo.json")+ const config = JSON.parse(readFileSync(file, "utf8"))+ config.tasks["@alook/web#test"].inputs.push("!public/{sw.js,sw.js.map,community-shell/**}")+ writeFileSync(file, JSON.stringify(config))+ const git = (...args: string[]) => execFileSync("git", args, { cwd: fixture.root, env: cleanGitEnvironment(), encoding: "utf8" })+ git("add", "turbo.json")+ git("-c", "user.name=Native fallback fixture", "-c", "[email protected]", "-c", "commit.gpgsign=false", "commit", "--quiet", "-m", "native invalid glob input")+ const head = git("rev-parse", "HEAD").trim()+ const nativeTasks = queryNativeTasks({ root: fixture.root, baseSha: head, headSha: head })+ expect(nativeTasks.reason).toBe("native_affected_fallback")+ const result = createExecutionPlan([{ status: "M", path: "src/web/src/lib/native-fallback-fixture.ts" }], { baseSha: head, headSha: head, nativeTasks })+ expect(result).toMatchObject({ full: true, full_reason: "native_affected_fallback" })+ } finally { fixture.cleanup() }+ })++ it.each([+ ["pull_request", "change", "affected"],+ ["merge_group", "change", "affected"],+ ["push", "fix: localized user bar", "main-smoke"],+ ["push", "release: v0.1.64", "full"],+ ["workflow_dispatch", "change", "full"],+ ])("runs the actual workflow scope entry for %s / %s", (event, message, mode) => {+ const fixture = gitDiffFixture("src/web/src/components/community/shell/user-bar.tsx")+ try {+ const workflow = readFileSync(join(import.meta.dirname, "../../.github/workflows/ci.yml"), "utf8").replaceAll("\r\n", "\n")+ const scope = workflow.slice(workflow.indexOf("\n scope:\n"), workflow.indexOf("\n auth-build:\n"))+ const body = scope.slice(scope.indexOf(" - id: scope\n")).match(/ run: \|\n([\s\S]*?)(?=^ - uses:)/m)?.[1]+ expect(body).toBeTruthy()+ const script = body!.replace(/^ {10}/gm, "").replaceAll(+ "node scripts/ci/changed-scopes.mjs", '"$CLASSIFIER_NODE" "$CLASSIFIER_SCRIPT" --ui-shards 1',+ ).replaceAll(".ci/execution-plan.json", '"$SCOPE_PLAN_FILE"').replace("mkdir -p .ci", 'mkdir -p "$SCOPE_DIR"')+ const workflowOutput = execFileSync("bash", ["-c", script], {+ cwd: fixture.root,+ env: {+ ...cleanGitEnvironment(),+ GIT_DIR: fixture.gitDir, GIT_WORK_TREE: fixture.root,+ CLASSIFIER_NODE: process.execPath, CLASSIFIER_SCRIPT: realpathSync(join(fixture.root, "scripts/ci/changed-scopes.mjs")),+ SCOPE_DIR: join(fixture.root, ".ci"), SCOPE_PLAN_FILE: join(fixture.root, ".ci/execution-plan.json"),+ EVENT_NAME: event, EVENT_SHA: "HEAD", PR_BASE_SHA: "HEAD^", PR_HEAD_SHA: "HEAD",+ MERGE_BASE_SHA: "HEAD^", PUSH_BASE_SHA: "HEAD^", HEAD_COMMIT_MESSAGE: message,+ DISPATCH_MODE: "full", GITHUB_OUTPUT: join(fixture.root, "outputs"),+ GITHUB_STEP_SUMMARY: join(fixture.root, "summary"),+ },+ })+ expect(existsSync(join(fixture.root, ".ci/execution-plan.json")), workflowOutput.toString()).toBe(true)+ const result = JSON.parse(readFileSync(join(fixture.root, ".ci/execution-plan.json"), "utf8"))+ expect(result.execution_mode).toBe(mode)+ expect(validateExecutionPlan(result)).toEqual(result)+ if (mode === "full") {+ expect(result.ui.specs).toEqual(["all"])+ expect(result.suites.integration).toContain("web")+ } else if (mode === "main-smoke") {+ expect(result.suites.unit).toEqual([])+ expect(result.suites.smoke).toEqual(loadScopeManifest().smoke_tests)+ expect(result.ui.specs).toEqual([...loadScopeManifest().ui.contracts.smoke].sort())+ } else {+ expect(result.ui.specs).toContain("60-desktop-default-user-bar-width.spec.ts")+ expect(result.ui.specs).not.toContain("all")+ }+ expect(readFileSync(join(fixture.root, "outputs"), "utf8")).toContain(`execution_mode=${mode}\n`)+ } finally {+ fixture.cleanup()+ }+ })+it("detects dependency changes from package manifests instead of branch names", () => {const manifest = (version?: string) => JSON.stringify({dependencies: version ? { "react-resizable-panels": version } : {},@@ -632,7 +1080,7 @@ describe("compatibility and CLI fail-closed behavior", () => {const planFile = join(directory, "plan.json")const summary = join(directory, "summary.md")try {- runCli([+ runFixtureCli(["--ui-shards", "1","--base", "missing-base","--head", "missing-head","--output", output,@@ -646,6 +1094,8 @@ describe("compatibility and CLI fail-closed behavior", () => {expect(values).toContain("run_resizable_panels_compat=true")expect(writtenPlan.full).toBe(true)expect(writtenPlan.full_reason).toBe("classifier_error")+ expect(writtenPlan.suites.static_tasks.length).toBeGreaterThan(0)+ expect(writtenPlan.suites.unit_build_tasks).toContain("@alook/agent-driver#build")expect(writtenPlan.compatibility.resizable_panels).toBe(true)expect(readFileSync(summary, "utf8")).toContain("Fail-closed reason:")} finally {@@ -659,7 +1109,7 @@ describe("compatibility and CLI fail-closed behavior", () => {const planFile = join(directory, "plan.json")const summary = join(directory, "summary.md")try {- runCli([+ runFixtureCli(["--ui-shards", "1","--force-full","--diagnostic-only","--output", output,@@ -685,51 +1135,37 @@ describe("compatibility and CLI fail-closed behavior", () => {it("reads a real Git diff and prints its canonical plan when no output file is requested", () => {const fixture = gitDiffFixture()const summary = join(fixture.root, "summary.md")- const stdout = vi.spyOn(process.stdout, "write").mockImplementation(() => true)- const localEnvironment = localGitEnvironmentNames()- const previousEnvironment = new Map(- localEnvironment.map((name) => [name, process.env[name]]),- )try {- for (const name of localEnvironment) delete process.env[name]- process.env.GIT_DIR = join(fixture.root, ".git")- process.env.GIT_WORK_TREE = fixture.root- runCli(["--base", "HEAD^", "--head", "HEAD", "--full-unless-benchmark-only", "--summary", summary])-- const written = stdout.mock.calls.map(([value]) => String(value)).join("")+ const written = runFixtureCli(["--ui-shards", "1", "--base", "HEAD^", "--head", "HEAD", "--main-smoke", "--summary", summary], fixture.root)const writtenPlan = JSON.parse(written)- expect(writtenPlan.full).toBe(true)- expect(writtenPlan.full_reason).toBe("forced")+ expect(writtenPlan.full).toBe(false)+ expect(writtenPlan.execution_mode).toBe("main-smoke")expect(writtenPlan.base_sha).toBe("HEAD^")expect(writtenPlan.head_sha).toBe("HEAD")expect(writtenPlan.changes).toEqual([{ status: "A", path: fixture.changedPath }])expect(readFileSync(summary, "utf8")).toContain(fixture.changedPath)} finally {- for (const name of localEnvironment) delete process.env[name]- for (const [name, value] of previousEnvironment) {- if (value !== undefined) process.env[name] = value- }- stdout.mockRestore()- rmSync(fixture.root, { recursive: true, force: true })+ fixture.cleanup()}})it.each([["src/benchmark/src/runner.mjs", false],- ["src/web/auth/index.ts", true],+ ["src/web/auth/index.ts", false],])("applies main-push policy through the actual CLI diff for %s", (path, full) => {const fixture = gitDiffFixture(String(path))const output = join(fixture.root, "projection")const planFile = join(fixture.root, "plan.json")try {- execFileSync(process.execPath, ["scripts/ci/changed-scopes.mjs", "--base", "HEAD^", "--head", "HEAD", "--full-unless-benchmark-only", "--output", output, "--plan-file", planFile], {- env: { ...cleanGitEnvironment(), GIT_DIR: join(fixture.root, ".git"), GIT_WORK_TREE: fixture.root },+ execFileSync(process.execPath, [realpathSync(join(fixture.root, "scripts/ci/changed-scopes.mjs")), "--ui-shards", "1", "--base", "HEAD^", "--head", "HEAD", "--main-smoke", "--output", output, "--plan-file", planFile], {+ cwd: fixture.root,+ env: cleanGitEnvironment(),})const result = JSON.parse(readFileSync(planFile, "utf8"))expect(result.full).toBe(full)- expect(result.changes).toEqual([{ status: "A", path }])+ expect(result.changes).toEqual([{ status: "M", path }])} finally {- rmSync(fixture.root, { recursive: true, force: true })+ fixture.cleanup()}})@@ -738,15 +1174,16 @@ describe("compatibility and CLI fail-closed behavior", () => {const output = join(fixture.root, "projection")const planFile = join(fixture.root, "plan.json")try {- execFileSync(process.execPath, ["scripts/ci/changed-scopes.mjs", "--base", "HEAD^", "--head", "HEAD", "--output", output, "--plan-file", planFile], {- env: { ...cleanGitEnvironment(), GIT_DIR: join(fixture.root, ".git"), GIT_WORK_TREE: fixture.root },+ execFileSync(process.execPath, [realpathSync(join(fixture.root, "scripts/ci/changed-scopes.mjs")), "--ui-shards", "1", "--base", "HEAD^", "--head", "HEAD", "--output", output, "--plan-file", planFile], {+ cwd: fixture.root,+ env: cleanGitEnvironment(),})const result = JSON.parse(readFileSync(planFile, "utf8"))expect(result.compatibility.resizable_panels).toBe(true)expect(result.jobs.resizable_panels_compat).toBe(true)expect(readFileSync(output, "utf8")).toContain("run_resizable_panels_compat=true")} finally {- rmSync(fixture.root, { recursive: true, force: true })+ fixture.cleanup()}})@@ -755,7 +1192,7 @@ describe("compatibility and CLI fail-closed behavior", () => {const output = join(directory, "output")const planFile = join(directory, "plan.json")try {- runCli(["--output", output, "--plan-file", planFile])+ runFixtureCli(["--ui-shards", "1", "--output", output, "--plan-file", planFile])expect(JSON.parse(readFileSync(planFile, "utf8"))).toMatchObject({full: true,full_reason: "classifier_error",diff --git a/scripts/ci/characterization-guard.mjs b/scripts/ci/characterization-guard.mjsindex 51b5d4d16..a3868a694 100644--- a/scripts/ci/characterization-guard.mjs+++ b/scripts/ci/characterization-guard.mjs@@ -6,6 +6,7 @@ import {buildExecutionPlan,loadScopeManifest,parseNameStatus,+ queryNativeTasks,validateExecutionPlan,} from "./changed-scopes.mjs"@@ -160,6 +161,7 @@ export function runCli(argv, runtime = {}) {baseSha: args.candidateSha,headSha: args.fixtureSha,diagnosticOnly: true,+ nativeTasks: (runtime.queryNativeTasks || queryNativeTasks)({ root: runtime.root || ROOT, baseSha: args.candidateSha, headSha: args.fixtureSha, manifest }),})const integrityBlobs = Object.fromEntries(manifest.integrity_paths.map((path) => [path, {candidate: blobAt(args.candidateSha, path, runtime),diff --git a/scripts/ci/characterization-guard.test.ts b/scripts/ci/characterization-guard.test.tsindex 377d5f6b3..35eab28f0 100644--- a/scripts/ci/characterization-guard.test.ts+++ b/scripts/ci/characterization-guard.test.ts@@ -2,7 +2,7 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"import { tmpdir } from "node:os"import { join } from "node:path"import { describe, expect, it, vi } from "vitest"-import { buildExecutionPlan, loadScopeManifest } from "./changed-scopes.mjs"+import { buildExecutionPlan as createExecutionPlan, loadScopeManifest, queryNativeTasks } from "./changed-scopes.mjs"import {blobAt,runCli,@@ -10,6 +10,15 @@ import {validateCharacterization,} from "./characterization-guard.mjs"+let nativeTasks: ReturnType<typeof queryNativeTasks>+function fullNativeFacts() {+ if (!nativeTasks) { const value = queryNativeTasks(); nativeTasks = { inventory: value.inventory, affected: value.inventory } }+ return nativeTasks+}+function buildExecutionPlan(changes, options) {+ return createExecutionPlan(changes, { ...options, nativeTasks: fullNativeFacts() })+}+const candidateSha = "a".repeat(40)const fixtureSha = "b".repeat(40)const sourcePath = "src/app/src/commands/update.ts"@@ -49,6 +58,7 @@ function cliRuntime(sourcePath: string | null) {const manifest = loadScopeManifest()return {manifest,+ queryNativeTasks: fullNativeFacts,execFileSync: vi.fn((_file: string, args: string[], options: unknown) => {if (args[0] === "ls-remote") return `${fixtureSha}\trefs/heads/test\n`if (args[0] === "show") return `${candidateSha}\n`diff --git a/scripts/ci/check-local.mjs b/scripts/ci/check-local.mjsnew file mode 100644index 000000000..1f17213ef--- /dev/null+++ b/scripts/ci/check-local.mjs@@ -0,0 +1,91 @@+import { execFileSync, spawnSync } from "node:child_process"+import { dirname, resolve } from "node:path"+import { mkdirSync, writeFileSync } from "node:fs"+import { fileURLToPath } from "node:url"+import { buildExecutionPlan, parseNameStatus, queryNativeTasks, stablePlanJson } from "./changed-scopes.mjs"+import { isolatedRepositoryGitEnvironment } from "./report-changed-patch-coverage.mjs"++const ROOT = resolve(fileURLToPath(new URL("../..", import.meta.url)))++export function collectLocalChanges({ root = ROOT, base } = {}) {+ const git = (...args) => execFileSync("git", args, {+ cwd: root,+ env: { ...isolatedRepositoryGitEnvironment(), GIT_OPTIONAL_LOCKS: "0" },+ stdio: ["ignore", "pipe", "pipe"],+ })+ const baseSha = base+ ? git("rev-parse", "--verify", base).toString().trim()+ : git("merge-base", "HEAD", "origin/main").toString().trim()+ const diffOptions = ["--name-status", "-z", "--find-renames", "--find-copies"]+ const changes = [+ ...parseNameStatus(git("diff", ...diffOptions, baseSha, "HEAD", "--")),+ ...parseNameStatus(git("diff", "--cached", ...diffOptions, "HEAD", "--")),+ ...parseNameStatus(git("diff", ...diffOptions, "--")),+ ]+ const untracked = git("ls-files", "--others", "--exclude-standard", "-z").toString().split("\0").filter(Boolean)+ const uniqueChanges = new Map([...changes, ...untracked.map((path) => ({ status: "A", path }))]+ .map((change) => [JSON.stringify([change.status, change.old_path ?? "", change.path]), change]))+ return {+ changes: [...uniqueChanges.values()],+ baseSha,+ headSha: git("rev-parse", "HEAD").toString().trim(),+ }+}++export function localCheckCommands(plan) {+ if (plan.full) return ["typecheck", "lint", "test", "typegrep:ws", "typegrep:agent-driver", "knip"]+ .map((script) => ["pnpm", script])+ const commands = []+ const turbo = (tasks) => {+ if (tasks.length) commands.push(["node", "scripts/ci/run-turbo.mjs", "run", ...tasks])+ }+ turbo(plan.suites.static_tasks.filter((task) => task.split("#")[1].startsWith("typecheck")))+ turbo(plan.suites.static_tasks.filter((task) => task.split("#")[1].startsWith("lint")))+ turbo(plan.suites.unit_build_tasks)+ if (plan.suites.unit_tasks.length) commands.push(["node", "scripts/ci/run-unit-tests.mjs", "--plan", ".ci/local-execution-plan.json"])+ if (plan.suites.static.some((name) => ["@alook/web", "@alook/shared", "@alook/ws-do"].includes(name))) {+ commands.push(["pnpm", "typegrep:ws"])+ }+ if (plan.suites.static.some((name) => ["@alook/agent-driver", "@alook/daemon"].includes(name))) {+ commands.push(["pnpm", "typegrep:agent-driver"])+ }+ turbo(plan.suites.knip_tasks)+ return commands+}++export function runLocalChecks(plan, { root = ROOT, execute = spawnSync } = {}) {+ if (!plan.full && plan.suites.unit_tasks.length) {+ const file = resolve(root, ".ci/local-execution-plan.json")+ mkdirSync(dirname(file), { recursive: true })+ writeFileSync(file, stablePlanJson(plan) + "\n")+ }+ for (const [command, ...args] of localCheckCommands(plan)) {+ const result = execute(command, args, { cwd: root, stdio: "inherit", shell: process.platform === "win32" })+ if (result.error) throw result.error+ if (result.status !== 0) throw new Error(`${command} ${args.join(" ")} failed (${result.signal || result.status})`)+ }+}++export function runCli(argv = process.argv.slice(2)) {+ let base+ let forceFull = false+ let planOnly = false+ for (let index = 0; index < argv.length; index += 1) {+ if (argv[index] === "--full") forceFull = true+ else if (argv[index] === "--plan") planOnly = true+ else if (argv[index] === "--base" && argv[index + 1]) base = argv[++index]+ else throw new Error(`unknown or incomplete local check option: ${argv[index]}`)+ }+ let plan+ try {+ const input = collectLocalChanges({ base })+ plan = buildExecutionPlan(input.changes, { ...input, forceFull, nativeTasks: queryNativeTasks(input) })+ } catch (error) {+ plan = buildExecutionPlan([], { forceFull: true, fallbackReason: String(error) })+ }+ if (planOnly) process.stdout.write(`${JSON.stringify({ plan, commands: localCheckCommands(plan) }, null, 2)}\n`)+ else runLocalChecks(plan)+ return plan+}++if (process.argv[1] === fileURLToPath(import.meta.url)) runCli()diff --git a/scripts/ci/check-local.test.ts b/scripts/ci/check-local.test.tsnew file mode 100644index 000000000..128ba811b--- /dev/null+++ b/scripts/ci/check-local.test.ts@@ -0,0 +1,147 @@+import { execFileSync } from "node:child_process"+import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs"+import { tmpdir } from "node:os"+import { dirname, join, resolve } from "node:path"+import { describe, expect, it, vi } from "vitest"+import { buildExecutionPlan, loadScopeManifest, queryNativeTasks } from "./changed-scopes.mjs"+import { collectLocalChanges, localCheckCommands, runLocalChecks } from "./check-local.mjs"+import { isolatedRepositoryGitEnvironment } from "./report-changed-patch-coverage.mjs"++function repository(files: Record<string, string> = { "base.ts": "export const base = 1\n" }) {+ const root = mkdtempSync(join(tmpdir(), "alook-local-check-"))+ const git = (...args: string[]) => execFileSync("git", args, { cwd: root, env: isolatedRepositoryGitEnvironment(), encoding: "utf8" })+ try {+ git("init", "--quiet")+ writeFileSync(join(root, ".git/info/exclude"), "/node_modules\n")+ git("config", "user.name", "Local Check")+ git("config", "user.email", "[email protected]")+ git("config", "commit.gpgsign", "false")+ mkdirSync(join(root, "fixture-hooks"))+ git("config", "core.hooksPath", join(root, "fixture-hooks"))+ const source = resolve(import.meta.dirname, "../..")+ for (const path of ["package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml", "turbo.json", ".gitignore",+ ...loadScopeManifest().packages.map(entry => entry.root + "/package.json")]) {+ mkdirSync(dirname(join(root, path)), { recursive: true })+ writeFileSync(join(root, path), readFileSync(join(source, path)))+ }+ symlinkSync(join(source, "node_modules"), join(root, "node_modules"), process.platform === "win32" ? "junction" : "dir")+ for (const [path, content] of Object.entries(files)) {+ mkdirSync(dirname(join(root, path)), { recursive: true })+ writeFileSync(join(root, path), content)+ }+ git("add", ".")+ git("commit", "--quiet", "-m", "base")+ const base = git("rev-parse", "HEAD").trim()+ git("update-ref", "refs/remotes/origin/main", base)+ return { root, git, base }+ } catch (error) {+ rmSync(root, { recursive: true, force: true })+ throw error+ }+}++describe("local canonical checks", () => {+ it.each(["staged modification", "committed modification", "staged rename", "staged deletion"])(+ "retains runtime scope when the final disk cancels a %s", (kind) => {+ const runtime = "src/web/src/components/community/shell/user-bar.tsx"+ const baseline = "export const original = true\n"+ const { root, git } = repository({ [runtime]: baseline, "README.md": "base\n" })+ try {+ if (kind === "staged rename") {+ git("mv", runtime, "moved-runtime.md")+ unlinkSync(join(root, "moved-runtime.md"))+ } else if (kind === "staged deletion") git("rm", runtime)+ else {+ writeFileSync(join(root, runtime), "export const changed = true\n")+ git("add", runtime)+ if (kind === "committed modification") git("commit", "--quiet", "-m", "runtime")+ }+ mkdirSync(dirname(join(root, runtime)), { recursive: true })+ writeFileSync(join(root, runtime), baseline)+ if (kind === "committed modification") git("add", runtime)+ writeFileSync(join(root, "README.md"), "documentation changed\n")+ const index = readFileSync(join(root, ".git/index"))+ const input = collectLocalChanges({ root })+ expect(input.changes.some((change) => change.path === runtime || change.old_path === runtime)).toBe(true)+ if (kind === "staged rename") expect(input.changes).toContainEqual({ status: "R100", old_path: runtime, path: "moved-runtime.md" })+ if (kind === "staged deletion") expect(input.changes).toContainEqual({ status: "D", path: runtime })+ const plan = buildExecutionPlan(input.changes, { nativeTasks: queryNativeTasks({ root, ...input }) })+ expect(plan.docs_only).toBe(false)+ expect(plan.suites.static).toContain("@alook/web")+ expect(localCheckCommands(plan).some((command) => command.includes("@alook/web#typecheck"))).toBe(true)+ expect(readFileSync(join(root, ".git/index"))).toEqual(index)+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+ },+ )++ it("includes branch commits, staged, unstaged and untracked source without changing the index", () => {+ const { root, git, base } = repository()+ try {+ writeFileSync(join(root, "committed.ts"), "export const committed = 1\n")+ git("add", ".")+ git("commit", "--quiet", "-m", "branch")+ writeFileSync(join(root, "staged.ts"), "export const staged = 1\n")+ git("add", "staged.ts")+ writeFileSync(join(root, "base.ts"), "export const base = 2\n")+ writeFileSync(join(root, "untracked.ts"), "export const untracked = 1\n")+ const index = readFileSync(join(root, ".git/index"))+ const input = collectLocalChanges({ root })+ expect(input.baseSha).toBe(base)+ expect(input.changes).toEqual(expect.arrayContaining([+ { status: "M", path: "base.ts" },+ { status: "A", path: "committed.ts" },+ { status: "A", path: "staged.ts" },+ { status: "A", path: "untracked.ts" },+ ]))+ expect(input.changes).toHaveLength(4)+ expect(readFileSync(join(root, ".git/index"))).toEqual(index)+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+ })++ it("keeps full checks and native unit build prerequisites before affected execution", () => {+ const full = buildExecutionPlan([], { forceFull: true })+ expect(localCheckCommands(full)).toEqual([+ ["pnpm", "typecheck"], ["pnpm", "lint"], ["pnpm", "test"],+ ["pnpm", "typegrep:ws"], ["pnpm", "typegrep:agent-driver"], ["pnpm", "knip"],+ ])+ const path = "src/daemon/agent-driver/src/index.ts"+ const fixture = repository({ [path]: "export const original = true\n" })+ try {+ writeFileSync(join(fixture.root, path), "export const changed = true\n")+ const input = collectLocalChanges({ root: fixture.root })+ const nativeTasks = queryNativeTasks({ root: fixture.root, ...input })+ const plan = buildExecutionPlan(input.changes, { nativeTasks })+ const commands = localCheckCommands(plan)+ const build = commands.findIndex(command => command.includes("@alook/agent-driver#build"))+ const tests = commands.findIndex(command => command.includes("scripts/ci/run-unit-tests.mjs"))+ expect(build).toBeGreaterThanOrEqual(0)+ expect(tests).toBeGreaterThan(build)+ expect(commands[tests]).toEqual(["node", "scripts/ci/run-unit-tests.mjs", "--plan", ".ci/local-execution-plan.json"])+ expect(localCheckCommands(buildExecutionPlan([{ status: "M", path: "README.md" }]))).toEqual([])+ } finally { rmSync(fixture.root, { recursive: true, force: true }) }+ })++ it("stops later checks at the first child failure or launch error", () => {+ const full = buildExecutionPlan([], { forceFull: true })+ const execute = vi.fn().mockReturnValueOnce({ status: 0 }).mockReturnValueOnce({ status: 7 })+ expect(() => runLocalChecks(full, { execute })).toThrow("failed (7)")+ expect(execute).toHaveBeenCalledTimes(2)+ const error = new Error("cannot launch")+ const launch = vi.fn().mockReturnValue({ error })+ expect(() => runLocalChecks(full, { execute: launch })).toThrow(error)+ expect(launch).toHaveBeenCalledTimes(1)+ })++ it("uses the real CLI in plan-only mode without starting package checks", () => {+ const output = execFileSync(process.execPath, ["scripts/ci/check-local.mjs", "--base", "HEAD", "--full", "--plan"], { encoding: "utf8" })+ const result = JSON.parse(output)+ expect(result.plan.base_sha).toMatch(/^[0-9a-f]{40}$/)+ expect(result.plan.head_sha).toBe(result.plan.base_sha)+ expect(result.plan.full).toBe(true)+ expect(result.commands).toEqual(localCheckCommands(result.plan))+ })+})diff --git a/scripts/ci/e2e-build-artifact.mjs b/scripts/ci/e2e-build-artifact.mjsindex 6c02da0d7..9a4f6f381 100644--- a/scripts/ci/e2e-build-artifact.mjs+++ b/scripts/ci/e2e-build-artifact.mjs@@ -6,6 +6,8 @@ import {mkdtempSync,openSync,readFileSync,+ readdirSync,+ realpathSync,rmSync,statSync,writeFileSync,@@ -14,8 +16,9 @@ import { tmpdir } from "node:os"import { join, resolve, sep } from "node:path"import { spawnSync } from "node:child_process"import { fileURLToPath } from "node:url"+import { executeTurbo, taskEnvironment } from "./run-turbo.mjs"-export const BUILD_ARTIFACT_VERSION = 1+export const BUILD_ARTIFACT_VERSION = 2export const BUILD_ARCHIVE_NAME = "ui-e2e-build.tgz"export const BUILD_MANIFEST_NAME = "ui-e2e-build-manifest.json"export const BUILD_OUTPUT_ROOTS = [@@ -24,6 +27,51 @@ export const BUILD_OUTPUT_ROOTS = []export const BUILD_ENTRYPOINTS = BUILD_OUTPUT_ROOTS.map((root) => `${root}/worker.js`)+export function buildOutputRoots(zones = ["web", "blog"]) {+ if (!Array.isArray(zones) || !zones.length || new Set(zones).size !== zones.length+ || zones.some(zone => !["web", "blog"].includes(zone))) throw new Error("invalid build zones")+ return ["web", "blog"].filter(zone => zones.includes(zone)).map(zone => zone === "web" ? "src/web/.open-next" : "src/web/blog/.open-next")+}++function nativeBuildHashes(root, outputRoots) {+ const tasks = outputRoots.map(path => path.includes("/blog/") ? "@alook/web#build:blog" : "@alook/web#build")+ const result = executeTurbo(["run", ...tasks, "--dry=json"], { root, stdio: ["ignore", "pipe", "pipe"] })+ if (result.error || result.status !== 0) throw new Error("native build identity query failed")+ const report = JSON.parse(result.stdout)+ const hashes = Object.fromEntries(report.tasks.filter(task => tasks.includes(task.taskId))+ .sort((left, right) => left.taskId.localeCompare(right.taskId)).map(task => [task.taskId, task.hash]))+ if (Object.keys(hashes).length !== tasks.length || Object.values(hashes).some(hash => !/^[a-f0-9]+$/.test(hash))) {+ throw new Error("native build identity is incomplete")+ }+ return hashes+}++function buildIdentity(root, outputRoots) {+ const packageManager = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8")).packageManager+ requiredString(packageManager, "package manager")+ const turbo = JSON.parse(readFileSync(resolve(root, "turbo.json"), "utf8"))+ const tasks = outputRoots.map(path => path.includes("/blog/") ? "@alook/web#build:blog" : "@alook/web#build")+ const patterns = [...turbo.globalEnv || [], ...tasks.flatMap(task => turbo.tasks[task].env || [])]+ const names = Object.keys(process.env).filter(name => !name.startsWith("ALOOK_TASK_")+ && patterns.some(pattern => pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern)).sort()+ const env = Object.fromEntries(names.map(name => [name, process.env[name]]))+ const files = {}+ for (const folder of ["src/web", ...(tasks.includes("@alook/web#build:blog") ? ["src/web/blog"] : [])]) {+ const absolute = resolve(root, folder)+ for (const name of existsSync(absolute) ? readdirSync(absolute).sort() : []) {+ if (/^(?:\.env|\.dev\.vars)(?:\..*)?$/.test(name) && statSync(resolve(absolute, name)).isFile()) {+ files[folder + "/" + name] = sha256File(resolve(absolute, name))+ }+ }+ }+ const environment = taskEnvironment(root)+ return {+ taskHashes: nativeBuildHashes(root, outputRoots),+ toolchain: { node: environment.ALOOK_TASK_NODE, bun: environment.ALOOK_TASK_BUN, platform: environment.ALOOK_TASK_PLATFORM, packageManager, workspace: realpathSync(root) },+ environmentSha256: createHash("sha256").update(JSON.stringify({ env, files })).digest("hex"),+ }+}+function requiredString(value, label) {if (typeof value !== "string" || value.length === 0) {throw new Error(`${label} is required`)@@ -57,8 +105,8 @@ function assertRegularFile(path, label) {}}-export function assertBuildOutputs(root) {- for (const entrypoint of BUILD_ENTRYPOINTS) {+export function assertBuildOutputs(root, roots = BUILD_OUTPUT_ROOTS) {+ for (const entrypoint of roots.map(path => `${path}/worker.js`)) {assertRegularFile(resolve(root, entrypoint), "OpenNext worker entrypoint")}}@@ -101,7 +149,7 @@ function normalizedArchiveMember(value) {return value.endsWith("/") ? value.slice(0, -1) : value}-export function verifyArchiveMembers(archive) {+export function verifyArchiveMembers(archive, roots = BUILD_OUTPUT_ROOTS) {const members = runTar(["-tzf", archive]).split("\n").filter(Boolean)@@ -109,7 +157,7 @@ export function verifyArchiveMembers(archive) {if (members.length === 0) throw new Error("build archive is empty")for (const member of members) {const segments = member.split("/")- const allowed = BUILD_OUTPUT_ROOTS.some(+ const allowed = roots.some((root) => member === root || member.startsWith(`${root}/`),)if (@@ -121,7 +169,7 @@ export function verifyArchiveMembers(archive) {throw new Error(`build archive contains an unexpected member: ${member}`)}}- for (const entrypoint of BUILD_ENTRYPOINTS) {+ for (const entrypoint of roots.map(path => `${path}/worker.js`)) {if (!members.includes(entrypoint)) {throw new Error(`build archive is missing OpenNext worker entrypoint: ${entrypoint}`)}@@ -133,12 +181,16 @@ function exactManifestKeys(manifest) {const expected = ["archiveSha256","attempt",+ "environmentSha256","headSha","lockfileSha256","roots","runId",+ "taskHashes",+ "toolchain","version",]+ expected.sort()const actual = Object.keys(manifest).sort()if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) {throw new Error("build manifest fields do not match the exact contract")@@ -158,7 +210,7 @@ function artifactPaths(root, directory) {}}-export function createBuildArtifact({ root, directory, runId, attempt, headSha }) {+export function createBuildArtifact({ root, directory, runId, attempt, headSha, zones }) {const repositoryRoot = resolve(root)const identity = {runId: requiredString(String(runId ?? ""), "run ID"),@@ -167,21 +219,23 @@ export function createBuildArtifact({ root, directory, runId, attempt, headSha }}const lockfile = resolve(repositoryRoot, "pnpm-lock.yaml")assertRegularFile(lockfile, "pnpm lockfile")- assertBuildOutputs(repositoryRoot)+ const outputRoots = buildOutputRoots(zones)+ assertBuildOutputs(repositoryRoot, outputRoots)const paths = artifactPaths(repositoryRoot, directory)mkdirSync(paths.artifactDirectory, { recursive: true })rmSync(paths.archive, { force: true })rmSync(paths.manifest, { force: true })- runTar(["-czf", paths.archive, "-C", repositoryRoot, ...BUILD_OUTPUT_ROOTS])- verifyArchiveMembers(paths.archive)+ runTar(["-czf", paths.archive, "-C", repositoryRoot, ...outputRoots])+ verifyArchiveMembers(paths.archive, outputRoots)const manifest = {version: BUILD_ARTIFACT_VERSION,...identity,lockfileSha256: sha256File(lockfile),archiveSha256: sha256File(paths.archive),- roots: BUILD_OUTPUT_ROOTS,+ roots: outputRoots,+ ...buildIdentity(repositoryRoot, outputRoots),}writeFileSync(paths.manifest, `${JSON.stringify(manifest, null, 2)}\n`)return { ...paths, manifestData: manifest }@@ -199,7 +253,7 @@ function assertEqual(actual, expected, label) {}}-export function verifyBuildArtifact({ root, directory, runId, attempt, headSha }) {+export function verifyBuildArtifact({ root, directory, runId, attempt, headSha, zones }) {const repositoryRoot = resolve(root)const paths = artifactPaths(repositoryRoot, directory)assertRegularFile(paths.archive, "build archive")@@ -219,10 +273,11 @@ export function verifyBuildArtifact({ root, directory, runId, attempt, headSha }assertEqual(manifest.runId, requiredString(String(runId ?? ""), "run ID"), "build run ID")assertEqual(manifest.attempt, positiveInteger(attempt, "attempt"), "build attempt")assertEqual(manifest.headSha, exactHeadSha(headSha), "build head SHA")+ const outputRoots = buildOutputRoots(zones)if (!Array.isArray(manifest.roots)- || manifest.roots.length !== BUILD_OUTPUT_ROOTS.length- || manifest.roots.some((value, index) => value !== BUILD_OUTPUT_ROOTS[index])+ || manifest.roots.length !== outputRoots.length+ || manifest.roots.some((value, index) => value !== outputRoots[index])) {throw new Error("build output roots mismatch")}@@ -233,13 +288,18 @@ export function verifyBuildArtifact({ root, directory, runId, attempt, headSha }assertRegularFile(lockfile, "pnpm lockfile")assertEqual(sha256File(lockfile), manifest.lockfileSha256, "build lockfile SHA-256")assertEqual(sha256File(paths.archive), manifest.archiveSha256, "build archive SHA-256")- verifyArchiveMembers(paths.archive)+ const currentIdentity = buildIdentity(repositoryRoot, outputRoots)+ assertEqual(JSON.stringify(manifest.toolchain), JSON.stringify(currentIdentity.toolchain), "build toolchain")+ assertManifestDigest(manifest.environmentSha256, "build environment digest")+ assertEqual(manifest.environmentSha256, currentIdentity.environmentSha256, "build environment")+ assertEqual(JSON.stringify(manifest.taskHashes), JSON.stringify(currentIdentity.taskHashes), "native build task hashes")+ verifyArchiveMembers(paths.archive, outputRoots)- for (const outputRoot of BUILD_OUTPUT_ROOTS) {+ for (const outputRoot of outputRoots) {rmSync(resolve(repositoryRoot, outputRoot), { recursive: true, force: true })}- runTar(["-xzf", paths.archive, "-C", repositoryRoot])- assertBuildOutputs(repositoryRoot)+ runTar(["-xzpf", paths.archive, "-C", repositoryRoot])+ assertBuildOutputs(repositoryRoot, outputRoots)return manifest}@@ -262,6 +322,7 @@ export function runCli(argv) {runId: args.runId,attempt: args.attempt,headSha: args.headSha,+ zones: args.zones ? args.zones.split(",") : undefined,}if (args.command === "create") return createBuildArtifact(options)if (args.command === "verify") return verifyBuildArtifact(options)diff --git a/scripts/ci/e2e-build-artifact.test.ts b/scripts/ci/e2e-build-artifact.test.tsindex 0ed66a29a..6517bdff5 100644--- a/scripts/ci/e2e-build-artifact.test.ts+++ b/scripts/ci/e2e-build-artifact.test.ts@@ -1,14 +1,17 @@import { createHash } from "node:crypto"import { spawnSync } from "node:child_process"import {+ chmodSync,+ lstatSync,mkdirSync,mkdtempSync,readFileSync,rmSync,+ symlinkSync,writeFileSync,} from "node:fs"import { tmpdir } from "node:os"-import { join } from "node:path"+import { join, resolve } from "node:path"import { fileURLToPath } from "node:url"import { afterEach, describe, expect, it, vi } from "vitest"import {@@ -26,11 +29,23 @@ const roots: string[] = []afterEach(() => {for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })+ vi.unstubAllEnvs()})-function fixture() {+function fixture(zones?: string[]) {const root = mkdtempSync(join(tmpdir(), "alook-ui-e2e-build-"))roots.push(root)+ writeFileSync(join(root, "package.json"), JSON.stringify({ name: "artifact-fixture", packageManager: "[email protected]" }))+ writeFileSync(join(root, "pnpm-workspace.yaml"), 'packages:\n - "src/web"\n')+ writeFileSync(join(root, ".gitignore"), "node_modules\n")+ mkdirSync(join(root, "src/web"), { recursive: true })+ writeFileSync(join(root, "src/web/package.json"), JSON.stringify({ name: "@alook/web", scripts: { build: "node -e 0", "build:blog": "node -e 0" } }))+ writeFileSync(join(root, "src/web/source.ts"), "export const value = 1\n")+ symlinkSync(resolve(import.meta.dirname, "../../node_modules"), join(root, "node_modules"), process.platform === "win32" ? "junction" : "dir")+ writeFileSync(join(root, "turbo.json"), JSON.stringify({ globalEnv: ["CI", "ALOOK_TASK_NODE", "ALOOK_TASK_PLATFORM", "ALOOK_TASK_WORKSPACE"], tasks: {+ "@alook/web#build": { env: ["NEXT_PUBLIC_*"], inputs: ["package.json", "source.ts"], outputs: [".open-next/**"] },+ "@alook/web#build:blog": { env: ["NEXT_PUBLIC_*"], inputs: ["package.json", "source.ts"], outputs: ["blog/.open-next/**"] },+ } }))writeFileSync(join(root, "pnpm-lock.yaml"), "lockfileVersion: '9.0'\n")for (const output of BUILD_OUTPUT_ROOTS) {mkdirSync(join(root, output, "assets"), { recursive: true })@@ -43,6 +58,7 @@ function fixture() {runId: "123",attempt: 2,headSha: HEAD_SHA,+ zones,})return { root, ...result }}@@ -52,6 +68,49 @@ function removeBuildOutputs(root: string) {}describe("UI E2E build artifact", () => {+ it("preserves archived executable modes under a restrictive consumer umask", () => {+ const artifact = fixture()+ const entry = join(artifact.root, BUILD_OUTPUT_ROOTS[0]!, "worker.js")+ chmodSync(entry, 0o751)+ const options = { root: artifact.root, directory: ".ci/ui-e2e-build", runId: "123", attempt: 2, headSha: HEAD_SHA }+ createBuildArtifact(options)+ removeBuildOutputs(artifact.root)+ const previous = process.umask(0o077)+ try {+ verifyBuildArtifact(options)+ if (process.platform !== "win32") expect(lstatSync(entry).mode & 0o777).toBe(0o751)+ expect(readFileSync(entry, "utf8")).toContain("export default")+ } finally { process.umask(previous) }+ })++ it("round-trips Web alone and rejects a consumer that additionally requires Blog", () => {+ const artifact = fixture(["web"])+ removeBuildOutputs(artifact.root)+ const options = { root: artifact.root, directory: ".ci/ui-e2e-build", runId: "123", attempt: 2, headSha: HEAD_SHA }+ expect(() => verifyBuildArtifact(options)).toThrow("roots mismatch")+ expect(verifyBuildArtifact({ ...options, zones: ["web"] }).roots).toEqual([BUILD_OUTPUT_ROOTS[0]])+ expect(readFileSync(join(artifact.root, BUILD_OUTPUT_ROOTS[0], "worker.js"), "utf8")).toContain("export default")+ expect(verifyArchiveMembers(artifact.archive, [BUILD_OUTPUT_ROOTS[0]]).some(path => path.includes("/blog/"))).toBe(false)+ })++ it("rejects a different build environment without exposing its values", () => {+ const artifact = fixture()+ vi.stubEnv("NEXT_PUBLIC_WS_DO_PORT", "8765")+ expect(() => verifyBuildArtifact({ root: artifact.root, directory: ".ci/ui-e2e-build", runId: "123", attempt: 2, headSha: HEAD_SHA })).toThrow("build environment mismatch")+ })++ it.each(["source", "configuration"])("rejects changed %s through native Turbo task hashes", kind => {+ const artifact = fixture()+ if (kind === "source") writeFileSync(join(artifact.root, "src/web/source.ts"), "export const value = 2\n")+ else {+ const path = join(artifact.root, "turbo.json")+ const config = JSON.parse(readFileSync(path, "utf8"))+ config.tasks["@alook/web#build"].outputs.push("another-output/**")+ writeFileSync(path, JSON.stringify(config))+ }+ expect(() => verifyBuildArtifact({ root: artifact.root, directory: ".ci/ui-e2e-build", runId: "123", attempt: 2, headSha: HEAD_SHA })).toThrow("native build task hashes mismatch")+ })+it("rejects incomplete create identities before reading the filesystem", () => {const options = {root: ".",@@ -82,7 +141,7 @@ describe("UI E2E build artifact", () => {})expect(manifest).toMatchObject({- version: 1,+ version: 2,runId: "123",attempt: 2,headSha: HEAD_SHA,@@ -227,7 +286,7 @@ describe("UI E2E build artifact", () => {it.each([["extra fields", (manifest: Record<string, unknown>) => { manifest.extra = true }, "exact contract"],- ["version", (manifest: Record<string, unknown>) => { manifest.version = 2 }, "version mismatch"],+ ["version", (manifest: Record<string, unknown>) => { manifest.version = 999 }, "version mismatch"],["roots", (manifest: Record<string, unknown>) => { manifest.roots = [BUILD_OUTPUT_ROOTS[0]] }, "roots mismatch"],["lockfile digest", (manifest: Record<string, unknown>) => { manifest.lockfileSha256 = "invalid" }, "lockfile digest"],["archive digest", (manifest: Record<string, unknown>) => { manifest.archiveSha256 = "invalid" }, "archive digest"],diff --git a/scripts/ci/e2e-shard-artifacts.mjs b/scripts/ci/e2e-shard-artifacts.mjsindex 6fdfaa329..35ca2f04b 100644--- a/scripts/ci/e2e-shard-artifacts.mjs+++ b/scripts/ci/e2e-shard-artifacts.mjs@@ -10,8 +10,10 @@ import {import { basename, join, relative, resolve } from "node:path"import { fileURLToPath } from "node:url"+import { collectPlaywrightCases } from "./e2e-shards.mjs"+export const SHARD_ARTIFACT_PREFIX = "blob-report"-export const SHARD_MANIFEST_VERSION = 1+export const SHARD_MANIFEST_VERSION = 2function parsePositiveInteger(value, label) {const parsed = Number(value)@@ -34,6 +36,9 @@ export function expectedMatrix(matrixInput) {const shards = new Map()const owners = new Map()+ const caseOwners = new Set()+ const nativeOwners = new Set()+ let nativeTotal = nulllet total = nullfor (const entry of matrix.include) {const shard = parsePositiveInteger(entry.shard, "matrix shard")@@ -51,16 +56,31 @@ export function expectedMatrix(matrixInput) {if (owner) throw new Error(`spec ${spec} is assigned to shards ${owner} and ${shard}`)owners.set(spec, shard)}- shards.set(shard, { shard, total: entryTotal, specs })+ const nativeShard = parsePositiveInteger(entry.native_shard, "native shard")+ const nativeCount = parsePositiveInteger(entry.native_total, "native total")+ if (nativeTotal === null) nativeTotal = nativeCount+ if (nativeTotal !== nativeCount || nativeShard > nativeCount || nativeOwners.has(nativeShard)) throw new Error("native partition identity mismatch")+ nativeOwners.add(nativeShard)+ if (!Array.isArray(entry.case_keys) || !entry.case_keys.length) throw new Error("matrix must contain native cases")+ const caseKeys = [...entry.case_keys].sort()+ const caseFiles = new Set()+ for (const key of caseKeys) {+ if (caseOwners.has(key)) throw new Error("duplicate matrix case")+ const identity = JSON.parse(key)+ if (!Array.isArray(identity) || identity.length < 3 || identity.some(value => typeof value !== "string") || !specs.includes(identity[0])) throw new Error("matrix case/file mismatch")+ caseFiles.add(identity[0]); caseOwners.add(key)+ }+ assertEqualArray([...caseFiles].sort(), specs, "matrix case/file closure mismatch")+ shards.set(shard, { shard, total: entryTotal, specs, nativeShard, nativeTotal: nativeCount, caseKeys })}if (shards.size !== total) throw new Error(`matrix declares ${total} shards but contains ${shards.size}`)for (let shard = 1; shard <= total; shard += 1) {if (!shards.has(shard)) throw new Error(`matrix is missing shard ${shard}`)}- return { total, shards, specs: [...owners.keys()].sort() }+ return { total, shards, specs: [...owners.keys()].sort(), caseKeys: [...caseOwners].sort() }}-export function createShardManifest({ runId, attempt, sha, shard, total, specs }) {+export function createShardManifest({ runId, attempt, sha, shard, total, specs, nativeShard, nativeTotal, caseKeys }) {const manifest = {version: SHARD_MANIFEST_VERSION,runId: String(runId),@@ -69,6 +89,9 @@ export function createShardManifest({ runId, attempt, sha, shard, total, specs }shard: parsePositiveInteger(shard, "manifest shard"),total: parsePositiveInteger(total, "manifest total"),specs: specs.map(normalizeSpecPath).sort(),+ nativeShard: parsePositiveInteger(nativeShard, "manifest native shard"),+ nativeTotal: parsePositiveInteger(nativeTotal, "manifest native total"),+ caseKeys: [...caseKeys].sort(),}if (!manifest.runId) throw new Error("manifest runId is required")if (!manifest.sha) throw new Error("manifest sha is required")@@ -209,6 +232,8 @@ export function verifyArtifactClosure({expected.specs,`shard ${shard} specs mismatch`,)+ if (manifest.nativeShard !== expected.nativeShard || manifest.nativeTotal !== expected.nativeTotal) throw new Error(`shard ${shard} native identity mismatch`)+ assertEqualArray(manifest.caseKeys || [], expected.caseKeys, `shard ${shard} cases mismatch`)const manifestAttempt = parsePositiveInteger(manifest.attempt, `shard ${shard} manifest attempt`)if (manifestAttempt > currentAttempt) throw new Error(`shard ${shard} manifest is from a future attempt`)if (executedShards.has(shard) && manifestAttempt !== currentAttempt) {@@ -220,19 +245,13 @@ export function verifyArtifactClosure({return { manifests, expectedSpecs: matrix.specs }}-function collectReportFiles(suites, files = []) {- for (const suite of suites ?? []) {- if (suite.file) files.push(normalizeSpecPath(suite.file))- collectReportFiles(suite.suites, files)- }- return files-}-export function verifyMergedReport({ report, matrix: matrixInput }) {const matrix = expectedMatrix(matrixInput)const reportJson = typeof report === "string" ? JSON.parse(report) : report- const actual = [...new Set(collectReportFiles(reportJson.suites))].sort()+ const cases = collectPlaywrightCases(reportJson)+ const actual = [...new Set(cases.map(test => test.file))].sort()assertEqualArray(actual, matrix.specs, "merged report spec set mismatch")+ assertEqualArray(cases.map(test => test.key).sort(), matrix.caseKeys, "merged report case set mismatch")return actual}@@ -257,6 +276,9 @@ export async function runCli(argv, env = process.env) {shard: args.shard,total: args.total,specs: JSON.parse(env.E2E_SPECS ?? "[]"),+ nativeShard: args.nativeShard,+ nativeTotal: args.nativeTotal,+ caseKeys: JSON.parse(env.E2E_CASE_KEYS ?? "[]"),})mkdirSync(resolve(args.output, ".."), { recursive: true })writeFileSync(args.output, `${JSON.stringify(manifest, null, 2)}\n`)diff --git a/scripts/ci/e2e-shard-artifacts.test.ts b/scripts/ci/e2e-shard-artifacts.test.tsindex fd245d3e3..e2f061199 100644--- a/scripts/ci/e2e-shard-artifacts.test.ts+++ b/scripts/ci/e2e-shard-artifacts.test.ts@@ -13,16 +13,21 @@ import {verifyMergedReport,} from "./e2e-shard-artifacts.mjs"+const key = (file: string) => JSON.stringify([file, "chromium", "case"])+const row = (file: string, shard: number, total: number) => ({ shard, total, specs: ["src/test/e2e-ui/" + file], native_shard: shard, native_total: total, case_keys: [key(file)] })+const reportSuite = (file: string, title = "case") => ({ file, specs: [{ title, tests: [{ projectName: "chromium" }] }] })+const reportFor = (...files: string[]) => ({ errors: [], suites: files.map(file => reportSuite(file)) })+const matrix = {include: [- { shard: 1, total: 2, specs: ["src/test/e2e-ui/a.spec.ts"] },- { shard: 2, total: 2, specs: ["src/test/e2e-ui/b.spec.ts"] },+ row("a.spec.ts", 1, 2),+ row("b.spec.ts", 2, 2),],}const singleShardMatrix = {include: [- { shard: 1, total: 1, specs: ["src/test/e2e-ui/a.spec.ts"] },+ row("a.spec.ts", 1, 1),],}@@ -48,6 +53,7 @@ function artifactRoot(attempts = [1, 2]) {shard,total: 2,specs: matrix.include[shard - 1]!.specs,+ nativeShard: shard, nativeTotal: 2, caseKeys: matrix.include[shard - 1]!.case_keys,}),))}@@ -68,6 +74,7 @@ function flatArtifactRoot() {shard: 1,total: 1,specs: singleShardMatrix.include[0]!.specs,+ nativeShard: 1, nativeTotal: 1, caseKeys: singleShardMatrix.include[0]!.case_keys,}),))return root@@ -89,8 +96,8 @@ describe("expectedMatrix", () => {it("rejects duplicate cross-shard assignment", () => {expect(() => expectedMatrix({ include: [- { shard: 1, total: 2, specs: ["src/test/e2e-ui/a.spec.ts"] },- { shard: 2, total: 2, specs: ["src/test/e2e-ui/a.spec.ts"] },+ row("a.spec.ts", 1, 2),+ row("a.spec.ts", 2, 2),] })).toThrow("assigned to shards")})})@@ -285,6 +292,8 @@ describe("verifyArtifactClosure", () => {it.each([["wrong run ID", (manifest: any) => { manifest.runId = "wrong" }, "run ID mismatch"],["wrong SHA", (manifest: any) => { manifest.sha = "wrong" }, "SHA mismatch"],+ ["wrong native identity", (manifest: any) => { manifest.nativeShard = 99 }, "native identity mismatch"],+ ["wrong cases", (manifest: any) => { manifest.caseKeys = [] }, "cases mismatch"],["wrong identity", (manifest: any) => { manifest.shard = 99 }, "manifest identity mismatch"],["wrong specs", (manifest: any) => { manifest.specs = ["unexpected.spec.ts"] }, "specs mismatch"],])("rejects %s", (_, mutate, message) => {@@ -370,21 +379,24 @@ describe("runCli", () => {"--sha", "def456","--shard", "1","--total", "2",+ "--native-shard", "1", "--native-total", "2","--output", output,], {E2E_SPECS: JSON.stringify(["src/test/e2e-ui/a.spec.ts"]),+ E2E_CASE_KEYS: JSON.stringify([key("a.spec.ts")]),})const contents = readFileSync(output, "utf8")expect(contents.endsWith("\n")).toBe(true)expect(JSON.parse(contents)).toEqual({- version: 1,+ version: 2,runId: "run-2",attempt: 2,sha: "def456",shard: 1,total: 2,specs: ["a.spec.ts"],+ nativeShard: 1, nativeTotal: 2, caseKeys: [key("a.spec.ts")],})})@@ -437,10 +449,7 @@ describe("runCli", () => {const root = mkdtempSync(join(tmpdir(), "alook-shard-cli-"))roots.push(root)const report = join(root, "report.json")- writeFileSync(report, JSON.stringify({ suites: [- { file: "src/test/e2e-ui/a.spec.ts" },- { file: "b.spec.ts" },- ] }))+ writeFileSync(report, JSON.stringify(reportFor("src/test/e2e-ui/a.spec.ts", "b.spec.ts")))await expect(runCli(["verify-merged",@@ -511,21 +520,19 @@ describe("runCliEntry", () => {})describe("verifyMergedReport", () => {- it("accepts the exact normalized unique spec set", () => {- expect(verifyMergedReport({- matrix,- report: { suites: [- { file: "a.spec.ts", suites: [] },- { file: "src/test/e2e-ui/b.spec.ts", suites: [] },- { file: "a.spec.ts", suites: [] },- ] },- })).toEqual(["a.spec.ts", "b.spec.ts"])+ it("accepts exact native file and case identities", () => {+ expect(verifyMergedReport({ matrix, report: reportFor("a.spec.ts", "src/test/e2e-ui/b.spec.ts") })).toEqual(["a.spec.ts", "b.spec.ts"])})it.each([- ["missing", [{ file: "a.spec.ts" }]],- ["unexpected", [{ file: "a.spec.ts" }, { file: "b.spec.ts" }, { file: "c.spec.ts" }]],- ])("rejects an exact-set %s report", (_, suites) => {- expect(() => verifyMergedReport({ matrix, report: { suites } })).toThrow("spec set mismatch")+ ["missing", ["a.spec.ts"]],+ ["unexpected", ["a.spec.ts", "b.spec.ts", "c.spec.ts"]],+ ])("rejects an exact-set %s report", (_, files) => {+ expect(() => verifyMergedReport({ matrix, report: reportFor(...files) })).toThrow("spec set mismatch")+ })++ it("rejects missing or duplicate cases even when files match", () => {+ expect(() => verifyMergedReport({ matrix, report: { errors: [], suites: [reportSuite("a.spec.ts"), reportSuite("b.spec.ts", "wrong")] } })).toThrow("case set mismatch")+ expect(() => verifyMergedReport({ matrix, report: reportFor("a.spec.ts", "a.spec.ts", "b.spec.ts") })).toThrow("duplicate native")})})diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjsindex 22db756ee..dff9e012e 100644--- a/scripts/ci/e2e-shards.mjs+++ b/scripts/ci/e2e-shards.mjs@@ -1,293 +1,139 @@-import { appendFileSync, readFileSync, readdirSync } from "node:fs"-import { relative, resolve } from "node:path"+import { appendFileSync, readFileSync } from "node:fs"+import { execFileSync } from "node:child_process"+import { createRequire } from "node:module"+import { resolve } from "node:path"import { fileURLToPath } from "node:url"+const ROOT = fileURLToPath(new URL("../..", import.meta.url))export const E2E_SPEC_ROOT = "src/web/src/test/e2e-ui"-export const E2E_SHARD_BUDGET_SECONDS = 240-export const E2E_FIXED_SETUP_SECONDS = 60-export const E2E_SAFETY_MARGIN_SECONDS = 15-export const E2E_SPEC_BUDGET_SECONDS = E2E_SHARD_BUDGET_SECONDS- - E2E_FIXED_SETUP_SECONDS- - E2E_SAFETY_MARGIN_SECONDS-export const DEFAULT_SPEC_SECONDS = E2E_SPEC_BUDGET_SECONDS+export const E2E_NATIVE_SHARDS = 24+export const E2E_TARGET_SECONDS = 240export const PLAYWRIGHT_IMAGE_REPOSITORY = "mcr.microsoft.com/playwright"--export const SPEC_SECONDS = {- "01-auth.spec.ts": 3.997,- "02-server-channel-message.spec.ts": 9.687,- "03-realtime-multiuser.spec.ts": 13.037,- "04-dm.spec.ts": 15.545,- "05-mention-bot.spec.ts": 4.117,- "06-channel-member-admin.spec.ts": 3.819,- "07-invite.spec.ts": 9.843,- "08-mobile.spec.ts": 37.929,- "09-forum-thread.spec.ts": 4.538,- "10-eject-nav-auth.spec.ts": 6.193,- "11-profile-ui-stability.spec.ts": 2.554,- "12-friends.spec.ts": 3.905,- "13-mentions.spec.ts": 9.591,- "14-forum-post-tags-presence.spec.ts": 16.213,- "15-mention-scope.spec.ts": 10.94,- "16-jump-to-present.spec.ts": 5.997,- "17-forum-sidebar-stage-b.spec.ts": 43.842,- "18-new-divider-scroll.spec.ts": DEFAULT_SPEC_SECONDS,- "19-marketing-seo.spec.ts": 1.713,- "20-community-attachment-thumbnails.spec.ts": 11.117,- "21-mobile-message-layout.spec.ts": 5.12,- "22-committed-message-delivery.spec.ts": 40.086,- "23-message-selection-context-menu.spec.ts": 3.392,- "24-composer-overflow.spec.ts": 12.763,- "25-community-ws-reconnect-overlay.spec.ts": 36.437,- "25-composer-accessory-rail-occupancy.spec.ts": 40.804,- "26-mobile-forum-post-actions.spec.ts": 21.297,- "27-canonical-forum-post-delete.spec.ts": 11.097,- "28-thread-realtime-audiences.spec.ts": 26.477,- "29-community-bot-avatar-cleanup.spec.ts": 8.216,- "29-multi-device-read-state.spec.ts": 72.169,- "30-bot-profile-audit-preview.spec.ts": 29.213,- "31-machine-guide-motion.spec.ts": 4.201,- "31-mention-candidate-pagination.spec.ts": 3.836,- "32-mobile-ws-foreground-validation.spec.ts": 95.792,- "33-picker-async-layout.spec.ts": 18.776,- "34-inbox-read-race.spec.ts": 26.519,- "35-bot-token-usage-quota.spec.ts": 10.867,- "35-channel-ref-directory-states.spec.ts": 12.626,- "36-server-switch-pending-checkpoint.spec.ts": 5.732,- "37-server-rail-dnd.spec.ts": 21.594,- "38-community-navigation-checkpoint-matrix.spec.ts": 4.646,- "39-mobile-composer-send.spec.ts": 16.534,- "39-mobile-message-interactions.spec.ts": 58.479,- "40-mobile-server-header-hierarchy.spec.ts": 14.449,- "40-server-rail-unread.spec.ts": 11.954,- "41-account-unread-projection.spec.ts": 28.753,- "41-community-initial-load-module-skeletons.spec.ts": 29.632,- "42-versioned-avatar-identity.spec.ts": 13.96,- "43-composer-attachment-drafts.spec.ts": 12.139,- "44-mobile-reaction-details.spec.ts": 32.952,- "45-desktop-thread-split-view.spec.ts": 11.647,- "46-community-loading-geometry-android.spec.ts": 49.779,- "46-community-loading-geometry-dark.spec.ts": 63.284,- "46-community-loading-geometry-light.spec.ts": 63.095,- "50-daemon-update-notice.spec.ts": 7.656,- "51-mobile-forum-tag-editor.spec.ts": 26.043,- "51-share-image-assets.spec.ts": 46.186,- "52-chat-composer-ordered-list.spec.ts": 16.531,- "53-mobile-inbox-surface.spec.ts": 8.362,- "54-authenticated-context-menu-policy.spec.ts": 13.721,- "54-blog-multizone.spec.ts": 5.485,- "55-message-scroll-characterization.spec.ts": DEFAULT_SPEC_SECONDS,- "56-inbox-friend-requests.spec.ts": 60,- "56-retired-workspace-links.spec.ts": DEFAULT_SPEC_SECONDS,- "57-server-delete-navigation-races.spec.ts": 55,- "58-system-notifications.spec.ts": 46.600,- "59-message-pagination-anchor.spec.ts": 45.600,- "60-desktop-default-user-bar-width.spec.ts": 83.700,- "63-mobile-notification-chat-route.spec.ts": DEFAULT_SPEC_SECONDS,- "64-billing-contact.spec.ts": 6,- "64-mobile-parent-return.spec.ts": DEFAULT_SPEC_SECONDS,- "65-analytics-document-boundary.spec.ts": DEFAULT_SPEC_SECONDS,- "66-grouped-message-toolbar.spec.ts": DEFAULT_SPEC_SECONDS,- "66-public-static-resource-cache.spec.ts": DEFAULT_SPEC_SECONDS,- "67-text-sidebar-threads.spec.ts": DEFAULT_SPEC_SECONDS,- "68-bot-memberships.spec.ts": DEFAULT_SPEC_SECONDS,- "69-table-fullscreen-scroll.spec.ts": DEFAULT_SPEC_SECONDS,- "70-renderer-action-themes.spec.ts": DEFAULT_SPEC_SECONDS,- "native-keyboard-viewport-projection.spec.ts": DEFAULT_SPEC_SECONDS,-}--function walk(directory) {- return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {- const path = resolve(directory, entry.name)- return entry.isDirectory() ? walk(path) : [path]- })-}--export function discoverE2eSpecs(root = resolve(E2E_SPEC_ROOT)) {- return walk(root)- .filter((path) => path.endsWith(".spec.ts"))- .map((path) => relative(root, path).replaceAll("\\", "/"))- .sort()-}--export function resolvePlaywrightVersion(lockfile = readFileSync(resolve("pnpm-lock.yaml"), "utf8")) {- const normalizedLockfile = lockfile.replaceAll("\r\n", "\n")- const importerStart = normalizedLockfile.indexOf("\n src/web:\n")- if (importerStart < 0) throw new Error("pnpm lockfile is missing the src/web importer")-- const importerBody = normalizedLockfile.slice(importerStart + 1)- const nextImporter = importerBody.slice(1).search(/\n \S[^\n]*:\n/)- const importer = nextImporter < 0- ? importerBody- : importerBody.slice(0, nextImporter + 1)- const dependency = importer.match(- /\n '@playwright\/test':\n(?: [^\n]*\n)*? version: ([^\s(]+)/,- )- if (!dependency) throw new Error("src/web importer is missing an exact @playwright/test version")- if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(dependency[1])) {- throw new Error(`invalid @playwright/test version: ${dependency[1]}`)- }- return dependency[1]+const sorted = values => [...new Set(values)].sort()+const normalize = value => value.replaceAll("\\", "/").replace(/^.*src\/test\/e2e-ui\//, "")++export function resolvePlaywrightVersion(lockfile = readFileSync(resolve(ROOT, "pnpm-lock.yaml"), "utf8")) {+ const text = lockfile.replaceAll("\r\n", "\n")+ const start = text.indexOf("\n src/web:\n")+ if (start < 0) throw new Error("pnpm lockfile is missing the src/web importer")+ const body = text.slice(start + 1)+ const end = body.slice(1).search(/\n \S[^\n]*:\n/)+ const importer = end < 0 ? body : body.slice(0, end + 1)+ const version = importer.match(/\n '@playwright\/test':\n(?: [^\n]*\n)*? version: ([^\s(]+)/)?.[1]+ if (!version) throw new Error("src/web importer is missing an exact @playwright/test version")+ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) throw new Error("invalid @playwright/test version: " + version)+ return version}export function resolvePlaywrightImage(lockfile) {return `${PLAYWRIGHT_IMAGE_REPOSITORY}:v${resolvePlaywrightVersion(lockfile)}-noble`}-function weightedSpecs(specs, weights, defaultSeconds, budgetSeconds) {- const uniqueSpecs = [...new Set(specs)]- if (uniqueSpecs.length !== specs.length) {- throw new Error("spec paths must be unique")- }- if (uniqueSpecs.length === 0) {- throw new Error("at least one spec is required")- }- if (uniqueSpecs.some((path) => typeof path !== "string" || path.length === 0)) {- throw new Error("spec paths must be non-empty strings")- }- if (!Number.isInteger(budgetSeconds) || budgetSeconds < 1) {- throw new Error("budgetSeconds must be a positive integer")+export function collectPlaywrightCases(report) {+ if (!report || !Array.isArray(report.suites) || !Array.isArray(report.errors) || report.errors.length) {+ throw new Error("native Playwright discovery failed")+ }+ const cases = []+ const visit = (suite, owner, parents) => {+ for (const spec of suite.specs || []) {+ if (!Array.isArray(spec.tests) || !spec.tests.length) throw new Error("native Playwright spec has no projects")+ for (const test of spec.tests) {+ const project = test.projectName || test.projectId+ if (typeof project !== "string" || typeof spec.title !== "string") throw new Error("invalid native Playwright case identity")+ cases.push({ key: JSON.stringify([owner, project, ...parents, spec.title]), file: owner })+ }+ }+ for (const child of suite.suites || []) visit(child, owner, [...parents, child.title])}- if (!Number.isFinite(defaultSeconds) || defaultSeconds <= 0) {- throw new Error("defaultSeconds must be a positive finite number")+ for (const suite of report.suites) {+ const file = normalize(suite.file || "")+ if (!file.endsWith(".spec.ts") || file.startsWith("/") || file.split("/").includes("..")) throw new Error("invalid native Playwright file")+ visit(suite, file, [])}-- return uniqueSpecs- .map((path) => ({- path,- seconds: Object.hasOwn(weights, path) ? weights[path] : defaultSeconds,- }))- .map((spec) => {- if (!Number.isFinite(spec.seconds) || spec.seconds <= 0) {- throw new Error(`spec estimate must be a positive finite number: ${spec.path}`)- }- if (spec.seconds > budgetSeconds) {- throw new Error(- `spec estimate exceeds the ${budgetSeconds}s Playwright budget: ${spec.path} (${spec.seconds}s); split the spec or add a stable case manifest`,- )- }- return spec- })- .sort((left, right) => right.seconds - left.seconds || left.path.localeCompare(right.path))-}--function roundedSeconds(value) {- return Math.round(value * 1_000) / 1_000+ if (new Set(cases.map(test => test.key)).size !== cases.length) throw new Error("duplicate native Playwright case")+ return cases.sort((left, right) => left.key.localeCompare(right.key))}-function packE2eShards(weighted, shardCount, fixedSetupSeconds, safetyMarginSeconds) {- const shards = Array.from({ length: shardCount }, (_, index) => ({- shard: index + 1,- spec_seconds: 0,- fixed_setup_seconds: fixedSetupSeconds,- safety_margin_seconds: safetyMarginSeconds,- predicted_seconds: roundedSeconds(fixedSetupSeconds + safetyMarginSeconds),- files: [],- }))-- for (const spec of weighted) {- const target = [...shards].sort(- (left, right) => left.spec_seconds - right.spec_seconds || left.shard - right.shard,- )[0]- target.files.push(spec.path)- target.spec_seconds = roundedSeconds(target.spec_seconds + spec.seconds)- target.predicted_seconds = roundedSeconds(- target.spec_seconds + fixedSetupSeconds + safetyMarginSeconds,- )- }-- return shards.map((shard) => ({- ...shard,- files: shard.files.sort(),- }))+export function listPlaywrightTests({ root = ROOT, specs = ["all"], shard, execute = execFileSync } = {}) {+ const web = resolve(root, "src/web")+ const require = createRequire(resolve(web, "package.json"))+ const cli = require.resolve("@playwright/test/cli")+ const args = [cli, "test", "--config", resolve(web, "playwright.config.ts"), "--list", "--reporter=json"]+ if (shard) args.push("--shard=" + shard.current + "/" + shard.total, "--pass-with-no-tests")+ if (!(specs.length === 1 && specs[0] === "all")) args.push(...specs.map(spec => "src/test/e2e-ui/" + normalize(spec)))+ const text = execute(process.execPath, args, {+ cwd: web, encoding: "utf8", maxBuffer: 16 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"],+ env: { ...process.env, PLAYWRIGHT_JSON_OUTPUT_FILE: "", PLAYWRIGHT_JSON_OUTPUT_DIR: "" },+ })+ const report = JSON.parse(text)+ if (report.config?.fullyParallel !== false || report.config?.workers !== 1+ || report.config?.projects?.some(project => project.retries !== 0)) throw new Error("native browser execution constraints changed")+ const cases = collectPlaywrightCases(report)+ return { files: sorted(cases.map(test => test.file)), cases }}-export function planE2eShards(specs, options = {}) {- const {- weights = SPEC_SECONDS,- defaultSeconds = DEFAULT_SPEC_SECONDS,- budgetSeconds = E2E_SHARD_BUDGET_SECONDS,- fixedSetupSeconds = E2E_FIXED_SETUP_SECONDS,- safetyMarginSeconds = E2E_SAFETY_MARGIN_SECONDS,- } = options- if (!Number.isFinite(fixedSetupSeconds) || fixedSetupSeconds < 0) {- throw new Error("fixedSetupSeconds must be a non-negative finite number")- }- if (!Number.isFinite(safetyMarginSeconds) || safetyMarginSeconds < 0) {- throw new Error("safetyMarginSeconds must be a non-negative finite number")- }- const specBudgetSeconds = budgetSeconds - fixedSetupSeconds - safetyMarginSeconds- if (!Number.isFinite(specBudgetSeconds) || specBudgetSeconds <= 0) {- throw new Error("fixed setup and safety margin must leave a positive spec budget")- }- const weighted = weightedSpecs(specs, weights, defaultSeconds, specBudgetSeconds)- const totalSeconds = weighted.reduce((total, spec) => total + spec.seconds, 0)- let shardCount = Math.ceil(totalSeconds / specBudgetSeconds)- let shards = packE2eShards(weighted, shardCount, fixedSetupSeconds, safetyMarginSeconds)-- while (shards.some((shard) => shard.spec_seconds > specBudgetSeconds)) {- shardCount += 1- shards = packE2eShards(weighted, shardCount, fixedSetupSeconds, safetyMarginSeconds)- }- return shards+export function discoverE2eSpecs(root = ROOT, execute) {+ return listPlaywrightTests({ root, execute }).files}-export function createE2eMatrix(specs = discoverE2eSpecs(), image = resolvePlaywrightImage()) {- const inventory = discoverE2eSpecs()- if (specs.includes("all") && !(specs.length === 1 && specs[0] === "all")) {- throw new Error("the all sentinel cannot be combined with explicit specs")- }- const selected = specs.length === 1 && specs[0] === "all" ? inventory : specs- const unknown = selected.filter((spec) => !inventory.includes(spec))- if (unknown.length > 0) {- throw new Error(`specs are outside the UI inventory: ${unknown.join(", ")}`)- }- const shards = planE2eShards(selected)- return {- include: shards.map((shard) => ({- shard: shard.shard,- total: shards.length,- image,- spec_seconds: shard.spec_seconds,- fixed_setup_seconds: shard.fixed_setup_seconds,- safety_margin_seconds: shard.safety_margin_seconds,- predicted_seconds: shard.predicted_seconds,- specs: shard.files.map((path) => `src/test/e2e-ui/${path}`),- })),- }+export function validateNativeUiFacts(facts, requested) {+ if (!facts || facts.version !== 1 || !Array.isArray(facts.files) || !facts.files.length+ || !Array.isArray(facts.cases) || !facts.cases.length || !Array.isArray(facts.shards) || !facts.shards.length) {+ throw new Error("native UI discovery is incomplete")+ }+ const selection = sorted(requested.map(normalize))+ if (JSON.stringify(selection) !== JSON.stringify(facts.selection)) throw new Error("native UI selection mismatch")+ if (!selection.includes("all") && JSON.stringify(selection) !== JSON.stringify(facts.files)) throw new Error("selected UI files lack native registrations")+ const keys = sorted(facts.cases.map(test => test.key))+ if (keys.length !== facts.cases.length || JSON.stringify(sorted(facts.cases.map(test => test.file))) !== JSON.stringify(facts.files)) throw new Error("native UI inventory is inconsistent")+ const owned = [], files = []+ for (let index = 0; index < facts.shards.length; index++) {+ const shard = facts.shards[index]+ if (shard.current !== index + 1 || shard.total !== facts.shards.length+ || !Array.isArray(shard.cases) || !Array.isArray(shard.files)) throw new Error("native UI shard identity mismatch")+ const identities = facts.cases.filter(test => shard.cases.includes(test.key))+ if (identities.length !== shard.cases.length || JSON.stringify(sorted(identities.map(test => test.file))) !== JSON.stringify(shard.files)) throw new Error("native UI shard case/file mismatch")+ owned.push(...shard.cases); files.push(...shard.files)+ }+ if (owned.length !== keys.length || JSON.stringify(sorted(owned)) !== JSON.stringify(keys)+ || files.length !== facts.files.length || JSON.stringify(sorted(files)) !== JSON.stringify(facts.files)) throw new Error("native UI partitions are missing or duplicate")+ if (facts.playwright_version !== resolvePlaywrightVersion()) throw new Error("native UI Playwright version mismatch")+ return facts}-function parseArgs(argv) {- const args = {}- for (let index = 0; index < argv.length; index += 1) {- const key = argv[index].replace(/^--/, "").replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())- args[key] = argv[++index]- }- return args+export function queryNativeUiFacts(specs, { root = ROOT, shardCount = E2E_NATIVE_SHARDS, execute } = {}) {+ if (!Array.isArray(specs) || !specs.length || specs.some(spec => typeof spec !== "string")+ || new Set(specs).size !== specs.length || (specs.includes("all") && specs.length !== 1)) throw new Error("invalid UI selection")+ const all = listPlaywrightTests({ root, specs, execute })+ if (!all.files.length) throw new Error("selected UI files have no native registrations")+ const count = Math.min(Number(shardCount), all.files.length)+ if (!Number.isInteger(count) || count < 1) throw new Error("native UI shard count must be positive")+ const shards = []+ for (let current = 1; current <= count; current++) {+ const part = listPlaywrightTests({ root, specs, shard: { current, total: count }, execute })+ shards.push({ current, total: count, files: part.files, cases: part.cases.map(test => test.key) })+ }+ return validateNativeUiFacts({ version: 1, playwright_version: resolvePlaywrightVersion(), selection: sorted(specs.map(normalize)), files: all.files, cases: all.cases, shards }, specs)}-function writeSummary(path, matrix) {- const rows = matrix.include- .map((shard) => `| ${shard.shard}/${shard.total} | ${shard.spec_seconds}s | ${shard.fixed_setup_seconds}s | ${shard.safety_margin_seconds}s | ${shard.predicted_seconds}s | \`${shard.specs.join(" ")}\` |`)- .join("\n")- appendFileSync(- path,- `## UI E2E shards\n\nPredicted Playwright command step; ${E2E_SHARD_BUDGET_SECONDS}s budget per shard. Each total includes measured spec time, fixed service setup, and an explicit safety margin.\n\n| Shard | Specs | Fixed setup | Margin | Predicted total | Files |\n| --- | ---: | ---: | ---: | ---: | --- |\n${rows}\n`,- )+export function createE2eMatrix(facts, image = resolvePlaywrightImage()) {+ validateNativeUiFacts(facts, facts.selection)+ const active = facts.shards.filter(shard => shard.cases.length)+ return { include: active.map((part, index) => ({+ shard: index + 1, total: active.length, native_shard: part.current, native_total: part.total, image,+ specs: part.files.map(file => "src/test/e2e-ui/" + file), case_keys: part.cases,+ })) }}-export function runCli(argv) {- const args = parseArgs(argv)- const specs = args.specsJson ? JSON.parse(args.specsJson) : discoverE2eSpecs()- if (!Array.isArray(specs) || specs.some((spec) => typeof spec !== "string")) {- throw new Error("--specs-json must be a JSON array of spec paths")- }- const matrix = createE2eMatrix(specs)- const json = JSON.stringify(matrix)- if (args.output) appendFileSync(args.output, `e2e_matrix=${json}\n`)- if (args.summary) writeSummary(args.summary, matrix)- if (!args.output) process.stdout.write(`${JSON.stringify(matrix, null, 2)}\n`)+export function runCli(argv, { root = ROOT, execute } = {}) {+ const args = {}+ for (let index = 0; index < argv.length; index += 2) args[argv[index].replace(/^--/, "")] = argv[index + 1]+ const specs = args["specs-json"] ? JSON.parse(args["specs-json"]) : ["all"]+ const facts = queryNativeUiFacts(specs, { root, shardCount: args.shards || E2E_NATIVE_SHARDS, execute })+ const matrix = createE2eMatrix(facts)+ if (args.output) appendFileSync(args.output, "e2e_matrix=" + JSON.stringify(matrix) + "\n")+ else process.stdout.write(JSON.stringify({ facts, matrix }, null, 2) + "\n")+ if (args.summary) appendFileSync(args.summary, `## Native UI shards\n\n${facts.cases.length} registered cases in ${facts.files.length} files; ${matrix.include.length} nonempty native partitions. ${E2E_TARGET_SECONDS}s is a measurement target, not a predicted cutoff.\n`)}-if (process.argv[1] === fileURLToPath(import.meta.url)) {- runCli(process.argv.slice(2))-}+if (process.argv[1] === fileURLToPath(import.meta.url)) runCli(process.argv.slice(2))diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.tsindex 02792f168..847e64cc1 100644--- a/scripts/ci/e2e-shards.test.ts+++ b/scripts/ci/e2e-shards.test.ts@@ -1,298 +1,131 @@-import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"+import { execFileSync, type ExecFileSyncOptionsWithStringEncoding } from "node:child_process"+import { createHash } from "node:crypto"+import { mkdirSync, readdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"import { tmpdir } from "node:os"-import { join } from "node:path"-import { describe, expect, it, vi } from "vitest"+import { join, resolve } from "node:path"+import { afterAll, describe, expect, it, vi } from "vitest"import {+ collectPlaywrightCases,createE2eMatrix,- DEFAULT_SPEC_SECONDS,discoverE2eSpecs,- E2E_FIXED_SETUP_SECONDS,- E2E_SAFETY_MARGIN_SECONDS,- E2E_SHARD_BUDGET_SECONDS,- E2E_SPEC_BUDGET_SECONDS,- planE2eShards,+ listPlaywrightTests,+ queryNativeUiFacts,resolvePlaywrightImage,resolvePlaywrightVersion,runCli,- SPEC_SECONDS,+ validateNativeUiFacts,} from "./e2e-shards.mjs"-describe("resolvePlaywrightVersion", () => {- const lockfile = `-importers:-- src/web:- devDependencies:- '@playwright/test':- specifier: ^1.62.1- version: 1.62.1-- src/ws-do:- dependencies: {}-`-- it("resolves the exact web importer version and official image", () => {- expect(resolvePlaywrightVersion(lockfile)).toBe("1.62.1")+const root = mkdtempSync(join(tmpdir(), "alook-native-playwright-"))+const web = join(root, "src/web")+const specRoot = join(web, "src/test/e2e-ui")+mkdirSync(specRoot, { recursive: true })+writeFileSync(join(web, "package.json"), '{"type":"module"}')+symlinkSync(resolve("src/web/node_modules"), join(web, "node_modules"), process.platform === "win32" ? "junction" : "dir")+const config = 'export default { testDir: "./src/test/e2e-ui", fullyParallel: false, workers: 1, retries: 0, projects: [{ name: "chromium" }] }'+writeFileSync(join(web, "playwright.config.ts"), config)+writeFileSync(join(specRoot, "a.spec.ts"), 'import { test } from "@playwright/test"; test.describe("owned", () => { for (let i = 0; i < 8; i++) test("case " + i, () => {}) })')+writeFileSync(join(specRoot, "b.spec.ts"), 'import "./imported.journey"')+writeFileSync(join(specRoot, "imported.journey.ts"), 'import { test } from "@playwright/test"; test("imported registration", () => {})')+writeFileSync(join(specRoot, "c.spec.ts"), 'import { test } from "@playwright/test"; test("last", () => {})')+afterAll(() => rmSync(root, { recursive: true, force: true }))++// Cache only successful native command text for identical controlled inputs.+// Each caller still parses and validates it. Source/config edits change the key;+// production callers keep the uncached executor.+const nativeOutput = new Map<string, string>()+const execute = (command: string, args: string[], options: ExecFileSyncOptionsWithStringEncoding) => {+ const inputs = [join(web, "package.json"), join(web, "playwright.config.ts"),+ ...readdirSync(specRoot).sort().map(file => join(specRoot, file))]+ const hash = createHash("sha256")+ for (const file of inputs) hash.update(file).update("\0").update(readFileSync(file)).update("\0")+ const key = JSON.stringify([command, args, options.cwd, hash.digest("hex")])+ if (!nativeOutput.has(key)) nativeOutput.set(key, execFileSync(command, args, options))+ return nativeOutput.get(key)!+}+const facts = () => queryNativeUiFacts(["all"], { root, shardCount: 3, execute })++describe("locked Playwright image", () => {+ const lockfile = "\n src/web:\n devDependencies:\n '@playwright/test':\n specifier: ^1.62.1\n version: 1.62.1\n\n src/ws-do:\n dependencies: {}\n"+ it("uses the exact importer, including CRLF", () => {expect(resolvePlaywrightVersion(lockfile.replaceAll("\n", "\r\n"))).toBe("1.62.1")- expect(resolvePlaywrightImage(lockfile)).toBe(- "mcr.microsoft.com/playwright:v1.62.1-noble",- )+ expect(resolvePlaywrightImage(lockfile)).toBe("mcr.microsoft.com/playwright:v1.62.1-noble")})-- it("rejects missing importers, missing dependencies, and malformed versions", () => {- expect(() => resolvePlaywrightVersion("importers:\n")).toThrow("src/web importer")- expect(() => resolvePlaywrightVersion(lockfile.replace("'@playwright/test'", "vitest")))- .toThrow("exact @playwright/test version")- expect(() => resolvePlaywrightVersion(lockfile.replace("version: 1.62.1", "version: latest")))- .toThrow("invalid @playwright/test version")+ it.each(["importers:\n", lockfile.replace("'@playwright/test'", "vitest"), lockfile.replace("version: 1.62.1", "version: latest")])("rejects an unresolved version", source => {+ expect(() => resolvePlaywrightVersion(source)).toThrow()})})-describe("discoverE2eSpecs", () => {- it("discovers nested specs in deterministic order", () => {- const root = mkdtempSync(join(tmpdir(), "alook-e2e-specs-"))- try {- mkdirSync(join(root, "nested"))- writeFileSync(join(root, "z.spec.ts"), "")- writeFileSync(join(root, "nested", "a.spec.ts"), "")- writeFileSync(join(root, "ignored.ts"), "")-- expect(discoverE2eSpecs(root)).toEqual(["nested/a.spec.ts", "z.spec.ts"])- } finally {- rmSync(root, { recursive: true, force: true })+describe("native discovery and partition closure", () => {+ it("discovers actual registrations, including an imported journey owned by its spec", () => {+ expect(discoverE2eSpecs(root, execute)).toEqual(["a.spec.ts", "b.spec.ts", "c.spec.ts"])+ const value = facts()+ expect(value.cases).toHaveLength(10)+ expect(value.cases).toContainEqual({ file: "b.spec.ts", key: '["b.spec.ts","chromium","imported registration"]' })+ expect(value.cases.filter(test => test.file === "a.spec.ts")).toHaveLength(8)+ const matrix = createE2eMatrix(value)+ expect(matrix.include.flatMap(part => part.case_keys).sort()).toEqual(value.cases.map(test => test.key).sort())+ expect(matrix.include.flatMap(part => part.specs).sort()).toEqual(["a.spec.ts", "b.spec.ts", "c.spec.ts"].map(file => "src/test/e2e-ui/" + file))+ expect(matrix.include.map(part => part.shard)).toEqual(matrix.include.map((_, index) => index + 1))+ for (const part of matrix.include) {+ expect(part.native_total).toBe(3)+ expect(part.case_keys).toEqual(value.shards[part.native_shard - 1]!.cases)}+ expect(matrix.include.length).toBeLessThan(3)})-})-describe("planE2eShards", () => {- it("assigns every spec exactly once with deterministic duration balance", () => {- const specs = discoverE2eSpecs()- const first = planE2eShards(specs)- const second = planE2eShards([...specs].reverse())- const assigned = first.flatMap((shard) => shard.files)- const specSeconds = first.map((shard) => shard.spec_seconds)- const predictedSeconds = first.map((shard) => shard.predicted_seconds)-- expect(first).toEqual(second)- expect(Object.keys(SPEC_SECONDS).sort()).toEqual(specs)- expect(first).toHaveLength(23)- expect([...assigned].sort()).toEqual(specs)- expect(new Set(assigned).size).toBe(specs.length)- expect(SPEC_SECONDS["18-new-divider-scroll.spec.ts"]).toBe(DEFAULT_SPEC_SECONDS)- expect(SPEC_SECONDS["55-message-scroll-characterization.spec.ts"]).toBe(DEFAULT_SPEC_SECONDS)- expect(SPEC_SECONDS["66-public-static-resource-cache.spec.ts"]).toBe(DEFAULT_SPEC_SECONDS)- expect(SPEC_SECONDS["66-grouped-message-toolbar.spec.ts"]).toBe(DEFAULT_SPEC_SECONDS)- expect(SPEC_SECONDS["67-text-sidebar-threads.spec.ts"]).toBe(DEFAULT_SPEC_SECONDS)- expect(SPEC_SECONDS["68-bot-memberships.spec.ts"]).toBe(DEFAULT_SPEC_SECONDS)- expect(SPEC_SECONDS["70-renderer-action-themes.spec.ts"]).toBe(DEFAULT_SPEC_SECONDS)- expect(SPEC_SECONDS["native-keyboard-viewport-projection.spec.ts"]).toBe(DEFAULT_SPEC_SECONDS)- expect(first.find((shard) => shard.files.includes("native-keyboard-viewport-projection.spec.ts"))?.files)- .toEqual(["native-keyboard-viewport-projection.spec.ts"])- expect(first.find((shard) => shard.files.includes("70-renderer-action-themes.spec.ts"))?.files)- .toEqual(["70-renderer-action-themes.spec.ts"])- expect(SPEC_SECONDS["69-table-fullscreen-scroll.spec.ts"]).toBe(DEFAULT_SPEC_SECONDS)- expect(first.find((shard) => shard.files.includes("69-table-fullscreen-scroll.spec.ts"))?.files)- .toEqual(["69-table-fullscreen-scroll.spec.ts"])- expect(SPEC_SECONDS["64-mobile-parent-return.spec.ts"]).toBe(DEFAULT_SPEC_SECONDS)- expect(first.find((shard) => shard.files.includes("64-mobile-parent-return.spec.ts"))?.files)- .toEqual(["64-mobile-parent-return.spec.ts"])- expect(first.find((shard) => shard.files.includes("66-public-static-resource-cache.spec.ts"))?.files)- .toEqual(["66-public-static-resource-cache.spec.ts"])- expect(first.find((shard) => shard.files.includes("66-grouped-message-toolbar.spec.ts"))?.files)- .toEqual(["66-grouped-message-toolbar.spec.ts"])- expect(first.find((shard) => shard.files.includes("67-text-sidebar-threads.spec.ts"))?.files)- .toEqual(["67-text-sidebar-threads.spec.ts"])- expect(specSeconds).toEqual([- 165, 165, 165, 165, 165, 165, 165, 165, 165, 165, 165, 165, 165, 155.638, 154.234, 155.283,- 156.095, 155.905, 156.323, 155.711, 153.963, 154.488, 156.138,- ])- expect(predictedSeconds).toEqual([- 240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 230.638, 229.234, 230.283,- 231.095, 230.905, 231.323, 230.711, 228.963, 229.488, 231.138,- ])- expect(first.every((shard) => (- shard.fixed_setup_seconds === E2E_FIXED_SETUP_SECONDS- && shard.safety_margin_seconds === E2E_SAFETY_MARGIN_SECONDS- && shard.predicted_seconds- === shard.spec_seconds + E2E_FIXED_SETUP_SECONDS + E2E_SAFETY_MARGIN_SECONDS- ))).toBe(true)- expect(Math.max(...predictedSeconds)).toBeLessThanOrEqual(E2E_SHARD_BUDGET_SECONDS)- expect(first).toHaveLength(- Math.ceil(specSeconds.reduce((total, seconds) => total + seconds, 0)- / E2E_SPEC_BUDGET_SECONDS),- )- })-- it("includes an unknown spec with a conservative default weight", () => {- const shards = planE2eShards(["known.spec.ts", "new.spec.ts"], {- weights: { "known.spec.ts": 5 },- })-- expect(shards.flatMap((shard) => shard.files).sort()).toEqual([- "known.spec.ts",- "new.spec.ts",- ])- expect(DEFAULT_SPEC_SECONDS).toBe(E2E_SPEC_BUDGET_SECONDS)- expect(shards.find((shard) => shard.files.includes("new.spec.ts"))?.files)- .toEqual(["new.spec.ts"])- expect(shards.map((shard) => shard.spec_seconds).sort((a, b) => a - b))- .toEqual([5, E2E_SPEC_BUDGET_SECONDS])- expect(shards.map((shard) => shard.predicted_seconds).sort((a, b) => a - b))- .toEqual([80, E2E_SHARD_BUDGET_SECONDS])- })-- it("increments the total-time lower bound when LPT does not fit", () => {- const weights = {- "a.spec.ts": 3,- "b.spec.ts": 3,- "c.spec.ts": 2,- "d.spec.ts": 2,- "e.spec.ts": 2,+ it("selects one real file and rejects unknown, duplicate or mixed-sentinel selections", () => {+ const value = queryNativeUiFacts(["b.spec.ts"], { root, execute })+ expect(value.files).toEqual(["b.spec.ts"])+ expect(value.cases).toHaveLength(1)+ for (const specs of [["missing.spec.ts"], ["b.spec.ts", "b.spec.ts"], ["all", "b.spec.ts"], []]) {+ expect(() => queryNativeUiFacts(specs, { root, execute })).toThrow()}- const shards = planE2eShards(Object.keys(weights), {- weights,- budgetSeconds: 6,- fixedSetupSeconds: 0,- safetyMarginSeconds: 0,- })-- expect(Math.ceil(12 / 6)).toBe(2)- expect(shards).toHaveLength(3)- expect(shards.every((shard) => shard.spec_seconds <= 6)).toBe(true)})- it("rejects duplicate or empty paths and invalid planning values", () => {- expect(() => planE2eShards(["a.spec.ts", "a.spec.ts"])).toThrow("unique")- expect(() => planE2eShards([])).toThrow("at least one")- expect(() => planE2eShards([""])).toThrow("non-empty strings")- expect(() => planE2eShards(["a.spec.ts"], { budgetSeconds: 0 }))- .toThrow("positive spec budget")- expect(() => planE2eShards(["a.spec.ts"], {- budgetSeconds: 1.5,- fixedSetupSeconds: 0,- safetyMarginSeconds: 0,- })).toThrow("budgetSeconds must be a positive integer")- expect(() => planE2eShards(["a.spec.ts"], { defaultSeconds: Number.NaN }))- .toThrow("positive finite")- expect(() => planE2eShards(["a.spec.ts"], { weights: { "a.spec.ts": 0 } }))- .toThrow("positive finite")- expect(() => planE2eShards(["a.spec.ts"], { fixedSetupSeconds: Number.NaN }))- .toThrow("non-negative finite")- expect(() => planE2eShards(["a.spec.ts"], { safetyMarginSeconds: -1 }))- .toThrow("non-negative finite")+ it("rejects native errors and incomplete or duplicate partitions", () => {+ expect(() => collectPlaywrightCases({ suites: [], errors: [{}] })).toThrow("discovery failed")+ const value = facts()+ const duplicate = structuredClone(value)+ duplicate.shards[0]!.cases.push(duplicate.shards[0]!.cases[0]!)+ expect(() => validateNativeUiFacts(duplicate, ["all"])).toThrow()+ const missing = structuredClone(value)+ missing.shards[0]!.cases.pop()+ expect(() => validateNativeUiFacts(missing, ["all"])).toThrow()+ expect(() => validateNativeUiFacts(value, ["b.spec.ts"])).toThrow("selection mismatch")+ expect(() => validateNativeUiFacts({ ...value, playwright_version: "0.0.0" }, ["all"])).toThrow("version mismatch")})- it("requires an oversized spec to be split or given a stable case manifest", () => {- expect(() => planE2eShards(["slow.spec.ts"], {- weights: { "slow.spec.ts": E2E_SPEC_BUDGET_SECONDS + 0.001 },- })).toThrow("split the spec or add a stable case manifest")- })-})--describe("createE2eMatrix", () => {- it("emits shell-safe repo-local spec arguments", () => {- const matrix = createE2eMatrix([- "01-auth.spec.ts",- "02-server-channel-message.spec.ts",- "03-realtime-multiuser.spec.ts",- "04-dm.spec.ts",- "05-mention-bot.spec.ts",- ])- const argumentsList = matrix.include.flatMap((entry) => entry.specs)-- expect(argumentsList.sort()).toEqual([- "src/test/e2e-ui/01-auth.spec.ts",- "src/test/e2e-ui/02-server-channel-message.spec.ts",- "src/test/e2e-ui/03-realtime-multiuser.spec.ts",- "src/test/e2e-ui/04-dm.spec.ts",- "src/test/e2e-ui/05-mention-bot.spec.ts",- ])- expect(matrix.include).toHaveLength(1)- expect(matrix.include.every((entry) => entry.total === 1)).toBe(true)- expect(matrix.include[0]).toMatchObject({- spec_seconds: 46.383,- fixed_setup_seconds: 60,- safety_margin_seconds: 15,- predicted_seconds: 121.383,- })- expect(matrix.include.every(- (entry) => entry.image === resolvePlaywrightImage(),- )).toBe(true)- })-- it("creates one shard for the Blog contract and rejects specs outside inventory", () => {- const matrix = createE2eMatrix(["54-blog-multizone.spec.ts"])-- expect(matrix.include).toHaveLength(1)- expect(matrix.include[0]).toMatchObject({- shard: 1,- total: 1,- spec_seconds: 5.485,- fixed_setup_seconds: 60,- safety_margin_seconds: 15,- predicted_seconds: 80.485,- specs: ["src/test/e2e-ui/54-blog-multizone.spec.ts"],- })- expect(() => createE2eMatrix(["future.spec.ts"])).toThrow("inventory")- })-- it("expands the all sentinel to the exact live inventory", () => {- const matrix = createE2eMatrix(["all"])- const assigned = matrix.include.flatMap((entry) => entry.specs)-- expect(assigned).toHaveLength(discoverE2eSpecs().length)- expect(new Set(assigned).size).toBe(assigned.length)- })-- it("rejects the all sentinel when combined with explicit specs", () => {- expect(() => createE2eMatrix(["all", "54-blog-multizone.spec.ts"]))- .toThrow("all sentinel")- })-})--describe("E2E shard CLI", () => {- it("writes an explicit matrix and human-readable summary", () => {- const directory = mkdtempSync(join(tmpdir(), "alook-e2e-cli-"))- const output = join(directory, "output")- const summary = join(directory, "summary.md")+ it("refreshes native observations when execution constraints or imported registrations change", () => {+ const journey = join(specRoot, "imported.journey.ts")+ const original = readFileSync(journey, "utf8")try {- runCli([- "--specs-json", JSON.stringify(["54-blog-multizone.spec.ts"]),- "--output", output,- "--summary", summary,- ])-- expect(readFileSync(output, "utf8")).toContain(- "src/test/e2e-ui/54-blog-multizone.spec.ts",- )- expect(readFileSync(summary, "utf8")).toContain(- "| 1/1 | 5.485s | 60s | 15s | 80.485s |",- )- expect(readFileSync(summary, "utf8")).toContain(- "Predicted Playwright command step; 240s budget per shard",- )+ writeFileSync(join(web, "playwright.config.ts"), config.replace("fullyParallel: false", "fullyParallel: true"))+ expect(() => queryNativeUiFacts(["all"], { root, execute })).toThrow("constraints changed")+ writeFileSync(join(web, "playwright.config.ts"), config)+ writeFileSync(journey, original + '; test("new imported registration", () => {})')+ const changed = listPlaywrightTests({ root, execute })+ expect(changed.cases).toHaveLength(11)+ expect(changed.cases.filter(test => test.file === "b.spec.ts")).toHaveLength(2)+ expect(changed.cases).toContainEqual({ file: "b.spec.ts", key: '["b.spec.ts","chromium","new imported registration"]' })} finally {- rmSync(directory, { recursive: true, force: true })+ writeFileSync(join(web, "playwright.config.ts"), config)+ writeFileSync(journey, original)}+ expect(listPlaywrightTests({ root, execute }).cases).toHaveLength(10)})+})- it("prints the default live inventory without an output file", () => {+describe("native shard CLI", () => {+ it("writes native matrix and a target without prediction claims", () => {+ const output = join(root, "output"), summary = join(root, "summary.md")+ runCli(["--specs-json", '["b.spec.ts"]', "--output", output, "--summary", summary], { root, execute })+ expect(JSON.parse(readFileSync(output, "utf8").trim().slice("e2e_matrix=".length)).include[0]).toMatchObject({ native_shard: 1, native_total: 1, specs: ["src/test/e2e-ui/b.spec.ts"] })+ expect(readFileSync(summary, "utf8")).toContain("not a predicted cutoff")const stdout = vi.spyOn(process.stdout, "write").mockImplementation(() => true)try {- runCli([])-- const matrix = JSON.parse(stdout.mock.calls.map(([value]) => String(value)).join(""))- expect(matrix.include.flatMap((entry: { specs: string[] }) => entry.specs))- .toHaveLength(discoverE2eSpecs().length)- } finally {- stdout.mockRestore()- }- })-- it("rejects malformed specs JSON values", () => {- expect(() => runCli(["--specs-json", JSON.stringify({ spec: "54-blog-multizone.spec.ts" })]))- .toThrow("JSON array")- expect(() => runCli(["--specs-json", JSON.stringify([42])]))- .toThrow("JSON array")+ runCli(["--shards", "1"], { root, execute })+ expect(JSON.parse(String(stdout.mock.calls[0]![0])).facts.cases).toHaveLength(10)+ } finally { stdout.mockRestore() }})})diff --git a/scripts/ci/extract-report-artifacts.test.ts b/scripts/ci/extract-report-artifacts.test.tsindex af938dde8..5d857a005 100644--- a/scripts/ci/extract-report-artifacts.test.ts+++ b/scripts/ci/extract-report-artifacts.test.ts@@ -8,7 +8,10 @@ import { createShardManifest, verifyArtifactClosure, verifyMergedReport } from "const root = resolve(import.meta.dirname, "../..")const extractor = join(root, "scripts/ci/extract-report-artifacts.py")const temporary: string[] = []-const matrix = { include: [{ shard: 1, total: 1, specs: ["a.spec.ts"] }] }+const caseKey = (file: string) => JSON.stringify([file, "chromium", "case"])+const row = (file: string, shard: number, total: number) => ({ shard, total, specs: [file], native_shard: shard, native_total: total, case_keys: [caseKey(file)] })+const matrix = { include: [row("a.spec.ts", 1, 1)] }+const singleReport = { errors: [], suites: [{ file: "a.spec.ts", specs: [{ title: "case", tests: [{ projectName: "chromium" }] }] }] }afterEach(() => {for (const directory of temporary.splice(0)) rmSync(directory, { recursive: true, force: true })@@ -77,7 +80,8 @@ print(json.dumps({"blob": base64.b64encode(blob).decode(), "early": early, "bounfunction archive(directory: string, options: Record<string, unknown> = {}, shard = 1, total = 1, attempt = 1) {mkdirSync(directory, { recursive: true })- const manifest = createShardManifest({ runId: "run-1", attempt, sha: "source-sha", shard, total, specs: [`${shard === 1 ? "a" : "b"}.spec.ts`] })+ const file = `${shard === 1 ? "a" : "b"}.spec.ts`+ const manifest = createShardManifest({ runId: "run-1", attempt, sha: "source-sha", shard, total, specs: [file], nativeShard: shard, nativeTotal: total, caseKeys: [caseKey(file)] })const result = execFileSync("python3", ["-c", fixtureBuilder, join(directory, "opaque-download"), JSON.stringify(manifest), JSON.stringify(options)], { encoding: "utf8" })return { manifest, ...JSON.parse(result) as { blob: string; early: number | null; boundary: number | null } }}@@ -100,7 +104,7 @@ describe("central-directory report artifact extraction", () => {expect(JSON.parse(readFileSync(join(output, "e2e-shard-manifest/shard-manifest.json"), "utf8"))).toEqual(expected.manifest)expect(readFileSync(join(raw, "opaque-download"))).toEqual(before)expect(verifyArtifactClosure({ root: output, output: join(directory, "verified"), matrix, runId: "run-1", attempt: 1, sha: "source-sha", executedShards: new Set([1]) }).manifests).toEqual([expected.manifest])- expect(verifyMergedReport({ report: { suites: [{ file: "a.spec.ts" }] }, matrix })).toEqual(["a.spec.ts"])+ expect(verifyMergedReport({ report: singleReport, matrix })).toEqual(["a.spec.ts"])})it("retains named multi-artifact directories and the original source, spec and attempt guards", () => {@@ -110,13 +114,13 @@ describe("central-directory report artifact extraction", () => {archive(join(raw, "blob-report-run-1-2"), { directories: true }, 2, 2, 2)const output = join(directory, "extracted")expect(extract(raw, output).status).toBe(0)- const two = { include: [...matrix.include.map(entry => ({ ...entry, total: 2 })), { shard: 2, total: 2, specs: ["b.spec.ts"] }] }+ const two = { include: [row("a.spec.ts", 1, 2), row("b.spec.ts", 2, 2)] }const args = { root: output, output: join(directory, "verified"), matrix: two, runId: "run-1", attempt: 2, sha: "source-sha", executedShards: new Set([2]) }expect(verifyArtifactClosure(args).manifests.map(item => item.attempt)).toEqual([1, 2])expect(() => verifyArtifactClosure({ ...args, sha: "wrong" })).toThrow("SHA mismatch")expect(() => verifyArtifactClosure({ ...args, executedShards: new Set([1, 2]) })).toThrow("artifact is stale")- expect(() => verifyArtifactClosure({ ...args, matrix: { include: [two.include[0], { ...two.include[1], specs: ["wrong.spec.ts"] }] } })).toThrow("specs mismatch")- expect(() => verifyMergedReport({ report: { suites: [{ file: "a.spec.ts" }] }, matrix: two })).toThrow("merged report spec set mismatch")+ expect(() => verifyArtifactClosure({ ...args, matrix: { include: [two.include[0], { ...two.include[1], specs: ["wrong.spec.ts"], case_keys: [caseKey("wrong.spec.ts")] }] } })).toThrow("specs mismatch")+ expect(() => verifyMergedReport({ report: singleReport, matrix: two })).toThrow("merged report spec set mismatch")})it.each(["../escape.zip", "/escape.zip", "blob-report/../escape.zip", "blob-report\\escape.zip", "C:/escape.zip", "blob-report/./report.zip"])("rejects unsafe member %s before publishing output", member => {diff --git a/scripts/ci/verify-changed-patch-coverage.mjs b/scripts/ci/report-changed-patch-coverage.mjssimilarity index 84%rename from scripts/ci/verify-changed-patch-coverage.mjsrename to scripts/ci/report-changed-patch-coverage.mjsindex c24a7f0be..8e3b70a40 100644--- a/scripts/ci/verify-changed-patch-coverage.mjs+++ b/scripts/ci/report-changed-patch-coverage.mjs@@ -33,6 +33,29 @@ function normalizedPath(path) {return path.replaceAll("\\", "/").replace(/^\.\//, "")}+export function validateCoverageReport(report) {+ const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value)+ if (!record(report)) throw new Error("coverage report must be an Istanbul file map")+ for (const [path, file] of Object.entries(report)) {+ if (!record(file)) throw new Error(`invalid Istanbul file: ${path}`)+ for (const [mapName, countsName] of [["statementMap", "s"], ["fnMap", "f"], ["branchMap", "b"]]) {+ const map = file[mapName], counts = file[countsName]+ if (!record(map) || !record(counts)+ || JSON.stringify(Object.keys(map).sort()) !== JSON.stringify(Object.keys(counts).sort())) {+ throw new Error(`invalid Istanbul ${countsName} map: ${path}`)+ }+ for (const value of Object.values(counts)) {+ const values = countsName === "b" && Array.isArray(value) ? value : [value]+ if ((countsName === "b" && !Array.isArray(value))+ || values.some((count) => typeof count !== "number" || !Number.isFinite(count) || count < 0)) {+ throw new Error(`invalid Istanbul ${countsName} counter: ${path}`)+ }+ }+ }+ }+ return report+}+export function parseAddedLines(diff) {const changed = new Map()let path = null@@ -189,7 +212,7 @@ export function runCli(argv) {trackedDiff,head === "WORKTREE" ? untrackedAddedLinesDiff(root) : "",].filter(Boolean).join("\n")- const report = JSON.parse(readFileSync(resolve(args.report), "utf8"))+ const report = validateCoverageReport(JSON.parse(readFileSync(resolve(args.report), "utf8")))const result = collectChangedPatchCoverage(parseAddedLines(diff), report, { root })const output = `${JSON.stringify(result, null, 2)}\n`if (args.output) writeFileSync(resolve(args.output), output)@@ -199,9 +222,6 @@ export function runCli(argv) {for (const file of result.files.filter((entry) => entry.missed > 0)) {process.stdout.write(`${file.path}: ${file.missed_lines.join(", ")}\n`)}- if (result.missed_lines > 0) {- throw new Error(`changed patch has ${result.missed_lines} uncovered executable lines`)- }return result}diff --git a/scripts/ci/verify-changed-patch-coverage.test.ts b/scripts/ci/report-changed-patch-coverage.test.tssimilarity index 89%rename from scripts/ci/verify-changed-patch-coverage.test.tsrename to scripts/ci/report-changed-patch-coverage.test.tsindex ad81b9737..f6c3ff80a 100644--- a/scripts/ci/verify-changed-patch-coverage.test.ts+++ b/scripts/ci/report-changed-patch-coverage.test.ts@@ -17,12 +17,24 @@ import {isolatedRepositoryGitEnvironment,parseAddedLines,runCli,-} from "./verify-changed-patch-coverage.mjs"+ validateCoverageReport,+} from "./report-changed-patch-coverage.mjs"function location(line: number) {return { start: { line, column: 0 }, end: { line, column: 1 } }}+it("keeps malformed reports fatal while allowing genuine uncovered counters", () => {+ const file = { path: "source.ts", statementMap: { "0": location(1) }, s: { "0": 0 }, fnMap: {}, f: {}, branchMap: {}, b: {} }+ expect(validateCoverageReport({ "source.ts": file })).toEqual({ "source.ts": file })+ for (const value of [null, [], "not a file map"]) {+ expect(() => validateCoverageReport(value)).toThrow("Istanbul file map")+ }+ expect(() => validateCoverageReport({ "source.ts": { ...file, s: {} } })).toThrow("invalid Istanbul s map")+ expect(() => validateCoverageReport({ "source.ts": { ...file, s: { "0": "1" } } })).toThrow("invalid Istanbul s counter")+ expect(() => validateCoverageReport({ "source.ts": { ...file, branchMap: { "0": {} }, b: { "0": -1 } } })).toThrow("invalid Istanbul b counter")+})+function git(root: string, ...args: string[]) {return execFileSync("git", args, {cwd: root,@@ -258,7 +270,7 @@ describe("changed patch coverage", () => {}})- it("supports an explicit head and reports every missed file before failing", () => {+ it("supports an explicit head and reports misses without enforcing a percentage", () => {const parent = poisonParentGitEnvironment()let root: string | undefinedconst stdout = vi.spyOn(process.stdout, "write").mockImplementation(() => true)@@ -270,12 +282,13 @@ describe("changed patch coverage", () => {git(root, "commit", "--quiet", "-m", "head")const reportPath = writeReport(root, "src/base.mjs", 0)- expect(() => runCli([+ const result = runCli(["--base", base,"--head", "HEAD","--report", reportPath,"--root", root,- ])).toThrow("changed patch has 1 uncovered executable lines")+ ])+ expect(result).toMatchObject({ covered_lines: 0, missed_lines: 1, total_lines: 1, percent: 0 })expect(stdout).toHaveBeenCalledWith(expect.stringContaining("0/1 lines"))expect(stdout).toHaveBeenCalledWith("src/base.mjs: 1\n")parent.expectUnchanged()diff --git a/scripts/ci/run-turbo.mjs b/scripts/ci/run-turbo.mjsnew file mode 100644index 000000000..eaa5e59cf--- /dev/null+++ b/scripts/ci/run-turbo.mjs@@ -0,0 +1,49 @@+import { execFileSync, spawnSync } from "node:child_process"+import { realpathSync } from "node:fs"+import { fileURLToPath } from "node:url"+import { isolatedRepositoryGitEnvironment } from "./report-changed-patch-coverage.mjs"+import { validatePlanEnvelope } from "./validate-execution-plan.mjs"++const ROOT = realpathSync(fileURLToPath(new URL("../..", import.meta.url)))++export function taskEnvironment(root = ROOT) {+ let bun = "unavailable"+ try { bun = execFileSync("bun", ["--version"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() } catch {}+ const libc = process.platform === "linux" ? "-glibc" + (process.report.getReport().header.glibcVersionRuntime || "unavailable") : ""+ return {+ ...isolatedRepositoryGitEnvironment(),+ ALOOK_TASK_PLATFORM: process.platform + "-" + process.arch + libc,+ ALOOK_TASK_NODE: process.versions.node,+ ALOOK_TASK_BUN: bun,+ ALOOK_TASK_WORKSPACE: realpathSync(root),+ }+}++export function executeTurbo(args, { root = ROOT, stdio = "inherit" } = {}) {+ return spawnSync("pnpm", ["exec", "turbo", ...args], {+ cwd: root,+ env: taskEnvironment(root),+ stdio,+ encoding: "utf8",+ maxBuffer: 16 * 1024 * 1024,+ shell: process.platform === "win32",+ })+}++export function runCli(argv = process.argv.slice(2)) {+ let args = argv+ if (args[0] === "--plan-group") {+ const group = args[1]+ if (!["static_tasks", "build_tasks", "knip_tasks", "unit_build_tasks"].includes(group)) throw new Error("unknown native task group")+ const plan = validatePlanEnvelope({ planJson: process.env.CI_EXECUTION_PLAN, planFile: process.env.CI_EXECUTION_PLAN_FILE, planHash: process.env.CI_PLAN_HASH })+ if (!plan.native_tasks) throw new Error("native task inventory is required for execution")+ if (!plan.suites[group].length) return+ args = ["run", ...plan.suites[group], ...args.slice(2)]+ }+ const result = executeTurbo(args)+ if (result.error) throw result.error+ if (result.signal) process.kill(process.pid, result.signal)+ else process.exitCode = result.status ?? 1+}++if (process.argv[1] === fileURLToPath(import.meta.url)) runCli()diff --git a/scripts/ci/run-unit-tests.mjs b/scripts/ci/run-unit-tests.mjsnew file mode 100644index 000000000..a52cc9bc1--- /dev/null+++ b/scripts/ci/run-unit-tests.mjs@@ -0,0 +1,173 @@+import { mkdirSync, readFileSync, writeFileSync } from "node:fs"+import { dirname, relative, resolve } from "node:path"+import { fileURLToPath } from "node:url"+import { createVitest } from "vitest/node"+import { loadScopeManifest, validateExecutionPlan } from "./changed-scopes.mjs"+import { validatePlanEnvelope } from "./validate-execution-plan.mjs"++const ROOT = resolve(fileURLToPath(new URL("../..", import.meta.url)))+export const CI_DEDICATED_TEST_FILES = [+ "src/daemon/agent-driver/src/pack.test.ts",+ "src/daemon/src/cli/daemonLifecycle.real.test.ts",+ "src/daemon/src/cli/diagnosticsLifecycle.real.test.ts",+ "src/daemon/src/cli/daemonStop.test.ts",+ "src/daemon/src/version.packed.test.ts",+ "src/daemon/src/agent-driver-bundle.packed.test.ts",+ "src/daemon/src/cli/daemonSelfUpdate.real.test.ts",+]+const dedicatedFiles = new Set(CI_DEDICATED_TEST_FILES.map(file => resolve(ROOT, file)))++export function unitProjects(plan, manifest = loadScopeManifest()) {+ if (plan.suites.smoke.length) return { projects: undefined, fullProjects: [], smoke: plan.suites.smoke }+ const tasks = plan.full+ ? Object.keys(manifest.unit_tasks)+ : plan.suites.unit_tasks+ const projects = new Set(plan.full ? ["ci-scripts"] : [])+ const fullProjects = new Set(plan.full ? ["ci-scripts"] : [])+ for (const task of tasks) {+ const entry = manifest.unit_tasks[task]+ if (!entry) throw new Error("unit task has no execution project: " + task)+ for (const project of entry.projects) {+ projects.add(project)+ if (entry.selection === "project") fullProjects.add(project)+ }+ }+ return { projects: [...projects].sort(), fullProjects: [...fullProjects].sort(), smoke: [] }+}++function moduleInput(path) {+ return /\.[cm]?[jt]sx?$/.test(path)+ && !/(?:^|\/)(?:vitest[^/]*|tsconfig[^/]*|eslint[^/]*|next\.config|open-next\.config|.*setup[^/]*|.*env[^/]*)\.[^/]+$/.test(path)+}++export function projectFullReason(plan) {+ if (plan.full) return plan.full_reason || "full_policy"+ if (plan.changes.some((change) => !change.status.startsWith("M"))) return "added_deleted_or_renamed_input"+ if (plan.paths.some((path) => !moduleInput(path))) return "nonmodule_input"+ return null+}++export async function selectUnitSpecifications(ctx, plan, scope, { ci = false } = {}) {+ const allowedProjects = scope.projects && new Set(scope.projects)+ const inScope = (spec) => !allowedProjects || allowedProjects.has(spec.project.name)+ const discovered = (await ctx.globTestSpecifications(scope.smoke)).filter(inScope)+ const delegated = ci ? discovered.filter(spec => dedicatedFiles.has(spec.moduleId)) : []+ const eligible = spec => inScope(spec) && (!ci || !dedicatedFiles.has(spec.moduleId))+ const all = discovered.filter(eligible)+ const fullReason = scope.smoke.length ? "main_smoke" : projectFullReason(plan)+ let selected+ let fallback = null+ if (fullReason) selected = all+ else {+ try {+ selected = all.length ? (await ctx.getRelevantTestSpecifications(all.map((spec) => spec.moduleId))).filter(eligible) : []+ } catch (error) {+ fallback = { reason: "native_related_analysis_failed", detail: error instanceof Error ? error.message : String(error) }+ selected = all+ }+ const fullProjects = new Set(scope.fullProjects)+ const directlyChanged = new Set(plan.changes.flatMap((change) => [+ resolve(ROOT, change.path), ...(change.old_path ? [resolve(ROOT, change.old_path)] : []),+ ]))+ selected.push(...all.filter((spec) => fullProjects.has(spec.project.name) || directlyChanged.has(spec.moduleId)))+ }+ const identity = (spec) => JSON.stringify([spec.project.name, spec.moduleId])+ const specs = [...new Map(selected.map((spec) => [identity(spec), spec])).values()]+ .sort((left, right) => identity(left).localeCompare(identity(right)))+ return {+ specs,+ receipt: {+ plan_hash: plan.plan_hash,+ mode: fallback ? "project_full" : fullReason || "native_related",+ fallback,+ cache: "bypassed",+ execution: null,+ discovered_files: discovered.length,+ delegated_files: delegated.map(spec => ({ project: spec.project.name, file: relative(ROOT, spec.moduleId).replaceAll("\\", "/") })),+ selected_files: specs.length,+ projects: scope.projects || [],+ files: specs.map((spec) => ({ project: spec.project.name, file: relative(ROOT, spec.moduleId).replaceAll("\\", "/") })),+ },+ }+}++export async function runUnitTests(plan, { ci = false, list = false, receiptFile, coverage = false } = {}) {+ validateExecutionPlan(plan)+ const scope = unitProjects(plan)+ if (scope.projects?.length === 0 && !scope.smoke.length) return null+ process.env.TEST = "true"+ process.env.VITEST = "true"+ process.env.NODE_ENV ??= "test"+ const opts = {+ root: ROOT,+ watch: false,+ project: coverage ? undefined : scope.projects,+ passWithNoTests: coverage,+ related: plan.full || scope.smoke.length ? undefined : plan.paths.map((path) => resolve(ROOT, path)),+ ...(coverage ? {+ coverage: {+ enabled: true,+ provider: "istanbul",+ include: plan.coverage.include_roots,+ reporter: ["json", "text"],+ reportOnFailure: true,+ },+ reporters: ["default", "blob"],+ outputFile: { blob: resolve(ROOT, ".vitest-reports/unit.blob") },+ } : {}),+ }+ const ctx = await createVitest(opts)+ try {+ if (coverage && !list) await ctx.standalone()+ const selected = await selectUnitSpecifications(ctx, plan, scope, { ci })+ if (receiptFile) {+ mkdirSync(dirname(resolve(receiptFile)), { recursive: true })+ writeFileSync(receiptFile, JSON.stringify(selected.receipt, null, 2) + "\n")+ }+ process.stdout.write(JSON.stringify(selected.receipt, null, 2) + "\n")+ if (list || (selected.specs.length === 0 && !coverage)) return selected.receipt+ if (!coverage) await ctx.standalone()+ const result = await ctx.runTestSpecifications(selected.specs, true)+ selected.receipt.execution = {+ unhandled_errors: result.unhandledErrors.length,+ files: result.testModules.map((module) => ({+ project: module.project.name,+ file: relative(ROOT, module.moduleId).replaceAll("\\", "/"),+ state: module.state(),+ ok: module.ok(),+ })),+ }+ if (receiptFile) writeFileSync(receiptFile, JSON.stringify(selected.receipt, null, 2) + "\n")+ if (result.unhandledErrors.length || result.testModules.some((module) => !module.ok())) {+ throw new Error("selected unit tests failed")+ }+ const actual = new Set(result.testModules.map((module) => JSON.stringify([module.project.name, module.moduleId])))+ if (selected.specs.some((spec) => !actual.has(JSON.stringify([spec.project.name, spec.moduleId])))) {+ throw new Error("selected unit test did not execute")+ }+ return selected.receipt+ } finally {+ await ctx.close()+ }+}++export async function runCli(argv = process.argv.slice(2), env = process.env) {+ const args = { ci: false, list: false, coverage: false }+ let planFile+ for (let index = 0; index < argv.length; index++) {+ const flag = argv[index]+ if (flag === "--ci") args.ci = true+ else if (flag === "--list") args.list = true+ else if (flag === "--coverage") args.coverage = true+ else if (flag === "--receipt") args.receiptFile = argv[++index]+ else if (flag === "--plan") planFile = argv[++index]+ else throw new Error("unknown or incomplete unit option: " + flag)+ }+ const plan = planFile ? validateExecutionPlan(JSON.parse(readFileSync(planFile, "utf8")))+ : validatePlanEnvelope({ planJson: env.CI_EXECUTION_PLAN, planFile: env.CI_EXECUTION_PLAN_FILE, planHash: env.CI_PLAN_HASH })+ return runUnitTests(plan, args)+}++if (process.argv[1] === fileURLToPath(import.meta.url)) {+ runCli().catch((error) => { process.stderr.write(String(error) + "\n"); process.exitCode = 1 })+}diff --git a/scripts/ci/run-unit-tests.test.ts b/scripts/ci/run-unit-tests.test.tsnew file mode 100644index 000000000..96fc3760c--- /dev/null+++ b/scripts/ci/run-unit-tests.test.ts@@ -0,0 +1,96 @@+import { resolve } from "node:path"+import { describe, expect, it, vi } from "vitest"+import { projectFullReason, selectUnitSpecifications, unitProjects } from "./run-unit-tests.mjs"++const spec = (project: string, file: string) => ({ project: { name: project }, moduleId: resolve(file) })+const plan = (path: string, status = "M") => ({+ full: false, plan_hash: "selection-fixture", paths: [path],+ changes: [{ path, status }], suites: { unit_tasks: ["@alook/web#test"], smoke: [] },+})++describe("native unit selection boundary", () => {+ it("admits the App filesystem contract when the native import graph has no related files", async () => {+ const app = { ...plan("src/web/src/lib/worker-runtime.ts"), suites: { unit_tasks: ["@alook/app#test"], smoke: [] } }+ const packed = spec("@alook/app", "src/app/test/packed-artifact.test.ts")+ const ordinary = spec("@alook/app", "src/app/test/index.test.ts")+ const ctx = { globTestSpecifications: async () => [packed, ordinary, spec("web-node", "src/web/src/lib/worker-runtime.test.ts")], getRelevantTestSpecifications: async () => [] }+ const selected = await selectUnitSpecifications(ctx, app, unitProjects(app))+ expect(selected.specs).toEqual(expect.arrayContaining([packed, ordinary]))+ expect(selected.specs).toHaveLength(2)+ expect(selected.receipt.fallback).toBeNull()+ })++ it("delegates the seven process and package cases only in CI", async () => {+ const files = [+ "src/daemon/agent-driver/src/pack.test.ts",+ "src/daemon/src/cli/daemonLifecycle.real.test.ts",+ "src/daemon/src/cli/diagnosticsLifecycle.real.test.ts",+ "src/daemon/src/cli/daemonStop.test.ts",+ "src/daemon/src/version.packed.test.ts",+ "src/daemon/src/agent-driver-bundle.packed.test.ts",+ "src/daemon/src/cli/daemonSelfUpdate.real.test.ts",+ ]+ const ordinary = spec("daemon-node", "src/daemon/src/config.test.ts")+ const all = [...files.map(file => spec(file.includes("agent-driver/src") ? "@alook/agent-driver" : "daemon-node", file)), ordinary]+ const ctx = { globTestSpecifications: async () => all }+ const scope = { projects: ["daemon-node", "@alook/agent-driver"], fullProjects: [], smoke: [] }+ const full = { ...plan("source.ts"), full: true }+ const selected = await selectUnitSpecifications(ctx, full, scope, { ci: true })+ expect(selected.specs).toEqual([ordinary])+ expect(selected.receipt.delegated_files.map(file => file.file).sort()).toEqual(files.sort())+ expect((await selectUnitSpecifications(ctx, full, scope)).specs).toHaveLength(8)+ })++ it("keeps native related, direct changed tests, and project contracts once per identity", async () => {+ const direct = spec("web-node", "direct.test.ts")+ const related = spec("web-dom", "related.dom.test.ts")+ const contract = spec("web-contracts", "architecture.test.ts")+ const unrelated = spec("web-node", "unrelated.test.ts")+ const ctx = {+ globTestSpecifications: vi.fn(async () => [direct, related, contract, unrelated, spec("blog-node", "foreign.test.ts")]),+ getRelevantTestSpecifications: vi.fn(async () => [related, related, spec("blog-node", "foreign.test.ts")]),+ }+ const result = await selectUnitSpecifications(ctx, plan("direct.test.ts"), {+ projects: ["web-node", "web-dom", "web-contracts"], fullProjects: ["web-contracts"], smoke: [],+ })+ expect(result.specs).toEqual(expect.arrayContaining([direct, related, contract]))+ expect(result.specs).toHaveLength(3)+ expect(result.receipt.fallback).toBeNull()+ expect(result.receipt.discovered_files).toBe(4)+ })++ it("reports a graph error and keeps the complete affected project set", async () => {+ const files = [spec("web-node", "a.test.ts"), spec("blog-node", "b.test.ts")]+ const ctx = { globTestSpecifications: async () => files, getRelevantTestSpecifications: async () => { throw new Error("MDX graph rejected") } }+ const result = await selectUnitSpecifications(ctx, plan("source.ts"), { projects: ["web-node", "blog-node"], fullProjects: [], smoke: [] })+ expect(result.specs).toHaveLength(2)+ expect(result.receipt).toMatchObject({ mode: "project_full", fallback: { reason: "native_related_analysis_failed", detail: "MDX graph rejected" } })+ })++ it.each(["A", "D", "R100"])("keeps project scope for %s rather than losing old/new paths", async status => {+ const ctx = { globTestSpecifications: async () => [spec("web-node", "a.test.ts")], getRelevantTestSpecifications: vi.fn() }+ const result = await selectUnitSpecifications(ctx, plan("source.ts", status), { projects: ["web-node"], fullProjects: [], smoke: [] })+ expect(result.receipt.mode).toBe("added_deleted_or_renamed_input")+ expect(result.specs).toHaveLength(1)+ expect(ctx.getRelevantTestSpecifications).not.toHaveBeenCalled()+ })++ it.each(["post.mdx", "migrations/001.sql", "vitest.shared.ts", "react-dom-setup.ts", "next.config.ts", ".env"])("keeps project scope for nonmodule/config input %s", path => {+ expect(projectFullReason(plan(path))).toBe("nonmodule_input")+ })++ it("distinguishes a valid zero related result from a failed analysis", async () => {+ const ctx = { globTestSpecifications: async () => [spec("web-node", "a.test.ts")], getRelevantTestSpecifications: async () => [] }+ const result = await selectUnitSpecifications(ctx, plan("source.ts"), { projects: ["web-node"], fullProjects: [], smoke: [] })+ expect(result.receipt).toMatchObject({ mode: "native_related", fallback: null, selected_files: 0 })+ })++ it("rejects an unmapped native unit task and retains structural project execution", () => {+ const unknown = plan("source.ts")+ unknown.suites.unit_tasks = ["@alook/web#test:unknown"]+ expect(() => unitProjects(unknown)).toThrow("no execution project")+ const contracts = plan("source.ts")+ contracts.suites.unit_tasks = ["@alook/web#test:contracts"]+ expect(unitProjects(contracts)).toEqual({ projects: ["web-contracts"], fullProjects: ["web-contracts"], smoke: [] })+ })+})diff --git a/scripts/ci/validate-execution-plan.mjs b/scripts/ci/validate-execution-plan.mjsindex f34b6cffb..7de3b1c64 100644--- a/scripts/ci/validate-execution-plan.mjs+++ b/scripts/ci/validate-execution-plan.mjs@@ -1,9 +1,12 @@+import { readFileSync } from "node:fs"import { fileURLToPath } from "node:url"import { projectPlan, validateExecutionPlan } from "./changed-scopes.mjs"-export function validatePlanEnvelope({ planJson, planHash, projectionName, projectionValue }) {- if (!planJson) throw new Error("CI execution plan is required")- const plan = validateExecutionPlan(JSON.parse(planJson))+export function validatePlanEnvelope({ planJson, planFile, planHash, projectionName, projectionValue }) {+ if (planJson && planFile) throw new Error("choose one execution plan input")+ const body = planFile ? readFileSync(planFile, "utf8") : planJson+ if (!body) throw new Error("CI execution plan is required")+ const plan = validateExecutionPlan(JSON.parse(body))if (plan.plan_hash !== planHash) throw new Error("CI execution plan envelope hash mismatch")if (projectionName) {@@ -21,6 +24,7 @@ export function validatePlanEnvelope({ planJson, planHash, projectionName, projeexport function runCli(env = process.env) {const plan = validatePlanEnvelope({planJson: env.CI_EXECUTION_PLAN,+ planFile: env.CI_EXECUTION_PLAN_FILE,planHash: env.CI_PLAN_HASH,projectionName: env.CI_PROJECTION_NAME,projectionValue: env.CI_PROJECTION_VALUE,diff --git a/scripts/ci/validate-execution-plan.test.ts b/scripts/ci/validate-execution-plan.test.tsindex 2aedf4a89..7c6a2ccfc 100644--- a/scripts/ci/validate-execution-plan.test.ts+++ b/scripts/ci/validate-execution-plan.test.ts@@ -1,13 +1,36 @@+import { mkdtempSync, rmSync, writeFileSync } from "node:fs"+import { tmpdir } from "node:os"+import { join } from "node:path"import { describe, expect, it, vi } from "vitest"import { buildExecutionPlan, projectPlan, stablePlanJson } from "./changed-scopes.mjs"+import { queryNativeUiFacts } from "./e2e-shards.mjs"import { runCli, runIfMain, validatePlanEnvelope } from "./validate-execution-plan.mjs"const plan = buildExecutionPlan([{ status: "M", path: "src/daemon/src/manager.ts" }],- { baseSha: "a".repeat(40), headSha: "b".repeat(40) },+ { baseSha: "a".repeat(40), headSha: "b".repeat(40), nativeUi: queryNativeUiFacts(["all"], { shardCount: 1 }) },)describe("execution plan consumer envelope", () => {+ it("validates a real full plan from a file and rejects altered bytes", () => {+ const directory = mkdtempSync(join(tmpdir(), "alook-plan-file-"))+ const file = join(directory, "execution-plan.json")+ const body = stablePlanJson(plan)+ expect(Buffer.byteLength(body)).toBeGreaterThan(32_767)+ try {+ writeFileSync(file, body)+ expect(validatePlanEnvelope({ planFile: file, planHash: plan.plan_hash })).toEqual(plan)+ const stdout = vi.spyOn(process.stdout, "write").mockImplementation(() => true)+ try {+ runCli({ CI_EXECUTION_PLAN_FILE: file, CI_PLAN_HASH: plan.plan_hash })+ expect(stdout).toHaveBeenCalledWith(expect.stringContaining(plan.plan_hash))+ } finally { stdout.mockRestore() }+ expect(() => validatePlanEnvelope({ planFile: file, planJson: body, planHash: plan.plan_hash })).toThrow("choose one")+ writeFileSync(file, stablePlanJson({ ...plan, head_sha: "c".repeat(40) }))+ expect(() => validatePlanEnvelope({ planFile: file, planHash: plan.plan_hash })).toThrow("hash mismatch")+ } finally { rmSync(directory, { recursive: true, force: true }) }+ })+it("validates the canonical hash and a mechanical projection", () => {expect(validatePlanEnvelope({planJson: stablePlanJson(plan),diff --git a/scripts/ci/verify-coverage-plan.mjs b/scripts/ci/verify-coverage-plan.mjsindex 3f36b58c8..7a7305659 100644--- a/scripts/ci/verify-coverage-plan.mjs+++ b/scripts/ci/verify-coverage-plan.mjs@@ -2,6 +2,7 @@ import { existsSync, readFileSync, writeFileSync } from "node:fs"import { isAbsolute, relative, resolve } from "node:path"import { fileURLToPath } from "node:url"import ts from "typescript"+import { validateCoverageReport } from "./report-changed-patch-coverage.mjs"import {loadScopeManifest,validateExecutionPlan,@@ -55,6 +56,7 @@ export function verifyCoveragePlan(plan, report, options = {}) {const root = options.root || ROOTconst manifest = options.manifest || loadScopeManifest()validateExecutionPlan(plan, { manifest })+ validateCoverageReport(report)const files = Object.entries(report).map(([key, value]) => ({path: normalizeReportPath(value.path || key, root),@@ -96,14 +98,8 @@ export function verifyCoveragePlan(plan, report, options = {}) {throw new Error(`Codecov project target ${targetName} requires a nonempty denominator`)}const percent = (totals.covered / totals.statements) * 100- if (percent < target.target) {- throw new Error(- `Codecov project target ${targetName} is ${percent.toFixed(2)}%, below ${target.target}%`,- )- }targets[targetName] = {path: target.path,- target: target.target,files: targetFiles.length,statements: totals.statements,covered: totals.covered,diff --git a/scripts/ci/verify-coverage-plan.test.ts b/scripts/ci/verify-coverage-plan.test.tsindex 078851206..d61438874 100644--- a/scripts/ci/verify-coverage-plan.test.ts+++ b/scripts/ci/verify-coverage-plan.test.ts@@ -1,14 +1,29 @@import { createHash } from "node:crypto"+import { execFileSync } from "node:child_process"import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"import { tmpdir } from "node:os"import { join, resolve } from "node:path"import { describe, expect, it } from "vitest"-import { buildExecutionPlan, stablePlanJson } from "./changed-scopes.mjs"-import { runCli, runIfMain, verifyCoveragePlan } from "./verify-coverage-plan.mjs"+import { buildExecutionPlan as createExecutionPlan, queryNativeTasks, stablePlanJson } from "./changed-scopes.mjs"+import { runCli, verifyCoveragePlan } from "./verify-coverage-plan.mjs"const baseSha = "a".repeat(40)const headSha = "b".repeat(40)+let nativeInventory: ReturnType<typeof queryNativeTasks>["inventory"]+function buildExecutionPlan(changes, options) {+ if (!nativeInventory) {+ const head = execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim()+ nativeInventory = queryNativeTasks({ baseSha: head, headSha: head }).inventory+ }+ const selected = changes.every(change => change.path.startsWith("src/web/")) ? ["@alook/web"]+ : changes.every(change => change.path.startsWith("src/email-worker/")) ? ["@alook/email-worker"] : null+ return createExecutionPlan(changes, {+ ...options,+ nativeTasks: { inventory: nativeInventory, affected: nativeInventory.filter(task => !selected || selected.includes(task.package.name)) },+ })+}+function coveredFile(path: string, covered = true) {return {path,@@ -30,6 +45,14 @@ function resignPlan(value) {}describe("verifyCoveragePlan", () => {+ it("rejects corrupt counters independently of informational coverage percentages", () => {+ const changed = "src/email-worker/src/index.ts"+ const plan = buildExecutionPlan([{ status: "M", path: changed }], { baseSha, headSha })+ const corrupt = coveredFile(changed)+ corrupt.s["0"] = Number.NaN+ expect(() => verifyCoveragePlan(plan, { [changed]: corrupt })).toThrow("invalid Istanbul s counter")+ expect(() => verifyCoveragePlan(plan, { [changed]: { path: changed } })).toThrow("invalid Istanbul s map")+ })it("audits the type-only navigation model without waiving the project denominator", () => {const changed = "src/web/src/lib/community/models/navigation.ts"const runtime = "src/web/src/lib/config.ts"@@ -125,7 +148,7 @@ describe("verifyCoveragePlan", () => {expect(() => verifyCoveragePlan(fixtureOnly, {})).toThrow("nonempty denominator")})- it("proves required changed files and a nonempty passing Codecov project denominator", () => {+ it("proves required changed files and a nonempty Codecov project denominator", () => {const changed = "src/email-worker/src/index.ts"const plan = buildExecutionPlan([{ status: "M", path: changed }], { baseSha, headSha })const report = {@@ -161,7 +184,7 @@ describe("verifyCoveragePlan", () => {}})- it("rejects empty and below-target Codecov project reports", () => {+ it("reports zero project percentages but rejects empty instrumentation", () => {const changed = "src/shared/src/semver.ts"const plan = buildExecutionPlan([{ status: "M", path: changed }], { baseSha, headSha })const testOnlyPlan = buildExecutionPlan(@@ -170,13 +193,18 @@ describe("verifyCoveragePlan", () => {)expect(() => verifyCoveragePlan(testOnlyPlan, {})).toThrow("nonempty denominator")- expect(() => verifyCoveragePlan(plan, {- [resolve("src/email-worker/src/lib/imap-client.ts")]: coveredFile(resolve("src/email-worker/src/lib/imap-client.ts")),- [resolve("src/email-worker/src/index.ts")]: coveredFile(resolve("src/email-worker/src/index.ts")),+ const result = verifyCoveragePlan(plan, {+ [resolve("src/email-worker/src/lib/imap-client.ts")]: coveredFile(resolve("src/email-worker/src/lib/imap-client.ts"), false),+ [resolve("src/email-worker/src/index.ts")]: coveredFile(resolve("src/email-worker/src/index.ts"), false),[resolve(changed)]: coveredFile(resolve(changed), false),- [resolve("src/web/src/lib/config.ts")]: coveredFile(resolve("src/web/src/lib/config.ts")),- [resolve("src/ws-do/src/index.ts")]: coveredFile(resolve("src/ws-do/src/index.ts")),- })).toThrow("project target shared")+ [resolve("src/web/src/lib/config.ts")]: coveredFile(resolve("src/web/src/lib/config.ts"), false),+ [resolve("src/ws-do/src/index.ts")]: coveredFile(resolve("src/ws-do/src/index.ts"), false),+ })+ expect(Object.keys(result.targets).sort()).toEqual(["email-worker", "shared", "web", "ws-do"])+ for (const target of Object.values(result.targets)) {+ expect(target).toMatchObject({ covered: 0, percent: 0 })+ expect(target.statements).toBeGreaterThan(0)+ }})it("rejects targets absent from the Codecov contract", () => {@@ -187,10 +215,10 @@ describe("verifyCoveragePlan", () => {expect(() => verifyCoveragePlan(resignPlan(invalid), {[resolve(changed)]: coveredFile(resolve(changed)),- })).toThrow("unknown Codecov project target")+ })).toThrow("execution plan projections do not match native tasks and event policy")})- it("writes an auditable target manifest from the CLI", () => {+ it("writes a zero-coverage report through the real CLI without a percentage failure", () => {const changed = "src/email-worker/src/index.ts"const plan = buildExecutionPlan([{ status: "M", path: changed }], { baseSha, headSha })const directory = mkdtempSync(join(tmpdir(), "alook-coverage-plan-"))@@ -200,7 +228,7 @@ describe("verifyCoveragePlan", () => {try {writeFileSync(planPath, JSON.stringify(plan))writeFileSync(reportPath, JSON.stringify({- [resolve(changed)]: coveredFile(resolve(changed)),+ [resolve(changed)]: coveredFile(resolve(changed), false),}))const args = ["--plan", planPath,@@ -208,14 +236,11 @@ describe("verifyCoveragePlan", () => {"--output", outputPath,"--unused-value", "ignored",]- runIfMain(- "file:///tmp/verify-coverage-plan.mjs",- "/tmp/verify-coverage-plan.mjs",- args,- )+ execFileSync(process.execPath, ["scripts/ci/verify-coverage-plan.mjs", ...args], { stdio: "pipe" })expect(JSON.parse(readFileSync(outputPath, "utf8"))).toMatchObject({plan_hash: plan.plan_hash,required_changed_files: [changed],+ targets: { "email-worker": { statements: 1, covered: 0, percent: 0 } },})} finally {rmSync(directory, { recursive: true, force: true })diff --git a/scripts/ci/workflow-contract.test.ts b/scripts/ci/workflow-contract.test.tsindex 854191621..783800007 100644--- a/scripts/ci/workflow-contract.test.ts+++ b/scripts/ci/workflow-contract.test.ts@@ -166,10 +166,6 @@ const nativeOauthWebConfig = readFileSync(resolve(import.meta.dirname, "../../src/web/wrangler.toml"),"utf8",)-const blogWorkerConfig = readFileSync(- resolve(import.meta.dirname, "../../src/web/blog/wrangler.toml"),- "utf8",-)const nativeOauthContract = readFileSync(resolve(import.meta.dirname, "../../src/web/src/lib/native-oauth.ts"),"utf8",@@ -260,23 +256,15 @@ describe("E2E UI workflow", () => {expect(dependabotConfig).not.toMatch(/^[ ]{6}- dependency-name: "react-resizable-panels"$/m)})- it("uses the canonical CI scope before merge and removes the second classifier", () => {- expect(workflow).toMatch(/^ pull_request:/m)- expect(workflow).toMatch(/^ merge_group:/m)- expect(workflow).toMatch(/^ workflow_dispatch:/m)- expect(workflow).toMatch(/^ push:/m)- expect(workflow).not.toMatch(/^ schedule:/m)- expect(existsSync(legacyUiWorkflowPath)).toBe(false)- expect(workflow.match(/^ scope:$/gm)).toHaveLength(1)- expect(ciJob("e2e-ui")).toContain("needs.scope.outputs.e2e_matrix")- })- it("keeps UI E2E on read-only PR and merge-queue runs without main history access", () => {- expect(ciJob("e2e-ui")).toContain("github.event_name != 'push'")- expect(ciJob("merge-reports")).toContain("github.event_name != 'push'")+ it("keeps selected browser runs read-only without a separate main history", () => {expect(workflow).toContain("actions: read")expect(workflow).not.toMatch(/^ pull_request_target:/m)expect(workflow).not.toContain("e2e-timing-history")+ for (const job of ["e2e-ui", "merge-reports"]) {+ expect(ciJob(job)).toContain("run_ui_e2e == 'true'")+ expect(ciJob(job)).not.toContain("github.event_name != 'push'")+ }})it("keeps failure diagnostics best-effort and merge inputs strict", () => {@@ -327,13 +315,14 @@ describe("E2E UI workflow", () => {const gate = ciJob("ui-e2e-gate")const devVars = "printf 'BETTER_AUTH_SECRET=ci-e2e-ui-secret\\nBETTER_AUTH_URL=http://localhost:3000\\nENCRYPTION_KEY=ci-e2e-encryption-key-32chars!!\\nDEV_WS_DO_URL=http://localhost:3000\\nNODE_ENV=development\\n' > src/web/.dev.vars"- expect(producer).toContain("image: ${{ fromJSON(needs.scope.outputs.e2e_matrix).include[0].image }}")+ expect(producer).toContain("image: ${{ needs.scope.outputs.worker_build_image }}")expect(producer).toContain("options: --init --ipc=host --user 1001")expect(producer).toContain("NEXT_PUBLIC_WS_DO_PORT: \"3000\"")expect(producer).toContain(devVars)expect(shard).toContain(devVars)- expect(producer.match(/opennextjs-cloudflare build/g)).toHaveLength(1)- expect(producer.match(/pnpm --filter @alook\/web build:blog/g)).toHaveLength(1)+ expect(producer).toContain("run_worker_build == 'true'")+ expect(producer).toContain('node scripts/ci/run-turbo.mjs run "${tasks[@]}" --concurrency=1')+ expect(producer).toContain('"@alook/web#build:blog"')expect(producer).toContain("e2e-build-artifact.mjs create")expect(producer).toContain("name: ${{ steps.artifact_identity.outputs.artifact_name }}")expect(producer).toContain("ui-e2e-build-manifest.json")@@ -429,24 +418,33 @@ describe("Local package test isolation", () => {}const rootTest = rootPackageJson.scripts.test- const driverBuild = rootTest.indexOf("pnpm --filter @alook/agent-driver build")- const workspaceTests = rootTest.indexOf("turbo run test --filter=!@alook/agent-driver")- const driverTests = rootTest.indexOf("pnpm --filter @alook/agent-driver test")+ const workspaceTests = rootTest.indexOf("scripts/ci/run-turbo.mjs run test")+ const driverTests = rootTest.indexOf("@alook/agent-driver#test")const scriptTests = rootTest.indexOf("vitest run --project ci-scripts")- expect(driverBuild).toBeGreaterThanOrEqual(0)- expect(workspaceTests).toBeGreaterThan(driverBuild)+ expect(workspaceTests).toBeGreaterThanOrEqual(0)expect(driverTests).toBeGreaterThan(workspaceTests)expect(scriptTests).toBeGreaterThan(driverTests)})})describe("CI workflow graph", () => {+ it("isolates explicit full runs while retaining cancellation of superseded ordinary checks", () => {+ const concurrency = ciWorkflow.slice(ciWorkflow.indexOf("\nconcurrency:\n"), ciWorkflow.indexOf("\njobs:\n"))+ const group = concurrency.split("\n").find((line) => line.trimStart().startsWith("group:"))!+ expect(group).toContain("github.event_name == 'workflow_dispatch'")+ expect(group).toContain("startsWith(github.event.head_commit.message, 'release:')")+ expect(group).toContain("github.run_id")+ expect(concurrency).toContain("cancel-in-progress: true")+ })+it("keeps approved triggers without a daily schedule", () => {expect(ciWorkflow).toMatch(/^ push:/m)expect(ciWorkflow).toMatch(/^ pull_request:/m)expect(ciWorkflow).toMatch(/^ merge_group:/m)expect(ciWorkflow).toMatch(/^ workflow_dispatch:/m)expect(ciWorkflow).not.toMatch(/^ schedule:/m)+ expect(existsSync(legacyUiWorkflowPath)).toBe(false)+ expect(ciWorkflow.match(/^ scope:$/gm)).toHaveLength(1)})it("keeps manual dispatch full by default and guards diagnostic fixtures before scoping", () => {@@ -462,7 +460,8 @@ describe("CI workflow graph", () => {expect(scope).toContain('--expected-class "$EXPECTED_CLASS"')expect(scope).toContain('--diagnostic-only')expect(scope).toContain('args+=(--base "$EVENT_SHA" --head "$EVENT_SHA" --force-full)')- expect(scope).toContain('args+=(--base "$PUSH_BASE_SHA" --head "$EVENT_SHA" --full-unless-benchmark-only)')+ expect(scope).toContain('args+=(--base "$PUSH_BASE_SHA" --head "$EVENT_SHA" --main-smoke)')+ expect(scope).toContain('args+=(--base "$PUSH_BASE_SHA" --head "$EVENT_SHA" --force-full)')expect(scope).not.toContain("ref: ${{ inputs.fixture_sha }}")})@@ -476,19 +475,24 @@ describe("CI workflow graph", () => {"ci-gate", "ui-e2e-gate",]) {const definition = ciJob(job)- expect(definition, job).toContain("CI_EXECUTION_PLAN: ${{ needs.scope.outputs.execution_plan }}")+ expect(definition, job).toContain("CI_EXECUTION_PLAN_FILE: .ci/execution-plan.json")expect(definition, job).toContain("CI_PLAN_HASH: ${{ needs.scope.outputs.plan_hash }}")expect(definition, job).toContain("node scripts/ci/validate-execution-plan.mjs")+ expect(definition, job).toContain("name: ${{ needs.scope.outputs.plan_artifact_name }}")+ expect(definition.indexOf("- name: Download execution plan")).toBeLessThan(definition.indexOf("- name: Validate execution plan"))}})- it("keeps named Codecov targets, patch enforcement, and changed-file proof auditable", () => {+ it("reports project and patch percentages while preserving coverage integrity and upload errors", () => {const linux = ciJob("test-linux")- expect(linux).toContain("coverage_include_roots")+ expect(linux).toContain("CI_EXECUTION_PLAN")expect(linux).toContain("verify-coverage-plan.mjs")expect(linux).toContain("coverage-target-manifest.json")expect(linux).toContain("coverage/coverage-final.json")- expect(readFileSync(resolve(repositoryRoot, "codecov.yml"), "utf8")).toContain("target: 100%")+ const coveragePolicy = readFileSync(resolve(repositoryRoot, "codecov.yml"), "utf8")+ expect(coveragePolicy).toMatch(/patch:[\s\S]*informational: true/)+ expect(coveragePolicy).not.toMatch(/target: \d/)+ expect(linux).toContain("fail_ci_if_error: true")})it("prepares shared services for every selected integration suite", () => {@@ -539,10 +543,10 @@ describe("CI workflow graph", () => {expect(ciWorkflow).not.toMatch(/^ build:/m)expect(staticChecks.match(/pnpm install --frozen-lockfile/g)).toHaveLength(1)expect(staticChecks.match(/continue-on-error: true/g)).toHaveLength(1)- expect(staticChecks).toContain("pnpm turbo run typecheck")- expect(staticChecks).toContain("pnpm turbo run lint")- expect(staticChecks).toContain("pnpm turbo run build")- expect(staticChecks).toContain("pnpm turbo run knip")+ expect(staticChecks).toContain("--plan-group static_tasks")+ expect(staticChecks).toContain("--plan-group static_tasks")+ expect(staticChecks).toContain("--plan-group build_tasks")+ expect(staticChecks).toContain("--plan-group knip_tasks")})it("gates the consolidated jobs under the stable CI Gate", () => {@@ -621,11 +625,11 @@ describe("Private agent driver package", () => {expect(existsSync(resolve(workflowRoot, "publish-agent-driver.yml"))).toBe(false)})- it("builds the workspace driver before a clean daemon publish build", () => {- const driverBuild = publishDaemonWorkflow.indexOf("pnpm -C src/daemon/agent-driver run build")- const daemonBuild = publishDaemonWorkflow.indexOf("pnpm -C src/daemon run build")- expect(driverBuild).toBeGreaterThan(0)- expect(daemonBuild).toBeGreaterThan(driverBuild)+ it("builds the daemon publish input through the native prerequisite graph", () => {+ expect(publishDaemonWorkflow).toContain("node scripts/ci/run-turbo.mjs run @alook/daemon#build")+ const config = JSON.parse(readFileSync(resolve(repositoryRoot, "turbo.json"), "utf8"))+ expect(config.tasks["@alook/daemon#build"].dependsOn).toContain("@alook/agent-driver#build")+ expect(daemonPackage.scripts.prepack).toContain("@alook/daemon#build")})it("keeps runtime and artifact contracts without the removed API report mechanism", () => {@@ -686,7 +690,7 @@ describe("CI test budgets", () => {const windows = ciJob("test-windows")expect(windows).toContain("for suite in app shared")expect(windows).toContain('filters+=("--filter=@alook/$suite")')- expect(windows).toContain('pnpm turbo run test "${filters[@]}"')+ expect(windows).toContain('node scripts/ci/run-turbo.mjs run test "${filters[@]}"')expect(windows).not.toContain("--affected")for (const packageName of ["web", "email-worker", "ws-do", "queue-worker"]) {expect(windows).not.toContain(`--filter=@alook/${packageName}`)@@ -857,29 +861,23 @@ describe("Turbo CI execution", () => {expect(scope).toContain("full: ${{ steps.scope.outputs.full }}")expect(scope).toContain("base_sha: ${{ steps.scope.outputs.base_sha }}")expect(scope).toContain("head_sha: ${{ steps.scope.outputs.head_sha }}")- expect(scope).toContain("execution_plan: ${{ steps.scope.outputs.execution_plan }}")+ expect(scope).toContain("plan_artifact_name: execution-plan-${{ github.run_id }}-${{ github.run_attempt }}")expect(scope).toContain("plan_hash: ${{ steps.scope.outputs.plan_hash }}")expect(ciWorkflow).not.toContain("--affected")- expect(ciJob("static-checks")).toContain("CI_PROJECTION_NAME: static_packages")+ expect(ciJob("static-checks")).toContain("CI_PROJECTION_NAME: static_tasks")expect(ciJob("test-windows")).toContain("CI_PROJECTION_NAME: windows_suites")})- it("retains full commands when scope classification fails closed", () => {+ it("runs validated native task groups and the canonical unit entry", () => {const staticChecks = ciJob("static-checks")- expect(staticChecks).toContain("pnpm turbo run typecheck")- expect(staticChecks).toContain("pnpm turbo run lint")- expect(staticChecks).toContain("pnpm turbo run knip")- expect(staticChecks).toContain("SELECTED_PACKAGES: ${{ needs.scope.outputs.build_packages }}")+ for (const group of ["static_tasks", "build_tasks", "knip_tasks"]) expect(staticChecks).toContain("--plan-group " + group)expect(staticChecks.match(/pnpm install --frozen-lockfile/g)).toHaveLength(1)const linux = ciJob("test-linux")- expect(linux).toContain("--project=daemon-node src/daemon")+ expect(linux).toContain("node scripts/ci/run-unit-tests.mjs")+ expect(linux).toContain("--ci --receipt .ci/unit-execution.json")const windows = ciJob("test-windows")expect(windows).toContain("run: pnpm --filter @alook/daemon test")- expect(linux).toContain('vitest_args=("${project_args[@]}")')- expect(linux).toContain('if (( ${#root_coverage[@]} )); then vitest_args+=("${root_coverage[@]}"); fi')- expect(linux).toContain('pnpm vitest run "${vitest_args[@]}"')- expect(windows).toContain("pnpm turbo run test \"${filters[@]}\"")- expect(linux.match(/VITEST_MAX_WORKERS=1/g)).toHaveLength(1)+ expect(windows).toContain('node scripts/ci/run-turbo.mjs run test "${filters[@]}"')expect(windows.match(/VITEST_MAX_WORKERS: 1/g)).toHaveLength(1)})@@ -889,27 +887,14 @@ describe("Turbo CI execution", () => {expect(daemonVitestConfig).toContain("sequence: { groupOrder: 2 }")})- it("builds agent-driver before every selected Linux consumer of its dist exports", () => {+ it("builds native unit prerequisites before serial process and packed phases", () => {const linux = ciJob("test-linux")- const buildStart = linux.indexOf("- name: Build selected agent-driver fixture")- const unitStart = linux.indexOf("- name: Run selected unit tests")- const realStart = linux.indexOf("- name: Run selected daemon real-process tests")- const packedStart = linux.indexOf("- name: Run selected package artifact tests")- const buildStep = linux.slice(buildStart, unitStart)-+ const buildStart = linux.indexOf("- name: Build native unit prerequisites")expect(buildStart).toBeGreaterThan(-1)- expect(buildStep).toContain("run: pnpm --filter @alook/agent-driver build")- for (const selector of [- "contains(fromJSON(needs.scope.outputs.unit_test_roots), 'src/daemon/agent-driver')",- "contains(fromJSON(needs.scope.outputs.unit_test_roots), 'src/daemon')",- "contains(fromJSON(needs.scope.outputs.linux_suites), 'agent-driver-packed')",- "contains(fromJSON(needs.scope.outputs.linux_suites), 'daemon-packed')",- "contains(fromJSON(needs.scope.outputs.linux_suites), 'daemon-real')",- ]) expect(buildStep).toContain(selector)- expect(buildStep).not.toContain("src/web")- expect(unitStart).toBeGreaterThan(buildStart)- expect(realStart).toBeGreaterThan(buildStart)- expect(packedStart).toBeGreaterThan(buildStart)+ expect(linux).toContain("run: node scripts/ci/run-turbo.mjs --plan-group unit_build_tasks")+ for (const phase of ["Run selected unit files", "Run selected daemon real-process tests", "Run selected package artifact tests"]) {+ expect(linux.indexOf("- name: " + phase)).toBeGreaterThan(buildStart)+ }})it("runs each direct Worker Node and runtime project once through its standard test task", () => {@@ -919,13 +904,17 @@ describe("Turbo CI execution", () => {const projectNames: string[] = []for (const module of directWorkerModules) {- expect(module.packageJson.scripts.test).toBe("vitest run --config vitest.workspace.config.ts")+ expect(module.packageJson.scripts.test).toBe("vitest run --config " + (module.name === "web" ? "vitest.workspace.config.ts" : "vitest.config.ts"))+ expect(module.packageJson.scripts["test:runtime"]).toContain("vitest.runtime.config.mts")expect(module.packageJson.scripts).not.toHaveProperty("test:workers")expect(module.packageJson.devDependencies["@cloudflare/vitest-plugin"]).toBe(vitestPluginVersion)- const expectedProjects = module.name === "web" ? 2 : 1+ const expectedProjects = 1expect(module.workspaceConfig.match(/vitest\.config\.ts/g)).toHaveLength(expectedProjects)- expect(module.workspaceConfig.match(/vitest\.runtime\.config\.mts/g)).toHaveLength(expectedProjects)+ if (module.name === "web") {+ expect(module.workspaceConfig).not.toContain("vitest.runtime.config.mts")+ expect(module.packageJson.scripts["test:runtime"]).toContain("vitest.runtime.config.mts")+ } else expect(module.workspaceConfig.match(/vitest\.runtime\.config\.mts/g)).toHaveLength(expectedProjects)if (module.name === "web") expect(module.workspaceConfig).toContain("./vitest.dom.config.ts")else expect(module.workspaceConfig).not.toContain("vitest.dom.config.ts")@@ -939,25 +928,17 @@ describe("Turbo CI execution", () => {projectNames.push(nodeProject, runtimeProject)}expect(new Set(projectNames).size).toBe(projectNames.length)- expect(ciJob("test-linux")).toContain("projects=(web-node web-dom web-runtime auth-node auth-runtime)")+ expect(ciJob("test-linux")).toContain("node scripts/ci/run-unit-tests.mjs")})- it("pins every deployed Worker to the latest reviewed compatibility date", () => {- const configs = [- ...directWorkerModules.map((module) => module.wranglerConfig),- nativeOauthAuthConfig,- blogWorkerConfig,- ]- expect(configs).toHaveLength(6)- for (const config of configs) {- expect(config).toContain('compatibility_date = "2026-09-07"')- }- })- it("runs Blog tests through both Web Node and DOM projects", () => {- expect(ciJob("blog-build")).toContain(- "pnpm --filter @alook/web exec vitest run --config vitest.workspace.config.ts --project=web-node --project=web-dom blog",- )+ it("verifies the Blog artifact from the same producer before dry-run", () => {+ const blog = ciJob("blog-build")+ expect(blog).toContain("needs: [scope, ui-e2e-build]")+ expect(blog).toContain("e2e-build-artifact.mjs verify")+ expect(blog).toContain("verify:blog-dry-run")+ expect(blog.indexOf("e2e-build-artifact.mjs verify")).toBeLessThan(blog.indexOf("verify:blog-dry-run"))+ expect(blog).not.toMatch(/exec (?:tsc|eslint|vitest)\b|run build:blog|opennextjs-cloudflare build/)})it("collects Node and workerd projects in one Istanbul report", () => {@@ -1002,91 +983,37 @@ describe("Turbo CI execution", () => {)})- it("runs selected non-daemon roots in isolated reports with exact coverage includes", () => {+ it("keeps a unit execution receipt and rejects invalid coverage before upload", () => {const linux = ciJob("test-linux")- expect(linux).toContain('for root in "${non_daemon[@]}"; do')- expect(linux).toContain('if [[ "$include" == "$root/"* ]]; then')- expect(linux).toContain('root_coverage+=("--coverage.include=$include")')- expect(linux).toContain("--coverage.reporter=json")- expect(linux).toContain(- '"--coverage.reportsDirectory=$coverage_dir/root-${root_index}-${report_stem}"',- )- for (const projects of [- "projects=(ci-scripts)",- "projects=(email-worker-node email-worker-runtime)",- "projects=(queue-worker-node queue-worker-runtime)",- "projects=(web-node web-dom web-runtime auth-node auth-runtime)",- "projects=(ws-do-node ws-do-runtime)",- ]) expect(linux).toContain(projects)- expect(linux).toContain('project_args+=("--project=$project")')- expect(linux).toContain('pnpm vitest run "${vitest_args[@]}"')- expect(linux).toContain(- '--outputFile.blob="$report_dir/root-${root_index}-${report_stem}.blob"',- )- expect(linux).not.toContain("--project='!daemon-node'")- expect(linux).not.toContain('"${non_daemon[@]}" "${coverage[@]}"')- expect(linux).not.toContain(".vitest-reports/non-daemon.blob")+ expect(linux).toContain("--ci --receipt .ci/unit-execution.json")+ expect(linux).toContain('args+=(--coverage)')+ expect(linux).toContain("if: always() && env.RUN_COVERAGE == 'true'")+ expect(linux).toContain("verify-coverage-plan.mjs")+ expect(linux).toContain("coverage/coverage-final.json")+ const upload = linux.match(/ - name: Upload unit execution evidence\n[\s\S]*?(?=\n - name:|$)/)?.[0] || ""+ const reports = upload.match(/ path: \|\n((?: [^\n]+\n)+)/)?.[1]+ ?.trim().split("\n").map(path => path.trim())+ expect(reports).toEqual([".ci/unit-execution.json", ".vitest-reports/unit.blob"])+ expect(upload).not.toMatch(/include-hidden-files:\s*true/i)+ expect(upload).toContain("if: always()")+ expect(upload).toContain("if-no-files-found: error")})- it("keeps package builds away from dist consumers and uploads one merged Istanbul report", () => {+ it("keeps real-process and packed tests serial after the unit report", () => {const linux = ciJob("test-linux")expect(linux).toContain("timeout-minutes: 45")- expect(linux).toContain(- "RUN_COVERAGE: ${{ github.event_name != 'push' || startsWith(github.event.head_commit.message, 'release:') }}",- )- expect(linux).toContain('pnpm vitest run "${vitest_args[@]}"')- expect(linux).toContain("pnpm vitest run --project=daemon-node src/daemon")- expect(linux).toContain(- '"--coverage.reportsDirectory=$coverage_dir/root-${root_index}-${report_stem}"',- )- expect(linux).toContain('coverage=(--coverage)')- expect(linux).toContain('--reporter=default --reporter=blob')- expect(linux).toContain('--outputFile.blob="$report_dir/root-${root_index}-${report_stem}.blob"')- expect(linux).toContain('--outputFile.blob="$report_dir/daemon.blob"')- expect(linux).toContain("--merge-reports=.vitest-reports")+ expect(linux).toContain("RUN_COVERAGE: ${{ needs.scope.outputs.execution_mode != 'main-smoke' }}")expect(linux.match(/codecov\/codecov-action/g)).toHaveLength(1)- expect(linux).toContain("if: env.RUN_COVERAGE == 'true'")expect(linux).toContain("files: ./coverage/coverage-final.json")- expect(linux).toContain("verify-coverage-plan.mjs")- for (const testPath of [- "src/pack.test.ts",- "src/cli/daemonLifecycle.real.test.ts",- "src/cli/diagnosticsLifecycle.real.test.ts",- "src/cli/daemonStop.test.ts",- "src/version.packed.test.ts",- "src/agent-driver-bundle.packed.test.ts",- "src/cli/daemonSelfUpdate.real.test.ts",- ]) {- expect(linux).toContain(`--exclude ${testPath}`)- }- expect(linux).not.toContain("--exclude src/daemon/")+ expect(linux).toContain("fail_ci_if_error: true")expect(linux).toContain("pnpm --filter @alook/daemon exec vitest run --no-file-parallelism")- for (const testPath of [- "src/cli/daemonLifecycle.real.test.ts",- "src/cli/diagnosticsLifecycle.real.test.ts",- "src/cli/daemonStop.test.ts",- ]) {- expect(linux.slice(linux.indexOf("- name: Run selected daemon real-process tests")))- .toContain(testPath)+ for (const path of ["src/cli/daemonLifecycle.real.test.ts", "src/cli/diagnosticsLifecycle.real.test.ts", "src/cli/daemonStop.test.ts"]) {+ expect(linux.slice(linux.indexOf("- name: Run selected daemon real-process tests"))).toContain(path)}- expect(linux).toContain(- "pnpm --filter @alook/agent-driver exec vitest run --no-file-parallelism src/pack.test.ts",- )- expect(linux).toContain(- "pnpm --filter @alook/daemon exec vitest run --no-file-parallelism src/version.packed.test.ts src/agent-driver-bundle.packed.test.ts src/cli/daemonSelfUpdate.real.test.ts",- )- const selectedUnitRun = linux.indexOf("- name: Run selected unit tests")- const coverageMerge = linux.indexOf("- name: Merge and verify selected coverage")- const realProcessRuns = linux.indexOf("- name: Run selected daemon real-process tests")- const packageRuns = linux.indexOf("- name: Run selected package artifact tests")- const coverageUpload = linux.indexOf("- name: Upload coverage")- expect(selectedUnitRun).toBeGreaterThan(-1)- expect(coverageMerge).toBeGreaterThan(selectedUnitRun)- expect(realProcessRuns).toBeGreaterThan(coverageMerge)- expect(packageRuns).toBeGreaterThan(realProcessRuns)- expect(coverageUpload).toBeGreaterThan(packageRuns)- expect(linux).not.toContain("coverage:workers")- expect(linux).not.toContain("workers-runtime")+ expect(linux).toContain("pnpm --filter @alook/agent-driver exec vitest run --no-file-parallelism src/pack.test.ts")+ expect(linux).toContain("pnpm --filter @alook/daemon exec vitest run --no-file-parallelism src/version.packed.test.ts src/agent-driver-bundle.packed.test.ts src/cli/daemonSelfUpdate.real.test.ts")+ const phases = ["Run selected unit files", "Verify selected coverage", "Run selected daemon real-process tests", "Run selected package artifact tests", "Upload coverage"].map(phase => linux.indexOf("- name: " + phase))+ expect(phases.every((position, index) => position >= 0 && (!index || position > phases[index - 1]!))).toBe(true)expect(ciWorkflow).not.toMatch(/^ coverage:/m)expect(rootPackageJson.scripts).not.toHaveProperty("coverage:workers")})@@ -1512,7 +1439,7 @@ describe("Native OAuth association contract", () => {.toContain("--outdir dist")expect(directWorkerModules[3].packageJson.scripts["build:auth"]).not.toContain("--outdir auth/dist")- expect(directWorkerModules[3].workspaceConfig).toContain("./auth/vitest.config.ts")- expect(directWorkerModules[3].workspaceConfig).toContain("./auth/vitest.runtime.config.mts")+ expect(directWorkerModules[3].packageJson.scripts["test:auth"]).toContain("auth/vitest.config.ts")+ expect(directWorkerModules[3].packageJson.scripts["test:auth:runtime"]).toContain("auth/vitest.runtime.config.mts")})})diff --git a/src/app/package.json b/src/app/package.jsonindex e7ffbe2f6..56a06964a 100644--- a/src/app/package.json+++ b/src/app/package.json@@ -1,7 +1,7 @@{"name": "@alook/app","version": "0.1.63",- "description": "Run Alook locally — one command, no clone needed",+ "description": "Run Alook locally \u2014 one command, no clone needed","license": "Apache-2.0","homepage": "https://github.com/alookai/alook#readme","repository": {@@ -31,7 +31,7 @@},"scripts": {"build": "bun build src/index.ts --outdir dist --target node --format esm --external commander --external wrangler && node scripts/bundle-daemon.mjs",- "prepack": "pnpm run build && node -e \"const{existsSync}=require('fs');if(!existsSync('bundled/web'))throw new Error('bundled/ missing — run pnpm bundle first')\"",+ "prepack": "node ../../scripts/ci/run-turbo.mjs run @alook/app#build && node -e \"const{existsSync}=require('fs');if(!existsSync('bundled/web'))throw new Error('bundled/ missing \u2014 run pnpm bundle first')\"","bundle": "bun run scripts/bundle.ts","knip": "knip","lint": "eslint src/",@@ -51,6 +51,6 @@"knip": "^6.32.2","typescript": "^6.0.3","typescript-eslint": "^8.72.0",- "vitest": "4.1.12"+ "vitest": "5.1.0"}}diff --git a/src/app/scripts/app-packed-artifact.mjs b/src/app/scripts/app-packed-artifact.mjsindex 246cea5c6..1ffc5a286 100644--- a/src/app/scripts/app-packed-artifact.mjs+++ b/src/app/scripts/app-packed-artifact.mjs@@ -33,7 +33,7 @@ export function runAppPackedArtifact(options) {mkdirSync(outputDir, { recursive: true });if (!options.skipBuild) {run("pnpm", ["run", "bundle"], appRoot);- run("pnpm", ["run", "build"], appRoot);+ run("node", ["../../scripts/ci/run-turbo.mjs", "run", "@alook/app#build"], appRoot);}const packed = JSON.parse(execFileSync("npm", ["pack",diff --git a/src/app/scripts/bundle-daemon.mjs b/src/app/scripts/bundle-daemon.mjsindex 27916c18d..2b18f9c49 100644--- a/src/app/scripts/bundle-daemon.mjs+++ b/src/app/scripts/bundle-daemon.mjs@@ -1,7 +1,6 @@#!/usr/bin/env nodeimport { cpSync, existsSync, mkdirSync, rmSync } from "node:fs";import { join, dirname } from "node:path";-import { execSync } from "node:child_process";import { fileURLToPath } from "node:url";const __dirname = dirname(fileURLToPath(import.meta.url));@@ -11,7 +10,6 @@ const source = join(daemonRoot, "dist", "cli", "index.js");const targetDir = join(appRoot, "dist", "daemon");const target = join(targetDir, "index.js");-execSync("pnpm run build", { cwd: daemonRoot, stdio: "inherit" });if (!existsSync(source)) throw new Error("@alook/daemon build did not produce dist/cli/index.js");rmSync(join(appRoot, "dist", "cli"), { recursive: true, force: true });diff --git a/src/app/scripts/bundle.ts b/src/app/scripts/bundle.tsindex 7c1f7836c..e268d8a47 100644--- a/src/app/scripts/bundle.ts+++ b/src/app/scripts/bundle.ts@@ -51,13 +51,15 @@ if (existsSync(bundledDir)) rmSync(bundledDir, { recursive: true });// --- Build Web ---console.log("\n=== Building Web (opennextjs-cloudflare) ===\n");const webSrc = join(monoRoot, "src", "web");-run("npx opennextjs-cloudflare build", webSrc);+run("node ../../scripts/ci/run-turbo.mjs run @alook/web#build @alook/email-worker#build @alook/ws-do#build @alook/queue-worker#build", appRoot);const webDest = join(bundledDir, "web");mkdirSync(webDest, { recursive: true });cpSync(join(webSrc, ".open-next"), join(webDest, ".open-next"), { recursive: true });rewriteAbsolutePaths(webDest);cpSync(join(webSrc, "wrangler.toml"), join(webDest, "wrangler.toml"));+const webPackage = JSON.parse(readFileSync(join(webSrc, "package.json"), "utf8"));+writeFileSync(join(webDest, "package.json"), JSON.stringify({ type: "module", imports: webPackage.imports }, null, 2) + "\n");cpSync(join(webSrc, "custom-worker.ts"), join(webDest, "custom-worker.ts"));mkdirSync(join(webDest, "src", "lib"), { recursive: true });mkdirSync(join(webDest, "src", "lib", "observability"), { recursive: true });@@ -75,7 +77,6 @@ const emailSrc = join(monoRoot, "src", "email-worker");const emailDest = join(bundledDir, "email-worker");mkdirSync(emailDest, { recursive: true });-run("npx wrangler deploy --dry-run --outdir dist", emailSrc);cpSync(join(emailSrc, "dist", "index.js"), join(emailDest, "index.js"));const emailToml = readFileSync(join(emailSrc, "wrangler.toml"), "utf-8");@@ -90,7 +91,6 @@ const wsSrc = join(monoRoot, "src", "ws-do");const wsDest = join(bundledDir, "ws-do");mkdirSync(wsDest, { recursive: true });-run("npx wrangler deploy --dry-run --outdir dist", wsSrc);cpSync(join(wsSrc, "dist", "index.js"), join(wsDest, "index.js"));const wsToml = readFileSync(join(wsSrc, "wrangler.toml"), "utf-8");@@ -105,7 +105,6 @@ const queueSrc = join(monoRoot, "src", "queue-worker");const queueDest = join(bundledDir, "queue-worker");mkdirSync(queueDest, { recursive: true });-run("npx wrangler deploy --dry-run --outdir dist", queueSrc);cpSync(join(queueSrc, "dist", "index.js"), join(queueDest, "index.js"));const queueToml = readFileSync(join(queueSrc, "wrangler.toml"), "utf-8");diff --git a/src/app/test/packed-artifact.test.ts b/src/app/test/packed-artifact.test.tsindex 39607356d..fe16181c7 100644--- a/src/app/test/packed-artifact.test.ts+++ b/src/app/test/packed-artifact.test.ts@@ -44,11 +44,12 @@ describe("packed artifact verifier", () => {const execSync = vi.fn();const cpSync = vi.fn();const mkdirSync = vi.fn();+ const packageSource = readFileSync(join(import.meta.dirname, "../../web/package.json"), "utf8");const bundleFs = {cpSync,existsSync: vi.fn(() => false),mkdirSync,- readFileSync: vi.fn(() => 'main = "src/index.ts"'),+ readFileSync: vi.fn((path: string) => path.endsWith("package.json") ? packageSource : 'main = "src/index.ts"'),readdirSync: vi.fn(() => []),rmSync: vi.fn(),writeFileSync: vi.fn(),@@ -72,6 +73,9 @@ describe("packed artifact verifier", () => {const appRoot = join(import.meta.dirname, "..");const monoRoot = join(appRoot, "..", "..");const webDest = join(appRoot, "bundled", "web");+ const packageWrite = bundleFs.writeFileSync.mock.calls.find(([path]) => path === join(webDest, "package.json"));+ expect(packageWrite).toBeDefined();+ expect(JSON.parse(String(packageWrite![1]))).toEqual({ type: "module", imports: JSON.parse(packageSource).imports });expect(mkdirSync).toHaveBeenCalledWith(join(webDest, "src", "lib"), { recursive: true });expect(mkdirSync).toHaveBeenCalledWith(join(webDest, "src", "lib", "observability"), { recursive: true });const copies = new Map(cpSync.mock.calls.map(([source, destination]) => [source, destination]));diff --git a/src/daemon/README.md b/src/daemon/README.mdindex df727629f..a5ec9cb04 100644--- a/src/daemon/README.md+++ b/src/daemon/README.md@@ -277,7 +277,7 @@ This project uses **pnpm** (see the `packageManager` field).```bashpnpm installpnpm run typecheck # tsc --noEmit (passes clean)-pnpm test # vitest — unit tests only (drivers/manager/inbox/credentials/server)+pnpm test # Vitest package suite, including its packed/runtime categoriespnpm run test:integration # real infra: requires wrangler dev + ws-do dev + queue-worker dev (see below)```diff --git a/src/daemon/agent-driver/package.json b/src/daemon/agent-driver/package.jsonindex 3c3e39828..2cb6575e2 100644--- a/src/daemon/agent-driver/package.json+++ b/src/daemon/agent-driver/package.json@@ -49,11 +49,11 @@},"devDependencies": {"@types/node": "^20.0.0",- "@vitest/coverage-v8": "4.1.12",+ "@vitest/coverage-v8": "5.1.0","eslint": "^9.39.5","knip": "^5.85.0","typescript": "^6.0.3","typescript-eslint": "^8.72.0",- "vitest": "4.1.12"+ "vitest": "5.1.0"}}diff --git a/src/daemon/package.json b/src/daemon/package.jsonindex f89a8d5d2..6981d077b 100644--- a/src/daemon/package.json+++ b/src/daemon/package.json@@ -1,7 +1,7 @@{"name": "@alook/daemon","version": "0.1.63",- "description": "Alook agent daemon — host-side runtime backend, process manager, credential proxy, and control plane.",+ "description": "Alook agent daemon \u2014 host-side runtime backend, process manager, credential proxy, and control plane.","license": "Apache-2.0","homepage": "https://github.com/alookai/alook#readme","repository": {@@ -37,9 +37,8 @@"access": "public"},"scripts": {- "prebuild": "pnpm -C agent-driver run build","build": "bun build src/index.ts --outdir dist --target node --format esm --external commander --external ws --external sharp --external quickjs-emscripten && bun build src/cli/index.ts --outdir dist/cli --target node --format esm --external commander --external ws --external sharp --external quickjs-emscripten && node scripts/prepare-dist.mjs",- "prepack": "pnpm run build",+ "prepack": "node ../../scripts/ci/run-turbo.mjs run @alook/daemon#build","typecheck": "tsc --noEmit","test": "pnpm test:unit && pnpm test:packed","test:unit": "vitest run --exclude src/version.packed.test.ts --exclude src/agent-driver-bundle.packed.test.ts --exclude src/cli/daemonSelfUpdate.real.test.ts",@@ -65,7 +64,7 @@"tsx": "^4.23.15","typescript": "^6.0.3","typescript-eslint": "^8.72.0",- "vitest": "4.1.12",+ "vitest": "5.1.0","zod": "^4.6.7"}}diff --git a/src/email-worker/package.json b/src/email-worker/package.jsonindex c8d8d6ddc..4df8e2671 100644--- a/src/email-worker/package.json+++ b/src/email-worker/package.json@@ -6,8 +6,10 @@"dev": "node ../../scripts/dev-with-wrangler-registry.mjs ../../.wrangler/registry wrangler dev --persist-to ../web/.wrangler/state","deploy": "wrangler deploy","knip": "knip",- "test": "vitest run --config vitest.workspace.config.ts",- "typecheck": "tsc --noEmit"+ "test": "vitest run --config vitest.config.ts",+ "typecheck": "tsc --noEmit",+ "test:runtime": "vitest run --config vitest.runtime.config.mts",+ "build": "wrangler deploy --dry-run --outdir dist"},"dependencies": {"@alook/shared": "workspace:*",@@ -21,7 +23,7 @@"@types/node": "^25.9.4","knip": "^6.32.2","typescript": "^6.0.3",- "vitest": "4.1.12",+ "vitest": "5.1.0","wrangler": "4.152.0"}}diff --git a/src/queue-worker/package.json b/src/queue-worker/package.jsonindex fe2007ac3..1d0e33d23 100644--- a/src/queue-worker/package.json+++ b/src/queue-worker/package.json@@ -6,8 +6,10 @@"dev": "node ../../scripts/dev-with-wrangler-registry.mjs ../../.wrangler/registry wrangler dev --persist-to ../web/.wrangler/state","deploy": "wrangler deploy","knip": "knip",- "test": "vitest run --config vitest.workspace.config.ts",- "typecheck": "tsc --noEmit"+ "test": "vitest run --config vitest.config.ts",+ "typecheck": "tsc --noEmit",+ "test:runtime": "vitest run --config vitest.runtime.config.mts",+ "build": "wrangler deploy --dry-run --outdir dist"},"dependencies": {"@alook/shared": "workspace:*"@@ -18,7 +20,7 @@"@types/node": "^25.9.4","knip": "^6.32.2","typescript": "^6.0.3",- "vitest": "4.1.12",+ "vitest": "5.1.0","wrangler": "4.152.0"}}diff --git a/src/shared/package.json b/src/shared/package.jsonindex 25ea0b27f..462b5b359 100644--- a/src/shared/package.json+++ b/src/shared/package.json@@ -34,6 +34,6 @@"knip": "^6.32.2","playwright-core": "^1.64.1","typescript": "^6.0.3",- "vitest": "4.1.12"+ "vitest": "5.1.0"}}diff --git a/src/shared/test/community-cli-contract.test.ts b/src/shared/test/community-cli-contract.test.tsindex fc2e7a480..c530c5a56 100644--- a/src/shared/test/community-cli-contract.test.ts+++ b/src/shared/test/community-cli-contract.test.ts@@ -1,4 +1,4 @@-import { describe, it, expect, expectTypeOf } from "vitest";+import { describe, it, expect } from "vitest";import {parseRef,formatRef,@@ -8,7 +8,6 @@ import {DM_SERVER,AgentInterruptRequestSchema,HostCommandSchema,- type HostCommand,} from "../src/community-cli-contract";import { CommunityAgentAttachmentUploadResponseSchema } from "../src/schemas";@@ -224,10 +223,6 @@ describe("formatRef", () => {).toThrow();});- it("formats a plain channel ref unchanged (regression)", () => {- expect(formatRef({ server: "studio#0042", channel: "general" })).toBe("/studio#0042/general");- });-it("formats a plain thread ref unchanged (regression)", () => {expect(formatRef({ server: "studio#0042", channel: "general", threadRootSeq: 5 })).toBe("/studio#0042/general/#5",@@ -319,7 +314,7 @@ describe("HostCommand nap contract", () => {});describe("HostCommand diagnostics contract", () => {- it("keeps the diagnostics arm in the HostCommand type and runtime schema", () => {+ it("accepts the diagnostics arm in the runtime command union", () => {type DiagnosticCommand = {type: "diagnostics:collect";reportId: string;@@ -327,9 +322,6 @@ describe("HostCommand diagnostics contract", () => {fromMs: number;deadlineAt: number;};- expectTypeOf<Extract<HostCommand, { type: "diagnostics:collect" }>>()- .toEqualTypeOf<DiagnosticCommand>();-const command: DiagnosticCommand = {type: "diagnostics:collect",reportId: "dbr_0123456789abcdef",@@ -356,7 +348,7 @@ describe("HostCommand control heartbeat contract", () => {});describe("HostCommand runtime config update contract", () => {- it("keeps the narrow revisioned config arm in the type and runtime schema", () => {+ it("accepts the revisioned config arm in the runtime command union", () => {const config = {version: 1,runtime: "codex",@@ -365,13 +357,6 @@ describe("HostCommand runtime config update contract", () => {reasoningEffort: "xhigh",runtimeConfigRevision: 8,};- type RuntimeConfigUpdate = {- type: "agent:runtime_config_update";- agentId: string;- config: typeof config;- };- expectTypeOf<Extract<HostCommand, { type: "agent:runtime_config_update" }>>()- .toMatchTypeOf<RuntimeConfigUpdate>();expect(HostCommandSchema.parse({type: "agent:runtime_config_update",agentId: "bot_1",@@ -381,10 +366,7 @@ describe("HostCommand runtime config update contract", () => {});describe("HostCommand machine update contract", () => {- it("keeps the no-payload arm in the type and strict runtime schema", () => {- type UpdateCommand = { type: "machine:update" };- expectTypeOf<Extract<HostCommand, { type: "machine:update" }>>()- .toEqualTypeOf<UpdateCommand>();+ it("accepts the payload-free update arm in the strict runtime schema", () => {expect(HostCommandSchema.safeParse({ type: "machine:update" })).toEqual(expect.objectContaining({ success: true }),);@@ -402,8 +384,6 @@ describe("HostCommand machine update contract", () => {describe("HostCommand machine stop contract", () => {it("accepts only the payload-free stop command", () => {- expectTypeOf<Extract<HostCommand, { type: "machine:stop" }>>()- .toEqualTypeOf<{ type: "machine:stop" }>();expect(HostCommandSchema.parse({ type: "machine:stop" })).toEqual({ type: "machine:stop" });for (const field of ["machineId", "command", "force", "delete", "credential"]) {expect(HostCommandSchema.safeParse({ type: "machine:stop", [field]: "extra" }).success).toBe(false);diff --git a/src/shared/test/diagnostics-contract.test.ts b/src/shared/test/diagnostics-contract.test.tsindex aa3edd9d5..16b58b02d 100644--- a/src/shared/test/diagnostics-contract.test.ts+++ b/src/shared/test/diagnostics-contract.test.ts@@ -1,4 +1,4 @@-import { describe, expect, expectTypeOf, it } from "vitest";+import { describe, expect, it } from "vitest";import * as Shared from "../src/index";import { HostCommandSchema } from "../src/community-cli-contract";import { DIAGNOSTIC_REPORT_FAILURE_CODES as DB_FAILURE_CODES } from "../src/db/community-machine-schema";@@ -14,8 +14,6 @@ import {DiagnosticReportIdSchema,OwnerDiagnosticReportSchema,} from "../src/diagnostics-contract";-import type { DiagnosticReportFailureCode } from "../src/diagnostics-contract";-import type { DiagnosticReportFailureCode as BarrelDiagnosticReportFailureCode } from "../src/index";const FROM_MS = 1_700_000_000_000;const DEADLINE_AT = FROM_MS + DIAGNOSTIC_COLLECT_SPAN_MS;@@ -55,8 +53,6 @@ describe("shared diagnostics contract ownership", () => {it("re-exports the database-owned failure-code tuple without copying it", () => {expect(DIAGNOSTIC_REPORT_FAILURE_CODES).toBe(DB_FAILURE_CODES);expect(DiagnosticReportFailureCodeSchema.options).toEqual([...DB_FAILURE_CODES]);- expectTypeOf<DiagnosticReportFailureCode>().toEqualTypeOf<(typeof DB_FAILURE_CODES)[number]>();- expectTypeOf<BarrelDiagnosticReportFailureCode>().toEqualTypeOf<DiagnosticReportFailureCode>();});});@@ -159,7 +155,6 @@ describe("owner-safe diagnostic report projection", () => {const parsed = OwnerDiagnosticReportSchema.safeParse(report);expect(parsed.success).toBe(true);if (parsed.success) expect(parsed.data).toEqual(report);- expect(Object.keys(ownerReport)).toHaveLength(6);});it.each([diff --git a/src/shared/test/queries/agent-link.test.ts b/src/shared/test/queries/agent-link.test.tsindex cdf11556b..a423f6226 100644--- a/src/shared/test/queries/agent-link.test.ts+++ b/src/shared/test/queries/agent-link.test.ts@@ -4,13 +4,6 @@ import * as agentLinkQueries from "../../src/db/queries/agent-link";describe("agent-link query module exports", () => {it("exports listByWorkspace", () => { expect(typeof agentLinkQueries.listByWorkspace).toBe("function"); });it("exports listByAgent", () => { expect(typeof agentLinkQueries.listByAgent).toBe("function"); });- it("exports create", () => { expect(typeof agentLinkQueries.create).toBe("function"); });- it("exports update", () => { expect(typeof agentLinkQueries.update).toBe("function"); });- it("exports remove", () => { expect(typeof agentLinkQueries.remove).toBe("function"); });- it("exports getColleaguesForAgent", () => { expect(typeof agentLinkQueries.getColleaguesForAgent).toBe("function"); });- it("exports getAllColleaguesForWorkspace", () => { expect(typeof agentLinkQueries.getAllColleaguesForWorkspace).toBe("function"); });- it("exports getByPair", () => { expect(typeof agentLinkQueries.getByPair).toBe("function"); });- it("exports upsertByPair", () => { expect(typeof agentLinkQueries.upsertByPair).toBe("function"); });});// Helper: a select().from().where() chain that resolves to `rows`.diff --git a/src/shared/test/queries/agent.test.ts b/src/shared/test/queries/agent.test.tsindex a16ab6438..2b1473bc6 100644--- a/src/shared/test/queries/agent.test.ts+++ b/src/shared/test/queries/agent.test.ts@@ -10,9 +10,6 @@ function createMockDb(rows: any[]) {}describe("agent query module exports", () => {- it("exports getExistingHandles", () => {- expect(typeof agentQueries.getExistingHandles).toBe("function");- });it("exports getAgentByHandle", () => {expect(typeof agentQueries.getAgentByHandle).toBe("function");diff --git a/src/shared/test/queries/community-bot-audit-log.test.ts b/src/shared/test/queries/community-bot-audit-log.test.tsindex 644a4710e..9581a3c00 100644--- a/src/shared/test/queries/community-bot-audit-log.test.ts+++ b/src/shared/test/queries/community-bot-audit-log.test.ts@@ -21,14 +21,10 @@ describe("community/bot-audit-log exports", () => {it("exposes writers", () => {expect(typeof q.insertBotActivityEventStatement).toBe("function")expect(typeof q.pruneBotActivityEventsStatement).toBe("function")- expect(typeof q.insertBotActivityEventAndPrune).toBe("function")expect(typeof q.insertBotAuditWakeTrigger).toBe("function")expect(typeof q.insertBotAuditError).toBe("function")})- it("exposes a reader", () => {- expect(typeof q.listOwnedBotActivityEvents).toBe("function")- })it("exposes the retention cap constant", () => {// Plan §Retention: 500 rows per bot. Locked here so a refactordiff --git a/src/shared/test/queries/community-bot.test.ts b/src/shared/test/queries/community-bot.test.tsindex cb9cfdb3f..b2e43f17e 100644--- a/src/shared/test/queries/community-bot.test.ts+++ b/src/shared/test/queries/community-bot.test.ts@@ -18,14 +18,9 @@ import { computeDiscriminator } from "../../src/lib/discriminator"*/describe("community/bot exports", () => {it("exposes read helpers", () => {- expect(typeof q.listBotsForOwner).toBe("function")- expect(typeof q.getBotOwnedBy).toBe("function")expect(typeof q.getLiveBotAvatar).toBe("function")expect(typeof q.countLiveBotsForOwner).toBe("function")- expect(typeof q.getBotBinding).toBe("function")- expect(typeof q.listBotsForMachine).toBe("function")expect(typeof q.listBotsBoundToMachine).toBe("function")- expect(typeof q.getMachineForOwner).toBe("function")})it("exposes bot-activity heatmap helpers", () => {@@ -35,7 +30,6 @@ describe("community/bot exports", () => {})it("exposes write helpers", () => {- expect(typeof q.createBot).toBe("function")expect(typeof q.updateBot).toBe("function")expect(typeof q.softDeleteBot).toBe("function")expect(typeof q.assertNoLiveBots).toBe("function")diff --git a/src/shared/test/queries/community-diagnostic-report.test.ts b/src/shared/test/queries/community-diagnostic-report.test.tsindex bd2733ce5..965ac857a 100644--- a/src/shared/test/queries/community-diagnostic-report.test.ts+++ b/src/shared/test/queries/community-diagnostic-report.test.ts@@ -259,16 +259,8 @@ describe("diagnostic report query contract", () => {});it("exports only the frozen B2a state-machine helpers", () => {- expect(typeof q.createOrGetPendingDiagnosticReport).toBe("function");- expect(typeof q.getDiagnosticReportForOwner).toBe("function");- expect(typeof q.getPendingDiagnosticReportForMachine).toBe("function");expect(typeof q.getDiagnosticReportForMachine).toBe("function");- expect(typeof q.timeoutPendingDiagnosticReport).toBe("function");- expect(typeof q.listPendingDiagnosticReportsForMachine).toBe("function");- expect(typeof q.getNextPendingDiagnosticDeadlineForMachine).toBe("function");- expect(typeof q.timeoutPendingDiagnosticReportsForMachine).toBe("function");expect(typeof q.failPendingDiagnosticReport).toBe("function");- expect(typeof q.finalizeDiagnosticReportUpload).toBe("function");});it("bulk timeout and reconnect reads stay scoped to one machine and preserve future rows", async () => {diff --git a/src/shared/test/queries/community-inbox.test.ts b/src/shared/test/queries/community-inbox.test.tsindex a621ac136..af6906710 100644--- a/src/shared/test/queries/community-inbox.test.ts+++ b/src/shared/test/queries/community-inbox.test.ts@@ -15,25 +15,13 @@ import { isChannelUnread, isDmUnread } from "../../src/db/queries/community/inbo// (channels) / "any message" (DMs), which are orthogonal to the seq switch.describe("community/inbox exports", () => {- it("exports listUnreadChannels", () => {- expect(typeof inboxQueries.listUnreadChannels).toBe("function");- });it("exports isChannelUnread", () => {expect(typeof inboxQueries.isChannelUnread).toBe("function");});- it("exports listUnreadDms", () => {- expect(typeof inboxQueries.listUnreadDms).toBe("function");- });it("exports isDmUnread", () => {expect(typeof inboxQueries.isDmUnread).toBe("function");});- it("exports listUnreadForumOpeners", () => {- expect(typeof inboxQueries.listUnreadForumOpeners).toBe("function");- });- it("exports listThreadOpenersByChildIds", () => {- expect(typeof inboxQueries.listThreadOpenersByChildIds).toBe("function");- });});describe("isChannelUnread — two-branch predicate (seq)", () => {diff --git a/src/shared/test/queries/community-machine.test.ts b/src/shared/test/queries/community-machine.test.tsindex 659583d22..40a5ecb67 100644--- a/src/shared/test/queries/community-machine.test.ts+++ b/src/shared/test/queries/community-machine.test.ts@@ -42,26 +42,13 @@ function rotateEpoch(describe("community/machine exports", () => {it("exports the documented helpers", () => {- expect(typeof q.createPairingToken).toBe("function");- expect(typeof q.createReconnectPairingToken).toBe("function");- expect(typeof q.claimPairingToken).toBe("function");- expect(typeof q.findActiveToken).toBe("function");- expect(typeof q.findTokenById).toBe("function");expect(typeof q.touchTokenLastUsed).toBe("function");expect(typeof q.revokeToken).toBe("function");expect(typeof q.getMachineByIdForUser).toBe("function");expect(typeof q.listMachinesForUser).toBe("function");expect(typeof q.deleteMachineForUser).toBe("function");- expect(typeof q.toSummary).toBe("function");expect(typeof sessionEpoch.transitionMachineSessionEpoch).toBe("function");- expect(typeof q.hashCredential).toBe("function");- expect(typeof q.doNameFromHash).toBe("function");- expect(typeof q.findCredentialByHash).toBe("function");- expect(typeof q.findActiveCredentialByBearer).toBe("function");expect(typeof q.revokeCredential).toBe("function");- expect(typeof q.revokeCredentialsForMachine).toBe("function");- expect(typeof q.mintAgentRunnerKey).toBe("function");- expect(typeof q.findActiveAgentRunnerKeyByBearer).toBe("function");});it("does not export legacy machineUuid helpers", () => {diff --git a/src/shared/test/queries/community-member.test.ts b/src/shared/test/queries/community-member.test.tsindex 3a684e396..de1dfc871 100644--- a/src/shared/test/queries/community-member.test.ts+++ b/src/shared/test/queries/community-member.test.ts@@ -28,20 +28,6 @@ function createTerminalWhereMock(rows: any[]) {return chain;}-describe("community/member exports", () => {- it("exports listMemberUserIds", () => {- expect(typeof memberQueries.listMemberUserIds).toBe("function");- });- it("exports countMembers", () => {- expect(typeof memberQueries.countMembers).toBe("function");- });- it("exports listMembersPaginated", () => {- expect(typeof memberQueries.listMembersPaginated).toBe("function");- });- it("exports the atomic member + owner-bot removal", () => {- expect(typeof memberQueries.removeMemberAndOwnerBots).toBe("function");- });-});describe("removeMemberAndOwnerBots", () => {it("batches rail cleanup with target and bot deletes and returns the removed target", async () => {@@ -256,9 +242,6 @@ describe("searchMembers", () => {return chain;}- it("exports searchMembers", () => {- expect(typeof memberQueries.searchMembers).toBe("function");- });it("prefix-only: 'Ali' returns Alice + Alicia; 'Bob' returns Bob; 'li' returns nothing", async () => {// The Drizzle mock returns whatever `.limit()` resolves to — assert that the@@ -378,9 +361,6 @@ describe("getMembersByUserIds", () => {return chain;}- it("exports getMembersByUserIds", () => {- expect(typeof memberQueries.getMembersByUserIds).toBe("function");- });it("returns [] without querying when the id list is empty", async () => {const db = createMock([{ id: "should_not_be_used" }]);diff --git a/src/shared/test/queries/community-mention.test.ts b/src/shared/test/queries/community-mention.test.tsindex bd207004c..252186a6b 100644--- a/src/shared/test/queries/community-mention.test.ts+++ b/src/shared/test/queries/community-mention.test.ts@@ -28,14 +28,6 @@ function createUpdateBuilderMock() {return db;}-describe("community/mention exports", () => {- it("exports markChannelMentionsReadBuilder", () => {- expect(typeof mentionQueries.markChannelMentionsReadBuilder).toBe("function");- });- it("exports hasMentionForMessage", () => {- expect(typeof mentionQueries.hasMentionForMessage).toBe("function");- });-});describe("hasMentionForMessage", () => {function createSelectMock(rows: unknown[]) {diff --git a/src/shared/test/queries/community-message-tag.test.ts b/src/shared/test/queries/community-message-tag.test.tsindex 682ec26e5..2f47961c3 100644--- a/src/shared/test/queries/community-message-tag.test.ts+++ b/src/shared/test/queries/community-message-tag.test.ts@@ -3,12 +3,6 @@ import * as tagQueries from "../../src/db/queries/community/message-tag";describe("community/message-tag exports", () => {it("exports the tag CRUD + filter", () => {- expect(typeof tagQueries.addMessageTag).toBe("function");- expect(typeof tagQueries.removeMessageTag).toBe("function");- expect(typeof tagQueries.replaceMessageTags).toBe("function");- expect(typeof tagQueries.listTagsForMessage).toBe("function");- expect(typeof tagQueries.listTagsForMessages).toBe("function");- expect(typeof tagQueries.filterMessageIdsByTag).toBe("function");expect(typeof tagQueries.listDistinctTagsForChannel).toBe("function");});});diff --git a/src/shared/test/queries/community-message.test.ts b/src/shared/test/queries/community-message.test.tsindex d34e0859e..4f01d573a 100644--- a/src/shared/test/queries/community-message.test.ts+++ b/src/shared/test/queries/community-message.test.ts@@ -10,14 +10,6 @@ import {vi.mock("nanoid", () => ({ nanoid: vi.fn(() => "m_generated") }));-describe("community/message exports", () => {- it("exports getMessagesByIds", () => {- expect(typeof messageQueries.getMessagesByIds).toBe("function");- });- it("exports createMessage", () => {- expect(typeof messageQueries.createMessage).toBe("function");- });-});describe("getMessageIdentityByChannelAndSeq", () => {it("projects only message identity for channel-scoped resolution", async () => {@@ -115,9 +107,6 @@ describe("getMessagesByIds", () => {});describe("getMessageInScope", () => {- it("exports as a function", () => {- expect(typeof messageQueries.getMessageInScope).toBe("function");- });it("returns the row when the db finds an in-scope match", async () => {const db = createSelectMock([messageRow("m_1")]);@@ -143,9 +132,6 @@ describe("getMessageInScope", () => {});describe("getMessagesByIdsInScope", () => {- it("exports as a function", () => {- expect(typeof messageQueries.getMessagesByIdsInScope).toBe("function");- });it("returns [] and does NOT hit db when ids is empty", async () => {const db = createSelectMock([messageRow("m_1")]);diff --git a/src/shared/test/queries/community-notification-setting.test.ts b/src/shared/test/queries/community-notification-setting.test.tsindex 287760bcb..a53a6438e 100644--- a/src/shared/test/queries/community-notification-setting.test.ts+++ b/src/shared/test/queries/community-notification-setting.test.ts@@ -18,11 +18,7 @@ const POST = { id: "p1", serverId: "s1", parentChannelId: "c1" };const DM = { id: "dm1", serverId: null as unknown as string, parentChannelId: null };describe("community/notification-setting exports", () => {- it("exports the three effective-level functions", () => {- expect(typeof notif.computeEffectiveLevel).toBe("function");- expect(typeof notif.resolveEffectiveLevel).toBe("function");- expect(typeof notif.resolveEffectiveLevelForUsers).toBe("function");- });+it("keeps the CRUD helpers", () => {expect(typeof notif.getSettings).toBe("function");diff --git a/src/shared/test/queries/community-read-state.test.ts b/src/shared/test/queries/community-read-state.test.tsindex 55faf985e..59072a9f7 100644--- a/src/shared/test/queries/community-read-state.test.ts+++ b/src/shared/test/queries/community-read-state.test.ts@@ -20,12 +20,7 @@ function createInsertBuilderMock() {describe("community/read-state exports", () => {it("exports markReadToMessageBuilder + markReadToMessage", () => {- expect(typeof readStateQueries.markReadToMessageBuilder).toBe("function");expect(typeof readStateQueries.markReadToMessage).toBe("function");- expect(typeof readStateQueries.markReadToMessageWithRevision).toBe("function");- });- it("exports markAllServerChannelsRead", () => {- expect(typeof readStateQueries.markAllServerChannelsRead).toBe("function");});it("builds one revision guard from multiple canonical effects", () => {diff --git a/src/shared/test/queries/community-thread.test.ts b/src/shared/test/queries/community-thread.test.tsindex ba9a92592..9b0b32036 100644--- a/src/shared/test/queries/community-thread.test.ts+++ b/src/shared/test/queries/community-thread.test.ts@@ -8,11 +8,8 @@ import { FORUM_ARCHIVE_TAG } from "../../src/constants/community";describe("community/thread exports", () => {it("exports the participant CRUD", () => {- expect(typeof threadQueries.addThreadParticipant).toBe("function");- expect(typeof threadQueries.listThreadParticipantUserIds).toBe("function");expect(typeof threadQueries.listThreadParticipants).toBe("function");expect(typeof threadQueries.removeThreadParticipant).toBe("function");- expect(typeof threadQueries.listParticipatingThreadIds).toBe("function");});});diff --git a/src/shared/test/queries/community-user-profile.test.ts b/src/shared/test/queries/community-user-profile.test.tsindex 612bac357..cd4c2795b 100644--- a/src/shared/test/queries/community-user-profile.test.ts+++ b/src/shared/test/queries/community-user-profile.test.ts@@ -22,13 +22,6 @@ function createUpsertMock(returnRow: any) {return chain;}-describe("community/user-profile exports", () => {- it("exports public profile + getProfile + updateProfile queries", () => {- expect(typeof profileQueries.getPublicProfileForViewer).toBe("function");- expect(typeof profileQueries.getProfile).toBe("function");- expect(typeof profileQueries.updateProfile).toBe("function");- });-});describe("getPublicProfileForViewer", () => {let sqlite: Sqlite.Database;diff --git a/src/shared/test/queries/conversation-map.test.ts b/src/shared/test/queries/conversation-map.test.tsindex dc1d19326..b891ce4f6 100644--- a/src/shared/test/queries/conversation-map.test.ts+++ b/src/shared/test/queries/conversation-map.test.ts@@ -14,9 +14,6 @@ function createMockDb(rows: any[]) {}describe("conversation-map query module exports", () => {- it("exports findByKey", () => {- expect(typeof conversationMapQueries.findByKey).toBe("function");- });it("exports createMapping", () => {expect(typeof conversationMapQueries.createMapping).toBe("function");diff --git a/src/shared/test/queries/conversation.test.ts b/src/shared/test/queries/conversation.test.tsindex a14718050..c5404f47a 100644--- a/src/shared/test/queries/conversation.test.ts+++ b/src/shared/test/queries/conversation.test.ts@@ -24,13 +24,6 @@ describe("conversation query module exports", () => {expect(typeof conversationQueries.createConversation).toBe("function");});- it("exports getConversation", () => {- expect(typeof conversationQueries.getConversation).toBe("function");- });-- it("exports getConversationsByIds", () => {- expect(typeof conversationQueries.getConversationsByIds).toBe("function");- });it("exports listConversations", () => {expect(typeof conversationQueries.listConversations).toBe("function");@@ -40,25 +33,16 @@ describe("conversation query module exports", () => {expect(typeof conversationQueries.listConversationsByAgent).toBe("function");});- it("exports updateConversationTitle", () => {- expect(typeof conversationQueries.updateConversationTitle).toBe("function");- });it("exports getOrCreateAgentConversation", () => {expect(typeof conversationQueries.getOrCreateAgentConversation).toBe("function");});- it("exports deleteConversation", () => {- expect(typeof conversationQueries.deleteConversation).toBe("function");- });it("exports listPreviousConversations", () => {expect(typeof conversationQueries.listPreviousConversations).toBe("function");});- it("exports hasPreviousConversations", () => {- expect(typeof conversationQueries.hasPreviousConversations).toBe("function");- });});describe("conversation query function signatures (with optional channel param)", () => {diff --git a/src/shared/test/queries/email-account.test.ts b/src/shared/test/queries/email-account.test.tsindex e5012c879..a43883c45 100644--- a/src/shared/test/queries/email-account.test.ts+++ b/src/shared/test/queries/email-account.test.ts@@ -13,14 +13,7 @@ function createSelectMock(rows: any[]) {}describe("email-account exports", () => {- it("exports createEmailAccount", () => { expect(typeof ea.createEmailAccount).toBe("function"); });- it("exports getEmailAccount", () => { expect(typeof ea.getEmailAccount).toBe("function"); });- it("exports getEmailAccountScoped", () => { expect(typeof ea.getEmailAccountScoped).toBe("function"); });- it("exports getEmailAccountById", () => { expect(typeof ea.getEmailAccountById).toBe("function"); });it("exports getEmailAccountsByAgent", () => { expect(typeof ea.getEmailAccountsByAgent).toBe("function"); });- it("exports updateEmailAccount", () => { expect(typeof ea.updateEmailAccount).toBe("function"); });- it("exports deleteEmailAccount", () => { expect(typeof ea.deleteEmailAccount).toBe("function"); });- it("exports getEmailAccountsByAgents", () => { expect(typeof ea.getEmailAccountsByAgents).toBe("function"); });it("exports getAllEmailAccountsForWorkspace", () => { expect(typeof ea.getAllEmailAccountsForWorkspace).toBe("function"); });});diff --git a/src/shared/test/queries/email.test.ts b/src/shared/test/queries/email.test.tsindex fa738489b..3dad13526 100644--- a/src/shared/test/queries/email.test.ts+++ b/src/shared/test/queries/email.test.ts@@ -31,9 +31,6 @@ describe("email query module exports", () => {expect(typeof emailQueries.getRejectedEmails).toBe("function");});- it("exports getEmailByMessageId", () => {- expect(typeof emailQueries.getEmailByMessageId).toBe("function");- });it("exports deleteEmail", () => {expect(typeof emailQueries.deleteEmail).toBe("function");@@ -43,17 +40,11 @@ describe("email query module exports", () => {expect(typeof emailQueries.createEmail).toBe("function");});- it("exports getEmailById", () => {- expect(typeof emailQueries.getEmailById).toBe("function");- });it("exports getEmailsByAgent", () => {expect(typeof emailQueries.getEmailsByAgent).toBe("function");});- it("exports updateEmailStatus", () => {- expect(typeof emailQueries.updateEmailStatus).toBe("function");- });});describe("email query function signatures", () => {diff --git a/src/shared/test/queries/inbox.test.ts b/src/shared/test/queries/inbox.test.tsindex cc6e9a9f9..0c03455c1 100644--- a/src/shared/test/queries/inbox.test.ts+++ b/src/shared/test/queries/inbox.test.ts@@ -13,18 +13,6 @@ function createMockDb(rows: any[]) {// Exports// ----------------------------------------------------------------------------describe("inbox exports", () => {- it("exports listUnreadConversations", () => { expect(typeof inboxQueries.listUnreadConversations).toBe("function"); });- it("exports getUnreadCount", () => { expect(typeof inboxQueries.getUnreadCount).toBe("function"); });- it("exports markConversationRead", () => { expect(typeof inboxQueries.markConversationRead).toBe("function"); });- it("exports markAllConversationsRead", () => { expect(typeof inboxQueries.markAllConversationsRead).toBe("function"); });- it("exports upsertUnreadEntry", () => { expect(typeof inboxQueries.upsertUnreadEntry).toBe("function"); });- it("exports updateUnreadLatestMessage", () => { expect(typeof inboxQueries.updateUnreadLatestMessage).toBe("function"); });- it("exports deleteUnreadEntry", () => { expect(typeof inboxQueries.deleteUnreadEntry).toBe("function"); });- it("exports deleteAllUnreadEntries", () => { expect(typeof inboxQueries.deleteAllUnreadEntries).toBe("function"); });- it("exports findLatestAssistantMessageId", () => { expect(typeof inboxQueries.findLatestAssistantMessageId).toBe("function"); });- it("exports isUnreadEligible", () => { expect(typeof inboxQueries.isUnreadEligible).toBe("function"); });-});// ---------------------------------------------------------------------------// TC4: isUnreadEligiblediff --git a/src/shared/test/queries/issue.test.ts b/src/shared/test/queries/issue.test.tsindex 63aa879c1..94266f0e9 100644--- a/src/shared/test/queries/issue.test.ts+++ b/src/shared/test/queries/issue.test.ts@@ -1,131 +1,178 @@-import { describe, it, expect, vi } from "vitest";+import { readFileSync } from "node:fs";+import Sqlite from "better-sqlite3";+import { drizzle } from "drizzle-orm/better-sqlite3";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import type { Database } from "../../src/db";+import { issue } from "../../src/db/schema";import * as issueQueries from "../../src/db/queries/issue";-function createSelectMock(rows: any[]) {- const chain: any = {};- chain.select = vi.fn(() => chain);- chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => Promise.resolve(rows));- chain.orderBy = vi.fn(() => chain);- chain.insert = vi.fn(() => chain);- chain.values = vi.fn(() => chain);- chain.returning = vi.fn(() => Promise.resolve(rows));- return chain;-}+let sqlite: Sqlite.Database;+let db: Database;-describe("issue exports", () => {- it("exports createIssue", () => { expect(typeof issueQueries.createIssue).toBe("function"); });- it("exports getIssue", () => { expect(typeof issueQueries.getIssue).toBe("function"); });- it("exports getIssueByConversation", () => { expect(typeof issueQueries.getIssueByConversation).toBe("function"); });- it("exports listIssues", () => { expect(typeof issueQueries.listIssues).toBe("function"); });- it("exports updateIssue", () => { expect(typeof issueQueries.updateIssue).toBe("function"); });- it("exports setLatestTask", () => { expect(typeof issueQueries.setLatestTask).toBe("function"); });- it("exports deleteIssue", () => { expect(typeof issueQueries.deleteIssue).toBe("function"); });- it("exports listIssueMessages", () => { expect(typeof issueQueries.listIssueMessages).toBe("function"); });+beforeEach(() => {+ sqlite = new Sqlite(":memory:");+ sqlite.pragma("foreign_keys=ON");+ sqlite.exec(`+ CREATE TABLE workspace(id TEXT PRIMARY KEY);+ CREATE TABLE user(id TEXT PRIMARY KEY);+ CREATE TABLE agent(id TEXT, workspace_id TEXT, PRIMARY KEY(id, workspace_id));+ CREATE TABLE conversation(id TEXT PRIMARY KEY);+ CREATE TABLE agent_task_queue(id TEXT PRIMARY KEY);+ INSERT INTO workspace VALUES('w'), ('other');+ INSERT INTO user VALUES('u1'), ('u2');+ INSERT INTO agent VALUES('a1','w'), ('a2','w');+ INSERT INTO conversation VALUES('c1'), ('c2');+ INSERT INTO agent_task_queue VALUES('t1');+ `);+ for (const name of ["0022_issues.sql", "0025_issue_nullable_agent.sql"]) {+ sqlite.exec(readFileSync(new URL(`../../../web/migrations/${name}`, import.meta.url), "utf8"));+ }+ db = drizzle(sqlite) as unknown as Database;});+afterEach(() => sqlite.close());++async function seed(id: string, values: Partial<typeof issue.$inferInsert> = {}) {+ await db.insert(issue).values({+ id, workspaceId: "w", creatorUserId: "u1", title: id,+ agentId: null, conversationId: null,+ createdAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z",+ ...values,+ }).run();+}++async function ids(options: Parameters<typeof issueQueries.listIssues>[2]) {+ return (await issueQueries.listIssues(db, "w", options)).map(row => row.id);+}describe("createIssue", () => {- it("creates with default status todo", async () => {- const iss = { id: "iss_1" };- const mockDb = createSelectMock([iss]);- const result = await issueQueries.createIssue(mockDb, { workspaceId: "w", agentId: "a", creatorUserId: "u", conversationId: "c", title: "T", description: "D" });- expect(mockDb.values).toHaveBeenCalledWith(expect.objectContaining({ status: "todo" }));- expect(result).toEqual(iss);- });- it("uses custom status", async () => {- const mockDb = createSelectMock([{ id: "iss_1" }]);- await issueQueries.createIssue(mockDb, { workspaceId: "w", agentId: null, creatorUserId: "u", conversationId: null, title: "T", description: "D", status: "in_progress" });- expect(mockDb.values).toHaveBeenCalledWith(expect.objectContaining({ status: "in_progress" }));+ it("persists the default todo status and supplied ownership", async () => {+ const created = await issueQueries.createIssue(db, {+ workspaceId: "w", agentId: "a1", creatorUserId: "u1", conversationId: "c1", title: "T", description: "D",+ });+ expect(created).toMatchObject({ id: expect.any(String), workspaceId: "w", creatorUserId: "u1", status: "todo", title: "T" });+ expect(await issueQueries.getIssue(db, created.id, "w")).toEqual(created);+ });+ it("persists custom status with nullable agent and conversation", async () => {+ const created = await issueQueries.createIssue(db, {+ workspaceId: "w", agentId: null, creatorUserId: "u1", conversationId: null, title: "T", description: "D", status: "in_progress",+ });+ expect(await issueQueries.getIssue(db, created.id, "w")).toMatchObject({ status: "in_progress", agentId: null, conversationId: null });});});describe("getIssue", () => {- it("returns null when not found", async () => { expect(await issueQueries.getIssue(createSelectMock([]), "x", "w")).toBeNull(); });- it("returns issue", async () => { const i = { id: "iss_1" }; expect(await issueQueries.getIssue(createSelectMock([i]), "iss_1", "w")).toEqual(i); });- it("returns null when userId does not match (where adds creatorUserId condition)", async () => {- expect(await issueQueries.getIssue(createSelectMock([]), "iss_1", "w", "other_user")).toBeNull();+ it("returns null when not found", async () => {+ expect(await issueQueries.getIssue(db, "missing", "w")).toBeNull();+ });+ it("returns an issue without requiring the optional userId", async () => {+ await seed("i");+ expect(await issueQueries.getIssue(db, "i", "w")).toMatchObject({ id: "i", creatorUserId: "u1" });});- it("returns issue without userId (backwards compat for daemon)", async () => {- const i = { id: "iss_1" };- expect(await issueQueries.getIssue(createSelectMock([i]), "iss_1", "w")).toEqual(i);+ it("filters a stored issue by both workspace and optional owner", async () => {+ await seed("i");+ expect(await issueQueries.getIssue(db, "i", "w", "u1")).toMatchObject({ id: "i" });+ expect(await issueQueries.getIssue(db, "i", "w", "u2")).toBeNull();+ expect(await issueQueries.getIssue(db, "i", "other", "u1")).toBeNull();});});describe("getIssueByConversation", () => {- it("returns null when not found", async () => { expect(await issueQueries.getIssueByConversation(createSelectMock([]), "x", "w")).toBeNull(); });- it("returns issue", async () => { const i = { id: "iss_1" }; expect(await issueQueries.getIssueByConversation(createSelectMock([i]), "c", "w")).toEqual(i); });+ it("returns null when not found", async () => {+ expect(await issueQueries.getIssueByConversation(db, "missing", "w")).toBeNull();+ });+ it("returns the matching conversation only in its workspace", async () => {+ await seed("i", { conversationId: "c1" });+ expect(await issueQueries.getIssueByConversation(db, "c1", "w")).toMatchObject({ id: "i" });+ expect(await issueQueries.getIssueByConversation(db, "c1", "other")).toBeNull();+ });});describe("listIssues", () => {- function createListMock() {- const chain: any = {};- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => chain); chain.orderBy = vi.fn(() => Promise.resolve([]));- return chain;- }- it("lists with userId filter", async () => {- const mockDb = createListMock();- await issueQueries.listIssues(mockDb, "w", { userId: "u1" });- expect(mockDb.orderBy).toHaveBeenCalled();- });- it("filters by agentId", async () => { await issueQueries.listIssues(createListMock(), "w", { userId: "u1", agentId: "a" }); });- it("filters by status", async () => { await issueQueries.listIssues(createListMock(), "w", { userId: "u1", status: "todo" }); });- it("filters terminal=true", async () => { await issueQueries.listIssues(createListMock(), "w", { userId: "u1", terminal: true }); });- it("filters terminal=false", async () => { await issueQueries.listIssues(createListMock(), "w", { userId: "u1", terminal: false }); });+ it("filters workspace and owner before ordering newest first", async () => {+ await seed("older");+ await seed("newer", { updatedAt: "2026-01-02T00:00:00.000Z" });+ await seed("other-owner", { creatorUserId: "u2" });+ await seed("other-workspace", { workspaceId: "other" });+ expect(await ids({ userId: "u1" })).toEqual(["newer", "older"]);+ });+ it("filters by agentId", async () => {+ await seed("a", { agentId: "a1" });+ await seed("b", { agentId: "a2" });+ await seed("unassigned");+ expect(await ids({ userId: "u1", agentId: "a1" })).toEqual(["a"]);+ });+ it("filters by status", async () => {+ await seed("todo");+ await seed("active", { status: "in_progress" });+ expect(await ids({ userId: "u1", status: "todo" })).toEqual(["todo"]);+ });+ it("filters terminal=true", async () => {+ for (const status of ["todo", "in_progress", "review", "done", "closed", "canceled", "failed"]) await seed(status, { status });+ expect((await ids({ userId: "u1", terminal: true })).sort()).toEqual(["canceled", "closed", "done", "failed"]);+ });+ it("filters terminal=false", async () => {+ for (const status of ["todo", "in_progress", "review", "done", "closed", "canceled", "failed"]) await seed(status, { status });+ expect((await ids({ userId: "u1", terminal: false })).sort()).toEqual(["in_progress", "review", "todo"]);+ });});describe("updateIssue", () => {- it("returns null when not found", async () => {- const chain: any = {};- chain.update = vi.fn(() => chain); chain.set = vi.fn(() => chain);- chain.where = vi.fn(() => chain); chain.returning = vi.fn(() => Promise.resolve([]));- expect(await issueQueries.updateIssue(chain, "x", "w", { title: "T" })).toBeNull();- });- it("returns updated issue", async () => {- const i = { id: "iss_1" };- const chain: any = {};- chain.update = vi.fn(() => chain); chain.set = vi.fn(() => chain);- chain.where = vi.fn(() => chain); chain.returning = vi.fn(() => Promise.resolve([i]));- expect(await issueQueries.updateIssue(chain, "iss_1", "w", { title: "T" })).toEqual(i);- });- it("sets completedAt for terminal status", async () => {- const chain: any = {};- chain.update = vi.fn(() => chain); chain.set = vi.fn(() => chain);- chain.where = vi.fn(() => chain); chain.returning = vi.fn(() => Promise.resolve([{ id: "iss_1" }]));- await issueQueries.updateIssue(chain, "iss_1", "w", { status: "done" });- expect(chain.set).toHaveBeenCalledWith(expect.objectContaining({ completedAt: expect.any(String) }));- });- it("sets completedAt null for active status", async () => {- const chain: any = {};- chain.update = vi.fn(() => chain); chain.set = vi.fn(() => chain);- chain.where = vi.fn(() => chain); chain.returning = vi.fn(() => Promise.resolve([{ id: "iss_1" }]));- await issueQueries.updateIssue(chain, "iss_1", "w", { status: "todo" });- expect(chain.set).toHaveBeenCalledWith(expect.objectContaining({ completedAt: null }));+ it("cannot update an absent or foreign-workspace issue", async () => {+ await seed("i");+ expect(await issueQueries.updateIssue(db, "missing", "w", { title: "T" })).toBeNull();+ expect(await issueQueries.updateIssue(db, "i", "other", { title: "T" })).toBeNull();+ expect(await issueQueries.getIssue(db, "i", "w")).toMatchObject({ title: "i" });+ });+ it("returns and persists the updated issue", async () => {+ await seed("i");+ const updated = await issueQueries.updateIssue(db, "i", "w", { title: "T" });+ expect(updated).toMatchObject({ id: "i", title: "T" });+ expect(await issueQueries.getIssue(db, "i", "w")).toEqual(updated);+ });+ it("persists completedAt for a terminal status", async () => {+ await seed("i");+ await issueQueries.updateIssue(db, "i", "w", { status: "done" });+ expect(await issueQueries.getIssue(db, "i", "w")).toMatchObject({ status: "done", completedAt: expect.any(String) });+ });+ it("clears persisted completedAt when the issue becomes active", async () => {+ await seed("i", { status: "done", completedAt: "2026-01-01T00:00:00.000Z" });+ await issueQueries.updateIssue(db, "i", "w", { status: "todo" });+ expect(await issueQueries.getIssue(db, "i", "w")).toMatchObject({ status: "todo", completedAt: null });+ });+});++describe("setLatestTask", () => {+ it("persists and clears the task link only within the workspace", async () => {+ await seed("i");+ await issueQueries.setLatestTask(db, "i", "w", "t1");+ expect(await issueQueries.getIssue(db, "i", "w")).toMatchObject({ latestTaskId: "t1" });+ expect(await issueQueries.setLatestTask(db, "i", "other", null)).toBeNull();+ expect(await issueQueries.getIssue(db, "i", "w")).toMatchObject({ latestTaskId: "t1" });+ await issueQueries.setLatestTask(db, "i", "w", null);+ expect(await issueQueries.getIssue(db, "i", "w")).toMatchObject({ latestTaskId: null });});});describe("deleteIssue", () => {- it("returns null when not found", async () => {- const chain: any = {};- chain.delete = vi.fn(() => chain); chain.where = vi.fn(() => chain);- chain.returning = vi.fn(() => Promise.resolve([]));- expect(await issueQueries.deleteIssue(chain, "x", "w")).toBeNull();- });- it("returns deleted issue", async () => {- const i = { id: "iss_1" };- const chain: any = {};- chain.delete = vi.fn(() => chain); chain.where = vi.fn(() => chain);- chain.returning = vi.fn(() => Promise.resolve([i]));- expect(await issueQueries.deleteIssue(chain, "iss_1", "w")).toEqual(i);+ it("cannot delete an absent or foreign-workspace issue", async () => {+ await seed("i");+ expect(await issueQueries.deleteIssue(db, "missing", "w")).toBeNull();+ expect(await issueQueries.deleteIssue(db, "i", "other")).toBeNull();+ expect(await issueQueries.getIssue(db, "i", "w")).toMatchObject({ id: "i" });+ });+ it("returns and removes the deleted issue", async () => {+ await seed("i");+ expect(await issueQueries.deleteIssue(db, "i", "w")).toMatchObject({ id: "i" });+ expect(await issueQueries.getIssue(db, "i", "w")).toBeNull();});});describe("listIssueMessages", () => {- it("returns null when issue not found", async () => { expect(await issueQueries.listIssueMessages(createSelectMock([]), "x", "w")).toBeNull(); });- it("returns empty when no conversationId", async () => {- const chain: any = {};- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => Promise.resolve([{ id: "iss_1", conversationId: null }]));- expect(await issueQueries.listIssueMessages(chain, "iss_1", "w")).toEqual([]);+ it("returns null when issue not found", async () => {+ expect(await issueQueries.listIssueMessages(db, "missing", "w")).toBeNull();+ });+ it("returns empty when no conversationId exists", async () => {+ await seed("i");+ expect(await issueQueries.listIssueMessages(db, "i", "w")).toEqual([]);});});diff --git a/src/shared/test/queries/machine.test.ts b/src/shared/test/queries/machine.test.tsindex 27fc2a2b8..0ddf91f54 100644--- a/src/shared/test/queries/machine.test.ts+++ b/src/shared/test/queries/machine.test.ts@@ -17,16 +17,7 @@ function createMockDb(rows: any[]) {}describe("machine query module exports", () => {- it("exports upsertMachine", () => { expect(typeof machineQueries.upsertMachine).toBe("function"); });- it("exports updateMachineLastSeen", () => { expect(typeof machineQueries.updateMachineLastSeen).toBe("function"); });- it("exports setMachineLastSeenNull", () => { expect(typeof machineQueries.setMachineLastSeenNull).toBe("function"); });- it("exports getMachineByDaemon", () => { expect(typeof machineQueries.getMachineByDaemon).toBe("function"); });it("exports listMachinesForWorkspace", () => { expect(typeof machineQueries.listMachinesForWorkspace).toBe("function"); });- it("exports deleteMachine", () => { expect(typeof machineQueries.deleteMachine).toBe("function"); });- it("exports setPendingUpdateVersion", () => { expect(typeof machineQueries.setPendingUpdateVersion).toBe("function"); });- it("exports clearPendingUpdateVersion", () => { expect(typeof machineQueries.clearPendingUpdateVersion).toBe("function"); });- it("exports setPendingRescan", () => { expect(typeof machineQueries.setPendingRescan).toBe("function"); });- it("exports clearPendingRescan", () => { expect(typeof machineQueries.clearPendingRescan).toBe("function"); });});describe("upsertMachine", () => {diff --git a/src/shared/test/queries/meeting-session.test.ts b/src/shared/test/queries/meeting-session.test.tsindex ec5b02cad..d744a67ea 100644--- a/src/shared/test/queries/meeting-session.test.ts+++ b/src/shared/test/queries/meeting-session.test.ts@@ -20,25 +20,11 @@ describe("meeting-session query module exports", () => {expect(typeof meetingQueries.createMeetingSession).toBe("function")})- it("exports getMeetingSession", () => {- expect(typeof meetingQueries.getMeetingSession).toBe("function")- })-- it("exports getMeetingSessionById", () => {- expect(typeof meetingQueries.getMeetingSessionById).toBe("function")- })it("exports listMeetingSessions", () => {expect(typeof meetingQueries.listMeetingSessions).toBe("function")})- it("exports updateMeetingSession", () => {- expect(typeof meetingQueries.updateMeetingSession).toBe("function")- })-- it("exports deleteMeetingSession", () => {- expect(typeof meetingQueries.deleteMeetingSession).toBe("function")- })it("exports listScheduledMeetings", () => {expect(typeof meetingQueries.listScheduledMeetings).toBe("function")diff --git a/src/shared/test/queries/member.test.ts b/src/shared/test/queries/member.test.tsindex 324c62b2e..f3720ce0a 100644--- a/src/shared/test/queries/member.test.ts+++ b/src/shared/test/queries/member.test.ts@@ -13,14 +13,6 @@ function createSelectMock(rows: any[]) {return chain;}-describe("member exports", () => {- it("exports getMemberByUserAndWorkspace", () => { expect(typeof memberQueries.getMemberByUserAndWorkspace).toBe("function"); });- it("exports listMembers", () => { expect(typeof memberQueries.listMembers).toBe("function"); });- it("exports updateMemberGlobalInstruction", () => { expect(typeof memberQueries.updateMemberGlobalInstruction).toBe("function"); });- it("exports createMember", () => { expect(typeof memberQueries.createMember).toBe("function"); });- it("exports getMember", () => { expect(typeof memberQueries.getMember).toBe("function"); });- it("exports deleteMember", () => { expect(typeof memberQueries.deleteMember).toBe("function"); });-});describe("getMemberByUserAndWorkspace", () => {it("returns null when not found", async () => { expect(await memberQueries.getMemberByUserAndWorkspace(createSelectMock([]), "u", "w")).toBeNull(); });diff --git a/src/shared/test/queries/message.test.ts b/src/shared/test/queries/message.test.tsindex 62cb3d259..a74771026 100644--- a/src/shared/test/queries/message.test.ts+++ b/src/shared/test/queries/message.test.ts@@ -23,21 +23,11 @@ describe("message query module exports", () => {expect(typeof messageQueries.createMessage).toBe("function");});- it("exports getNewestMessageId", () => {- expect(typeof messageQueries.getNewestMessageId).toBe("function");- });-- it("exports getActiveMessageCount", () => {- expect(typeof messageQueries.getActiveMessageCount).toBe("function");- });it("exports listMessages", () => {expect(typeof messageQueries.listMessages).toBe("function");});- it("exports getMessage", () => {- expect(typeof messageQueries.getMessage).toBe("function");- });it("exports updateMessageTaskId", () => {expect(typeof messageQueries.updateMessageTaskId).toBe("function");diff --git a/src/shared/test/queries/runtime.test.ts b/src/shared/test/queries/runtime.test.tsindex 711aae506..ab7c2386b 100644--- a/src/shared/test/queries/runtime.test.ts+++ b/src/shared/test/queries/runtime.test.ts@@ -11,9 +11,6 @@ function createMockDb(rows: any[]) {}describe("runtime query module exports", () => {- it("exports getAgentRuntimesForWorkspace", () => {- expect(typeof runtimeQueries.getAgentRuntimesForWorkspace).toBe("function");- });it("exports getAgentRuntimeForWorkspace", () => {expect(typeof runtimeQueries.getAgentRuntimeForWorkspace).toBe("function");@@ -41,9 +38,6 @@ describe("updateRuntimeCliVersionByDaemon", () => {return chain;}- it("exports updateRuntimeCliVersionByDaemon", () => {- expect(typeof runtimeQueries.updateRuntimeCliVersionByDaemon).toBe("function");- });it("no-ops without touching DB when cliVersion is empty", async () => {const mockDb = createUpdateMockDb();diff --git a/src/shared/test/queries/server.test.ts b/src/shared/test/queries/server.test.tsindex 99774922c..46545e93c 100644--- a/src/shared/test/queries/server.test.ts+++ b/src/shared/test/queries/server.test.ts@@ -80,15 +80,6 @@ function createDbMock(opts: {return { db, insertCalls, selectCalls };}-describe("community/server exports", () => {- it("exports createServer", () => {- expect(typeof serverQueries.createServer).toBe("function");- });-- it("exports the old-value icon CAS", () => {- expect(typeof serverQueries.updateServerIconIfCurrent).toBe("function");- });-});describe("updateServerIconIfCurrent", () => {function updateDb(rows: unknown[]) {diff --git a/src/shared/test/queries/session.test.ts b/src/shared/test/queries/session.test.tsindex 61a55d035..bfd8d6bd3 100644--- a/src/shared/test/queries/session.test.ts+++ b/src/shared/test/queries/session.test.ts@@ -9,9 +9,6 @@ function createMockDb(rows: any[]) {return chain;}-describe("session exports", () => {- it("exports getValidSession", () => { expect(typeof sessionQueries.getValidSession).toBe("function"); });-});describe("getValidSession", () => {it("returns null when no valid session", async () => { expect(await sessionQueries.getValidSession(createMockDb([]), "tok")).toBeNull(); });diff --git a/src/shared/test/queries/user.test.ts b/src/shared/test/queries/user.test.tsindex e3d834a81..56e48e638 100644--- a/src/shared/test/queries/user.test.ts+++ b/src/shared/test/queries/user.test.ts@@ -66,14 +66,6 @@ function conditionContainsString(node: unknown, needle: string, seen = new Set<ureturn false;}-describe("user exports", () => {- it("exports getUserPublic", () => { expect(typeof userQueries.getUserPublic).toBe("function"); });- it("exports getUserSelf", () => { expect(typeof userQueries.getUserSelf).toBe("function"); });- it("exports getUserByEmail", () => { expect(typeof userQueries.getUserByEmail).toBe("function"); });- it("exports getUserByProviderAccount", () => { expect(typeof userQueries.getUserByProviderAccount).toBe("function"); });- it("exports createUser", () => { expect(typeof userQueries.createUser).toBe("function"); });- it("exports updateUser", () => { expect(typeof userQueries.updateUser).toBe("function"); });-});describe("getUserPublic", () => {it("returns null when not found", async () => { expect(await userQueries.getUserPublic(createSelectMock([]), "x")).toBeNull(); });diff --git a/src/shared/test/queries/whitelist.test.ts b/src/shared/test/queries/whitelist.test.tsindex 4a86e1903..67e90ca5e 100644--- a/src/shared/test/queries/whitelist.test.ts+++ b/src/shared/test/queries/whitelist.test.ts@@ -20,13 +20,6 @@ describe("whitelist query module exports", () => {expect(typeof whitelistQueries.getWhitelist).toBe("function");});- it("exports addWhitelist", () => {- expect(typeof whitelistQueries.addWhitelist).toBe("function");- });-- it("exports removeWhitelist", () => {- expect(typeof whitelistQueries.removeWhitelist).toBe("function");- });it("exports removeWhitelistByEmail", () => {expect(typeof whitelistQueries.removeWhitelistByEmail).toBe("function");diff --git a/src/web/auth/index.test.ts b/src/web/auth/index.test.tsindex fd3d3c54d..a7eb6e993 100644--- a/src/web/auth/index.test.ts+++ b/src/web/auth/index.test.ts@@ -1,3 +1,4 @@+import rawContractInput0 from "../public/alook.svg?raw"import { createHash } from "node:crypto";import { readFileSync } from "node:fs";import { describe, expect, it, vi } from "vitest";@@ -15,10 +16,7 @@ import handler, {const ATTEMPT = "attempt_1234567890123456";const CODE = "c".repeat(32);-const CANONICAL_LOGO = readFileSync(- new URL("../public/alook.svg", import.meta.url),- "utf8",-).trim();+const CANONICAL_LOGO = rawContractInput0.trim();const DM_SANS_WOFF2 = readFileSync(new URL("../src/app/fonts/dm-sans-latin.woff2", import.meta.url),).toString("base64");diff --git a/src/web/auth/vitest.config.ts b/src/web/auth/vitest.config.tsindex 80a895e10..d78b996f8 100644--- a/src/web/auth/vitest.config.ts+++ b/src/web/auth/vitest.config.ts@@ -7,6 +7,6 @@ export default mergeConfig(shared, defineConfig({name: "auth-node",include: ["**/*.test.ts"],exclude: ["test-runtime/**"],- sequence: { groupOrder: 2 },+ sequence: { groupOrder: 1 },},}));diff --git a/src/web/auth/wrangler.test.ts b/src/web/auth/wrangler.test.tsindex 47c2f40c3..feecb219f 100644--- a/src/web/auth/wrangler.test.ts+++ b/src/web/auth/wrangler.test.ts@@ -1,8 +1,8 @@-import { readFileSync } from "node:fs";+import rawContractInput0 from "./wrangler.toml?raw"import { describe, expect, it } from "vitest";import authVitestConfig from "./vitest.config";-const config = readFileSync(new URL("./wrangler.toml", import.meta.url), "utf8");+const config = rawContractInput0;describe("alook-auth Wrangler contract", () => {it("keeps the standalone node test project isolated from runtime tests", () => {@@ -12,7 +12,6 @@ describe("alook-auth Wrangler contract", () => {name: "auth-node",include: ["**/*.test.ts"],exclude: ["test-runtime/**"],- sequence: { groupOrder: 2 },},});});diff --git a/src/web/blog/custom-worker.test.ts b/src/web/blog/custom-worker.test.tsindex 06403236d..f46c25bbf 100644--- a/src/web/blog/custom-worker.test.ts+++ b/src/web/blog/custom-worker.test.ts@@ -14,7 +14,7 @@ vi.mock("cloudflare:workers", () => ({},}));-vi.mock("./.open-next/worker.js", () => ({+vi.mock("#blog-open-next-worker", () => ({default: { fetch: mocks.openNextFetch },}));diff --git a/src/web/blog/custom-worker.ts b/src/web/blog/custom-worker.tsindex 43aaf1e1c..4406cb341 100644--- a/src/web/blog/custom-worker.ts+++ b/src/web/blog/custom-worker.ts@@ -2,7 +2,7 @@ import { WorkerEntrypoint } from "cloudflare:workers";import { parseBlogDiscoveryManifest, type BlogDiscoveryManifestV1 } from "@/lib/blog-discovery-manifest";import { finalizePublicWorkerResponse } from "@/lib/public-worker-response";-import openNextHandler from "./.open-next/worker.js";+import openNextHandler from "#blog-open-next-worker";const MANIFEST_PATH = "/internal/blog-discovery";diff --git a/src/web/blog/mdx-options.ts b/src/web/blog/mdx-options.tsnew file mode 100644index 000000000..5edaf7ead--- /dev/null+++ b/src/web/blog/mdx-options.ts@@ -0,0 +1,15 @@+import path from "node:path";++export const blogMdxOptions: {+ remarkPlugins: string[]+ rehypePlugins: Array<string | [string, ...unknown[]]>+} = {+ remarkPlugins: ["remark-gfm"],+ rehypePlugins: [+ path.resolve(import.meta.dirname, "rehype-blog-images.mjs"),+ "rehype-slug",+ ["rehype-autolink-headings", { behavior: "wrap" }],+ ["rehype-external-links", { target: "_blank", rel: ["noopener", "noreferrer"] }],+ ["rehype-pretty-code", { theme: { light: "vitesse-light", dark: "vitesse-dark" }, keepBackground: false }],+ ],+};diff --git a/src/web/blog/next.config.ts b/src/web/blog/next.config.tsindex 7a71fca0c..8c87a80d6 100644--- a/src/web/blog/next.config.ts+++ b/src/web/blog/next.config.ts@@ -5,6 +5,8 @@ import { readFileSync } from "node:fs";import path from "node:path";import { createRequire } from "node:module";+const { blogMdxOptions } = createRequire(path.resolve(__dirname, "next.config.ts"))("./mdx-options.ts") as typeof import("./mdx-options");+const blogRedirectRules = JSON.parse(readFileSync(path.resolve(__dirname, "src/lib/blog/redirects.json"), "utf8"),) as Array<{ source: string; destination: string; statusCode: 301 }>;@@ -29,18 +31,7 @@ const nextConfig: NextConfig = {},};-const withMDX = createMDX({- options: {- remarkPlugins: ["remark-gfm"],- rehypePlugins: [- path.resolve(__dirname, "rehype-blog-images.mjs"),- "rehype-slug",- ["rehype-autolink-headings", { behavior: "wrap" }],- ["rehype-external-links", { target: "_blank", rel: ["noopener", "noreferrer"] }],- ["rehype-pretty-code", { theme: { light: "vitesse-light", dark: "vitesse-dark" }, keepBackground: false }],- ],- },-});+const withMDX = createMDX({ options: blogMdxOptions });export default async function blogConfig() {const { prepareBlogImages } = createRequire(path.resolve(__dirname, "next.config.ts"))("./scripts/prepare-images.mjs");diff --git a/src/web/blog/open-next-worker.d.ts b/src/web/blog/open-next-worker.d.tsindex c0b061f62..8d72995ec 100644--- a/src/web/blog/open-next-worker.d.ts+++ b/src/web/blog/open-next-worker.d.ts@@ -1,11 +1,3 @@-declare module "*/.open-next/worker.js" {- const handler: {- fetch(- request: Request,- env: BlogCloudflareEnv,- ctx: ExecutionContext,- ): Response | Promise<Response>;- };-- export default handler;-}+import type { OpenNextWorkerHandler } from "../open-next-handler"+declare const handler: OpenNextWorkerHandler<BlogCloudflareEnv>+export default handlerdiff --git a/src/web/blog/open-next.config.test.ts b/src/web/blog/open-next.config.test.tsindex a0e5d40be..a1ef339ca 100644--- a/src/web/blog/open-next.config.test.ts+++ b/src/web/blog/open-next.config.test.ts@@ -1,13 +1,24 @@+import { execFileSync } from "node:child_process";+import { createRequire } from "node:module";+import { resolve, relative } from "node:path";+import { pathToFileURL } from "node:url";import { describe, expect, it } from "vitest";import config from "./open-next.config";import staticAssetsIncrementalCache from "@opennextjs/cloudflare/overrides/incremental-cache/static-assets-incremental-cache";describe("Blog OpenNext configuration", () => {it("builds the nested app without mutable cache bindings", async () => {- expect(config.appPath).toBe("blog");- expect(config.buildOutputPath).toBe("blog");- expect(config.packageJsonPath).toBe("blog");- expect(config.buildCommand).toBe("pnpm --dir .. build:blog:next");+ const web = resolve(import.meta.dirname, "..");+ const fromWeb = createRequire(resolve(web, "package.json"));+ const fromCloudflare = createRequire(fromWeb.resolve("@opennextjs/cloudflare"));+ const helper = pathToFileURL(fromCloudflare.resolve("@opennextjs/aws/build/helper.js")).href;+ const selected = { appPath: config.appPath, buildOutputPath: config.buildOutputPath, packageJsonPath: config.packageJsonPath };+ const script = `import { normalizeOptions } from ${JSON.stringify(helper)}; const result = normalizeOptions(${JSON.stringify(selected)}, ".", "."); console.log(JSON.stringify({ app: result.appPath, output: result.appBuildOutputPath, package: result.appPackageJsonPath }));`;+ const output = execFileSync(process.execPath, ["--input-type=module", "--eval", script], { cwd: web, encoding: "utf8" });+ const resolved = JSON.parse(output.trim().split("\n").at(-1)!);+ expect(relative(web, resolved.app)).toBe("blog");+ expect(relative(web, resolved.output)).toBe("blog");+ expect(relative(web, resolved.package)).toBe("package.json");expect(config.dangerous?.disableIncrementalCache).not.toBe(true);expect(config.dangerous?.enableCacheInterception).toBe(true);expect(config.dangerous?.disableTagCache).toBe(true);diff --git a/src/web/blog/open-next.config.ts b/src/web/blog/open-next.config.tsindex f919b0613..80b0adfdb 100644--- a/src/web/blog/open-next.config.ts+++ b/src/web/blog/open-next.config.ts@@ -15,8 +15,8 @@ export default {...cloudflare,appPath: "blog",buildOutputPath: "blog",- packageJsonPath: "blog",- buildCommand: "pnpm --dir .. build:blog:next",+ packageJsonPath: ".",+ buildCommand: "pnpm build:blog:next",dangerous: {...cloudflare.dangerous,disableTagCache: true,diff --git a/src/web/blog/scripts/stage-shared-assets.test.ts b/src/web/blog/scripts/stage-shared-assets.test.tsindex 27beb2f1c..4da1ccbc7 100644--- a/src/web/blog/scripts/stage-shared-assets.test.ts+++ b/src/web/blog/scripts/stage-shared-assets.test.ts@@ -1,12 +1,15 @@-import { mkdtempSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, existsSync, symlinkSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join } from "node:path";-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it } from "vitest";import { sharedBlogAssets, stageSharedBlogAssets } from "./stage-shared-assets";+const roots: string[] = [];+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });+describe("stageSharedBlogAssets", () => {it("copies every canonical asset byte-for-byte", () => {- const root = mkdtempSync(join(tmpdir(), "alook-blog-assets-"));+ const root = mkdtempSync(join(tmpdir(), "alook-blog-assets-")); roots.push(root);for (const [index, asset] of sharedBlogAssets.entries()) {const source = join(root, asset.source);mkdirSync(dirname(source), { recursive: true });@@ -20,12 +23,14 @@ describe("stageSharedBlogAssets", () => {expect(readFileSync(join(root, asset.destination))).toEqual(readFileSync(join(root, asset.source)));}- expect(readFileSync(join(root, "blog/package.json"), "utf8"))- .toBe('{"name":"@alook/web"}');+ expect(existsSync(join(root, "blog/package.json"))).toBe(false);+ symlinkSync("../package.json", join(root, "blog/package.json"), "file");+ stageSharedBlogAssets(root);+ expect(existsSync(join(root, "blog/package.json"))).toBe(false);});- it("rejects a nested package manifest that is not the canonical Web manifest", () => {- const root = mkdtempSync(join(tmpdir(), "alook-blog-assets-mismatch-"));+ it("preserves and rejects an unknown nested package manifest", () => {+ const root = mkdtempSync(join(tmpdir(), "alook-blog-assets-mismatch-")); roots.push(root);for (const [index, asset] of sharedBlogAssets.entries()) {const source = join(root, asset.source);mkdirSync(dirname(source), { recursive: true });@@ -35,6 +40,6 @@ describe("stageSharedBlogAssets", () => {writeFileSync(join(root, "package.json"), '{"name":"@alook/web"}');writeFileSync(join(root, "blog/package.json"), '{"name":"wrong"}');- expect(() => stageSharedBlogAssets(root)).toThrow("Nested Blog package pointer differs");+ expect(() => stageSharedBlogAssets(root)).toThrow("Unexpected nested Blog package manifest");});});diff --git a/src/web/blog/scripts/stage-shared-assets.ts b/src/web/blog/scripts/stage-shared-assets.tsindex 168d5c5fb..6c4e87c56 100644--- a/src/web/blog/scripts/stage-shared-assets.ts+++ b/src/web/blog/scripts/stage-shared-assets.ts@@ -1,4 +1,4 @@-import { copyFileSync, existsSync, mkdirSync, readFileSync, symlinkSync } from "node:fs";+import { copyFileSync, mkdirSync, readFileSync, lstatSync, readlinkSync, unlinkSync } from "node:fs";import { dirname, resolve } from "node:path";import { fileURLToPath } from "node:url";import sharedBuildInputs from "../shared-build-inputs.json";@@ -17,13 +17,13 @@ export function stageSharedBlogAssets(webRoot: string): void {}}- const packageManifest = resolve(webRoot, "package.json");const nestedPackageManifest = resolve(webRoot, "blog/package.json");- if (!existsSync(nestedPackageManifest)) {- symlinkSync("../package.json", nestedPackageManifest, "file");- }- if (!readFileSync(packageManifest).equals(readFileSync(nestedPackageManifest))) {- throw new Error("Nested Blog package pointer differs from the canonical Web package manifest");+ const nestedPackage = lstatSync(nestedPackageManifest, { throwIfNoEntry: false });+ if (nestedPackage) {+ if (!nestedPackage.isSymbolicLink() || readlinkSync(nestedPackageManifest) !== "../package.json") {+ throw new Error("Unexpected nested Blog package manifest");+ }+ unlinkSync(nestedPackageManifest);}}diff --git a/src/web/blog/src/content/alook-vs-buzz.test.ts b/src/web/blog/src/content/alook-vs-buzz.test.tsindex eaedcd210..5aaa302d1 100644--- a/src/web/blog/src/content/alook-vs-buzz.test.ts+++ b/src/web/blog/src/content/alook-vs-buzz.test.ts@@ -1,7 +1,7 @@-import { readFileSync } from "node:fs";+import rawContractInput0 from "./alook-vs-buzz.mdx?raw"import { describe, expect, it } from "vitest";-const article = readFileSync(new URL("./alook-vs-buzz.mdx", import.meta.url), "utf8");+const article = rawContractInput0;function faqPairs() {const [schema, body] = article.split("\n];\n\n", 2);diff --git a/src/web/blog/src/lib/public-page-metadata.test.ts b/src/web/blog/src/lib/public-page-metadata.test.tsnew file mode 100644index 000000000..ac36141d8--- /dev/null+++ b/src/web/blog/src/lib/public-page-metadata.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it, vi } from "vitest";+import { SITE_OG_IMAGE, SITE_OG_IMAGE_URL } from "@/lib/seo/site-metadata";++vi.mock("@/lib/observability/regions", () => ({ ObservedStaticContent: () => null }));+vi.mock("@blog/lib/blog/posts", () => ({ getAllPosts: vi.fn() }));+vi.mock("@blog/app/blog/(index)/recent-posts", () => ({ RecentPosts: () => null }));++import { metadata as blog } from "@blog/app/blog/(index)/page";+import { metadata as guides } from "@blog/app/guides/page";+import { metadata as tutorials } from "@blog/app/tutorials/page";++const pages = [+ ["blog", blog, "https://alook.ai/blog", "Blog — AI Agent Collaboration & Workflows — Alook"],+ ["tutorials", tutorials, "https://alook.ai/tutorials", "Tutorials — Alook"],+ ["guides", guides, "https://alook.ai/guides", "Guides — Coding Agent Collaboration — Alook"],+] as const;++describe("Blog public page metadata", () => {+ it.each(pages)("keeps %s search and sharing metadata aligned", (_name, metadata, url, title) => {+ expect(metadata.title).toEqual({ absolute: title });+ expect(metadata.description).toEqual(expect.any(String));+ expect(metadata.description!.length).toBeGreaterThan(50);+ expect(metadata.alternates?.canonical).toBe(url);+ expect(metadata.openGraph).toEqual({+ type: "website",+ siteName: "Alook",+ title,+ description: metadata.description,+ url,+ images: [SITE_OG_IMAGE],+ });+ expect(metadata.twitter).toEqual({+ card: "summary_large_image",+ site: "@alook_ai",+ title,+ description: metadata.description,+ images: [SITE_OG_IMAGE_URL],+ });+ });+++ it("preserves Blog discovery links", () => {+ expect(blog.alternates?.types).toEqual({+ "application/rss+xml": "/blog/feed.xml",+ "text/markdown": "/llms.txt",+ });+ });+});diff --git a/src/web/blog/tsconfig.json b/src/web/blog/tsconfig.jsonindex e8e6aace2..e668bd721 100644--- a/src/web/blog/tsconfig.json+++ b/src/web/blog/tsconfig.json@@ -1,21 +1,37 @@{- "extends": "../tsconfig.json",- "compilerOptions": {- "paths": {- "@/*": ["../src/*"],- "@blog/*": ["./src/*"]- },- "plugins": [{ "name": "next" }],- "tsBuildInfoFile": "./.next/cache/tsconfig.tsbuildinfo",- "types": ["./cloudflare-env.d.ts", "node"]- },- "include": [- "next-env.d.ts",- "**/*.ts",- "**/*.tsx",- "**/*.mdx",- ".next/types/**/*.ts",- ".next/dev/types/**/*.ts"- ],- "exclude": ["../node_modules", "**/*.test.ts", "**/*.test.tsx"]+ "extends": "../tsconfig.json",+ "compilerOptions": {+ "paths": {+ "@/*": [+ "../src/*"+ ],+ "@blog/*": [+ "./src/*"+ ]+ },+ "plugins": [+ {+ "name": "next"+ }+ ],+ "tsBuildInfoFile": "./.next/cache/tsconfig.tsbuildinfo",+ "types": [+ "./cloudflare-env.d.ts",+ "node"+ ]+ },+ "include": [+ "next-env.d.ts",+ "**/*.ts",+ "**/*.tsx",+ "**/*.mdx",+ ".next/types/**/*.ts",+ ".next/dev/types/**/*.ts",+ "../src/raw.d.ts"+ ],+ "exclude": [+ "../node_modules",+ "**/*.test.ts",+ "**/*.test.tsx"+ ]}diff --git a/src/web/blog/vitest.config.mts b/src/web/blog/vitest.config.mtsnew file mode 100644index 000000000..d3ff2f976--- /dev/null+++ b/src/web/blog/vitest.config.mts@@ -0,0 +1,10 @@+import { defineConfig, mergeConfig } from "vitest/config"+import { blogTestConfig } from "./vitest.shared.mjs"++export default defineConfig(async () => mergeConfig(await blogTestConfig(), defineConfig({+ test: {+ name: "blog-node",+ include: ["**/*.test.ts"],+ exclude: ["**/*.dom.test.{ts,tsx}", "node_modules/**", ".next/**", ".open-next/**"],+ },+})))diff --git a/src/web/blog/vitest.dom.config.mts b/src/web/blog/vitest.dom.config.mtsnew file mode 100644index 000000000..f24beeceb--- /dev/null+++ b/src/web/blog/vitest.dom.config.mts@@ -0,0 +1,12 @@+import path from "node:path"+import { defineConfig, mergeConfig } from "vitest/config"+import { blogTestConfig } from "./vitest.shared.mjs"++export default defineConfig(async () => mergeConfig(await blogTestConfig(), defineConfig({+ test: {+ name: "blog-dom",+ environment: "jsdom",+ include: ["**/*.dom.test.{ts,tsx}"],+ setupFiles: [path.resolve(import.meta.dirname, "../src/test/react-dom-setup.ts")],+ },+})))diff --git a/src/web/blog/vitest.shared.mts b/src/web/blog/vitest.shared.mtsnew file mode 100644index 000000000..d81049d75--- /dev/null+++ b/src/web/blog/vitest.shared.mts@@ -0,0 +1,40 @@+import path from "node:path"+import mdx from "@mdx-js/rollup"+import { defineConfig, mergeConfig } from "vitest/config"+import shared from "../../../vitest.shared"+import { blogMdxOptions } from "./mdx-options"++async function plugins(entries: (string | [string, ...unknown[]])[]) {+ return Promise.all(entries.map(async (entry) => {+ const [specifier, ...options] = typeof entry === "string" ? [entry] : entry+ const { default: plugin } = await import(String(specifier))+ return options.length ? [plugin, ...options] : plugin+ }))+}++export async function blogTestConfig() {+ const compiler = mdx({+ ...blogMdxOptions,+ remarkPlugins: await plugins(blogMdxOptions.remarkPlugins),+ rehypePlugins: await plugins(blogMdxOptions.rehypePlugins),+ })+ return mergeConfig(shared, defineConfig({+ root: import.meta.dirname,+ resolve: {+ alias: {+ "@": path.resolve(import.meta.dirname, "../src"),+ "@blog": path.resolve(import.meta.dirname, "src"),+ "#blog-open-next-worker": path.resolve(import.meta.dirname, "../src/test-runtime/open-next-node-stub.ts"),+ "./.open-next/server-functions/default/src/web/.next/required-server-files.json": path.resolve(import.meta.dirname, "../test-runtime/next-config-stub.json"),+ },+ },+ plugins: [{+ ...compiler,+ transform: {+ filter: { id: { exclude: /[?&]raw(?:[&=]|$)/ } },+ handler: compiler.transform,+ },+ }],+ test: { testTimeout: 30_000, hookTimeout: 30_000 },+ }))+}diff --git a/src/web/blog/vitest.workspace.config.ts b/src/web/blog/vitest.workspace.config.tsnew file mode 100644index 000000000..5ab405134--- /dev/null+++ b/src/web/blog/vitest.workspace.config.ts@@ -0,0 +1,11 @@+import { defineConfig } from "vitest/config"++export default defineConfig({+ root: import.meta.dirname,+ test: {+ projects: [+ "./vitest.config.mts",+ "./vitest.dom.config.mts"+ ],+ },+})diff --git a/src/web/custom-worker.ts b/src/web/custom-worker.tsindex e14e4c774..c9ab740ae 100644--- a/src/web/custom-worker.ts+++ b/src/web/custom-worker.ts@@ -1,19 +1,15 @@-// The import below is generated by `opennextjs-cloudflare build` and doesn't-// exist at typecheck time. The build step creates it before wrangler bundles.-// @ts-ignore — generated at build time, may not exist yet-import openNextHandler from "./.open-next/worker.js"+import openNextHandler from "#open-next-worker"import { createWebWorkerHandler } from "./src/lib/worker-runtime"import type { NextConfig } from "next"import { resolveObservationLabels } from "./src/lib/observability/build"// @ts-ignore — generated by Next build before the Worker bundleimport requiredServerFiles from "./.open-next/server-functions/default/src/web/.next/required-server-files.json"-// @ts-ignore — generated at build time, may not exist yet-export { DOQueueHandler } from "./.open-next/worker.js"+export { DOQueueHandler } from "#open-next-worker"const buildEnv = (requiredServerFiles as { config: Pick<NextConfig, "env"> }).config.envconst build = resolveObservationLabels({ release: buildEnv?.NEXT_PUBLIC_FARO_RELEASE, environment: buildEnv?.NEXT_PUBLIC_FARO_ENVIRONMENT })-const webHandler = createWebWorkerHandler(openNextHandler as ExportedHandler<CloudflareEnv>, build)+const webHandler = createWebWorkerHandler(openNextHandler, build)export default {...webHandler,async scheduled(_event: ScheduledController, env: CloudflareEnv, ctx: ExecutionContext) {diff --git a/src/web/knip.json b/src/web/knip.jsonindex f517bc5fd..c5c8159c7 100644--- a/src/web/knip.json+++ b/src/web/knip.json@@ -30,9 +30,20 @@"app-store-capture/next.config.ts","app-store-capture/postcss.config.mjs","app-store-capture/app/**/page.tsx",- "app-store-capture/app/layout.tsx"+ "app-store-capture/app/layout.tsx",+ "blog/vitest.config.mts",+ "blog/vitest.dom.config.mts"+ ],+ "project": [+ "src/**/*.{ts,tsx,css,mdx}",+ "blog/**/*.{ts,tsx,mts,css,mdx}",+ "auth/**/*.{ts,tsx,mts}",+ "scripts/**/*.{ts,mjs}",+ "test-runtime/**/*.ts",+ "app-store-capture/**/*.{ts,tsx,mjs,css}",+ "!app-store-capture/.next/**",+ "!app-store-capture/next-env.d.ts"],- "project": ["src/**/*.{ts,tsx,css,mdx}", "blog/**/*.{ts,tsx,css,mdx}", "auth/**/*.{ts,tsx,mts}", "scripts/**/*.{ts,mjs}", "test-runtime/**/*.ts", "app-store-capture/**/*.{ts,tsx,mjs,css}", "!app-store-capture/.next/**", "!app-store-capture/next-env.d.ts"],"ignoreDependencies": ["cloudflare","rehype-autolink-headings",@@ -45,9 +56,18 @@"src/components/ui/**"],"vitest": {- "entry": ["src/**/*.test.{ts,tsx}", "blog/**/*.test.{ts,tsx}", "auth/**/*.test.ts", "scripts/**/*.test.ts", "src/test/**/*.{ts,tsx}", "test-runtime/**/*.test.ts"]+ "entry": [+ "src/**/*.test.{ts,tsx}",+ "blog/**/*.test.{ts,tsx}",+ "auth/**/*.test.ts",+ "scripts/**/*.test.ts",+ "src/test/**/*.{ts,tsx}",+ "test-runtime/**/*.test.ts"+ ]},"eslint": {- "entry": ["eslint.config.mjs"]+ "entry": [+ "eslint.config.mjs"+ ]}}diff --git a/src/web/open-next-handler.d.ts b/src/web/open-next-handler.d.tsnew file mode 100644index 000000000..3b014182c--- /dev/null+++ b/src/web/open-next-handler.d.ts@@ -0,0 +1,3 @@+export interface OpenNextWorkerHandler<Env> {+ fetch(request: Request, env: Env, ctx: ExecutionContext): Response | Promise<Response>+}diff --git a/src/web/open-next-worker.d.ts b/src/web/open-next-worker.d.tsnew file mode 100644index 000000000..c1a250548--- /dev/null+++ b/src/web/open-next-worker.d.ts@@ -0,0 +1,4 @@+import type { OpenNextWorkerHandler } from "./open-next-handler"+export { DOQueueHandler } from "@opennextjs/cloudflare/durable-objects/queue"+declare const handler: OpenNextWorkerHandler<CloudflareEnv>+export default handlerdiff --git a/src/web/open-next.config.ts b/src/web/open-next.config.tsindex ffcee6c81..befeaeaa0 100644--- a/src/web/open-next.config.ts+++ b/src/web/open-next.config.ts@@ -1,10 +1,15 @@-import { defineCloudflareConfig } from "@opennextjs/cloudflare";+import { defineCloudflareConfig, type OpenNextConfig } from "@opennextjs/cloudflare";import r2IncrementalCache from "@opennextjs/cloudflare/overrides/incremental-cache/r2-incremental-cache";import { withRegionalCache } from "@opennextjs/cloudflare/overrides/incremental-cache/regional-cache";import doQueue from "@opennextjs/cloudflare/overrides/queue/do-queue";-export default defineCloudflareConfig({+const cloudflare = defineCloudflareConfig({incrementalCache: withRegionalCache(r2IncrementalCache, { mode: "long-lived" }),queue: doQueue,enableCacheInterception: true,});++export default {+ ...cloudflare,+ buildCommand: "pnpm build:next",+} satisfies OpenNextConfig;diff --git a/src/web/package.json b/src/web/package.jsonindex 9948a7b86..85c9d08c9 100644--- a/src/web/package.json+++ b/src/web/package.json@@ -8,16 +8,16 @@"dev:blog": "node ../../scripts/dev-with-wrangler-registry.mjs ../../.wrangler/registry next dev blog --hostname 127.0.0.1 --port 3002","dev:auth": "wrangler dev --config auth/wrangler.toml","dev:zones:worker": "node scripts/dev-zones.mjs --worker",- "build": "next build && NODE_ENV=production tsx scripts/stage-service-worker.ts",+ "build": "opennextjs-cloudflare build","build:blog:next": "pnpm validate:blog && tsx blog/scripts/stage-shared-assets.ts && next build blog && tsx blog/scripts/validate-rendered.ts && tsx blog/scripts/prepare-open-next-standalone.ts",- "build:blog": "tsx blog/scripts/stage-shared-assets.ts && opennextjs-cloudflare build --config blog/wrangler.toml --openNextConfigPath blog/open-next.config.ts && tsx blog/scripts/stage-cache-assets.ts",+ "build:blog": "opennextjs-cloudflare build --config blog/wrangler.toml --openNextConfigPath blog/open-next.config.ts && tsx blog/scripts/stage-cache-assets.ts","build:auth": "wrangler deploy --dry-run --config auth/wrangler.toml --outdir dist","validate:blog": "tsx blog/scripts/validate-blog-assets.ts","verify:blog-dry-run": "tsx scripts/verify-blog-dry-run.ts","verify:zone-output": "tsx scripts/verify-zone-output.ts","preflight:bug-reports": "tsx scripts/preflight-bug-reports.ts","start": "next start",- "lint": "node --max-old-space-size=8192 node_modules/eslint/bin/eslint.js src/ blog/ auth/ scripts/ app-store-capture/",+ "lint": "node --max-old-space-size=8192 node_modules/eslint/bin/eslint.js src/ scripts/ readme-capture/ app-store-capture/","deploy": "opennextjs-cloudflare build && opennextjs-cloudflare deploy","deploy:blog": "pnpm build:blog && opennextjs-cloudflare deploy --config blog/wrangler.toml","deploy:auth": "wrangler deploy --config auth/wrangler.toml",@@ -34,8 +34,19 @@"knip": "knip","seed:stress": "tsx scripts/seed-stress.ts","perf:switch": "tsx scripts/perf-report.ts --clear && playwright test --config playwright.perf.config.ts && tsx scripts/perf-report.ts",- "typecheck": "tsc --noEmit && tsc --noEmit -p blog/tsconfig.json && tsc --noEmit -p auth/tsconfig.json",- "seo:check": "lhci autorun --config=lighthouserc.json && node scripts/print-lighthouse-scores.mjs"+ "typecheck": "tsc --noEmit",+ "seo:check": "lhci autorun --config=lighthouserc.json && node scripts/print-lighthouse-scores.mjs",+ "test:blog": "vitest run --config blog/vitest.workspace.config.ts",+ "test:auth": "vitest run --config auth/vitest.config.ts",+ "typecheck:blog": "tsc --noEmit -p blog/tsconfig.json",+ "typecheck:auth": "tsc --noEmit -p auth/tsconfig.json",+ "lint:blog": "node --max-old-space-size=8192 node_modules/eslint/bin/eslint.js blog/",+ "lint:auth": "node --max-old-space-size=8192 node_modules/eslint/bin/eslint.js auth/",+ "test:runtime": "vitest run --config vitest.runtime.config.mts",+ "test:auth:runtime": "vitest run --config auth/vitest.runtime.config.mts",+ "test:contracts": "vitest run --config vitest.contracts.config.ts",+ "test:tooling": "vitest run --config vitest.tooling.config.ts",+ "build:next": "next build && NODE_ENV=production tsx scripts/stage-service-worker.ts"},"dependencies": {"@alook/shared": "workspace:*",@@ -168,7 +179,18 @@"tsx": "^4.23.15","typescript": "^6.0.3","typescript-eslint": "8.72.0",- "vitest": "4.1.12",- "wrangler": "4.152.0"+ "vitest": "5.1.0",+ "wrangler": "4.152.0",+ "@mdx-js/rollup": "3.1.1"+ },+ "imports": {+ "#open-next-worker": {+ "types": "./open-next-worker.d.ts",+ "default": "./.open-next/worker.js"+ },+ "#blog-open-next-worker": {+ "types": "./blog/open-next-worker.d.ts",+ "default": "./blog/.open-next/worker.js"+ }}}diff --git a/src/web/playwright.config.ts b/src/web/playwright.config.tsindex 54b8cc25f..21766056b 100644--- a/src/web/playwright.config.ts+++ b/src/web/playwright.config.ts@@ -7,8 +7,6 @@ export default defineConfig({testMatch: "**/*.spec.ts",fullyParallel: false,forbidOnly: !!process.env.CI,- // The suite shares and mutates three seeded user accounts, so every run is- // single-worker and zero-retry; parallelism or retries would reuse state.retries: 0,workers: 1,reporter: process.env.CI ? [["blob"], ["github"], ["list"]] : "list",diff --git a/src/web/scripts/dev-zones.mjs b/src/web/scripts/dev-zones.mjsindex f37c8420d..6bfaca734 100644--- a/src/web/scripts/dev-zones.mjs+++ b/src/web/scripts/dev-zones.mjs@@ -21,6 +21,8 @@ import {const packageManagerCli = process.env.npm_execpathconst workerMode = process.argv.includes("--worker")const withWsDo = process.argv.includes("--with-ws-do")+const webOnly = process.argv.includes("--web-only")+if (webOnly && !workerMode) throw new Error("--web-only requires --worker")const wranglerEntryFlag = process.argv.indexOf("--wrangler-entry")const wranglerEntry = wranglerEntryFlag === -1 ? undefined : process.argv[wranglerEntryFlag + 1]if (!packageManagerCli && !wranglerEntry) throw new Error("npm_execpath is required")@@ -39,6 +41,7 @@ if ((manifestFlag !== -1 || ownerFlag !== -1) && (!manifestPath || !ownerRoot ||throw new Error("Public static phases require their manifest, owner root and exact combined worker mode")}const manifest = manifestPath ? readPublicStaticManifest(manifestPath, ownerRoot) : undefined+if (manifest && webOnly) throw new Error("Public static release phases require both zones")const runtimeRoot = resolve(process.cwd(), "../..")if (manifest) assertPublicStaticWriteSeparation(manifest, [ownerRoot, resolve(runtimeRoot, "src/web/.wrangler/state"), resolve(runtimeRoot, "src/web/.wrangler/state.e2e-backup"), resolve(runtimeRoot, "src/web/blog/.wrangler/state"), resolve(runtimeRoot, "src/web/e2e-service-logs"), resolve(runtimeRoot, ".wrangler/registry")])const phaseGate = manifest ? createPhaseGate() : undefined@@ -191,7 +194,7 @@ const selectedBackends = manifest ? [}),},...phaseWorkerDefinitions(manifest, manifest.defaultRelease, wranglerEntry, runtimeRoot),-] : backends+] : backends.filter(backend => !webOnly || backend.label !== "Blog backend")for (const backend of selectedBackends) {const child = spawnBackend(backend.label, backend.command, backend.args)@@ -334,7 +337,7 @@ for (const signal of ["SIGINT", "SIGTERM"]) {}try {- await Promise.all([waitForPort(3001), waitForPort(3002)])+ await Promise.all([waitForPort(3001), ...(!webOnly ? [waitForPort(3002)] : [])])assertLive()if (manifest) {await waitForHttpOk("http://127.0.0.1:8789/health")diff --git a/src/web/scripts/perf-query-cache.test.ts b/src/web/scripts/perf-query-cache.test.tsindex 0c91671a7..8759eb18a 100644--- a/src/web/scripts/perf-query-cache.test.ts+++ b/src/web/scripts/perf-query-cache.test.ts@@ -1,6 +1,6 @@+import rawContractInput0 from "../src/test/e2e-ui/perf/perf-query-cache.ts?raw"import { IDBFactory } from "fake-indexeddb"import { createStore, get, set } from "idb-keyval"-import { readFileSync } from "node:fs"import { ScriptTarget, ModuleKind, transpileModule } from "typescript"import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { createIdbPersister, PERSIST_BUSTER, PERSIST_CACHE_PREFIX, PERSIST_VERSION } from "../src/lib/query-persister"@@ -52,7 +52,7 @@ describe("perf switch current disk qualification", () => {it("executes the browser-serialized operation against the actual canonical collection rows", async () => {await set(key, JSON.stringify(snapshot()), store)expect(await operatePerfQueryCache(expected)).toBe(true)- const source = readFileSync(new URL("../src/test/e2e-ui/perf/perf-query-cache.ts", import.meta.url), "utf8")+ const source = rawContractInput0const compiled = transpileModule(source, { compilerOptions: { target: ScriptTarget.ESNext, module: ModuleKind.CommonJS } }).outputTextconst exports = {} as { operatePerfQueryCache: typeof operatePerfQueryCache }new Function("exports", compiled)(exports)diff --git a/src/web/scripts/perf-switch.test.ts b/src/web/scripts/perf-switch.test.tsindex f26992bae..e83044d94 100644--- a/src/web/scripts/perf-switch.test.ts+++ b/src/web/scripts/perf-switch.test.ts@@ -1,4 +1,4 @@-import { readFileSync } from "node:fs"+import rawContractInput0 from "../src/test/e2e-ui/perf/switch.perf.ts?raw"import { JSDOM } from "jsdom"import { createSourceFile, isCallExpression, isFunctionDeclaration, isPropertyAccessExpression, isVariableStatement, ModuleKind, ScriptTarget, transpileModule } from "typescript"import { afterEach, expect, it } from "vitest"@@ -6,7 +6,7 @@ import { tid } from "../src/lib/community/testids"type Target = { serverId: string; channelId?: string; messageScrollerId: string }const target: Target = { serverId: "server", channelId: "target", messageScrollerId: tid.messageScroller }-const ast = createSourceFile("switch.perf.ts", readFileSync(new URL("../src/test/e2e-ui/perf/switch.perf.ts", import.meta.url), "utf8"), ScriptTarget.ESNext, true)+const ast = createSourceFile("switch.perf.ts", rawContractInput0, ScriptTarget.ESNext, true)const setupSource = ast.statements.flatMap(s => isVariableStatement(s) ? [...s.declarationList.declarations] : []).find(d => d.name.getText(ast) === "INPAGE_SETUP")!.initializer!.getText(ast)let predicate = ast.statements.find(s => isFunctionDeclaration(s) && s.name?.text === "samplePerfTarget")?.getText(ast)if (!predicate) {diff --git a/src/web/src/app/(auth)/sign-in/social-sign-in.dom.test.ts b/src/web/src/app/(auth)/sign-in/social-sign-in.dom.test.tsindex 4d4bd1b26..7b883a0d7 100644--- a/src/web/src/app/(auth)/sign-in/social-sign-in.dom.test.ts+++ b/src/web/src/app/(auth)/sign-in/social-sign-in.dom.test.ts@@ -1,3 +1,6 @@+import resolvedRawInput0 from "./social-sign-in.tsx?raw"+import resolvedRawInput1 from "./apple-sign-in-artwork.ts?raw"+import staticContractInput0 from "../../globals.css?raw"import { createElement } from "react"import { createHash } from "node:crypto"import { existsSync, readFileSync } from "node:fs"@@ -183,7 +186,7 @@ describe("social sign-in stack and native boundary", () => {})it("keeps every provider on Apple's mandated black-on-light and white-on-dark tokens", () => {- const globalsCss = readFileSync(resolve(webRoot, "src/app/globals.css"), "utf8")+ const globalsCss = staticContractInput0expect(globalsCss).toMatch(/:root\s*\{[^}]*--apple-signin:\s*oklch\(0 0 0\);[^}]*--apple-signin-foreground:\s*oklch\(1 0 0\);/s,)@@ -201,14 +204,8 @@ describe("social sign-in stack and native boundary", () => {}),)- const source = readFileSync(- resolve(webRoot, "src/app/(auth)/sign-in/social-sign-in.tsx"),- "utf8",- )- const artwork = readFileSync(- resolve(webRoot, "src/app/(auth)/sign-in/apple-sign-in-artwork.ts"),- "utf8",- )+ const source = resolvedRawInput0+ const artwork = resolvedRawInput1expect(source).not.toContain("SiApple")expect(source).not.toContain("appleid.cdn-apple.com/appleid/button/logo")expect(artwork).not.toContain("appleid.cdn-apple.com/appleid/button/logo")diff --git a/src/web/src/app/(public-community)/c/invite/[token]/invite-accept-client.test.ts b/src/web/src/app/(public-community)/c/invite/[token]/invite-accept-client.test.tsindex 169fbd6d4..5bc69c578 100644--- a/src/web/src/app/(public-community)/c/invite/[token]/invite-accept-client.test.ts+++ b/src/web/src/app/(public-community)/c/invite/[token]/invite-accept-client.test.ts@@ -1,9 +1,9 @@-import { readFileSync } from "node:fs"+import rawContractInput0 from "./invite-accept-client.tsx?raw"import { describe, expect, it } from "vitest"describe("InviteAcceptClient loading geometry", () => {it("reserves the ready landing title, metadata, CTA, members, and footer stack", () => {- const source = readFileSync(new URL("./invite-accept-client.tsx", import.meta.url), "utf8")+ const source = rawContractInput0expect(source).toContain('className="mt-1 h-10 w-56 rounded"')expect(source).toContain('className="mt-4 flex h-5 items-center gap-1.5"')expect(source).toContain('className="mt-6 h-11 w-full rounded-xl"')diff --git a/src/web/src/app/_og/homepage-social-image.test.ts b/src/web/src/app/_og/homepage-social-image.test.tsindex 0cb4b136b..02c593587 100644--- a/src/web/src/app/_og/homepage-social-image.test.ts+++ b/src/web/src/app/_og/homepage-social-image.test.ts@@ -1,3 +1,4 @@+import rawContractInput0 from "../../../../../README.md?raw"import { existsSync, readFileSync } from "node:fs"import { createHash } from "node:crypto"import sharp from "sharp"@@ -24,7 +25,7 @@ describe("homepage social images", () => {})it("retains the complete current README banner, including its text and paper", async () => {- const readme = readFileSync(new URL("../../../../../README.md", import.meta.url), "utf8")+ const readme = rawContractInput0expect(readme.match(/<img\s+src="([^"]+)"/)?.[1]).toBe("./assets/readme/banner.png")const expected = await sharp(readFileSync(banner)).resize({ width: 1200 })diff --git a/src/web/src/app/_og/render-og-image.test.ts b/src/web/src/app/_og/render-og-image.test.tsindex 62e960279..4f9cee6c0 100644--- a/src/web/src/app/_og/render-og-image.test.ts+++ b/src/web/src/app/_og/render-og-image.test.ts@@ -1,3 +1,4 @@+import rawContractInput0 from "./render-og-image.tsx?raw"import { inflateSync } from "node:zlib"import { readFileSync } from "node:fs"import { beforeEach, describe, expect, it, vi } from "vitest"@@ -258,7 +259,7 @@ function countSmallColorComponents(describe("OG image", () => {it("loads the canonical public assets through the request-scoped ASSETS binding", async () => {- const rendererSource = readFileSync(new URL("./render-og-image.tsx", import.meta.url), "utf8")+ const rendererSource = rawContractInput0expect(officialLogo.byteLength).toBeGreaterThan(1_000)expect(officialFont.byteLength).toBeGreaterThan(30_000)diff --git a/src/web/src/app/api/community/channels/[id]/route.test.ts b/src/web/src/app/api/community/channels/[id]/route.test.tsindex bc3e7ecc6..8bccb937f 100644--- a/src/web/src/app/api/community/channels/[id]/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/route.test.ts@@ -369,13 +369,6 @@ describe("DELETE /channels/[id]", () => {mockGetChannelType.mockResolvedValue("forum")})- it("403 when not canManage", async () => {- mockResolveChannelAccessContext.mockResolvedValue(accessCtx({ canManage: false }))- const res = await DELETE(delReq(), ctx)- expect(res.status).toBe(403)- expect(mockDeleteChannelWithMedia).not.toHaveBeenCalled()- })-it("manager deletes a public channel; fans out server-wide", async () => {mockResolveChannelAccessContext.mockResolvedValue(accessCtx({ role: "admin", canManage: true }))const res = await DELETE(delReq(), ctx)diff --git a/src/web/src/app/api/ws/token/route.session.test.ts b/src/web/src/app/api/ws/token/route.session.test.tsindex 1bba885de..3f6395182 100644--- a/src/web/src/app/api/ws/token/route.session.test.ts+++ b/src/web/src/app/api/ws/token/route.session.test.ts@@ -1,5 +1,6 @@+import rawContractInput0 from "../../../../../migrations/0001_schema.sql?raw"+import rawContractInput1 from "../../../../../migrations/0035_device_code_table.sql?raw"import { createHmac } from "node:crypto"-import { readFileSync } from "node:fs"import { DatabaseSync } from "node:sqlite"import { NextRequest } from "next/server"import { beforeEach, describe, expect, it, vi } from "vitest"@@ -21,8 +22,8 @@ beforeEach(() => {database = new DatabaseSync(":memory:")database.exec(`CREATE TABLE user (id TEXT PRIMARY KEY, name TEXT, email TEXT, emailVerified INTEGER, image TEXT, createdAt INTEGER, updatedAt INTEGER, discriminator TEXT, isBot INTEGER, deletedAt TEXT);CREATE TABLE session (id TEXT PRIMARY KEY, token TEXT, userId TEXT, expiresAt INTEGER, createdAt INTEGER, updatedAt INTEGER, ipAddress TEXT, userAgent TEXT);`)- database.exec(readFileSync(new URL("../../../../../migrations/0001_schema.sql", import.meta.url), "utf8"))- database.exec(readFileSync(new URL("../../../../../migrations/0035_device_code_table.sql", import.meta.url), "utf8"))+ database.exec(rawContractInput0)+ database.exec(rawContractInput1)database.prepare("INSERT INTO user VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run("viewer-192", "Fixture", "[email protected]", 1, null, new Date(now).toISOString(), new Date(now).toISOString(), "0001", 0, null)database.prepare("INSERT INTO session VALUES (?, ?, ?, ?, ?, ?, ?, ?)")diff --git a/src/web/src/app/c/me/[dmId]/page.test.ts b/src/web/src/app/c/me/[dmId]/page.test.tsindex 43353470f..bb6ead8df 100644--- a/src/web/src/app/c/me/[dmId]/page.test.ts+++ b/src/web/src/app/c/me/[dmId]/page.test.ts@@ -1,9 +1,9 @@-import { readFileSync } from "node:fs"+import rawContractInput0 from "../../../../components/community/channels/dm-view.tsx?raw"import { describe, expect, it } from "vitest"describe("DM page loading ownership", () => {it("keeps full-frame and message-body ownership separate", () => {- const source = readFileSync(new URL("../../../../components/community/channels/dm-view.tsx", import.meta.url), "utf8")+ const source = rawContractInput0expect(source).toContain("fullFramePending: !hasDm && dmsLoading")expect(source).toContain("missingPeer: !hasDm && !dmsLoading")expect(source).toContain("messageBodyLoading: hasDm && messagesLoading")@@ -33,13 +33,13 @@ describe("DM page loading ownership", () => {})it("uses the cache-first DM projection as the header and composer identity", () => {- const source = readFileSync(new URL("../../../../components/community/channels/dm-view.tsx", import.meta.url), "utf8")+ const source = rawContractInput0expect(source).toContain("const directoryDm = dms.find(candidate => candidate.id === dmId)")expect(source).not.toContain("profilesByUserId.get(raw.userId)")})it("owns lazy channel-directory state and retry inside the keyed DM view", () => {- const source = readFileSync(new URL("../../../../components/community/channels/dm-view.tsx", import.meta.url), "utf8")+ const source = rawContractInput0expect(source).toContain("export function DmView({ dmId, routeCommitted")expect(source).toContain("useChannelRefDirectory(channelRefDirectoryEnabled)")expect(source).toContain("loading: !channelRefDirectoryResolved")@@ -51,7 +51,7 @@ describe("DM page loading ownership", () => {})it("keeps chip toggle and picker add on separate reaction intents", () => {- const source = readFileSync(new URL("../../../../components/community/channels/dm-view.tsx", import.meta.url), "utf8")+ const source = rawContractInput0expect(source).toContain("const toggleReaction = useToggleReactionApi()")expect(source).toContain("const addReaction = useAddReactionApi()")expect(source).toContain("onToggleReaction: (id: string, emoji: string) =>\n toggleReaction(")diff --git a/src/web/src/app/fonts.test.ts b/src/web/src/app/fonts.test.tsindex 14fd95e13..255365588 100644--- a/src/web/src/app/fonts.test.ts+++ b/src/web/src/app/fonts.test.ts@@ -10,10 +10,11 @@ const { localFont } = vi.hoisted(() => ({vi.mock("next/font/local", () => ({ default: localFont }))-import { caveat, dmMono, dmSans, instrumentSerif, literata, vt323 } from "./fonts"describe("local font configuration", () => {- it("loads every design font from committed assets", () => {+ it("loads every design font from committed assets", async () => {+ vi.resetModules()+ const { caveat, dmMono, dmSans, instrumentSerif, literata, vt323 } = await import("./fonts")expect(localFont.mock.calls.map(([options]) => options)).toEqual([{src: "./fonts/dm-sans-latin.woff2",diff --git a/src/web/src/components/community/bots/bot-activity-modal.dom.test.ts b/src/web/src/components/community/bots/bot-activity-modal.dom.test.tsindex 90517a1ee..2f12ca22e 100644--- a/src/web/src/components/community/bots/bot-activity-modal.dom.test.ts+++ b/src/web/src/components/community/bots/bot-activity-modal.dom.test.ts@@ -1,4 +1,4 @@-import { readFileSync } from "node:fs"+import staticContractInput0 from "./bot-activity-modal.tsx?raw"import { resolve } from "node:path"import React from "react"import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"@@ -307,11 +307,7 @@ describe("BotActivityModal CommunitySheet contract", () => {expect(onOpenChange).toHaveBeenCalledOnce()expect(onOpenChange).toHaveBeenCalledWith(false)- const source = readFileSync(resolve(- process.cwd(),- process.cwd().endsWith("/src/web") ? "" : "src/web",- "src/components/community/bots/bot-activity-modal.tsx",- ), "utf8")+ const source = staticContractInput0expect(source).not.toContain("@/components/ui/dialog")expect(source).not.toContain("@/components/ui/sheet")expect(source).not.toMatch(/>\s*Close\s*</)diff --git a/src/web/src/components/community/bots/bot-list-controller.dom.test.ts b/src/web/src/components/community/bots/bot-list-controller.dom.test.tsindex 2eeb562fb..b4f5e77c9 100644--- a/src/web/src/components/community/bots/bot-list-controller.dom.test.ts+++ b/src/web/src/components/community/bots/bot-list-controller.dom.test.ts@@ -1,3 +1,7 @@+import contractText0 from "./bot-list-controller.ts?raw"+import contractText1 from "./bot-list-machine-group.tsx?raw"+import contractText2 from "./bot-list-overlays.tsx?raw"+import contractText3 from "./bot-list-view.tsx?raw"import React from "react"import { useCommunityNavigationController } from "@/components/community/shell/use-community-navigation-controller"import { CommunityRouteContext } from "@/contexts/community/route-frame"@@ -5,7 +9,6 @@ import { normalizeCommunityHref } from "@/lib/community/community-route"import { CommunityModuleRouteContext } from "@/contexts/community/module-route"import { useQueryClient } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"-import { readFileSync } from "node:fs"import { dirname, resolve } from "node:path"import { fileURLToPath } from "node:url"import { act, fireEvent, waitFor } from "@/test/react-dom-harness"@@ -16,7 +19,16 @@ import type { BotSummary } from "@/hooks/community/use-bots"import type { BotListController } from "./bot-list-types"const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..")-const readWebSource = (path: string) => readFileSync(resolve(webRoot, path), "utf8")+const contractSources: Record<string, string> = {+ "src/components/community/bots/bot-list-controller.ts": contractText0,+ "src/components/community/bots/bot-list-machine-group.tsx": contractText1,+ "src/components/community/bots/bot-list-overlays.tsx": contractText2,+ "src/components/community/bots/bot-list-view.tsx": contractText3,+}+const readWebSource = (path: string) => {+ if (!(path in contractSources)) throw new Error("unregistered contract source: " + path)+ return contractSources[path]+}const mocks = vi.hoisted(() => ({hookOrder: [] as string[],diff --git a/src/web/src/components/community/bots/bot-list-facade.contract.dom.test.ts b/src/web/src/components/community/bots/bot-list-facade.contract.dom.test.tsdeleted file mode 100644index 4c6d6cefa..000000000--- a/src/web/src/components/community/bots/bot-list-facade.contract.dom.test.ts+++ /dev/null@@ -1,84 +0,0 @@-import { readFileSync } from "node:fs"-import { dirname, resolve } from "node:path"-import { fileURLToPath } from "node:url"-import React, { type ComponentProps, type ComponentRef } from "react"-import { beforeEach, describe, expect, expectTypeOf, it, vi } from "vitest"-import { render, screen } from "@/test/react-dom-harness"--const mocks = vi.hoisted(() => ({- controllerValue: { marker: "controller" },- controller: vi.fn(),- view: vi.fn(),-}))--vi.mock("./bot-list-controller", () => ({- useBotListController: () => {- mocks.controller()- return mocks.controllerValue- },-}))-vi.mock("./bot-list-view", () => ({- renderBotListView: (props: unknown, controller: unknown) => {- mocks.view(props, controller)- return React.createElement("div", { "data-testid": "bot-list-view" })- },-}))--import * as facade from "./bot-list"--type ExpectedBotListProps = {- onBack?: () => void-}--const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..")-const source = (path: string) => readFileSync(resolve(webRoot, path), "utf8")--describe("BotList facade contract", () => {- beforeEach(() => vi.clearAllMocks())-- it("keeps the exact public surface and omitted-props default", () => {- expect(Object.keys(facade)).toEqual(["BotList"])- expectTypeOf<ComponentProps<typeof facade.BotList>>().toEqualTypeOf<ExpectedBotListProps>()- expectTypeOf<ExpectedBotListProps>().toEqualTypeOf<ComponentProps<typeof facade.BotList>>()- expectTypeOf<ComponentRef<typeof facade.BotList>>().toEqualTypeOf<never>()-- const text = source("src/components/community/bots/bot-list.tsx")- expect(text).toContain("export function BotList({ onBack }: BotListProps = {})")- expect(text).toContain("const controller = useBotListController()")- expect(text).toContain("return renderBotListView({ onBack }, controller)")- expect(text).not.toMatch(/<BotListView\b|createElement\(BotListView/)- expect(text).not.toMatch(/forwardRef|useImperativeHandle/)- })-- it("invokes the controller and plain view exactly once with omitted props resolved", () => {- const rendered = render(React.createElement(facade.BotList))- expect(screen.getByTestId("bot-list-view")).toBeInTheDocument()- expect(mocks.controller).toHaveBeenCalledOnce()- expect(mocks.view).toHaveBeenCalledOnce()- expect(mocks.view).toHaveBeenCalledWith({ onBack: undefined }, mocks.controllerValue)-- const onBack = vi.fn()- rendered.rerender(React.createElement(facade.BotList, { onBack }))- expect(mocks.controller).toHaveBeenCalledTimes(2)- expect(mocks.view).toHaveBeenLastCalledWith({ onBack }, mocks.controllerValue)- })-- it("keeps the production page and existing regression on the original path", () => {- const page = source("src/components/community/shell/community-module-route.tsx")- const existingTest = source("src/components/community/bots/bot-list-card.dom.test.ts")- const consumer = source("src/components/community/bots/me-bots-route.tsx")- expect(page).toContain('import BotsRoute from "../bots/me-bots-route"')- expect(consumer).toContain('from "@/components/community/bots/bot-list"')- expect(existingTest).toContain('from "./bot-list"')- expect(`${page}\n${existingTest}`).not.toMatch(- /bot-list-(types|controller|view|machine-group|overlays)/,- )- })-- it("keeps all internals private to the bot-list implementation", () => {- const types = source("src/components/community/bots/bot-list-types.ts")- expect(types).not.toMatch(/^export (?:const|function|class|let|var) /m)- expect(source("src/components/community/bots/bot-list-controller.ts"))- .not.toMatch(/from ["']@\/components\/community\//)- })-})diff --git a/src/web/src/components/community/bots/bot-list-facade.contract.test.ts b/src/web/src/components/community/bots/bot-list-facade.contract.test.tsnew file mode 100644index 000000000..5c759632f--- /dev/null+++ b/src/web/src/components/community/bots/bot-list-facade.contract.test.ts@@ -0,0 +1,44 @@+import source0 from "./bot-list-card.dom.test.ts?raw"+import source1 from "./bot-list-controller.ts?raw"+import source2 from "./bot-list-types.ts?raw"+import source3 from "./me-bots-route.tsx?raw"+import source4 from "../shell/community-module-route.tsx?raw"+import { describe, expect, it } from "vitest"+import * as facade from "./bot-list"++const sources: Record<string, string> = {+ "src/components/community/bots/bot-list-card.dom.test.ts": source0,+ "src/components/community/bots/bot-list-controller.ts": source1,+ "src/components/community/bots/bot-list-types.ts": source2,+ "src/components/community/bots/me-bots-route.tsx": source3,+ "src/components/community/shell/community-module-route.tsx": source4,+}+const source = (path: string) => {+ if (!(path in sources)) throw new Error("unregistered contract source: " + path)+ return sources[path]+}++describe("BotList facade contract", () => {+ it("exposes the public component without internal runtime exports", () => {+ expect(Object.keys(facade)).toEqual(["BotList"])+ })++ it("keeps the production page and existing regression on the original path", () => {+ const page = source("src/components/community/shell/community-module-route.tsx")+ const existingTest = source("src/components/community/bots/bot-list-card.dom.test.ts")+ const consumer = source("src/components/community/bots/me-bots-route.tsx")+ expect(page).toContain('import BotsRoute from "../bots/me-bots-route"')+ expect(consumer).toContain('from "@/components/community/bots/bot-list"')+ expect(existingTest).toContain('from "./bot-list"')+ expect(`${page}\n${existingTest}`).not.toMatch(+ /bot-list-(types|controller|view|machine-group|overlays)/,+ )+ })++ it("keeps all internals private to the bot-list implementation", () => {+ const types = source("src/components/community/bots/bot-list-types.ts")+ expect(types).not.toMatch(/^export (?:const|function|class|let|var) /m)+ expect(source("src/components/community/bots/bot-list-controller.ts"))+ .not.toMatch(/from ["']@\/components\/community\//)+ })+})diff --git a/src/web/src/components/community/bots/bot-list-overlays.dom.test.ts b/src/web/src/components/community/bots/bot-list-overlays.dom.test.tsindex a8589eacd..eedcad8c8 100644--- a/src/web/src/components/community/bots/bot-list-overlays.dom.test.ts+++ b/src/web/src/components/community/bots/bot-list-overlays.dom.test.ts@@ -1,5 +1,5 @@+import contractText0 from "./bot-list-overlays.tsx?raw"import React from "react"-import { readFileSync } from "node:fs"import { resolve } from "node:path"import { beforeEach, describe, expect, it, vi } from "vitest"import type { BotListController } from "./bot-list-types"@@ -8,7 +8,13 @@ import { fireEvent, render } from "@/test/react-dom-harness"const webRoot = process.cwd().endsWith("/src/web")? process.cwd(): resolve(process.cwd(), "src/web")-const readWebSource = (path: string) => readFileSync(resolve(webRoot, path), "utf8")+const contractSources: Record<string, string> = {+ "src/components/community/bots/bot-list-overlays.tsx": contractText0,+}+const readWebSource = (path: string) => {+ if (!(path in contractSources)) throw new Error("unregistered contract source: " + path)+ return contractSources[path]+}function host(name: string) {const Host = ({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) =>diff --git a/src/web/src/components/community/bots/bot-select-menu.contract.test.ts b/src/web/src/components/community/bots/bot-select-menu.contract.test.tsindex dbed48780..7ba8ee6ea 100644--- a/src/web/src/components/community/bots/bot-select-menu.contract.test.ts+++ b/src/web/src/components/community/bots/bot-select-menu.contract.test.ts@@ -1,4 +1,5 @@-import { readFileSync } from "node:fs"+import staticContractInput0 from "./model-field.tsx?raw"+import staticContractInput1 from "./reasoning-effort-field.tsx?raw"import { dirname, resolve } from "node:path"import { fileURLToPath } from "node:url"import { describe, expect, it } from "vitest"@@ -6,13 +7,10 @@ import { describe, expect, it } from "vitest"const directory = dirname(fileURLToPath(import.meta.url))describe("bot select menu spacing", () => {- it("gives model and effort menus a shared padded content and row rhythm", () => {- const menuSource = readFileSync(resolve(directory, "bot-select-menu.tsx"), "utf8")- const modelSource = readFileSync(resolve(directory, "model-field.tsx"), "utf8")- const effortSource = readFileSync(resolve(directory, "reasoning-effort-field.tsx"), "utf8")+ it("keeps model and effort menus on the same content and row owners", () => {+ const modelSource = staticContractInput0+ const effortSource = staticContractInput1- expect(menuSource).toContain('cn("p-1.5", className)')- expect(menuSource).toContain('cn("min-h-10 py-2 pr-9 pl-3 leading-snug", className)')expect(modelSource).toContain("<BotSelectMenuContent")expect(modelSource).toContain("<BotSelectMenuItem")expect(effortSource).toContain("<BotSelectMenuContent")diff --git a/src/web/src/components/community/bots/model-field-select.dom.test.tsx b/src/web/src/components/community/bots/model-field-select.dom.test.tsxindex 63e01a728..013d5d4a3 100644--- a/src/web/src/components/community/bots/model-field-select.dom.test.tsx+++ b/src/web/src/components/community/bots/model-field-select.dom.test.tsx@@ -25,6 +25,10 @@ describe("ModelField with the real Select", () => {const view = render(<ModelField runtime={{ ...runtime, id: "opencode" }} value={null} onChange={onChange} menu={{ open: true, container: host }} />);await act(async () => {});expect(host.querySelectorAll('[role="option"]')).toHaveLength(3);+ expect(host.querySelector('[data-slot="select-content"]')).toHaveClass("p-1.5");+ for (const option of host.querySelectorAll('[role="option"]')) {+ expect(option).toHaveClass("min-h-10", "py-2", "pr-9", "pl-3", "leading-snug");+ }expect(host.querySelector('[data-testid="bot-model-filter-input"]')).not.toBe(document.activeElement);expect(onChange).not.toHaveBeenCalled();view.rerender(<ModelField runtime={{ ...runtime, id: "opencode" }} value="gemini-3.1-pro-high" onChange={onChange} menu={{ open: false, container: host }} />);diff --git a/src/web/src/components/community/channels/adaptive-navigation-cutover.contract.test.ts b/src/web/src/components/community/channels/adaptive-navigation-cutover.contract.test.tsindex efc46ace3..1b651c491 100644--- a/src/web/src/components/community/channels/adaptive-navigation-cutover.contract.test.ts+++ b/src/web/src/components/community/channels/adaptive-navigation-cutover.contract.test.ts@@ -1,8 +1,30 @@-import { existsSync, readFileSync } from "node:fs"+import contractText0 from "../../../app/c/[...path]/page.tsx?raw"+import contractText1 from "../messages/message-context-sheet.tsx?raw"+import contractText2 from "../shell/community-module-route.tsx?raw"+import contractText3 from "../shell/community-route-frame.tsx?raw"+import contractText4 from "../shell/server-sidebar-slot.tsx?raw"+import contractText5 from "./channel-sidebar.tsx?raw"+import contractText6 from "./dm-view.tsx?raw"+import contractText7 from "./server-conversation-route.tsx?raw"+import contractText8 from "./thread-channel-surface.tsx?raw"+import { existsSync } from "node:fs"import { describe, expect, it } from "vitest"-const readSource = (relativePath: string) =>- readFileSync(new URL(relativePath, import.meta.url), "utf8")+const contractSources: Record<string, string> = {+ "../../../app/c/[...path]/page.tsx": contractText0,+ "../messages/message-context-sheet.tsx": contractText1,+ "../shell/community-module-route.tsx": contractText2,+ "../shell/community-route-frame.tsx": contractText3,+ "../shell/server-sidebar-slot.tsx": contractText4,+ "./channel-sidebar.tsx": contractText5,+ "./dm-view.tsx": contractText6,+ "./server-conversation-route.tsx": contractText7,+ "./thread-channel-surface.tsx": contractText8,+}+const readSource = (path: string) => {+ if (!(path in contractSources)) throw new Error("unregistered contract source: " + path)+ return contractSources[path]+}describe("adaptive navigation cutover contracts", () => {it("uses the one flat route builder while preserving parent-aware sidebar callbacks", () => {diff --git a/src/web/src/components/community/channels/channel-sidebar.crumb.test.ts b/src/web/src/components/community/channels/channel-sidebar.crumb.test.tsindex b85eee553..95e1c5cf1 100644--- a/src/web/src/components/community/channels/channel-sidebar.crumb.test.ts+++ b/src/web/src/components/community/channels/channel-sidebar.crumb.test.ts@@ -1,5 +1,5 @@+import rawContractInput0 from "../../../app/globals.css?raw"import { describe, it, expect, vi } from "vitest"-import { readFileSync } from "node:fs"import { createElement } from "react"import { renderToStaticMarkup } from "react-dom/server"@@ -116,7 +116,7 @@ describe("ChannelSidebar header", () => {expect(html).toContain("min-h-0 flex-1 overflow-y-auto px-2 py-4 thin-scrollbar scrollbar-none",)- const css = readFileSync(new URL("../../../app/globals.css", import.meta.url), "utf8")+ const css = rawContractInput0expect(css).toContain(".thin-scrollbar.scrollbar-none")expect(css).toContain("scrollbar-width: none")})diff --git a/src/web/src/components/community/channels/forum-child-header.contract.test.ts b/src/web/src/components/community/channels/forum-child-header.contract.test.tsindex 3c22d87dc..e768d8eff 100644--- a/src/web/src/components/community/channels/forum-child-header.contract.test.ts+++ b/src/web/src/components/community/channels/forum-child-header.contract.test.ts@@ -1,3 +1,6 @@+import staticContractInput0 from "./channel-route.tsx?raw"+import staticContractInput1 from "./thread-channel-surface.tsx?raw"+import staticContractInput2 from "./forum-view.tsx?raw"import { describe, expect, it } from "vitest"import fs from "node:fs"import path from "node:path"@@ -7,9 +10,9 @@ const componentDirectory = path.dirname(fileURLToPath(import.meta.url))describe("forum child header wiring", () => {it("keeps opener/list edit affordances absent and limits renaming to ordinary threads", () => {- const route = fs.readFileSync(path.join(componentDirectory, "channel-route.tsx"), "utf8")- const surface = fs.readFileSync(path.join(componentDirectory, "thread-channel-surface.tsx"), "utf8")- const forumView = fs.readFileSync(path.join(componentDirectory, "forum-view.tsx"), "utf8")+ const route = staticContractInput0+ const surface = staticContractInput1+ const forumView = staticContractInput2expect(route).toContain("<ThreadChannelSurface")expect(surface).toContain("parentMessageId && !parentIsForum")diff --git a/src/web/src/components/community/channels/forum-view.test.ts b/src/web/src/components/community/channels/forum-view.test.tsindex 35b974a6b..74bffd31d 100644--- a/src/web/src/components/community/channels/forum-view.test.ts+++ b/src/web/src/components/community/channels/forum-view.test.ts@@ -1,5 +1,5 @@+import rawContractInput0 from "../../../app/globals.css?raw"import { beforeEach, describe, it, expect, vi } from "vitest"-import { readFileSync } from "node:fs"import { createElement } from "react"import { renderToStaticMarkup } from "react-dom/server"import {@@ -459,7 +459,7 @@ describe("ForumView filter bar / composer swap", () => {const html = render([makePost({ tags: ["alpha", "beta", "gamma", "delta"] })])const railIndex = html.indexOf(tid.forumTagScroller)const railMarkup = html.slice(Math.max(0, railIndex - 400), railIndex + 900)- const css = readFileSync(new URL("../../../app/globals.css", import.meta.url), "utf8")+ const css = rawContractInput0expect(railMarkup).toContain("overflow-x-auto")expect(railMarkup).toContain("thin-scrollbar scrollbar-none")diff --git a/src/web/src/components/community/channels/thread-split-view.native.dom.test.tsx b/src/web/src/components/community/channels/thread-split-view.native.dom.test.tsxindex 4f0eda9e7..a383511fc 100644--- a/src/web/src/components/community/channels/thread-split-view.native.dom.test.tsx+++ b/src/web/src/components/community/channels/thread-split-view.native.dom.test.tsx@@ -1,4 +1,4 @@-import { readFileSync } from "node:fs"+import staticContractInput0 from "./thread-split-view.module.css?raw"import { dirname, resolve } from "node:path"import { fileURLToPath } from "node:url"import { createElement, createRef } from "react"@@ -115,7 +115,7 @@ describe("ThreadSplitView actual native persistence", () => {} finally { vi.stubGlobal("window", browser) }const ssr = document.createElement("div")ssr.innerHTML = html- const css = readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), "thread-split-view.module.css"), "utf8")+ const css = staticContractInput0const selectors = [...css.matchAll(/(\.layout\[data-layout-pending\][^{}]+)\{/g)].map(match => match[1].trim().replace(/\.([\w-]+)/g, (_, name: string) => `.${styles[name]}`))expect(selectors.length).toBeGreaterThan(0)diff --git a/src/web/src/components/community/channels/use-channel-tree.dom.test.ts b/src/web/src/components/community/channels/use-channel-tree.dom.test.tsindex 26cd5c8a2..37e1bc973 100644--- a/src/web/src/components/community/channels/use-channel-tree.dom.test.ts+++ b/src/web/src/components/community/channels/use-channel-tree.dom.test.ts@@ -1,5 +1,6 @@+import staticContractInput0 from "./channel-sidebar.tsx?raw"+import staticContractInput1 from "./channel-route.tsx?raw"import { act, renderHook } from "@/test/react-dom-harness"-import { readFileSync } from "node:fs"import { resolve } from "node:path"import { describe, expect, it } from "vitest"import { UNCATEGORIZED_CATEGORY_ID } from "@alook/shared"@@ -112,21 +113,13 @@ describe("canonical channel tree ownership", () => {describe("ChannelSidebar rename ownership", () => {it("submits through the external mutation without eagerly mutating the local tree", () => {- const source = readFileSync(resolve(- process.cwd(),- process.cwd().endsWith("/src/web") ? "" : "src/web",- "src/components/community/channels/channel-sidebar.tsx",- ), "utf8")+ const source = staticContractInput0expect(source).toContain("onCreate={({ name }) => { onRenameChannel?.(dialog.id, name) }}")expect(source).not.toContain("renameChannel(dialog.id, name)")})it("keeps title, same-server refs, and member UI on reconciled server detail", () => {- const source = readFileSync(resolve(- process.cwd(),- process.cwd().endsWith("/src/web") ? "" : "src/web",- "src/components/community/channels/channel-route.tsx",- ), "utf8")+ const source = staticContractInput1expect(source).toContain("topLevelName: channelInServer?.name")expect(source).toContain(".map((channel) => toChannelRefCandidate(currentServer, channel))")expect(source).toContain("useChannelMemberViewModel({")diff --git a/src/web/src/components/community/community-avatar-shape.contract.test.ts b/src/web/src/components/community/community-avatar-shape.contract.test.tsindex 91ac4cfde..9b8538520 100644--- a/src/web/src/components/community/community-avatar-shape.contract.test.ts+++ b/src/web/src/components/community/community-avatar-shape.contract.test.ts@@ -1,11 +1,21 @@-import { readFileSync } from "node:fs"+import contractText0 from "../avatar/bot-avatar-picker-dialog.tsx?raw"+import contractText1 from "./settings/user-settings.tsx?raw"+import contractText2 from "./shell/shell-frame-overlays.tsx?raw"import { dirname, resolve } from "node:path"import { fileURLToPath } from "node:url"import { describe, expect, it } from "vitest"const componentDirectory = dirname(fileURLToPath(import.meta.url))const webRoot = resolve(componentDirectory, "../../..")-const readWeb = (path: string) => readFileSync(resolve(webRoot, path), "utf8")+const contractSources: Record<string, string> = {+ "src/components/avatar/bot-avatar-picker-dialog.tsx": contractText0,+ "src/components/community/settings/user-settings.tsx": contractText1,+ "src/components/community/shell/shell-frame-overlays.tsx": contractText2,+}+const readWeb = (path: string) => {+ if (!(path in contractSources)) throw new Error("unregistered contract source: " + path)+ return contractSources[path]+}describe("community avatar shape contract", () => {it("keeps My Profile preview and crop circular", () => {diff --git a/src/web/src/components/community/machines/guide-me-avatar-motion.dom.test.ts b/src/web/src/components/community/machines/guide-me-avatar-motion.dom.test.tsindex e8eb1ff04..db425ac53 100644--- a/src/web/src/components/community/machines/guide-me-avatar-motion.dom.test.ts+++ b/src/web/src/components/community/machines/guide-me-avatar-motion.dom.test.ts@@ -1,4 +1,4 @@-import { readFileSync } from "node:fs"+import staticContractInput0 from "../../../app/globals.css?raw"import { resolve } from "node:path"import React from "react"import { describe, expect, it, vi } from "vitest"@@ -130,11 +130,7 @@ describe("first-signup guide avatar motion", () => {})it("uses phase easings for the one-shot NPC motion while leaving orbit linear", () => {- const styles = readFileSync(resolve(- process.cwd(),- process.cwd().endsWith("/src/web") ? "" : "src/web",- "src/app/globals.css",- ), "utf8")+ const styles = staticContractInput0expect(styles).toContain("animation: community-guide-me-orbit 4.8s linear infinite;",diff --git a/src/web/src/components/community/members/add-members-dialog.test.ts b/src/web/src/components/community/members/add-members-dialog.test.tsindex 72fa46c17..d9b76aae3 100644--- a/src/web/src/components/community/members/add-members-dialog.test.ts+++ b/src/web/src/components/community/members/add-members-dialog.test.ts@@ -1,7 +1,7 @@+import rawContractInput0 from "./add-members-dialog.tsx?raw"import { describe, it, expect, vi, beforeEach } from "vitest"import { createElement } from "react"import { renderToStaticMarkup } from "react-dom/server"-import { readFileSync } from "node:fs"// Spy on toastApiError so the reject path can be asserted without a real DOM// (sonner injects a <style> at import time). Mock before importing the module.@@ -40,7 +40,7 @@ describe("AddMemberRow", () => {})it("uses the shared resolved/loading/error/retry picker contract", () => {- const source = readFileSync(new URL("./add-members-dialog.tsx", import.meta.url), "utf8")+ const source = rawContractInput0expect(source).toContain("resolved: queryState.resolved")expect(source).toContain("loading: queryState.loading")expect(source).toContain("error: queryState.error")diff --git a/src/web/src/components/community/members/member-list.test.ts b/src/web/src/components/community/members/member-list.test.tsindex d1e8955b2..edd9a40f2 100644--- a/src/web/src/components/community/members/member-list.test.ts+++ b/src/web/src/components/community/members/member-list.test.ts@@ -1,3 +1,4 @@+import resolvedRawInput0 from "./member-list.tsx?raw"import { describe, it, expect } from "vitest"import fs from "node:fs"import path from "node:path"@@ -70,19 +71,13 @@ describe("hasMemberMenu", () => {describe("member action identity contract", () => {it("sends the stable member id, never the display name, to role mutations", () => {- const source = fs.readFileSync(- path.join(path.dirname(fileURLToPath(import.meta.url)), "member-list.tsx"),- "utf8",- )+ const source = resolvedRawInput0expect(source).toContain("onSetRole?.(mem.id, r)")expect(source).not.toContain("onSetRole?.(mem.name, r)")})it("keeps loading inside the real toolbar and scroll ownership", () => {- const source = fs.readFileSync(- path.join(path.dirname(fileURLToPath(import.meta.url)), "member-list.tsx"),- "utf8",- )+ const source = resolvedRawInput0expect(source).toContain("<MemberListSkeleton showSearch={Boolean(onSearch)} showAddMember={Boolean(onAddMember)} />",)diff --git a/src/web/src/components/community/messages/attachment-download-surfaces.contract.test.ts b/src/web/src/components/community/messages/attachment-download-surfaces.contract.test.tsindex 86c4b4a5d..a6561aa00 100644--- a/src/web/src/components/community/messages/attachment-download-surfaces.contract.test.ts+++ b/src/web/src/components/community/messages/attachment-download-surfaces.contract.test.ts@@ -1,10 +1,33 @@-import { readFileSync } from "node:fs"-import { dirname, resolve } from "node:path"-import { fileURLToPath } from "node:url"+import source0 from "../channels/dm-view.tsx?raw"+import source1 from "../channels/thread-channel-surface.tsx?raw"+import source2 from "./attachment-card.tsx?raw"+import source3 from "./attachment-preview-sheet.tsx?raw"+import source4 from "./media-attachment-block.tsx?raw"+import source5 from "./message-channel-controller-actions.ts?raw"+import source6 from "./message-context-sheet.tsx?raw"+import source7 from "./message-share-dialog.tsx?raw"+import source8 from "./message.tsx?raw"+import source9 from "./thread-opener.tsx?raw"+import source10 from "../../remote-image/remote-markdown-image.tsx?raw"import { describe, expect, it } from "vitest"-const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..")-const source = (path: string) => readFileSync(resolve(webRoot, path), "utf8")+const sources: Record<string, string> = {+ "src/components/community/channels/dm-view.tsx": source0,+ "src/components/community/channels/thread-channel-surface.tsx": source1,+ "src/components/community/messages/attachment-card.tsx": source2,+ "src/components/community/messages/attachment-preview-sheet.tsx": source3,+ "src/components/community/messages/media-attachment-block.tsx": source4,+ "src/components/community/messages/message-channel-controller-actions.ts": source5,+ "src/components/community/messages/message-context-sheet.tsx": source6,+ "src/components/community/messages/message-share-dialog.tsx": source7,+ "src/components/community/messages/message.tsx": source8,+ "src/components/community/messages/thread-opener.tsx": source9,+ "src/components/remote-image/remote-markdown-image.tsx": source10,+}+const source = (path: string) => {+ if (!(path in sources)) throw new Error("unregistered contract source: " + path)+ return sources[path]+}describe("Community attachment download surface contract", () => {it("keeps every ordinary attachment action on the shared owner", () => {diff --git a/src/web/src/components/community/messages/composer-accessory-rail.dom.test.ts b/src/web/src/components/community/messages/composer-accessory-rail.dom.test.tsindex a119f193a..b8c220291 100644--- a/src/web/src/components/community/messages/composer-accessory-rail.dom.test.ts+++ b/src/web/src/components/community/messages/composer-accessory-rail.dom.test.ts@@ -1,5 +1,5 @@+import staticContractInput0 from "./composer-accessory-rail.tsx?raw"import React from "react"-import { readFileSync } from "node:fs"import { resolve } from "node:path"import { beforeEach, describe, expect, it, vi } from "vitest"import { tid } from "@/lib/community/testids"@@ -94,11 +94,7 @@ describe("ComposerAccessoryRail", () => {})it("does not reintroduce WS or viewport-derived width ownership", () => {- const source = readFileSync(resolve(- process.cwd(),- process.cwd().endsWith("/src/web") ? "" : "src/web",- "src/components/community/messages/composer-accessory-rail.tsx",- ), "utf8")+ const source = staticContractInput0expect(source).not.toContain("@/stores/community/ws")expect(source).not.toMatch(/max-w-\[calc\([^\]]*vw/)})diff --git a/src/web/src/components/community/messages/composer-facade.contract.test.ts b/src/web/src/components/community/messages/composer-facade.contract.test.tsindex b5f75b470..8cca64d3a 100644--- a/src/web/src/components/community/messages/composer-facade.contract.test.ts+++ b/src/web/src/components/community/messages/composer-facade.contract.test.ts@@ -1,80 +1,37 @@-import { existsSync, readFileSync } from "node:fs"+import source0 from "../channels/channel-route.tsx?raw"+import source1 from "../channels/dm-view.tsx?raw"+import source2 from "../channels/text-channel-surface.tsx?raw"+import source3 from "../channels/thread-channel-surface.dom.test.ts?raw"+import source4 from "../channels/thread-channel-surface.tsx?raw"+import source5 from "./create-forum-thread.tsx?raw"+import source6 from "./message-channel-controller.tsx?raw"+import { existsSync } from "node:fs"import { dirname, resolve } from "node:path"import { fileURLToPath } from "node:url"-import type { ComponentProps, ComponentRef } from "react"-import { describe, expect, expectTypeOf, it } from "vitest"-import { Composer } from "./composer"-import type { ComposerHandle, ComposerMention, ComposerProps } from "./composer"+import { describe, expect, it } from "vitest"+import * as facade from "./composer"-const messagesDirectory = dirname(fileURLToPath(import.meta.url))-const webRoot = resolve(messagesDirectory, "../../../..")-const readWeb = (path: string) =>- readFileSync(resolve(webRoot, path), "utf8")+const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..")+const sources: Record<string, string> = {+ "src/components/community/channels/channel-route.tsx": source0,+ "src/components/community/channels/dm-view.tsx": source1,+ "src/components/community/channels/text-channel-surface.tsx": source2,+ "src/components/community/channels/thread-channel-surface.dom.test.ts": source3,+ "src/components/community/channels/thread-channel-surface.tsx": source4,+ "src/components/community/messages/create-forum-thread.tsx": source5,+ "src/components/community/messages/message-channel-controller.tsx": source6,+}+const readWeb = (path: string) => {+ if (!(path in sources)) throw new Error("unregistered contract source: " + path)+ return sources[path]+}-describe("Composer public facade", () => {- it("keeps the exact props and seven-method forwarded handle", () => {- expectTypeOf<ComponentProps<typeof Composer>>().toEqualTypeOf<ComposerProps>()- expectTypeOf<ComponentRef<typeof Composer>>().toEqualTypeOf<ComposerHandle>()- expectTypeOf<ComposerMention>().toEqualTypeOf<{ id: string; label: string }>()- expectTypeOf<NonNullable<ComposerProps["replyingTo"]>>().toEqualTypeOf<{- authorId?: string- authorName: string- text: string- }>()- expectTypeOf<keyof ComposerHandle>().toEqualTypeOf<- | "focusEditor"- | "insertTextAtCaret"- | "insertMentionAtCaret"- | "submitNow"- | "resetAfterSubmit"- | "isEmpty"- | "openFilePicker"- >()- })-- it("keeps DM, channel, and thread on the structured reply-target contract", () => {- const dm = readWeb("src/components/community/channels/dm-view.tsx")- const channel = readWeb("src/components/community/channels/text-channel-surface.tsx")- const thread = readWeb("src/components/community/channels/thread-channel-surface.tsx")-- expect(dm).toContain("replyingTo={replyTo ?? undefined}")- expect(dm).not.toContain("replyingTo={replyTo?.authorName}")- expect(channel).toContain("replyingTo={controller.replyTo ?? undefined}")- expect(thread).toContain("replyingTo={controller.replyTo ?? undefined}")- })-- it("retains the original-path eight-export facade", () => {- const source = readWeb("src/components/community/messages/composer.tsx")- const namesFromBlocks = (pattern: RegExp) =>- [...source.matchAll(pattern)].flatMap((match) =>- match[1]- .split(",")- .map((part) => part.trim().split(/\s+as\s+/)[1] ?? part.trim())- .filter(Boolean),- )- const typeExports = namesFromBlocks(/export\s+type\s*\{([^}]*)\}/gs)- const valueExports = [- ...namesFromBlocks(/export\s*\{([^}]*)\}/gs),- ...[...source.matchAll(/export\s+(?:const|function|class)\s+(\w+)/g)].map(- (match) => match[1],- ),- ]- expect(new Set(typeExports)).toEqual(- new Set(["ComposerHandle", "ComposerMention", "ComposerProps", "SendAttachment"]),- )- expect(new Set(valueExports)).toEqual(- new Set([- "Composer",- "ComposerSkeleton",- "pendingFilesToSendAttachments",- "clipboardFiles",- ]),- )- expect(source).not.toMatch(/export\s+(?:default|\*)/)- expect(source).toContain("useComposerController(props, ref)")- expect(source).toContain("<ComposerView {...viewProps} />")- expect(source).not.toContain("useEditor(")- expect(source).not.toContain("useFileAttachments(")+describe("Composer facade boundaries", () => {+ it("exposes the public controls and file helpers without internal runtime exports", () => {+ expect(Object.keys(facade).sort()).toEqual([+ "Composer", "ComposerSkeleton", "clipboardFiles", "pendingFilesToSendAttachments",+ ])+ expect(existsSync(resolve(webRoot, "src/components/community/messages/index.ts"))).toBe(false)})it("keeps every direct importer on the facade and out of internals", () => {@@ -96,22 +53,4 @@ describe("Composer public facade", () => {}})- it("keeps every production owner below 400 lines without a barrel", () => {- const owners = [- "composer.tsx",- "composer-types.ts",- "composer-file-utils.ts",- "use-composer-controller.ts",- "use-composer-suggestions.ts",- "composer-suggestion-popups.tsx",- "composer-view.tsx",- ]- for (const owner of owners) {- const source = readWeb(`src/components/community/messages/${owner}`)- expect(source.split("\n").length, owner).toBeLessThan(400)- }- expect(- existsSync(resolve(webRoot, "src/components/community/messages/index.ts")),- ).toBe(false)- })})diff --git a/src/web/src/components/community/messages/composer-view.dom.test.ts b/src/web/src/components/community/messages/composer-view.dom.test.tsindex 35ebc6590..aeb7777b3 100644--- a/src/web/src/components/community/messages/composer-view.dom.test.ts+++ b/src/web/src/components/community/messages/composer-view.dom.test.ts@@ -1,3 +1,4 @@+import resolvedRawInput0 from "../../../app/globals.css?raw"import { createElement, type ReactNode } from "react"import { readFileSync } from "node:fs"import { resolve } from "node:path"@@ -179,14 +180,7 @@ describe("ComposerView", () => {})it("scopes single-line placeholder containment to chat composers", () => {- const css = readFileSync(- resolve(- process.cwd(),- process.cwd().endsWith("/src/web") ? "" : "src/web",- "src/app/globals.css",- ),- "utf8",- )+ const css = resolvedRawInput0const globalRule = css.match(/\.tiptap p\.is-editor-empty:first-child::before\s*\{([^}]*)\}/,)?.[1]diff --git a/src/web/src/components/community/messages/message-body.dom.test.ts b/src/web/src/components/community/messages/message-body.dom.test.tsindex 6e068c3a4..e3637c745 100644--- a/src/web/src/components/community/messages/message-body.dom.test.ts+++ b/src/web/src/components/community/messages/message-body.dom.test.ts@@ -1,8 +1,8 @@+import staticContractInput0 from "../../../app/globals.css?raw"import { describe, it, expect, vi } from "vitest"import React from "react"import { act, fireEvent } from "@/test/react-dom-harness"import { renderCommunity as render } from "@/test/community-owner-harness"-import { readFileSync } from "node:fs"import { dirname, resolve } from "node:path"import { fileURLToPath } from "node:url"import { extractTableDataFromElement } from "streamdown"@@ -107,7 +107,7 @@ describe("MessageBody — remote image geometry", () => {})it("caps community Markdown images at 300px without distorting their ratio", () => {- const css = readFileSync(resolve(componentDirectory, "../../../app/globals.css"), "utf8")+ const css = staticContractInput0expect(css).toContain('[data-community-message-body] [data-streamdown="image-wrapper"]')expect(css).toMatch(/\[data-community-message-body\] \[data-streamdown="image-wrapper"\][^{]*\{[^}]*max-width: 100%;/s)expect(css).toMatch(/\[data-community-message-body\] \[data-streamdown="image"\][^{]*\{[^}]*width: 100%;[^}]*height: 100%;[^}]*max-width: 100%;[^}]*max-height: 100%;[^}]*object-fit: contain;/s)diff --git a/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts b/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.tsindex 2419c47c3..8f531fe05 100644--- a/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts+++ b/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts@@ -1,100 +1,28 @@-import { readFileSync } from "node:fs"-import { dirname, resolve } from "node:path"-import { fileURLToPath } from "node:url"-import type { ComponentProps, ComponentRef, ReactNode } from "react"-import type { MentionType } from "@alook/shared"-import { describe, expect, expectTypeOf, it } from "vitest"+import source0 from "../channels/text-channel-surface.dom.test.ts?raw"+import source1 from "../channels/text-channel-surface.tsx?raw"+import source2 from "../channels/thread-channel-surface.dom.test.ts?raw"+import source3 from "../channels/thread-channel-surface.tsx?raw"+import source4 from "./message-channel-controller-actions.ts?raw"+import source5 from "./message-channel-controller-send.ts?raw"+import { describe, expect, it } from "vitest"import * as facade from "./message-channel-controller"-import type { MessageChannelControllerValue as FacadeControllerValue } from "./message-channel-controller"-import type {- FileAttachment,- ImagePreview,- SendAttachment,-} from "@/lib/community/models/message"-import type { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"-type ExpectedReplyTarget = { id: string; authorId?: string; authorName: string; text: string }-type ExpectedContextTarget = {- serverId: string- channelId: string- label: string- seq: number+const sources: Record<string, string> = {+ "src/components/community/channels/text-channel-surface.dom.test.ts": source0,+ "src/components/community/channels/text-channel-surface.tsx": source1,+ "src/components/community/channels/thread-channel-surface.dom.test.ts": source2,+ "src/components/community/channels/thread-channel-surface.tsx": source3,+ "src/components/community/messages/message-channel-controller-actions.ts": source4,+ "src/components/community/messages/message-channel-controller-send.ts": source5,}-type ExpectedMessageActions = {- onToggleReaction: (id: string, emoji: string) => void- onReact: (id: string, emoji: string) => void- onReply: (id: string) => void- onPin: (id: string) => void- onMark: (id: string) => void- onCreateThread: (id: string) => Promise<void>- onCopy: (id: string, selectedText?: string) => void- onRetry: (id: string) => void- onDismiss: (id: string) => void- onPreviewImage: (image: ImagePreview) => void- onPreviewAttachment: (attachment: FileAttachment) => void-}-type ExpectedControllerValue = {- feed: ReturnType<typeof useChannelMessageFeed>- pinnedIds: Set<string>- replyTo: ExpectedReplyTarget | null- setReplyTo: (reply: ExpectedReplyTarget | null) => void- scrollTargetId: string | null- setScrollTargetId: (targetId: string | null) => void- consumeScrollTarget: (targetId: string) => void- contextTarget: ExpectedContextTarget | null- setContextTarget: (target: ExpectedContextTarget | null) => void- openContextSeq: (seq: number) => void- onSheetReply: (target: ExpectedReplyTarget) => void- jumpToSeq: (seq: number) => void- messageActions: ExpectedMessageActions- threadActions: Omit<ExpectedMessageActions, "onCreateThread"> & { onCreateThread: undefined }- acceptMessage: (- markdown: string,- attachments?: SendAttachment[],- mentionType?: MentionType,- ) => boolean- localSubmitVersion: number- handleTyping: () => void- typingUsers: string[]-}-type ExpectedControllerProps = {- channelId: string- serverId: string- serverParam: string- channelName: string- forumParentChannelId?: string- viewer: { id: string; name: string; avatar: string }- anchorMessageId: string | null- feed: ReturnType<typeof useChannelMessageFeed>- uiHandlers: {- navigate?: (serverId: string, channelId: string) => void- previewImage?: (image: ImagePreview) => void- previewAttachment?: (attachment: FileAttachment) => void- }- onOpenThread: (threadId: string) => void- onOpenPinned: () => void- resolveUserName: (userId: string) => string- children: (controller: ExpectedControllerValue) => ReactNode+const source = (path: string) => {+ if (!(path in sources)) throw new Error("unregistered contract source: " + path)+ return sources[path]}-const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..")-const source = (path: string) => readFileSync(resolve(webRoot, path), "utf8")--describe("MessageChannelController facade contract", () => {- it("keeps the exact runtime export and a direct non-component render call", () => {+describe("MessageChannelController facade boundaries", () => {+ it("exposes the public component without internal runtime exports", () => {expect(Object.keys(facade)).toEqual(["MessageChannelController"])- expectTypeOf<ComponentProps<typeof facade.MessageChannelController>>()- .toEqualTypeOf<ExpectedControllerProps>()- expectTypeOf<ExpectedControllerProps>()- .toEqualTypeOf<ComponentProps<typeof facade.MessageChannelController>>()- expectTypeOf<FacadeControllerValue>().toEqualTypeOf<ExpectedControllerValue>()- expectTypeOf<ExpectedControllerValue>().toEqualTypeOf<FacadeControllerValue>()- expectTypeOf<ComponentRef<typeof facade.MessageChannelController>>().toEqualTypeOf<never>()- const text = source("src/components/community/messages/message-channel-controller.tsx")- expect(text).toContain("useMessageChannelController(props)")- expect(text).toContain("return renderMessageChannelController(children, value)")- expect(text).not.toMatch(/<MessageChannelControllerView\b|createElement\(MessageChannelControllerView/)- expect(text).not.toMatch(/forwardRef|useImperativeHandle/)})it("keeps production and test consumers on the original path", () => {@@ -111,39 +39,10 @@ describe("MessageChannelController facade contract", () => {}})- it("keeps hook wiring in one owner and pure helpers hook-free", () => {- const state = source("src/components/community/messages/message-channel-controller-state.ts")- const body = state.slice(state.indexOf("export function useMessageChannelController"))- const actions = source("src/components/community/messages/message-channel-controller-actions.ts")- const send = source("src/components/community/messages/message-channel-controller-send.ts")- const orderedHooks = [- "const router = useRouter()",- "const searchParams = useSearchParams()",- "const [replyTo, setReplyTo] = useAtom(useCreateAtom<ReplyTarget | null>(null))",- "const targetEntry = useMemo(() => ({ entry: feed.positionEntry, atom: createAtom<string | null>(anchorMessageId) }), [anchorMessageId, feed.positionEntry])",- "const [scrollTargetId, setScrollTargetId] = useAtom(targetEntry.atom)",- "const [contextTarget, setContextTarget] = useAtom(useCreateAtom<MessageContextTarget | null>(null))",- "useSendMessage()",- "useToggleReactionApi()",- "useAddReactionApi()",- "usePinMessage()",- "useUnpinMessage()",- "useToggleMark()",- "useCreateThread()",- "useUploadFile()",- "useTypingUsersForScope(`ch:${channelId}`)",- "useTypingNamesForScope(`ch:${channelId}`)",- ]- let cursor = -1- for (const token of orderedHooks) {- const position = body.indexOf(token, cursor + 1)- expect(position, token).toBeGreaterThan(cursor)- cursor = position+ it("keeps action and send helpers hook-free", () => {+ for (const helper of ["actions", "send"]) {+ expect(source(`src/components/community/messages/message-channel-controller-${helper}.ts`))+ .not.toMatch(/\buse[A-Z][A-Za-z]+\(/)}- expect(body.match(/\buseCreateAtom(?:<[^>]+>)?\(/g)).toHaveLength(3)- expect(body.match(/\bcreateAtom(?:<[^>]+>)?\(/g)).toHaveLength(1)- expect(body).not.toMatch(/\buseState(?:<[^>]+>)?\(/)- expect(actions).not.toMatch(/\buse[A-Z][A-Za-z]+\(/)- expect(send).not.toMatch(/\buse[A-Z][A-Za-z]+\(/)})})diff --git a/src/web/src/components/community/messages/message-context-sheet-header.test.ts b/src/web/src/components/community/messages/message-context-sheet-header.test.tsindex 9fe323701..ec2e47159 100644--- a/src/web/src/components/community/messages/message-context-sheet-header.test.ts+++ b/src/web/src/components/community/messages/message-context-sheet-header.test.ts@@ -1,9 +1,9 @@-import { readFileSync } from "node:fs"+import rawContractInput0 from "./message-context-sheet.tsx?raw"import { describe, expect, it } from "vitest"describe("MessageContextSheet header", () => {it("supplies a structured title that truncates only the channel label", () => {- const source = readFileSync(new URL("./message-context-sheet.tsx", import.meta.url), "utf8")+ const source = rawContractInput0expect(source).toContain("title={channelLabel ? (")expect(source).toContain('<span className="flex w-full min-w-0 items-center gap-1.5">')diff --git a/src/web/src/components/community/messages/message-link-surfaces.contract.test.ts b/src/web/src/components/community/messages/message-link-surfaces.contract.test.tsindex f2a4f5a43..f5f9d1e66 100644--- a/src/web/src/components/community/messages/message-link-surfaces.contract.test.ts+++ b/src/web/src/components/community/messages/message-link-surfaces.contract.test.ts@@ -1,10 +1,25 @@-import { readFileSync } from "node:fs"-import { dirname, resolve } from "node:path"-import { fileURLToPath } from "node:url"+import source0 from "../channels/dm-view.tsx?raw"+import source1 from "../channels/text-channel-surface.tsx?raw"+import source2 from "../channels/thread-channel-surface.tsx?raw"+import source3 from "./message-context-sheet.tsx?raw"+import source4 from "./message-list-row.tsx?raw"+import source5 from "./message-row.tsx?raw"+import source6 from "./message.tsx?raw"import { describe, expect, it } from "vitest"-const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..")-const source = (path: string) => readFileSync(resolve(webRoot, path), "utf8")+const sources: Record<string, string> = {+ "src/components/community/channels/dm-view.tsx": source0,+ "src/components/community/channels/text-channel-surface.tsx": source1,+ "src/components/community/channels/thread-channel-surface.tsx": source2,+ "src/components/community/messages/message-context-sheet.tsx": source3,+ "src/components/community/messages/message-list-row.tsx": source4,+ "src/components/community/messages/message-row.tsx": source5,+ "src/components/community/messages/message.tsx": source6,+}+const source = (path: string) => {+ if (!(path in sources)) throw new Error("unregistered contract source: " + path)+ return sources[path]+}describe("Community ordinary-link action surface contract", () => {it("routes DM, channel, and thread timeline messages through one Message boundary", () => {diff --git a/src/web/src/components/community/messages/message-list-controller.dom.test.ts b/src/web/src/components/community/messages/message-list-controller.dom.test.tsindex 7b07bbdd5..a8e14aabb 100644--- a/src/web/src/components/community/messages/message-list-controller.dom.test.ts+++ b/src/web/src/components/community/messages/message-list-controller.dom.test.ts@@ -1,5 +1,5 @@+import contractText0 from "./message-list-controller.ts?raw"import React from "react"-import { readFileSync } from "node:fs"import { dirname, resolve } from "node:path"import { fileURLToPath } from "node:url"import { act, render as rtlRender } from "@/test/react-dom-harness"@@ -9,10 +9,17 @@ import type { ResolvedMessageListProps } from "./message-list-types"import { MESSAGE_RAIL_TAIL_PADDING_END_PX } from "@/lib/community/conversation-layout"const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..")-const readWebSource = (path: string) => readFileSync(resolve(webRoot, path), "utf8")+const contractSources: Record<string, string> = {+ "src/components/community/messages/message-list-controller.ts": contractText0,+}+const readWebSource = (path: string) => {+ if (!(path in contractSources)) throw new Error("unregistered contract source: " + path)+ return contractSources[path]+}const mocks = vi.hoisted(() => ({- hookOrder: [] as string[],+ readPositionReady: false,+ paginationEnabled: false,scrollInputs: [] as unknown[],paginationInputs: [] as unknown[],scrollRef: { current: null as HTMLDivElement | null },@@ -39,7 +46,6 @@ vi.mock("@/hooks/community/use-scroll-anchor", () => ({input.onScrollTargetPositioned(input.scrollToMessageId)}}, [input, loaded])- mocks.hookOrder.push("anchor")mocks.scrollInputs.push({ ...input, tailPaddingEnd: input.tailPaddingEnd ?? MESSAGE_RAIL_TAIL_PADDING_END_PX })return {scrollRef: mocks.scrollRef,@@ -49,8 +55,8 @@ vi.mock("@/hooks/community/use-scroll-anchor", () => ({requestPresentPosition: mocks.requestPresentPosition,jumpTo: mocks.jumpToIndex,positionOutcome,- readPositionReady: false,- paginationEnabled: false,+ readPositionReady: mocks.readPositionReady,+ paginationEnabled: mocks.paginationEnabled,captureOlderPageAnchor: mocks.captureOlderPageAnchor,captureNewerPageAnchor: mocks.captureNewerPageAnchor,}@@ -58,7 +64,6 @@ vi.mock("@/hooks/community/use-scroll-anchor", () => ({}))vi.mock("@/hooks/community/use-virtual-cursor-pagination", () => ({useVirtualCursorPagination: (input: { edge: string }) => {- mocks.hookOrder.push(input.edge)mocks.paginationInputs.push(input)},}))@@ -132,7 +137,10 @@ describe("useMessageListController", () => {currentScrollNode = scrollNode as unknown as HTMLDivElementresizeCallback = nulldisconnect.mockClear()- mocks.hookOrder.length = 0+ mocks.readPositionReady = false+ mocks.paginationEnabled = false+ mocks.captureOlderPageAnchor.mockClear()+ mocks.captureNewerPageAnchor.mockClear()mocks.scrollInputs.length = 0mocks.paginationInputs.length = 0mocks.scrollRef.current = null@@ -224,7 +232,7 @@ describe("useMessageListController", () => {])})- it("uses the exact loading predicate and calls anchor/start/end hooks unconditionally in order", () => {+ it("keeps loading, reading and both pagination directions tied to the current scroll owner", () => {let renderer: ReturnType<typeof rtlRender>act(() => {renderer = rtlRender(@@ -232,58 +240,27 @@ describe("useMessageListController", () => {)})expect(latest.isLoading).toBe(false)- expect(mocks.hookOrder.slice(0, 3)).toEqual(["anchor", "start", "end"])- expect(mocks.scrollInputs[0]).toEqual({- items: expect.any(Array),- newDividerBefore: undefined,- initialScrollReady: true,- positionDataState: "pending",- positionEntry: undefined,- positionScope: undefined,- initialPositionMessageId: undefined,- messageWindow: undefined,- active: undefined,- positioningActive: undefined,- presentRequest: undefined,- hasMoreNewer: undefined,- isFetchingOlder: undefined,- isFetchingNewer: undefined,- presentVersion: undefined,- localSubmitVersion: undefined,- hasMoreOlder: undefined,- tailPaddingEnd: 32,- scrollToMessageId: undefined,- onScrollTargetCancelled: undefined,- onScrollTargetPositioned: expect.any(Function),- })+ expect(mocks.scrollInputs[0]).toMatchObject({ initialScrollReady: true, positionDataState: "pending" })+ expect((mocks.scrollInputs[0] as { items: unknown }).items).toBe(latest.items)expect(mocks.paginationInputs.slice(0, 2)).toEqual([- {+ expect.objectContaining({virtualizer: mocks.virtualizer,count: latest.items.length,enabled: false,- requestKey: undefined,- hasMore: undefined,- isFetching: undefined,isError: false,onBeforeLoad: mocks.captureOlderPageAnchor,- onLoad: undefined,edge: "start",preloadWithinViewport: true,- },- {+ }),+ expect.objectContaining({virtualizer: mocks.virtualizer,count: latest.items.length,enabled: false,- requestKey: undefined,- hasMore: undefined,- isFetching: undefined,isError: false,- hasMoreAtStart: undefined,onBeforeLoad: mocks.captureNewerPageAnchor,- onLoad: undefined,edge: "end",preloadWithinViewport: true,- },+ }),])expect(latest.scrollRef).toBe(mocks.scrollRef)expect(latest.virtualizer).toBe(mocks.virtualizer)@@ -297,7 +274,24 @@ describe("useMessageListController", () => {}))})expect(latest.isLoading).toBe(true)- expect(mocks.hookOrder.slice(-3)).toEqual(["anchor", "start", "end"])+ act(() => mocks.finishPosition("success"))+ mocks.readPositionReady = true+ mocks.paginationEnabled = true+ renderer!.rerender(React.createElement(Probe, { value: props({ loading: false }) }))+ expect(latest.isLoading).toBe(false)+ expect(latest.readPositionReady).toBe(true)+ expect(mocks.paginationInputs.slice(-2)).toEqual([+ expect.objectContaining({ edge: "start", enabled: true, onBeforeLoad: mocks.captureOlderPageAnchor }),+ expect.objectContaining({ edge: "end", enabled: true, onBeforeLoad: mocks.captureNewerPageAnchor }),+ ])+ mocks.readPositionReady = false+ mocks.paginationEnabled = false+ renderer!.rerender(React.createElement(Probe, { value: props({ loading: false }) }))+ expect(latest.readPositionReady).toBe(false)+ expect(mocks.paginationInputs.slice(-2)).toEqual([+ expect.objectContaining({ edge: "start", enabled: false }),+ expect.objectContaining({ edge: "end", enabled: false }),+ ])})it("delegates the shared tail padding to the original virtualizer hook", () => {@@ -375,7 +369,7 @@ describe("useMessageListController", () => {expect(latest.pillCount).toBeUndefined()})- it("passes every pagination/anchor input through and gives jump mode server-count precedence", () => {+ it("preserves requested pagination callbacks and gives jump mode server-count precedence", () => {const loadOlder = vi.fn()const loadNewer = vi.fn()const jumpToPresent = vi.fn()@@ -397,35 +391,23 @@ describe("useMessageListController", () => {}),}))})- expect(mocks.scrollInputs.at(-1)).toEqual({+ expect(mocks.scrollInputs.at(-1)).toMatchObject({items: expect.any(Array),newDividerBefore: "m1",- positionScope: undefined,- positionEntry: undefined,- positionDataState: undefined,- positioningActive: undefined,- messageWindow: undefined,- initialPositionMessageId: undefined,- active: undefined,- presentRequest: undefined,initialScrollReady: false,hasMoreNewer: true,isFetchingOlder: true,isFetchingNewer: true,presentVersion: 7,- localSubmitVersion: undefined,hasMoreOlder: true,tailPaddingEnd: 32,- scrollToMessageId: undefined,- onScrollTargetCancelled: undefined,onScrollTargetPositioned: expect.any(Function),})expect(mocks.paginationInputs.slice(-2)).toEqual([- {+ expect.objectContaining({virtualizer: mocks.virtualizer,count: latest.items.length,enabled: false,- requestKey: undefined,hasMore: true,isFetching: true,isError: false,@@ -433,12 +415,11 @@ describe("useMessageListController", () => {onLoad: loadOlder,edge: "start",preloadWithinViewport: true,- },- {+ }),+ expect.objectContaining({virtualizer: mocks.virtualizer,count: latest.items.length,enabled: false,- requestKey: undefined,hasMore: true,isFetching: true,isError: false,@@ -447,7 +428,7 @@ describe("useMessageListController", () => {onLoad: loadNewer,edge: "end",preloadWithinViewport: true,- },+ }),])expect(latest.pillCount).toBe(9)expect(latest.pillMode).toBe("jump")diff --git a/src/web/src/components/community/messages/message-list-facade.contract.test.ts b/src/web/src/components/community/messages/message-list-facade.contract.test.tsindex c6d65f5d8..ee7574d1d 100644--- a/src/web/src/components/community/messages/message-list-facade.contract.test.ts+++ b/src/web/src/components/community/messages/message-list-facade.contract.test.ts@@ -1,83 +1,28 @@-import { readFileSync } from "node:fs"-import { dirname, resolve } from "node:path"-import { fileURLToPath } from "node:url"-import type { ComponentProps, ComponentRef, ReactNode } from "react"-import { describe, expect, expectTypeOf, it, vi } from "vitest"+import source0 from "../../../app/c/layout.tsx?raw"+import source1 from "../../../app/c/page.tsx?raw"+import source2 from "../channels/channel-loading-frame.tsx?raw"+import source3 from "../channels/dm-view.tsx?raw"+import source4 from "../channels/text-channel-surface.tsx?raw"+import source5 from "../channels/thread-channel-surface.tsx?raw"+import { describe, expect, it } from "vitest"import * as facade from "./message-list"-import type { FileAttachment, ImagePreview, Msg } from "@/lib/community/models/message"-import type { OpenProfile } from "@/components/community/social/profile-types"-type ExpectedMessageListProps = {- channel: string- messages: Msg[]- loading?: boolean- pinnedIds?: Set<string>- newDividerBefore?: string- onOpenThread: (id: string) => void- onOpenProfile?: OpenProfile- onToggleReaction?: (id: string, emoji: string) => void- onReact?: (id: string, emoji: string) => void- onReply?: (id: string) => void- resolveAuthorMentionText?: (authorId: string) => string | null- onInsertMentionText?: (text: string) => void- onPin?: (id: string) => void- onMark?: (id: string) => void- onCreateThread?: (id: string) => void- onCopy?: (id: string, selectedText?: string) => void- onRetry?: (id: string) => void- onDismiss?: (id: string) => void- onPreviewImage?: (image: ImagePreview) => void- onPreviewAttachment?: (attachment: FileAttachment) => void- resolveUserName?: (userId: string) => string- scrollToMessageId?: string | null- initialPositionMessageId?: string | null- positionEntry?: object | null- hero?: ReactNode- variant?: "channel" | "dm"- onScrollRoot?: (element: HTMLDivElement | null) => void- viewerUserId?: string- initialScrollReady?: boolean- onScrollTargetConsumed?: (id: string) => void- hasMore?: boolean- historyStartKnown?: boolean- isFetching?: boolean- isFetchingOlder?: boolean- onLoadOlder?: () => void- hasMoreNewer?: boolean- isFetchingNewer?: boolean- onLoadNewer?: () => void- onJumpToPresent?: () => void- presentVersion?: number- localSubmitVersion?: number- unreadCount?: number+const sources: Record<string, string> = {+ "src/app/c/layout.tsx": source0,+ "src/app/c/page.tsx": source1,+ "src/components/community/channels/channel-loading-frame.tsx": source2,+ "src/components/community/channels/dm-view.tsx": source3,+ "src/components/community/channels/text-channel-surface.tsx": source4,+ "src/components/community/channels/thread-channel-surface.tsx": source5,+}+const source = (path: string) => {+ if (!(path in sources)) throw new Error("unregistered contract source: " + path)+ return sources[path]}-const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..")-const source = (path: string) => readFileSync(resolve(webRoot, path), "utf8")--describe("MessageList facade contract", () => {- it("keeps the exact one-value public surface and applies defaults in the facade", () => {+describe("MessageList facade boundaries", () => {+ it("exposes the public component without internal runtime exports", () => {expect(Object.keys(facade)).toEqual(["MessageList"])- expectTypeOf<ComponentProps<typeof facade.MessageList>>()- .toEqualTypeOf<ExpectedMessageListProps>()- expectTypeOf<ExpectedMessageListProps>()- .toEqualTypeOf<ComponentProps<typeof facade.MessageList>>()- expectTypeOf<ComponentRef<typeof facade.MessageList>>().toEqualTypeOf<never>()- const text = source("src/components/community/messages/message-list.tsx")- expect(text).toContain('variant = "channel"')- expect(text).toContain("initialScrollReady = true")- expect(text).not.toContain("composerOverlap")- expect(text).toContain("useMessageListController(resolvedProps)")- expect(text).toContain("return renderMessageListView(resolvedProps, controller, () => (")- expect(text).toContain("<VirtualRows")- expect(text).toContain("items={controller.items}")- expect(text).toContain("virtualizer={controller.virtualizer}")- expect(text).not.toContain("itemKey=")- expect(text).toContain(- "renderItem={(item, index) => renderMessageListRow(item, resolvedProps, controller, index)}",- )- expect(text).not.toMatch(/<MessageListView\b|createElement\(MessageListView/)- expect(text).not.toMatch(/forwardRef|useImperativeHandle/)})it("keeps all production consumers on the original path", () => {diff --git a/src/web/src/components/community/messages/message.render.dom.test.ts b/src/web/src/components/community/messages/message.render.dom.test.tsindex 5ac439cc3..b20261c58 100644--- a/src/web/src/components/community/messages/message.render.dom.test.ts+++ b/src/web/src/components/community/messages/message.render.dom.test.ts@@ -1,3 +1,4 @@+import resolvedRawInput0 from "../../../app/globals.css?raw"import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"import { readFileSync } from "node:fs"import { resolve } from "node:path"@@ -1651,14 +1652,7 @@ describe("Message touch action menu", () => {const body = renderer!.root.findByProps({ "data-community-message-body": true })expect(body.props.className).toContain("select-text")- const globalCss = readFileSync(- resolve(- process.cwd(),- process.cwd().endsWith("/src/web") ? "" : "src/web",- "src/app/globals.css",- ),- "utf8",- )+ const globalCss = resolvedRawInput0expect(globalCss).toMatch(/\[data-community-message-body\]\s*\{[^}]*-webkit-touch-callout:\s*default;[^}]*user-select:\s*text;/s,)diff --git a/src/web/src/components/community/messages/use-composer-controller.dom.test.ts b/src/web/src/components/community/messages/use-composer-controller.dom.test.tsindex 684ce48f2..7dc12f17d 100644--- a/src/web/src/components/community/messages/use-composer-controller.dom.test.ts+++ b/src/web/src/components/community/messages/use-composer-controller.dom.test.ts@@ -1,3 +1,4 @@+import resolvedRawInput0 from "./use-composer-controller.ts?raw"import { readFileSync } from "node:fs"import { resolve } from "node:path"import { forwardRef, createElement, createRef } from "react"@@ -1344,14 +1345,7 @@ describe("useComposerController", () => {})it("pins the layout/draft/typing ordering boundaries in source", () => {- const source = readFileSync(- resolve(- process.cwd(),- process.cwd().endsWith("/src/web") ? "" : "src/web",- "src/components/community/messages/use-composer-controller.ts",- ),- "utf8",- )+ const source = resolvedRawInput0const gate = source.indexOf("if (!editor || client.isMutating(")const awaitFiles = source.indexOf("await awaitPendingFiles()")const secondCheck = source.indexOf("assert()", awaitFiles)diff --git a/src/web/src/components/community/messages/virtualizer-direct-dom.contract.test.ts b/src/web/src/components/community/messages/virtualizer-direct-dom.contract.test.tsindex ebe73c89c..05a4e3b89 100644--- a/src/web/src/components/community/messages/virtualizer-direct-dom.contract.test.ts+++ b/src/web/src/components/community/messages/virtualizer-direct-dom.contract.test.ts@@ -1,3 +1,10 @@+import scrollAnchorSource from "../../../hooks/community/use-scroll-anchor.ts?raw"+import reactOptionsSource from "../../../hooks/community/virtualizer-react-options.ts?raw"+import contractText0 from "../channels/forum-post-list.tsx?raw"+import contractText1 from "../members/member-list.tsx?raw"+import contractText2 from "../settings/server-settings.tsx?raw"+import contractText3 from "./message-list.tsx?raw"+import contractText4 from "./virtual-cursor-list.tsx?raw"import { describe, expect, it, vi } from "vitest"import { createElement } from "react"import { renderToStaticMarkup } from "react-dom/server"@@ -9,14 +16,24 @@ import { fileURLToPath } from "node:url"const componentDirectory = path.dirname(fileURLToPath(import.meta.url))const hooksDirectory = path.resolve(componentDirectory, "../../../hooks/community")-const readComponent = (name: string) => fs.readFileSync(path.join(componentDirectory, name), "utf8")+const contractSources: Record<string, string> = {+ "../channels/forum-post-list.tsx": contractText0,+ "../members/member-list.tsx": contractText1,+ "../settings/server-settings.tsx": contractText2,+ "message-list.tsx": contractText3,+ "virtual-cursor-list.tsx": contractText4,+}+const readComponent = (path: string) => {+ if (!(path in contractSources)) throw new Error("unregistered contract source: " + path)+ return contractSources[path]+}describe("community virtualizer direct DOM contract", () => {const virtualRows = readComponent("virtual-cursor-list.tsx")it("gives MessageList one React geometry writer with native direct updates disabled", () => {const messageList = readComponent("message-list.tsx")- const scrollAnchor = fs.readFileSync(path.join(hooksDirectory, "use-scroll-anchor.ts"), "utf8")+ const scrollAnchor = scrollAnchorSourceexpect(messageList).toContain("<VirtualRows")expect(scrollAnchor).toContain("...COMMUNITY_VIRTUALIZER_REACT_OPTIONS")@@ -25,7 +42,7 @@ describe("community virtualizer direct DOM contract", () => {expect(messageList).toMatch(/<VirtualRows\s+reactLayout/)expect(scrollAnchor).toMatch(/\.\.\.COMMUNITY_VIRTUALIZER_REACT_OPTIONS,\s+directDomUpdates: false/)expect(scrollAnchor).toContain("initialRect:")- expect(fs.readFileSync(path.join(hooksDirectory, "virtualizer-react-options.ts"), "utf8")).toContain("directDomUpdates: true")+ expect(reactOptionsSource).toContain("directDomUpdates: true")})it.each([false, true])("writes SSR height and transforms only for React layout=%s", (reactLayout) => {diff --git a/src/web/src/components/community/official-server-badge.dom.test.ts b/src/web/src/components/community/official-server-badge.dom.test.tsindex c3cb4a625..a02be81da 100644--- a/src/web/src/components/community/official-server-badge.dom.test.ts+++ b/src/web/src/components/community/official-server-badge.dom.test.ts@@ -1,3 +1,4 @@+import badgeAsset from "../../../public/official-server-badge-flat.svg?raw"import { resolve } from "node:path"import { readFileSync } from "node:fs"import { createElement } from "react"@@ -10,11 +11,7 @@ describe("official server badge asset", () => {render(createElement(OfficialServerBadge, { official: true }))const badge = screen.getByRole("img", { name: "Official server" })expect(badge).toHaveAttribute("src", "/official-server-badge-flat.svg")- const asset = readFileSync(resolve(- import.meta.dirname,- "../../../public",- badge.getAttribute("src")!.slice(1),- ), "utf8")+ const asset = badgeAssetconst document = new DOMParser().parseFromString(asset, "image/svg+xml")expect(document.querySelector("parsererror")).toBeNull()expect(document.documentElement.localName).toBe("svg")diff --git a/src/web/src/components/community/onboarding-tiles/connect-tile-brand.test.ts b/src/web/src/components/community/onboarding-tiles/connect-tile-brand.test.tsindex fdbe6538b..4f59a25e0 100644--- a/src/web/src/components/community/onboarding-tiles/connect-tile-brand.test.ts+++ b/src/web/src/components/community/onboarding-tiles/connect-tile-brand.test.ts@@ -1,9 +1,9 @@-import { readFileSync } from "node:fs"+import rawContractInput0 from "./connect-tile.tsx?raw"import { describe, expect, it } from "vitest"describe("ConnectTile brand mark", () => {it("loads the shared multicolor asset directly", () => {- const source = readFileSync(new URL("./connect-tile.tsx", import.meta.url), "utf8")+ const source = rawContractInput0expect(source).toContain('href="/alook.svg"')expect(source).toContain('className="ot-alook ot-center"')diff --git a/src/web/src/components/community/onboarding/onboarding-preview-flow.test.ts b/src/web/src/components/community/onboarding/onboarding-preview-flow.test.tsindex a33649e82..35029ee93 100644--- a/src/web/src/components/community/onboarding/onboarding-preview-flow.test.ts+++ b/src/web/src/components/community/onboarding/onboarding-preview-flow.test.ts@@ -1,25 +1,34 @@+import migratedSource0 from "./community-onboarding-form.tsx?raw"+import migratedSource1 from "./initialize-community-onboarding.ts?raw"+import migratedSource2 from "./onboarding-machine-dialog.tsx?raw"+import migratedSource3 from "./onboarding-model-dialog.tsx?raw"+import migratedSource4 from "./onboarding-select-dialog.preview.tsx?raw"+import migratedSource5 from "./onboarding-select-dialog.tsx?raw"+import migratedSource6 from "./onboarding-status-dialog.tsx?raw"+const migratedSources: Record<string, string> = {+ "community-onboarding-form.tsx": migratedSource0,+ "initialize-community-onboarding.ts": migratedSource1,+ "onboarding-machine-dialog.tsx": migratedSource2,+ "onboarding-model-dialog.tsx": migratedSource3,+ "onboarding-select-dialog.preview.tsx": migratedSource4,+ "onboarding-select-dialog.tsx": migratedSource5,+ "onboarding-status-dialog.tsx": migratedSource6,+}+import resolvedRawInput0 from "./onboarding-select-dialog.preview.tsx?raw"+import resolvedRawInput1 from "./community-onboarding-form.tsx?raw"+import resolvedRawInput2 from "./onboarding-machine-dialog.tsx?raw"+import resolvedRawInput3 from "../machines/me-machines-route.tsx?raw"+import staticContractInput0 from "./onboarding-status-dialog.tsx?raw"import { readFileSync } from "node:fs"import { dirname, resolve } from "node:path"import { fileURLToPath } from "node:url"import { describe, expect, it } from "vitest"const directory = dirname(fileURLToPath(import.meta.url))-const previewSource = readFileSync(- resolve(directory, "onboarding-select-dialog.preview.tsx"),- "utf8",-)-const onboardingFormSource = readFileSync(- resolve(directory, "community-onboarding-form.tsx"),- "utf8",-)-const machineDialogSource = readFileSync(- resolve(directory, "onboarding-machine-dialog.tsx"),- "utf8",-)-const machinesPageSource = readFileSync(- resolve(directory, "../machines/me-machines-route.tsx"),- "utf8",-)+const previewSource = resolvedRawInput0+const onboardingFormSource = resolvedRawInput1+const machineDialogSource = resolvedRawInput2+const machinesPageSource = resolvedRawInput3describe("onboarding preview flow", () => {it("shows the machine step between harness and identity", () => {@@ -42,7 +51,7 @@ describe("onboarding preview flow", () => {"onboarding-status-dialog.tsx","onboarding-model-dialog.tsx",]) {- const source = readFileSync(resolve(directory, filename), "utf8")+ const source = migratedSources[filename]expect(source).toContain("<DialogContent")expect(source).not.toContain("overlayClassName=")}@@ -79,14 +88,14 @@ describe("onboarding preview flow", () => {"onboarding-select-dialog.preview.tsx","onboarding-status-dialog.tsx",]) {- const source = readFileSync(resolve(directory, filename), "utf8")+ const source = migratedSources[filename]expect(source).not.toMatch(/\b(?:Guide|Builder)\b/)}expect(previewSource).toMatch(/\bbots?\b/)expect(previewSource).toContain('key: "reviewer"')- expect(readFileSync(resolve(directory, "onboarding-status-dialog.tsx"), "utf8"))+ expect(staticContractInput0).toContain("checkpoint.bots.map")expect(onboardingFormSource).not.toContain("Two bots")})diff --git a/src/web/src/components/community/onboarding/onboarding-select-dialog.contract.test.ts b/src/web/src/components/community/onboarding/onboarding-select-dialog.contract.test.tsindex 384f2033e..d68caf636 100644--- a/src/web/src/components/community/onboarding/onboarding-select-dialog.contract.test.ts+++ b/src/web/src/components/community/onboarding/onboarding-select-dialog.contract.test.ts@@ -1,12 +1,10 @@+import resolvedRawInput0 from "./onboarding-select-dialog.tsx?raw"import { readFileSync } from "node:fs"import { dirname, resolve } from "node:path"import { fileURLToPath } from "node:url"import { describe, expect, it } from "vitest"-const source = readFileSync(- resolve(dirname(fileURLToPath(import.meta.url)), "onboarding-select-dialog.tsx"),- "utf8",-)+const source = resolvedRawInput0describe("OnboardingSelectDialog contract", () => {it("builds on the shared shadcn dialog, field, and radio primitives", () => {diff --git a/src/web/src/components/community/settings/server-audit-removal.contract.test.ts b/src/web/src/components/community/settings/server-audit-removal.contract.test.tsindex 10592746e..91d7b31c8 100644--- a/src/web/src/components/community/settings/server-audit-removal.contract.test.ts+++ b/src/web/src/components/community/settings/server-audit-removal.contract.test.ts@@ -1,3 +1,11 @@+import auditMigration from "../../../../migrations/0084_drop_community_audit_log.sql?raw"+import communitySchema from "../../../../../shared/src/db/community-schema.ts?raw"+import contractText0 from "../../../app/api/community/bots/[id]/audit-log/route.ts?raw"+import contractText1 from "../channels/channel-sidebar.tsx?raw"+import contractText2 from "./server-settings.tsx?raw"+import contractText3 from "./settings-types.ts?raw"+import contractText4 from "../../../hooks/community/use-server-panels.ts?raw"+import contractText5 from "../../../lib/query-keys.ts?raw"import { existsSync, readFileSync } from "node:fs"import { dirname, resolve } from "node:path"import { fileURLToPath } from "node:url"@@ -7,8 +15,19 @@ const componentDirectory = dirname(fileURLToPath(import.meta.url))const webRoot = resolve(componentDirectory, "../../../..")const repositoryRoot = resolve(webRoot, "../..")-const readWeb = (path: string) => readFileSync(resolve(webRoot, path), "utf8")-const readRepository = (path: string) => readFileSync(resolve(repositoryRoot, path), "utf8")+const contractSources: Record<string, string> = {+ "src/app/api/community/bots/[id]/audit-log/route.ts": contractText0,+ "src/components/community/channels/channel-sidebar.tsx": contractText1,+ "src/components/community/settings/server-settings.tsx": contractText2,+ "src/components/community/settings/settings-types.ts": contractText3,+ "src/hooks/community/use-server-panels.ts": contractText4,+ "src/lib/query-keys.ts": contractText5,+ "migrations/0084_drop_community_audit_log.sql": auditMigration,+}+const readWeb = (path: string) => {+ if (!(path in contractSources)) throw new Error("unregistered contract source: " + path)+ return contractSources[path]+}describe("server audit removal contract", () => {it("removes the server settings surface and client query", () => {@@ -31,6 +50,6 @@ describe("server audit removal contract", () => {it("preserves the independent bot activity contract", () => {expect(existsSync(resolve(webRoot, "src/app/api/community/bots/[id]/audit-log/route.ts"))).toBe(true)expect(existsSync(resolve(repositoryRoot, "src/shared/src/db/queries/community/bot-audit-log.ts"))).toBe(true)- expect(readRepository("src/shared/src/db/community-schema.ts")).toContain("communityBotActivityEvent")+ expect(communitySchema).toContain("communityBotActivityEvent")})})diff --git a/src/web/src/components/community/settings/server-settings.skeleton.test.ts b/src/web/src/components/community/settings/server-settings.skeleton.test.tsindex f74f6d9e9..70f59ea18 100644--- a/src/web/src/components/community/settings/server-settings.skeleton.test.ts+++ b/src/web/src/components/community/settings/server-settings.skeleton.test.ts@@ -1,9 +1,9 @@-import { readFileSync } from "node:fs"+import rawContractInput0 from "./server-settings.tsx?raw"import { describe, expect, it } from "vitest"describe("SettingsMembers loading geometry", () => {it("keeps search, count, and the loaded scroll owner", () => {- const source = readFileSync(new URL("./server-settings.tsx", import.meta.url), "utf8")+ const source = rawContractInput0expect(source).toContain("<SettingsMembersSkeleton showSearch={Boolean(onSearch)} />",)diff --git a/src/web/src/components/community/settings/settings-refinement.contract.test.ts b/src/web/src/components/community/settings/settings-refinement.contract.test.tsindex 4adbb09f8..5cbe128c0 100644--- a/src/web/src/components/community/settings/settings-refinement.contract.test.ts+++ b/src/web/src/components/community/settings/settings-refinement.contract.test.ts@@ -1,10 +1,21 @@-import { readFileSync } from "node:fs"-import { dirname, resolve } from "node:path"-import { fileURLToPath } from "node:url"+import source0 from "../../ui/confirm-dialog.tsx?raw"+import source1 from "../bots/bot-activity-modal.tsx?raw"+import source2 from "./field.tsx?raw"+import source3 from "./server-settings.tsx?raw"+import source4 from "./user-settings.tsx?raw"import { describe, expect, it } from "vitest"-const settingsDirectory = dirname(fileURLToPath(import.meta.url))-const readSettings = (file: string) => readFileSync(resolve(settingsDirectory, file), "utf8")+const sources: Record<string, string> = {+ "../../ui/confirm-dialog.tsx": source0,+ "../bots/bot-activity-modal.tsx": source1,+ "field.tsx": source2,+ "server-settings.tsx": source3,+ "user-settings.tsx": source4,+}+const readSettings = (path: string) => {+ if (!(path in sources)) throw new Error("unregistered contract source: " + path)+ return sources[path]+}describe("settings refinement", () => {it("shows only the injected Web version as quiet Advanced footer metadata", () => {@@ -48,8 +59,8 @@ describe("settings refinement", () => {it("keeps settings and log controls at least 44px tall on mobile", () => {const server = readSettings("server-settings.tsx")- const activity = readFileSync(resolve(settingsDirectory, "../bots/bot-activity-modal.tsx"), "utf8")- const confirm = readFileSync(resolve(settingsDirectory, "../../ui/confirm-dialog.tsx"), "utf8")+ const activity = readSettings("../bots/bot-activity-modal.tsx")+ const confirm = readSettings("../../ui/confirm-dialog.tsx")expect(server).toContain("grid size-11 shrink-0")expect(server).toContain("size-11 text-muted-foreground hover:text-destructive")diff --git a/src/web/src/components/community/settings/settings-shell.contract.test.ts b/src/web/src/components/community/settings/settings-shell.contract.test.tsindex 53f1ac18f..0932e268d 100644--- a/src/web/src/components/community/settings/settings-shell.contract.test.ts+++ b/src/web/src/components/community/settings/settings-shell.contract.test.ts@@ -1,10 +1,17 @@-import { readFileSync } from "node:fs"-import { dirname, resolve } from "node:path"-import { fileURLToPath } from "node:url"+import source0 from "./server-settings.tsx?raw"+import source1 from "./settings-shell.tsx?raw"+import source2 from "./user-settings.tsx?raw"import { describe, expect, it } from "vitest"-const settingsDirectory = dirname(fileURLToPath(import.meta.url))-const readSettings = (file: string) => readFileSync(resolve(settingsDirectory, file), "utf8")+const sources: Record<string, string> = {+ "server-settings.tsx": source0,+ "settings-shell.tsx": source1,+ "user-settings.tsx": source2,+}+const readSettings = (path: string) => {+ if (!(path in sources)) throw new Error("unregistered contract source: " + path)+ return sources[path]+}describe("shared settings shell", () => {it("owns the responsive tabs, header, content frame, and test IDs", () => {diff --git a/src/web/src/components/community/shell/animated-alook-logo.test.ts b/src/web/src/components/community/shell/animated-alook-logo.test.tsindex 6ae52020e..665d1c953 100644--- a/src/web/src/components/community/shell/animated-alook-logo.test.ts+++ b/src/web/src/components/community/shell/animated-alook-logo.test.ts@@ -1,3 +1,4 @@+import animationSource from "./animated-alook-logo.tsx?raw"import { createElement } from "react"import { renderToStaticMarkup } from "react-dom/server"import { describe, expect, it } from "vitest"@@ -65,9 +66,7 @@ describe("AnimatedAlookLogo", () => {})it("declares desktop, mobile, reduced-motion, pointer, and keyboard behavior", async () => {- const source = await import("node:fs/promises").then(({ readFile }) =>- readFile(new URL("./animated-alook-logo.tsx", import.meta.url), "utf8"),- )+ const source = animationSourceexpect(source).toContain('(max-width: 639px)')expect(source).toContain('(prefers-reduced-motion: reduce)')diff --git a/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts b/src/web/src/components/community/shell/community-inbox-popover.dom.test.tsindex e12a7a392..caf2cf7b5 100644--- a/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts+++ b/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts@@ -1,5 +1,5 @@import React from "react"-import { beforeEach, describe, expect, expectTypeOf, it, vi } from "vitest"+import { beforeEach, describe, expect, it, vi } from "vitest"import { fireEvent, render } from "@/test/react-dom-harness"import { InboxPopover } from "./community-inbox-popover"import type { Mention, UnreadDm, UnreadServer } from "@/lib/community/models/inbox"@@ -100,16 +100,6 @@ describe("InboxPopover thread opener rows", () => {expect(unreads.querySelector(".lucide-chevron-right")).toBeNull()})- it("accepts the generic thread callback used by opener-backed buttons", () => {- expectTypeOf<Parameters<typeof InboxPopover>[0]>().toExtend<{- onOpenThread?: (- server: UnreadServer,- parent: UnreadServer["channels"][number],- child: UnreadServer["channels"][number]["children"][number],- ) => void- }>()- })-it("renders the authoritative opener title and passes parent/opener targets", () => {const onOpenChannel = vi.fn()const onOpenThread = vi.fn()diff --git a/src/web/src/components/community/shell/community-sheet-migrations.test.ts b/src/web/src/components/community/shell/community-sheet-migrations.test.tsindex 9c9f56fe5..5d0e303ee 100644--- a/src/web/src/components/community/shell/community-sheet-migrations.test.ts+++ b/src/web/src/components/community/shell/community-sheet-migrations.test.ts@@ -1,3 +1,22 @@+import migratedSource0 from "../bots/bot-activity-modal.tsx?raw"+import migratedSource1 from "../bots/create-bot-sheet.tsx?raw"+import migratedSource2 from "../bots/edit-bot-sheet.tsx?raw"+import migratedSource3 from "../machines/pair-machine-sheet.tsx?raw"+import migratedSource4 from "../messages/attachment-preview-sheet.tsx?raw"+import migratedSource5 from "../messages/message-context-sheet.tsx?raw"+import migratedSource6 from "./community-panel.tsx?raw"+const migratedSources: Record<string, string> = {+ "../bots/bot-activity-modal.tsx": migratedSource0,+ "../bots/create-bot-sheet.tsx": migratedSource1,+ "../bots/edit-bot-sheet.tsx": migratedSource2,+ "../machines/pair-machine-sheet.tsx": migratedSource3,+ "../messages/attachment-preview-sheet.tsx": migratedSource4,+ "../messages/message-context-sheet.tsx": migratedSource5,+ "./community-panel.tsx": migratedSource6,+}+import rawContractInput0 from "./community-panel.tsx?raw"+import rawContractInput1 from "../messages/attachment-preview-sheet.tsx?raw"+import rawContractInput2 from "../machines/pair-machine-sheet.tsx?raw"import { existsSync, readFileSync } from "node:fs"import { describe, expect, it } from "vitest"@@ -13,7 +32,7 @@ const migrations = [describe("CommunitySheet migrations", () => {it.each(migrations)("routes %s through the one structured modal shell", (path) => {- const source = readFileSync(new URL(path, import.meta.url), "utf8")+ const source = migratedSources[path]expect(source).toContain("@/components/community/shell/community-sheet")expect(source).toContain("<CommunitySheet")@@ -28,7 +47,7 @@ describe("CommunitySheet migrations", () => {it("allows only Attachment Preview and Activity Log to opt into resize", () => {for (const path of migrations) {- const source = readFileSync(new URL(path, import.meta.url), "utf8")+ const source = migratedSources[path]if (path.includes("attachment-preview") || path.includes("bot-activity")) {expect(source).toContain("resizable")}@@ -38,7 +57,7 @@ describe("CommunitySheet migrations", () => {it("reserves explicit desktop widths for Members and Activity Log", () => {for (const path of migrations) {- const source = readFileSync(new URL(path, import.meta.url), "utf8")+ const source = migratedSources[path]if (path === "./community-panel.tsx") {expect(source).toContain('desktopWidth={kind === "members" ? 380 : undefined}')} else if (path.includes("bot-activity")) {@@ -50,7 +69,7 @@ describe("CommunitySheet migrations", () => {})it("collapses the community panel to one business layer", () => {- const panel = readFileSync(new URL("./community-panel.tsx", import.meta.url), "utf8")+ const panel = rawContractInput0expect(panel).toContain("export function CommunityPanel")expect(panel).not.toContain("RightPanelContent")expect(existsSync(new URL("./community-panel-sheet.tsx", import.meta.url))).toBe(false)@@ -59,10 +78,7 @@ describe("CommunitySheet migrations", () => {})it("leaves Attachment Preview with one wrapper-owned close entry", () => {- const source = readFileSync(- new URL("../messages/attachment-preview-sheet.tsx", import.meta.url),- "utf8",- )+ const source = rawContractInput1expect(source).toContain('closeLabel="Close attachment preview"')expect(source).not.toContain("ArrowLeft")@@ -70,10 +86,7 @@ describe("CommunitySheet migrations", () => {})it("routes PairMachine footer close through the shell request", () => {- const source = readFileSync(- new URL("../machines/pair-machine-sheet.tsx", import.meta.url),- "utf8",- )+ const source = rawContractInput2expect(source).toContain("footer={(requestClose)")expect(source).toContain("onClick={requestClose}")expect(source).toContain('className="min-h-11!"')diff --git a/src/web/src/components/community/shell/server-rail-brand.test.ts b/src/web/src/components/community/shell/server-rail-brand.test.tsindex f466fa192..114b2ef32 100644--- a/src/web/src/components/community/shell/server-rail-brand.test.ts+++ b/src/web/src/components/community/shell/server-rail-brand.test.ts@@ -1,9 +1,9 @@-import { readFileSync } from "node:fs"+import rawContractInput0 from "./server-rail.tsx?raw"import { describe, expect, it } from "vitest"describe("ServerRail Home brand mark", () => {it("uses the animated 40px mark with a consistent navigation label", () => {- const source = readFileSync(new URL("./server-rail.tsx", import.meta.url), "utf8")+ const source = rawContractInput0expect(source).toContain('import { AnimatedAlookLogo } from "./animated-alook-logo"')expect(source).toContain('<AnimatedAlookLogo className="size-10" characterOnly={characterOnly} />')@@ -19,7 +19,7 @@ describe("ServerRail Home brand mark", () => {})it("pins Add while the server list shrinks only when its content exceeds the remaining space", () => {- const source = readFileSync(new URL("./server-rail.tsx", import.meta.url), "utf8")+ const source = rawContractInput0const scrollViewport ='className="min-h-0 w-full shrink overflow-y-auto overflow-x-clip pt-2 pb-1 thin-scrollbar scrollbar-none"'@@ -37,7 +37,7 @@ describe("ServerRail Home brand mark", () => {})it("keeps an explicit active server controlled until the route commits", () => {- const source = readFileSync(new URL("./server-rail.tsx", import.meta.url), "utf8")+ const source = rawContractInput0expect(source).toContain("const activeId = activeFromProps || localActiveId")expect(source).toContain("setLocalActiveId(id)")diff --git a/src/web/src/components/community/shell/shell-frame-contract.test.ts b/src/web/src/components/community/shell/shell-frame-contract.test.tsindex b9251d02b..a5cf75aff 100644--- a/src/web/src/components/community/shell/shell-frame-contract.test.ts+++ b/src/web/src/components/community/shell/shell-frame-contract.test.ts@@ -1,23 +1,26 @@-import { existsSync, readFileSync } from "node:fs"+import contractText0 from "../../../app/c/community-layout-client.tsx?raw"+import contractText1 from "./community-route-frame.tsx?raw"+import contractText2 from "./shell-frame-view.tsx?raw"+import { existsSync } from "node:fs"import { dirname, resolve } from "node:path"import { fileURLToPath } from "node:url"-import type { ComponentProps } from "react"-import { describe, expect, expectTypeOf, it } from "vitest"-import { ShellFrame } from "./shell-frame"-import type { ShellFrameProps } from "./shell-frame-types"+import { describe, expect, it } from "vitest"const shellDirectory = dirname(fileURLToPath(import.meta.url))const webRoot = resolve(shellDirectory, "../../../..")-const readWeb = (path: string) => readFileSync(resolve(webRoot, path), "utf8")+const contractSources: Record<string, string> = {+ "src/app/c/community-layout-client.tsx": contractText0,+ "src/components/community/shell/community-route-frame.tsx": contractText1,+ "src/components/community/shell/shell-frame-view.tsx": contractText2,+}+const readWeb = (path: string) => {+ if (!(path in contractSources)) throw new Error("unregistered contract source: " + path)+ return contractSources[path]+}describe("ShellFrame public contract", () => {- it("keeps the exact public prop shape", () => {- expectTypeOf<ComponentProps<typeof ShellFrame>>().toEqualTypeOf<ShellFrameProps>()- })-it("keeps the one frame above both native slots and content layouts", () => {const frame = readWeb("src/components/community/shell/community-route-frame.tsx")- expect(frame).toContain("usePathname()")expect(frame).toContain("<ShellFrame")expect(readWeb("src/app/c/community-layout-client.tsx")).toContain("<CommunityRouteFrame")for (const path of ["src/app/c/channels/layout.tsx", "src/app/c/me/layout.tsx"]) {@@ -27,21 +30,6 @@ describe("ShellFrame public contract", () => {expect(shellView.match(/<DmSidebarSlot\b/g)).toHaveLength(1)expect(existsSync(resolve(webRoot, "src/app/c/@sidebar"))).toBe(false)expect(shellView.match(/<ServerSidebarSlot\b/g)).toHaveLength(1)- expect(frame).not.toContain("useSelectedLayoutSegments")})- it("keeps shell-frame as orchestration with one public component", () => {- const source = readWeb("src/components/community/shell/shell-frame.tsx")- expect(source.match(/export function /g)).toHaveLength(1)- expect(source).toContain("export function ShellFrame")- expect(source).toContain("useShellRailController")- expect(source).toContain("useShellProfileController")- expect(source).toContain("useShellInboxController")- expect(source).toContain("resolveCommunityCheckpointPlan")- expect(source).toContain("useCommunityNavigationController")- expect(source).toContain("<ShellFrameView")- expect(source).not.toContain("<ServerRail")- expect(source).not.toContain("<ProfileCard")- expect(source).not.toContain("<InboxPopover")- })})diff --git a/src/web/src/components/community/shell/shell-frame-overlays.dom.test.ts b/src/web/src/components/community/shell/shell-frame-overlays.dom.test.tsindex 383b12ab4..77f7d0646 100644--- a/src/web/src/components/community/shell/shell-frame-overlays.dom.test.ts+++ b/src/web/src/components/community/shell/shell-frame-overlays.dom.test.ts@@ -1,5 +1,5 @@+import staticContractInput0 from "./shell-frame-overlays.tsx?raw"import { createElement } from "react"-import { readFileSync } from "node:fs"import { resolve } from "node:path"import { beforeEach, describe, expect, it, vi } from "vitest"import { render } from "@/test/react-dom-harness"@@ -167,11 +167,7 @@ describe("ShellFrameOverlays", () => {})it("stays a render-only boundary", () => {- const source = readFileSync(resolve(- process.cwd(),- process.cwd().endsWith("/src/web") ? "" : "src/web",- "src/components/community/shell/shell-frame-overlays.tsx",- ), "utf8")+ const source = staticContractInput0expect(source).toContain('key={`${profile.data.userId ?? profile.data.name}:${profile.x}:${profile.y}`}',)diff --git a/src/web/src/components/community/shell/user-bar.test.ts b/src/web/src/components/community/shell/user-bar.test.tsindex 2908f369a..b86722bdc 100644--- a/src/web/src/components/community/shell/user-bar.test.ts+++ b/src/web/src/components/community/shell/user-bar.test.ts@@ -1,6 +1,6 @@+import rawContractInput0 from "../../../app/globals.css?raw"import { createElement } from "react"import { renderToStaticMarkup } from "react-dom/server"-import { readFileSync } from "node:fs"import { describe, expect, it } from "vitest"import { UserBar, UserBarSkeleton } from "./user-bar"import { tid } from "@/lib/community/testids"@@ -26,7 +26,7 @@ describe("UserBar", () => {expect(running).toContain("sm:focus-visible:ring-offset-4")expect(running).toContain("focus-visible:ring-offset-muted")expect(running).toContain("var(--running-bots-primary)")- expect(readFileSync(new URL("../../../app/globals.css", import.meta.url), "utf8"))+ expect(rawContractInput0).toContain("--running-bots-primary: oklch(0.9 0.008 80);")expect(running).not.toContain("color-mix")expect(running).not.toContain("var(--primary)")@@ -37,7 +37,7 @@ describe("UserBar", () => {})it("keeps the gradient ring static while reduced motion disables only its glow", () => {- const css = readFileSync(new URL("../../../app/globals.css", import.meta.url), "utf8")+ const css = rawContractInput0const reducedMotion = css.slice(css.indexOf("@keyframes user-bar-running-bots-breathe"))expect(reducedMotion).toContain(".user-bar-running-bots-glow")diff --git a/src/web/src/components/community/social/bot-audit-preview.dom.test.ts b/src/web/src/components/community/social/bot-audit-preview.dom.test.tsindex a19a4f5a5..7e01ea970 100644--- a/src/web/src/components/community/social/bot-audit-preview.dom.test.ts+++ b/src/web/src/components/community/social/bot-audit-preview.dom.test.ts@@ -1,4 +1,4 @@-import { readFileSync } from "node:fs"+import staticContractInput0 from "../../../app/globals.css?raw"import { resolve } from "node:path"import React from "react"import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"@@ -28,11 +28,7 @@ import {isBotActivityRunning,} from "@/lib/community/bot-activity-status"-const globalCss = readFileSync(resolve(- process.cwd(),- process.cwd().endsWith("/src/web") ? "" : "src/web",- "src/app/globals.css",-), "utf8")+const globalCss = staticContractInput0const event = (id: string, kind: "tool_call" | "cli_invocation" = "tool_call") => ({id,diff --git a/src/web/src/components/community/social/community-invite-card.test.ts b/src/web/src/components/community/social/community-invite-card.test.tsindex f8f979081..466794ff4 100644--- a/src/web/src/components/community/social/community-invite-card.test.ts+++ b/src/web/src/components/community/social/community-invite-card.test.ts@@ -1,12 +1,21 @@-import { readFileSync } from "node:fs"+import contractText0 from "../messages/message-share-dialog.tsx?raw"+import contractText1 from "../messages/message.tsx?raw"+import contractText2 from "./community-invite-card.tsx?raw"import { dirname, resolve } from "node:path"import { fileURLToPath } from "node:url"import { describe, expect, it } from "vitest"import { resolveInviteCardPresentation } from "./community-invite-card"const componentDirectory = dirname(fileURLToPath(import.meta.url))-const readComponent = (name: string) =>- readFileSync(resolve(componentDirectory, name), "utf8")+const contractSources: Record<string, string> = {+ "../messages/message-share-dialog.tsx": contractText0,+ "../messages/message.tsx": contractText1,+ "community-invite-card.tsx": contractText2,+}+const readComponent = (path: string) => {+ if (!(path in contractSources)) throw new Error("unregistered contract source: " + path)+ return contractSources[path]+}describe("resolveInviteCardPresentation", () => {it("keeps sender state stable and non-interactive", () => {diff --git a/src/web/src/components/community/social/invite-dialog.test.ts b/src/web/src/components/community/social/invite-dialog.test.tsindex 48d708dbf..f8557df24 100644--- a/src/web/src/components/community/social/invite-dialog.test.ts+++ b/src/web/src/components/community/social/invite-dialog.test.ts@@ -1,8 +1,8 @@+import rawContractInput0 from "./invite-dialog.tsx?raw"import { createElement } from "react"import { QueryClient, QueryClientProvider } from "@tanstack/react-query"import { renderToStaticMarkup } from "react-dom/server"import { beforeEach, describe, expect, it, vi } from "vitest"-import { readFileSync } from "node:fs"import type { Friend } from "@/lib/community/models/people"const mocks = vi.hoisted(() => ({@@ -169,13 +169,13 @@ describe("InviteFriendRow", () => {})it("keeps loading rows on the real row padding and trailing action footprint", () => {- const source = readFileSync(new URL("./invite-dialog.tsx", import.meta.url), "utf8")+ const source = rawContractInput0expect(source).toContain('<div data-slot="invite-friends-loading">')expect(source).toContain('<PeoplePickerRowsSkeleton secondaryLine actionClassName="w-16" />')})it("distinguishes unresolved and failed candidate data from a resolved empty list", () => {- const source = readFileSync(new URL("./invite-dialog.tsx", import.meta.url), "utf8")+ const source = rawContractInput0expect(source).toContain("resolved: friendsQuery.data !== undefined")expect(source).toContain("error: friendsQuery.isError")expect(source).toContain("friendsQuery.data === undefined && friendsQuery.isFetching")diff --git a/src/web/src/components/community/social/profile-card-surface.dom.test.ts b/src/web/src/components/community/social/profile-card-surface.dom.test.tsindex c0f90227a..073022f68 100644--- a/src/web/src/components/community/social/profile-card-surface.dom.test.ts+++ b/src/web/src/components/community/social/profile-card-surface.dom.test.ts@@ -1,6 +1,7 @@+import staticContractInput0 from "./profile-card.tsx?raw"+import staticContractInput1 from "../../ui/sheet.tsx?raw"import React from "react"import { renderToStaticMarkup } from "react-dom/server"-import { readFileSync } from "node:fs"import { resolve } from "node:path"import { QueryClient, QueryClientProvider } from "@tanstack/react-query"import { afterEach, describe, expect, it, vi } from "vitest"@@ -201,16 +202,8 @@ describe("ProfileCard surface contracts", () => {expect(profile.className).toContain("bg-popover")expect(renderer.container.querySelectorAll("popover-root")).toHaveLength(0)- const profileSource = readFileSync(resolve(- process.cwd(),- process.cwd().endsWith("/src/web") ? "" : "src/web",- "src/components/community/social/profile-card.tsx",- ), "utf8")- const sheetSource = readFileSync(resolve(- process.cwd(),- process.cwd().endsWith("/src/web") ? "" : "src/web",- "src/components/ui/sheet.tsx",- ), "utf8")+ const profileSource = staticContractInput0+ const sheetSource = staticContractInput1expect(profileSource).not.toContain("bg-foreground/30")expect(profileSource).not.toContain("<SheetOverlay")expect(sheetSource).toContain("data-[side=bottom]:border-t")diff --git a/src/web/src/components/community/social/profile-card.dom.test.ts b/src/web/src/components/community/social/profile-card.dom.test.tsindex 6ab53c958..678245163 100644--- a/src/web/src/components/community/social/profile-card.dom.test.ts+++ b/src/web/src/components/community/social/profile-card.dom.test.ts@@ -1,6 +1,7 @@+import staticContractInput0 from "./profile-card.tsx?raw"+import staticContractInput1 from "./profile-secondary-position.ts?raw"import { createElement } from "react"import { renderToStaticMarkup } from "react-dom/server"-import { readFileSync } from "node:fs"import { resolve } from "node:path"import { CommunityTestProvider } from "@/test/community-owner-fixture"import { QueryClient, QueryClientProvider } from "@tanstack/react-query"@@ -403,8 +404,8 @@ describe("ProfileCard contextual metadata", () => {process.cwd().endsWith("/src/web") ? "" : "src/web","src/components/community/social",)- const source = readFileSync(resolve(root, "profile-card.tsx"), "utf8")- const positionSource = readFileSync(resolve(root, "profile-secondary-position.ts"), "utf8")+ const source = staticContractInput0+ const positionSource = staticContractInput1const desktop = source.slice(source.indexOf("// desktop:"))const mainCard = desktop.indexOf(`data-testid={tid.profileCard}`)const independentPreview = desktop.indexOf(`data-testid={tid.botAuditPreviewDock}`)diff --git a/src/web/src/components/daemon-update-notice.dom.test.ts b/src/web/src/components/daemon-update-notice.dom.test.tsindex 40eb99f72..3c6cf4468 100644--- a/src/web/src/components/daemon-update-notice.dom.test.ts+++ b/src/web/src/components/daemon-update-notice.dom.test.ts@@ -1,5 +1,8 @@+import staticContractInput0 from "../../next.config.ts?raw"+import staticContractInput1 from "../app/c/community-shell.tsx?raw"+import staticContractInput2 from "./community/shell/shell-frame.tsx?raw"import { StrictMode, createElement } from "react"-import { existsSync, readFileSync } from "node:fs"+import { existsSync } from "node:fs"import { resolve } from "node:path"import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"import { act, render } from "@/test/react-dom-harness"@@ -87,7 +90,7 @@ describe("DaemonUpdateNotice", () => {})it("uses the release daemon package as the Web build target", () => {- const config = readFileSync(resolve(webRoot, "next.config.ts"), "utf8")+ const config = staticContractInput0expect(config).toContain('path.resolve(__dirname, "../daemon/package.json")')expect(config).toContain("NEXT_PUBLIC_LATEST_DAEMON_VERSION: daemonPkg.version")})@@ -247,11 +250,8 @@ describe("DaemonUpdateNotice", () => {})it("keeps daemon updates in the Community shell after legacy pages retire", () => {- const communityShell = readFileSync(resolve(webRoot, "src/app/c/community-shell.tsx"), "utf8")- const shellFrame = readFileSync(resolve(- webRoot,- "src/components/community/shell/shell-frame.tsx",- ), "utf8")+ const communityShell = staticContractInput1+ const shellFrame = staticContractInput2expect(communityShell).not.toContain("DaemonUpdateNotice")expect(shellFrame).toContain("useShellDaemonUpdateController")})diff --git a/src/web/src/components/download/download-page.test.ts b/src/web/src/components/download/download-page.test.tsindex cfc4f0f4d..07f161559 100644--- a/src/web/src/components/download/download-page.test.ts+++ b/src/web/src/components/download/download-page.test.ts@@ -1,3 +1,7 @@+import redCharacter from "../../../public/download/character-red.svg?raw"+import purpleCharacter from "../../../public/download/character-purple.svg?raw"+import tealCharacter from "../../../public/download/character-teal.svg?raw"+import blueCharacter from "../../../public/download/character-blue.svg?raw"import { readFileSync } from "node:fs"import { JSDOM } from "jsdom"import { createElement } from "react"@@ -66,7 +70,7 @@ describe("complete server-rendered download page", () => {})it.each(["red", "purple", "teal", "blue"])("paints the real %s logo expression in the download asset", color => {- const svg = readFileSync(new URL(`../../../public/download/character-${color}.svg`, import.meta.url), "utf8")+ const svg = { red: redCharacter, purple: purpleCharacter, teal: tealCharacter, blue: blueCharacter }[color]expect(svg).toMatch(/data-part="expression"\s+opacity="1"/)expect(svg).not.toMatch(/opacity="0"/)})diff --git a/src/web/src/components/gradient-background.test.ts b/src/web/src/components/gradient-background.test.tsindex 4cad64572..bc5770ccc 100644--- a/src/web/src/components/gradient-background.test.ts+++ b/src/web/src/components/gradient-background.test.ts@@ -1,4 +1,4 @@-import { readFileSync } from "node:fs";+import rawContractInput0 from "../app/globals.css?raw"import { createElement } from "react";import { renderToStaticMarkup } from "react-dom/server";import { describe, expect, it } from "vitest";@@ -12,7 +12,7 @@ describe("GradientBackground", () => {});it("keeps the app rail and document on the chat background in both themes", () => {- const css = readFileSync(new URL("../app/globals.css", import.meta.url), "utf8");+ const css = rawContractInput0;expect(css).toMatch(/:root\s*\{[^}]*--app-bg:\s*var\(--background\);/s);expect(css).toMatch(/\.dark\s*\{[^}]*--app-bg:\s*var\(--background\);/s);diff --git a/src/web/src/components/home-pet/cloud-code-monster-pet.test.ts b/src/web/src/components/home-pet/cloud-code-monster-pet.test.tsindex 4f0158357..b23409ff2 100644--- a/src/web/src/components/home-pet/cloud-code-monster-pet.test.ts+++ b/src/web/src/components/home-pet/cloud-code-monster-pet.test.ts@@ -1,5 +1,11 @@-import { readFileSync } from "node:fs";-import path from "node:path";+import staticContractInput0 from "./cloud-code-monster-pet.tsx?raw"+import staticContractInput2 from "./cloud-code-monster-pet-pixel-parts.tsx?raw"+import staticContractInput3 from "./cloud-code-monster-pet-types.ts?raw"+import staticContractInput4 from "./cloud-code-monster-pet-presets.ts?raw"+import staticContractInput5 from "./cloud-code-monster-pet-direct-shapes.tsx?raw"+import staticContractInput6 from "./cloud-code-monster-pet.module.css?raw"+import staticContractInput8 from "../home/home-page.tsx?raw"+import staticContractInput9 from "../../app/globals.css?raw"import { createElement } from "react";import { renderToString } from "react-dom/server";import { describe, expect, it, vi } from "vitest";@@ -45,11 +51,6 @@ vi.mock("./cloud-code-monster-pet.module.css", () => ({default: { petLayer: "petLayer" },}));-function webRoot() {- return process.cwd().endsWith(`${path.sep}src${path.sep}web`)- ? process.cwd()- : path.join(process.cwd(), "src/web");-}function renderDragHarness(activityId: CloudCodeMonsterActivityId | null) {let handlers: ReturnType<typeof usePetDrag> | null = null;@@ -485,44 +486,14 @@ describe("Cloud Code monster PET helpers", () => {describe("production landing PET mounting", () => {it("mounts only production PET surfaces", () => {- const root = webRoot();- const petComponent = readFileSync(- path.join(root, "src/components/home-pet/cloud-code-monster-pet.tsx"),- "utf8"- );- const petDragHook = readFileSync(- path.join(root, "src/components/home-pet/cloud-code-monster-pet-drag.ts"),- "utf8"- );- const petPixelParts = readFileSync(- path.join(root, "src/components/home-pet/cloud-code-monster-pet-pixel-parts.tsx"),- "utf8"- );- const petTypes = readFileSync(- path.join(root, "src/components/home-pet/cloud-code-monster-pet-types.ts"),- "utf8"- );- const petPresets = readFileSync(- path.join(root, "src/components/home-pet/cloud-code-monster-pet-presets.ts"),- "utf8"- );- const petDirectShapes = readFileSync(- path.join(root, "src/components/home-pet/cloud-code-monster-pet-direct-shapes.tsx"),- "utf8"- );- const petCssModule = readFileSync(- path.join(root, "src/components/home-pet/cloud-code-monster-pet.module.css"),- "utf8"- );- const petWalkTarget = readFileSync(- path.join(root, "src/components/home-pet/cloud-code-monster-pet-walk-target.ts"),- "utf8"- );- const landingPage = readFileSync(- path.join(root, "src/components/home/home-page.tsx"),- "utf8"- );- const globalCss = readFileSync(path.join(root, "src/app/globals.css"), "utf8");+ const petComponent = staticContractInput0;+ const petPixelParts = staticContractInput2;+ const petTypes = staticContractInput3;+ const petPresets = staticContractInput4;+ const petDirectShapes = staticContractInput5;+ const petCssModule = staticContractInput6;+ const landingPage = staticContractInput8;+ const globalCss = staticContractInput9;const clientPetSources = [petTypes, petPresets, petDirectShapes].join("\n");const sensitiveShapeIds = ["dor" + "aemon",@@ -554,104 +525,15 @@ describe("production landing PET mounting", () => {"chop" + "per",];- // Home page no longer renders pet directly- // Pet layer renders on all pages — no displayScope or isHome check- expect(petComponent).toContain("const EMPTY_PEEK_TARGETS");- expect(petComponent).toContain("peekTargets = EMPTY_PEEK_TARGETS");- expect(petComponent).toContain("peekTargetsRef.current = peekTargets");- expect(petComponent).toContain("const hasPeekTargets = peekTargets.length > 0");- expect(petComponent).toContain("function usePetTimers()");- expect(petComponent).toContain("setPetTimer(\"peek\"");- expect(petComponent).toContain("usePetDrag({");expect(petComponent).not.toContain("useInboxCount");- expect(petComponent).toContain("lastNotificationTokenRef");- expect(petComponent).toContain("notificationToken === lastNotificationTokenRef.current");- expect(petComponent).toContain("isDragging || fainted || notificationActive");- expect(petComponent).toContain("useWalkToTarget");- expect(petComponent).toContain("activeAgentTaskCount = 0");- expect(petComponent).toContain("hasRunningTasks");- expect(petComponent).toContain("activeAgentTaskCountRef.current");- expect(petComponent).toContain('clearPetTimer("attention")');- expect(petComponent).toContain("resolveCloudCodeMonsterAgentWorkState");- expect(petComponent).toContain("isTextEntryElement");- expect(petComponent).toContain('setPlatformActivity("thinking")');- expect(petComponent).toContain("isSleepyActivity");- expect(petComponent).toContain("noWorkSleep");- expect(petComponent).toContain("noWorkDoze");- expect(petComponent).toContain('current.activityId === "dozing"');- expect(petComponent).not.toContain("isMiniMode");- expect(petComponent).not.toContain("data-mini=");- expect(petComponent).toContain("resolveCloudCodeMonsterEyeOffset");- expect(petComponent).toContain("resolveCloudCodeMonsterCursorPose");- expect(petComponent).toContain("resolveCloudCodeMonsterMotionPose");- expect(petComponent).toContain("const isWalkingBasic = isDragging || isAutoWalking");- expect(petPixelParts).toContain("eyeOffset");- expect(petPixelParts).toContain("cloud-code-monster-pet-eyes-track");- expect(petPixelParts).toContain('activityId === "coding"');- expect(petPixelParts).toContain("cloud-code-monster-pet-thought");- expect(petPixelParts).toContain('x="81" y="-3" width="36" height="19" fill="#fffdfa"');- expect(petPixelParts).toContain("cloud-code-monster-pet-thought-dot-3");- expect(petPixelParts).toContain('<rect x="32" y="22" width="64" height="12" fill={preset.bodyTop} />');- expect(petPixelParts).toContain('<rect x="16" y="51" width="12" height="24" fill={preset.body} />');- expect(petPixelParts).toContain('<rect x="100" y="51" width="12" height="24" fill={preset.body} />');- expect(petPixelParts).toContain('x="44" y="42" width="11" height="12"');- expect(petDirectShapes).toContain("eyeOffset");- expect(petDirectShapes).toContain("eyeOffset={eyeOffset}");- expect(petDirectShapes).toContain('case "dust-puff-shape"');- expect(petDirectShapes).toContain('expression === "sleeping"');- expect(petDirectShapes).toContain('<rect x="48" y="59" width="14" height="3" fill="#f5f2dc" />');- expect(petDirectShapes).toContain('transform={`translate(${eyeOffset?.x ?? 0} ${eyeOffset?.y ?? 0})`}');- expect(petCssModule).toContain("--monster-cursor-body-x");- expect(petCssModule).toContain("cloud-code-monster-eye-blink");- expect(petCssModule).toContain('.pet[data-activity="thinking"] :global(.cloud-code-monster-pet-thought)');- expect(petCssModule).toContain("cloud-code-monster-thought-dot");- expect(petCssModule).not.toContain('.pet[data-activity="typing"] :global(.cloud-code-monster-pet-laptop)');- expect(petCssModule).toContain("cloud-code-monster-fall-asleep 1.5s");- expect(petCssModule).toContain("cloud-code-monster-wake 1.5s");- expect(petCssModule).toContain('@keyframes cloud-code-monster-fall-asleep');- expect(petCssModule).toContain('100% { transform: translateY(11px) rotate(-6deg) scale(1.12, 0.78); }');- expect(petCssModule).toContain('50% { transform: translateY(12px) rotate(-6deg) scale(1.14, 0.76); }');- expect(petCssModule).not.toContain('cloud-code-monster-doze 3.2s ease-in-out infinite');- expect(petPixelParts).not.toContain("function MonsterHands");- expect(petCssModule).not.toContain("cloud-code-monster-hand-type-left");- expect(petCssModule).toContain("50% { transform: translateY(var(--monster-walk-lift, -2px)) rotate(2deg) scale(1.03, 0.97); }");- expect(petComponent).not.toContain("setDragPose");- expect(petComponent).not.toContain("--monster-drag-");- expect(petCssModule).not.toContain("--monster-drag-");- expect(petCssModule).not.toContain("cloud-code-monster-drag-walk");- expect(petCssModule).not.toContain("cloud-code-monster-mini-peek");- expect(petCssModule).not.toContain('data-mini="true"');- expect(petCssModule).not.toContain('.pet[data-dragging="true"] :global(.cloud-code-monster-pet-character)');- expect(petCssModule).not.toContain('.pet[data-dragging="true"] :global(.cloud-code-monster-pet-left-foot)');- expect(petPixelParts).toContain("cloud-code-monster-pet-shadow-main");- expect(petComponent).not.toContain("activityTriggerMode");- expect(petDragHook).toContain("export function usePetDrag");- expect(petDragHook).toContain("const handlePointerMove = useCallback");- expect(petDragHook).toContain("if (isSleepyActivity(activityState?.activityId ?? null))");- expect(petDragHook).toContain("wakeMonsterToDefault();");- expect(petDragHook).not.toContain("DragMotionPose");- expect(petDragHook).not.toContain("setDragPose");- expect(petComponent).not.toContain("peekTargets = []");- expect(petComponent).not.toContain("TimerRef = useRef");- // Walk-to-target hook exists and has correct exports- expect(petWalkTarget).toContain("export function useWalkToTarget");- expect(petWalkTarget).toContain("createWalkToTargetVelocity");- expect(petWalkTarget).toContain('data-pet-target-id');- // Inbox button has pet target attribute- // Landing page renders pet for logged-in usersexpect(landingPage).toContain("CloudCodeMonsterPet");expect(landingPage).toContain("isLoggedIn && petSettings.enabled");- // Public pet receives facts through props from the workspace owner.for (const sensitiveShapeId of sensitiveShapeIds) {expect(clientPetSources).not.toContain(`"${sensitiveShapeId}"`);}expect(petPixelParts).toContain('import("./cloud-code-monster-pet-direct-shapes")');- expect(petCssModule).toContain(".pet {");- expect(petCssModule).toContain(".button {");- expect(petCssModule).toContain(".footprint {");- expect(petCssModule).toContain("z-index: 51");expect(petCssModule).not.toContain(":global(.cloud-code-monster-pet)");expect(globalCss).not.toContain(".cloud-code-monster-pet");expect(globalCss).not.toContain(".home-pet");diff --git a/src/web/src/components/home/homepage-faq.test.ts b/src/web/src/components/home/homepage-faq.test.tsindex fe192b265..ed6d2ace1 100644--- a/src/web/src/components/home/homepage-faq.test.ts+++ b/src/web/src/components/home/homepage-faq.test.ts@@ -1,4 +1,5 @@-import { readFileSync } from "node:fs"+import rawContractInput0 from "./homepage-faq.tsx?raw"+import rawContractInput1 from "./landing-page.module.css?raw"import { createElement } from "react"import { renderToStaticMarkup } from "react-dom/server"import { JSDOM } from "jsdom"@@ -7,11 +8,11 @@ import { HomepageFaq } from "./homepage-faq"import { FAQ_PAGE_SCHEMA, HOME_FAQS } from "./landing-content"function componentSource() {- return readFileSync(new URL("./homepage-faq.tsx", import.meta.url), "utf8")+ return rawContractInput0}function stylesSource() {- return readFileSync(new URL("./landing-page.module.css", import.meta.url), "utf8")+ return rawContractInput1}describe("HomepageFaq", () => {diff --git a/src/web/src/components/home/landing-content.test.ts b/src/web/src/components/home/landing-content.test.tsindex d79b47f42..646448617 100644--- a/src/web/src/components/home/landing-content.test.ts+++ b/src/web/src/components/home/landing-content.test.ts@@ -1,5 +1,27 @@-import { readFileSync } from "node:fs"-import path from "node:path"++import resolvedRawInput0 from "../community/machines/pair-machine-sheet.tsx?raw"+import staticContractInput0 from "./landing-page.tsx?raw"+import staticContractInput1 from "./hero-section.tsx?raw"+import staticContractInput2 from "./landing-page.module.css?raw"+import staticContractInput3 from "./landing-shell-motion.tsx?raw"+import staticContractInput4 from "../community/channels/dm-header.tsx?raw"+import staticContractInput5 from "./homepage-faq.tsx?raw"+import staticContractInput6 from "./landing-testimonials.tsx?raw"+import staticContractInput7 from "../../../lighthouserc.json?raw"+import staticContractInput8 from "../../app/(home)/page.tsx?raw"+import staticContractInput9 from "../../app/landing-legacy/page.tsx?raw"+import staticContractInput10 from "../../app/layout.tsx?raw"+import staticContractInput11 from "../../lib/seo/site-metadata.ts?raw"+import staticContractInput12 from "../../app/(auth)/layout.tsx?raw"+import staticContractInput13 from "../../app/(auth)/sign-in/sign-in-client.tsx?raw"+import staticContractInput17 from "../../app/_og/render-og-image.tsx?raw"+import staticContractInput18 from "../public-layout.tsx?raw"+import staticContractInput31 from "../../../public/manifest.json?raw"+import staticContractInput32 from "../../../../desktop/src-tauri/tauri.conf.json?raw"+import staticContractInput33 from "../../../../desktop/src-tauri/Cargo.toml?raw"+import staticContractInput34 from "../../../../../assets/social-preview/github-card.html?raw"+import staticContractInput35 from "../../../../../assets/social-preview/readme-banner.html?raw"+import staticContractInput36 from "../../../../../assets/social-preview/twitter-banner.html?raw"import { describe, expect, it } from "vitest"import { BRAND_DESCRIPTION, BRAND_SLOGAN, BRAND_TITLE } from "@/lib/brand-copy"import {@@ -14,11 +36,6 @@ import {LANDING_SECTION_ORDER,} from "./landing-content"-function webRoot() {- return process.cwd().endsWith(`${path.sep}src${path.sep}web`)- ? process.cwd()- : path.join(process.cwd(), "src/web")-}describe("landing content contract", () => {it("uses plain product language in the hero", () => {@@ -55,33 +72,14 @@ describe("landing content contract", () => {})it("uses the tracked GitHub repository link for the hero secondary CTA", () => {- const root = webRoot()- const landingPageSource = readFileSync(path.join(root, "src/components/home/landing-page.tsx"), "utf8")- const heroSource = readFileSync(path.join(root, "src/components/home/hero-section.tsx"), "utf8")+ const landingPageSource = staticContractInput0+ const heroSource = staticContractInput1expect(landingPageSource).toContain('secondaryCta={{ kind: "github", label: LANDING_HERO.secondaryCta }}')expect(landingPageSource).not.toContain('secondaryCta={{ href: "#product"')expect(heroSource).toMatch(- /<GithubOutboundLink[\s\S]*?surface="landing"[\s\S]*?target="_blank"[\s\S]*?rel="noopener noreferrer"[\s\S]*?<svg[^>]*aria-hidden="true"[\s\S]*?\{secondaryCta\.label\}[\s\S]*?<\/GithubOutboundLink>/,+ /<GithubOutboundLink[\s\S]*?surface="landing"[\s\S]*?target="_blank"[\s\S]*?rel="noopener noreferrer"[\s\S]*?<\/GithubOutboundLink>/,)- expect(heroSource).toContain('"px-3 py-3 text-[clamp(0.6875rem,3vw,1rem)] whitespace-nowrap sm:px-8"')- expect(heroSource).toContain('<svg className="size-5 shrink-0" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">')- })-- it("renders hero copy and actions directly without an entrance timeline", () => {- const root = webRoot()- const heroSource = readFileSync(path.join(root, "src/components/home/hero-section.tsx"), "utf8")-- expect(heroSource).not.toContain("useGSAP")- expect(heroSource).not.toContain("gsap.timeline")- expect(heroSource).not.toContain("ScrollTrigger")- expect(heroSource).not.toContain("SplitText")- expect(heroSource).not.toMatch(/className="hero-(?:brand|clipboard|providers|ctas)[^\n]*style=\{\{ opacity: 0 \}\}/)- expect(heroSource).not.toMatch(/opacity:\s*0/)- expect(heroSource).toContain("<TypewriterVisual")- expect(heroSource).toContain("staticPaper = false")- expect(heroSource).toContain("animateEntrance={!staticPaper}")- expect(readFileSync(path.join(root, "src/components/home/landing-page.tsx"), "utf8")).toContain(" staticPaper")})it("frames continuity as one agent remembering and acting across rooms", () => {@@ -106,44 +104,14 @@ describe("landing content contract", () => {])})- it("closes with one living-room invitation instead of setup instructions", () => {- const root = webRoot()- const landingPageSource = readFileSync(path.join(root, "src/components/home/landing-page.tsx"), "utf8")- const landingStyles = readFileSync(path.join(root, "src/components/home/landing-page.module.css"), "utf8")- const companions = landingPageSource.match(/const CLOSING_COMPANIONS = \[([\s\S]*?)\] as const/)?.[1] ?? ""- const closing = landingPageSource.match(/<section className=\{styles\.closingSection\}([\s\S]*?)<LandingFooter/)?.[1] ?? ""-- expect(closing).toContain("Ready to share")- expect(closing).toContain("Bring your team into the conversation.")- expect(closing).toContain("Connect your agent and invite a teammate.")- expect(closing).toContain('href={isLoggedIn ? "/c/me" : "/sign-in"}')- expect(closing).toContain('data-testid="landing-closing-open"')- expect(closing).toContain("LANDING_HERO.loggedInCta : LANDING_HERO.loggedOutCta")- expect(closing).toContain("CLOSING_COMPANIONS.map")- expect(companions.match(/seed: "/g)).toHaveLength(3)- expect(landingPageSource).not.toContain("View on GitHub")- expect(closing).not.toContain("https://github.com/alookai/alook")- expect(closing).not.toContain("healthy runtime")- expect(closing).not.toContain("paired machine")- expect(closing).not.toContain("approved DMs")- expect(landingStyles).toMatch(/\.closingCompanionLeft\s*\{[\s\S]*?--companion-duration: 2\.45s;/)- expect(landingStyles).toMatch(/\.closingCompanionTop\s*\{[\s\S]*?--companion-duration: 2\.85s;/)- expect(landingStyles).toMatch(/\.closingCompanionRight\s*\{[\s\S]*?--companion-duration: 2\.65s;/)- expect(landingStyles).toMatch(/@media \(prefers-reduced-motion: reduce\)[\s\S]*?\.closingCompanion\s*\{[\s\S]*?animation: none;/)- expect(landingStyles).not.toContain(".closingGathering::before")- expect(landingStyles).toMatch(/\.closingCta > \.kicker\s*\{[\s\S]*?text-transform: none;/)- expect(landingStyles).toMatch(/\.footer\s*\{[\s\S]*?background: var\(--landing-section-bg\);/)- expect(landingStyles).not.toMatch(/\.footer\s*\{[\s\S]*?border-top:/)+ it("disables closing decoration for reduced motion", () => {+ expect(staticContractInput2).toMatch(/@media \(prefers-reduced-motion: reduce\)[\s\S]*?\.closingCompanion\s*\{[\s\S]*?animation: none;/)})it("keeps product-demo labels out of the homepage heading tree", () => {- const root = webRoot()- const shellSource = readFileSync(path.join(root, "src/components/home/landing-shell-motion.tsx"), "utf8")- const dmHeaderSource = readFileSync(path.join(root, "src/components/community/channels/dm-header.tsx"), "utf8")- const pairMachineSource = readFileSync(- path.join(root, "src/components/community/machines/pair-machine-sheet.tsx"),- "utf8",- )+ const shellSource = staticContractInput3+ const dmHeaderSource = staticContractInput4+ const pairMachineSource = resolvedRawInput0expect(shellSource).not.toMatch(/<h[1-6]\b/)expect(shellSource).toContain(@@ -152,18 +120,16 @@ describe("landing content contract", () => {expect(shellSource).not.toContain("npm exec --yes --package=@alook/daemon@latest -- alook-daemon")expect(shellSource).not.toContain("--server-url https://alook.ai")expect(shellSource).not.toContain("--ws-url wss://alook.ai")- expect(shellSource.match(/<DmHeader dm=\{DMS\[0\]\} titleAs="div" \/>/g)).toHaveLength(2)expect(shellSource).toContain('headingAs="div"')expect(dmHeaderSource).toContain('titleAs: Title = "h1"')expect(pairMachineSource).toContain('headingAs = "h3"')})it("keeps one H1 and includes the testimonials in the shorter homepage outline", () => {- const root = webRoot()- const landingPageSource = readFileSync(path.join(root, "src/components/home/landing-page.tsx"), "utf8")- const heroSource = readFileSync(path.join(root, "src/components/home/hero-section.tsx"), "utf8")- const faqSource = readFileSync(path.join(root, "src/components/home/homepage-faq.tsx"), "utf8")- const testimonialsSource = readFileSync(path.join(root, "src/components/home/landing-testimonials.tsx"), "utf8")+ const landingPageSource = staticContractInput0+ const heroSource = staticContractInput1+ const faqSource = staticContractInput5+ const testimonialsSource = staticContractInput6expect(heroSource.match(/<h1\b/g)).toHaveLength(1)expect(landingPageSource.match(/<h2\b/g)).toHaveLength(1)@@ -174,8 +140,7 @@ describe("landing content contract", () => {})it("requires every Lighthouse SEO audit to pass", () => {- const root = webRoot()- const config = JSON.parse(readFileSync(path.join(root, "lighthouserc.json"), "utf8"))+ const config = JSON.parse(staticContractInput7)expect(config.ci.collect.startServerReadyPattern).toBe("Alook multi-zone Next development ready",@@ -184,57 +149,12 @@ describe("landing content contract", () => {expect(config.ci.assert.assertions["categories:seo"]).toEqual(["error", { minScore: 1 }])})- it("promotes the approved landing while preserving the legacy route", () => {- const root = webRoot()- const repoRoot = path.resolve(root, "../..")- const rootRoute = readFileSync(path.join(root, "src/app/(home)/page.tsx"), "utf8")- const legacyRoute = readFileSync(path.join(root, "src/app/landing-legacy/page.tsx"), "utf8")- const rootLayout = readFileSync(path.join(root, "src/app/layout.tsx"), "utf8")- const siteMetadataSource = readFileSync(path.join(root, "src/lib/seo/site-metadata.ts"), "utf8")- const authLayout = readFileSync(path.join(root, "src/app/(auth)/layout.tsx"), "utf8")- const signInClient = readFileSync(path.join(root, "src/app/(auth)/sign-in/sign-in-client.tsx"), "utf8")- const communityLayout = readFileSync(path.join(root, "src/app/c/layout.tsx"), "utf8")- const communityLayoutClient = readFileSync(path.join(root, "src/app/c/community-layout-client.tsx"), "utf8")- const ogRoute = readFileSync(path.join(root, "src/app/og/route.tsx"), "utf8")- const ogRenderer = readFileSync(path.join(root, "src/app/_og/render-og-image.tsx"), "utf8")- const publicLayout = readFileSync(path.join(root, "src/components/public-layout.tsx"), "utf8")- const landingPageSource = ["landing-page.tsx", "landing-feature-gallery.tsx", "landing-feature-scene.tsx"].map(file => readFileSync(path.join(root, "src/components/home", file), "utf8")).join("\n")- const landingContentSource = readFileSync(path.join(root, "src/components/home/landing-content.ts"), "utf8")- const landingStyles = readFileSync(path.join(root, "src/components/home/landing-page.module.css"), "utf8")- const motionStyles = readFileSync(path.join(root, "src/components/home/landing-shell-motion.module.css"), "utf8")- const reachSource = readFileSync(path.join(root, "src/components/home/landing-reach-motion.tsx"), "utf8")- const reachStyles = readFileSync(path.join(root, "src/components/home/landing-reach-motion.module.css"), "utf8")- const reachMockupLicense = readFileSync(- path.join(root, "src/components/home/opensourceui-mockups.LICENSE.txt"),- "utf8",- )- const shellSource = readFileSync(path.join(root, "src/components/home/landing-shell-motion.tsx"), "utf8")- const playbackSource = readFileSync(path.join(root, "src/components/home/use-landing-motion-playback.ts"), "utf8")- const heroSource = readFileSync(path.join(root, "src/components/home/hero-section.tsx"), "utf8")- const typewriterSource = readFileSync(path.join(root, "src/components/typewriter-visual.tsx"), "utf8")- const swarmSource = readFileSync(path.join(root, "src/components/home/hero-avatar-swarm.tsx"), "utf8")- const swarmStyles = readFileSync(path.join(root, "src/components/home/hero-avatar-swarm.module.css"), "utf8")- const navSource = readFileSync(path.join(root, "src/components/home/marketing-nav.tsx"), "utf8")- const marketingLinksSource = readFileSync(path.join(root, "src/components/home/marketing-site-links.ts"), "utf8")- const legacyHome = readFileSync(path.join(root, "src/components/home/home-page.tsx"), "utf8")- const normalizedLandingPageSource = landingPageSource.replace(/\s+/g, " ")- const brandCopySource = readFileSync(path.join(root, "src/lib/brand-copy.ts"), "utf8")- const manifest = JSON.parse(readFileSync(path.join(root, "public/manifest.json"), "utf8"))- const tauriConfig = JSON.parse(- readFileSync(path.join(repoRoot, "src/desktop/src-tauri/tauri.conf.json"), "utf8"),- )- const cargoManifest = readFileSync(path.join(repoRoot, "src/desktop/src-tauri/Cargo.toml"), "utf8")- const githubPreview = readFileSync(path.join(repoRoot, "assets/social-preview/github-card.html"), "utf8")- const readmePreview = readFileSync(path.join(repoRoot, "assets/social-preview/readme-banner.html"), "utf8")- const twitterPreview = readFileSync(path.join(repoRoot, "assets/social-preview/twitter-banner.html"), "utf8")-- expect(rootRoute).toContain("LandingPage")- expect(rootRoute).not.toContain("getSession")+ it("keeps public and legacy routes plus cross-platform brand metadata aligned", () => {+ const rootRoute = staticContractInput8+ const legacyRoute = staticContractInput9expect(rootRoute).toContain("<SessionLandingPage />")+ expect(rootRoute).not.toContain("getSession")expect(rootRoute).toContain('path: "/"')- expect(rootRoute).not.toContain("HomePage")- expect(rootRoute).not.toContain("FAQPage")- expect(rootRoute).not.toContain("Personal Company")expect(legacyRoute).toContain("HomePage")expect(legacyRoute).toContain("getSession")expect(legacyRoute).toContain("index: false")@@ -245,276 +165,33 @@ describe("landing content contract", () => {expect(BRAND_DESCRIPTION).toContain("shared rooms")expect(LANDING_HERO.subline).toBe("Chat with your team, friends, and agents like Claude Code and Codex in one place. No more relaying messages.")expect(LANDING_META_TITLE).toBe("Alook | Multi-Agent Collaboration for Team and Friends")- expect(LANDING_META_DESCRIPTION).toBe(- "Bring Claude Code and Codex agents into shared chats with Alook. Coordinate multi-agent workflows, share context, and review work with your team.",- )- expect(brandCopySource).not.toContain("Personal Company")+ expect(LANDING_META_DESCRIPTION).toBe("Bring Claude Code and Codex agents into shared chats with Alook. Coordinate multi-agent workflows, share context, and review work with your team.")expect(rootRoute).toContain("LANDING_META_TITLE")expect(rootRoute).toContain("LANDING_META_DESCRIPTION")- expect(rootLayout).toContain("siteMetadata")- expect(siteMetadataSource).toContain("BRAND_TITLE")- expect(siteMetadataSource).toContain("BRAND_DESCRIPTION")- expect(siteMetadataSource).toContain("BRAND_SLOGAN")- expect(rootLayout).not.toContain("Personal Company")- expect(rootLayout).not.toContain("Give them an email")- expect(siteMetadataSource).toContain('url: "/favicon.ico", type: "image/x-icon"')- expect(siteMetadataSource).toContain('url: "/apple-touch-icon.png", sizes: "180x180"')- expect(authLayout).toContain("description: BRAND_SLOGAN")- expect(authLayout).not.toContain("Personal Company")- expect(authLayout).not.toContain("Your Your")- expect(signInClient).toContain('label: "Bring your own agents"')- expect(signInClient).toContain('description: "Use your own computer and existing agent subscriptions."')- expect(signInClient).not.toContain("Bring your own workspaces")- expect(communityLayout).toContain('data-community-shell="public"')- expect(communityLayoutClient).toContain('<SignupTracker redirectTo="/c/me/machines" />')- expect(ogRoute).toContain("SITE_OG_IMAGE_URL")- expect(ogRoute).toContain("Response.redirect")- expect(ogRoute).not.toContain("searchParams")- expect(ogRenderer).toContain('await getCloudflareContext({ async: true })')- expect(ogRenderer).toContain('env.ASSETS')- expect(ogRenderer).toContain('"https://assets.local/icon-192.png"')- expect(ogRenderer).toContain('"https://assets.local/fonts/dm-sans-600.ttf"')- expect(ogRenderer).not.toContain('node:fs')- expect(ogRenderer).not.toContain('node:path')- expect(ogRenderer).not.toContain('process.cwd()')- expect(ogRenderer).not.toContain("OG_LOGO_DATA_URI")- expect(ogRenderer).not.toContain("alook.svg")- expect(ogRenderer).toContain("width={120}")- expect(ogRenderer).toContain("height={120}")- expect(ogRenderer).toContain("borderRadius: 28")- expect(ogRenderer).toContain("HOME / FAMILY-PLANS")- expect(ogRenderer).toContain("Maya joined the room.")- expect(ogRenderer).toContain("Bring the agents you already use into a room with people you trust.")- expect(ogRenderer).not.toContain("[email protected]")- expect(ogRenderer).not.toContain("[email protected]")- expect(ogRenderer).not.toContain("stay always on")- expect(ogRenderer).not.toContain("Personal Company")- expect(publicLayout).toContain("BRAND_SLOGAN")- expect(publicLayout).not.toContain("Personal Company")+ expect(staticContractInput10).toContain("siteMetadata")+ expect(staticContractInput11).toContain("BRAND_TITLE")+ expect(staticContractInput11).toContain("BRAND_DESCRIPTION")+ expect(staticContractInput11).toContain("BRAND_SLOGAN")+ expect(staticContractInput11).toContain('url: "/favicon.ico", type: "image/x-icon"')+ expect(staticContractInput11).toContain('url: "/apple-touch-icon.png", sizes: "180x180"')+ expect(staticContractInput12).toContain("description: BRAND_SLOGAN")+ expect(staticContractInput13).toContain('label: "Bring your own agents"')+ expect(staticContractInput13).toContain('description: "Use your own computer and existing agent subscriptions."')+ expect(staticContractInput17).toContain("BRAND_SLOGAN")+ expect(staticContractInput18).toContain("BRAND_SLOGAN")+ const manifest = JSON.parse(staticContractInput31)+ const tauri = JSON.parse(staticContractInput32)expect(manifest.name).toBe("Alook | Multi-Agent Collaboration for Team and Friends")expect(manifest.description).toContain("people you trust")- expect(tauriConfig.bundle.shortDescription).toBe("Multi-Agent Collaboration for Team and Friends")- expect(tauriConfig.bundle.longDescription).toContain("shared rooms")- expect(cargoManifest).toContain('description = "Alook | Multi-Agent Collaboration for Team and Friends"')- for (const preview of [githubPreview, readmePreview, twitterPreview]) {+ expect(tauri.bundle.shortDescription).toBe("Multi-Agent Collaboration for Team and Friends")+ expect(tauri.bundle.longDescription).toContain("shared rooms")+ expect(staticContractInput33).toContain('description = "Alook | Multi-Agent Collaboration for Team and Friends"')+ for (const preview of [staticContractInput34, staticContractInput35, staticContractInput36]) {expect(preview).toContain('<div class="title">Multi-Agent Collaboration</div>')expect(preview).toContain('<div class="tagline">for Team and Friends</div>')expect(preview).not.toContain("Your Personal Company")}- expect(readmePreview).toContain("width: 1280px")- expect(twitterPreview).toContain("width: 1500px")- expect(twitterPreview).toContain("justify-content: flex-start")- for (const preview of [readmePreview, twitterPreview]) {- expect(preview).toContain(- ".title {\n color: #356f95;\n font-family: 'VT323', monospace;",- )- expect(preview).toContain(- ".tagline {\n color: #1b271f;\n font-family: 'VT323', monospace;",- )- expect(preview).not.toContain('class="spec"')- }- expect(readmePreview).toContain("font-size: 68px")- expect(twitterPreview).toContain("font-size: 80px")- expect(landingPageSource).toContain("export function LandingPage")- expect(playbackSource).toContain("LANDING_MOTION_VISIBILITY_THRESHOLD = 0.3")- expect(playbackSource).toContain("IntersectionObserver")- expect(playbackSource).toContain('LandingMotionVisibility = "hidden" | "paused" | "playing"')- expect(playbackSource).toContain('shouldReset: visibility === "hidden"')- expect(shellSource).toContain("reducedMotion || !isPlaying")- expect(shellSource).toContain("!reducedMotion && shouldReset")- expect(reachSource).toContain("reducedMotion || !isPlaying")- expect(reachSource).toContain("!reducedMotion && shouldReset")- expect(landingPageSource).toContain("isLoggedIn={isLoggedIn}")- expect(landingPageSource).toContain('homeHref="/"')- expect(landingPageSource).toContain("highlightActions")- const footerSource = readFileSync(path.join(root, "src/components/home/landing-footer.tsx"), "utf8")- expect(landingPageSource).toContain("<LandingFooter />")- expect(footerSource).toContain("FooterSocialLinks")- expect(footerSource).toContain("GithubOutboundLink")- expect(footerSource).toContain('surface="public_footer"')- expect(footerSource).toContain("DISCORD_INVITE_URL")- expect(footerSource).toContain("https://x.com/alook_ai")- expect(landingPageSource).toContain("HeroSection")- expect(landingPageSource).toContain("<HomepageFaq />")- expect(landingPageSource).toContain("MarketingNav")- expect(landingPageSource).toContain("showTemplates={false}")- expect(landingPageSource).toContain("revealAfterHero")- expect(landingPageSource).toContain("collapseLinksOnMobile")- expect(heroSource).toContain("TypewriterVisual")- expect(typewriterSource).toContain("var(--tw-blob-theme, oklch(0.88 0.025 82))")- expect(heroSource).toContain("backgroundDecoration")- expect(landingPageSource).toContain("<HeroAvatarSwarm />")- expect(swarmSource).toContain("HERO_SWARM_AVATARS")- expect(swarmSource.match(/\{ name: "/g)).toHaveLength(20)- const swarmDurations = [...swarmSource.matchAll(/duration: "([\d.]+)s"/g)].map((match) => Number(match[1]))- expect(swarmDurations).toHaveLength(20)- expect(Math.min(...swarmDurations)).toBeGreaterThanOrEqual(4.5)- expect(swarmSource).toContain('aria-hidden="true"')- expect(swarmSource).toContain("data-path={avatar.path}")- expect(swarmStyles).toContain("pointer-events: none")- expect(swarmStyles).toContain("calc(100vw + 150px)")- expect(swarmStyles).toContain("animation-fill-mode: forwards")- expect(swarmStyles).toContain("--swarm-ground: 78%")- expect(swarmStyles).toContain("left: calc(var(--avatar-start-x) - 64%)")- expect(swarmStyles).toContain("scale(1.2, 0.78)")- expect(swarmSource).toContain("styles.shadow")- expect(swarmSource).not.toContain("styles.ground")- expect(swarmStyles).not.toContain(".ground {")- expect(swarmStyles).toContain("prefers-reduced-motion: reduce")- expect(navSource).toContain("showTemplates = true")- expect(navSource).toContain("highlightActions = false")- expect(navSource).toContain('highlightActions ? "var(--landing-accent)" : "var(--landing-text)"')- expect(marketingLinksSource).toContain('{ href: "/pricing", label: "Pricing"')- expect(marketingLinksSource).toContain('{ href: "/blog", label: "Blog"')- expect(marketingLinksSource).toContain("MARKETING_SITE_LINK_CLASS_NAME")- expect(marketingLinksSource).toContain("MARKETING_SITE_LINK_STYLE")- expect(navSource).toContain("MARKETING_SITE_LINKS.map")- expect(navSource).toContain("MARKETING_SITE_LINK_CLASS_NAME")- expect(navSource).toContain("MARKETING_SITE_LINK_STYLE")- expect(footerSource).toContain("MARKETING_SITE_LINKS.map")- expect(footerSource).toContain('<a href="/tutorials"')- expect(navSource).not.toContain('href="/tutorials"')- expect(footerSource).toContain("MARKETING_SITE_LINK_CLASS_NAME")- expect(footerSource).toContain("MARKETING_SITE_LINK_STYLE")- expect(landingStyles).toContain("--landing-content-max: 1320px")- expect(landingStyles).toContain("--landing-page-gutter: clamp(24px, 5vw, 72px)")- expect(landingStyles).toContain("max-width: var(--landing-content-max)")- expect(motionStyles).toContain("--motion-frame-radius: var(--gallery-frame-radius, var(--radius-lg))")- expect(motionStyles).toContain("clip-path: inset(0 round var(--motion-frame-radius))")- expect(landingPageSource).toContain("LANDING_HERO.headlineLead")- expect(landingPageSource).toContain("LANDING_HERO.headlineTail")- expect(landingPageSource).toContain("subline={LANDING_HERO.subline}")- expect(landingPageSource).toContain("largeCtas")- expect(landingPageSource).toContain("highlightPrimaryCta")- expect(heroSource).toContain('highlightPrimaryCta ? "var(--landing-accent)" : "var(--landing-text)"')- expect(landingPageSource).toContain("LandingReachMotion")- expect(landingPageSource).not.toContain("MOBILE WEB PLACEHOLDER")- expect(landingPageSource).not.toContain("DemoTerminal")- expect(landingPageSource).not.toContain("/onboard.md")- expect(landingPageSource).not.toContain("A SHARED HOME")- expect(landingPageSource).not.toContain("Email")- expect(landingPageSource).not.toContain("Schedule")- expect(landingPageSource).not.toContain("same memory")- expect(landingPageSource).not.toContain("anyone")- expect(landingPageSource).not.toContain("subscriptions")- expect(normalizedLandingPageSource).toContain(- "Connect the agent you already use, running on your computer with your projects and tools.",- )- expect(landingPageSource).not.toContain("NOT ANOTHER")- expect(landingPageSource).not.toContain("leaves the terminal")- expect(landingPageSource).not.toContain("Your agent gets a name")- expect(landingPageSource).toContain("Let teammates talk to your agent.")- expect(normalizedLandingPageSource).toContain(- "Ask for a preview, request changes, and review results in one conversation.",- )- expect(landingPageSource).toContain('data-testid="landing-runtime-badges"')- expect(landingPageSource).toContain("A companion of your own.")- expect(landingPageSource).not.toContain("One persistent identity across rooms")- expect(readFileSync(path.join(root, "src/components/home/landing-profile-content.tsx"), "utf8")).toContain("I keep the same account, identity, and relationships across every room.")- expect(landingPageSource).toContain("InteractiveIdentityProfileCard")- expect(readFileSync(path.join(root, "src/components/home/landing-profile-content.tsx"), "utf8")).toContain('name: "Maya"')- expect(readFileSync(path.join(root, "src/components/home/landing-profile-content.tsx"), "utf8")).toContain('userId: "maya"')- expect(landingPageSource).not.toContain('"landing-maya"')- expect(readFileSync(path.join(root, "src/components/home/landing-profile-content.tsx"), "utf8")).toContain('initialStatusText="Free for dinner"')- expect(landingPageSource).toContain("IdentityProof")- expect(landingPageSource).toContain('data-testid="landing-identity-proof"')- expect(landingPageSource).toContain('data-testid="landing-identity-motion"')- expect(landingPageSource).toContain('<LandingShellMotion scene="identity" compact={compact} />')- expect(landingPageSource).not.toContain('<ProductScene scene="spaces" />')- expect(landingPageSource).toContain("ResizeObserver")- expect(landingPageSource).toContain("--identity-card-fit-scale")- expect(landingPageSource).toContain("styles.identityCardSlot")- expect(landingPageSource).toContain("styles.identitySceneSlot")- expect(landingStyles).toMatch(/\.identityMediaLayout\s*\{[\s\S]*?max-width: 1040px;/)- expect(landingStyles).toMatch(/\.identityLayout \.sectionIntro h2\s*\{[\s\S]*?max-width: 1040px;/)- expect(landingStyles).toMatch(/\.identityMediaLayout\s*\{[\s\S]*?align-items: stretch;/)- expect(landingStyles).toContain("scale(var(--identity-card-fit-scale))")- expect(landingStyles).toContain("--motion-shell-border-width: 0px")- expect(landingStyles).toMatch(/\.productSection,\s*\.timelineSection\s*\{[\s\S]*?background: var\(--landing-section-bg/)- expect(landingStyles).toMatch(/\.identitySection,\s*\.reachSection\s*\{[\s\S]*?background: var\(--landing-bg\)/)- expect(landingStyles).toMatch(/\.identitySceneSlot \.galleryFrame\s*\{[\s\S]*?border: 0;/)- expect(motionStyles).toContain("var(--motion-shell-border-width, 1px)")- expect(landingStyles).toContain("@media (min-width: 640px) and (max-width: 1023px)")- expect(landingStyles).toContain("@media (max-width: 639px)")- expect(landingStyles).toMatch(- /@media \(max-width: 639px\)[\s\S]*?\.landingHeroTypewriter\s*\{[\s\S]*?transform: translateY\(-12%\);/,- )- expect(landingStyles).not.toContain("translateY(-16%)")- expect(landingStyles).toMatch(/\.identityProfileCard\s*\{[\s\S]*?width: 300px;/)- expect(landingStyles).toMatch(/@media \(max-width: 639px\)[\s\S]*?\.identityProfileCard\s*\{[\s\S]*?width: min\(300px, 100%\);/)- expect(landingPageSource).toContain("onPointerMove={tiltCard}")- expect(landingPageSource).toContain("identityProfileCardSensor")- expect(landingPageSource).toContain("Math.max(0.5")- expect(landingStyles).toContain("inset: -72px")- expect(landingStyles).toContain("perspective: 900px")- expect(landingStyles).toContain("prefers-reduced-motion: reduce")- expect(landingPageSource).not.toContain("PaletteSwitcher")- expect(landingStyles).toMatch(/\.page:global\(\.landing\)\s*\{[\s\S]*?--landing-bg: #f4f9e9;/)- expect(landingStyles).toMatch(/\.page:global\(\.landing\)\s*\{[\s\S]*?--landing-accent: #356f95;/)- expect(landingStyles).toMatch(/\.page:global\(\.landing\)\s*\{[\s\S]*?--tw-blob-theme: var\(--landing-section-bg\);/)- expect(landingStyles).toMatch(/\.page:global\(\.landing\)\s*\{[\s\S]*?--landing-text-muted: #47633b;/)- expect(landingStyles).toMatch(/\.landingHeroEmphasis\s*\{[\s\S]*?color: var\(--landing-accent\);/)- expect(landingStyles).toMatch(/\.landingHeroTail\s*\{[\s\S]*?color: var\(--landing-text\);/)- expect(landingPageSource).toContain("showMobileDesktopHint={false}")- expect(landingStyles).not.toContain("#5b6b60")- expect(landingStyles).toContain("--landing-section-bg")- expect(landingStyles.match(/--tw-blob-theme:/g)).toHaveLength(1)- expect(landingPageSource).toContain('<ProductScene scene="server" compact={compact} />')- expect(landingPageSource).toContain('<LandingShellMotion scene="identity" compact={compact} />')- expect(landingPageSource).toContain('<ProductScene scene="machine" compact={compact} />')- expect(landingPageSource).toContain('<LandingShellMotion scene="continuity" compact={compact} />')- expect(landingPageSource).not.toContain("IdentityTimeline")- expect(shellSource).toContain("continuity-frontend-design")- expect(shellSource).toContain("I’ll check the page with Shelly")- expect(shellSource).toContain("then ask Tracy about the weekend plan")- expect(shellSource).toContain("Have you checked the updated page on your phone")- expect(shellSource).toContain("Can we confirm the Saturday plan we discussed")- expect(shellSource).toContain("<InboxPopover")- expect(shellSource).toContain('data-motion-target", "continuity-inbox"')- expect(shellSource).toContain(- 'inbox={scene === "continuity" || scene === "server" || scene === "machine" ? <span /> : undefined}',- )- expect(landingPageSource).not.toContain("ProductGallery")- expect(landingPageSource).not.toContain("storyTabs")- expect(landingPageSource).toContain("Check in from your phone.")- expect(normalizedLandingPageSource).toContain(- "Read updates and give the next instruction. Keep your agent’s computer online.",- )- expect(reachSource).toContain('data-slot="laptop-mockup-card"')- expect(reachSource).toContain('data-variant="starlight"')- expect(reachSource).toContain('data-testid="landing-laptop-mockup"')- expect(reachSource).toContain('data-slot="phone-mockup-card"')- expect(reachSource).toContain('data-variant="titanium"')- expect(reachSource).toContain('data-testid="landing-phone-mockup"')- expect(reachSource).toContain("styles.phoneDynamicIsland")- expect(reachSource).toContain("styles.phoneHomeIndicator")- expect(reachSource).not.toContain("styles.deviceBar")- expect(shellSource).toContain("<span>Phone</span>")- expect(`${reachSource} ${shellSource}`).not.toContain("Alook Web")- expect(reachSource).toContain('<LandingShellMotion scene="server" beat={beat} />')- expect(reachSource).toContain("<LandingMobileChatMotion beat={beat} />")- expect(shellSource).toContain("data-testid={tid.landingMobileMotionStage}")- expect(shellSource).toContain("mobileBack={() => {}}")- expect(shellSource).toContain('mobileBackDisplay="always"')- expect(shellSource).toContain("stage.getBoundingClientRect().width / 390")- expect(motionStyles).toContain("transform: scale(var(--mobile-stage-scale))")- expect(motionStyles).toMatch(/\.mobileMessages\s*\{[\s\S]*?justify-content: flex-start;/)- expect(reachStyles).toContain("width: clamp(146px, 42%, 190px)")- expect(reachStyles).toContain("clamp(-210px, -40vw, -150px)")- expect(reachStyles).toContain("width: clamp(108px, 24%, 224px)")- expect(reachStyles).toContain("aspect-ratio: 70.6 / 146.6")- expect(reachStyles).toContain("right: clamp(14px, 5%, 56px)")- expect(reachStyles).toContain("bottom: clamp(24px, 7%, 56px)")- expect(reachStyles).toContain("aspect-ratio: 1120 / 760")- expect(reachStyles).toContain("clamp(14px, 4vw, 24px)")- expect(reachStyles).toMatch(/\.desktopShell\s*\{[\s\S]*?left: 1%;/)- expect(reachStyles).toMatch(/\.laptopBase\s*\{[\s\S]*?linear-gradient/)- expect(reachMockupLicense).toContain("Copyright (c) 2026 Bidyut Kundu")- expect(footerSource).toContain("BRAND_SLOGAN")- expect(landingPageSource).toContain("Keep your existing setup.")- expect(landingPageSource).not.toContain("The runtime and workspace stay on your paired machine")- expect(`${landingPageSource} ${landingContentSource.split("export const HOME_FAQS")[0]}`.replace(LANDING_HERO.subline, "")).not.toMatch(/\bplaces?\b/i)- expect(landingPageSource).not.toContain("stay in touch")- expect(legacyHome).toContain("export function HomePage")+ expect(staticContractInput35).toContain("width: 1280px")+ expect(staticContractInput36).toContain("width: 1500px")})})diff --git a/src/web/src/components/home/landing-page-funnel.dom.test.ts b/src/web/src/components/home/landing-page-funnel.dom.test.tsindex e2e64e775..18fcc42ec 100644--- a/src/web/src/components/home/landing-page-funnel.dom.test.ts+++ b/src/web/src/components/home/landing-page-funnel.dom.test.ts@@ -1,6 +1,6 @@import { createElement, type ReactNode } from "react"import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"-import { fireEvent, render, screen } from "@/test/react-dom-harness"+import { fireEvent, render, screen, within } from "@/test/react-dom-harness"const mocks = vi.hoisted(() => ({ capture: vi.fn() }))vi.mock("@/lib/analytics", () => ({ trackLandingCtaClicked: mocks.capture }))vi.mock("./landing-page.module.css", () => ({ default: new Proxy({}, { get: (_target, key) => String(key) }) }))@@ -25,6 +25,13 @@ describe("landing closing funnel entrance", () => {it.each([false, true])("captures the actual closing click for signed-in=%s before document navigation", isLoggedIn => {render(createElement(LandingPage, { isLoggedIn }))const anchor = screen.getByTestId("landing-closing-open")+ const closing = anchor.closest("section")!+ expect(closing).toHaveTextContent("Ready to share")+ expect(within(closing).getByRole("heading", { name: "Bring your team into the conversation." })).toBeVisible()+ expect(closing).toHaveTextContent("Connect your agent and invite a teammate.")+ expect(anchor).toHaveTextContent(isLoggedIn ? "Open Alook" : "Get started")+ expect(within(closing).queryByRole("link", { name: /GitHub/i })).toBeNull()+ expect(closing).not.toHaveTextContent(/healthy runtime|paired machine|approved DMs/)expect(anchor).toHaveAttribute("href", isLoggedIn ? "/c/me" : "/sign-in")anchor.addEventListener("click", event => event.preventDefault())fireEvent.click(anchor)diff --git a/src/web/src/components/legacy-desktop-command-contract.test.ts b/src/web/src/components/legacy-desktop-command-contract.architecture.test.tssimilarity index 100%rename from src/web/src/components/legacy-desktop-command-contract.test.tsrename to src/web/src/components/legacy-desktop-command-contract.architecture.test.tsdiff --git a/src/web/src/components/privacy/privacy-policy-content.test.ts b/src/web/src/components/privacy/privacy-policy-content.test.tsindex d057129c8..4af0fd6aa 100644--- a/src/web/src/components/privacy/privacy-policy-content.test.ts+++ b/src/web/src/components/privacy/privacy-policy-content.test.ts@@ -1,4 +1,5 @@-import { readFileSync } from "node:fs"+import rawContractInput0 from "../../app/privacy/page.tsx?raw"+import rawContractInput1 from "../community/settings/user-settings.tsx?raw"import { createElement } from "react"import { renderToStaticMarkup } from "react-dom/server"import { describe, expect, it, vi } from "vitest"@@ -43,11 +44,8 @@ describe("shared Privacy policy", () => {})it("is the body source for both public and Settings entry points", () => {- const publicPage = readFileSync(new URL("../../app/privacy/page.tsx", import.meta.url), "utf8")- const userSettings = readFileSync(- new URL("../community/settings/user-settings.tsx", import.meta.url),- "utf8",- )+ const publicPage = rawContractInput0+ const userSettings = rawContractInput1for (const source of [publicPage, userSettings]) {expect(source).toContain("PrivacyPolicyContent")diff --git a/src/web/src/components/terms/terms-content.test.ts b/src/web/src/components/terms/terms-content.test.tsindex f637c90cb..d3f0b7399 100644--- a/src/web/src/components/terms/terms-content.test.ts+++ b/src/web/src/components/terms/terms-content.test.ts@@ -1,4 +1,4 @@-import { readFileSync } from "node:fs"+import rawContractInput0 from "../community/settings/user-settings.tsx?raw"import { createElement } from "react"import { renderToStaticMarkup } from "react-dom/server"import { describe, expect, it, vi } from "vitest"@@ -27,7 +27,7 @@ describe("Terms of Service", () => {})it("uses the same content in its own Settings tab and keeps public sharing metadata canonical", () => {- const settings = readFileSync(new URL("../community/settings/user-settings.tsx", import.meta.url), "utf8")+ const settings = rawContractInput0expect(settings).toMatch(/\{\s*value: "terms",\s*label: "Terms",/)expect(settings).toContain('<SettingsShellPanel value="terms">')expect(settings).toContain("<TermsContent />")diff --git a/src/web/src/components/ui/app-edge-fade.test.ts b/src/web/src/components/ui/app-edge-fade.test.tsindex 8fd6d7cc8..d2c13a355 100644--- a/src/web/src/components/ui/app-edge-fade.test.ts+++ b/src/web/src/components/ui/app-edge-fade.test.ts@@ -1,3 +1,4 @@+import resolvedRawInput0 from "../../app/globals.css?raw"import { createElement } from "react"import { renderToStaticMarkup } from "react-dom/server"import { readFileSync } from "node:fs"@@ -30,10 +31,7 @@ describe("AppEdgeFade", () => {})it("defines one fixed 60px token independent of the app safe-area tokens", () => {- const css = readFileSync(- fileURLToPath(new URL("../../app/globals.css", import.meta.url)),- "utf8",- )+ const css = resolvedRawInput0const token = css.match(/--app-edge-fade-size:\s*([^;]+);/)expect(token?.[1]?.trim()).toBe("60px")diff --git a/src/web/src/components/ui/popover.test.ts b/src/web/src/components/ui/popover.test.tsindex c517f66a2..2b4401ddb 100644--- a/src/web/src/components/ui/popover.test.ts+++ b/src/web/src/components/ui/popover.test.ts@@ -1,8 +1,8 @@-import { readFileSync } from "node:fs"+import rawContractInput0 from "./popover.tsx?raw"import { describe, expect, it } from "vitest"describe("Popover primitive surface", () => {- const source = readFileSync(new URL("./popover.tsx", import.meta.url), "utf8")+ const source = rawContractInput0it("exposes Base UI's real nonmodal composition parts", () => {for (const part of [diff --git a/src/web/src/components/ui/toast.dom.test.ts b/src/web/src/components/ui/toast.dom.test.tsindex 2956c48b2..c0fcab677 100644--- a/src/web/src/components/ui/toast.dom.test.ts+++ b/src/web/src/components/ui/toast.dom.test.ts@@ -1,4 +1,4 @@-import { readFileSync } from "node:fs"+import staticContractInput0 from "../../app/layout.tsx?raw"import { resolve } from "node:path"import React, { type ReactNode } from "react"import { beforeEach, describe, expect, it, vi } from "vitest"@@ -217,11 +217,7 @@ describe("top-center message notification", () => {})it("mounts the external manager provider before authenticated producers", () => {- const layout = readFileSync(resolve(- process.cwd(),- process.cwd().endsWith("/src/web") ? "" : "src/web",- "src/app/layout.tsx",- ), "utf8")+ const layout = staticContractInput0expect(layout.indexOf("<MessageNotificationToaster />")).toBeLessThan(layout.indexOf("<TooltipProvider>"))})diff --git a/src/web/src/hooks/community/use-virtual-cursor-pagination.dom.test.ts b/src/web/src/hooks/community/use-virtual-cursor-pagination.dom.test.tsindex 5e3866a35..903775c31 100644--- a/src/web/src/hooks/community/use-virtual-cursor-pagination.dom.test.ts+++ b/src/web/src/hooks/community/use-virtual-cursor-pagination.dom.test.ts@@ -153,15 +153,6 @@ describe.each(["start", "end"] as const)("native virtual cursor pagination (%s)"expect(f.onLoad).toHaveBeenCalledOnce()})- it("keeps initial and target positioning separate from pagination", () => {- const f = fixture({ enabled: false })- f.setRange(...boundary)- f.rerender()- expect(f.onLoad).not.toHaveBeenCalled()- f.rerender({ enabled: true })- expect(f.onLoad).toHaveBeenCalledOnce()- })-it("stops when the cursor is exhausted and accepts a later available cursor", () => {const f = fixture({ hasMore: false })f.setRange(...boundary)diff --git a/src/web/src/lib/apple-auth.test.ts b/src/web/src/lib/apple-auth.test.tsindex 2ec96e164..27f776627 100644--- a/src/web/src/lib/apple-auth.test.ts+++ b/src/web/src/lib/apple-auth.test.ts@@ -133,16 +133,6 @@ describe("Apple profile mapping", () => {expect(lookup).not.toHaveBeenCalled()})- it("rejects an empty stable subject before identity lookup", async () => {- const lookup = vi.fn()- await expect(mapAppleProfileToUser({- sub: " ",- email: "[email protected]",- email_verified: true,- }, lookup)).resolves.toEqual({ email: undefined })- expect(lookup).not.toHaveBeenCalled()- })-it("rehydrates a returning Apple identity from its stored verified user", async () => {const lookup = vi.fn().mockResolvedValue({email: "[email protected]",diff --git a/src/web/src/lib/auth-response-cookies.test.ts b/src/web/src/lib/auth-response-cookies.test.tsindex d15eeca55..153f7cfbe 100644--- a/src/web/src/lib/auth-response-cookies.test.ts+++ b/src/web/src/lib/auth-response-cookies.test.ts@@ -1,5 +1,6 @@+import rawContractInput0 from "../../migrations/0001_schema.sql?raw"+import rawContractInput1 from "../../migrations/0035_device_code_table.sql?raw"import { DatabaseSync } from "node:sqlite"-import { readFileSync } from "node:fs"import { createHmac } from "node:crypto"import { afterEach, describe, expect, it, vi } from "vitest"import { NextRequest } from "next/server"@@ -88,8 +89,8 @@ describe("same-request signed session refresh", () => {try {sqlite.exec(`CREATE TABLE user (id TEXT PRIMARY KEY, name TEXT, email TEXT, emailVerified INTEGER, image TEXT, createdAt INTEGER, updatedAt INTEGER, discriminator TEXT, isBot INTEGER, deletedAt TEXT);CREATE TABLE session (id TEXT PRIMARY KEY, token TEXT, userId TEXT, expiresAt INTEGER, createdAt INTEGER, updatedAt INTEGER, ipAddress TEXT, userAgent TEXT);`)- sqlite.exec(readFileSync(new URL("../../migrations/0001_schema.sql", import.meta.url), "utf8"))- sqlite.exec(readFileSync(new URL("../../migrations/0035_device_code_table.sql", import.meta.url), "utf8"))+ sqlite.exec(rawContractInput0)+ sqlite.exec(rawContractInput1)const now = Date.now()sqlite.prepare("INSERT INTO user VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run("viewer-a", "Viewer", "[email protected]", 1, null, new Date(now).toISOString(), new Date(now).toISOString(), "0001", 0, null)sqlite.prepare("INSERT INTO session VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run("session-a", "fixture-token", "viewer-a", new Date(now + 30 * 86400000).toISOString(), new Date(now).toISOString(), new Date(now).toISOString(), null, null)diff --git a/src/web/src/lib/community/create-community-message-allowlist.test.ts b/src/web/src/lib/community/create-community-message-allowlist.architecture.test.tssimilarity index 100%rename from src/web/src/lib/community/create-community-message-allowlist.test.tsrename to src/web/src/lib/community/create-community-message-allowlist.architecture.test.tsdiff --git a/src/web/src/lib/community/fanout.test.ts b/src/web/src/lib/community/fanout.test.tsindex 5e0611a6e..bdf760816 100644--- a/src/web/src/lib/community/fanout.test.ts+++ b/src/web/src/lib/community/fanout.test.ts@@ -1,5 +1,5 @@+import rawContractInput0 from "./fanout.ts?raw"import { describe, it, expect, vi, beforeEach } from "vitest"-import { readFileSync } from "node:fs"const mockGetCloudflareContext = vi.fn(() => ({ env: { DB: {} } }))vi.mock("@opennextjs/cloudflare", () => ({@@ -230,7 +230,7 @@ describe("fanOutToServerMembers", () => {})it("contains no local reach classifier after delegating to shared", () => {- const source = readFileSync(new URL("./fanout.ts", import.meta.url), "utf8")+ const source = rawContractInput0expect(source).not.toMatch(/\bchannelReach\b|\bisStoredChannelType\b|switch\s*\(\s*reach\s*\)/)})})diff --git a/src/web/src/lib/community/machine-disconnect.test.ts b/src/web/src/lib/community/machine-disconnect.test.tsindex 3c2062a35..107a3bb83 100644--- a/src/web/src/lib/community/machine-disconnect.test.ts+++ b/src/web/src/lib/community/machine-disconnect.test.ts@@ -1,3 +1,4 @@+import resolvedRawInput0 from "./machine-disconnect.ts?raw"import { describe, it, expect, vi, beforeEach, afterAll } from "vitest"import fs from "node:fs"import path from "node:path"@@ -87,10 +88,7 @@ describe("forceCloseCommunityMachineByDoName", () => {// Guard: the module must delegate to the shared `wsDoFetch` helper.it("goes through the new helper (single wsDoFetch import, no ad-hoc fallback)", () => {- const src = fs.readFileSync(- path.resolve(__dirname, "machine-disconnect.ts"),- "utf8",- )+ const src = resolvedRawInput0expect(src).toMatch(/wsDoFetch/)expect(src).not.toMatch(/WS_DO_WORKER/)expect(src).not.toMatch(/DEV_WS_DO_URL/)diff --git a/src/web/src/lib/community/message-dispatcher-architecture.test.ts b/src/web/src/lib/community/message-dispatcher-architecture.test.tsindex 830002e22..4a7196749 100644--- a/src/web/src/lib/community/message-dispatcher-architecture.test.ts+++ b/src/web/src/lib/community/message-dispatcher-architecture.test.ts@@ -1,8 +1,19 @@-import { existsSync, readFileSync } from "node:fs"+import contractText0 from "./fanout.ts?raw"+import contractText1 from "./message-dispatcher.ts?raw"+import contractText2 from "./message-handler.ts?raw"+import contractText3 from "./queue-producer.ts?raw"+import { existsSync } from "node:fs"import { describe, expect, it } from "vitest"-function source(name: string): string {- return readFileSync(new URL(name, import.meta.url), "utf8")+const contractSources: Record<string, string> = {+ "./fanout.ts": contractText0,+ "./message-dispatcher.ts": contractText1,+ "./message-handler.ts": contractText2,+ "./queue-producer.ts": contractText3,+}+const source = (path: string) => {+ if (!(path in contractSources)) throw new Error("unregistered contract source: " + path)+ return contractSources[path]}describe("committed-message delivery architecture", () => {diff --git a/src/web/src/lib/native-oauth-authenticated-cleanup.test.ts b/src/web/src/lib/native-oauth-authenticated-cleanup.test.tsindex 7ee3e23d8..30f060a34 100644--- a/src/web/src/lib/native-oauth-authenticated-cleanup.test.ts+++ b/src/web/src/lib/native-oauth-authenticated-cleanup.test.ts@@ -1,4 +1,5 @@-import { readFileSync } from "node:fs"+import rawContractInput0 from "../app/c/layout.tsx?raw"+import rawContractInput1 from "../app/c/community-layout-client.tsx?raw"import { beforeEach, describe, expect, it, vi } from "vitest"import { cleanupAuthenticatedNativeOauthResidue } from "./native-oauth-authenticated-cleanup"@@ -187,8 +188,8 @@ describe("cleanupAuthenticatedNativeOauthResidue", () => {})it("mounts only behind the authenticated Community layout gate", () => {- const communityLayout = readFileSync(new URL("../app/c/layout.tsx", import.meta.url), "utf8")- const communityClient = readFileSync(new URL("../app/c/community-layout-client.tsx", import.meta.url), "utf8")+ const communityLayout = rawContractInput0+ const communityClient = rawContractInput1expect(communityLayout).not.toContain("getSession")expect(communityClient).toContain("const session = useSession()")diff --git a/src/web/src/lib/observability/coverage.architecture.test.ts b/src/web/src/lib/observability/coverage.architecture.test.tsnew file mode 100644index 000000000..008e5b614--- /dev/null+++ b/src/web/src/lib/observability/coverage.architecture.test.ts@@ -0,0 +1,346 @@+import { readFileSync, readdirSync } from "node:fs"+import { resolve, relative } from "node:path"+import ts from "typescript"+import { expect, it } from "vitest"+import { actionNames, apiRoutes, pageRoutes, routeTemplate } from "./coverage"+import { actionVariants } from "./actions"+import { resolveCommunityModulePlan } from "../community/community-route"++const web = resolve(import.meta.dirname, "../../..")+const files = (root: string) => readdirSync(root, { recursive: true }).filter((file): file is string => typeof file === "string" && /\.tsx?$/.test(file)).map(file => resolve(root, file))++it("keeps the route whitelist aligned with both builds and parallel route slots", () => {+ const routes = new Set(["src/app", "blog/src/app"].flatMap(root => files(resolve(web, root)).filter(file => file.endsWith("/page.tsx")).map(file => "/" + relative(resolve(web, root), file).split("/").slice(0, -1).filter(segment => !segment.startsWith("(") && !segment.startsWith("@")).join("/"))))+ expect([...routes].filter(route => !/^\/c(?:\/|$)/.test(route)).sort()).toEqual(pageRoutes.filter(route => !/^\/c(?:\/|$)/.test(route)).sort())+ expect([...routes].filter(route => route === "/c" || route.startsWith("/c/")).sort()).toEqual(["/c", "/c/[...path]", "/c/invite/[token]"])+ for (const route of pageRoutes.filter(route => route === "/c" || route.startsWith("/c/"))) {+ const concrete = route.replace(/\[[^\]]+\]/g, "fixture-id")+ expect(resolveCommunityModulePlan(concrete).route, concrete).not.toBe("unknown")+ expect(routeTemplate(concrete), concrete).toBe(route)+ }+})+it("keeps the API whitelist aligned with the current route files", () => {+ const root = resolve(web, "src/app/api")+ const routes = files(root).filter(file => file.endsWith("/route.ts")).map(file => "/api/" + relative(root, file).split("/").slice(0, -1).join("/"))+ expect(routes.sort()).toEqual([...apiRoutes].sort())+})+it("keeps existing mutation owners inventoried and semantic variants on the whitelist", () => {+ const inventory = new Set<string>([...mutationCoverage, ...facadeCoverage].map(entry => entry.file))+ for (const file of files(resolve(web, "src"))) {+ if (/\.test\./.test(file) || file.includes("/test/")) continue+ const source = ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.Latest, true, file.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS)+ const visit = (node: ts.Node) => {+ if (ts.isCallExpression(node) && ["useMutation", "useCommunityCommandMutation"].includes(node.expression.getText(source))) {+ expect(inventory.has("src/web/" + relative(web, file)), file).toBe(true)+ }+ ts.forEachChild(node, visit)+ }+ visit(source)+ }+ for (const variants of Object.values(actionVariants)) for (const name of Object.values(variants)) expect(actionNames as readonly string[]).toContain(name)+})++const mutationCoverage = [+ { file: "src/web/src/components/community/onboarding/onboarding-agent-dialog.tsx", owner: "OnboardingAgentDialog", action: "automation.access_code.create" },+ { file: "src/web/src/hooks/community/use-automation.ts", owner: "useAutomation", action: "automation.access_code.command" },+ { "file": "src/web/src/hooks/community/use-bot-memberships.ts", "owner": "useBotMemberships", "action": "community.command" },+ { "file": "src/web/src/hooks/community/mutations/bot-creation.ts", "owner": "useBotCreationDecision", "action": "bot.creation.decision" },+ {+ "file": "src/web/src/app/(public-community)/c/invite/[token]/invite-accept-client.tsx",+ "owner": "InviteAcceptInner",+ "action": "server.invite.accept"+ },+ {+ "file": "src/web/src/components/community/machines/machine-list.tsx",+ "owner": "MachineList",+ "action": "machine.command"+ },+ {+ "file": "src/web/src/components/community/machines/pair-machine-sheet.tsx",+ "owner": "PairMachineSheet",+ "action": "machine.pair.generate"+ },+ {+ "file": "src/web/src/components/community/machines/pair-machine-sheet.tsx",+ "owner": "PairMachineSheet",+ "action": "machine.pair.launch"+ },+ {+ "file": "src/web/src/components/community/members/add-members-dialog.tsx",+ "owner": "AddMembersDialog",+ "action": "channel.members.add"+ },+ {+ "file": "src/web/src/components/community/members/member-list.tsx",+ "owner": "MemberList",+ "action": "member.management.command"+ },+ {+ "file": "src/web/src/components/community/messages/create-forum-thread.tsx",+ "owner": "CreateForumThread",+ "action": "forum.thread.create"+ },+ {+ "file": "src/web/src/components/community/messages/message-share-dialog.tsx",+ "owner": "MessageShareDialog",+ "action": "message.export"+ },+ {+ "file": "src/web/src/components/community/messages/use-composer-controller.ts",+ "owner": "useComposerController",+ "action": "message.compose.send"+ },+ {+ "file": "src/web/src/components/community/onboarding/community-onboarding-form.tsx",+ "owner": "CommunityOnboardingForm",+ "action": "community.onboarding.initialize"+ },+ {+ "file": "src/web/src/components/community/onboarding/onboarding-machine-dialog.tsx",+ "owner": "OnboardingMachineDialog",+ "action": "machine.pair.generate"+ },+ {+ "file": "src/web/src/components/community/settings/account-deletion-flow.tsx",+ "owner": "AccountDeletionFlow",+ "action": "account.deletion.command"+ },+ {+ "file": "src/web/src/components/community/settings/user-settings.tsx",+ "owner": "AdvancedSettings",+ "action": "cache.clear"+ },+ {+ "file": "src/web/src/components/community/social/invite-dialog.tsx",+ "owner": "InviteDialog",+ "action": "invitation.send"+ },+ {+ "file": "src/web/src/components/community/social/invite-dialog.tsx",+ "owner": "InviteDialog",+ "action": "invitation.copy"+ },+ {+ "file": "src/web/src/hooks/community/mutations/dm.ts",+ "owner": "useCreateOrGetDm",+ "action": "dm.open"+ },+ {+ "file": "src/web/src/hooks/community/mutations/forum.ts",+ "owner": "useCreateForumThread",+ "action": "forum.thread.create"+ },+ {+ "file": "src/web/src/hooks/community/mutations/forum.ts",+ "owner": "useUpdatePostTags",+ "action": "forum.tags.update"+ },+ {+ "file": "src/web/src/hooks/community/mutations/forum.ts",+ "owner": "useDeleteForumThread",+ "action": "forum.thread.delete"+ },+ {+ "file": "src/web/src/hooks/community/mutations/invites.ts",+ "owner": "useResolveOrCreateInvite",+ "action": "server.invite.resolve"+ },+ {+ "file": "src/web/src/hooks/community/mutations/invites.ts",+ "owner": "useRevokeInvite",+ "action": "server.invite.revoke"+ },+ {+ "file": "src/web/src/hooks/community/mutations/members.ts",+ "owner": "useMemberCommand",+ "action": "server.member.command"+ },+ {+ "file": "src/web/src/hooks/community/mutations/message-memberships.ts",+ "owner": "usePinCommand",+ "action": "message.pin.command"+ },+ {+ "file": "src/web/src/hooks/community/mutations/message-memberships.ts",+ "owner": "useMarkCommand",+ "action": "message.mark.command"+ },+ {+ "file": "src/web/src/hooks/community/mutations/message-reactions.ts",+ "owner": "useReactionIntent",+ "action": "message.reaction.command"+ },+ {+ "file": "src/web/src/hooks/community/mutations/messages.ts",+ "owner": "useSendMessage",+ "action": "channel.message.send"+ },+ {+ "file": "src/web/src/hooks/community/mutations/messages.ts",+ "owner": "useSendDmMessage",+ "action": "dm.message.send"+ },+ {+ "file": "src/web/src/hooks/community/mutations/messages.ts",+ "owner": "useCreateThread",+ "action": "message.thread.create"+ },+ {+ "file": "src/web/src/hooks/community/mutations/messages.ts",+ "owner": "useMarkAllInboxRead",+ "action": "inbox.read_all"+ },+ {+ "file": "src/web/src/hooks/community/mutations/messages.ts",+ "owner": "useDeleteMention",+ "action": "mention.dismiss"+ },+ {+ "file": "src/web/src/hooks/community/mutations/notifications.ts",+ "owner": "useNotificationCommand",+ "action": "notification.settings.command"+ },+ {+ "file": "src/web/src/hooks/community/mutations/profile.ts",+ "owner": "useUpdateProfile",+ "action": "profile.update"+ },+ {+ "file": "src/web/src/hooks/community/mutations/profile.ts",+ "owner": "useUploadUserAvatar",+ "action": "profile.avatar.upload"+ },+ {+ "file": "src/web/src/hooks/community/mutations/uploads.ts",+ "owner": "useUploadFile",+ "action": "attachment.upload"+ },+ {+ "file": "src/web/src/hooks/community/use-account-sign-out.ts",+ "owner": "useAccountSignOut",+ "action": "account.sign_out"+ },+ {+ "file": "src/web/src/hooks/community/use-billing.ts",+ "owner": "useBilling",+ "action": "billing.redirect"+ },+ {+ "file": "src/web/src/hooks/community/use-billing.ts",+ "owner": "useBilling",+ "action": "billing.change.cancel"+ },+ {+ "file": "src/web/src/hooks/community/use-bot-bug-report.ts",+ "owner": "useBotBugReport",+ "action": "bot.bug_report.submit"+ },+ {+ "file": "src/web/src/hooks/community/use-bots.ts",+ "owner": "useBotCommand",+ "action": "bot.command"+ },+ {+ "file": "src/web/src/hooks/community/use-channel-members.ts",+ "owner": "useChannelMemberCommand",+ "action": "channel.member.command"+ },+ {+ "file": "src/web/src/hooks/community/use-community-command-mutation.ts",+ "owner": "useCommunityCommandMutation",+ "action": "community.command"+ },+ {+ "file": "src/web/src/hooks/community/use-notification-settings.ts",+ "owner": "useSetBotNotificationSetting",+ "action": "bot.notification.update"+ },+ {+ "file": "src/web/src/hooks/use-file-attachments.ts",+ "owner": "useFileAttachments",+ "action": "attachment.prepare"+ }+] as const++const facadeCoverage = [+ {+ "file": "src/web/src/hooks/community/mutations/channels.ts",+ "owner": "useCreateChannel",+ "action": "channel.create"+ },+ {+ "file": "src/web/src/hooks/community/mutations/channels.ts",+ "owner": "useRenameChannel",+ "action": "channel.rename"+ },+ {+ "file": "src/web/src/hooks/community/mutations/channels.ts",+ "owner": "useDeleteChannel",+ "action": "channel.delete"+ },+ {+ "file": "src/web/src/hooks/community/mutations/channels.ts",+ "owner": "useCreateCategory",+ "action": "category.create"+ },+ {+ "file": "src/web/src/hooks/community/mutations/channels.ts",+ "owner": "useUpdateCategory",+ "action": "category.update"+ },+ {+ "file": "src/web/src/hooks/community/mutations/channels.ts",+ "owner": "useDeleteCategory",+ "action": "category.delete"+ },+ {+ "file": "src/web/src/hooks/community/mutations/channels.ts",+ "owner": "useReorderCategories",+ "action": "category.reorder"+ },+ {+ "file": "src/web/src/hooks/community/mutations/channels.ts",+ "owner": "useReorderChannels",+ "action": "channel.reorder"+ },+ {+ "file": "src/web/src/hooks/community/mutations/friends.ts",+ "owner": "useFriendCommand",+ "action": "friend.command"+ },+ {+ "file": "src/web/src/hooks/community/mutations/server-rail.ts",+ "owner": "useServerRailCommit",+ "action": "server.rail.reorder"+ },+ {+ "file": "src/web/src/hooks/community/mutations/servers.ts",+ "owner": "useCreateServer",+ "action": "server.create"+ },+ {+ "file": "src/web/src/hooks/community/mutations/servers.ts",+ "owner": "useJoinServer",+ "action": "server.join"+ },+ {+ "file": "src/web/src/hooks/community/mutations/servers.ts",+ "owner": "useLeaveServer",+ "action": "server.leave"+ },+ {+ "file": "src/web/src/hooks/community/mutations/servers.ts",+ "owner": "useDeleteServer",+ "action": "server.delete"+ },+ {+ "file": "src/web/src/hooks/community/mutations/servers.ts",+ "owner": "useUpdateServer",+ "action": "server.update"+ },+ {+ "file": "src/web/src/hooks/community/mutations/servers.ts",+ "owner": "useUploadServerIcon",+ "action": "server.icon.upload"+ }+] as constdiff --git a/src/web/src/lib/observability/coverage.test.ts b/src/web/src/lib/observability/coverage.test.tsindex 1b7c1913f..ff7775835 100644--- a/src/web/src/lib/observability/coverage.test.ts+++ b/src/web/src/lib/observability/coverage.test.ts@@ -1,348 +1,6 @@-import { readFileSync, readdirSync } from "node:fs"-import { resolve, relative } from "node:path"-import ts from "typescript"import { expect, it } from "vitest"-import { actionNames, apiRoutes, pageRoutes, routeTemplate } from "./coverage"-import { actionVariants } from "./actions"-import { resolveCommunityModulePlan } from "../community/community-route"+import { routeTemplate } from "./coverage"-const web = resolve(import.meta.dirname, "../../..")-const files = (root: string) => readdirSync(root, { recursive: true }).filter((file): file is string => typeof file === "string" && /\.tsx?$/.test(file)).map(file => resolve(root, file))it("normalizes the ordinary message route without retaining a message ID or query", () => {expect(routeTemplate("/c/messages/private_message_188?seq=123")).toBe("/c/messages/[messageId]")})-it("keeps the route whitelist aligned with both builds and parallel route slots", () => {- const routes = new Set(["src/app", "blog/src/app"].flatMap(root => files(resolve(web, root)).filter(file => file.endsWith("/page.tsx")).map(file => "/" + relative(resolve(web, root), file).split("/").slice(0, -1).filter(segment => !segment.startsWith("(") && !segment.startsWith("@")).join("/"))))- expect([...routes].filter(route => !/^\/c(?:\/|$)/.test(route)).sort()).toEqual(pageRoutes.filter(route => !/^\/c(?:\/|$)/.test(route)).sort())- expect([...routes].filter(route => route === "/c" || route.startsWith("/c/")).sort()).toEqual(["/c", "/c/[...path]", "/c/invite/[token]"])- for (const route of pageRoutes.filter(route => route === "/c" || route.startsWith("/c/"))) {- const concrete = route.replace(/\[[^\]]+\]/g, "fixture-id")- expect(resolveCommunityModulePlan(concrete).route, concrete).not.toBe("unknown")- expect(routeTemplate(concrete), concrete).toBe(route)- }-})-it("keeps the API whitelist aligned with the current route files", () => {- const root = resolve(web, "src/app/api")- const routes = files(root).filter(file => file.endsWith("/route.ts")).map(file => "/api/" + relative(root, file).split("/").slice(0, -1).join("/"))- expect(routes.sort()).toEqual([...apiRoutes].sort())-})-it("keeps existing mutation owners inventoried and semantic variants on the whitelist", () => {- const inventory = new Set<string>([...mutationCoverage, ...facadeCoverage].map(entry => entry.file))- for (const file of files(resolve(web, "src"))) {- if (/\.test\./.test(file) || file.includes("/test/")) continue- const source = ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.Latest, true, file.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS)- const visit = (node: ts.Node) => {- if (ts.isCallExpression(node) && ["useMutation", "useCommunityCommandMutation"].includes(node.expression.getText(source))) {- expect(inventory.has("src/web/" + relative(web, file)), file).toBe(true)- }- ts.forEachChild(node, visit)- }- visit(source)- }- for (const variants of Object.values(actionVariants)) for (const name of Object.values(variants)) expect(actionNames as readonly string[]).toContain(name)-})--const mutationCoverage = [- { file: "src/web/src/components/community/onboarding/onboarding-agent-dialog.tsx", owner: "OnboardingAgentDialog", action: "automation.access_code.create" },- { file: "src/web/src/hooks/community/use-automation.ts", owner: "useAutomation", action: "automation.access_code.command" },- { "file": "src/web/src/hooks/community/use-bot-memberships.ts", "owner": "useBotMemberships", "action": "community.command" },- { "file": "src/web/src/hooks/community/mutations/bot-creation.ts", "owner": "useBotCreationDecision", "action": "bot.creation.decision" },- {- "file": "src/web/src/app/(public-community)/c/invite/[token]/invite-accept-client.tsx",- "owner": "InviteAcceptInner",- "action": "server.invite.accept"- },- {- "file": "src/web/src/components/community/machines/machine-list.tsx",- "owner": "MachineList",- "action": "machine.command"- },- {- "file": "src/web/src/components/community/machines/pair-machine-sheet.tsx",- "owner": "PairMachineSheet",- "action": "machine.pair.generate"- },- {- "file": "src/web/src/components/community/machines/pair-machine-sheet.tsx",- "owner": "PairMachineSheet",- "action": "machine.pair.launch"- },- {- "file": "src/web/src/components/community/members/add-members-dialog.tsx",- "owner": "AddMembersDialog",- "action": "channel.members.add"- },- {- "file": "src/web/src/components/community/members/member-list.tsx",- "owner": "MemberList",- "action": "member.management.command"- },- {- "file": "src/web/src/components/community/messages/create-forum-thread.tsx",- "owner": "CreateForumThread",- "action": "forum.thread.create"- },- {- "file": "src/web/src/components/community/messages/message-share-dialog.tsx",- "owner": "MessageShareDialog",- "action": "message.export"- },- {- "file": "src/web/src/components/community/messages/use-composer-controller.ts",- "owner": "useComposerController",- "action": "message.compose.send"- },- {- "file": "src/web/src/components/community/onboarding/community-onboarding-form.tsx",- "owner": "CommunityOnboardingForm",- "action": "community.onboarding.initialize"- },- {- "file": "src/web/src/components/community/onboarding/onboarding-machine-dialog.tsx",- "owner": "OnboardingMachineDialog",- "action": "machine.pair.generate"- },- {- "file": "src/web/src/components/community/settings/account-deletion-flow.tsx",- "owner": "AccountDeletionFlow",- "action": "account.deletion.command"- },- {- "file": "src/web/src/components/community/settings/user-settings.tsx",- "owner": "AdvancedSettings",- "action": "cache.clear"- },- {- "file": "src/web/src/components/community/social/invite-dialog.tsx",- "owner": "InviteDialog",- "action": "invitation.send"- },- {- "file": "src/web/src/components/community/social/invite-dialog.tsx",- "owner": "InviteDialog",- "action": "invitation.copy"- },- {- "file": "src/web/src/hooks/community/mutations/dm.ts",- "owner": "useCreateOrGetDm",- "action": "dm.open"- },- {- "file": "src/web/src/hooks/community/mutations/forum.ts",- "owner": "useCreateForumThread",- "action": "forum.thread.create"- },- {- "file": "src/web/src/hooks/community/mutations/forum.ts",- "owner": "useUpdatePostTags",- "action": "forum.tags.update"- },- {- "file": "src/web/src/hooks/community/mutations/forum.ts",- "owner": "useDeleteForumThread",- "action": "forum.thread.delete"- },- {- "file": "src/web/src/hooks/community/mutations/invites.ts",- "owner": "useResolveOrCreateInvite",- "action": "server.invite.resolve"- },- {- "file": "src/web/src/hooks/community/mutations/invites.ts",- "owner": "useRevokeInvite",- "action": "server.invite.revoke"- },- {- "file": "src/web/src/hooks/community/mutations/members.ts",- "owner": "useMemberCommand",- "action": "server.member.command"- },- {- "file": "src/web/src/hooks/community/mutations/message-memberships.ts",- "owner": "usePinCommand",- "action": "message.pin.command"- },- {- "file": "src/web/src/hooks/community/mutations/message-memberships.ts",- "owner": "useMarkCommand",- "action": "message.mark.command"- },- {- "file": "src/web/src/hooks/community/mutations/message-reactions.ts",- "owner": "useReactionIntent",- "action": "message.reaction.command"- },- {- "file": "src/web/src/hooks/community/mutations/messages.ts",- "owner": "useSendMessage",- "action": "channel.message.send"- },- {- "file": "src/web/src/hooks/community/mutations/messages.ts",- "owner": "useSendDmMessage",- "action": "dm.message.send"- },- {- "file": "src/web/src/hooks/community/mutations/messages.ts",- "owner": "useCreateThread",- "action": "message.thread.create"- },- {- "file": "src/web/src/hooks/community/mutations/messages.ts",- "owner": "useMarkAllInboxRead",- "action": "inbox.read_all"- },- {- "file": "src/web/src/hooks/community/mutations/messages.ts",- "owner": "useDeleteMention",- "action": "mention.dismiss"- },- {- "file": "src/web/src/hooks/community/mutations/notifications.ts",- "owner": "useNotificationCommand",- "action": "notification.settings.command"- },- {- "file": "src/web/src/hooks/community/mutations/profile.ts",- "owner": "useUpdateProfile",- "action": "profile.update"- },- {- "file": "src/web/src/hooks/community/mutations/profile.ts",- "owner": "useUploadUserAvatar",- "action": "profile.avatar.upload"- },- {- "file": "src/web/src/hooks/community/mutations/uploads.ts",- "owner": "useUploadFile",- "action": "attachment.upload"- },- {- "file": "src/web/src/hooks/community/use-account-sign-out.ts",- "owner": "useAccountSignOut",- "action": "account.sign_out"- },- {- "file": "src/web/src/hooks/community/use-billing.ts",- "owner": "useBilling",- "action": "billing.redirect"- },- {- "file": "src/web/src/hooks/community/use-billing.ts",- "owner": "useBilling",- "action": "billing.change.cancel"- },- {- "file": "src/web/src/hooks/community/use-bot-bug-report.ts",- "owner": "useBotBugReport",- "action": "bot.bug_report.submit"- },- {- "file": "src/web/src/hooks/community/use-bots.ts",- "owner": "useBotCommand",- "action": "bot.command"- },- {- "file": "src/web/src/hooks/community/use-channel-members.ts",- "owner": "useChannelMemberCommand",- "action": "channel.member.command"- },- {- "file": "src/web/src/hooks/community/use-community-command-mutation.ts",- "owner": "useCommunityCommandMutation",- "action": "community.command"- },- {- "file": "src/web/src/hooks/community/use-notification-settings.ts",- "owner": "useSetBotNotificationSetting",- "action": "bot.notification.update"- },- {- "file": "src/web/src/hooks/use-file-attachments.ts",- "owner": "useFileAttachments",- "action": "attachment.prepare"- }-] as const--const facadeCoverage = [- {- "file": "src/web/src/hooks/community/mutations/channels.ts",- "owner": "useCreateChannel",- "action": "channel.create"- },- {- "file": "src/web/src/hooks/community/mutations/channels.ts",- "owner": "useRenameChannel",- "action": "channel.rename"- },- {- "file": "src/web/src/hooks/community/mutations/channels.ts",- "owner": "useDeleteChannel",- "action": "channel.delete"- },- {- "file": "src/web/src/hooks/community/mutations/channels.ts",- "owner": "useCreateCategory",- "action": "category.create"- },- {- "file": "src/web/src/hooks/community/mutations/channels.ts",- "owner": "useUpdateCategory",- "action": "category.update"- },- {- "file": "src/web/src/hooks/community/mutations/channels.ts",- "owner": "useDeleteCategory",- "action": "category.delete"- },- {- "file": "src/web/src/hooks/community/mutations/channels.ts",- "owner": "useReorderCategories",- "action": "category.reorder"- },- {- "file": "src/web/src/hooks/community/mutations/channels.ts",- "owner": "useReorderChannels",- "action": "channel.reorder"- },- {- "file": "src/web/src/hooks/community/mutations/friends.ts",- "owner": "useFriendCommand",- "action": "friend.command"- },- {- "file": "src/web/src/hooks/community/mutations/server-rail.ts",- "owner": "useServerRailCommit",- "action": "server.rail.reorder"- },- {- "file": "src/web/src/hooks/community/mutations/servers.ts",- "owner": "useCreateServer",- "action": "server.create"- },- {- "file": "src/web/src/hooks/community/mutations/servers.ts",- "owner": "useJoinServer",- "action": "server.join"- },- {- "file": "src/web/src/hooks/community/mutations/servers.ts",- "owner": "useLeaveServer",- "action": "server.leave"- },- {- "file": "src/web/src/hooks/community/mutations/servers.ts",- "owner": "useDeleteServer",- "action": "server.delete"- },- {- "file": "src/web/src/hooks/community/mutations/servers.ts",- "owner": "useUpdateServer",- "action": "server.update"- },- {- "file": "src/web/src/hooks/community/mutations/servers.ts",- "owner": "useUploadServerIcon",- "action": "server.icon.upload"- }-] as constdiff --git a/src/web/src/lib/product-analytics-document.test.ts b/src/web/src/lib/product-analytics-document.test.tsindex c2d0eb132..fd9b13120 100644--- a/src/web/src/lib/product-analytics-document.test.ts+++ b/src/web/src/lib/product-analytics-document.test.ts@@ -1,11 +1,11 @@-import { readFileSync } from "node:fs"+import rawContractInput0 from "../../public/analytics-events.html?raw"import { runInNewContext } from "node:vm"import { describe, expect, it } from "vitest"import { ONBOARDING_ANALYTICS_STAGES, PRODUCT_ANALYTICS_EVENTS } from "./product-analytics-contract"import { authFailureParams } from "./auth-failure"function documentSender(origin = "https://alook.ai") {- const html = readFileSync(new URL("../../public/analytics-events.html", import.meta.url), "utf8")+ const html = rawContractInput0const script = html.match(/<script>([\s\S]*?)<\/script>/)?.[1]if (!script) throw new Error("missing event document script")const window = { gtag: undefined as ((...args: unknown[]) => void) | undefined, dataLayer: [] as ArrayLike<unknown>[], sendProductEvent: (_input: { event: string; params: Record<string, string> }) => {} }diff --git a/src/web/src/lib/query-persister.old-owner.test.ts b/src/web/src/lib/query-persister.old-owner.test.tsindex ecd76855f..eb707265d 100644--- a/src/web/src/lib/query-persister.old-owner.test.ts+++ b/src/web/src/lib/query-persister.old-owner.test.ts@@ -1,6 +1,6 @@+import rawContractInput0 from "./test-fixtures/query-persister-07fa.ts.txt?raw"import "fake-indexeddb/auto"import { createHash } from "node:crypto"-import { readFileSync } from "node:fs"import * as ts from "typescript"import * as idb from "idb-keyval"import * as nativeStore from "@tanstack/store"@@ -19,7 +19,7 @@ import { communityKeys } from "@/lib/query-keys"import { createIdbPersister, PERSIST_BUSTER, PERSIST_CACHE_PREFIX, PERSIST_VERSION, type QualifiedPersister } from "./query-persister"function oldDocument() {- const source = readFileSync(new URL("./test-fixtures/query-persister-07fa.ts.txt", import.meta.url), "utf8")+ const source = rawContractInput0expect(createHash("sha256").update(source).digest("hex")).toBe("d1e237f2265acd04afa98d58f28b118930b76bfd7056382de40a8e4afe4672e6")const modules: Record<string, unknown> = {"idb-keyval": idb, "@tanstack/store": nativeStore,diff --git a/src/web/src/lib/seo/public-page-metadata.test.ts b/src/web/src/lib/seo/public-page-metadata.test.tsindex 76314dc13..3321e4075 100644--- a/src/web/src/lib/seo/public-page-metadata.test.ts+++ b/src/web/src/lib/seo/public-page-metadata.test.ts@@ -5,22 +5,14 @@ import { SITE_OG_IMAGE, SITE_OG_IMAGE_URL } from "./site-metadata";vi.mock("@/components/home/landing-page", () => ({ LandingPage: () => null }));vi.mock("@/lib/observability/regions", () => ({ ObservedStaticContent: () => null }));vi.mock("@/app/pricing/pricing-client", () => ({ default: () => null }));-vi.mock("@blog/lib/blog/posts", () => ({ getAllPosts: vi.fn() }));-vi.mock("@blog/app/blog/(index)/recent-posts", () => ({ RecentPosts: () => null }));import { metadata as home } from "@/app/(home)/page";import { metadata as pricing } from "@/app/pricing/page";-import { metadata as blog } from "@blog/app/blog/(index)/page";-import { metadata as guides } from "@blog/app/guides/page";-import { metadata as tutorials } from "@blog/app/tutorials/page";const pages = [["home", home, "https://alook.ai", "Alook | Multi-Agent Collaboration for Team and Friends"],["pricing", pricing, "https://alook.ai/pricing", "Pricing — Free, Studio & House Plans — Alook"],- ["blog", blog, "https://alook.ai/blog", "Blog — AI Agent Collaboration & Workflows — Alook"],- ["tutorials", tutorials, "https://alook.ai/tutorials", "Tutorials — Alook"],- ["guides", guides, "https://alook.ai/guides", "Guides — Coding Agent Collaboration — Alook"],] as const;describe("public page metadata", () => {@@ -46,14 +38,11 @@ describe("public page metadata", () => {});});- it("preserves the approved homepage description and Blog discovery links", () => {+ it("preserves the approved homepage description", () => {expect(home.description).toBe("Bring Claude Code and Codex agents into shared chats with Alook. Coordinate multi-agent workflows, share context, and review work with your team.",);- expect(blog.alternates?.types).toEqual({- "application/rss+xml": "/blog/feed.xml",- "text/markdown": "/llms.txt",- });+});it("keeps nested public page canonical URLs under the site origin", () => {diff --git a/src/web/src/raw.d.ts b/src/web/src/raw.d.tsnew file mode 100644index 000000000..2a6eac578--- /dev/null+++ b/src/web/src/raw.d.ts@@ -0,0 +1,4 @@+declare module "*?raw" {+ const source: string+ export default source+}diff --git a/src/web/src/test/architecture/react-dom-harness-contract.test.ts b/src/web/src/test/architecture/react-dom-harness-contract.test.tsindex 15fe6aef1..86c2f58ac 100644--- a/src/web/src/test/architecture/react-dom-harness-contract.test.ts+++ b/src/web/src/test/architecture/react-dom-harness-contract.test.ts@@ -49,6 +49,9 @@ describe("React DOM harness contract", () => {expect(harness).toContain('from "@testing-library/user-event"')expect(harness).not.toMatch(/\bcleanup\s*\(/)expect(harness).not.toMatch(/IS_REACT_ACT_ENVIRONMENT\s*=/)- expect(setup.trim()).toBe('import "@testing-library/jest-dom/vitest"')+ expect(setup).toMatch(/\bfrom\s*["']vitest["']/)+ expect(setup).toMatch(/\bfrom\s*["']@testing-library\/jest-dom\/matchers["']/)+ expect(setup).not.toMatch(/^import(?!\s+type\b)[^\n]*["']@testing-library\/jest-dom\/vitest["']/m)+ expect(setup).not.toMatch(/\bcleanup\s*\(|IS_REACT_ACT_ENVIRONMENT\s*=/)})})diff --git a/src/web/src/test/architecture/vitest-workspace-config.test.ts b/src/web/src/test/architecture/vitest-workspace-config.test.tsindex f165c4313..46f23a476 100644--- a/src/web/src/test/architecture/vitest-workspace-config.test.ts+++ b/src/web/src/test/architecture/vitest-workspace-config.test.ts@@ -1,40 +1,101 @@-import { describe, expect, it } from "vitest";-import domConfig from "../../../vitest.dom.config";-import nodeConfig from "../../../vitest.config";-import workspaceConfig from "../../../vitest.workspace.config";+import { execFileSync } from "node:child_process"+import { constants, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, rmSync, symlinkSync, writeFileSync } from "node:fs"+import { tmpdir } from "node:os"+import path from "node:path"+import { describe, expect, it } from "vitest"-describe("Web Vitest workspace contract", () => {- it("runs node, DOM, and workerd projects without dropping the auth Worker", () => {- expect(workspaceConfig).toMatchObject({- test: {- projects: [- "./vitest.config.ts",- "./vitest.dom.config.ts",- "./vitest.runtime.config.mts",- "./auth/vitest.config.ts",- "./auth/vitest.runtime.config.mts",- ],- },- });- });+describe("service test project ownership", () => {+ it("discovers each service in its own project without duplicate files", () => {+ const root = path.resolve(import.meta.dirname, "../../../../..")+ const source = [+ 'import { createVitest } from "vitest/node"',+ 'import { relative, sep } from "node:path"',+ 'const ctx = await createVitest({root:process.cwd(),watch:false})',+ 'try { const specs=await ctx.globTestSpecifications(); process.stdout.write(JSON.stringify({files:specs.map(spec=>({project:spec.project.name,file:relative(process.cwd(),spec.moduleId).split(sep).join("/")})),projects:ctx.projects.map(project=>({name:project.name,group:project.config.sequence.groupOrder??0,maxWorkers:project.config.maxWorkers}))})) } finally { await ctx.close() }',+ ].join("\n")+ const { files, projects } = JSON.parse(execFileSync(process.execPath, ["--input-type=module", "-e", source], {+ cwd: root, encoding: "utf8", maxBuffer: 4 * 1024 * 1024,+ })) as { files: { project: string; file: string }[]; projects: { name: string; group: number; maxWorkers: number }[] }+ const workersByGroup = new Map<number, Set<number>>()+ for (const project of projects) {+ if (!workersByGroup.has(project.group)) workersByGroup.set(project.group, new Set())+ workersByGroup.get(project.group)!.add(project.maxWorkers)+ }+ for (const workers of workersByGroup.values()) expect(workers.size).toBe(1)+ expect(projects.find(project => project.name === "daemon-node")?.maxWorkers).toBe(1)+ expect(new Set(files.map(file => file.file)).size).toBe(files.length)+ expect(files).toEqual(expect.arrayContaining([+ { project: "web-node", file: "src/web/src/components/community/bots/bot-list-facade.contract.test.ts" },+ { project: "web-dom", file: "src/web/src/components/community/bots/bot-list-card.dom.test.ts" },+ { project: "web-contracts", file: "src/web/src/test/architecture/react-dom-harness-contract.test.ts" },+ { project: "web-tooling", file: "src/web/app-store-capture/config.test.ts" },+ { project: "blog-node", file: "src/web/blog/src/lib/public-page-metadata.test.ts" },+ { project: "blog-dom", file: "src/web/blog/src/app/guides/page.dom.test.tsx" },+ { project: "auth-node", file: "src/web/auth/index.test.ts" },+ ]))+ for (const project of ["web-runtime", "auth-runtime"]) {+ expect(files.some(file => file.project === project && file.file.includes("/test-runtime/"))).toBe(true)+ }+ expect(files.filter(file => file.file.startsWith("src/web/blog/")).every(file => file.project.startsWith("blog-"))).toBe(true)+ expect(files.filter(file => file.file.startsWith("src/web/auth/")).every(file => file.project.startsWith("auth-"))).toBe(true)+ })- it("keeps Web Node and DOM ownership explicit and disjoint from auth and runtime", () => {- expect(nodeConfig).toMatchObject({- test: {- include: expect.arrayContaining(["app-store-capture/**/*.test.ts"]),- exclude: expect.arrayContaining(["**/*.dom.test.{ts,tsx}"]),- },- });- expect(domConfig).toMatchObject({- test: {- include: [- "src/**/*.dom.test.{ts,tsx}",- "blog/**/*.dom.test.{ts,tsx}",- "scripts/**/*.dom.test.{ts,tsx}",- "readme-capture/**/*.dom.test.{ts,tsx}",- "app-store-capture/**/*.dom.test.{ts,tsx}",- ],- },- });- });-});+ it("executes cold service contracts through the canonical CI unit entry", () => {+ const root = path.resolve(import.meta.dirname, "../../../../..")+ const scratch = mkdtempSync(path.join(tmpdir(), "alook-mixed-unit-contract-"))+ const fixture = path.join(scratch, "source")+ const receipt = path.join(scratch, "execution.json")+ const planFile = path.join(scratch, "plan.json")+ const files = ["src/web/auth/index.test.ts", "src/daemon/src/logger.test.ts", "src/daemon/src/cli/daemonRefresh.test.ts", "src/web/src/lib/middleware/request-logger.test.ts", "src/web/src/lib/apple-oauth-hardening.test.ts"]+ const env = { ...process.env }+ for (const key of ["TEST", "VITEST", "NODE_ENV"]) delete env[key]+ const source = [+ 'import { queryNativeTasks, buildExecutionPlan } from "./scripts/ci/changed-scopes.mjs"',+ 'import { writeFileSync } from "node:fs"',+ 'const {inventory}=queryNativeTasks(); const affected=inventory.filter(task=>["@alook/web#test:auth","@alook/web#test","@alook/daemon#test"].includes(task.fullName))',+ `const plan=buildExecutionPlan(${JSON.stringify(files)}.map(path=>({status:"M",path})),{nativeTasks:{inventory,affected}})`,+ 'writeFileSync(process.argv[1],JSON.stringify(plan))',+ ].join("\n")+ try {+ for (const name of execFileSync("git", ["rev-parse", "--local-env-vars"], { cwd: root, encoding: "utf8" }).trim().split(/\r?\n/)) delete env[name]+ const paths = execFileSync("git", ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], { cwd: root, env, encoding: "utf8" }).split("\0").filter(Boolean)+ for (const file of paths) {+ const from = path.join(root, file), to = path.join(fixture, file)+ if (!existsSync(from)) continue+ mkdirSync(path.dirname(to), { recursive: true })+ if (lstatSync(from).isSymbolicLink()) symlinkSync(readlinkSync(from), to)+ else copyFileSync(from, to, constants.COPYFILE_FICLONE)+ }+ for (const dir of new Set([".", ...paths.filter(file => file.endsWith("/package.json")).map(file => path.dirname(file))])) {+ const from = path.resolve(root, dir, "node_modules"), to = path.resolve(fixture, dir, "node_modules")+ if (existsSync(from) && !existsSync(to)) symlinkSync(from, to, process.platform === "win32" ? "junction" : "dir")+ }+ const projects: string[] = []+ for (const dir of ["src/web", "src/web/auth", "src/daemon"]) {+ const name = dir + "/vitest.cold-fixture.config.ts"+ const include = files.filter(file => file.startsWith(dir + "/") && (dir !== "src/web" || file.startsWith("src/web/src/")))+ .map(file => path.relative(dir, file).replaceAll("\\", "/"))+ writeFileSync(path.join(fixture, name), 'import source from "./vitest.config"\nexport default {...source,cacheDir:'+ + JSON.stringify(path.join(scratch, "vite-cache", dir)) + ',test:{...source.test,include:' + JSON.stringify(include)+ + ',fsModuleCachePath:' + JSON.stringify(path.join(scratch, "native-cache")) + '}}\n')+ projects.push(name)+ }+ copyFileSync(path.join(fixture, "vitest.config.ts"), path.join(fixture, "vitest.source-fixture.config.ts"))+ writeFileSync(path.join(fixture, "vitest.config.ts"), 'import source from "./vitest.source-fixture.config"\nexport default {...source,test:{...source.test,projects:'+ + JSON.stringify(projects) + ',fsModuleCachePath:' + JSON.stringify(path.join(scratch, "native-cache")) + '}}\n')+ for (const file of files) expect(readFileSync(path.join(fixture, file)).equals(readFileSync(path.join(root, file)))).toBe(true)+ execFileSync(process.execPath, ["--input-type=module", "-e", source, planFile], { cwd: fixture, env, encoding: "utf8", maxBuffer: 4 * 1024 * 1024 })+ execFileSync(process.execPath, ["scripts/ci/run-unit-tests.mjs", "--ci", "--plan", planFile, "--receipt", receipt], { cwd: fixture, env, encoding: "utf8", maxBuffer: 4 * 1024 * 1024 })+ const result = JSON.parse(readFileSync(receipt, "utf8")) as {+ fallback: unknown+ execution: { unhandled_errors: number; files: { file: string; ok: boolean }[] }+ }+ expect(result.fallback).toBeNull()+ expect(result.execution.unhandled_errors).toBe(0)+ expect(result.execution.files).toHaveLength(files.length)+ for (const file of files) {+ expect(result.execution.files.find(entry => entry.file === file)?.ok).toBe(true)+ }+ } finally { rmSync(scratch, { recursive: true, force: true }) }+ })+})diff --git a/src/web/src/test/community-sqlite-db.test.ts b/src/web/src/test/community-sqlite-db.test.tsindex 70c377451..c2b2d771c 100644--- a/src/web/src/test/community-sqlite-db.test.ts+++ b/src/web/src/test/community-sqlite-db.test.ts@@ -1,4 +1,4 @@-import { readFileSync } from "node:fs"+import rawContractInput0 from "../../migrations/0068_dm_to_channel.sql?raw"import { afterEach, expect, it } from "vitest"import { createRequire } from "node:module"import { queries } from "@alook/shared"@@ -18,7 +18,7 @@ function fixture() {}it("retains the actual migration's two notification partial unique constraints", () => {const { sqlite } = fixture()- const migration = readFileSync(new URL("../../migrations/0068_dm_to_channel.sql", import.meta.url), "utf8")+ const migration = rawContractInput0const statements = migration.split("\n").filter(line => line.startsWith("CREATE UNIQUE INDEX idx_notification_setting_user_"))expect(statements).toHaveLength(2)for (const sql of statements) {diff --git a/src/web/src/test/e2e-service-definitions.test.ts b/src/web/src/test/e2e-service-definitions.test.tsindex bae2a6926..54980468b 100644--- a/src/web/src/test/e2e-service-definitions.test.ts+++ b/src/web/src/test/e2e-service-definitions.test.ts@@ -16,7 +16,7 @@ import {waitForServicesReady,wranglerLogEnvironment,} from "./e2e-ui/_setup/services"-import { MACHINE_WS_URL, resolveMachineWsUrl, resolveWsUrl, WEB_URL, WS_URL } from "./e2e-ui/_setup/paths"+import { MACHINE_WS_URL, requiredE2EZones, resolveMachineWsUrl, resolveWsUrl, WEB_URL, WS_URL } from "./e2e-ui/_setup/paths"const temporaryRoots: string[] = []@@ -78,6 +78,20 @@ describe("UI E2E service definitions", () => {.toBe("http://localhost:8789/health")})+ it("starts and verifies only Web for a Web-only journey", () => {+ const root = mkdtempSync(resolve(tmpdir(), "alook-web-only-services-"))+ temporaryRoots.push(root)+ const web = resolve(root, E2E_PREBUILT_ENTRYPOINTS[0])+ mkdirSync(dirname(web), { recursive: true })+ writeFileSync(web, "export default {}\n")+ expect(requiredE2EZones('["web"]')).toEqual(["web"])+ expect(() => requiredE2EZones('["blog"]')).toThrow("Invalid E2E service zones")+ expect(serviceBuildCommands(true, true, root, ["web"])).toEqual([])+ expect(serviceBuildCommands(true, false, root, ["web"]).map(build => build.name)).toEqual(["web worker"])+ expect(serviceDefinitions(true, ["web"])[0].args).toContain("--web-only")+ expect(serviceDefinitions(true, ["web", "blog"])[0].args).not.toContain("--web-only")+ })+it("skips both builds only when both prebuilt worker entrypoints exist", () => {const root = mkdtempSync(resolve(tmpdir(), "alook-prebuilt-services-"))temporaryRoots.push(root)diff --git a/src/web/src/test/e2e-service-startup.test.ts b/src/web/src/test/e2e-service-startup.test.tsindex 7330f9f56..e6d37bb2e 100644--- a/src/web/src/test/e2e-service-startup.test.ts+++ b/src/web/src/test/e2e-service-startup.test.ts@@ -7,13 +7,15 @@ import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitesconst transport = vi.hoisted(() => ({ spawn: vi.fn(), spawnSync: vi.fn(), root: "" }))vi.mock("child_process", () => ({ spawn: transport.spawn, spawnSync: transport.spawnSync }))-vi.mock("./e2e-ui/_setup/paths", async () => {+vi.mock("./e2e-ui/_setup/paths", async (importOriginal) => {+ const { requiredE2EZones } = await importOriginal<typeof import("./e2e-ui/_setup/paths")>()const fs = await import("node:fs")const os = await import("node:os")const path = await import("node:path")transport.root = fs.mkdtempSync(path.resolve(os.tmpdir(), "alook-service-startup-"))return {REPO_ROOT: transport.root,+ requiredE2EZones,SERVICE_LOG_DIR: path.resolve(transport.root, "logs"),SERVICE_STATE_PATH: path.resolve(transport.root, "state.json"),resolveWsUrl: () => { throw new Error("Native startup must not resolve a split WS health URL") },@@ -134,8 +136,8 @@ describe("normal UI service startup", () => {nested: lstatSync(nested).mode & 0o777,}const seen: unknown[] = []- transport.spawnSync.mockImplementation((command) => {- if (command !== "pnpm") return { status: 0, stdout: "", stderr: "" }+ transport.spawnSync.mockImplementation((command, args) => {+ if (command !== "node" || !args.includes("@alook/web#build")) return { status: 0, stdout: "", stderr: "" }seen.push({original: readFileSync(resolve(backupDir, "prior-state"), "utf8"),mode: lstatSync(resolve(backupDir, "prior-state")).mode & 0o777,@@ -173,7 +175,7 @@ describe("normal UI service startup", () => {priorState()const previousSpawn = transport.spawnSync.getMockImplementation()!transport.spawnSync.mockImplementation((command, args, options) => {- if (command === "pnpm" && args[1] !== "db:reset") {+ if (command === "node" && args[0] === "scripts/ci/run-turbo.mjs") {mkdirSync(stateDir, { recursive: true })writeFileSync(priorFile, "build-created state")}@@ -222,7 +224,7 @@ describe("normal UI service startup", () => {it("does not back up build-created state when no local state existed before preparation", async () => {const previousSpawn = transport.spawnSync.getMockImplementation()!transport.spawnSync.mockImplementation((command, args, options) => {- if (command === "pnpm" && args[1] !== "db:reset") {+ if (command === "node" && args[0] === "scripts/ci/run-turbo.mjs") {mkdirSync(stateDir, { recursive: true })writeFileSync(priorFile, "build-created state")}diff --git a/src/web/src/test/e2e-ui/01-auth.spec.ts b/src/web/src/test/e2e-ui/01-auth.spec.tsindex 4d5460347..7f07dddd7 100644--- a/src/web/src/test/e2e-ui/01-auth.spec.ts+++ b/src/web/src/test/e2e-ui/01-auth.spec.ts@@ -103,6 +103,7 @@ test.describe("auth & first screen", () => {// Not bounced to sign-in.await expect(page).not.toHaveURL(/\/sign-in/)await page.waitForURL(/\/c/, { timeout: 20_000 , waitUntil: "commit" })+ await expect(page.getByTestId(tid.userBar)).toBeVisible()})})diff --git a/src/web/src/test/e2e-ui/04-dm.spec.ts b/src/web/src/test/e2e-ui/04-dm.spec.tsindex c2c4092f0..4e85967a6 100644--- a/src/web/src/test/e2e-ui/04-dm.spec.ts+++ b/src/web/src/test/e2e-ui/04-dm.spec.ts@@ -67,7 +67,6 @@ test.describe("direct messages", () => {level: 1,name: new RegExp(userName("alice")),})).toBeVisible()- expect(routeHistory).not.toContain("/c/me")await expect(bob.page.getByTestId(tid.message(messageId))).toHaveCount(1)await expect(bob.page.getByText(body, { exact: false }).first()).toBeVisible({ timeout: 20_000 })diff --git a/src/web/src/test/e2e-ui/05-mention-bot.spec.ts b/src/web/src/test/e2e-ui/05-mention-bot.spec.tsdeleted file mode 100644index fe05c6ceb..000000000--- a/src/web/src/test/e2e-ui/05-mention-bot.spec.ts+++ /dev/null@@ -1,54 +0,0 @@-import { test, expect } from "./_fixtures/case-fixture"-import { tid } from "./_fixtures/testids"-import { composerEditable } from "./_fixtures/actions"--import type { CaseActors } from "./_fixtures/case-fixture"--// Journey 5 — @-mentions. The mention popup shows SERVER MEMBERS (regression-// a4672ca2: not the viewer's friends). Bot reply is out of scope (no daemon /-// queue-worker); we assert the mention UI + that a mention produces an inbox-// entry for the mentioned user.-test.describe("mentions", () => {- async function prepareCase1(actors: CaseActors) {- const { seedServer, seedChannel, seedJoinServer } = actors.seed- const serverId: string = await seedServer("alice", `Mention ${Date.now()}`)- const channelId: string = await seedChannel("alice", serverId, "mentions")- await seedJoinServer("alice", "bob", serverId)- return { serverId, channelId }- }-- test("the @-mention popup lists server members", async ({ caseActors }) => {- const actors = await caseActors(["alice", "bob"])- const { asUser, userName } = actors- const { serverId, channelId } = await prepareCase1(actors)-- const { page } = await asUser("alice")- await page.goto(`/c/channels/${serverId}/${channelId}`)- await page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })-- const editable = composerEditable(page)- await editable.click()- await editable.pressSequentially("@")- // Bob (a server member) is offered as a mention option — the popup lists- // server members, so his display name appears as a role="option".- await expect(- page.getByRole("option").filter({ hasText: userName("bob") }),- ).toBeVisible({ timeout: 15_000 })- })-- test("@everyone is offered in a channel", async ({ caseActors }) => {- const actors = await caseActors(["alice", "bob"])- const { asUser } = actors- const { serverId, channelId } = await prepareCase1(actors)-- const { page } = await asUser("alice")- await page.goto(`/c/channels/${serverId}/${channelId}`)- await page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })-- const editable = composerEditable(page)- await editable.click()- await editable.pressSequentially("@")- // Virtual candidate keyed by its mention type.- await expect(page.getByTestId(tid.mentionOption("everyone"))).toBeVisible({ timeout: 15_000 })- })-})diff --git a/src/web/src/test/e2e-ui/06-channel-member-admin.spec.ts b/src/web/src/test/e2e-ui/06-channel-member-admin.spec.tsindex 4b6c248ad..deda9123e 100644--- a/src/web/src/test/e2e-ui/06-channel-member-admin.spec.ts+++ b/src/web/src/test/e2e-ui/06-channel-member-admin.spec.ts@@ -25,6 +25,10 @@ test.describe("channel & member admin", () => {await page.goto(`/c/channels/${serverId}/${channelId}`)// She's redirected away from the server she can't access.await expect(page).not.toHaveURL(new RegExp(`/channels/${serverId}/${channelId}$`), { timeout: 20_000 })+ await expect(page.getByTestId(tid.userBar)).toBeVisible()+ await expect(page.getByTestId(tid.composerInput)).toHaveCount(0)+ const denied = await page.request.get(`/api/community/channels/${channelId}`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS })+ expect(denied.status()).toBe(403)})test("the member list shows server members", async ({ caseActors }) => {diff --git a/src/web/src/test/e2e-ui/08-mobile.spec.ts b/src/web/src/test/e2e-ui/08-mobile.spec.tsindex 62b6b4b8f..542122690 100644--- a/src/web/src/test/e2e-ui/08-mobile.spec.ts+++ b/src/web/src/test/e2e-ui/08-mobile.spec.ts@@ -229,7 +229,6 @@ test.describe("mobile layout", () => {await page.goto(`/c/channels/${serverId}/${childChannelId}`)const current = page.getByRole("banner").getByText("mobile-child", { exact: true })await expect(current).toBeVisible()- expect(await current.evaluate((element) => element.tagName)).toBe("SPAN")const back = page.getByRole("button", { name: "Back" })await expect(back).toBeVisible()const historyLength = await page.evaluate(() => history.length)diff --git a/src/web/src/test/e2e-ui/10-eject-nav-auth.spec.ts b/src/web/src/test/e2e-ui/10-eject-nav-auth.spec.tsindex 40b19c4a3..f6b53d379 100644--- a/src/web/src/test/e2e-ui/10-eject-nav-auth.spec.ts+++ b/src/web/src/test/e2e-ui/10-eject-nav-auth.spec.ts@@ -13,23 +13,11 @@ test.describe("eject, navigation & logout", () => {return { serverId, channelId }}- test("direct URL to a server you're not in redirects away", async ({ caseActors }) => {- const actors = await caseActors(["alice", "carol"])- const { asUser } = actors- const { serverId, channelId } = await prepareCase1(actors)-- // Carol is not a member.- const { page } = await asUser("carol")- await page.goto(`/c/channels/${serverId}/${channelId}`)- await expect(page).not.toHaveURL(new RegExp(`/channels/${serverId}/${channelId}$`), { timeout: 20_000 })- })-- test("clicking a rail server lands on a channel, not the bare server root", async ({ caseActors }) => {+ test("a bare server URL resolves to a channel", async ({ caseActors }) => {const actors = await caseActors(["alice"])const { asUser } = actorsconst { serverId } = await prepareCase1(actors)- // Alice owns the server; navigating via the rail resolves to a channel.const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}`)// The bare-server route redirects to the first channel.diff --git a/src/web/src/test/e2e-ui/13-mentions.spec.ts b/src/web/src/test/e2e-ui/13-mentions.spec.tsindex 6253e12a7..b0a3df16f 100644--- a/src/web/src/test/e2e-ui/13-mentions.spec.ts+++ b/src/web/src/test/e2e-ui/13-mentions.spec.ts@@ -114,15 +114,6 @@ test.describe("mentions — mandatory discriminator", () => {clipboardData: transfer,}))}, content)- expect(await editable.evaluate((element) => Array.from(element.children).map((block) => ({- tag: block.tagName,- text: block.textContent,- breaks: block.querySelectorAll("br").length,- })))).toEqual(content.split("\n\n").map((block) => ({- tag: "P",- text: block.replaceAll("\n", ""),- breaks: block.split("\n").length - 1,- })))} else {await editable.fill(content)}@@ -352,11 +343,17 @@ test.describe("mentions — mandatory discriminator", () => {})test("setting a display name with # / @ / newline is rejected (400)", async ({ caseActors }) => {- const actors = await caseActors(["alice", "bob", "carol"])- const { asUser } = actors- await prepareCase1(actors)-- const { page } = await asUser("alice")+ const actors = await caseActors(["alice"])+ const originalName = actors.userName("alice")+ const { page } = await actors.asUser("alice")+ actors.onCleanup(async () => {+ await actors.seed.renameUser("alice", originalName)+ const restored = await confirmCommunityFixtureApiResponse(page.request.get("/api/community/users/me/profile", {+ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS,+ }))+ expect(restored.status()).toBe(200)+ expect(await restored.json()).toMatchObject({ name: originalName })+ })for (const bad of ["Ann#1234", "bad@name", "line\nbreak"]) {const res = await confirmCommunityFixtureApiResponse(page.request.patch("/api/community/users/me/profile", {headers: { "Content-Type": "application/json", ...CURRENT_COMMUNITY_FIXTURE_HEADERS },diff --git a/src/web/src/test/e2e-ui/15-mention-scope.spec.ts b/src/web/src/test/e2e-ui/15-mention-scope.spec.tsindex 4a5fc8217..86a613379 100644--- a/src/web/src/test/e2e-ui/15-mention-scope.spec.ts+++ b/src/web/src/test/e2e-ui/15-mention-scope.spec.ts@@ -84,7 +84,7 @@ test.describe("mentions — candidate scope", () => {test("public top-level channel → whole server roster (bob AND carol), backed by servers/:id/members", async ({ caseActors }) => {const actors = await caseActors(["alice", "bob", "carol"])- const { asUser } = actors+ const { asUser, userName } = actorsconst { serverId, publicChannelId, alice, openMentionPopup } = await prepareCase1(actors)const { page } = await asUser("alice")@@ -102,7 +102,8 @@ test.describe("mentions — candidate scope", () => {const opt = await openMentionPopup(page)// Assert a KNOWN-PRESENT row first (roster arrived), THEN the wider claim —// so a slow roster load can't false-pass an absence check.- await expect(opt.bob).toBeVisible({ timeout: 15_000 })+ await expect(page.getByRole("option").filter({ hasText: userName("bob") }).and(opt.bob))+ .toBeVisible({ timeout: 15_000 })await expect(opt.carol).toBeVisible({ timeout: 15_000 })await expect(opt.everyone).toBeVisible()// @here was removed, so its popup row must not appear.diff --git a/src/web/src/test/e2e-ui/16-jump-to-present.spec.ts b/src/web/src/test/e2e-ui/16-jump-to-present.spec.tsindex 3563c6e1a..38baa7af8 100644--- a/src/web/src/test/e2e-ui/16-jump-to-present.spec.ts+++ b/src/web/src/test/e2e-ui/16-jump-to-present.spec.ts@@ -36,7 +36,6 @@ test("anchored channel jumps to the newest tail with one request", async ({ caseawait expect(page.getByTestId(tid.message(anchorId))).toBeVisible({ timeout: 30_000 })const jumpButton = page.getByRole("button", { name: "Jump to present", exact: true })await expect(jumpButton).toBeVisible({ timeout: 20_000 })- await expect(jumpButton).toHaveAttribute("data-testid", tid.scrollToPresent)await expect(jumpButton).toHaveText("Jump to present")let newestGets = 0diff --git a/src/web/src/test/e2e-ui/18-new-divider-scroll.spec.ts b/src/web/src/test/e2e-ui/18-new-divider-scroll.spec.tsindex ff85ab0cd..747552850 100644--- a/src/web/src/test/e2e-ui/18-new-divider-scroll.spec.ts+++ b/src/web/src/test/e2e-ui/18-new-divider-scroll.spec.ts@@ -1,7 +1,7 @@import { communityFixtureFetch } from "./_fixtures/business-contract"import { test, expect } from "./_fixtures/case-fixture"import { gotoAfterUserWsAuth, sendMessage } from "./_fixtures/actions"-import { communityFrameEvents, proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"+import { communityFrameEvents, proxyCommunityWebSockets, type CapturedCommunityFrame } from "./_fixtures/community-ws-proxy"import { tid } from "./_fixtures/testids"import { WEB_URL } from "./_setup/paths"@@ -52,7 +52,30 @@ test("NEW divider does not fight upward scrolling while a peer message arrives",}const { page, context } = await asUser("alice")- const proxy = await proxyCommunityWebSockets(context)+ const liveBody = `live during upward scroll ${Date.now()}`+ const liveFrame = (frame: Parameters<typeof communityFrameEvents>[0]) => communityFrameEvents(frame).some(event =>+ event.type === "community:message.create" && event.channelId === channelId && event.message?.content === liveBody)+ const proxy = await proxyCommunityWebSockets(context, { decide: frame => liveFrame(frame) ? "hold" : "forward" })+ await page.addInitScript(() => {+ const frames: Array<{ type: string }> = []+ Object.defineProperty(window, "__e2eScrollReceivedFrames", { value: frames })+ const NativeWebSocket = window.WebSocket+ window.WebSocket = class extends NativeWebSocket {+ constructor(...args: ConstructorParameters<typeof WebSocket>) {+ super(...args)+ if (new URL(this.url).pathname !== "/api/ws/user") return+ this.addEventListener("message", (event) => {+ if (typeof event.data !== "string") return+ try {+ const frame = JSON.parse(event.data) as { type?: unknown }+ if (typeof frame?.type === "string" && frame.type.startsWith("community:")) {+ frames.push(frame as { type: string })+ }+ } catch {}+ })+ }+ }+ })await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)await page.waitForURL(new RegExp(channelId), { timeout: 20_000, waitUntil: "commit" })const divider = page.getByTestId(tid.newDivider)@@ -64,6 +87,17 @@ test("NEW divider does not fight upward scrolling while a peer message arrives",expect(box).not.toBeNull()await page.mouse.move(box!.x + box!.width / 2, box!.y + box!.height / 2)+ const liveMessageId = await seedMessage("bob", channelId, liveBody)+ const receivedCount = async () => {+ const frames = await page.evaluate(() => (window as typeof window & {+ __e2eScrollReceivedFrames: CapturedCommunityFrame[]+ }).__e2eScrollReceivedFrames)+ return frames.flatMap(communityFrameEvents).filter(event => event.type === "community:message.create"+ && event.channelId === channelId && event.message?.id === liveMessageId).length+ }+ await expect.poll(() => proxy.heldCount()).toBe(1)+ expect(await receivedCount()).toBe(0)+const recorder = await scroller.evaluateHandle((element) => {const root = element as HTMLElementconst samples: BodySample[] = []@@ -100,25 +134,24 @@ test("NEW divider does not fight upward scrolling while a peer message arrives",})let bodySamples: BodySample[] = []- let liveMessageId = ""try {- const liveAppend = (async () => {- await page.waitForTimeout(250) // inject the append during the upward-scroll gesture- return seedMessage("bob", channelId, `live during upward scroll ${Date.now()}`)- })()for (let index = 0; index < 60; index++) {await page.mouse.wheel(0, -24)+ if (index === 10) expect(proxy.releaseHeld(liveFrame)).toBe(1)await page.waitForTimeout(24) // fixed wheel-event cadence under testawait recorder.evaluate((recording) => recording.sample())+ if (index === 30) {+ expect(await receivedCount()).toBe(1)+ }}- liveMessageId = await liveAppendawait page.waitForTimeout(250) // post-append scroll-correction exclusion window} finally {+ proxy.releaseHeld(liveFrame)bodySamples = await recorder.evaluate((recording) => recording.finish())await recorder.dispose()}- await expect.poll(() => proxy.frames.filter(frame => communityFrameEvents(frame).some(event =>+ expect(proxy.frames.filter(frame => communityFrameEvents(frame).some(event =>event.type === "community:message.create" && event.channelId === channelId && event.message?.id === liveMessageId,)).length).toBe(1)expect(bodySamples.length).toBeGreaterThan(1)diff --git a/src/web/src/test/e2e-ui/25-cold-community-auth.spec.ts b/src/web/src/test/e2e-ui/25-cold-community-auth.spec.tsnew file mode 100644index 000000000..81d86ffb0--- /dev/null+++ b/src/web/src/test/e2e-ui/25-cold-community-auth.spec.ts@@ -0,0 +1,55 @@+import { test, expect } from "./_fixtures/case-fixture"+import { composerEditable } from "./_fixtures/actions"+import { tid } from "./_fixtures/testids"++test("slow auth and an initial retry never block a cold Community page", async ({ caseActors, caseResources }) => {+ test.setTimeout(90_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedServer } = actors.seed++ const serverId = await seedServer("alice", `Reconnect cold start ${Date.now()}`)+ const channelId = await seedChannel("alice", serverId, "reconnect-cold-start")+ const alice = await asUser("alice")+ let tokenRequests = 0+ let releaseTokens!: () => void+ let holdTokens = true+ const tokenGate = new Promise<void>((resolve) => {+ releaseTokens = resolve+ })+ caseResources.own(releaseTokens, async (captured) => { captured() })+ let socketAttempts = 0++ await alice.page.route("**/api/ws/token", async (route) => {+ tokenRequests += 1+ if (holdTokens) await tokenGate+ await route.continue()+ })+ await alice.page.routeWebSocket((url) => url.pathname.endsWith("/user"), (ws) => {+ socketAttempts += 1+ void ws.close({ code: 1012, reason: "cold start auth retry" })+ })+ await alice.page.setViewportSize({ width: 390, height: 844 })++ try {+ await alice.page.goto(`/c/channels/${serverId}/${channelId}`)+ const composer = composerEditable(alice.page)+ await expect(composer).toBeVisible({ timeout: 30_000 })+ await expect.poll(() => tokenRequests).toBeGreaterThan(0)+ await alice.page.waitForTimeout(1_600)+ await expect(alice.page.getByTestId(tid.wsReconnectOverlay)).toHaveCount(0)+ await expect.poll(() => composer.evaluate((element) => element.closest("[inert]") !== null))+ .toBe(false)+ await composer.fill("Cold start stays usable")+ await expect(composer).toContainText("Cold start stays usable")++ holdTokens = false+ releaseTokens()+ await expect.poll(() => socketAttempts, { timeout: 20_000 }).toBeGreaterThan(1)+ await expect(composer).toContainText("Cold start stays usable")+ } finally {+ holdTokens = false+ releaseTokens()+ }+})diff --git a/src/web/src/test/e2e-ui/25-community-cache-first-warm-reload.spec.ts b/src/web/src/test/e2e-ui/25-community-cache-first-warm-reload.spec.tsnew file mode 100644index 000000000..005a794d0--- /dev/null+++ b/src/web/src/test/e2e-ui/25-community-cache-first-warm-reload.spec.ts@@ -0,0 +1 @@+import "./community-cache-first-warm-reload.journey"diff --git a/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts b/src/web/src/test/e2e-ui/25-reconnect-interactive-cache.spec.tssimilarity index 60%rename from src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.tsrename to src/web/src/test/e2e-ui/25-reconnect-interactive-cache.spec.tsindex 2ca670d99..8a84ba383 100644--- a/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts+++ b/src/web/src/test/e2e-ui/25-reconnect-interactive-cache.spec.ts@@ -1,88 +1,7 @@import type { Page, WebSocketRoute } from "@playwright/test"import { test, expect } from "./_fixtures/case-fixture"-import {- composerEditable,- gotoAfterUserWsAuth,-} from "./_fixtures/actions"-+import { composerEditable, gotoAfterUserWsAuth } from "./_fixtures/actions"import { tid } from "./_fixtures/testids"-import "./community-cache-first-warm-reload.journey"--const USER_WS_AUTH_CONSUMED_ATTRIBUTE = "data-e2e-user-ws-auth-consumed"--async function installUserWsAuthConsumedBarrier(page: Page) {- await page.addInitScript(({ attribute }) => {- const NativeWebSocket = window.WebSocket- window.WebSocket = class extends NativeWebSocket {- constructor(...args: ConstructorParameters<typeof WebSocket>) {- super(...args)- if (!new URL(this.url).pathname.endsWith("/user")) return- this.addEventListener("message", (event) => {- if (typeof event.data !== "string") return- try {- const message = JSON.parse(event.data) as { type?: string }- if (message.type !== "auth.ok") return- setTimeout(() => {- document.documentElement.setAttribute(attribute, "true")- }, 0)- } catch {}- })- }- }- }, { attribute: USER_WS_AUTH_CONSUMED_ATTRIBUTE })-}--test("slow auth and an initial retry never block a cold Community page", async ({ caseActors, caseResources }) => {- test.setTimeout(90_000)-- const actors = await caseActors(["alice"])- const { asUser } = actors- const { seedChannel, seedServer } = actors.seed-- const serverId = await seedServer("alice", `Reconnect cold start ${Date.now()}`)- const channelId = await seedChannel("alice", serverId, "reconnect-cold-start")- const alice = await asUser("alice")- let tokenRequests = 0- let releaseTokens!: () => void- let holdTokens = true- const tokenGate = new Promise<void>((resolve) => {- releaseTokens = resolve- })- caseResources.own(releaseTokens, async (captured) => { captured() })- let socketAttempts = 0-- await alice.page.route("**/api/ws/token", async (route) => {- tokenRequests += 1- if (holdTokens) await tokenGate- await route.continue()- })- await alice.page.routeWebSocket((url) => url.pathname.endsWith("/user"), (ws) => {- socketAttempts += 1- void ws.close({ code: 1012, reason: "cold start auth retry" })- })- await alice.page.setViewportSize({ width: 390, height: 844 })-- try {- await alice.page.goto(`/c/channels/${serverId}/${channelId}`)- const composer = composerEditable(alice.page)- await expect(composer).toBeVisible({ timeout: 30_000 })- await expect.poll(() => tokenRequests).toBeGreaterThan(0)- await alice.page.waitForTimeout(1_600)- await expect(alice.page.getByTestId(tid.wsReconnectOverlay)).toHaveCount(0)- await expect.poll(() => composer.evaluate((element) => element.closest("[inert]") !== null))- .toBe(false)- await composer.fill("Cold start stays usable")- await expect(composer).toContainText("Cold start stays usable")-- holdTokens = false- releaseTokens()- await expect.poll(() => socketAttempts, { timeout: 20_000 }).toBeGreaterThan(1)- await expect(composer).toContainText("Cold start stays usable")- } finally {- holdTokens = false- releaseTokens()- }-})test("a real WebSocket outage keeps cached content interactive and Retry reconnects", async ({ caseActors, caseResources }, testInfo) => {test.setTimeout(120_000)@@ -248,65 +167,3 @@ test("a real WebSocket outage keeps cached content interactive and Retry reconne})}})--test("an active onboarding form keeps focus priority during a reconnect", async ({ caseResources }) => {- test.setTimeout(90_000)- const context = await caseResources.newContext({ viewport: { width: 390, height: 844 } })- const page = await context.newPage()- let userWs: WebSocketRoute | null = null- let blockUserWs = false- await page.routeWebSocket((url) => url.pathname.endsWith("/user"), (ws) => {- userWs = ws- if (blockUserWs) {- ws.close({ code: 1012, reason: "active onboarding reconnect e2e outage" })- return- }- ws.connectToServer()- })-- let caseJourneyFailure1: unknown-let caseJourneyFailure1Present = false- try {- await installUserWsAuthConsumedBarrier(page)- await page.goto("/sign-in")- await page.getByRole("button", { name: "Continue with email", exact: true }).click()- await page.getByRole("textbox", { name: "Email" }).fill(- `guide-reconnect-${process.pid}-${Date.now()}@example.com`,- )- await page.getByRole("button", { name: "Sign in", exact: true }).click()- await page.waitForURL("**/c/me/machines", { waitUntil: "commit" })- const onboarding = page.getByTestId(tid.onboardingHarnessDialog)- await expect(onboarding).toBeVisible()- await expect(page.locator("html")).toHaveAttribute(- USER_WS_AUTH_CONSUMED_ATTRIBUTE,- "true",- { timeout: 20_000 },- )-- const onboardingAction = onboarding.getByRole("radio", { name: "Claude Code" })- await onboardingAction.focus()- blockUserWs = true- expect(userWs).not.toBeNull()- await userWs!.close({ code: 1012, reason: "active onboarding reconnect e2e outage" })-- await page.waitForTimeout(1_600)- const failedStatus = page.getByTestId(tid.wsReconnectOverlay)- if (await failedStatus.count()) {- await expect(failedStatus).toHaveAttribute("data-ws-status", "failed")- await expect(failedStatus).not.toHaveAttribute("aria-modal")- }- await expect(onboarding).toBeVisible()- await expect(onboardingAction).toBeFocused()- expect(await onboarding.evaluate((element) => element.closest("[inert]") !== null)).toBe(false)-- blockUserWs = false- await expect(onboarding).toBeVisible()- } catch (error) { caseJourneyFailure1 = error; caseJourneyFailure1Present = true; throw error } finally {- try {-- blockUserWs = false- await caseResources.closeContext(context)-- } catch (cleanupError) { if (caseJourneyFailure1Present) throw new AggregateError([caseJourneyFailure1, cleanupError], "Journey and resource exit both failed"); throw cleanupError }- }-})diff --git a/src/web/src/test/e2e-ui/25-reconnect-onboarding-focus.spec.ts b/src/web/src/test/e2e-ui/25-reconnect-onboarding-focus.spec.tsnew file mode 100644index 000000000..3d681342e--- /dev/null+++ b/src/web/src/test/e2e-ui/25-reconnect-onboarding-focus.spec.ts@@ -0,0 +1,66 @@+import type { WebSocketRoute } from "@playwright/test"+import { test, expect } from "./_fixtures/case-fixture"+import { tid } from "./_fixtures/testids"+import { USER_WS_AUTH_CONSUMED_ATTRIBUTE, installUserWsAuthConsumedBarrier } from "./_fixtures/community-ws-reconnect"++test("an active onboarding form keeps focus priority during a reconnect", async ({ caseResources }) => {+ test.setTimeout(90_000)+ const context = await caseResources.newContext({ viewport: { width: 390, height: 844 } })+ const page = await context.newPage()+ let userWs: WebSocketRoute | null = null+ let blockUserWs = false+ await page.routeWebSocket((url) => url.pathname.endsWith("/user"), (ws) => {+ userWs = ws+ if (blockUserWs) {+ ws.close({ code: 1012, reason: "active onboarding reconnect e2e outage" })+ return+ }+ ws.connectToServer()+ })++ let caseJourneyFailure1: unknown+let caseJourneyFailure1Present = false+ try {+ await installUserWsAuthConsumedBarrier(page)+ await page.goto("/sign-in")+ await page.getByRole("button", { name: "Continue with email", exact: true }).click()+ await page.getByRole("textbox", { name: "Email" }).fill(+ `guide-reconnect-${process.pid}-${Date.now()}@example.com`,+ )+ await page.getByRole("button", { name: "Sign in", exact: true }).click()+ await page.waitForURL("**/c/me/machines", { waitUntil: "commit" })+ const onboarding = page.getByTestId(tid.onboardingHarnessDialog)+ await expect(onboarding).toBeVisible()+ await expect(page.locator("html")).toHaveAttribute(+ USER_WS_AUTH_CONSUMED_ATTRIBUTE,+ "true",+ { timeout: 20_000 },+ )++ const onboardingAction = onboarding.getByRole("radio", { name: "Claude Code" })+ await onboardingAction.focus()+ blockUserWs = true+ expect(userWs).not.toBeNull()+ await userWs!.close({ code: 1012, reason: "active onboarding reconnect e2e outage" })++ await page.waitForTimeout(1_600)+ const failedStatus = page.getByTestId(tid.wsReconnectOverlay)+ if (await failedStatus.count()) {+ await expect(failedStatus).toHaveAttribute("data-ws-status", "failed")+ await expect(failedStatus).not.toHaveAttribute("aria-modal")+ }+ await expect(onboarding).toBeVisible()+ await expect(onboardingAction).toBeFocused()+ expect(await onboarding.evaluate((element) => element.closest("[inert]") !== null)).toBe(false)++ blockUserWs = false+ await expect(onboarding).toBeVisible()+ } catch (error) { caseJourneyFailure1 = error; caseJourneyFailure1Present = true; throw error } finally {+ try {++ blockUserWs = false+ await caseResources.closeContext(context)++ } catch (cleanupError) { if (caseJourneyFailure1Present) throw new AggregateError([caseJourneyFailure1, cleanupError], "Journey and resource exit both failed"); throw cleanupError }+ }+})diff --git a/src/web/src/test/e2e-ui/30-activity-older-pages.spec.ts b/src/web/src/test/e2e-ui/30-activity-older-pages.spec.tsnew file mode 100644index 000000000..1c6d5d31c--- /dev/null+++ b/src/web/src/test/e2e-ui/30-activity-older-pages.spec.ts@@ -0,0 +1,108 @@+import { test, expect } from "./_fixtures/case-fixture"+import { gotoAfterUserWsAuth } from "./_fixtures/actions"+import { tid } from "./_fixtures/testids"+import { connectMachine } from "./_fixtures/community-machine"+import { prepareCase, settleSheet, attachPageScreenshot, type ActivityAnchorPage, activityAnchorSnapshot, settleActivityPosition, gateOlderActivityPages, seedActivityHistory, expectActivityPosition } from "./_fixtures/bot-profile-audit"++for (const scenario of ["same-day", "cross-day"] as const) {+for (const width of [1280, 390] as const) {+test(`Activity ${scenario} older pages preserve real event positions at ${width}`, async ({ caseActors, caseResources }, testInfo) => {+ test.setTimeout(120_000)+ const actors = await caseActors(["alice"])+ const { pairMachine, createBot, jsonRequest, headersFor } = await prepareCase(actors, caseResources)+ const { credential, machineId } = await pairMachine()+ const machine = connectMachine(credential, caseResources, { machineId, headers: headersFor("alice") })+ await machine.opened+ const suffix = Date.now().toString(36)+ const botId = await createBot(machineId, `Anchor ${scenario} ${width} ${suffix}`)+ let gate: Awaited<ReturnType<typeof gateOlderActivityPages>> | undefined+ let journeyFailure: unknown+ let journeyFailurePresent = false+ const positioning: Array<{ page: number; target: number; deltaY: number; olderRequests: string[] } & Awaited<ReturnType<typeof settleActivityPosition>>> = []+ try {+ const history = await seedActivityHistory({ machine, botId, suffix, scenario, caseResources, jsonRequest, testInfo })+ const { page } = await actors.asUser("alice", { viewport: { width, height: 900 }, colorScheme: width === 390 ? "dark" : "light" })+ gate = await gateOlderActivityPages(page, botId, caseResources)+ await gotoAfterUserWsAuth(page, `/c/me/bots?audit=${botId}`)+ const sheet = page.getByTestId(tid.botActivityModal)+ await settleSheet(sheet)+ const scroller = sheet.getByRole("region", { name: "Activity log", exact: true })+ await expect(scroller).toHaveCount(1)+ await expect.poll(() => scroller.evaluate(element => Boolean(element.querySelector("[data-activity-event-id]"))+ && element.scrollHeight > element.clientHeight+ && element.scrollTop + element.clientHeight >= element.scrollHeight - 1)).toBe(true)+ for (const [index, target] of [0, 80].entries()) {+ await scroller.hover()+ await page.mouse.wheel(0, -1_000_000)+ const zeroPosition = await settleActivityPosition(scroller, 0)+ positioning.push({ page: index + 1, target: 0, deltaY: -1_000_000, olderRequests: gate.entries.map(entry => entry.url), ...zeroPosition })+ expect(zeroPosition.settled, "physical zero and rendered geometry settle before choosing the reading position").toBe(true)+ if (target > 0) {+ await page.mouse.wheel(0, target)+ const nearTopPosition = await settleActivityPosition(scroller, target)+ positioning.push({ page: index + 1, target, deltaY: target, olderRequests: gate.entries.map(entry => entry.url), ...nearTopPosition })+ expect(nearTopPosition.settled, "physical near-top target and rendered geometry settle without another wheel").toBe(true)+ }+ await expect.poll(async () => Math.abs(await scroller.evaluate(element => element.scrollTop) - target)).toBeLessThanOrEqual(1)+ await expect.poll(() => gate!.entries.length).toBe(index + 1)+ const pending = gate.entries[index]+ const cursor = history[150 - index * 50]+ const url = new URL(pending.url)+ expect(url.searchParams.get("limit")).toBe("50")+ expect(url.searchParams.get("beforeId")).toBe(cursor.id)+ expect(url.searchParams.get("beforeCreatedAt")).toBe(cursor.createdAt)+ const before = await activityAnchorSnapshot(scroller)+ expect(Math.abs(before.scrollTop - target), "physical target at retained snapshot").toBeLessThanOrEqual(1)+ expect(before.overflowAnchor).toBe("none")+ const anchor = before.events.find(event => event.top >= 32 && event.bottom <= before.clientHeight)+ expect(anchor).toBeDefined()+ await attachPageScreenshot(testInfo, `activity-anchor-${scenario}-${width}-before-page-${index + 1}`, page)+ const atRelease = await activityAnchorSnapshot(scroller)+ expect(Math.abs(atRelease.scrollTop - target), "physical target at response release").toBeLessThanOrEqual(1)+ const releaseAnchor = atRelease.events.find(event => event.id === anchor!.id)+ expect(releaseAnchor).toBeDefined()+ expect(Math.abs(releaseAnchor!.top - anchor!.top), "named event at response release").toBeLessThanOrEqual(1)+ const [response] = await Promise.all([+ page.waitForResponse(value => value.url() === pending.url && value.request().method() === "GET"),+ Promise.resolve().then(() => pending.release()),+ ])+ expect(response.status()).toBe(200)+ const body = await response.json() as ActivityAnchorPage+ expect(body.events.map(event => ({ id: event.id, createdAt: event.createdAt })))+ .toEqual(history.slice(100 - index * 50, 150 - index * 50).reverse())+ expect(body.nextCursor).not.toBeNull()+ await expect.poll(() => scroller.evaluate(element => element.scrollHeight)).toBeGreaterThan(before.scrollHeight + 300)+ try {+ await expect.poll(async () => {+ const after = await activityAnchorSnapshot(scroller)+ const kept = after.events.find(event => event.id === anchor!.id)+ return kept ? Math.abs(kept.top - anchor!.top) : Number.POSITIVE_INFINITY+ }).toBeLessThanOrEqual(1)+ await scroller.evaluate(() => new Promise<void>(resolveFrame => {+ requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(() => resolveFrame())))+ }))+ await expectActivityPosition(scroller, anchor!)+ expect(gate.entries).toHaveLength(index + 1)+ } finally {+ await testInfo.attach(`activity-anchor-${scenario}-${width}-page-${index + 1}`, {+ body: JSON.stringify({ scenario, width, target, anchor, request: pending.url, returnedIds: body.events.map(event => event.id), before, atRelease, after: await activityAnchorSnapshot(scroller), olderRequestCount: gate.entries.length }),+ contentType: "application/json",+ })+ await attachPageScreenshot(testInfo, `activity-anchor-${scenario}-${width}-page-${index + 1}`, page)+ }+ }+ } catch (error) { journeyFailure = error; journeyFailurePresent = true; throw error } finally {+ const exitErrors: unknown[] = []+ try { await gate?.close() } catch (error) { exitErrors.push(error) }+ try { await machine.close() } catch (error) { exitErrors.push(error) }+ try {+ await testInfo.attach(`activity-anchor-${scenario}-${width}-positioning`, {+ body: JSON.stringify({ responseReleaseTargets: [0, 80], requestStartPosition: "not asserted; the gate can hold a request during the zero-position step", positioning }),+ contentType: "application/json",+ })+ } catch (error) { exitErrors.push(error) }+ if (exitErrors.length) throw new AggregateError(journeyFailurePresent ? [journeyFailure, ...exitErrors] : exitErrors, "Activity journey, cleanup or evidence retention failed")+ }+ })+}+}diff --git a/src/web/src/test/e2e-ui/30-activity-recovery.spec.ts b/src/web/src/test/e2e-ui/30-activity-recovery.spec.tsnew file mode 100644index 000000000..527c7b56e--- /dev/null+++ b/src/web/src/test/e2e-ui/30-activity-recovery.spec.ts@@ -0,0 +1,178 @@+import { test, expect } from "./_fixtures/case-fixture"+import { gotoAfterUserWsAuth } from "./_fixtures/actions"+import { tid } from "./_fixtures/testids"+import { connectMachine } from "./_fixtures/community-machine"+import { prepareCase, settleSheet, attachPageScreenshot, type ActivityAnchorPage, activityAnchorSnapshot, gateOlderActivityPages, seedActivityHistory, observeActivityFrames, publishActivityReset, expectActivityPosition, visibleActivityAnchor } from "./_fixtures/bot-profile-audit"++for (const width of [1280, 390] as const) {+test(`Activity recovery, live reading and reopen preserve event ownership at ${width}`, async ({ caseActors, caseResources }, testInfo) => {+ test.setTimeout(120_000)+ const actors = await caseActors(["alice"])+ const { pairMachine, createBot, jsonRequest, headersFor } = await prepareCase(actors, caseResources)+ const suffix = Date.now().toString(36)+ const { credential, machineId } = await pairMachine()+ const machine = connectMachine(credential, caseResources, { machineId, headers: headersFor("alice") })+ await machine.opened+ const botId = await createBot(machineId, `Recovery ${width} ${suffix}`)+ let gate: Awaited<ReturnType<typeof gateOlderActivityPages>> | undefined+ let journeyFailure: unknown+ let journeyFailurePresent = false+ const steps: Array<Record<string, unknown>> = []+ try {+ const history = await seedActivityHistory({ machine, botId, suffix, scenario: "same-day", caseResources, jsonRequest, testInfo })+ const { page } = await actors.asUser("alice", { viewport: { width, height: 900 }, colorScheme: width === 390 ? "dark" : "light" })+ const frames = observeActivityFrames(page, caseResources)+ gate = await gateOlderActivityPages(page, botId, caseResources)+ await gotoAfterUserWsAuth(page, `/c/me/bots?audit=${botId}`)+ const sheet = page.getByTestId(tid.botActivityModal)+ await settleSheet(sheet)+ const scroller = sheet.getByRole("region", { name: "Activity log", exact: true })+ await expect(scroller).toHaveCSS("overflow-anchor", "none")+ const record = async (phase: string) => {+ steps.push({ phase, snapshot: await activityAnchorSnapshot(scroller), olderRequests: gate!.entries.map(entry => entry.url) })+ await attachPageScreenshot(testInfo, `activity-recovery-${width}-${phase}`, page)+ }+ await expect.poll(() => scroller.evaluate(element => Boolean(element.querySelector("[data-activity-event-id]"))+ && element.scrollHeight > element.clientHeight+ && element.scrollTop + element.clientHeight >= element.scrollHeight - 1)).toBe(true)+ await scroller.hover()+ await page.mouse.wheel(0, -1_000_000)+ await expect.poll(() => scroller.evaluate(element => element.scrollTop)).toBe(0)+ await expect.poll(() => gate!.entries.length).toBe(1)+ const anchor = await visibleActivityAnchor(scroller)+ const cursor = history[150]+ await record("before-error")+ for (const index of [0, 1]) {+ await expect.poll(() => gate!.entries.length).toBe(index + 1)+ const pending = gate.entries[index]+ const url = new URL(pending.url)+ expect(url.searchParams.get("beforeId")).toBe(cursor.id)+ expect(url.searchParams.get("beforeCreatedAt")).toBe(cursor.createdAt)+ const atRelease = await activityAnchorSnapshot(scroller)+ steps.push({ phase: `before-error-release-${index + 1}`, snapshot: atRelease })+ expect(atRelease.scrollTop, "physical target before injected error").toBe(0)+ const releaseAnchor = atRelease.events.find(event => event.id === anchor.id)+ expect(releaseAnchor).toBeDefined()+ expect(Math.abs(releaseAnchor!.top - anchor.top)).toBeLessThanOrEqual(1)+ const [response] = await Promise.all([+ page.waitForResponse(value => value.url() === pending.url),+ Promise.resolve().then(() => pending.release(503)),+ ])+ expect(response.status()).toBe(503)+ steps.push({ phase: `injected-error-${index + 1}`, url: pending.url, status: response.status() })+ }+ const retry = sheet.getByRole("button", { name: "Retry older", exact: true })+ await expect(retry).toBeEnabled()+ await expectActivityPosition(scroller, anchor)+ await scroller.evaluate(() => new Promise<void>(resolveFrame => {+ requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(() => resolveFrame())))+ }))+ expect(gate.entries).toHaveLength(2)+ await record("failed-and-stopped")+ await retry.click()+ await expect.poll(() => gate!.entries.length).toBe(3)+ expect(gate.entries[2].url).toBe(gate.entries[0].url)+ const beforeRecovery = await activityAnchorSnapshot(scroller)+ steps.push({ phase: "before-recovery-release", snapshot: beforeRecovery })+ expect(beforeRecovery.scrollTop, "physical target before recovery").toBe(0)+ const recoveryAnchor = beforeRecovery.events.find(event => event.id === anchor.id)+ expect(recoveryAnchor).toBeDefined()+ expect(Math.abs(recoveryAnchor!.top - anchor.top)).toBeLessThanOrEqual(1)+ const [recovered] = await Promise.all([+ page.waitForResponse(value => value.url() === gate!.entries[2].url && value.status() === 200),+ Promise.resolve().then(() => gate!.entries[2].release()),+ ])+ const recoveredBody = await recovered.json() as ActivityAnchorPage+ expect(recoveredBody.events.map(event => ({ id: event.id, createdAt: event.createdAt }))).toEqual(history.slice(100, 150).reverse())+ expect(recoveredBody.nextCursor).toEqual({ beforeCreatedAt: history[100].createdAt, beforeId: history[100].id })+ steps.push({ phase: "recovery-response", status: recovered.status(), body: recoveredBody })+ await expect.poll(() => scroller.evaluate(element => element.scrollHeight)).toBeGreaterThan(beforeRecovery.scrollHeight + 300)+ await expect(retry).toHaveCount(0)+ await expectActivityPosition(scroller, anchor)+ expect(gate.entries).toHaveLength(3)+ await record("recovered")+ const publish = (label: string, createdAt: string) => publishActivityReset({+ machine, botId, suffix, id: `bae_${label}_${suffix}`, createdAt, frames, caseResources, jsonRequest, testInfo,+ })+ const liveId = `bae_history_${suffix}`+ const liveTime = Date.parse(history[199].createdAt) + 86_400_000+ await publish("history", new Date(liveTime).toISOString())+ await expectActivityPosition(scroller, anchor)+ await expect(scroller.locator(`[data-activity-event-id="${liveId}"]`)).toHaveCount(0)+ await record("live-while-reading")+ await publish("late", new Date(Date.parse(history[140].createdAt) + 500).toISOString())+ await expectActivityPosition(scroller, anchor)+ await record("late-interleave")+ await page.setViewportSize({ width, height: 760 })+ await expectActivityPosition(scroller, anchor)+ await record("resized")+ const beforeTakeover = await scroller.evaluate(element => element.scrollTop)+ await scroller.hover()+ await page.mouse.wheel(0, 150)+ await expect.poll(() => scroller.evaluate(element => element.scrollTop)).toBeGreaterThan(beforeTakeover + 100)+ const readerAnchor = await visibleActivityAnchor(scroller)+ expect(readerAnchor.id).not.toBe(anchor.id)+ await publish("reader", new Date(liveTime + 1_000).toISOString())+ await expectActivityPosition(scroller, readerAnchor)+ await record("reader-takeover")+ await scroller.hover()+ await page.mouse.wheel(0, 1_000_000)+ await expect.poll(() => scroller.evaluate(element => element.scrollTop + element.clientHeight >= element.scrollHeight - 1)).toBe(true)+ const tailId = `bae_tail_${suffix}`+ await publish("tail", new Date().toISOString())+ await expect(scroller.locator(`[data-activity-event-id="${tailId}"]`)).toBeVisible()+ await expect.poll(() => scroller.evaluate(element => element.scrollTop + element.clientHeight >= element.scrollHeight - 1)).toBe(true)+ await expect(scroller.locator("[data-activity-date]").filter({ hasText: /^Today$/ }).last()).toBeVisible()+ await record("tail-follow")+ await gate.close()+ steps.push({ phase: "older-control-retired-before-navigation", requests: gate.entries.map(entry => entry.url) })+ await sheet.getByRole("button", { name: "Close", exact: true }).click()+ await expect(sheet).toHaveCount(0)+ await expect(page).toHaveURL("/c/me/bots")+ await gotoAfterUserWsAuth(page, `/c/me/bots?audit=${botId}`)+ await settleSheet(sheet)+ await expect(scroller.locator(`[data-activity-event-id="${tailId}"]`)).toBeVisible()+ await expect.poll(() => scroller.evaluate(element => element.scrollTop + element.clientHeight >= element.scrollHeight - 1)).toBe(true)+ await record("reopened")+ const otherBotId = await createBot(machineId, `Other ${width} ${suffix}`)+ await gotoAfterUserWsAuth(page, `/c/me/bots?audit=${otherBotId}`)+ await settleSheet(sheet)+ const otherId = `bae_other_${suffix}`+ await publishActivityReset({ machine, botId: otherBotId, suffix, id: otherId, createdAt: new Date().toISOString(), frames, caseResources, jsonRequest, testInfo })+ await expect(scroller.locator(`[data-activity-event-id="${otherId}"]`)).toBeVisible()+ await expect(scroller.locator(`[data-activity-event-id="${tailId}"]`)).toHaveCount(0)+ await record("other-bot")+ gate = await gateOlderActivityPages(page, botId, caseResources)+ steps.push({ phase: "pending-control-installed-before-return" })+ await gotoAfterUserWsAuth(page, `/c/me/bots?audit=${botId}`)+ await settleSheet(sheet)+ await expect(scroller.locator(`[data-activity-event-id="${tailId}"]`)).toBeVisible()+ const requestsBeforeWheel = gate.entries.length+ await scroller.hover()+ await page.mouse.wheel(0, -1_000_000)+ await expect.poll(() => gate!.entries.length).toBe(1)+ const pendingUrl = gate.entries[0].url+ const pendingSearch = new URL(pendingUrl).searchParams+ const pendingCursor = history.find(event => event.id === pendingSearch.get("beforeId"))+ expect(pendingCursor).toBeDefined()+ expect(pendingSearch.get("beforeCreatedAt")).toBe(pendingCursor!.createdAt)+ expect(pendingSearch.get("limit")).toBe("50")+ await expect(sheet).toBeVisible()+ steps.push({ phase: "owned-pending-route-ready", requestsBeforeWheel, url: pendingUrl, cursor: pendingCursor, snapshot: await activityAnchorSnapshot(scroller) })+ const failed = page.waitForEvent("requestfailed", { predicate: request => request.url() === pendingUrl })+ await gate.close()+ const aborted = await failed+ expect(aborted.failure()?.errorText).toBeTruthy()+ steps.push({ phase: "owned-pending-route-exit", url: aborted.url(), failure: aborted.failure() })+ await sheet.getByRole("button", { name: "Close", exact: true }).click()+ await expect(sheet).toHaveCount(0)+ await attachPageScreenshot(testInfo, `activity-recovery-${width}-closed`, page)+ } catch (error) { journeyFailure = error; journeyFailurePresent = true; throw error } finally {+ await testInfo.attach(`activity-recovery-${width}-steps`, { body: JSON.stringify({ width, botId, steps }), contentType: "application/json" })+ try {+ await gate?.close()+ await machine.close()+ } catch (cleanupError) { if (journeyFailurePresent) throw new AggregateError([journeyFailure, cleanupError], "Journey and resource exit both failed"); throw cleanupError }+ }+ })+}diff --git a/src/web/src/test/e2e-ui/30-audit-hover-touch.spec.ts b/src/web/src/test/e2e-ui/30-audit-hover-touch.spec.tsnew file mode 100644index 000000000..998da1294--- /dev/null+++ b/src/web/src/test/e2e-ui/30-audit-hover-touch.spec.ts@@ -0,0 +1,94 @@+import { communityFixtureFetch } from "./_fixtures/business-contract"+import { test, expect } from "./_fixtures/case-fixture"+import { gotoAfterUserWsAuth } from "./_fixtures/actions"+import { tid } from "./_fixtures/testids"+import { WEB_URL } from "./_setup/paths"+import { connectMachine } from "./_fixtures/community-machine"+import { prepareCase, settleSheet, expectSheetThemeTokens, attachPageScreenshot } from "./_fixtures/bot-profile-audit"++test("full audit log reveals a truncated row by hover and touch", async ({ caseActors, caseResources }, testInfo) => {+ test.setTimeout(120_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { headersFor, pairMachine, createBot } = await prepareCase(actors, caseResources)++ const suffix = Date.now().toString(36)+ const longAuditTarget = `/Users/alice/workspace/${"deeply-nested-audit-target/".repeat(5)}result-${suffix}.md`+ const fullAuditText = `read · ${longAuditTarget}`+ const { credential, machineId } = await pairMachine()+ const machine = connectMachine(credential, caseResources, { machineId, headers: headersFor("alice") })+ await machine.opened+ const botId = await createBot(machineId, `Tooltip bot ${suffix}`)++ let caseJourneyFailure1: unknown+let caseJourneyFailure1Present = false+ try {+ machine.socket.send(JSON.stringify({+ type: "bot_audit_event",+ agentId: botId,+ sessionId: `session-${suffix}`,+ launchId: `launch-${suffix}`,+ event: { kind: "tool_call", payload: { name: "Read", target: longAuditTarget } },+ }))++ await expect.poll(async () => {+ const response = await communityFixtureFetch(+ `${WEB_URL}/api/community/bots/${botId}/audit-log?limit=10`,+ { headers: headersFor("alice") },+ )+ if (!response.ok) return false+ const { events } = (await response.json()) as {+ events: Array<{ payload?: { target?: string } | null }>+ }+ return events.some((event) => event.payload?.target === longAuditTarget)+ }).toBe(true)++ const { page } = await asUser("alice")+ await page.setViewportSize({ width: 1280, height: 900 })+ await gotoAfterUserWsAuth(page, `/c/me/bots?audit=${botId}`)+ const sheet = page.getByTestId(tid.botActivityModal)+ await settleSheet(sheet)+ const trigger = sheet.locator("[data-activity-tooltip-trigger]").filter({ hasText: "read" })+ await expect(trigger).toHaveCount(1)+ await expect.poll(() => trigger.locator("span").first().evaluate((element) => (+ element.scrollWidth > element.clientWidth+ ))).toBe(true)++ await trigger.hover()+ const tooltip = page.getByRole("tooltip")+ await expect(tooltip).toHaveText(fullAuditText)+ await expect(tooltip).toHaveCSS("opacity", "1")+ await attachPageScreenshot(testInfo, "bot-activity-log-tooltip-desktop", page)+ await page.emulateMedia({ colorScheme: "dark" })+ await expect(page.locator("html")).toHaveClass(/dark/)+ await settleSheet(sheet)+ await expectSheetThemeTokens(sheet)+ await expect(tooltip).toHaveCSS("opacity", "1")+ await attachPageScreenshot(testInfo, "bot-activity-log-tooltip-desktop-dark", page)+ await page.mouse.move(0, 0)+ await expect(tooltip).toBeHidden()++ await page.setViewportSize({ width: 390, height: 844 })+ await page.emulateMedia({ colorScheme: "light" })+ await expect(page.locator("html")).not.toHaveClass(/dark/)+ await settleSheet(sheet)+ await trigger.click()+ const detailDialog = page.getByRole("dialog", { name: "Activity details" })+ await expect(detailDialog.getByTestId(tid.botActivityDetail)).toHaveText(fullAuditText)+ await attachPageScreenshot(testInfo, "bot-activity-log-detail-mobile", page)+ await page.emulateMedia({ colorScheme: "dark" })+ await expect(page.locator("html")).toHaveClass(/dark/)+ await expect(detailDialog.getByTestId(tid.botActivityDetail)).toHaveText(fullAuditText)+ await attachPageScreenshot(testInfo, "bot-activity-log-detail-mobile-dark", page)+ await detailDialog.getByRole("button", { name: "Close" }).click()+ await expect(detailDialog).toBeHidden()+ await expect(trigger).toBeFocused()+ } catch (error) { caseJourneyFailure1 = error; caseJourneyFailure1Present = true; throw error } finally {+ try {++ await machine.close()++ } catch (cleanupError) { if (caseJourneyFailure1Present) throw new AggregateError([caseJourneyFailure1, cleanupError], "Journey and resource exit both failed"); throw cleanupError }+ }+})diff --git a/src/web/src/test/e2e-ui/30-bot-lifecycle-audit-modal.spec.ts b/src/web/src/test/e2e-ui/30-bot-lifecycle-audit-modal.spec.tsnew file mode 100644index 000000000..37e5a0f8e--- /dev/null+++ b/src/web/src/test/e2e-ui/30-bot-lifecycle-audit-modal.spec.ts@@ -0,0 +1,345 @@+import { communityFixtureFetch } from "./_fixtures/business-contract"+import { test, expect } from "./_fixtures/case-fixture"+import { gotoAfterUserWsAuth } from "./_fixtures/actions"+import { tid } from "./_fixtures/testids"+import { WEB_URL } from "./_setup/paths"+import { connectMachine } from "./_fixtures/community-machine"+import { prepareCase, attachPageScreenshot, expectActivityHeader, enrollBot, sendBotMessage, setBotMark, openBotProfile } from "./_fixtures/bot-profile-audit"++test("owner-only bot mark sticker, Stop lifecycle, owner swap, and URL-owned audit modal", async ({ caseActors, caseResources }, testInfo) => {+ test.setTimeout(180_000)++ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { seedChannel, seedJoinServer, seedServer } = actors.seed+ const { headersFor, jsonRequest, pairMachine, createBot, joinBotToServer } = await prepareCase(actors, caseResources)++ const suffix = Date.now().toString(36)+ const serverId = await seedServer("alice", `profile-preview-server-with-a-long-name-${suffix}`)+ const channelName = `bots-with-a-long-channel-name-${suffix}`+ const channelId = await seedChannel("alice", serverId, channelName)+ const staleServerId = await seedServer("alice", `stale-mark-server-${suffix}`)+ const staleChannelName = `former-private-work-${suffix}`+ const staleChannelId = await seedChannel("alice", staleServerId, staleChannelName)+ await seedJoinServer("alice", "bob", serverId)++ const { credential, machineId } = await pairMachine()+ const machine = connectMachine(credential, caseResources, { machineId, headers: headersFor("alice") })+ await machine.opened+ const botName = `Preview bot ${suffix} long-name`+ const botId = await createBot(machineId, botName)+ const runnerKey = await enrollBot(credential, botId)+ await joinBotToServer(runnerKey, botId, serverId)+ await joinBotToServer(runnerKey, botId, staleServerId)++ const { servers } = await jsonRequest<{+ servers: Array<{ id: string; name: string; discriminator: string }>+ }>("alice", "/api/community/servers")+ const server = servers.find((candidate) => candidate.id === serverId)+ const staleServer = servers.find((candidate) => candidate.id === staleServerId)+ expect(server).toBeTruthy()+ expect(staleServer).toBeTruthy()+ const channelRef = `/${server!.name}#${server!.discriminator}/${channelName}`+ let latestSeq = 0+ for (const index of [1, 2, 3]) {+ const created = await jsonRequest<{ message: { seq: number } }>(+ "alice",+ `/api/community/channels/${channelId}/messages`,+ {+ method: "POST",+ body: JSON.stringify({ content: `Marked task ${index} ${suffix}` }),+ },+ )+ latestSeq = created.message.seq+ await setBotMark(runnerKey, channelRef, latestSeq)+ }+ const longBotMessage = await sendBotMessage(+ runnerKey,+ channelRef,+ `**Long marked task ${suffix}** ${"with enough detail to require a second line ".repeat(5)}`,+ latestSeq,+ )+ await setBotMark(runnerKey, channelRef, longBotMessage.seq)++ const staleMessage = await jsonRequest<{ message: { seq: number } }>(+ "alice",+ `/api/community/channels/${staleChannelId}/messages`,+ {+ method: "POST",+ body: JSON.stringify({ content: `Persisted stale mark ${suffix}` }),+ },+ )+ const staleChannelRef = `/${staleServer!.name}#${staleServer!.discriminator}/${staleChannelName}`+ await setBotMark(runnerKey, staleChannelRef, staleMessage.message.seq)+ const staleMembers = await jsonRequest<{+ members: Array<{ id: string; userId: string }>+ }>("alice", `/api/community/servers/${staleServerId}/members`)+ const staleBotMember = staleMembers.members.find((member) => member.userId === botId)+ expect(staleBotMember).toBeTruthy()+ const removeStaleBot = await communityFixtureFetch(+ `${WEB_URL}/api/community/servers/${staleServerId}/members/${staleBotMember!.id}`,+ { method: "DELETE", headers: headersFor("alice") },+ )+ expect(removeStaleBot.status).toBe(204)++ let caseJourneyFailure2: unknown+let caseJourneyFailure2Present = false+ try {+ machine.socket.send(JSON.stringify({ type: "agent_activity", agentId: botId, state: "idle" }))+ for (let index = 0; index < 11; index += 1) {+ machine.socket.send(JSON.stringify({+ type: "bot_audit_event",+ eventId: `bae_${suffix}_${String(index).padStart(2, "0")}`,+ agentId: botId,+ sessionId: `session-${suffix}`,+ launchId: `launch-${suffix}`,+ event: { kind: "text", payload: { text: `Open activity log ${index}`, truncated: false, chars: `Open activity log ${index}`.length } },+ }))+ }++ await expect.poll(async () => {+ const response = await communityFixtureFetch(+ `${WEB_URL}/api/community/bots/${botId}/audit-log?limit=10`,+ { headers: headersFor("alice") },+ )+ if (!response.ok) return 0+ return ((await response.json()) as { events: unknown[] }).events.length+ }).toBe(10)++ const authoritativeMarks = await jsonRequest<{+ marked: Array<{+ id: string+ server: string+ channel: string+ m: { authorName: string; content: string; createdAt: string }+ }>+ }>("alice", `/api/community/bots/${botId}/marks`)+ expect(authoritativeMarks.marked).toHaveLength(4)+ expect(authoritativeMarks.marked.some((mark) => mark.m.authorName === botName)).toBe(true)+ expect(authoritativeMarks.marked).toContainEqual(expect.objectContaining({+ server: staleServer!.name,+ channel: staleChannelName,+ m: expect.objectContaining({ content: `Persisted stale mark ${suffix}` }),+ }))++ const route = `/c/channels/${serverId}/${channelId}`+ const alice = await asUser("alice")+ const ownerMarkRequests: string[] = []+ alice.page.on("request", (request) => {+ if (new URL(request.url()).pathname === `/api/community/bots/${botId}/marks`) {+ ownerMarkRequests.push(request.url())+ }+ })+ await gotoAfterUserWsAuth(alice.page, route)+ await openBotProfile(alice.page, botName)++ const sticker = alice.page.getByTestId(tid.botMarkSticker)+ await expect(sticker).toBeVisible()+ await expect(sticker).toHaveAttribute("aria-label", "Bot log")+ const activityTab = sticker.getByRole("tab", { name: "Thoughts" })+ const marksTab = sticker.getByRole("tab", { name: /Marked messages/ })+ const auditRows = alice.page.locator(+ `[data-testid^="${tid.botAuditPreviewRow("")}"]`,+ )+ const activityScroller = sticker+ .getByRole("tabpanel", { name: "Recent thoughts" })+ .getByTestId(tid.botAuditPreviewScroll)+ await expect(activityTab).toHaveAttribute("aria-selected", "true")+ await expect(auditRows).toHaveCount(10)+ await expect(activityScroller).toHaveCSS("overflow-y", "auto")+ await expect.poll(async () => activityScroller.evaluate((element) =>+ element.scrollTop + element.clientHeight >= element.scrollHeight - 1))+ .toBe(true)+ expect((await auditRows.allTextContents()).some((text) =>+ /open activity log 0$/i.test(text))).toBe(false)+ const liveEventId = `bae_${suffix}_11`+ let liveEventAcknowledged = false+ const onAuditAck = (data: unknown) => {+ const frame = JSON.parse(String(data)) as { type?: string; eventId?: string }+ if (frame.type === "bot_audit_event_ack" && frame.eventId === liveEventId) {+ liveEventAcknowledged = true+ }+ }+ machine.socket.on("message", onAuditAck)+ try {+ machine.socket.send(JSON.stringify({+ type: "bot_audit_event",+ eventId: liveEventId,+ agentId: botId,+ sessionId: `session-${suffix}`,+ launchId: `launch-${suffix}`,+ event: { kind: "text", payload: { text: "Open activity log 11", truncated: false, chars: "Open activity log 11".length } },+ }))+ await expect.poll(() => liveEventAcknowledged, {+ message: `machine receives bot_audit_event_ack for ${liveEventId}`,+ timeout: 30_000,+ }).toBe(true)+ } finally {+ machine.socket.off("message", onAuditAck)+ }+ await expect.poll(async () =>+ (await auditRows.allTextContents()).join(" ").toLowerCase())+ .toContain("open activity log 11")+ await expect(auditRows).toHaveCount(10)+ expect((await auditRows.allTextContents()).some((text) =>+ /open activity log 1$/i.test(text))).toBe(false)+ await expect.poll(async () => activityScroller.evaluate((element) =>+ element.scrollTop + element.clientHeight >= element.scrollHeight - 1))+ .toBe(true)+ await expect(sticker.getByRole("button", { name: /Load more activity/ })).toHaveCount(0)+ await marksTab.click()+ await expect(marksTab).toHaveAttribute("aria-selected", "true")+ await expect(alice.page.locator(`[data-testid^="${tid.botMarkStickerRow("")}"]`))+ .toHaveCount(3)+ await expect(alice.page.getByTestId(tid.botMarkStickerOverflow)).toBeVisible()+ await expect(sticker.getByTitle(`${server!.name} · #${channelName}`).first()).toBeVisible()+ await expect(sticker).toContainText(botName)+ await expect(sticker).toContainText(`Long marked task ${suffix}`)+ await expect(sticker).not.toContainText("**Long marked task")+ await expect(sticker.locator("time")).toHaveCount(3)+ const markedBody = sticker.locator("[data-community-message-body]").filter({ hasText: `Long marked task ${suffix}` })+ await expect(markedBody).toHaveCount(1)+ await expect(markedBody.locator('[data-streamdown="strong"]')).toHaveText(`Long marked task ${suffix}`)+ await expect(markedBody).toHaveText(`Long marked task ${suffix} ${"with enough detail to require a second line ".repeat(5)}`.trim())+ await expect(markedBody.locator("p")).toHaveCSS("-webkit-line-clamp", "none")+ expect(ownerMarkRequests.length).toBeGreaterThan(0)+ machine.socket.send(JSON.stringify({ type: "agent_activity", agentId: botId, state: "running" }))+ const stop = alice.page.getByTestId(tid.botMarkStickerStop)+ await expect(stop).toBeVisible()+ await attachPageScreenshot(testInfo, "bot-work-sticker-marked-running-desktop", alice.page)+ await activityTab.click()+ await expect(activityTab).toHaveAttribute("aria-selected", "true")+ await expect(sticker.getByRole("button", { name: /Load more activity/ })).toHaveCount(0)+ await expect(stop).toBeVisible()+ await attachPageScreenshot(testInfo, "bot-work-sticker-activity-running-desktop", alice.page)+ await marksTab.click()+ const interruptFrame = new Promise<unknown>((resolveFrame) => {+ const onMessage = (data: unknown) => {+ const frame = JSON.parse(String(data)) as { type: string }+ if (frame.type === "machine:heartbeat") return+ machine.socket.off("message", onMessage)+ resolveFrame(frame)+ }+ caseResources.own(onMessage, async captured => { machine.socket.off("message", captured) })+ machine.socket.on("message", onMessage)+ })+ await stop.click()+ await expect(stop).toContainText("Stopping…")+ await expect(stop).toBeDisabled()+ await expect(interruptFrame).resolves.toEqual({ type: "agent:interrupt", agentId: botId })+ machine.socket.send(JSON.stringify({ type: "agent_activity", agentId: botId, state: "idle" }))+ await expect.poll(async () => {+ const profile = await jsonRequest<{ statusText: string | null }>(+ "alice",+ `/api/community/users/${botId}/profile`,+ )+ return profile.statusText+ }).toBe("Idle")+ await gotoAfterUserWsAuth(alice.page, route)+ await openBotProfile(alice.page, botName)+ await expect(alice.page.getByTestId(tid.botMarkStickerStop))+ .toHaveCount(0)+ await expect(sticker).toBeVisible()++ await alice.page.setViewportSize({ width: 375, height: 812 })+ await alice.page.emulateMedia({ colorScheme: "dark" })+ await expect(alice.page.locator("html")).toHaveClass(/dark/)+ await expect(sticker).toBeVisible()+ const mobileStickerGeometry = await sticker.evaluate((element) => ({+ clientWidth: element.clientWidth,+ scrollWidth: element.scrollWidth,+ right: element.getBoundingClientRect().right,+ }))+ expect(mobileStickerGeometry.scrollWidth).toBeLessThanOrEqual(mobileStickerGeometry.clientWidth)+ expect(mobileStickerGeometry.right).toBeLessThanOrEqual(375)+ await expect(sticker.getByLabel("Loading thoughts")).toHaveCount(0)+ await expect(sticker.getByText("Open activity log 11", { exact: true })).toBeVisible()+ await attachPageScreenshot(testInfo, "bot-mark-sticker-activity-mobile-dark", alice.page)+ await sticker.getByRole("tab", { name: "Marked messages" }).click()+ await expect(alice.page.locator(`[data-testid^="${tid.botMarkStickerRow("")}"]`))+ .toHaveCount(3)+ await attachPageScreenshot(testInfo, "bot-mark-sticker-marks-mobile-dark", alice.page)+ await sticker.getByRole("tab", { name: "Thoughts" }).click()+ await sticker.getByTestId(tid.botAuditPreviewRow(liveEventId))+ .getByText("Open activity log 11", { exact: true }).click()+ await expect(alice.page).toHaveURL(new RegExp(`/c/me/bots\\?audit=${botId}`))+ await gotoAfterUserWsAuth(alice.page, route)+ await openBotProfile(alice.page, botName)+ const footer = sticker.locator("footer")+ await expect(footer.locator("time")).toHaveCount(0)+ const ownerLink = alice.page.getByTestId(tid.profileOwnerLink)+ await expect(alice.page.getByTestId(tid.profileBotBadge)).toContainText("Bot")+ await expect(ownerLink).toBeVisible()+ const ownerLinkBox = await ownerLink.boundingBox()+ expect(ownerLinkBox?.height).toBeGreaterThanOrEqual(44)+ const ownerHandle = await ownerLink.textContent()+ await ownerLink.click()+ await expect(alice.page.getByTestId(tid.profileCard)).toHaveCount(1)+ await expect(alice.page.getByTestId(tid.profileOwnerLink)).toHaveCount(0)+ await expect(alice.page.getByTestId(tid.profileCard))+ .toContainText(ownerHandle!.trim().replace(/^@/, ""))++ await alice.page.mouse.click(4, 4)+ await expect(alice.page.getByTestId(tid.profileCard)).toHaveCount(0)+ await alice.page.setViewportSize({ width: 1280, height: 900 })+ await alice.page.emulateMedia({ colorScheme: "light" })+ await openBotProfile(alice.page, botName)+ await expect(alice.page.getByTestId(tid.botAuditPreviewDock)).toHaveAttribute(+ "data-placement",+ /^(right|left|top|bottom)$/,+ )+ const openActivity = sticker.getByTestId(tid.botAuditPreviewRow(liveEventId))+ .getByTitle("Open full audit log", { exact: true })+ await expect(openActivity.locator("time")).toHaveCount(1)+ await openActivity.focus()+ await expect(openActivity).toBeFocused()+ await openActivity.press("Enter")+ await expect(alice.page).toHaveURL(new RegExp(`/c/me/bots\\?audit=${botId}$`))+ await expect(alice.page.getByTestId(tid.botActivityModal)).toBeVisible()+ await expectActivityHeader(alice.page, testInfo, 1280)+ await expectActivityHeader(alice.page, testInfo, 390)+ await alice.page.setViewportSize({ width: 1280, height: 900 })+ await alice.page.reload()+ await expect(alice.page.getByTestId(tid.botActivityModal)).toBeVisible()+ await alice.page.goBack({ waitUntil: "commit" })+ await expect(alice.page).toHaveURL(new RegExp(`${route}$`))+ await alice.page.goForward({ waitUntil: "commit" })+ await expect(alice.page.getByTestId(tid.botActivityModal)).toBeVisible()++ await alice.page.goto(`/c/me/bots?machineId=${machineId}&audit=${botId}`)+ await expect(alice.page.getByTestId(tid.botActivityModal)).toBeVisible()+ await alice.page.getByRole("button", { name: "Close", exact: true }).click()+ await expect(alice.page).toHaveURL(`/c/me/bots?machineId=${machineId}`)++ const bob = await asUser("bob")+ const bobDirectMarks = await communityFixtureFetch(`${WEB_URL}/api/community/bots/${botId}/marks`, {+ headers: headersFor("bob"),+ })+ expect(bobDirectMarks.status).toBe(404)+ const bobMarkRequests: string[] = []+ bob.page.on("request", (request) => {+ if (new URL(request.url()).pathname === `/api/community/bots/${botId}/marks`) {+ bobMarkRequests.push(request.url())+ }+ })+ await gotoAfterUserWsAuth(bob.page, route)+ await openBotProfile(bob.page, botName)+ await expect(bob.page.getByTestId(tid.profileOwnerLink)).toBeVisible()+ await expect(bob.page.getByTestId(tid.botMarkSticker)).toHaveCount(0)+ expect(bobMarkRequests).toEqual([])+ await bob.page.getByTestId(tid.profileOwnerLink).click()+ await expect(bob.page.getByTestId(tid.profileCard)).toHaveCount(1)+ await expect(bob.page.getByTestId(tid.profileOwnerLink)).toHaveCount(0)++ await bob.page.goto(`/c/me/bots?audit=${botId}`)+ await expect(bob.page.getByTestId(tid.botActivityModal)).toHaveCount(0)+ await expect.poll(() => new URL(bob.page.url()).searchParams.has("audit")).toBe(false)+ expect(bobMarkRequests).toEqual([])+ } catch (error) { caseJourneyFailure2 = error; caseJourneyFailure2Present = true; throw error } finally {+ try {++ await machine.close()++ } catch (cleanupError) { if (caseJourneyFailure2Present) throw new AggregateError([caseJourneyFailure2, cleanupError], "Journey and resource exit both failed"); throw cleanupError }+ }+})diff --git a/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts b/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.tsdeleted file mode 100644index cad81ce96..000000000--- a/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts+++ /dev/null@@ -1,1580 +0,0 @@-import { communityFixtureFetch, currentCommunityFixtureError } from "./_fixtures/business-contract"-import type { Locator, Page, Route, TestInfo, WebSocket as BrowserSocket } from "@playwright/test"-import { test, expect } from "./_fixtures/case-fixture"-import { composerEditable, gotoAfterUserWsAuth } from "./_fixtures/actions"--import { tid } from "./_fixtures/testids"-import { WEB_URL } from "./_setup/paths"-import { connectMachine } from "./_fixtures/community-machine"-import type { CaseActors, CaseResources, OwnedCaseResource } from "./_fixtures/case-fixture"--async function prepareCase(actors: CaseActors, caseResources: CaseResources) {- const { sessionCookie } = actors- const createdBotIds = new Map<string, OwnedCaseResource<string>>()- const createdMachineIds = new Map<string, OwnedCaseResource<string>>()- async function cleanupCreatedResources(): Promise<void> {- const errors: unknown[] = []- for (const resource of [...createdBotIds.values(), ...createdMachineIds.values()]) {- try {- await resource.close()- }- catch (error) {- errors.push(error)- }- }- if (errors.length)- throw new AggregateError(errors, "Bot preview resource cleanup failed")- }- function headersFor(key: UserKey, extra?: Record<string, string>) {- return {- Cookie: sessionCookie(key),- Origin: WEB_URL,- ...extra,- }- }- async function jsonRequest<T>(key: UserKey, path: string, init?: RequestInit): Promise<T> {- const response = await communityFixtureFetch(`${WEB_URL}${path}`, {- ...init,- headers: headersFor(key, {- ...(init?.body ? { "Content-Type": "application/json" } : {}),- ...(init?.headers as Record<string, string> | undefined),- }),- })- expect(response.status, `${init?.method ?? "GET"} ${path}`).toBeLessThan(300)- return response.json() as Promise<T>- }- async function pairMachine(): Promise<{- credential: string- machineId: string- }> {- const pair = await jsonRequest<{- tokenId: string- }>("alice", "/api/community/machines/pair", {- method: "POST",- })- const activationProof: { response?: Response; machineId?: string } = {}- const pairingToken = caseResources.own(pair.tokenId, async () => {- if (!activationProof.response?.ok || !activationProof.machineId) throw new Error("Pairing token consumption is UNKNOWN; this case must stop")- })- const response = await fetch(`${WEB_URL}/api/community/daemon/activate`, {- method: "POST",- headers: {- Authorization: `Bearer ${pair.tokenId}`,- "Content-Type": "application/json",- Origin: WEB_URL,- },- body: JSON.stringify({- hostname: `profile-preview-e2e-${Date.now()}`,- platform: "darwin",- arch: "arm64",- runtimeReport: [{ id: "codex", status: "healthy" }],- }),- })- expect(response.status).toBe(200)- const data = await response.json() as {- credential: string- machineId: string- }- createdMachineIds.set(data.machineId, caseResources.own(data.machineId, async (machineId) => {- const response = await communityFixtureFetch(`${WEB_URL}/api/community/machines/${machineId}`, { method: "DELETE", headers: headersFor("alice") })- expect(response.status, `delete test machine ${machineId}`).toBe(204)- createdMachineIds.delete(machineId)- }))- activationProof.response = response- activationProof.machineId = data.machineId- await pairingToken.close()- return data- }- async function createBot(machineId: string, name: string): Promise<string> {- const data = await jsonRequest<{- bot: {- id: string- }- }>("alice", "/api/community/bots", {- method: "POST",- body: JSON.stringify({ name, machineId, runtime: "codex" }),- })- createdBotIds.set(data.bot.id, caseResources.own(data.bot.id, async (botId) => {- const response = await communityFixtureFetch(`${WEB_URL}/api/community/bots/${botId}`, { method: "DELETE", headers: headersFor("alice") })- expect(response.status, `delete test bot ${botId}`).toBe(204)- createdBotIds.delete(botId)- }))- return data.bot.id- }- async function joinBotToServer(runnerKey: string, botId: string, serverId: string): Promise<void> {- const token = await actors.seed.createInvite("alice", serverId)- const joined = await jsonRequest<{ serverId: string; member: { userId: string } }>(- "alice",- `/api/community/invites/${token}/join`,- {- method: "POST",- headers: { Authorization: `Bearer ${runnerKey}` },- body: "{}",- },- )- expect(joined.serverId).toBe(serverId)- expect(joined.member.userId).toBe(botId)- }- actors.onCleanup(cleanupCreatedResources)- return { createdBotIds, createdMachineIds, cleanupCreatedResources, headersFor, jsonRequest, pairMachine, createBot, joinBotToServer }-}--type UserKey = "alice" | "bob"-type Rect = { x: number; y: number; width: number; height: number }-type PreviewFrameSample = {- phase: "start" | "mutation" | "frame"- rootOverflowX: number- rootOverflowY: number- scrollX: number- scrollY: number- ready: string | null- visibility: string | null- pointerEvents: string | null- rect: Rect | null- viewportWidth: number- viewportHeight: number-}--async function rect(locator: Locator): Promise<Rect> {- const value = await locator.boundingBox()- expect(value).not.toBeNull()- return value!-}--async function settleSheet(sheet: Locator): Promise<void> {- await expect(sheet).toBeVisible()- await sheet.evaluate((element) => new Promise<void>((resolveStable) => {- const deadline = performance.now() + 1_000- let previous = ""- let stableFrames = 0- const sample = () => {- const bounds = element.getBoundingClientRect()- const style = getComputedStyle(element)- const current = [- bounds.x,- bounds.y,- bounds.width,- bounds.height,- style.opacity,- style.transform,- style.backgroundColor,- style.borderTopColor,- style.borderRightColor,- style.borderBottomColor,- style.borderLeftColor,- ].join(":")- stableFrames = current === previous ? stableFrames + 1 : 0- previous = current- if (stableFrames >= 3 || performance.now() >= deadline) resolveStable()- else requestAnimationFrame(sample)- }- requestAnimationFrame(sample)- }))-}--async function expectSheetThemeTokens(sheet: Locator): Promise<void> {- const colors = await sheet.evaluate((element) => {- const probe = document.createElement("div")- probe.style.cssText = [- "position:fixed",- "visibility:hidden",- "background-color:var(--background)",- "border:1px solid var(--border)",- ].join(";")- document.body.appendChild(probe)-- const sheetStyle = getComputedStyle(element)- const probeStyle = getComputedStyle(probe)- const header = element.querySelector<HTMLElement>("[data-slot='sheet-header']")- const body = element.querySelector<HTMLElement>("[data-slot='sheet-body']")- if (!header || !body) throw new Error("missing sheet surface")- const result = {- expectedBackground: probeStyle.backgroundColor,- expectedBorder: probeStyle.borderLeftColor,- sheetBackground: sheetStyle.backgroundColor,- sheetBorder: sheetStyle.borderLeftColor,- headerBackground: getComputedStyle(header).backgroundColor,- headerBorder: getComputedStyle(header).borderBottomColor,- bodyBackground: getComputedStyle(body).backgroundColor,- }- probe.remove()- return result- })-- expect(colors).toMatchObject({- sheetBackground: colors.expectedBackground,- sheetBorder: colors.expectedBorder,- headerBackground: "rgba(0, 0, 0, 0)",- headerBorder: colors.expectedBorder,- bodyBackground: colors.expectedBackground,- })-}--async function attachPageScreenshot(testInfo: TestInfo, name: string, page: Page): Promise<void> {- await testInfo.attach(`${name}.png`, {- body: await page.screenshot(),- contentType: "image/png",- })-}--async function expectActivityHeader(- page: Page,- testInfo: TestInfo,- width: 390 | 1280,-): Promise<void> {- await page.setViewportSize({ width, height: width === 390 ? 844 : 900 })- const sheet = page.getByTestId(tid.botActivityModal)- await settleSheet(sheet)- const header = sheet.locator("[data-slot='sheet-header']")- const avatar = header.locator("[data-slot='sheet-header-leading']")- const title = header.locator("[data-slot='sheet-title']")- const description = header.locator("[data-slot='sheet-description']")- const close = sheet.getByRole("button", { name: "Close", exact: true })- const [avatarRect, titleRect, descriptionRect, closeRect] = await Promise.all([- rect(avatar), rect(title), rect(description), rect(close),- ])-- expect(avatarRect.width).toBeCloseTo(32, 0)- expect(avatarRect.height).toBeCloseTo(32, 0)- expect(titleRect.x).toBeGreaterThanOrEqual(avatarRect.x + avatarRect.width + 11.5)- expect(descriptionRect.x).toBeCloseTo(titleRect.x, 0)- expect(titleRect.x + titleRect.width).toBeLessThanOrEqual(closeRect.x + 0.5)- const styles = await title.evaluate((element) => {- const titleStyle = getComputedStyle(element)- const descriptionNode = element.parentElement?.querySelector<HTMLElement>("[data-slot='sheet-description']")- if (!descriptionNode) throw new Error("missing Activity Log description")- const descriptionStyle = getComputedStyle(descriptionNode)- return {- titleFontSize: titleStyle.fontSize,- titleFontWeight: titleStyle.fontWeight,- titleLineHeight: titleStyle.lineHeight,- descriptionFontSize: descriptionStyle.fontSize,- descriptionLineHeight: descriptionStyle.lineHeight,- }- })- expect(styles).toMatchObject({- titleFontSize: "18px",- titleFontWeight: "600",- descriptionFontSize: "14px",- })- expect(Number.parseFloat(styles.titleLineHeight)).toBeGreaterThan(Number.parseFloat(styles.titleFontSize))- expect(Number.parseFloat(styles.descriptionLineHeight)).toBeGreaterThan(Number.parseFloat(styles.descriptionFontSize))- await attachPageScreenshot(testInfo, `activity-log-header-${width}`, page)-}--async function expectFooterGeometry(- page: Page,- title: string,- actionNames: string[],- width: 390 | 639 | 640,-): Promise<void> {- await page.setViewportSize({ width, height: 844 })- const sheet = page.getByRole("dialog", { name: title, exact: true })- await settleSheet(sheet)- const footer = sheet.locator("[data-slot='sheet-footer']")- const actions = actionNames.map((name) => footer.getByRole("button", { name, exact: true }))- const footerRect = await rect(footer)- const actionRects = await Promise.all(actions.map(rect))- const style = await footer.evaluate((element) => {- const value = getComputedStyle(element)- return {- display: value.display,- flexDirection: value.flexDirection,- justifyContent: value.justifyContent,- alignItems: value.alignItems,- }- })- expect(style).toEqual({- display: "flex",- flexDirection: "row",- justifyContent: "flex-end",- alignItems: "center",- })- for (const actionRect of actionRects) {- expect(actionRect.width).toBeLessThan(footerRect.width * 0.75)- if (width < 640) expect(actionRect.height).toBeGreaterThanOrEqual(44)- }- for (let index = 1; index < actionRects.length; index++) {- expect(actionRects[index]!.x).toBeGreaterThan(actionRects[index - 1]!.x)- expect(actionRects[index]!.y).toBeCloseTo(actionRects[0]!.y, 0)- }- const finalAction = actionRects.at(-1)!- expect(footerRect.x + footerRect.width - (finalAction.x + finalAction.width))- .toBe(width < 640 ? 16 : 24)-}--async function enrollBot(credential: string, botId: string): Promise<string> {- const response = await fetch(`${WEB_URL}/api/community/daemon/enroll-agent`, {- method: "POST",- headers: {- Authorization: `Bearer ${credential}`,- "Content-Type": "application/json",- Origin: WEB_URL,- },- body: JSON.stringify({ agentId: botId }),- })- expect(response.status).toBe(200)- const data = await response.json() as { runnerKey: string }- return data.runnerKey-}--async function sendBotMessage(- runnerKey: string,- channel: string,- text: string,- seenUpToSeq = 0,-): Promise<{ seq: number }> {- const response = await fetch(`${WEB_URL}/api/community/channels/resolve/messages`, {- method: "POST",- headers: {- Authorization: `Bearer ${runnerKey}`,- "Content-Type": "application/json",- Origin: WEB_URL,- },- body: JSON.stringify({- channel,- content: { text },- attachments: [],- seenUpToSeq,- nonce: `profile-preview:${crypto.randomUUID()}`,- }),- })- expect(response.status).toBe(200)- const data = await response.json() as { state: string; message: { seq: string } }- expect(data.state).toBe("sent")- const seq = Number(data.message.seq.replace(/^#/, ""))- expect(Number.isInteger(seq) && seq > 0).toBe(true)- return { seq }-}--async function setBotMark(- runnerKey: string,- channel: string,- seq: number,-): Promise<void> {- const response = await fetch(`${WEB_URL}/api/community/messages/resolve/properties`, {- method: "PUT",- headers: {- Authorization: `Bearer ${runnerKey}`,- "Content-Type": "application/json",- Origin: WEB_URL,- },- body: JSON.stringify({- channel,- seq,- property: { type: "mark", value: true },- }),- })- expect(response.status).toBe(200)- await expect(response.json()).resolves.toMatchObject({ type: "mark", value: true })-}--async function openBotProfile(page: Page, botName: string): Promise<void> {- await page.getByRole("button", { name: botName, exact: true }).click()- await expect(page.getByTestId(tid.profileCard)).toBeVisible()-}--async function installPreviewFrameProbe(page: Page): Promise<void> {- await page.evaluate((dockTestId) => {- type ProbeState = {- active: boolean- observer: MutationObserver- samples: PreviewFrameSample[]- }- const target = window as typeof window & { __previewFrameProbe?: ProbeState }- const samples: PreviewFrameSample[] = []- const sample = (phase: PreviewFrameSample["phase"]) => {- if (samples.length >= 500) return- const root = document.documentElement- const dock = document.querySelector<HTMLElement>(`[data-testid="${dockTestId}"]`)- const style = dock ? getComputedStyle(dock) : null- const bounds = dock?.getBoundingClientRect()- samples.push({- phase,- rootOverflowX: root.scrollWidth - root.clientWidth,- rootOverflowY: root.scrollHeight - root.clientHeight,- scrollX: window.scrollX,- scrollY: window.scrollY,- ready: dock?.getAttribute("data-measurement-ready") ?? null,- visibility: style?.visibility ?? null,- pointerEvents: style?.pointerEvents ?? null,- rect: bounds- ? { x: bounds.x, y: bounds.y, width: bounds.width, height: bounds.height }- : null,- viewportWidth: window.innerWidth,- viewportHeight: window.innerHeight,- })- }- const observer = new MutationObserver(() => sample("mutation"))- observer.observe(document.body, {- attributes: true,- attributeFilter: ["class", "data-measurement-ready", "style"],- childList: true,- subtree: true,- })- target.__previewFrameProbe = { active: true, observer, samples }- sample("start")- const frame = () => {- const state = target.__previewFrameProbe- if (!state?.active) return- sample("frame")- requestAnimationFrame(frame)- }- requestAnimationFrame(frame)- }, tid.botAuditPreviewDock)-}--async function finishPreviewFrameProbe(page: Page): Promise<PreviewFrameSample[]> {- return page.evaluate(async () => {- await new Promise<void>((resolveFrames) => {- requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(- () => resolveFrames(),- )))- })- const target = window as typeof window & {- __previewFrameProbe?: {- active: boolean- observer: MutationObserver- samples: PreviewFrameSample[]- }- }- const state = target.__previewFrameProbe- if (!state) throw new Error("preview frame probe was not installed")- state.active = false- state.observer.disconnect()- return state.samples- })-}--function expectPreviewFrames(samples: PreviewFrameSample[], label: string): void {- expect(samples.length, `${label}: captured frames`).toBeGreaterThan(1)- const baseline = samples[0]!- expect(baseline.rootOverflowX, `${label}: baseline root X overflow`).toBe(0)- expect(baseline.rootOverflowY, `${label}: baseline root Y overflow`).toBe(0)- const visible = samples.filter((sample) => sample.ready === "true"- && sample.visibility === "visible"- && sample.rect)- expect(visible.length, `${label}: visible positioned frames`).toBeGreaterThan(0)-- for (const [index, sample] of samples.entries()) {- expect(sample.rootOverflowX, `${label}: frame ${index} root X overflow`).toBe(0)- expect(sample.rootOverflowY, `${label}: frame ${index} root Y overflow`).toBe(0)- expect(sample.scrollX, `${label}: frame ${index} root scrollX`).toBe(baseline.scrollX)- expect(sample.scrollY, `${label}: frame ${index} root scrollY`).toBe(baseline.scrollY)- if (sample.ready === "false") {- expect(sample.visibility, `${label}: frame ${index} hidden measurement`).toBe("hidden")- expect(sample.pointerEvents, `${label}: frame ${index} inert measurement`).toBe("none")- }- if (sample.ready !== "true" || sample.visibility !== "visible" || !sample.rect) continue- expect(sample.rect.x, `${label}: frame ${index} left boundary`).toBeGreaterThanOrEqual(7.5)- expect(sample.rect.y, `${label}: frame ${index} top boundary`).toBeGreaterThanOrEqual(7.5)- expect(- sample.rect.x + sample.rect.width,- `${label}: frame ${index} right boundary`,- ).toBeLessThanOrEqual(sample.viewportWidth - 7.5)- expect(- sample.rect.y + sample.rect.height,- `${label}: frame ${index} bottom boundary`,- ).toBeLessThanOrEqual(sample.viewportHeight - 7.5)- }-}--async function probeOwnedBotProfile(- page: Page,- author: Locator,- label: string,-): Promise<PreviewFrameSample[]> {- await expect(author).toBeVisible({ timeout: 20_000 })- await installPreviewFrameProbe(page)- await author.click()- const dock = page.getByTestId(tid.botAuditPreviewDock)- await expect(dock).toHaveAttribute("data-measurement-ready", "true")- await expect(dock).toBeVisible()- const samples = await finishPreviewFrameProbe(page)- expectPreviewFrames(samples, label)- return samples-}--test("full audit log reveals a truncated row by hover and touch", async ({ caseActors, caseResources }, testInfo) => {- test.setTimeout(120_000)-- const actors = await caseActors(["alice"])- const { asUser } = actors- const { headersFor, pairMachine, createBot } = await prepareCase(actors, caseResources)-- const suffix = Date.now().toString(36)- const longAuditTarget = `/Users/alice/workspace/${"deeply-nested-audit-target/".repeat(5)}result-${suffix}.md`- const fullAuditText = `read · ${longAuditTarget}`- const { credential, machineId } = await pairMachine()- const machine = connectMachine(credential, caseResources, { machineId, headers: headersFor("alice") })- await machine.opened- const botId = await createBot(machineId, `Tooltip bot ${suffix}`)-- let caseJourneyFailure1: unknown-let caseJourneyFailure1Present = false- try {- machine.socket.send(JSON.stringify({- type: "bot_audit_event",- agentId: botId,- sessionId: `session-${suffix}`,- launchId: `launch-${suffix}`,- event: { kind: "tool_call", payload: { name: "Read", target: longAuditTarget } },- }))-- await expect.poll(async () => {- const response = await communityFixtureFetch(- `${WEB_URL}/api/community/bots/${botId}/audit-log?limit=10`,- { headers: headersFor("alice") },- )- if (!response.ok) return false- const { events } = (await response.json()) as {- events: Array<{ payload?: { target?: string } | null }>- }- return events.some((event) => event.payload?.target === longAuditTarget)- }).toBe(true)-- const { page } = await asUser("alice")- await page.setViewportSize({ width: 1280, height: 900 })- await gotoAfterUserWsAuth(page, `/c/me/bots?audit=${botId}`)- const sheet = page.getByTestId(tid.botActivityModal)- await settleSheet(sheet)- const trigger = sheet.locator("[data-activity-tooltip-trigger]").filter({ hasText: "read" })- await expect(trigger).toHaveCount(1)- await expect.poll(() => trigger.locator("span").first().evaluate((element) => (- element.scrollWidth > element.clientWidth- ))).toBe(true)-- await trigger.hover()- const tooltip = page.getByRole("tooltip")- await expect(tooltip).toHaveText(fullAuditText)- await expect(tooltip).toHaveCSS("opacity", "1")- await attachPageScreenshot(testInfo, "bot-activity-log-tooltip-desktop", page)- await page.emulateMedia({ colorScheme: "dark" })- await expect(page.locator("html")).toHaveClass(/dark/)- await settleSheet(sheet)- await expectSheetThemeTokens(sheet)- await expect(tooltip).toHaveCSS("opacity", "1")- await attachPageScreenshot(testInfo, "bot-activity-log-tooltip-desktop-dark", page)- await page.mouse.move(0, 0)- await expect(tooltip).toBeHidden()-- await page.setViewportSize({ width: 390, height: 844 })- await page.emulateMedia({ colorScheme: "light" })- await expect(page.locator("html")).not.toHaveClass(/dark/)- await settleSheet(sheet)- await trigger.click()- const detailDialog = page.getByRole("dialog", { name: "Activity details" })- await expect(detailDialog.getByTestId(tid.botActivityDetail)).toHaveText(fullAuditText)- await attachPageScreenshot(testInfo, "bot-activity-log-detail-mobile", page)- await page.emulateMedia({ colorScheme: "dark" })- await expect(page.locator("html")).toHaveClass(/dark/)- await expect(detailDialog.getByTestId(tid.botActivityDetail)).toHaveText(fullAuditText)- await attachPageScreenshot(testInfo, "bot-activity-log-detail-mobile-dark", page)- await detailDialog.getByRole("button", { name: "Close" }).click()- await expect(detailDialog).toBeHidden()- await expect(trigger).toBeFocused()- } catch (error) { caseJourneyFailure1 = error; caseJourneyFailure1Present = true; throw error } finally {- try {-- await machine.close()-- } catch (cleanupError) { if (caseJourneyFailure1Present) throw new AggregateError([caseJourneyFailure1, cleanupError], "Journey and resource exit both failed"); throw cleanupError }- }-})--test("owned bot profile preview stays root-bounded from its first visible frame", async ({ caseActors, caseResources }, testInfo) => {- test.setTimeout(120_000)-- const actors = await caseActors(["alice", "bob"])- const { asUser } = actors- const { seedChannel, seedForumThread, seedJoinServer, seedServer } = actors.seed- const { jsonRequest, pairMachine, createBot, joinBotToServer, headersFor } = await prepareCase(actors, caseResources)-- const suffix = Date.now().toString(36)- const serverId = await seedServer("alice", `preview-overflow-${suffix}`)- const channelName = `regular-${suffix}`- const forumName = `forum-${suffix}`- const channelId = await seedChannel("alice", serverId, channelName)- const forumId = await seedChannel("alice", serverId, forumName, "forum")- const forumThreadId = await seedForumThread(- "alice",- forumId,- `Right column ${suffix}`,- `Forum opener ${suffix}`,- )- await seedJoinServer("alice", "bob", serverId)-- const { credential, machineId } = await pairMachine()- const machine = connectMachine(credential, caseResources, { machineId, headers: headersFor("alice") })- await machine.opened- const botName = `Overflow bot ${suffix}`- const botId = await createBot(machineId, botName)- const runnerKey = await enrollBot(credential, botId)- await joinBotToServer(runnerKey, botId, serverId)- const { servers } = await jsonRequest<{- servers: Array<{ id: string; name: string; discriminator: string }>- }>("alice", "/api/community/servers")- const server = servers.find((candidate) => candidate.id === serverId)- expect(server).toBeTruthy()- const channelRef = `/${server!.name}#${server!.discriminator}/${channelName}`- const forumRef = `/${server!.name}#${server!.discriminator}/${forumName}`- const forumEnvelope = await jsonRequest<{- threads: Array<{ id: string; parentMessageId: string | null }>- included: { messages: Array<{ id: string; seq: number }> }- }>(- "alice",- `/api/community/channels/${forumId}/threads?order=createdAt&limit=50&include=parentMessage`,- )- const forumThread = forumEnvelope.threads.find((thread) => thread.id === forumThreadId)- const forumOpener = forumEnvelope.included.messages.find(- (message) => message.id === forumThread?.parentMessageId,- )- expect(forumOpener?.seq).toBeGreaterThan(0)- await sendBotMessage(runnerKey, channelRef, `Regular overflow probe ${suffix}`)- await sendBotMessage(- runnerKey,- `${forumRef}/#${forumOpener!.seq}`,- `Forum overflow probe ${suffix}`,- )-- const regularRoute = `/c/channels/${serverId}/${channelId}`- const alice = await asUser("alice")- await alice.page.setViewportSize({ width: 1280, height: 900 })- await gotoAfterUserWsAuth(alice.page, regularRoute)- const regularFrames = await probeOwnedBotProfile(- alice.page,- alice.page.getByRole("button", { name: botName, exact: true }),- "regular channel",- )- await testInfo.attach("owned-agent-preview-regular-frames.json", {- body: Buffer.from(JSON.stringify(regularFrames, null, 2)),- contentType: "application/json",- })- await attachPageScreenshot(testInfo, "owned-agent-preview-regular", alice.page)-- await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${forumThreadId}`)- const split = alice.page.getByTestId(tid.threadSplit)- await expect(split).toHaveAttribute("data-layout", "split", { timeout: 20_000 })- const threadPanel = alice.page.getByTestId(tid.threadSplitPanel)- const forumFrames = await probeOwnedBotProfile(- alice.page,- threadPanel.getByRole("button", { name: botName, exact: true }),- "forum split right column",- )- await testInfo.attach("owned-agent-preview-forum-split-frames.json", {- body: Buffer.from(JSON.stringify(forumFrames, null, 2)),- contentType: "application/json",- })- await attachPageScreenshot(testInfo, "owned-agent-preview-forum-split", alice.page)-- await alice.page.setViewportSize({ width: 390, height: 844 })- await gotoAfterUserWsAuth(alice.page, regularRoute)- await openBotProfile(alice.page, botName)- await expect(alice.page.getByRole("dialog", { name: `${botName} profile` })).toBeVisible()- await expect(alice.page.getByTestId(tid.botMarkSticker)).toBeVisible()- await expect(alice.page.getByTestId(tid.botAuditPreviewDock)).toHaveCount(0)- await attachPageScreenshot(testInfo, "owned-agent-preview-mobile-390", alice.page)-- const bob = await asUser("bob")- await bob.page.setViewportSize({ width: 1280, height: 900 })- await gotoAfterUserWsAuth(bob.page, regularRoute)- await openBotProfile(bob.page, botName)- await expect(bob.page.getByTestId(tid.profileOwnerLink)).toBeVisible()- await expect(bob.page.getByTestId(tid.botMarkSticker)).toHaveCount(0)- await expect(bob.page.getByTestId(tid.botAuditPreviewDock)).toHaveCount(0)- await attachPageScreenshot(testInfo, "owned-agent-preview-non-owner", bob.page)-})--test("owner-only bot mark sticker, Stop lifecycle, owner swap, and URL-owned audit modal", async ({ caseActors, caseResources }, testInfo) => {- test.setTimeout(180_000)-- const actors = await caseActors(["alice", "bob"])- const { asUser } = actors- const { seedChannel, seedJoinServer, seedServer } = actors.seed- const { headersFor, jsonRequest, pairMachine, createBot, joinBotToServer } = await prepareCase(actors, caseResources)-- const suffix = Date.now().toString(36)- const serverId = await seedServer("alice", `profile-preview-server-with-a-long-name-${suffix}`)- const channelName = `bots-with-a-long-channel-name-${suffix}`- const channelId = await seedChannel("alice", serverId, channelName)- const staleServerId = await seedServer("alice", `stale-mark-server-${suffix}`)- const staleChannelName = `former-private-work-${suffix}`- const staleChannelId = await seedChannel("alice", staleServerId, staleChannelName)- await seedJoinServer("alice", "bob", serverId)-- const { credential, machineId } = await pairMachine()- const machine = connectMachine(credential, caseResources, { machineId, headers: headersFor("alice") })- await machine.opened- const botName = `Preview bot ${suffix} long-name`- const botId = await createBot(machineId, botName)- const runnerKey = await enrollBot(credential, botId)- await joinBotToServer(runnerKey, botId, serverId)- await joinBotToServer(runnerKey, botId, staleServerId)-- const { servers } = await jsonRequest<{- servers: Array<{ id: string; name: string; discriminator: string }>- }>("alice", "/api/community/servers")- const server = servers.find((candidate) => candidate.id === serverId)- const staleServer = servers.find((candidate) => candidate.id === staleServerId)- expect(server).toBeTruthy()- expect(staleServer).toBeTruthy()- const channelRef = `/${server!.name}#${server!.discriminator}/${channelName}`- let latestSeq = 0- for (const index of [1, 2, 3]) {- const created = await jsonRequest<{ message: { seq: number } }>(- "alice",- `/api/community/channels/${channelId}/messages`,- {- method: "POST",- body: JSON.stringify({ content: `Marked task ${index} ${suffix}` }),- },- )- latestSeq = created.message.seq- await setBotMark(runnerKey, channelRef, latestSeq)- }- const longBotMessage = await sendBotMessage(- runnerKey,- channelRef,- `**Long marked task ${suffix}** ${"with enough detail to require a second line ".repeat(5)}`,- latestSeq,- )- await setBotMark(runnerKey, channelRef, longBotMessage.seq)-- const staleMessage = await jsonRequest<{ message: { seq: number } }>(- "alice",- `/api/community/channels/${staleChannelId}/messages`,- {- method: "POST",- body: JSON.stringify({ content: `Persisted stale mark ${suffix}` }),- },- )- const staleChannelRef = `/${staleServer!.name}#${staleServer!.discriminator}/${staleChannelName}`- await setBotMark(runnerKey, staleChannelRef, staleMessage.message.seq)- const staleMembers = await jsonRequest<{- members: Array<{ id: string; userId: string }>- }>("alice", `/api/community/servers/${staleServerId}/members`)- const staleBotMember = staleMembers.members.find((member) => member.userId === botId)- expect(staleBotMember).toBeTruthy()- const removeStaleBot = await communityFixtureFetch(- `${WEB_URL}/api/community/servers/${staleServerId}/members/${staleBotMember!.id}`,- { method: "DELETE", headers: headersFor("alice") },- )- expect(removeStaleBot.status).toBe(204)-- let caseJourneyFailure2: unknown-let caseJourneyFailure2Present = false- try {- machine.socket.send(JSON.stringify({ type: "agent_activity", agentId: botId, state: "idle" }))- for (let index = 0; index < 11; index += 1) {- machine.socket.send(JSON.stringify({- type: "bot_audit_event",- eventId: `bae_${suffix}_${String(index).padStart(2, "0")}`,- agentId: botId,- sessionId: `session-${suffix}`,- launchId: `launch-${suffix}`,- event: { kind: "text", payload: { text: `Open activity log ${index}`, truncated: false, chars: `Open activity log ${index}`.length } },- }))- }-- await expect.poll(async () => {- const response = await communityFixtureFetch(- `${WEB_URL}/api/community/bots/${botId}/audit-log?limit=10`,- { headers: headersFor("alice") },- )- if (!response.ok) return 0- return ((await response.json()) as { events: unknown[] }).events.length- }).toBe(10)-- const authoritativeMarks = await jsonRequest<{- marked: Array<{- id: string- server: string- channel: string- m: { authorName: string; content: string; createdAt: string }- }>- }>("alice", `/api/community/bots/${botId}/marks`)- expect(authoritativeMarks.marked).toHaveLength(4)- expect(authoritativeMarks.marked.some((mark) => mark.m.authorName === botName)).toBe(true)- expect(authoritativeMarks.marked).toContainEqual(expect.objectContaining({- server: staleServer!.name,- channel: staleChannelName,- m: expect.objectContaining({ content: `Persisted stale mark ${suffix}` }),- }))-- const route = `/c/channels/${serverId}/${channelId}`- const alice = await asUser("alice")- const ownerMarkRequests: string[] = []- alice.page.on("request", (request) => {- if (new URL(request.url()).pathname === `/api/community/bots/${botId}/marks`) {- ownerMarkRequests.push(request.url())- }- })- await gotoAfterUserWsAuth(alice.page, route)- await openBotProfile(alice.page, botName)-- const sticker = alice.page.getByTestId(tid.botMarkSticker)- await expect(sticker).toBeVisible()- await expect(sticker).toHaveAttribute("aria-label", "Bot log")- const activityTab = sticker.getByRole("tab", { name: "Thoughts" })- const marksTab = sticker.getByRole("tab", { name: /Marked messages/ })- const auditRows = alice.page.locator(- `[data-testid^="${tid.botAuditPreviewRow("")}"]`,- )- const activityScroller = sticker- .getByRole("tabpanel", { name: "Recent thoughts" })- .getByTestId(tid.botAuditPreviewScroll)- await expect(activityTab).toHaveAttribute("aria-selected", "true")- await expect(auditRows).toHaveCount(10)- await expect(activityScroller).toHaveCSS("overflow-y", "auto")- await expect.poll(async () => activityScroller.evaluate((element) =>- element.scrollTop + element.clientHeight >= element.scrollHeight - 1))- .toBe(true)- expect((await auditRows.allTextContents()).some((text) =>- /open activity log 0$/i.test(text))).toBe(false)- const liveEventId = `bae_${suffix}_11`- let liveEventAcknowledged = false- const onAuditAck = (data: unknown) => {- const frame = JSON.parse(String(data)) as { type?: string; eventId?: string }- if (frame.type === "bot_audit_event_ack" && frame.eventId === liveEventId) {- liveEventAcknowledged = true- }- }- machine.socket.on("message", onAuditAck)- try {- machine.socket.send(JSON.stringify({- type: "bot_audit_event",- eventId: liveEventId,- agentId: botId,- sessionId: `session-${suffix}`,- launchId: `launch-${suffix}`,- event: { kind: "text", payload: { text: "Open activity log 11", truncated: false, chars: "Open activity log 11".length } },- }))- await expect.poll(() => liveEventAcknowledged, {- message: `machine receives bot_audit_event_ack for ${liveEventId}`,- timeout: 30_000,- }).toBe(true)- } finally {- machine.socket.off("message", onAuditAck)- }- await expect.poll(async () =>- (await auditRows.allTextContents()).join(" ").toLowerCase())- .toContain("open activity log 11")- await expect(auditRows).toHaveCount(10)- expect((await auditRows.allTextContents()).some((text) =>- /open activity log 1$/i.test(text))).toBe(false)- await expect.poll(async () => activityScroller.evaluate((element) =>- element.scrollTop + element.clientHeight >= element.scrollHeight - 1))- .toBe(true)- await expect(sticker.getByRole("button", { name: /Load more activity/ })).toHaveCount(0)- await marksTab.click()- await expect(marksTab).toHaveAttribute("aria-selected", "true")- await expect(alice.page.locator(`[data-testid^="${tid.botMarkStickerRow("")}"]`))- .toHaveCount(3)- await expect(alice.page.getByTestId(tid.botMarkStickerOverflow)).toBeVisible()- await expect(sticker.getByTitle(`${server!.name} · #${channelName}`).first()).toBeVisible()- await expect(sticker).toContainText(botName)- await expect(sticker).toContainText(`Long marked task ${suffix}`)- await expect(sticker).not.toContainText("**Long marked task")- await expect(sticker.locator("time")).toHaveCount(3)- const markedBody = sticker.locator("[data-community-message-body]").filter({ hasText: `Long marked task ${suffix}` })- await expect(markedBody).toHaveCount(1)- await expect(markedBody.locator('[data-streamdown="strong"]')).toHaveText(`Long marked task ${suffix}`)- await expect(markedBody).toHaveText(`Long marked task ${suffix} ${"with enough detail to require a second line ".repeat(5)}`.trim())- await expect(markedBody.locator("p")).toHaveCSS("-webkit-line-clamp", "none")- expect(ownerMarkRequests.length).toBeGreaterThan(0)- machine.socket.send(JSON.stringify({ type: "agent_activity", agentId: botId, state: "running" }))- const stop = alice.page.getByTestId(tid.botMarkStickerStop)- await expect(stop).toBeVisible()- await attachPageScreenshot(testInfo, "bot-work-sticker-marked-running-desktop", alice.page)- await activityTab.click()- await expect(activityTab).toHaveAttribute("aria-selected", "true")- await expect(sticker.getByRole("button", { name: /Load more activity/ })).toHaveCount(0)- await expect(stop).toBeVisible()- await attachPageScreenshot(testInfo, "bot-work-sticker-activity-running-desktop", alice.page)- await marksTab.click()- const interruptFrame = new Promise<unknown>((resolveFrame) => {- const onMessage = (data: unknown) => {- const frame = JSON.parse(String(data)) as { type: string }- if (frame.type === "machine:heartbeat") return- machine.socket.off("message", onMessage)- resolveFrame(frame)- }- caseResources.own(onMessage, async captured => { machine.socket.off("message", captured) })- machine.socket.on("message", onMessage)- })- await stop.click()- await expect(stop).toContainText("Stopping…")- await expect(stop).toBeDisabled()- await expect(interruptFrame).resolves.toEqual({ type: "agent:interrupt", agentId: botId })- machine.socket.send(JSON.stringify({ type: "agent_activity", agentId: botId, state: "idle" }))- await expect.poll(async () => {- const profile = await jsonRequest<{ statusText: string | null }>(- "alice",- `/api/community/users/${botId}/profile`,- )- return profile.statusText- }).toBe("Idle")- await gotoAfterUserWsAuth(alice.page, route)- await openBotProfile(alice.page, botName)- await expect(alice.page.getByTestId(tid.botMarkStickerStop))- .toHaveCount(0)- await expect(sticker).toBeVisible()-- await alice.page.setViewportSize({ width: 375, height: 812 })- await alice.page.emulateMedia({ colorScheme: "dark" })- await expect(alice.page.locator("html")).toHaveClass(/dark/)- await expect(sticker).toBeVisible()- const mobileStickerGeometry = await sticker.evaluate((element) => ({- clientWidth: element.clientWidth,- scrollWidth: element.scrollWidth,- right: element.getBoundingClientRect().right,- }))- expect(mobileStickerGeometry.scrollWidth).toBeLessThanOrEqual(mobileStickerGeometry.clientWidth)- expect(mobileStickerGeometry.right).toBeLessThanOrEqual(375)- await expect(sticker.getByLabel("Loading thoughts")).toHaveCount(0)- await expect(sticker.getByText("Open activity log 11", { exact: true })).toBeVisible()- await attachPageScreenshot(testInfo, "bot-mark-sticker-activity-mobile-dark", alice.page)- await sticker.getByRole("tab", { name: "Marked messages" }).click()- await expect(alice.page.locator(`[data-testid^="${tid.botMarkStickerRow("")}"]`))- .toHaveCount(3)- await attachPageScreenshot(testInfo, "bot-mark-sticker-marks-mobile-dark", alice.page)- await sticker.getByRole("tab", { name: "Thoughts" }).click()- await sticker.getByTestId(tid.botAuditPreviewRow(liveEventId))- .getByText("Open activity log 11", { exact: true }).click()- await expect(alice.page).toHaveURL(new RegExp(`/c/me/bots\\?audit=${botId}`))- await gotoAfterUserWsAuth(alice.page, route)- await openBotProfile(alice.page, botName)- const footer = sticker.locator("footer")- await expect(footer.locator("time")).toHaveCount(0)- const ownerLink = alice.page.getByTestId(tid.profileOwnerLink)- await expect(alice.page.getByTestId(tid.profileBotBadge)).toContainText("Bot")- await expect(ownerLink).toBeVisible()- const ownerLinkBox = await ownerLink.boundingBox()- expect(ownerLinkBox?.height).toBeGreaterThanOrEqual(44)- const ownerHandle = await ownerLink.textContent()- await ownerLink.click()- await expect(alice.page.getByTestId(tid.profileCard)).toHaveCount(1)- await expect(alice.page.getByTestId(tid.profileOwnerLink)).toHaveCount(0)- await expect(alice.page.getByTestId(tid.profileCard))- .toContainText(ownerHandle!.trim().replace(/^@/, ""))-- await alice.page.mouse.click(4, 4)- await expect(alice.page.getByTestId(tid.profileCard)).toHaveCount(0)- await alice.page.setViewportSize({ width: 1280, height: 900 })- await alice.page.emulateMedia({ colorScheme: "light" })- await openBotProfile(alice.page, botName)- await expect(alice.page.getByTestId(tid.botAuditPreviewDock)).toHaveAttribute(- "data-placement",- /^(right|left|top|bottom)$/,- )- const openActivity = sticker.getByTestId(tid.botAuditPreviewRow(liveEventId))- .getByTitle("Open full audit log", { exact: true })- await expect(openActivity.locator("time")).toHaveCount(1)- await openActivity.focus()- await expect(openActivity).toBeFocused()- await openActivity.press("Enter")- await expect(alice.page).toHaveURL(new RegExp(`/c/me/bots\\?audit=${botId}$`))- await expect(alice.page.getByTestId(tid.botActivityModal)).toBeVisible()- await expectActivityHeader(alice.page, testInfo, 1280)- await expectActivityHeader(alice.page, testInfo, 390)- await alice.page.setViewportSize({ width: 1280, height: 900 })- await alice.page.reload()- await expect(alice.page.getByTestId(tid.botActivityModal)).toBeVisible()- await alice.page.goBack({ waitUntil: "commit" })- await expect(alice.page).toHaveURL(new RegExp(`${route}$`))- await alice.page.goForward({ waitUntil: "commit" })- await expect(alice.page.getByTestId(tid.botActivityModal)).toBeVisible()-- await alice.page.goto(`/c/me/bots?machineId=${machineId}&audit=${botId}`)- await expect(alice.page.getByTestId(tid.botActivityModal)).toBeVisible()- await alice.page.getByRole("button", { name: "Close", exact: true }).click()- await expect(alice.page).toHaveURL(`/c/me/bots?machineId=${machineId}`)-- const bob = await asUser("bob")- const bobDirectMarks = await communityFixtureFetch(`${WEB_URL}/api/community/bots/${botId}/marks`, {- headers: headersFor("bob"),- })- expect(bobDirectMarks.status).toBe(404)- const bobMarkRequests: string[] = []- bob.page.on("request", (request) => {- if (new URL(request.url()).pathname === `/api/community/bots/${botId}/marks`) {- bobMarkRequests.push(request.url())- }- })- await gotoAfterUserWsAuth(bob.page, route)- await openBotProfile(bob.page, botName)- await expect(bob.page.getByTestId(tid.profileOwnerLink)).toBeVisible()- await expect(bob.page.getByTestId(tid.botMarkSticker)).toHaveCount(0)- expect(bobMarkRequests).toEqual([])- await bob.page.getByTestId(tid.profileOwnerLink).click()- await expect(bob.page.getByTestId(tid.profileCard)).toHaveCount(1)- await expect(bob.page.getByTestId(tid.profileOwnerLink)).toHaveCount(0)-- await bob.page.goto(`/c/me/bots?audit=${botId}`)- await expect(bob.page.getByTestId(tid.botActivityModal)).toHaveCount(0)- await expect.poll(() => new URL(bob.page.url()).searchParams.has("audit")).toBe(false)- expect(bobMarkRequests).toEqual([])- } catch (error) { caseJourneyFailure2 = error; caseJourneyFailure2Present = true; throw error } finally {- try {-- await machine.close()-- } catch (cleanupError) { if (caseJourneyFailure2Present) throw new AggregateError([caseJourneyFailure2, cleanupError], "Journey and resource exit both failed"); throw cleanupError }- }-})--test("CommunitySheet footers keep four consumers horizontal and intrinsic at 390/639/640", async ({ caseActors, caseResources }) => {- test.setTimeout(180_000)-- const actors = await caseActors(["alice"])- const { asUser } = actors- const { seedChannel, seedServer } = actors.seed- const { cleanupCreatedResources, jsonRequest, pairMachine, createBot, headersFor } = await prepareCase(actors, caseResources)-- const { credential, machineId } = await pairMachine()- const machine = connectMachine(credential, caseResources, { machineId, headers: headersFor("alice") })- await machine.opened- const botName = `Footer bot ${Date.now().toString(36)}`- await createBot(machineId, botName)- const { page } = await asUser("alice")- await gotoAfterUserWsAuth(page, "/c/me/bots")-- const capacity = await jsonRequest<{ ownedCount: number; limit: number }>("alice", "/api/community/bots")- expect(capacity.ownedCount).toBeLessThan(capacity.limit)- const create = page.getByRole("button", { name: "Create a bot", exact: true })- await expect(create).toBeEnabled()- await create.click()- for (const width of [390, 639, 640] as const) {- await expectFooterGeometry(page, "Create a bot", ["Cancel", "Create bot"], width)- }- await page.getByRole("dialog", { name: "Create a bot", exact: true })- .getByRole("button", { name: "Close", exact: true }).click()-- await page.locator('[data-slot="card"]')- .filter({ has: page.getByText(botName, { exact: true }) })- .getByRole("button", { name: "Bot actions", exact: true }).click()- await page.getByRole("menuitem", { name: "Edit", exact: true }).click()- for (const width of [390, 639, 640] as const) {- await expectFooterGeometry(page, `Edit ${botName}`, ["Cancel", "Save"], width)- }- await page.getByRole("dialog", { name: `Edit ${botName}`, exact: true })- .getByRole("button", { name: "Close", exact: true }).click()-- await cleanupCreatedResources()- await gotoAfterUserWsAuth(page, "/c/me/machines")- await page.getByTestId(tid.machinePairOpen).click()- for (const width of [390, 639, 640] as const) {- await expectFooterGeometry(page, "Connect a machine", ["Done"], width)- }- await page.getByRole("dialog", { name: "Connect a machine", exact: true })- .getByRole("button", { name: "Done", exact: true }).click()-- const serverId = await seedServer("alice", `footer-${Date.now()}`)- const channelId = await seedChannel("alice", serverId, `footer-${Date.now()}`)- await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)- const fileName = `footer-oracle-${Date.now()}.md`- const uploadResponse = page.waitForResponse((response) => (- response.request().method() === "POST"- && new URL(response.url()).pathname === `/api/community/channels/${channelId}/attachments`- ))- const messageResponse = page.waitForResponse((response) => (- response.request().method() === "POST"- && new URL(response.url()).pathname === `/api/community/channels/${channelId}/messages`- ))- const editable = composerEditable(page)- await editable.click()- await editable.pressSequentially("Attachment footer oracle")- await page.getByTestId(tid.composerFileInput).setInputFiles({- name: fileName,- mimeType: "text/markdown",- buffer: Buffer.from("# Footer oracle"),- })- await page.keyboard.press("Enter")- expect((await uploadResponse).ok()).toBe(true)- expect((await messageResponse).status()).toBe(201)- await page.getByTestId(tid.attachmentCard(fileName)).click()- for (const width of [390, 639, 640] as const) {- await expectFooterGeometry(page, fileName, ["Download"], width)- }-})--type ActivityAnchorPage = {- events: Array<{ id: string; createdAt: string }>- nextCursor: { beforeCreatedAt: string; beforeId: string } | null-}--async function activityAnchorSnapshot(scroller: Locator) {- return scroller.evaluate(element => {- const root = element.getBoundingClientRect()- return {- scrollTop: element.scrollTop,- scrollHeight: element.scrollHeight,- clientHeight: element.clientHeight,- overflowAnchor: getComputedStyle(element).overflowAnchor,- events: [...element.querySelectorAll<HTMLElement>("[data-activity-event-id]")].flatMap(wrapper => {- const body = wrapper.firstElementChild- if (!(body instanceof HTMLElement)) return []- const rect = body.getBoundingClientRect()- return [{ id: wrapper.dataset.activityEventId!, top: rect.top - root.top, bottom: rect.bottom - root.top, height: rect.height }]- }),- }- })-}--async function settleActivityPosition(scroller: Locator, target: number) {- return scroller.evaluate(async (element, target) => {- const samples: Array<{ scrollTop: number; scrollHeight: number; clientHeight: number; events: Array<{ id: string; top: number; bottom: number }> }> = []- let previous = ""- let stableFrames = 0- for (let frame = 0; frame < 120; frame += 1) {- await new Promise<void>(resolveFrame => requestAnimationFrame(() => resolveFrame()))- if (!element.isConnected) return { settled: false, samples }- const root = element.getBoundingClientRect()- const sample = {- scrollTop: element.scrollTop,- scrollHeight: element.scrollHeight,- clientHeight: element.clientHeight,- events: [...element.querySelectorAll<HTMLElement>("[data-activity-event-id]")].flatMap(wrapper => {- const body = wrapper.firstElementChild- if (!(body instanceof HTMLElement)) return []- const rect = body.getBoundingClientRect()- return [{ id: wrapper.dataset.activityEventId!, top: rect.top - root.top, bottom: rect.bottom - root.top }]- }),- }- samples.push(sample)- const signature = JSON.stringify(sample)- stableFrames = Math.abs(sample.scrollTop - target) <= 1 && sample.events.length > 0 && signature === previous ? stableFrames + 1 : 0- if (stableFrames === 2) return { settled: true, samples }- previous = signature- }- return { settled: false, samples }- }, target)-}--async function gateOlderActivityPages(page: Page, botId: string, caseResources: CaseResources) {- const entries: Array<{ url: string; release: (status?: 503) => void }> = []- const running = new Set<Promise<void>>()- let closing = false- const matches = (url: URL) => url.pathname === `/api/community/bots/${botId}/audit-log`- const handler = (route: Route) => {- const url = new URL(route.request().url())- if (!url.searchParams.has("beforeId")) return route.continue()- if (closing) return route.abort("failed")- let release!: (status?: 503) => void- const ready = new Promise<503 | undefined>(resolveGate => { release = resolveGate })- const operation = (async () => {- const status = await ready- if (page.isClosed()) return- if (closing) await route.abort("failed")- else if (status) await route.fulfill(currentCommunityFixtureError("Injected Activity older-page failure", status))- else await route.continue()- })()- entries.push({ url: url.toString(), release })- running.add(operation)- return operation.finally(() => running.delete(operation))- }- const owned = caseResources.own(entries, async () => {- closing = true- for (const entry of entries) entry.release()- await Promise.all(running)- if (!page.isClosed()) await page.unroute(matches, handler)- })- await page.route(matches, handler)- return { entries, close: () => owned.close() }-}--type ActivityJsonRequest = Awaited<ReturnType<typeof prepareCase>>["jsonRequest"]--async function seedActivityHistory({ machine, botId, suffix, scenario, caseResources, jsonRequest, testInfo }: {- machine: ReturnType<typeof connectMachine>- botId: string- suffix: string- scenario: "same-day" | "cross-day"- caseResources: CaseResources- jsonRequest: ActivityJsonRequest- testInfo: TestInfo-}) {- const now = new Date()- const start = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() - 5, 12)- const history = Array.from({ length: 200 }, (_, index) => ({- id: `bae_anchor_${suffix}_${String(index).padStart(3, "0")}`,- createdAt: new Date(start + (scenario === "cross-day" ? Math.floor(index / 60) * 86_400_000 + index % 60 * 1_000 : index * 1_000)).toISOString(),- }))- const acknowledged = new Set<string>()- const acknowledgements: Array<{ type: string; eventId: string }> = []- const expectedIds = new Set(history.map(event => event.id))- const onMessage = (raw: unknown) => {- const frame = JSON.parse(String(raw)) as { type?: string; eventId?: string }- if (frame.type === "bot_audit_event_ack" && frame.eventId && expectedIds.has(frame.eventId)) {- acknowledged.add(frame.eventId)- acknowledgements.push({ type: frame.type, eventId: frame.eventId })- }- }- const listener = caseResources.own(onMessage, async captured => { machine.socket.off("message", captured) })- machine.socket.on("message", onMessage)- for (const event of history) machine.socket.send(JSON.stringify({- type: "bot_audit_event",- eventId: event.id,- occurredAt: event.createdAt,- agentId: botId,- sessionId: `anchor-session-${suffix}`,- launchId: `anchor-launch-${suffix}`,- event: { kind: "session_reset", payload: { trigger: "idle_timeout" } },- }))- await expect.poll(() => acknowledged.size, { timeout: 30_000 }).toBe(history.length)- await listener.close()- const headPath = `/api/community/bots/${botId}/audit-log?limit=50`- const head = await jsonRequest<ActivityAnchorPage>("alice", headPath)- await testInfo.attach("activity-history-backend", {- body: JSON.stringify({ botId, scenario, history, acknowledgements, headPath, head }),- contentType: "application/json",- })- expect(head.events.map(event => ({ id: event.id, createdAt: event.createdAt }))).toEqual(history.slice(-50).reverse())- expect(head.nextCursor).toEqual({ beforeCreatedAt: history[150].createdAt, beforeId: history[150].id })- return history-}--function observeActivityFrames(page: Page, caseResources: CaseResources) {- const frames: Array<{ id: string; botId: string; createdAt: string }> = []- const onSocket = (socket: BrowserSocket) => {- const onFrame = ({ payload }: { payload: string | Buffer }) => {- let frame: { type?: string; id?: string; botId?: string; createdAt?: string }- try { frame = JSON.parse(String(payload)) } catch { return }- if (frame.type === "community:bot.audit_event" && frame.id && frame.botId && frame.createdAt) {- frames.push({ id: frame.id, botId: frame.botId, createdAt: frame.createdAt })- }- }- socket.on("framereceived", onFrame)- caseResources.own(socket, async captured => { captured.off("framereceived", onFrame) })- }- page.on("websocket", onSocket)- caseResources.own(onSocket, async captured => { page.off("websocket", captured) })- return frames-}--async function publishActivityReset({ machine, botId, suffix, id, createdAt, frames, caseResources, jsonRequest, testInfo }: {- machine: ReturnType<typeof connectMachine>- botId: string- suffix: string- id: string- createdAt: string- frames: ReturnType<typeof observeActivityFrames>- caseResources: CaseResources- jsonRequest: ActivityJsonRequest- testInfo: TestInfo-}) {- let acknowledged = false- const onMessage = (raw: unknown) => {- const frame = JSON.parse(String(raw)) as { type?: string; eventId?: string }- if (frame.type === "bot_audit_event_ack" && frame.eventId === id) acknowledged = true- }- const listener = caseResources.own(onMessage, async captured => { machine.socket.off("message", captured) })- machine.socket.on("message", onMessage)- machine.socket.send(JSON.stringify({- type: "bot_audit_event", eventId: id, occurredAt: createdAt, agentId: botId,- sessionId: `anchor-session-${suffix}`, launchId: `anchor-launch-${suffix}`,- event: { kind: "session_reset", payload: { trigger: "idle_timeout" } },- }))- await expect.poll(() => acknowledged).toBe(true)- await listener.close()- await expect.poll(() => frames.some(frame => frame.id === id && frame.botId === botId && frame.createdAt === createdAt)).toBe(true)- const cursor = new URLSearchParams({ limit: "50", beforeCreatedAt: new Date(Date.parse(createdAt) + 1).toISOString(), beforeId: id })- const path = `/api/community/bots/${botId}/audit-log?${cursor}`- const persisted = await jsonRequest<ActivityAnchorPage>("alice", path)- await testInfo.attach(`activity-live-${id}`, {- body: JSON.stringify({ id, botId, createdAt, acknowledged, received: frames.filter(frame => frame.id === id), path, persisted }),- contentType: "application/json",- })- expect(persisted.events[0]).toMatchObject({ id, createdAt })-}--async function expectActivityPosition(scroller: Locator, anchor: { id: string; top: number }) {- await expect.poll(async () => {- const snapshot = await activityAnchorSnapshot(scroller)- const kept = snapshot.events.find(event => event.id === anchor.id)- return kept ? Math.abs(kept.top - anchor.top) : Number.POSITIVE_INFINITY- }).toBeLessThanOrEqual(1)-}--async function visibleActivityAnchor(scroller: Locator) {- const snapshot = await activityAnchorSnapshot(scroller)- const anchor = snapshot.events.find(event => event.top >= 32 && event.bottom <= snapshot.clientHeight)- expect(anchor).toBeDefined()- return anchor!-}--for (const scenario of ["same-day", "cross-day"] as const) {- for (const width of [1280, 390] as const) {- test(`Activity ${scenario} older pages preserve real event positions at ${width}`, async ({ caseActors, caseResources }, testInfo) => {- test.setTimeout(120_000)- const actors = await caseActors(["alice"])- const { pairMachine, createBot, jsonRequest, headersFor } = await prepareCase(actors, caseResources)- const { credential, machineId } = await pairMachine()- const machine = connectMachine(credential, caseResources, { machineId, headers: headersFor("alice") })- await machine.opened- const suffix = Date.now().toString(36)- const botId = await createBot(machineId, `Anchor ${scenario} ${width} ${suffix}`)- let gate: Awaited<ReturnType<typeof gateOlderActivityPages>> | undefined- let journeyFailure: unknown- let journeyFailurePresent = false- const positioning: Array<{ page: number; target: number; deltaY: number; olderRequests: string[] } & Awaited<ReturnType<typeof settleActivityPosition>>> = []- try {- const history = await seedActivityHistory({ machine, botId, suffix, scenario, caseResources, jsonRequest, testInfo })- const { page } = await actors.asUser("alice", { viewport: { width, height: 900 }, colorScheme: width === 390 ? "dark" : "light" })- gate = await gateOlderActivityPages(page, botId, caseResources)- await gotoAfterUserWsAuth(page, `/c/me/bots?audit=${botId}`)- const sheet = page.getByTestId(tid.botActivityModal)- await settleSheet(sheet)- const scroller = sheet.getByRole("region", { name: "Activity log", exact: true })- await expect(scroller).toHaveCount(1)- await expect.poll(() => scroller.evaluate(element => Boolean(element.querySelector("[data-activity-event-id]"))- && element.scrollHeight > element.clientHeight- && element.scrollTop + element.clientHeight >= element.scrollHeight - 1)).toBe(true)- for (const [index, target] of [0, 80].entries()) {- await scroller.hover()- await page.mouse.wheel(0, -1_000_000)- const zeroPosition = await settleActivityPosition(scroller, 0)- positioning.push({ page: index + 1, target: 0, deltaY: -1_000_000, olderRequests: gate.entries.map(entry => entry.url), ...zeroPosition })- expect(zeroPosition.settled, "physical zero and rendered geometry settle before choosing the reading position").toBe(true)- if (target > 0) {- await page.mouse.wheel(0, target)- const nearTopPosition = await settleActivityPosition(scroller, target)- positioning.push({ page: index + 1, target, deltaY: target, olderRequests: gate.entries.map(entry => entry.url), ...nearTopPosition })- expect(nearTopPosition.settled, "physical near-top target and rendered geometry settle without another wheel").toBe(true)- }- await expect.poll(async () => Math.abs(await scroller.evaluate(element => element.scrollTop) - target)).toBeLessThanOrEqual(1)- await expect.poll(() => gate!.entries.length).toBe(index + 1)- const pending = gate.entries[index]- const cursor = history[150 - index * 50]- const url = new URL(pending.url)- expect(url.searchParams.get("limit")).toBe("50")- expect(url.searchParams.get("beforeId")).toBe(cursor.id)- expect(url.searchParams.get("beforeCreatedAt")).toBe(cursor.createdAt)- const before = await activityAnchorSnapshot(scroller)- expect(Math.abs(before.scrollTop - target), "physical target at retained snapshot").toBeLessThanOrEqual(1)- expect(before.overflowAnchor).toBe("none")- const anchor = before.events.find(event => event.top >= 32 && event.bottom <= before.clientHeight)- expect(anchor).toBeDefined()- await attachPageScreenshot(testInfo, `activity-anchor-${scenario}-${width}-before-page-${index + 1}`, page)- const atRelease = await activityAnchorSnapshot(scroller)- expect(Math.abs(atRelease.scrollTop - target), "physical target at response release").toBeLessThanOrEqual(1)- const releaseAnchor = atRelease.events.find(event => event.id === anchor!.id)- expect(releaseAnchor).toBeDefined()- expect(Math.abs(releaseAnchor!.top - anchor!.top), "named event at response release").toBeLessThanOrEqual(1)- const [response] = await Promise.all([- page.waitForResponse(value => value.url() === pending.url && value.request().method() === "GET"),- Promise.resolve().then(() => pending.release()),- ])- expect(response.status()).toBe(200)- const body = await response.json() as ActivityAnchorPage- expect(body.events.map(event => ({ id: event.id, createdAt: event.createdAt })))- .toEqual(history.slice(100 - index * 50, 150 - index * 50).reverse())- expect(body.nextCursor).not.toBeNull()- await expect.poll(() => scroller.evaluate(element => element.scrollHeight)).toBeGreaterThan(before.scrollHeight + 300)- try {- await expect.poll(async () => {- const after = await activityAnchorSnapshot(scroller)- const kept = after.events.find(event => event.id === anchor!.id)- return kept ? Math.abs(kept.top - anchor!.top) : Number.POSITIVE_INFINITY- }).toBeLessThanOrEqual(1)- await scroller.evaluate(() => new Promise<void>(resolveFrame => {- requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(() => resolveFrame())))- }))- await expectActivityPosition(scroller, anchor!)- expect(gate.entries).toHaveLength(index + 1)- } finally {- await testInfo.attach(`activity-anchor-${scenario}-${width}-page-${index + 1}`, {- body: JSON.stringify({ scenario, width, target, anchor, request: pending.url, returnedIds: body.events.map(event => event.id), before, atRelease, after: await activityAnchorSnapshot(scroller), olderRequestCount: gate.entries.length }),- contentType: "application/json",- })- await attachPageScreenshot(testInfo, `activity-anchor-${scenario}-${width}-page-${index + 1}`, page)- }- }- } catch (error) { journeyFailure = error; journeyFailurePresent = true; throw error } finally {- const exitErrors: unknown[] = []- try { await gate?.close() } catch (error) { exitErrors.push(error) }- try { await machine.close() } catch (error) { exitErrors.push(error) }- try {- await testInfo.attach(`activity-anchor-${scenario}-${width}-positioning`, {- body: JSON.stringify({ responseReleaseTargets: [0, 80], requestStartPosition: "not asserted; the gate can hold a request during the zero-position step", positioning }),- contentType: "application/json",- })- } catch (error) { exitErrors.push(error) }- if (exitErrors.length) throw new AggregateError(journeyFailurePresent ? [journeyFailure, ...exitErrors] : exitErrors, "Activity journey, cleanup or evidence retention failed")- }- })- }-}--for (const width of [1280, 390] as const) {- test(`Activity recovery, live reading and reopen preserve event ownership at ${width}`, async ({ caseActors, caseResources }, testInfo) => {- test.setTimeout(120_000)- const actors = await caseActors(["alice"])- const { pairMachine, createBot, jsonRequest, headersFor } = await prepareCase(actors, caseResources)- const suffix = Date.now().toString(36)- const { credential, machineId } = await pairMachine()- const machine = connectMachine(credential, caseResources, { machineId, headers: headersFor("alice") })- await machine.opened- const botId = await createBot(machineId, `Recovery ${width} ${suffix}`)- let gate: Awaited<ReturnType<typeof gateOlderActivityPages>> | undefined- let journeyFailure: unknown- let journeyFailurePresent = false- const steps: Array<Record<string, unknown>> = []- try {- const history = await seedActivityHistory({ machine, botId, suffix, scenario: "same-day", caseResources, jsonRequest, testInfo })- const { page } = await actors.asUser("alice", { viewport: { width, height: 900 }, colorScheme: width === 390 ? "dark" : "light" })- const frames = observeActivityFrames(page, caseResources)- gate = await gateOlderActivityPages(page, botId, caseResources)- await gotoAfterUserWsAuth(page, `/c/me/bots?audit=${botId}`)- const sheet = page.getByTestId(tid.botActivityModal)- await settleSheet(sheet)- const scroller = sheet.getByRole("region", { name: "Activity log", exact: true })- await expect(scroller).toHaveCSS("overflow-anchor", "none")- const record = async (phase: string) => {- steps.push({ phase, snapshot: await activityAnchorSnapshot(scroller), olderRequests: gate!.entries.map(entry => entry.url) })- await attachPageScreenshot(testInfo, `activity-recovery-${width}-${phase}`, page)- }- await expect.poll(() => scroller.evaluate(element => Boolean(element.querySelector("[data-activity-event-id]"))- && element.scrollHeight > element.clientHeight- && element.scrollTop + element.clientHeight >= element.scrollHeight - 1)).toBe(true)- await scroller.hover()- await page.mouse.wheel(0, -1_000_000)- await expect.poll(() => scroller.evaluate(element => element.scrollTop)).toBe(0)- await expect.poll(() => gate!.entries.length).toBe(1)- const anchor = await visibleActivityAnchor(scroller)- const cursor = history[150]- await record("before-error")- for (const index of [0, 1]) {- await expect.poll(() => gate!.entries.length).toBe(index + 1)- const pending = gate.entries[index]- const url = new URL(pending.url)- expect(url.searchParams.get("beforeId")).toBe(cursor.id)- expect(url.searchParams.get("beforeCreatedAt")).toBe(cursor.createdAt)- const atRelease = await activityAnchorSnapshot(scroller)- steps.push({ phase: `before-error-release-${index + 1}`, snapshot: atRelease })- expect(atRelease.scrollTop, "physical target before injected error").toBe(0)- const releaseAnchor = atRelease.events.find(event => event.id === anchor.id)- expect(releaseAnchor).toBeDefined()- expect(Math.abs(releaseAnchor!.top - anchor.top)).toBeLessThanOrEqual(1)- const [response] = await Promise.all([- page.waitForResponse(value => value.url() === pending.url),- Promise.resolve().then(() => pending.release(503)),- ])- expect(response.status()).toBe(503)- steps.push({ phase: `injected-error-${index + 1}`, url: pending.url, status: response.status() })- }- const retry = sheet.getByRole("button", { name: "Retry older", exact: true })- await expect(retry).toBeEnabled()- await expectActivityPosition(scroller, anchor)- await scroller.evaluate(() => new Promise<void>(resolveFrame => {- requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(() => resolveFrame())))- }))- expect(gate.entries).toHaveLength(2)- await record("failed-and-stopped")- await retry.click()- await expect.poll(() => gate!.entries.length).toBe(3)- expect(gate.entries[2].url).toBe(gate.entries[0].url)- const beforeRecovery = await activityAnchorSnapshot(scroller)- steps.push({ phase: "before-recovery-release", snapshot: beforeRecovery })- expect(beforeRecovery.scrollTop, "physical target before recovery").toBe(0)- const recoveryAnchor = beforeRecovery.events.find(event => event.id === anchor.id)- expect(recoveryAnchor).toBeDefined()- expect(Math.abs(recoveryAnchor!.top - anchor.top)).toBeLessThanOrEqual(1)- const [recovered] = await Promise.all([- page.waitForResponse(value => value.url() === gate!.entries[2].url && value.status() === 200),- Promise.resolve().then(() => gate!.entries[2].release()),- ])- const recoveredBody = await recovered.json() as ActivityAnchorPage- expect(recoveredBody.events.map(event => ({ id: event.id, createdAt: event.createdAt }))).toEqual(history.slice(100, 150).reverse())- expect(recoveredBody.nextCursor).toEqual({ beforeCreatedAt: history[100].createdAt, beforeId: history[100].id })- steps.push({ phase: "recovery-response", status: recovered.status(), body: recoveredBody })- await expect.poll(() => scroller.evaluate(element => element.scrollHeight)).toBeGreaterThan(beforeRecovery.scrollHeight + 300)- await expect(retry).toHaveCount(0)- await expectActivityPosition(scroller, anchor)- expect(gate.entries).toHaveLength(3)- await record("recovered")- const publish = (label: string, createdAt: string) => publishActivityReset({- machine, botId, suffix, id: `bae_${label}_${suffix}`, createdAt, frames, caseResources, jsonRequest, testInfo,- })- const liveId = `bae_history_${suffix}`- const liveTime = Date.parse(history[199].createdAt) + 86_400_000- await publish("history", new Date(liveTime).toISOString())- await expectActivityPosition(scroller, anchor)- await expect(scroller.locator(`[data-activity-event-id="${liveId}"]`)).toHaveCount(0)- await record("live-while-reading")- await publish("late", new Date(Date.parse(history[140].createdAt) + 500).toISOString())- await expectActivityPosition(scroller, anchor)- await record("late-interleave")- await page.setViewportSize({ width, height: 760 })- await expectActivityPosition(scroller, anchor)- await record("resized")- const beforeTakeover = await scroller.evaluate(element => element.scrollTop)- await scroller.hover()- await page.mouse.wheel(0, 150)- await expect.poll(() => scroller.evaluate(element => element.scrollTop)).toBeGreaterThan(beforeTakeover + 100)- const readerAnchor = await visibleActivityAnchor(scroller)- expect(readerAnchor.id).not.toBe(anchor.id)- await publish("reader", new Date(liveTime + 1_000).toISOString())- await expectActivityPosition(scroller, readerAnchor)- await record("reader-takeover")- await scroller.hover()- await page.mouse.wheel(0, 1_000_000)- await expect.poll(() => scroller.evaluate(element => element.scrollTop + element.clientHeight >= element.scrollHeight - 1)).toBe(true)- const tailId = `bae_tail_${suffix}`- await publish("tail", new Date().toISOString())- await expect(scroller.locator(`[data-activity-event-id="${tailId}"]`)).toBeVisible()- await expect.poll(() => scroller.evaluate(element => element.scrollTop + element.clientHeight >= element.scrollHeight - 1)).toBe(true)- await expect(scroller.locator("[data-activity-date]").filter({ hasText: /^Today$/ }).last()).toBeVisible()- await record("tail-follow")- await gate.close()- steps.push({ phase: "older-control-retired-before-navigation", requests: gate.entries.map(entry => entry.url) })- await sheet.getByRole("button", { name: "Close", exact: true }).click()- await expect(sheet).toHaveCount(0)- await expect(page).toHaveURL("/c/me/bots")- await gotoAfterUserWsAuth(page, `/c/me/bots?audit=${botId}`)- await settleSheet(sheet)- await expect(scroller.locator(`[data-activity-event-id="${tailId}"]`)).toBeVisible()- await expect.poll(() => scroller.evaluate(element => element.scrollTop + element.clientHeight >= element.scrollHeight - 1)).toBe(true)- await record("reopened")- const otherBotId = await createBot(machineId, `Other ${width} ${suffix}`)- await gotoAfterUserWsAuth(page, `/c/me/bots?audit=${otherBotId}`)- await settleSheet(sheet)- const otherId = `bae_other_${suffix}`- await publishActivityReset({ machine, botId: otherBotId, suffix, id: otherId, createdAt: new Date().toISOString(), frames, caseResources, jsonRequest, testInfo })- await expect(scroller.locator(`[data-activity-event-id="${otherId}"]`)).toBeVisible()- await expect(scroller.locator(`[data-activity-event-id="${tailId}"]`)).toHaveCount(0)- await record("other-bot")- gate = await gateOlderActivityPages(page, botId, caseResources)- steps.push({ phase: "pending-control-installed-before-return" })- await gotoAfterUserWsAuth(page, `/c/me/bots?audit=${botId}`)- await settleSheet(sheet)- await expect(scroller.locator(`[data-activity-event-id="${tailId}"]`)).toBeVisible()- const requestsBeforeWheel = gate.entries.length- await scroller.hover()- await page.mouse.wheel(0, -1_000_000)- await expect.poll(() => gate!.entries.length).toBe(1)- const pendingUrl = gate.entries[0].url- const pendingSearch = new URL(pendingUrl).searchParams- const pendingCursor = history.find(event => event.id === pendingSearch.get("beforeId"))- expect(pendingCursor).toBeDefined()- expect(pendingSearch.get("beforeCreatedAt")).toBe(pendingCursor!.createdAt)- expect(pendingSearch.get("limit")).toBe("50")- await expect(sheet).toBeVisible()- steps.push({ phase: "owned-pending-route-ready", requestsBeforeWheel, url: pendingUrl, cursor: pendingCursor, snapshot: await activityAnchorSnapshot(scroller) })- const failed = page.waitForEvent("requestfailed", { predicate: request => request.url() === pendingUrl })- await gate.close()- const aborted = await failed- expect(aborted.failure()?.errorText).toBeTruthy()- steps.push({ phase: "owned-pending-route-exit", url: aborted.url(), failure: aborted.failure() })- await sheet.getByRole("button", { name: "Close", exact: true }).click()- await expect(sheet).toHaveCount(0)- await attachPageScreenshot(testInfo, `activity-recovery-${width}-closed`, page)- } catch (error) { journeyFailure = error; journeyFailurePresent = true; throw error } finally {- await testInfo.attach(`activity-recovery-${width}-steps`, { body: JSON.stringify({ width, botId, steps }), contentType: "application/json" })- try {- await gate?.close()- await machine.close()- } catch (cleanupError) { if (journeyFailurePresent) throw new AggregateError([journeyFailure, cleanupError], "Journey and resource exit both failed"); throw cleanupError }- }- })-}diff --git a/src/web/src/test/e2e-ui/30-bot-profile-bounds.spec.ts b/src/web/src/test/e2e-ui/30-bot-profile-bounds.spec.tsnew file mode 100644index 000000000..4eab0330c--- /dev/null+++ b/src/web/src/test/e2e-ui/30-bot-profile-bounds.spec.ts@@ -0,0 +1,108 @@+import { test, expect } from "./_fixtures/case-fixture"+import { gotoAfterUserWsAuth } from "./_fixtures/actions"+import { tid } from "./_fixtures/testids"+import { connectMachine } from "./_fixtures/community-machine"+import { prepareCase, attachPageScreenshot, enrollBot, sendBotMessage, openBotProfile, probeOwnedBotProfile } from "./_fixtures/bot-profile-audit"++test("owned bot profile preview stays root-bounded from its first visible frame", async ({ caseActors, caseResources }, testInfo) => {+ test.setTimeout(120_000)++ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { seedChannel, seedForumThread, seedJoinServer, seedServer } = actors.seed+ const { jsonRequest, pairMachine, createBot, joinBotToServer, headersFor } = await prepareCase(actors, caseResources)++ const suffix = Date.now().toString(36)+ const serverId = await seedServer("alice", `preview-overflow-${suffix}`)+ const channelName = `regular-${suffix}`+ const forumName = `forum-${suffix}`+ const channelId = await seedChannel("alice", serverId, channelName)+ const forumId = await seedChannel("alice", serverId, forumName, "forum")+ const forumThreadId = await seedForumThread(+ "alice",+ forumId,+ `Right column ${suffix}`,+ `Forum opener ${suffix}`,+ )+ await seedJoinServer("alice", "bob", serverId)++ const { credential, machineId } = await pairMachine()+ const machine = connectMachine(credential, caseResources, { machineId, headers: headersFor("alice") })+ await machine.opened+ const botName = `Overflow bot ${suffix}`+ const botId = await createBot(machineId, botName)+ const runnerKey = await enrollBot(credential, botId)+ await joinBotToServer(runnerKey, botId, serverId)+ const { servers } = await jsonRequest<{+ servers: Array<{ id: string; name: string; discriminator: string }>+ }>("alice", "/api/community/servers")+ const server = servers.find((candidate) => candidate.id === serverId)+ expect(server).toBeTruthy()+ const channelRef = `/${server!.name}#${server!.discriminator}/${channelName}`+ const forumRef = `/${server!.name}#${server!.discriminator}/${forumName}`+ const forumEnvelope = await jsonRequest<{+ threads: Array<{ id: string; parentMessageId: string | null }>+ included: { messages: Array<{ id: string; seq: number }> }+ }>(+ "alice",+ `/api/community/channels/${forumId}/threads?order=createdAt&limit=50&include=parentMessage`,+ )+ const forumThread = forumEnvelope.threads.find((thread) => thread.id === forumThreadId)+ const forumOpener = forumEnvelope.included.messages.find(+ (message) => message.id === forumThread?.parentMessageId,+ )+ expect(forumOpener?.seq).toBeGreaterThan(0)+ await sendBotMessage(runnerKey, channelRef, `Regular overflow probe ${suffix}`)+ await sendBotMessage(+ runnerKey,+ `${forumRef}/#${forumOpener!.seq}`,+ `Forum overflow probe ${suffix}`,+ )++ const regularRoute = `/c/channels/${serverId}/${channelId}`+ const alice = await asUser("alice")+ await alice.page.setViewportSize({ width: 1280, height: 900 })+ await gotoAfterUserWsAuth(alice.page, regularRoute)+ const regularFrames = await probeOwnedBotProfile(+ alice.page,+ alice.page.getByRole("button", { name: botName, exact: true }),+ "regular channel",+ )+ await testInfo.attach("owned-agent-preview-regular-frames.json", {+ body: Buffer.from(JSON.stringify(regularFrames, null, 2)),+ contentType: "application/json",+ })+ await attachPageScreenshot(testInfo, "owned-agent-preview-regular", alice.page)++ await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${forumThreadId}`)+ const split = alice.page.getByTestId(tid.threadSplit)+ await expect(split).toHaveAttribute("data-layout", "split", { timeout: 20_000 })+ const threadPanel = alice.page.getByTestId(tid.threadSplitPanel)+ const forumFrames = await probeOwnedBotProfile(+ alice.page,+ threadPanel.getByRole("button", { name: botName, exact: true }),+ "forum split right column",+ )+ await testInfo.attach("owned-agent-preview-forum-split-frames.json", {+ body: Buffer.from(JSON.stringify(forumFrames, null, 2)),+ contentType: "application/json",+ })+ await attachPageScreenshot(testInfo, "owned-agent-preview-forum-split", alice.page)++ await alice.page.setViewportSize({ width: 390, height: 844 })+ await gotoAfterUserWsAuth(alice.page, regularRoute)+ await openBotProfile(alice.page, botName)+ await expect(alice.page.getByRole("dialog", { name: `${botName} profile` })).toBeVisible()+ await expect(alice.page.getByTestId(tid.botMarkSticker)).toBeVisible()+ await expect(alice.page.getByTestId(tid.botAuditPreviewDock)).toHaveCount(0)+ await attachPageScreenshot(testInfo, "owned-agent-preview-mobile-390", alice.page)++ const bob = await asUser("bob")+ await bob.page.setViewportSize({ width: 1280, height: 900 })+ await gotoAfterUserWsAuth(bob.page, regularRoute)+ await openBotProfile(bob.page, botName)+ await expect(bob.page.getByTestId(tid.profileOwnerLink)).toBeVisible()+ await expect(bob.page.getByTestId(tid.botMarkSticker)).toHaveCount(0)+ await expect(bob.page.getByTestId(tid.botAuditPreviewDock)).toHaveCount(0)+ await attachPageScreenshot(testInfo, "owned-agent-preview-non-owner", bob.page)+})diff --git a/src/web/src/test/e2e-ui/30-sheet-footer-geometry.spec.ts b/src/web/src/test/e2e-ui/30-sheet-footer-geometry.spec.tsnew file mode 100644index 000000000..9ab59c645--- /dev/null+++ b/src/web/src/test/e2e-ui/30-sheet-footer-geometry.spec.ts@@ -0,0 +1,80 @@+import { test, expect } from "./_fixtures/case-fixture"+import { composerEditable, gotoAfterUserWsAuth } from "./_fixtures/actions"+import { tid } from "./_fixtures/testids"+import { connectMachine } from "./_fixtures/community-machine"+import { prepareCase, expectFooterGeometry } from "./_fixtures/bot-profile-audit"++test("CommunitySheet footers keep four consumers horizontal and intrinsic at 390/639/640", async ({ caseActors, caseResources }) => {+ test.setTimeout(180_000)++ const actors = await caseActors(["alice"])+ const { asUser } = actors+ const { seedChannel, seedServer } = actors.seed+ const { cleanupCreatedResources, jsonRequest, pairMachine, createBot, headersFor } = await prepareCase(actors, caseResources)++ const { credential, machineId } = await pairMachine()+ const machine = connectMachine(credential, caseResources, { machineId, headers: headersFor("alice") })+ await machine.opened+ const botName = `Footer bot ${Date.now().toString(36)}`+ await createBot(machineId, botName)+ const { page } = await asUser("alice")+ await gotoAfterUserWsAuth(page, "/c/me/bots")++ const capacity = await jsonRequest<{ ownedCount: number; limit: number }>("alice", "/api/community/bots")+ expect(capacity.ownedCount).toBeLessThan(capacity.limit)+ const create = page.getByRole("button", { name: "Create a bot", exact: true })+ await expect(create).toBeEnabled()+ await create.click()+ for (const width of [390, 639, 640] as const) {+ await expectFooterGeometry(page, "Create a bot", ["Cancel", "Create bot"], width)+ }+ await page.getByRole("dialog", { name: "Create a bot", exact: true })+ .getByRole("button", { name: "Close", exact: true }).click()++ await page.locator('[data-slot="card"]')+ .filter({ has: page.getByText(botName, { exact: true }) })+ .getByRole("button", { name: "Bot actions", exact: true }).click()+ await page.getByRole("menuitem", { name: "Edit", exact: true }).click()+ for (const width of [390, 639, 640] as const) {+ await expectFooterGeometry(page, `Edit ${botName}`, ["Cancel", "Save"], width)+ }+ await page.getByRole("dialog", { name: `Edit ${botName}`, exact: true })+ .getByRole("button", { name: "Close", exact: true }).click()++ await cleanupCreatedResources()+ await gotoAfterUserWsAuth(page, "/c/me/machines")+ await page.getByTestId(tid.machinePairOpen).click()+ for (const width of [390, 639, 640] as const) {+ await expectFooterGeometry(page, "Connect a machine", ["Done"], width)+ }+ await page.getByRole("dialog", { name: "Connect a machine", exact: true })+ .getByRole("button", { name: "Done", exact: true }).click()++ const serverId = await seedServer("alice", `footer-${Date.now()}`)+ const channelId = await seedChannel("alice", serverId, `footer-${Date.now()}`)+ await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)+ const fileName = `footer-oracle-${Date.now()}.md`+ const uploadResponse = page.waitForResponse((response) => (+ response.request().method() === "POST"+ && new URL(response.url()).pathname === `/api/community/channels/${channelId}/attachments`+ ))+ const messageResponse = page.waitForResponse((response) => (+ response.request().method() === "POST"+ && new URL(response.url()).pathname === `/api/community/channels/${channelId}/messages`+ ))+ const editable = composerEditable(page)+ await editable.click()+ await editable.pressSequentially("Attachment footer oracle")+ await page.getByTestId(tid.composerFileInput).setInputFiles({+ name: fileName,+ mimeType: "text/markdown",+ buffer: Buffer.from("# Footer oracle"),+ })+ await page.keyboard.press("Enter")+ expect((await uploadResponse).ok()).toBe(true)+ expect((await messageResponse).status()).toBe(201)+ await page.getByTestId(tid.attachmentCard(fileName)).click()+ for (const width of [390, 639, 640] as const) {+ await expectFooterGeometry(page, fileName, ["Download"], width)+ }+})diff --git a/src/web/src/test/e2e-ui/46-community-loading-geometry-dark.spec.ts b/src/web/src/test/e2e-ui/46-community-loading-geometry-dark.spec.tsdeleted file mode 100644index dda518830..000000000--- a/src/web/src/test/e2e-ui/46-community-loading-geometry-dark.spec.ts+++ /dev/null@@ -1,38 +0,0 @@-import { test } from "./_fixtures/case-fixture"-import {- runDesktopPersistedPendingGeometry,- runNeutralRootGeometry,- runRouteLoadingGeometry,- seedGeometryRoutes,-} from "./_fixtures/community-loading-geometry"--test.describe("community dark loading geometry", () => {- test("dark: neutral root owns two viewport cold restores", async ({ caseActors }, testInfo) => {- const actors = await caseActors(["dave", "bob"])- const { asUser } = actors- const serverIds: string[] = []- await seedGeometryRoutes(serverIds, actors.seed, actors.userId)-- await runNeutralRootGeometry("dark", asUser, testInfo, actors.userId, actors.onCleanup)- })-- test("dark: persisted desktop sidebars keep every pending-frame boundary aligned", async ({ caseActors }) => {- test.setTimeout(240_000)- const actors = await caseActors(["dave", "bob", "geometry"])- const { asUser } = actors- const serverIds: string[] = []- await seedGeometryRoutes(serverIds, actors.seed, actors.userId)-- await runDesktopPersistedPendingGeometry("dark", asUser, actors.onCleanup)- })-- test("dark: 18 route × viewport pending→loaded pairs keep shell CLS at zero", async ({ caseActors }, testInfo) => {- test.setTimeout(600_000)- const actors = await caseActors(["dave", "bob"])- const { asUser } = actors- const serverIds: string[] = []- const routes = await seedGeometryRoutes(serverIds, actors.seed, actors.userId)-- await runRouteLoadingGeometry("dark", routes, asUser, testInfo, actors.onCleanup)- })-})diff --git a/src/web/src/test/e2e-ui/46-community-loading-geometry-light.spec.ts b/src/web/src/test/e2e-ui/46-community-loading-geometry-light.spec.tsdeleted file mode 100644index 41888fe77..000000000--- a/src/web/src/test/e2e-ui/46-community-loading-geometry-light.spec.ts+++ /dev/null@@ -1,38 +0,0 @@-import { test } from "./_fixtures/case-fixture"-import {- runDesktopPersistedPendingGeometry,- runNeutralRootGeometry,- runRouteLoadingGeometry,- seedGeometryRoutes,-} from "./_fixtures/community-loading-geometry"--test.describe("community light loading geometry", () => {- test("light: neutral root owns two viewport cold restores", async ({ caseActors }, testInfo) => {- const actors = await caseActors(["dave", "bob"])- const { asUser } = actors- const serverIds: string[] = []- await seedGeometryRoutes(serverIds, actors.seed, actors.userId)-- await runNeutralRootGeometry("light", asUser, testInfo, actors.userId, actors.onCleanup)- })-- test("light: persisted desktop sidebars keep every pending-frame boundary aligned", async ({ caseActors }) => {- test.setTimeout(360_000)- const actors = await caseActors(["dave", "bob", "geometry"])- const { asUser } = actors- const serverIds: string[] = []- await seedGeometryRoutes(serverIds, actors.seed, actors.userId)-- await runDesktopPersistedPendingGeometry("light", asUser, actors.onCleanup)- })-- test("light: 18 route × viewport pending→loaded pairs keep shell CLS at zero", async ({ caseActors }, testInfo) => {- test.setTimeout(600_000)- const actors = await caseActors(["dave", "bob"])- const { asUser } = actors- const serverIds: string[] = []- const routes = await seedGeometryRoutes(serverIds, actors.seed, actors.userId)-- await runRouteLoadingGeometry("light", routes, asUser, testInfo, actors.onCleanup)- })-})diff --git a/src/web/src/test/e2e-ui/46-dark-neutral-restore.spec.ts b/src/web/src/test/e2e-ui/46-dark-neutral-restore.spec.tsnew file mode 100644index 000000000..a5602d880--- /dev/null+++ b/src/web/src/test/e2e-ui/46-dark-neutral-restore.spec.ts@@ -0,0 +1,13 @@+import { test } from "./_fixtures/case-fixture"+import { runNeutralRootGeometry, seedGeometryRoutes } from "./_fixtures/community-loading-geometry"++test.describe("community dark loading geometry", () => {+test("dark: neutral root owns two viewport cold restores", async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["dave", "bob"])+ const { asUser } = actors+ const serverIds: string[] = []+ await seedGeometryRoutes(serverIds, actors.seed, actors.userId)++ await runNeutralRootGeometry("dark", asUser, testInfo, actors.userId, actors.onCleanup)+ })+})diff --git a/src/web/src/test/e2e-ui/46-dark-persisted-sidebars.spec.ts b/src/web/src/test/e2e-ui/46-dark-persisted-sidebars.spec.tsnew file mode 100644index 000000000..9d1fa0bfa--- /dev/null+++ b/src/web/src/test/e2e-ui/46-dark-persisted-sidebars.spec.ts@@ -0,0 +1,14 @@+import { test } from "./_fixtures/case-fixture"+import { runDesktopPersistedPendingGeometry, seedGeometryRoutes } from "./_fixtures/community-loading-geometry"++test.describe("community dark loading geometry", () => {+test("dark: persisted desktop sidebars keep every pending-frame boundary aligned", async ({ caseActors }) => {+ test.setTimeout(240_000)+ const actors = await caseActors(["dave", "bob", "geometry"])+ const { asUser } = actors+ const serverIds: string[] = []+ await seedGeometryRoutes(serverIds, actors.seed, actors.userId)++ await runDesktopPersistedPendingGeometry("dark", asUser, actors.onCleanup)+ })+})diff --git a/src/web/src/test/e2e-ui/46-dark-route-loading.spec.ts b/src/web/src/test/e2e-ui/46-dark-route-loading.spec.tsnew file mode 100644index 000000000..3f8cc4110--- /dev/null+++ b/src/web/src/test/e2e-ui/46-dark-route-loading.spec.ts@@ -0,0 +1,14 @@+import { test } from "./_fixtures/case-fixture"+import { runRouteLoadingGeometry, seedGeometryRoutes } from "./_fixtures/community-loading-geometry"++test.describe("community dark loading geometry", () => {+test("dark: 18 route × viewport pending→loaded pairs keep shell CLS at zero", async ({ caseActors }, testInfo) => {+ test.setTimeout(600_000)+ const actors = await caseActors(["dave", "bob"])+ const { asUser } = actors+ const serverIds: string[] = []+ const routes = await seedGeometryRoutes(serverIds, actors.seed, actors.userId)++ await runRouteLoadingGeometry("dark", routes, asUser, testInfo, actors.onCleanup)+ })+})diff --git a/src/web/src/test/e2e-ui/46-light-neutral-restore.spec.ts b/src/web/src/test/e2e-ui/46-light-neutral-restore.spec.tsnew file mode 100644index 000000000..28e5a5b8d--- /dev/null+++ b/src/web/src/test/e2e-ui/46-light-neutral-restore.spec.ts@@ -0,0 +1,13 @@+import { test } from "./_fixtures/case-fixture"+import { runNeutralRootGeometry, seedGeometryRoutes } from "./_fixtures/community-loading-geometry"++test.describe("community light loading geometry", () => {+test("light: neutral root owns two viewport cold restores", async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["dave", "bob"])+ const { asUser } = actors+ const serverIds: string[] = []+ await seedGeometryRoutes(serverIds, actors.seed, actors.userId)++ await runNeutralRootGeometry("light", asUser, testInfo, actors.userId, actors.onCleanup)+ })+})diff --git a/src/web/src/test/e2e-ui/46-light-persisted-sidebars.spec.ts b/src/web/src/test/e2e-ui/46-light-persisted-sidebars.spec.tsnew file mode 100644index 000000000..83d1b85eb--- /dev/null+++ b/src/web/src/test/e2e-ui/46-light-persisted-sidebars.spec.ts@@ -0,0 +1,14 @@+import { test } from "./_fixtures/case-fixture"+import { runDesktopPersistedPendingGeometry, seedGeometryRoutes } from "./_fixtures/community-loading-geometry"++test.describe("community light loading geometry", () => {+test("light: persisted desktop sidebars keep every pending-frame boundary aligned", async ({ caseActors }) => {+ test.setTimeout(360_000)+ const actors = await caseActors(["dave", "bob", "geometry"])+ const { asUser } = actors+ const serverIds: string[] = []+ await seedGeometryRoutes(serverIds, actors.seed, actors.userId)++ await runDesktopPersistedPendingGeometry("light", asUser, actors.onCleanup)+ })+})diff --git a/src/web/src/test/e2e-ui/46-light-route-loading.spec.ts b/src/web/src/test/e2e-ui/46-light-route-loading.spec.tsnew file mode 100644index 000000000..535b386a6--- /dev/null+++ b/src/web/src/test/e2e-ui/46-light-route-loading.spec.ts@@ -0,0 +1,14 @@+import { test } from "./_fixtures/case-fixture"+import { runRouteLoadingGeometry, seedGeometryRoutes } from "./_fixtures/community-loading-geometry"++test.describe("community light loading geometry", () => {+test("light: 18 route × viewport pending→loaded pairs keep shell CLS at zero", async ({ caseActors }, testInfo) => {+ test.setTimeout(600_000)+ const actors = await caseActors(["dave", "bob"])+ const { asUser } = actors+ const serverIds: string[] = []+ const routes = await seedGeometryRoutes(serverIds, actors.seed, actors.userId)++ await runRouteLoadingGeometry("light", routes, asUser, testInfo, actors.onCleanup)+ })+})diff --git a/src/web/src/test/e2e-ui/55-composer-resize-anchors.spec.ts b/src/web/src/test/e2e-ui/55-composer-resize-anchors.spec.tsnew file mode 100644index 000000000..6c3594c78--- /dev/null+++ b/src/web/src/test/e2e-ui/55-composer-resize-anchors.spec.ts@@ -0,0 +1,296 @@+import { test, expect } from "./_fixtures/case-fixture"+import { composerEditable, gotoAfterUserWsAuth, sendMessage } from "./_fixtures/actions"+import { communityFrameEvents, proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"+import { beginScrollTraceAnalysis, endScrollTraceAnalysis, installScrollTrace, markScrollTrace, startScrollTrace, summarizeScrollTrace } from "./_fixtures/scroll-trace"+import { tid } from "./_fixtures/testids"+import { expectUniqueSsrCommunityFrame } from "./_fixtures/community-ssr-frame"+import { VIEWPORT, seedProfile, identity, finishAndAttach, establishScrollDistancePrecondition, establishExactPinnedPrecondition, establishTailMessageBelowViewportPrecondition, waitForCommittedGeometry, waitForStableTail, advanceScrollTraceFrame, expectViewportAnchorPreserved, expectResizeAnchorPreserved, expectContinuousResizeAnchorPreserved, expectInFlowMessageGeometry, messageCreateCount, type PostedMessageIdentity, expectMessageCreateIdentity, seedScrollCase, tracedAsUser } from "./_fixtures/message-scroll-characterization"++test.describe("message scroll characterization", () => {+test("normal-flow composer resizes preserve semantic anchors and interaction boundaries", async ({ caseActors }, testInfo) => {+ test.setTimeout(180_000)+ const actors = await caseActors(["alice", "bob", "carol"])+ const asUser = tracedAsUser(actors)+ const { userId } = actors+ const { serverId, composerChannelId, composerProfile } = await seedScrollCase(actors)+ const { seedThread } = actors.seed++ const splitThreadId = await seedThread(+ "alice",+ composerProfile.ids.at(-1)!,+ `scroll split ${Date.now()}`,+ )+ const splitProfile = await seedProfile(actors, splitThreadId, 24, false, "alice")+ const alice = await asUser("alice")+ const bob = await asUser("bob")+ await alice.page.setViewportSize(VIEWPORT)+ await bob.page.setViewportSize(VIEWPORT)+ await installScrollTrace(alice.page)+ const proxy = await proxyCommunityWebSockets(alice.context)+ let mutationPosts = 0+ alice.page.on("request", (request) => {+ const pathname = new URL(request.url()).pathname+ if (+ request.method() === "POST"+ && (pathname.endsWith("/messages") || pathname.includes("/attachments"))+ ) mutationPosts += 1+ })+ await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${composerChannelId}`)+ await gotoAfterUserWsAuth(bob.page, `/c/channels/${serverId}/${composerChannelId}`)+ const scroller = alice.page.getByTestId(tid.messageScroller)+ const editable = composerEditable(alice.page)+ const bobEditable = composerEditable(bob.page)+ await expect(editable).toBeVisible()+ await expect(bobEditable).toBeVisible()+ await startScrollTrace(alice.page, {+ scenario: "composer-exact-pinned-resize-policy",+ identity: identity(composerChannelId),+ estimatedSizes: composerProfile.estimates,+ })++ const composerLines = (prefix: string, count: number) => Array.from(+ { length: count },+ (_, line) => `${prefix} line ${line} ${"content ".repeat(8)}`,+ ).join("\n")++ for (const distance of [0, 2, 100, 300]) {+ await editable.fill(composerLines(`boundary-${distance}`, 8))+ const precondition = distance === 0+ ? await establishExactPinnedPrecondition(scroller, `composer-resize-${distance}`, 0)+ : await establishScrollDistancePrecondition(+ scroller,+ `composer-resize-${distance}`,+ distance,+ )+ await markScrollTrace(alice.page, `composer-resize-${distance}-precondition`, {+ detail: precondition,+ })+ const before = await waitForCommittedGeometry(scroller)+ expectInFlowMessageGeometry(before, `resize-${distance}-before`)++ // Match the user journey that exposed the regression: grow the composer,+ // establish the reading position, then delete the draft. Positioning the+ // scroller before growth misses the browser's shrink-time maxScrollTop clamp.+ await beginScrollTraceAnalysis(alice.page, `composer-shrink-${distance}`)+ await editable.click()+ await alice.page.keyboard.press("ControlOrMeta+A")+ await alice.page.keyboard.press("Backspace")+ await expect(editable).toHaveText("")+ await expect.poll(() => scroller.evaluate((element) => element.clientHeight))+ .toBeGreaterThan(before.clientHeight)+ const shrunk = await waitForCommittedGeometry(scroller)+ expectInFlowMessageGeometry(shrunk, `resize-${distance}-shrunk`)+ expectResizeAnchorPreserved(before, shrunk, distance, `resize-${distance}-shrunk`)+ await endScrollTraceAnalysis(alice.page, `composer-shrink-${distance}`)+ await advanceScrollTraceFrame(scroller)++ await beginScrollTraceAnalysis(alice.page, `composer-grow-${distance}`)+ await editable.fill(composerLines(`boundary-${distance}`, 8))+ await expect.poll(() => scroller.evaluate((element) => element.clientHeight))+ .toBe(before.clientHeight)+ const grown = await waitForCommittedGeometry(scroller)+ expectInFlowMessageGeometry(grown, `resize-${distance}-grown`)+ expectResizeAnchorPreserved(before, grown, distance, `resize-${distance}-grown`)+ await endScrollTraceAnalysis(alice.page, `composer-grow-${distance}`)+ await advanceScrollTraceFrame(scroller)+ }++ await editable.fill("")+ await advanceScrollTraceFrame(scroller)++ const selectionDraft = composerLines("selection-draft", 8)+ await editable.fill(selectionDraft)+ await establishScrollDistancePrecondition(scroller, "selection-footer-away", 300)+ const selectionBase = await waitForCommittedGeometry(scroller)+ const selectionTargetId = selectionBase.firstVisibleId!+ const selectionTarget = alice.page.getByTestId(tid.message(selectionTargetId))+ await beginScrollTraceAnalysis(alice.page, "selection-footer-away")+ await selectionTarget.locator("div.group").first().dispatchEvent("pointerover", {+ pointerId: 1,+ pointerType: "mouse",+ isPrimary: true,+ })+ const selectionAction = alice.page.getByTestId(tid.messageShare(selectionTargetId))+ await expect(selectionAction).toBeVisible()+ await selectionAction.evaluate((button) => (button as HTMLButtonElement).click())+ await expect(alice.page.getByTestId(tid.messageSelectionToolbar)).toBeVisible()+ const conversationFooter = alice.page.locator('[data-slot="community-conversation-footer"]')+ await expect(conversationFooter).toHaveAttribute("data-selection-active", "true")+ await expect(editable).toBeHidden()+ const selectionOpen = await waitForCommittedGeometry(scroller)+ expect(selectionOpen.clientHeight).toBeGreaterThan(selectionBase.clientHeight)+ expect(selectionOpen.scrollHeight).toBe(selectionBase.scrollHeight)+ expectViewportAnchorPreserved(selectionBase, selectionOpen, "selection-open-away")+ await expect(editable).toContainText("selection-draft line 0")+ await alice.page.getByRole("button", { name: "Cancel message selection" }).click()+ await expect(alice.page.getByTestId(tid.messageSelectionToolbar)).toHaveCount(0)+ await expect(conversationFooter).toHaveAttribute("data-selection-active", "false")+ await expect(editable).toBeVisible()+ const selectionClosed = await waitForCommittedGeometry(scroller)+ expect(selectionClosed.clientHeight).toBe(selectionBase.clientHeight)+ expect(selectionClosed.scrollHeight).toBe(selectionBase.scrollHeight)+ expectViewportAnchorPreserved(selectionBase, selectionClosed, "selection-closed-away")+ await expect(editable).toContainText("selection-draft line 7")+ await editable.fill("")+ await endScrollTraceAnalysis(alice.page, "selection-footer-away")+ await advanceScrollTraceFrame(scroller)++ await establishExactPinnedPrecondition(scroller, "reply-resize-pinned", 0)+ const replyBase = await waitForCommittedGeometry(scroller)+ await beginScrollTraceAnalysis(alice.page, "reply-banner-pinned")+ const replyTarget = alice.page.getByTestId(tid.message(composerProfile.ids.at(-1)!))+ await expect(replyTarget).toBeVisible()+ await replyTarget.locator("div.group").first().dispatchEvent("pointerover", {+ pointerId: 1,+ pointerType: "mouse",+ isPrimary: true,+ })+ const replyButton = replyTarget.getByRole("button", { name: "Reply", exact: true })+ await expect(replyButton).toBeVisible()+ await expect(replyButton).toBeInViewport()+ expect((await waitForCommittedGeometry(scroller)).distanceToEnd).toBeLessThanOrEqual(1)+ await replyButton.evaluate((button) => (button as HTMLButtonElement).click())+ await expect(alice.page.locator('[data-slot="composer-reply-preview"]')).toBeVisible()+ const replyOpen = await waitForCommittedGeometry(scroller)+ expect(replyOpen.clientHeight).toBeLessThan(replyBase.clientHeight)+ expect(replyOpen.distanceToEnd).toBeLessThanOrEqual(1)+ expectResizeAnchorPreserved(replyBase, replyOpen, 0, "reply-open")+ expectInFlowMessageGeometry(replyOpen, "reply-open")+ await alice.page.getByRole("button", { name: "Cancel reply" }).click()+ await expect(alice.page.locator('[data-slot="composer-reply-preview"]')).toHaveCount(0)+ const replyClosed = await waitForCommittedGeometry(scroller)+ expect(replyClosed.clientHeight).toBe(replyBase.clientHeight)+ expect(replyClosed.distanceToEnd).toBeLessThanOrEqual(1)+ expectResizeAnchorPreserved(replyBase, replyClosed, 0, "reply-closed")+ await endScrollTraceAnalysis(alice.page, "reply-banner-pinned")+ await advanceScrollTraceFrame(scroller)++ await establishTailMessageBelowViewportPrecondition(+ scroller,+ "attachment-resize-away",+ composerProfile.ids.at(-1)!,+ )+ const attachmentBase = await waitForCommittedGeometry(scroller)+ await beginScrollTraceAnalysis(alice.page, "attachment-chip-away")+ await alice.page.getByTestId(tid.composerFileInput).setInputFiles({+ name: "geometry-only.txt",+ mimeType: "text/plain",+ buffer: Buffer.from("geometry only"),+ })+ await expect(alice.page.getByText("geometry-only.txt", { exact: true })).toBeVisible()+ const attachmentOpen = await waitForCommittedGeometry(scroller)+ expect(attachmentOpen.clientHeight).toBeLessThan(attachmentBase.clientHeight)+ expectViewportAnchorPreserved(attachmentBase, attachmentOpen, "attachment-open-away")+ expectInFlowMessageGeometry(attachmentOpen, "attachment-open-away")+ await alice.page.getByRole("button", { name: "Remove file" }).click()+ await expect(alice.page.getByText("geometry-only.txt", { exact: true })).toHaveCount(0)+ const attachmentClosed = await waitForCommittedGeometry(scroller)+ expect(attachmentClosed.clientHeight).toBe(attachmentBase.clientHeight)+ expectViewportAnchorPreserved(attachmentBase, attachmentClosed, "attachment-closed-away")+ await endScrollTraceAnalysis(alice.page, "attachment-chip-away")+ await advanceScrollTraceFrame(scroller)++ await establishScrollDistancePrecondition(scroller, "typing-rail-away", 101)+ const typingBase = await waitForCommittedGeometry(scroller)+ await beginScrollTraceAnalysis(alice.page, "typing-rail-away")+ await bobEditable.fill("typing rail geometry")+ await expect(alice.page.getByTestId(tid.typingIndicator)).toBeVisible({ timeout: 20_000 })+ const typingOpen = await waitForCommittedGeometry(scroller)+ expect(typingOpen.clientHeight).toBe(typingBase.clientHeight)+ expectViewportAnchorPreserved(typingBase, typingOpen, "typing-rail-away")+ expect(typingOpen.railRect, "typing-rail-away: scoped Footer rail exists").not.toBeNull()+ expectInFlowMessageGeometry(typingOpen, "typing-rail-away")+ await bobEditable.fill("")+ await endScrollTraceAnalysis(alice.page, "typing-rail-away")+ await advanceScrollTraceFrame(scroller)++ const trace = await finishAndAttach(alice.page, testInfo)+ const resizeSegments = new Map(+ summarizeScrollTrace(trace).analysisSegments.map((segment) => [segment.name, segment]),+ )+ for (const distance of [0, 2, 100, 300]) {+ const grow = resizeSegments.get(`composer-grow-${distance}`)+ const shrink = resizeSegments.get(`composer-shrink-${distance}`)+ expect(grow, `missing composer-grow-${distance}`).toBeDefined()+ expect(shrink, `missing composer-shrink-${distance}`).toBeDefined()+ expectContinuousResizeAnchorPreserved(trace, `composer-grow-${distance}`, distance)+ expectContinuousResizeAnchorPreserved(trace, `composer-shrink-${distance}`, distance)+ }+ expect(resizeSegments.get("typing-rail-away")?.writerCount).toBe(0)+ expectContinuousResizeAnchorPreserved(trace, "selection-footer-away", 300)+ expect(mutationPosts).toBe(0)+ expect(proxy.frames.flatMap(communityFrameEvents).filter((event) =>+ event.type === "community:message.create" && event.channelId === composerChannelId)).toHaveLength(0)++ await alice.page.goto(`/c/channels/${serverId}/${splitThreadId}`, { waitUntil: "commit" })+ const frame = await expectUniqueSsrCommunityFrame(alice.page)+ const split = frame.getByTestId(tid.threadSplit)+ await expect(split).toHaveCount(1)+ await expect(split).toHaveAttribute("data-layout", "split", { timeout: 30_000 })+ const parentPanel = split.getByTestId(tid.threadSplitParent)+ const threadPanel = split.getByTestId(tid.threadSplitPanel)+ const parentSurface = parentPanel.locator('[data-slot="community-conversation-surface"]')+ const threadSurface = threadPanel.locator('[data-slot="community-conversation-surface"]')+ await expect(parentSurface).toHaveAttribute("data-channel-id", composerChannelId)+ await expect(threadSurface).toHaveAttribute("data-channel-id", splitThreadId)+ await expect(parentSurface).toHaveCount(1)+ await expect(threadSurface).toHaveCount(1)++ const parentEditable = composerEditable(alice.page, parentPanel)+ const threadEditable = composerEditable(alice.page, threadPanel)+ await parentEditable.fill(composerLines("split-parent", 2))+ await threadEditable.fill(composerLines("split-thread", 6))+ const parentScroller = parentPanel.getByTestId(tid.messageScroller)+ const threadScroller = threadPanel.getByTestId(tid.messageScroller)+ await establishTailMessageBelowViewportPrecondition(+ parentScroller,+ "split-parent-away",+ composerProfile.ids.at(-1)!,+ )+ await establishTailMessageBelowViewportPrecondition(+ threadScroller,+ "split-thread-away",+ splitProfile.ids.at(-1)!,+ )+ const parentGeometry = await waitForCommittedGeometry(parentScroller)+ const threadGeometry = await waitForCommittedGeometry(threadScroller)+ const parentComposerBox = await parentSurface+ .locator('[data-slot="community-conversation-footer"]')+ .boundingBox()+ const threadComposerBox = await threadSurface+ .locator('[data-slot="community-conversation-footer"]')+ .boundingBox()+ expect(parentGeometry.surfaceChannelId).toBe(composerChannelId)+ expect(threadGeometry.surfaceChannelId).toBe(splitThreadId)+ expect(parentComposerBox).not.toBeNull()+ expect(threadComposerBox).not.toBeNull()+ expect(Math.abs(parentGeometry.composerRect!.top - parentComposerBox!.y)).toBeLessThanOrEqual(1)+ expect(Math.abs(threadGeometry.composerRect!.top - threadComposerBox!.y)).toBeLessThanOrEqual(1)+ expect(threadGeometry.composerRect!.top).not.toBe(parentGeometry.composerRect!.top)+ expectInFlowMessageGeometry(parentGeometry, "split-parent")+ expectInFlowMessageGeometry(threadGeometry, "split-thread")+ expect(mutationPosts).toBe(0)++ await parentEditable.fill("")+ await threadEditable.fill("")+ const parentBefore = await waitForCommittedGeometry(parentScroller)+ const content = `thread local acceptance ${Date.now()}`+ const post = alice.page.waitForResponse(response => response.request().method() === "POST"+ && new URL(response.url()).pathname === `/api/community/channels/${splitThreadId}/messages`+ && response.request().postDataJSON().content === content)+ await sendMessage(alice.page, content, threadPanel)+ const response = await post+ expect(response.status()).toBe(201)+ const nonce = response.request().postDataJSON().nonce as string+ expect(nonce.length).toBeGreaterThan(0)+ const result = await response.json() as { message: PostedMessageIdentity }+ expect(result.message).toMatchObject({ authorId: userId("alice"), channelId: splitThreadId, content })+ await expect.poll(() => messageCreateCount(proxy.frames, splitThreadId, content)).toBe(1)+ await expectMessageCreateIdentity(proxy.frames, splitThreadId, result.message, nonce)+ await expect(threadPanel.getByTestId(tid.message(result.message.id))).toBeVisible()+ await expect(threadPanel.getByText(content, { exact: true })).toHaveCount(1)+ await waitForStableTail(threadScroller, "thread-local-submit-ack")+ const parentAfter = await waitForCommittedGeometry(parentScroller)+ expectViewportAnchorPreserved(parentBefore, parentAfter, "thread-local-submit-parent")+ })+})diff --git a/src/web/src/test/e2e-ui/55-dm-composer-viewport.spec.ts b/src/web/src/test/e2e-ui/55-dm-composer-viewport.spec.tsnew file mode 100644index 000000000..2dc040b7b--- /dev/null+++ b/src/web/src/test/e2e-ui/55-dm-composer-viewport.spec.ts@@ -0,0 +1,129 @@+import { test, expect } from "./_fixtures/case-fixture"+import { composerEditable, gotoAfterUserWsAuth, sendMessage } from "./_fixtures/actions"+import { communityFrameEvents, proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"+import { beginScrollTraceAnalysis, endScrollTraceAnalysis, installScrollTrace, markScrollTrace, startScrollTrace, summarizeScrollTrace } from "./_fixtures/scroll-trace"+import { tid } from "./_fixtures/testids"+import { VIEWPORT, seedDmProfile, identity, finishAndAttach, establishScrollDistancePrecondition, establishExactPinnedPrecondition, waitForCommittedGeometry, waitForStableTail, advanceScrollTraceFrame, expectResizeAnchorPreserved, expectContinuousResizeAnchorPreserved, expectInFlowMessageGeometry, messageCreateCount, type PostedMessageIdentity, expectMessageCreateIdentity, tracedAsUser } from "./_fixtures/message-scroll-characterization"++test.describe("message scroll characterization", () => {+test("DM composer clear preserves pinned and away viewport geometry", async ({ caseActors }, testInfo) => {+ test.setTimeout(180_000)+ const actors = await caseActors(["alice", "bob", "carol"])+ const asUser = tracedAsUser(actors)+ const { userId } = actors+ const composerDmId = await actors.seed.seedDm("alice", userId("bob"))+ const composerDmProfile = await seedDmProfile(actors, composerDmId, 36)++ const alice = await asUser("alice")+ await alice.page.setViewportSize(VIEWPORT)+ await installScrollTrace(alice.page)+ const proxy = await proxyCommunityWebSockets(alice.context)+ let messagePosts = 0+ alice.page.on("request", (request) => {+ if (+ request.method() === "POST"+ && new URL(request.url()).pathname === `/api/community/channels/${composerDmId}/messages`+ ) messagePosts += 1+ })+ await gotoAfterUserWsAuth(alice.page, `/c/me/${composerDmId}`)+ const scroller = alice.page.getByTestId(tid.messageScroller)+ const editable = composerEditable(alice.page)+ await expect(editable).toBeVisible()+ await expect(alice.page.getByTestId(tid.message(composerDmProfile.ids.at(-1)!)))+ .toBeVisible({ timeout: 30_000 })+ await scroller.evaluate((element) => {+ element.scrollTop = element.scrollHeight+ element.dispatchEvent(new Event("scroll"))+ })+ const tailGeometry = await alice.page.evaluate(({ scrollerId, messageId }) => {+ const scrollerElement = document.querySelector<HTMLElement>(+ `[data-testid="${scrollerId}"]`,+ )!+ const content = scrollerElement.querySelector<HTMLElement>("[data-message-list-content]")!+ const finalMessage = document.querySelector<HTMLElement>(`[data-testid="${messageId}"]`)!+ const composer = document.querySelector<HTMLElement>('[data-onboarding-target="dm-composer"]')!+ return {+ paddingBottom: Number.parseFloat(getComputedStyle(content).paddingBottom),+ tailGap: scrollerElement.getBoundingClientRect().bottom+ - finalMessage.getBoundingClientRect().bottom,+ scrollerBottom: scrollerElement.getBoundingClientRect().bottom,+ composerTop: composer.getBoundingClientRect().top,+ }+ }, {+ scrollerId: tid.messageScroller,+ messageId: tid.message(composerDmProfile.ids.at(-1)!),+ })+ expect(tailGeometry.paddingBottom).toBe(0)+ expect(tailGeometry.tailGap).toBeGreaterThanOrEqual(39)+ expect(tailGeometry.tailGap).toBeLessThanOrEqual(41)+ expect(tailGeometry.scrollerBottom).toBeLessThanOrEqual(tailGeometry.composerTop + 1)+ await startScrollTrace(alice.page, {+ scenario: "dm-composer-clear-viewport",+ identity: identity(composerDmId),+ estimatedSizes: composerDmProfile.estimates,+ })++ const composerLines = (prefix: string) => Array.from(+ { length: 6 },+ (_, line) => `${prefix} line ${line} ${"content ".repeat(8)}`,+ ).join("\n")++ for (const distance of [0, 2, 100, 300]) {+ await editable.fill(composerLines(`dm-${distance}`))+ const precondition = distance === 0+ ? await establishExactPinnedPrecondition(scroller, `dm-composer-${distance}`, 0)+ : await establishScrollDistancePrecondition(scroller, `dm-composer-${distance}`, distance)+ await markScrollTrace(alice.page, `dm-composer-${distance}-precondition`, {+ detail: precondition,+ })+ const before = await waitForCommittedGeometry(scroller)+ expectInFlowMessageGeometry(before, `dm-${distance}-before`)+ expect(before.surfaceChannelId).toBe(composerDmId)++ await beginScrollTraceAnalysis(alice.page, `dm-composer-shrink-${distance}`)+ await editable.click()+ await alice.page.keyboard.press("ControlOrMeta+A")+ await alice.page.keyboard.press("Backspace")+ await expect(editable).toHaveText("")+ await expect.poll(() => scroller.evaluate((element) => element.clientHeight))+ .toBeGreaterThan(before.clientHeight)+ const after = await waitForCommittedGeometry(scroller)+ expectInFlowMessageGeometry(after, `dm-${distance}-after`)+ expectResizeAnchorPreserved(before, after, distance, `dm-${distance}-after`)+ await endScrollTraceAnalysis(alice.page, `dm-composer-shrink-${distance}`)+ await advanceScrollTraceFrame(scroller)+ }++ const trace = await finishAndAttach(alice.page, testInfo)+ const segments = new Map(+ summarizeScrollTrace(trace).analysisSegments.map((segment) => [segment.name, segment]),+ )+ for (const distance of [0, 2, 100, 300]) {+ const segmentName = `dm-composer-shrink-${distance}`+ expect(segments.get(segmentName)).toBeDefined()+ expectContinuousResizeAnchorPreserved(trace, segmentName, distance)+ }+ expect(messagePosts).toBe(0)+ expect(proxy.frames.flatMap(communityFrameEvents).filter((event) =>+ event.type === "community:message.create" && event.channelId === composerDmId)).toHaveLength(0)++ await establishScrollDistancePrecondition(scroller, "dm-local-submit-away", 300)+ const content = `dm local acceptance ${Date.now()}`+ const post = alice.page.waitForResponse(response => response.request().method() === "POST"+ && new URL(response.url()).pathname === `/api/community/channels/${composerDmId}/messages`+ && response.request().postDataJSON().content === content)+ await sendMessage(alice.page, content)+ const response = await post+ expect(response.status()).toBe(201)+ const nonce = response.request().postDataJSON().nonce as string+ expect(nonce.length).toBeGreaterThan(0)+ const result = await response.json() as { message: PostedMessageIdentity }+ expect(result.message).toMatchObject({ authorId: userId("alice"), channelId: composerDmId, content })+ await expect.poll(() => messageCreateCount(proxy.frames, composerDmId, content)).toBe(1)+ await expectMessageCreateIdentity(proxy.frames, composerDmId, result.message, nonce)+ await expect(alice.page.getByTestId(tid.message(result.message.id))).toBeVisible()+ await expect(alice.page.getByText(content, { exact: true })).toHaveCount(1)+ await waitForStableTail(scroller, "dm-local-submit-ack")+ expect(messagePosts).toBe(1)+ })+})diff --git a/src/web/src/test/e2e-ui/55-draft-optimistic-viewport.spec.ts b/src/web/src/test/e2e-ui/55-draft-optimistic-viewport.spec.tsnew file mode 100644index 000000000..94fad171a--- /dev/null+++ b/src/web/src/test/e2e-ui/55-draft-optimistic-viewport.spec.ts@@ -0,0 +1,140 @@+import { test, expect } from "./_fixtures/case-fixture"+import { composerEditable, gotoAfterUserWsAuth, sendMessage } from "./_fixtures/actions"+import { communityFrameEvents, proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"+import { beginScrollTraceAnalysis, endScrollTraceAnalysis, installScrollTrace, markScrollTrace, startScrollTrace } from "./_fixtures/scroll-trace"+import { tid } from "./_fixtures/testids"+import { VIEWPORT, identity, finishAndAttach, establishScrollDistancePrecondition, messageCreateCount, seedScrollCase, tracedAsUser } from "./_fixtures/message-scroll-characterization"++test.describe("message scroll characterization", () => {+test("manual draft clear and optimistic send stay distinct through viewport changes", async ({ caseActors }, testInfo) => {+ test.setTimeout(180_000)+ const actors = await caseActors(["alice", "bob", "carol"])+ const asUser = tracedAsUser(actors)+ const { serverId, composerChannelId, composerProfile } = await seedScrollCase(actors)++ const alice = await asUser("alice")+ await alice.page.setViewportSize(VIEWPORT)+ await installScrollTrace(alice.page)+ const proxy = await proxyCommunityWebSockets(alice.context)+ let messagePosts = 0+ alice.page.on("request", (request) => {+ if (+ request.method() === "POST"+ && new URL(request.url()).pathname === `/api/community/channels/${composerChannelId}/messages`+ ) messagePosts += 1+ })+ await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${composerChannelId}`)+ const scroller = alice.page.getByTestId(tid.messageScroller)+ const editable = composerEditable(alice.page)+ await expect(editable).toBeVisible()+ await startScrollTrace(alice.page, {+ scenario: "composer-clear-send-and-viewport",+ identity: identity(composerChannelId),+ estimatedSizes: composerProfile.estimates,+ })++ const typeSixLines = async (prefix: string) => {+ await editable.click()+ for (let line = 0; line < 6; line += 1) {+ await editable.pressSequentially(`${prefix} line ${line} ${"content ".repeat(8)}`)+ if (line < 5) await alice.page.keyboard.press("Shift+Enter")+ }+ }+ await markScrollTrace(alice.page, "stimulus:prepare-pinned-draft")+ await typeSixLines("pinned")+ const pinnedDraftPrecondition = await establishScrollDistancePrecondition(+ scroller,+ "manual-delete-pinned",+ 0,+ )+ await markScrollTrace(alice.page, "manual-delete-pinned-precondition", {+ detail: pinnedDraftPrecondition,+ })+ await beginScrollTraceAnalysis(alice.page, "manual-delete-pinned")+ await markScrollTrace(alice.page, "manual-delete-pinned")+ await alice.page.keyboard.press("ControlOrMeta+A")+ await alice.page.keyboard.press("Backspace")+ await expect(alice.page.getByTestId(tid.composerInput)).toHaveText("")+ expect(messagePosts).toBe(0)+ expect(proxy.frames.flatMap(communityFrameEvents).filter((event) =>+ event.type === "community:message.create" && event.channelId === composerChannelId)).toHaveLength(0)+ await endScrollTraceAnalysis(alice.page, "manual-delete-pinned")++ await markScrollTrace(alice.page, "stimulus:prepare-away-draft")+ await typeSixLines("away")+ const awayDraftPrecondition = await establishScrollDistancePrecondition(+ scroller,+ "manual-delete-away",+ 300,+ )+ await markScrollTrace(alice.page, "manual-delete-away-precondition", {+ detail: awayDraftPrecondition,+ })+ await beginScrollTraceAnalysis(alice.page, "manual-delete-away")+ await markScrollTrace(alice.page, "manual-delete-away")+ await alice.page.keyboard.press("ControlOrMeta+A")+ await alice.page.keyboard.press("Backspace")+ await expect(alice.page.getByTestId(tid.composerInput)).toHaveText("")+ expect(messagePosts).toBe(0)+ await endScrollTraceAnalysis(alice.page, "manual-delete-away")++ await markScrollTrace(alice.page, "stimulus:pin-for-send")+ const pinnedSendPrecondition = await establishScrollDistancePrecondition(+ scroller,+ "optimistic-send-pinned",+ 0,+ )+ await markScrollTrace(alice.page, "optimistic-send-pinned-precondition", {+ detail: pinnedSendPrecondition,+ })+ await beginScrollTraceAnalysis(alice.page, "optimistic-send-pinned", {+ dataTransitionSource: "optimistic-send",+ })+ const pinnedSend = `optimistic pinned ${Date.now()}`+ await markScrollTrace(alice.page, "optimistic-pinned", { dataTransitionSource: "optimistic-send" })+ await sendMessage(alice.page, pinnedSend)+ await expect(alice.page.getByText(pinnedSend, { exact: true })).toHaveCount(1)+ await markScrollTrace(alice.page, "post-ack-pinned", { dataTransitionSource: "post-ack" })+ await expect.poll(() => messageCreateCount(proxy.frames, composerChannelId, pinnedSend)).toBe(1)+ await markScrollTrace(alice.page, "ws-dedupe-pinned", { dataTransitionSource: "ws-dedupe" })+ await endScrollTraceAnalysis(alice.page, "optimistic-send-pinned")++ await markScrollTrace(alice.page, "stimulus:send-away")+ const awaySendPrecondition = await establishScrollDistancePrecondition(+ scroller,+ "optimistic-send-away",+ 300,+ )+ await markScrollTrace(alice.page, "optimistic-send-away-precondition", {+ detail: awaySendPrecondition,+ })+ await beginScrollTraceAnalysis(alice.page, "optimistic-send-away", {+ dataTransitionSource: "optimistic-send",+ })+ const awaySend = `optimistic away ${Date.now()}`+ await markScrollTrace(alice.page, "optimistic-away", { dataTransitionSource: "optimistic-send" })+ await sendMessage(alice.page, awaySend)+ await expect(alice.page.getByText(awaySend, { exact: true })).toHaveCount(1)+ await markScrollTrace(alice.page, "post-ack-away", { dataTransitionSource: "post-ack" })+ await expect.poll(() => messageCreateCount(proxy.frames, composerChannelId, awaySend)).toBe(1)+ await markScrollTrace(alice.page, "ws-dedupe-away", { dataTransitionSource: "ws-dedupe" })+ await expect.poll(() => scroller.evaluate((element) =>+ Math.max(0, element.scrollHeight - element.clientHeight - element.scrollTop))).toBeLessThanOrEqual(1)+ expect(messagePosts).toBe(2)+ await endScrollTraceAnalysis(alice.page, "optimistic-send-away")++ await beginScrollTraceAnalysis(alice.page, "viewport-keyboard-profile")+ await markScrollTrace(alice.page, "stimulus:viewport-keyboard-profile")+ await alice.page.setViewportSize({ width: 1280, height: 560 })+ await alice.page.setViewportSize(VIEWPORT)+ await endScrollTraceAnalysis(alice.page, "viewport-keyboard-profile")+ const trace = await finishAndAttach(alice.page, testInfo)+ expect(trace.marks.filter((mark) =>+ ["optimistic-pinned", "optimistic-away"].includes(mark.name)+ && mark.dataTransitionSource === "optimistic-send")).toHaveLength(2)+ expect(trace.marks.filter((mark) => mark.dataTransitionSource === "post-ack")).toHaveLength(2)+ expect(trace.marks.filter((mark) => mark.dataTransitionSource === "ws-dedupe")).toHaveLength(2)+ expect(messageCreateCount(proxy.frames, composerChannelId, pinnedSend)).toBe(1)+ expect(messageCreateCount(proxy.frames, composerChannelId, awaySend)).toBe(1)+ })+})diff --git a/src/web/src/test/e2e-ui/55-history-local-remote-owners.spec.ts b/src/web/src/test/e2e-ui/55-history-local-remote-owners.spec.tsnew file mode 100644index 000000000..5f380dc9f--- /dev/null+++ b/src/web/src/test/e2e-ui/55-history-local-remote-owners.spec.ts@@ -0,0 +1,144 @@+import { communityFixtureFetch } from "./_fixtures/business-contract"+import type { CommunityConversationEntryRead } from "@alook/shared"+import { test, expect } from "./_fixtures/case-fixture"+import { gotoAfterUserWsAuth, sendMessage } from "./_fixtures/actions"+import { communityFrameEvents, proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"+import { beginScrollTraceAnalysis, endScrollTraceAnalysis, installScrollTrace, markScrollTrace, startScrollTrace, startAnalyzedScrollTrace } from "./_fixtures/scroll-trace"+import { tid } from "./_fixtures/testids"+import { WEB_URL } from "./_setup/paths"+import { expectPublicCommunityDocument } from "./_fixtures/community-ssr-frame"+import { VIEWPORT, holdNextRequest, seedProfile, identity, finishAndAttach, establishScrollDistancePrecondition, waitForCommittedGeometry, waitForStableTail, messageCreateCount, type PostedMessageIdentity, expectMessageCreateIdentity, seedScrollServer, tracedAsUser } from "./_fixtures/message-scroll-characterization"++test.describe("message scroll characterization", () => {+test("local history submission and passive remote append use distinct owners", async ({ caseActors }, testInfo) => {+ test.setTimeout(120_000)+ const actors = await caseActors(["alice", "bob", "carol"])+ const asUser = tracedAsUser(actors)+ const { userId, sessionCookie } = actors+ const serverId = await seedScrollServer(actors)+ const { seedChannel } = actors.seed+ const channelId = await seedChannel("alice", serverId, `scroll-passive-threshold-${Date.now()}`)+ await seedProfile(actors, channelId, 130, false, "rotate", 18)+ const alice = await asUser("alice")+ await alice.page.setViewportSize(VIEWPORT)+ await installScrollTrace(alice.page)+ const proxy = await proxyCommunityWebSockets(alice.context)+ let composerPosts = 0+ alice.page.on("request", request => {+ if (request.method() === "POST" && new URL(request.url()).pathname === `/api/community/channels/${channelId}/messages`) composerPosts += 1+ })+ const documentResponse = alice.page.waitForResponse(response => response.request().isNavigationRequest()+ && new URL(response.url()).pathname === `/c/channels/${serverId}/${channelId}`)+ const anchorResponse = alice.page.waitForResponse(response => {+ const url = new URL(response.url())+ return response.request().method() === "GET" && url.pathname === `/api/community/channels/${channelId}/messages` && url.searchParams.get("entry") === "1"+ })+ await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${channelId}`)+ const scroller = alice.page.getByTestId(tid.messageScroller)+ await expect(scroller.locator('[data-message-list-content]')).toHaveAttribute("data-read-position-ready", "true")+ const anchored = await anchorResponse+ expect(anchored.status()).toBe(200)+ expectPublicCommunityDocument(await (await documentResponse).text())+ const anchorPage = await anchored.json() as CommunityConversationEntryRead+ expect(anchorPage.selection.reason).toBe("read_pointer")+ expect(anchorPage.page.hasMoreNewer).toBe(true)+ let newestGets = 0+ alice.page.on("request", request => {+ const url = new URL(request.url())+ if (request.method() === "GET" && url.pathname === `/api/community/channels/${channelId}/messages` && url.search === "") newestGets += 1+ })+ const newest = await holdNextRequest(actors, alice.page, `**/api/community/channels/${channelId}/messages**`, url => url.search === "")+ await startScrollTrace(alice.page, {+ scenario: "local-history-submission",+ identity: identity(channelId),+ })+ await beginScrollTraceAnalysis(alice.page, "local-history-submission", {+ dataTransitionSource: "optimistic-send",+ commandDirection: "forward",+ })+ let localTracePending = true+ const attachLocalTrace = async () => {+ if (!localTracePending) return+ localTracePending = false+ await endScrollTraceAnalysis(alice.page, "local-history-submission")+ await finishAndAttach(alice.page, testInfo)+ }+ // The case owner preserves the body error and captures before page teardown.+ actors.onCleanup(attachLocalTrace)+ const localContent = `local history submission ${Date.now()}`+ const localPost = alice.page.waitForResponse(response => response.request().method() === "POST"+ && new URL(response.url()).pathname === `/api/community/channels/${channelId}/messages`+ && response.request().postDataJSON().content === localContent)+ try {+ await sendMessage(alice.page, localContent)+ await newest.matched+ newest.release()+ const response = await localPost+ expect(response.status()).toBe(201)+ const nonce = response.request().postDataJSON().nonce as string+ expect(nonce.length).toBeGreaterThan(0)+ const result = await response.json() as { message: PostedMessageIdentity }+ expect(result.message).toMatchObject({ authorId: userId("alice"), channelId, content: localContent })+ await expect.poll(() => messageCreateCount(proxy.frames, channelId, localContent)).toBe(1)+ await expectMessageCreateIdentity(proxy.frames, channelId, result.message, nonce)+ await expect(alice.page.getByTestId(tid.message(result.message.id))).toBeVisible()+ await expect(alice.page.getByText(localContent, { exact: true })).toHaveCount(1)+ await waitForStableTail(scroller, "local-history-submission-ack")+ expect(newestGets).toBe(1)+ expect(composerPosts).toBe(1)+ } finally {+ await newest.dispose()+ }+ await attachLocalTrace()+ const finishPassiveTrace = await startAnalyzedScrollTrace(alice.page, {+ scenario: "passive-append-position-admission",+ identity: identity(channelId),+ dataTransitionSource: "overlay-ws",+ })+ const attachPassiveTrace = async () => {+ await finishPassiveTrace(testInfo)+ }+ actors.onCleanup(attachPassiveTrace)+ for (const author of ["bob", "alice"] as const) {+ for (const distance of [0, 1, 2, 20, 100, 101]) {+ await markScrollTrace(alice.page, `${author}-${distance}-admission-start`)+ await establishScrollDistancePrecondition(scroller, `${author}-${distance}`, distance, 0.01)+ const before = await waitForCommittedGeometry(scroller)+ expect(before.firstVisibleId).not.toBeNull()+ expect(Math.abs(before.distanceToEnd - distance)).toBeLessThanOrEqual(0.01)+ await markScrollTrace(alice.page, `${author}-${distance}-precondition`, { detail: before })+ const nonce = `scroll186_${author}_${distance}_${Date.now()}`+ const content = `passive ${author} at ${distance} ${nonce}`+ const response = await communityFixtureFetch(`${WEB_URL}/api/community/channels/${channelId}/messages`, {+ method: "POST",+ headers: { Cookie: sessionCookie(author), "Content-Type": "application/json", Origin: WEB_URL },+ body: JSON.stringify({ content, nonce }),+ })+ expect(response.status).toBe(201)+ const result = await response.json() as { message: PostedMessageIdentity }+ expect(result.message).toMatchObject({ authorId: userId(author), channelId, content })+ await expect.poll(() => proxy.frames.filter(frame => communityFrameEvents(frame).some(event =>+ event.type === "community:message.create" && event.channelId === channelId && event.message?.id === result.message.id,+ )).length).toBe(1)+ await expectMessageCreateIdentity(proxy.frames, channelId, result.message, nonce)+ if (distance <= 1) {+ await expect(alice.page.getByTestId(tid.message(result.message.id))).toBeVisible()+ await waitForStableTail(scroller, `${author}-${distance}-received`)+ } else {+ await alice.page.waitForTimeout(250)+ const bodyOffset = await scroller.locator(`[data-msg-id="${before.firstVisibleId}"]`).evaluate((element, scrollerTestId) => {+ const root = element.closest<HTMLElement>(`[data-testid="${scrollerTestId}"]`)!+ return element.getBoundingClientRect().top - root.getBoundingClientRect().top+ }, tid.messageScroller)+ expect(Math.abs(bodyOffset - before.firstVisibleOffset!)).toBeLessThanOrEqual(1)+ const after = await waitForCommittedGeometry(scroller)+ expect(Math.abs(after.scrollTop - before.scrollTop)).toBeLessThanOrEqual(1)+ expect(after.distanceToEnd).toBeGreaterThan(distance)+ }+ expect(composerPosts).toBe(1)+ }+ }+ expect(newestGets).toBe(1)+ await attachPassiveTrace()+ })+})diff --git a/src/web/src/test/e2e-ui/55-jump-peer-tail-follow.spec.ts b/src/web/src/test/e2e-ui/55-jump-peer-tail-follow.spec.tsnew file mode 100644index 000000000..5f78732c4--- /dev/null+++ b/src/web/src/test/e2e-ui/55-jump-peer-tail-follow.spec.ts@@ -0,0 +1,35 @@+import { test, expect } from "./_fixtures/case-fixture"+import { gotoAfterUserWsAuth } from "./_fixtures/actions"+import { proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"+import { tid } from "./_fixtures/testids"+import { VIEWPORT, seedProfile, establishExactPinnedPrecondition, waitForStableTail, messageCreateCount, seedScrollServer } from "./_fixtures/message-scroll-characterization"++test.describe("message scroll characterization", () => {+test("jumping to present lets the next peer message follow the tail", async ({ caseActors }) => {+ test.setTimeout(180_000)+ const actors = await caseActors(["alice", "bob", "carol"])+ const serverId = await seedScrollServer(actors)+ const channelId = await actors.seed.seedChannel("alice", serverId, `scroll-upward-${Date.now()}`)+ const profile = await seedProfile(actors, channelId, 72, false, "rotate", 23)+ const alice = await actors.asUser("alice")+ await alice.page.setViewportSize(VIEWPORT)+ const proxy = await proxyCommunityWebSockets(alice.context)+ await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${channelId}`)+ const scroller = alice.page.getByTestId(tid.messageScroller)+ await expect(scroller).toBeVisible({ timeout: 30_000 })+ const present = alice.page.getByTestId(tid.scrollToPresent)+ await expect(present).toBeVisible({ timeout: 30_000 })+ await present.click()+ await expect(alice.page.getByTestId(tid.message(profile.ids.at(-1)!)))+ .toBeVisible({ timeout: 30_000 })+ await expect(present).toHaveCount(0)+ await waitForStableTail(scroller, "remote-fixture-tail")+ await establishExactPinnedPrecondition(scroller, "remote-pinned", 0)+ const pinnedBody = `remote pinned ${Date.now()}`+ const pinnedId = await actors.seed.seedMessage("bob", channelId, pinnedBody)+ await expect.poll(() => messageCreateCount(proxy.frames, channelId, pinnedBody)).toBe(1)+ await expect(alice.page.getByTestId(tid.message(pinnedId))).toBeVisible({ timeout: 20_000 })+ await expect.poll(() => scroller.evaluate((element) =>+ Math.max(0, element.scrollHeight - element.clientHeight - element.scrollTop))).toBeLessThanOrEqual(1)+ })+})diff --git a/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts b/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.tsdeleted file mode 100644index 99d73381d..000000000--- a/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts+++ /dev/null@@ -1,1745 +0,0 @@-import { communityFixtureFetch, confirmCommunityFixtureApiResponse, CURRENT_COMMUNITY_FIXTURE_HEADERS } from "./_fixtures/business-contract"-import type { CommunityConversationEntryRead } from "@alook/shared"-import type { Locator, Page, Route, TestInfo } from "@playwright/test"-import { test, expect, type CaseActors } from "./_fixtures/case-fixture"-import { composerEditable, gotoAfterUserWsAuth, sendMessage } from "./_fixtures/actions"-import {- communityFrameEvents,- proxyCommunityWebSockets,-} from "./_fixtures/community-ws-proxy"-import {- abortScrollTrace,- attachScrollTrace,- beginScrollTraceAnalysis,- createScrollTraceIdentity,- endScrollTraceAnalysis,- finishScrollTrace,- installScrollTrace,- installScrollTraceInCurrentDocument,- markScrollTrace,- scrollTraceSelfTest,- startScrollTrace,- startAnalyzedScrollTrace,- summarizeScrollTrace,- type ScrollTraceResult,-} from "./_fixtures/scroll-trace"-import { tid } from "./_fixtures/testids"-import { cancelControlledBackwardGrowth, controlledBackwardGrowth } from "./_fixtures/backward-growth"-import { WEB_URL } from "./_setup/paths"-import { expectUniqueSsrCommunityFrame, expectPublicCommunityDocument } from "./_fixtures/community-ssr-frame"--const VIEWPORT = { width: 1280, height: 800 }--type HeldRequest = {- matched: Promise<URL>- hasMatched: () => boolean- release: () => void- dispose: () => Promise<void>-}--async function holdNextRequest(- actors: CaseActors,- page: Page,- pattern: string,- predicate: (url: URL) => boolean,- options: { required?: boolean } = {},-): Promise<HeldRequest> {- let resolveMatched!: (url: URL) => void- let release!: () => void- let consumed = false- let timeout: ReturnType<typeof setTimeout> | undefined- const matched = new Promise<URL>((resolveValue, reject) => {- resolveMatched = (url) => {- if (timeout) clearTimeout(timeout)- resolveValue(url)- }- if (options.required !== false) timeout = setTimeout(() => reject(new Error(`held request did not match ${pattern}`)), 20_000)- })- const gate = new Promise<void>((resolveValue) => { release = resolveValue })- const handler = async (route: Route) => {- const url = new URL(route.request().url())- if (!consumed && predicate(url)) {- consumed = true- resolveMatched(url)- await gate- }- await route.continue()- }- await page.route(pattern, handler)- const held = {- matched,- hasMatched: () => consumed,- release,- dispose: async () => {- if (timeout) clearTimeout(timeout)- release()- if (!page.isClosed()) await page.unroute(pattern, handler)- },- }- actors.onCleanup(() => held.dispose())- return held-}--function profileContent(index: number): string {- const shape = index % 8- if (shape === 0) return `short row ${index}`- if (shape === 1) return Array.from({ length: 4 }, (_, line) => `row ${index} line ${line}`).join("\n")- if (shape === 2) return Array.from({ length: 12 }, (_, line) => `row ${index} variable line ${line} ${"x".repeat(line * 2)}`).join("\n")- if (shape === 3) return `long-token-${"characterization".repeat(18)}-${index}`- if (shape === 4) return `- list ${index}\n- second item ${"wide ".repeat(12)}\n- third item`- if (shape === 5) return `> quote ${index}\n> ${"quoted content ".repeat(15)}`- if (shape === 6) return `\`\`\`ts\nconst row${index} = ${JSON.stringify("code ".repeat(18))}\n\`\`\``- return `**bold ${index}** ${"wrapping markdown ".repeat(22)}`-}--function estimatePlainMessage(content: string): number {- return 24 + Math.min(Math.max(1, Math.ceil(content.length / 55)) * 20, 400)-}--async function seedResizableHtmlPreview(page: Page, channelId: string) {- const html = '<!doctype html><html><body><div id="content" style="height:160px">Asynchronous content</div><script>addEventListener("message",event=>{if(event.source===parent&&event.data?.type==="scroll-fixture-height"&&Number.isFinite(event.data.height))document.getElementById("content").style.height=event.data.height+"px"})</script></body></html>'- const upload = await confirmCommunityFixtureApiResponse(page.request.post(`/api/community/channels/${channelId}/attachments`, {- headers: CURRENT_COMMUNITY_FIXTURE_HEADERS,- multipart: { file: { name: "scroll-resize.html", mimeType: "text/html", buffer: Buffer.from(html) } },- }))- expect(upload.status()).toBe(200)- const attachmentId = (await upload.json() as { id: string }).id- const posted = await confirmCommunityFixtureApiResponse(page.request.post(`/api/community/channels/${channelId}/messages`, {- headers: CURRENT_COMMUNITY_FIXTURE_HEADERS,- data: { content: `[alook-html-preview](${attachmentId})`, attachments: [attachmentId] },- }))- expect(posted.status()).toBe(201)- const messageId = (await posted.json() as { message: { id: string } }).message.id- return { messageId, attachmentId }-}--async function seedProfile(- actors: CaseActors,- channelId: string,- count: number,- imageAtTail = false,- authors: "rotate" | "alice" = "rotate",- checkpointAt?: number,-): Promise<{ ids: string[]; estimates: Record<string, number> }> {- const { seedMessage } = actors.seed- const ids: string[] = []- const estimates: Record<string, number> = {}- for (let index = 0; index < count; index += 1) {- const content = imageAtTail && index === count - 1- ? `async image row ${index}\n`- : profileContent(index)- const afterCheckpoint = checkpointAt !== undefined && index > checkpointAt- const author = afterCheckpoint- ? index % 2 === 0 ? "bob" : "carol"- : authors === "alice"- ? "alice"- : index % 3 === 0 ? "alice" : index % 3 === 1 ? "bob" : "carol"- const id = await seedMessage(author, channelId, content)- ids.push(id)- estimates[id] = estimatePlainMessage(content)- if (index === checkpointAt) await setReadCheckpoint(actors, channelId, id)- }- return { ids, estimates }-}--async function seedDmProfile(- actors: CaseActors,- dmId: string,- count: number,-): Promise<{ ids: string[]; estimates: Record<string, number> }> {- const { seedDmMessage } = actors.seed- const ids: string[] = []- const estimates: Record<string, number> = {}- for (let index = 0; index < count; index += 1) {- const content = profileContent(index)- const id = await seedDmMessage("alice", dmId, content)- ids.push(id)- estimates[id] = estimatePlainMessage(content)- }- return { ids, estimates }-}--async function setReadCheckpoint(actors: CaseActors, channelId: string, messageId: string): Promise<void> {- const response = await communityFixtureFetch(`${WEB_URL}/api/community/channels/${channelId}/read`, {- method: "PUT",- headers: {- Cookie: actors.sessionCookie("alice"),- "Content-Type": "application/json",- Origin: WEB_URL,- },- body: JSON.stringify({ lastReadMessageId: messageId }),- })- expect(response.ok).toBe(true)-}--function identity(channelId: string, viewport = VIEWPORT) {- return createScrollTraceIdentity({- account: "alice",- channel: channelId,- viewport: { ...viewport, dpr: 1 },- })-}--async function finishAndAttach(page: Page, testInfo: TestInfo): Promise<ScrollTraceResult> {- await markScrollTrace(page, "final-stimulus")- const result = await finishScrollTrace(page)- await attachScrollTrace(testInfo, result)- return result-}--async function establishScrollDistancePrecondition(- scroller: Locator,- label: string,- targetDistanceToEnd: number,- tolerance = 1,-): Promise<{ scrollTop: number; scrollHeight: number; clientHeight: number; distanceToEnd: number }> {- const readGeometry = () => scroller.evaluate((element) => ({- scrollTop: element.scrollTop,- scrollHeight: element.scrollHeight,- clientHeight: element.clientHeight,- distanceToEnd: Math.max(0, element.scrollHeight - element.clientHeight - element.scrollTop),- })).then((geometry) => ({- ...geometry,- targetDistanceToEnd,- atTarget: Math.abs(geometry.distanceToEnd - targetDistanceToEnd) <= tolerance,- }))- const driveToTarget = async () => {- const geometry = await readGeometry()- if (geometry.atTarget) return geometry- await scroller.evaluate((element, targetDistance) => {- element.scrollTop = Math.max(0, element.scrollHeight - element.clientHeight - targetDistance)- element.dispatchEvent(new Event("scroll"))- }, targetDistanceToEnd)- return readGeometry()- }- await scroller.evaluate((element, targetDistance) => {- element.scrollTop = Math.max(0, element.scrollHeight - element.clientHeight - targetDistance)- element.dispatchEvent(new Event("scroll"))- }, targetDistanceToEnd)- await expect.poll(driveToTarget, {- timeout: 20_000,- message: `${label}: scroller must reach ${targetDistanceToEnd}px from end before the stimulus`,- }).toMatchObject({ atTarget: true })- await scroller.evaluate(() => new Promise<void>((resolveValue) => {- requestAnimationFrame(() => requestAnimationFrame(() => resolveValue()))- }))- await expect.poll(driveToTarget, {- timeout: 20_000,- message: `${label}: ${targetDistanceToEnd}px distance must survive two committed RAFs`,- }).toMatchObject({ atTarget: true })- await scroller.evaluate(() => new Promise<void>((resolveValue) => {- requestAnimationFrame(() => requestAnimationFrame(() => resolveValue()))- }))- await expect.poll(readGeometry, {- timeout: 20_000,- message: `${label}: ${targetDistanceToEnd}px distance must remain stable without another write`,- }).toMatchObject({ atTarget: true })- const { atTarget: _atTarget, targetDistanceToEnd: _target, ...geometry } = await readGeometry()- return geometry-}--async function establishExactPinnedPrecondition(- scroller: Locator,- label: string,- targetDistanceToEnd: 0 | 1,-): Promise<{ scrollTop: number; scrollHeight: number; clientHeight: number; distanceToEnd: number }> {- // The resize latch is intentionally monotonic: same-position/clamp events- // at the end cannot recover false. Exercise its one valid recovery path by- // first establishing away geometry, then scrolling forward into <=1px.- await establishScrollDistancePrecondition(scroller, `${label}-away-first`, 8)- return establishScrollDistancePrecondition(scroller, label, targetDistanceToEnd)-}--async function establishTailMessageBelowViewportPrecondition(- scroller: Locator,- label: string,- tailMessageId: string,-): Promise<void> {- const driveTailBelowViewport = () => scroller.evaluate((element, messageId) => {- const root = element as HTMLElement- const rootRect = root.getBoundingClientRect()- const tail = Array.from(root.querySelectorAll<HTMLElement>("[data-msg-id]"))- .find((row) => row.dataset.msgId === messageId)- const distanceToEnd = Math.max(0, root.scrollHeight - root.clientHeight - root.scrollTop)- // A fresh virtualizer may not have mounted the known tail row yet even- // while the viewport is still pinned. Only accept an absent row after an- // actual away position has been established.- const tailBelowViewport = tail- ? tail.getBoundingClientRect().top >= rootRect.bottom - 1- : distanceToEnd >= Math.max(1, root.clientHeight / 2)- if (!tailBelowViewport) {- root.scrollTop = Math.max(0, root.scrollTop - Math.max(400, root.clientHeight / 2))- root.dispatchEvent(new Event("scroll"))- }- return { tailBelowViewport, scrollTop: root.scrollTop, distanceToEnd }- }, tailMessageId)-- await expect.poll(driveTailBelowViewport, {- timeout: 20_000,- message: `${label}: tail row must leave the viewport so the accessory rail is semantically required`,- }).toMatchObject({ tailBelowViewport: true })- await scroller.evaluate(() => new Promise<void>((resolveValue) => {- requestAnimationFrame(() => requestAnimationFrame(() => resolveValue()))- }))-}--async function establishMidHistoryPrecondition(- scroller: Locator,-): Promise<{ scrollTop: number; scrollHeight: number; clientHeight: number; distanceToEnd: number }> {- const readGeometry = () => scroller.evaluate((element) => ({- scrollTop: element.scrollTop,- scrollHeight: element.scrollHeight,- clientHeight: element.clientHeight,- distanceToEnd: Math.max(0, element.scrollHeight - element.clientHeight - element.scrollTop),- }))- await scroller.evaluate((element) => {- element.scrollTop = Math.max(0, (element.scrollHeight - element.clientHeight) / 2)- element.dispatchEvent(new Event("scroll"))- })- await expect.poll(async () => {- const geometry = await readGeometry()- return {- ...geometry,- insideHistory: geometry.scrollTop > 300 && geometry.distanceToEnd > 300,- }- }, {- timeout: 20_000,- message: "remote-mid-history: scroller must be stably away from both boundaries",- }).toMatchObject({ insideHistory: true })- await scroller.evaluate(() => new Promise<void>((resolveValue) => {- requestAnimationFrame(() => requestAnimationFrame(() => resolveValue()))- }))- const before = await readGeometry()- await scroller.evaluate(() => new Promise<void>((resolveValue) => {- requestAnimationFrame(() => requestAnimationFrame(() => resolveValue()))- }))- await expect.poll(async () => {- const geometry = await readGeometry()- return {- ...geometry,- stable: Math.abs(geometry.scrollTop - before.scrollTop) <= 1- && geometry.scrollTop > 300- && geometry.distanceToEnd > 300,- }- }, {- timeout: 20_000,- message: "remote-mid-history: actual geometry must remain stable across committed RAFs",- }).toMatchObject({ stable: true })- return readGeometry()-}--type MessageViewportGeometry = {- scrollTop: number- scrollHeight: number- clientHeight: number- distanceToEnd: number- firstVisibleId: string | null- firstVisibleOffset: number | null- contentPaddingBottom: number- railPosition: string | null- railRect: { top: number; bottom: number; height: number } | null- accessoryPosition: string | null- accessoryRect: { top: number; bottom: number; height: number } | null- railInFooter: boolean- railInScroller: boolean- composerRect: { top: number; bottom: number } | null- surfaceChannelId: string | null- scrollerRect: { top: number; bottom: number }-}--async function readMessageViewportGeometry(scroller: Locator): Promise<MessageViewportGeometry> {- return scroller.evaluate((element, accessoryRailTestId) => {- const root = element as HTMLElement- const rootRect = root.getBoundingClientRect()- const surface = root.closest<HTMLElement>('[data-slot="community-conversation-surface"]')- const firstVisible = Array.from(root.querySelectorAll<HTMLElement>("[data-msg-id]"))- .find((row) => {- const rect = row.getBoundingClientRect()- return rect.bottom > rootRect.top + 1 && rect.top < rootRect.bottom - 1- }) ?? null- const firstRect = firstVisible?.getBoundingClientRect() ?? null- const content = root.querySelector<HTMLElement>("[data-message-list-content]")- const composer = surface?.querySelector<HTMLElement>('[data-slot="community-conversation-footer"]')- const composerRect = composer?.getBoundingClientRect() ?? null- const accessory = composer?.querySelector<HTMLElement>('[data-slot="community-composer-accessory-slot"]')- const accessoryRect = accessory?.getBoundingClientRect() ?? null- const rail = accessory?.querySelector<HTMLElement>(`[data-testid="${accessoryRailTestId}"]`)- const railRect = rail?.getBoundingClientRect() ?? null- return {- scrollTop: root.scrollTop,- scrollHeight: root.scrollHeight,- clientHeight: root.clientHeight,- distanceToEnd: Math.max(0, root.scrollHeight - root.clientHeight - root.scrollTop),- firstVisibleId: firstVisible?.dataset.msgId ?? null,- firstVisibleOffset: firstRect ? firstRect.top - rootRect.top : null,- contentPaddingBottom: content ? Number.parseFloat(getComputedStyle(content).paddingBottom) : 0,- railPosition: rail ? getComputedStyle(rail).position : null,- railRect: railRect ? { top: railRect.top, bottom: railRect.bottom, height: railRect.height } : null,- accessoryPosition: accessory ? getComputedStyle(accessory).position : null,- accessoryRect: accessoryRect ? { top: accessoryRect.top, bottom: accessoryRect.bottom, height: accessoryRect.height } : null,- railInFooter: !!rail && rail.parentElement === accessory && rail.closest('[data-slot="community-conversation-footer"]') === composer,- railInScroller: !!rail && !!rail.closest("[data-message-scroller-boundary]"),- composerRect: composerRect ? { top: composerRect.top, bottom: composerRect.bottom } : null,- surfaceChannelId: surface?.dataset.channelId ?? null,- scrollerRect: { top: rootRect.top, bottom: rootRect.bottom },- }- }, tid.composerAccessoryRail)-}--async function waitForCommittedGeometry(scroller: Locator): Promise<MessageViewportGeometry> {- await scroller.evaluate(() => new Promise<void>((resolveValue) => {- requestAnimationFrame(() => requestAnimationFrame(() => resolveValue()))- }))- let previous = ""- let settled: MessageViewportGeometry | null = null- await expect.poll(async () => {- const geometry = await readMessageViewportGeometry(scroller)- const signature = JSON.stringify(geometry)- const stable = signature === previous- previous = signature- if (stable) settled = geometry- return stable- }, { timeout: 20_000 }).toBe(true)- return settled!-}--async function expectSkeletonTailGeometry(- page: Page,- _width: 390 | 1280,- label: string,-): Promise<void> {- const geometry = await page.locator("[data-message-list-skeleton-tail]").first().evaluate((tail, scrollerTestId) => {- const tailRect = tail.getBoundingClientRect()- const scroller = tail.closest<HTMLElement>("[data-message-list-content]")- ?.closest<HTMLElement>(`[data-testid="${scrollerTestId}"]`)- const scrollerRect = scroller?.getBoundingClientRect()- const content = tail.closest<HTMLElement>("[data-message-list-content]")- return {- tailHeight: tailRect.height,- tailBottom: tailRect.bottom,- scrollerBottom: scrollerRect?.bottom ?? null,- contentPaddingBottom: content- ? Number.parseFloat(getComputedStyle(content).paddingBottom)- : null,- }- }, tid.messageScroller)- const expectedTail = 40- expect(geometry.contentPaddingBottom, `${label}: outer padding`).toBe(0)- expect(geometry.tailHeight, `${label}: placeholder height`).toBe(expectedTail)- expect(geometry.scrollerBottom, `${label}: scroller boundary`).not.toBeNull()- expect(- Math.abs(geometry.tailBottom - geometry.scrollerBottom!),- `${label}: placeholder ends at scroller bottom`,- ).toBeLessThanOrEqual(1)-}--async function waitForStableTail(scroller: Locator, label: string): Promise<void> {- await expect.poll(async () => {- const before = await readMessageViewportGeometry(scroller)- await scroller.evaluate(() => new Promise<void>((resolveValue) => {- requestAnimationFrame(() => requestAnimationFrame(() => resolveValue()))- }))- const after = await readMessageViewportGeometry(scroller)- return {- atTail: after.distanceToEnd <= 1,- stable: Math.abs(after.scrollTop - before.scrollTop) <= 1- && Math.abs(after.scrollHeight - before.scrollHeight) <= 1,- }- }, {- timeout: 20_000,- message: `${label}: product scroll-to-bottom must finish before exact-pinned setup`,- }).toMatchObject({ atTail: true, stable: true })-}--async function advanceScrollTraceFrame(scroller: Locator): Promise<void> {- await scroller.evaluate(() => new Promise<void>((resolveValue) => {- requestAnimationFrame(() => resolveValue())- }))-}--function expectViewportAnchorPreserved(- before: MessageViewportGeometry,- after: MessageViewportGeometry,- label: string,-): void {- expect(Math.abs(after.scrollTop - before.scrollTop), `${label}: scrollTop`).toBeLessThanOrEqual(1)- expect(after.firstVisibleId, `${label}: first visible row`).toBe(before.firstVisibleId)- expect(- Math.abs((after.firstVisibleOffset ?? 0) - (before.firstVisibleOffset ?? 0)),- `${label}: first visible offset`,- ).toBeLessThanOrEqual(1)-}--function expectResizeAnchorPreserved(- before: MessageViewportGeometry,- after: MessageViewportGeometry,- distance: number,- label: string,-): void {- if (distance <= 100) {- expect(- Math.abs(after.distanceToEnd - before.distanceToEnd),- `${label}: distance to tail`,- ).toBeLessThanOrEqual(1)- return- }- expectViewportAnchorPreserved(before, after, label)-}--function expectContinuousResizeAnchorPreserved(- trace: ScrollTraceResult,- segmentName: string,- distance: number,-): void {- const start = trace.marks.find((mark) => mark.name === `analysis-start:${segmentName}`)- const end = trace.marks.find((mark) => mark.name === `analysis-end:${segmentName}`)- expect(start, `${segmentName}: start mark`).toBeDefined()- expect(end, `${segmentName}: end mark`).toBeDefined()- const frames = trace.frames.filter((frame) => (- frame.frame >= start!.frame && frame.frame <= end!.frame- ))- expect(frames.length, `${segmentName}: continuous frames`).toBeGreaterThan(1)-- const baseline = frames[0]!- if (distance <= 100) {- for (const frame of frames) {- expect(- Math.abs(frame.distanceToEnd - baseline.distanceToEnd),- `${segmentName}: frame ${frame.frame} tail-distance drift`,- ).toBeLessThanOrEqual(1)- }- return- }-- for (const frame of frames) {- expect(frame.firstVisibleId, `${segmentName}: frame ${frame.frame} visible row`)- .toBe(baseline.firstVisibleId)- expect(- Math.abs((frame.firstVisibleOffset ?? 0) - (baseline.firstVisibleOffset ?? 0)),- `${segmentName}: frame ${frame.frame} visible-anchor drift`,- ).toBeLessThanOrEqual(1)- }-}--function expectInFlowMessageGeometry(geometry: MessageViewportGeometry, label: string): void {- expect(geometry.contentPaddingBottom, `${label}: outer tail padding removed`).toBe(0)- expect(geometry.composerRect, `${label}: scoped composer`).not.toBeNull()- if (geometry.railRect) {- expect(geometry.railPosition, `${label}: rail position`).toBe("static")- expect(geometry.railInFooter, `${label}: Footer owns rail`).toBe(true)- expect(geometry.railInScroller, `${label}: rail outside scroller`).toBe(false)- expect(geometry.accessoryPosition, `${label}: accessory position`).toBe("absolute")- expect(geometry.accessoryRect, `${label}: accessory slot`).not.toBeNull()- expect(geometry.accessoryRect!.height, `${label}: accessory height`).toBe(40)- expect(geometry.railRect.height, `${label}: rail height`).toBe(32)- expect(Math.abs(geometry.railRect.top - geometry.accessoryRect!.top - 4), `${label}: upper center gap`).toBeLessThanOrEqual(1)- expect(Math.abs(geometry.accessoryRect!.bottom - geometry.railRect.bottom - 4), `${label}: lower center gap`).toBeLessThanOrEqual(1)- expect(Math.abs(geometry.accessoryRect!.bottom - geometry.composerRect!.top), `${label}: slot ends at Footer`).toBeLessThanOrEqual(1)- expect(geometry.railRect.top, `${label}: rail top`).toBeGreaterThanOrEqual(geometry.scrollerRect.top - 1)- expect(geometry.railRect.bottom, `${label}: rail bottom`).toBeLessThanOrEqual(geometry.scrollerRect.bottom + 1)- expect(geometry.railRect.bottom, `${label}: rail clears composer`).toBeLessThanOrEqual(- geometry.composerRect!.top + 1,- )- }-}--function messageCreateCount(- frames: Awaited<ReturnType<typeof proxyCommunityWebSockets>>["frames"],- channelId: string,- body: string,-): number {- return frames.filter((frame) => communityFrameEvents(frame).some((event) =>- event.type === "community:message.create"- && event.channelId === channelId- && event.message?.content?.includes(body))).length-}--type PostedMessageIdentity = { id: string; seq: number; channelId: string; authorId: string; content: string }--async function expectMessageCreateIdentity(- frames: Awaited<ReturnType<typeof proxyCommunityWebSockets>>["frames"],- channelId: string,- message: PostedMessageIdentity,- nonce: string,-): Promise<void> {- expect(message.id.length).toBeGreaterThan(0)- expect(message.seq).toBeGreaterThan(0)- await expect.poll(() => frames.flatMap(communityFrameEvents).filter(event =>- event.type === "community:message.create" && event.channelId === channelId && event.message?.id === message.id,- ).length).toBe(1)- const created = frames.flatMap(communityFrameEvents).find(event =>- event.type === "community:message.create" && event.channelId === channelId && event.message?.id === message.id,- )!- expect(created.message).toMatchObject({ id: message.id, seq: message.seq, authorId: message.authorId, clientNonce: nonce })-}--async function seedScrollCase(actors: CaseActors) {- const { seedServer, seedJoinServer, seedChannel, seedDm } = actors.seed- const { userId } = actors- const stamp = Date.now()- const serverId = await seedServer("alice", `Scroll characterization ${stamp}`)- await seedJoinServer("alice", "bob", serverId)- await seedJoinServer("alice", "carol", serverId)- const coldChannelId = await seedChannel("alice", serverId, `scroll-cold-${stamp}`)- const loadingChannelId = await seedChannel("alice", serverId, `scroll-loading-${stamp}`)- const upwardChannelId = await seedChannel("alice", serverId, `scroll-upward-${stamp}`)- const composerChannelId = await seedChannel("alice", serverId, `scroll-composer-${stamp}`)- const composerDmId = await seedDm("alice", userId("bob"))- const loadingProfile = await seedProfile(actors, loadingChannelId, 130, false, "rotate", 64)- const upwardProfile = await seedProfile(actors, upwardChannelId, 72, false, "rotate", 23)- const composerProfile = await seedProfile(actors, composerChannelId, 36, true, "alice")- const composerDmProfile = await seedDmProfile(actors, composerDmId, 36)- return { serverId, coldChannelId, loadingChannelId, upwardChannelId, composerChannelId, composerDmId, loadingProfile, upwardProfile, composerProfile, composerDmProfile }-}--function tracedAsUser(actors: CaseActors): CaseActors["asUser"] {- return async (key, options) => {- const opened = await actors.asUser(key, options)- actors.onCleanup(async () => {- if (!opened.page.isClosed()) await abortScrollTrace(opened.page)- })- return opened- }-}--test.describe("message scroll characterization", () => {- test("measured reaction updates above the fold preserve reading during repeated controlled backward input", async ({ caseActors }, testInfo) => {- test.setTimeout(120_000)- const actors = await caseActors(["alice"])- const serverId = await actors.seed.seedServer("alice", `Measured reactions ${Date.now()}`)- const channelId = await actors.seed.seedChannel("alice", serverId, "measured-reactions")- const { page } = await tracedAsUser(actors)("alice")- await page.setViewportSize({ width: 390, height: 800 })- await seedProfile(actors, channelId, 4, false, "alice")- const messageId = await actors.seed.seedMessage("alice", channelId, "A measured historical message")- await seedProfile(actors, channelId, 24, false, "alice")- const reactionFrame = (frame: Parameters<typeof communityFrameEvents>[0]) => communityFrameEvents(frame).some(event =>- event.type === "community:reaction.add" && event.messageId === messageId)- const proxy = await proxyCommunityWebSockets(page.context(), { decide: frame => reactionFrame(frame) ? "hold" : "forward" })- const batches = [["👍", "❤️", "😂", "🎉", "👀"], ["🚀", "✅", "🔥", "💯", "🤔"]]- await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)- const scroller = page.getByTestId(tid.messageScroller)- await expect(scroller.locator('[data-message-list-content]')).toHaveAttribute("data-read-position-ready", "true")- await waitForCommittedGeometry(scroller)- await scroller.evaluate(element => { element.scrollTop = 0; element.dispatchEvent(new Event("scroll")) })- await expect(page.getByTestId(tid.message(messageId))).toHaveCount(1)- await scroller.evaluate((element, id) => {- const row = element.querySelector<HTMLElement>(`[data-msg-id="${id}"]`)- if (!row) throw new Error("The measured reaction message is required")- element.scrollTop += row.getBoundingClientRect().bottom - element.getBoundingClientRect().top + 256- element.dispatchEvent(new Event("scroll"))- }, messageId)- await waitForCommittedGeometry(scroller)- await installScrollTraceInCurrentDocument(page)- await startScrollTrace(page, { scenario: "measured-reactions-backward-growth", identity: identity(channelId, { width: 390, height: 800 }) })- await beginScrollTraceAnalysis(page, "above-fold-repeated-growth", { commandDirection: "backward" })- const samples: Array<{ at: number; rowHeight: number; lastInputAt: number }> = []- let trace: ScrollTraceResult | undefined- try {- for (const [round, emojis] of batches.entries()) {- for (const emoji of emojis) await actors.seed.seedReaction("alice", messageId, emoji)- await expect.poll(() => proxy.frames.flatMap(communityFrameEvents).filter(event =>- event.type === "community:reaction.add" && event.messageId === messageId).length).toBe((round + 1) * 5)- await markScrollTrace(page, `stimulus:reactions-${round}`, { detail: { input: "controlled-wheel-and-scroll", emojis, messageId } })- const before = await scroller.evaluate(controlledBackwardGrowth, { start: messageId })- expect(before.growingBottom).toBeLessThan(0)- expect(proxy.releaseHeld(reactionFrame)).toBeGreaterThan(0)- await expect.poll(() => page.getByTestId(tid.message(messageId)).evaluate(element => element.closest("[data-index]")!.getBoundingClientRect().height))- .toBeGreaterThan(before.rowHeight)- const input = await scroller.evaluate(controlledBackwardGrowth, { finish: true as const })- expect(input.measurement, "Native row growth must be measured during controlled input").not.toBeNull()- expect(input.measurement!.direction).toBe("backward")- expect(input.measurement!.at - input.measurement!.lastInputAt).toBeLessThan(150)- expect(input.inputDelta).toBeLessThan(0)- samples.push({ at: before.at, rowHeight: before.rowHeight, lastInputAt: input.measurement!.lastInputAt })- await advanceScrollTraceFrame(scroller)- const after = await page.getByTestId(tid.message(before.id)).evaluate(element => {- const root = element.closest<HTMLElement>("[data-message-scroller-boundary]")?.querySelector<HTMLElement>("[data-pagination-enabled]")- if (!root) throw new Error("The reading scroller is required")- return element.getBoundingClientRect().top - root.getBoundingClientRect().top- })- await markScrollTrace(page, `observed:reactions-${round}`, { detail: { before, after, input } })- expect.soft(Math.abs(after - before.top + input.inputDelta), `Reading drift after reaction batch ${round}`).toBeLessThanOrEqual(1)- }- } finally {- await scroller.evaluate(cancelControlledBackwardGrowth)- await endScrollTraceAnalysis(page, "above-fold-repeated-growth")- trace = await finishAndAttach(page, testInfo)- }- if (!trace) throw new Error("The reaction-growth trace is required")- for (const sample of samples) {- const measurement = trace.measurements.find(row => row.id === messageId && row.timestamp >= sample.at && row.height > sample.rowHeight + 1)- expect(measurement, "A real growing-row measurement must precede the 150ms backward reset").toBeDefined()- expect(measurement!.timestamp - sample.lastInputAt).toBeLessThan(150)- }- })-- test("controlled upward release before native movement prevents HTML tail resize follow", async ({ caseActors }, testInfo) => {- test.setTimeout(120_000)- const actors = await caseActors(["alice"])- const serverId = await actors.seed.seedServer("alice", `Released HTML ${Date.now()}`)- const channelId = await actors.seed.seedChannel("alice", serverId, "released-html")- const { page } = await tracedAsUser(actors)("alice")- await page.setViewportSize(VIEWPORT)- await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)- await seedProfile(actors, channelId, 24, false, "alice")- const { attachmentId } = await seedResizableHtmlPreview(page, channelId)- const scroller = page.getByTestId(tid.messageScroller)- const iframe = page.getByTestId(tid.htmlPreviewFrame(attachmentId))- await expect(page.getByTestId(tid.htmlPreview(attachmentId))).toHaveAttribute("data-html-preview-status", "ready")- await expect(iframe).toHaveCSS("height", "160px")- await installScrollTraceInCurrentDocument(page)- await startScrollTrace(page, { scenario: "released-html-tail-growth", identity: identity(channelId) })- try {- for (const distance of [0, 1, 2]) {- await iframe.evaluate(element => (element as HTMLIFrameElement).contentWindow?.postMessage({ type: "scroll-fixture-height", height: 160 }, "*"))- await expect(iframe).toHaveCSS("height", "160px")- await establishScrollDistancePrecondition(scroller, `released-tail-${distance}`, distance, 0.05)- await beginScrollTraceAnalysis(page, `released-tail-${distance}`)- try {- const before = await scroller.evaluate((element, frameId) => {- const frame = element.querySelector<HTMLIFrameElement>(`[data-testid="${frameId}"]`)- if (!frame?.contentWindow) throw new Error("A real mounted HTML preview is required")- const wheel = new WheelEvent("wheel", { deltaY: -20, bubbles: true })- element.dispatchEvent(wheel)- const result = { top: element.scrollTop, distance: element.scrollHeight - element.clientHeight - element.scrollTop,- trusted: wheel.isTrusted }- frame.contentWindow.postMessage({ type: "scroll-fixture-height", height: 260 }, "*")- return result- }, tid.htmlPreviewFrame(attachmentId))- await markScrollTrace(page, `stimulus:released-tail-${distance}`, { detail: before })- await expect(iframe).toHaveCSS("height", "260px")- await advanceScrollTraceFrame(scroller)- const after = await scroller.evaluate(element => element.scrollTop)- await markScrollTrace(page, `observed:released-tail-${distance}`, { detail: { before, after } })- expect.soft(Math.abs(after - before.top), `Released reader movement at ${distance}px`).toBeLessThanOrEqual(1)- } finally {- await endScrollTraceAnalysis(page, `released-tail-${distance}`)- }- }- } finally {- await finishAndAttach(page, testInfo)- }- })-- test("cold and warm loading, older prepend, and jump-to-present remain observable", async ({ caseActors }, testInfo) => {- test.setTimeout(180_000)- const actors = await caseActors(["alice", "bob", "carol"])- const asUser = tracedAsUser(actors)- const { serverId, coldChannelId, loadingChannelId, loadingProfile } = await seedScrollCase(actors)-- const alice = await asUser("alice")- await alice.page.setViewportSize(VIEWPORT)- await installScrollTrace(alice.page)- const initialMessages = await holdNextRequest(actors,- alice.page,- `**/api/community/channels/${coldChannelId}/messages**`,- () => true,- )- const image = await holdNextRequest(actors,- alice.page,- "**/icon-512.png?scroll-trace=1",- () => true,- )- await alice.page.goto(`/c/channels/${serverId}`, { waitUntil: "commit" })- await alice.page.getByTestId(tid.channelRow(coldChannelId)).click()- const initialUrl = await initialMessages.matched- expect(initialUrl.searchParams.has("anchor")).toBe(false)- const scroller = alice.page.getByTestId(tid.messageScroller)- await expect(scroller.locator('[data-slot="skeleton"]').first()).toBeVisible({ timeout: 20_000 })- await expectSkeletonTailGeometry(alice.page, 1280, "desktop cold skeleton")- const selfTest = await scrollTraceSelfTest(alice.page)- expect(selfTest).toMatchObject({- getterValue: 7,- methodValue: 8,- setterError: "RangeError",- methodError: "RangeError",- receiverPreserved: true,- restored: true,- unsupportedUntouched: true,- })- await startScrollTrace(alice.page, {- scenario: "cold-load-and-async-row",- identity: identity(coldChannelId),- })- await beginScrollTraceAnalysis(alice.page, "cold-load-and-async-row", {- dataTransitionSource: "initial-cold",- })- await markScrollTrace(alice.page, "cold-request-held", { dataTransitionSource: "initial-cold" })- const coldProfile = await seedProfile(actors, coldChannelId, 12, true, "alice")- initialMessages.release()- await image.matched- await expect(alice.page.getByTestId(tid.message(coldProfile.ids.at(-1)!))).toBeVisible({ timeout: 30_000 })- await markScrollTrace(alice.page, "async-image-release", {- detail: { position: "tail", asset: "local-fixture" },- })- image.release()- await expect(alice.page.getByTestId(tid.message(coldProfile.ids.at(-1)!)).locator("img")).toBeVisible()- await endScrollTraceAnalysis(alice.page, "cold-load-and-async-row")- const cold = await finishAndAttach(alice.page, testInfo)- expect(cold.frames.some((frame) => frame.loaders.top.mounted || frame.rows.length === 0)).toBe(true)- await initialMessages.dispose()- await image.dispose()-- const mobile = await asUser("alice")- await mobile.page.setViewportSize({ width: 390, height: 844 })- const mobileInitialMessages = await holdNextRequest(actors,- mobile.page,- `**/api/community/channels/${coldChannelId}/messages**`,- () => true,- )- await mobile.page.goto(`/c/channels/${serverId}`, { waitUntil: "commit" })- await mobile.page.getByTestId(tid.channelRow(coldChannelId)).click()- await mobileInitialMessages.matched- await expect(mobile.page.getByTestId(tid.messageScroller)- .locator('[data-slot="skeleton"]').first()).toBeVisible({ timeout: 20_000 })- await expectSkeletonTailGeometry(mobile.page, 390, "mobile cold skeleton")- mobileInitialMessages.release()- await expect(mobile.page.getByTestId(tid.message(coldProfile.ids.at(-1)!)))- .toBeVisible({ timeout: 30_000 })- await mobileInitialMessages.dispose()-- await installScrollTraceInCurrentDocument(alice.page)- await alice.page.getByTestId(tid.channelRow(loadingChannelId)).click()- await alice.page.waitForURL(new RegExp(loadingChannelId), { waitUntil: "commit" })- await expect(alice.page.getByTestId(tid.messageScroller)).toBeVisible()- const warmRequest = await holdNextRequest(actors,- alice.page,- `**/api/community/channels/${coldChannelId}/messages**`,- () => true,- { required: false },- )- await alice.page.getByTestId(tid.channelRow(coldChannelId)).click()- await alice.page.waitForURL(new RegExp(coldChannelId), { waitUntil: "commit" })- await expect(alice.page.getByTestId(tid.message(coldProfile.ids.at(-1)!))).toBeVisible({ timeout: 20_000 })- await startScrollTrace(alice.page, {- scenario: "warm-cache-reuse",- identity: identity(coldChannelId),- estimatedSizes: coldProfile.estimates,- })- await beginScrollTraceAnalysis(alice.page, "warm-cache-reuse", {- dataTransitionSource: "initial-cache",- })- await markScrollTrace(alice.page, "cached-rows-painted", {- dataTransitionSource: "initial-cache",- detail: { renderedBeforeRelease: true, revalidationMatched: warmRequest.hasMatched() },- })- warmRequest.release()- await endScrollTraceAnalysis(alice.page, "warm-cache-reuse")- await finishAndAttach(alice.page, testInfo)- await warmRequest.dispose()-- const anchored = await asUser("alice")- await anchored.page.setViewportSize(VIEWPORT)- await installScrollTrace(anchored.page)- await anchored.page.goto(`/c/channels/${serverId}/${loadingChannelId}`, { waitUntil: "commit" })- const anchoredNewDivider = anchored.page.getByTestId(tid.newDivider)- await expect(async () => {- expect(await anchoredNewDivider.count()).toBe(1)- expect(await anchoredNewDivider.isVisible()).toBe(true)- }).toPass({ timeout: 30_000 })- await expect(anchored.page.getByTestId(tid.messageScroller)).toHaveAttribute("data-pagination-enabled", "true")- const older = await holdNextRequest(actors,- anchored.page,- `**/api/community/channels/${loadingChannelId}/messages**`,- (url) => url.searchParams.has("cursor"),- )- await startScrollTrace(anchored.page, {- scenario: "older-loading-prepend",- identity: identity(loadingChannelId),- estimatedSizes: loadingProfile.estimates,- })- await beginScrollTraceAnalysis(anchored.page, "older-loading-prepend", {- dataTransitionSource: "older-page",- commandDirection: "backward",- })- await markScrollTrace(anchored.page, "stimulus:older-boundary", { dataTransitionSource: "older-page" })- await anchored.page.getByTestId(tid.messageScroller).evaluate((element) => {- element.scrollTop = 0- element.dispatchEvent(new Event("scroll"))- })- await older.matched- await expect(anchored.page.getByText("Loading older messages…", { exact: true })).toBeVisible()- older.release()- await expect(anchored.page.getByText("Loading older messages…", { exact: true })).toHaveCount(0)- await endScrollTraceAnalysis(anchored.page, "older-loading-prepend")- const olderTrace = await finishAndAttach(anchored.page, testInfo)- expect(olderTrace.marks.filter((mark) =>- mark.name === "stimulus:older-boundary"- && mark.dataTransitionSource === "older-page")).toHaveLength(1)- await older.dispose()-- await installScrollTraceInCurrentDocument(anchored.page)- const present = anchored.page.getByTestId(tid.scrollToPresent)- await expect(present).toBeVisible({ timeout: 30_000 })- let newestGets = 0- anchored.page.on("request", (request) => {- const url = new URL(request.url())- if (- request.method() === "GET"- && url.pathname === `/api/community/channels/${loadingChannelId}/messages`- && url.search === ""- ) newestGets += 1- })- const newest = await holdNextRequest(actors,- anchored.page,- `**/api/community/channels/${loadingChannelId}/messages**`,- (url) => url.search === "",- )- await startScrollTrace(anchored.page, {- scenario: "newer-loading-present",- identity: identity(loadingChannelId),- estimatedSizes: loadingProfile.estimates,- })- await beginScrollTraceAnalysis(anchored.page, "newer-loading-present", {- dataTransitionSource: "newer-page",- commandDirection: "forward",- })- await markScrollTrace(anchored.page, "stimulus:jump-present", { dataTransitionSource: "newer-page" })- await present.click()- await newest.matched- newest.release()- await expect(anchored.page.getByTestId(tid.message(loadingProfile.ids.at(-1)!))).toBeVisible({ timeout: 30_000 })- await expect(present).toHaveCount(0)- await endScrollTraceAnalysis(anchored.page, "newer-loading-present")- await finishAndAttach(anchored.page, testInfo)- await expect.poll(() => newestGets).toBe(1)- await anchored.page.waitForTimeout(500)- expect(newestGets).toBe(1)- await newest.dispose()- })-- test("peer receives follow after clamped bottom input without movement", async ({ caseActors }) => {- test.setTimeout(120_000)- const actors = await caseActors(["alice", "bob", "carol"])- const asUser = tracedAsUser(actors)- const { serverId } = await seedScrollCase(actors)- const { seedChannel, seedMessage } = actors.seed-- const channelId = await seedChannel("alice", serverId, `scroll-bottom-input-${Date.now()}`)- await seedProfile(actors, channelId, 18)- let tailId = await seedMessage("bob", channelId, "bottom input start\n[keyboard target](https://example.com)")- await setReadCheckpoint(actors, channelId, tailId)- const alice = await asUser("alice")- await alice.page.setViewportSize(VIEWPORT)- const proxy = await proxyCommunityWebSockets(alice.context)- await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${channelId}`)- const scroller = alice.page.getByTestId(tid.messageScroller)- await expect(scroller.locator('[data-message-list-content]')).toHaveAttribute("data-read-position-ready", "true")- for (const input of ["click", "wheel", "ArrowDown", "PageDown", "End", "Space"]) {- await waitForStableTail(scroller, `bottom-${input}`)- if (input !== "click" && input !== "wheel") {- await alice.page.getByTestId(tid.message(tailId)).getByRole("link", { name: "Link: https://example.com/" }).focus()- }- const before = await waitForCommittedGeometry(scroller)- expect(before.distanceToEnd).toBeLessThanOrEqual(1)- const box = await scroller.boundingBox()- expect(box).not.toBeNull()- await alice.page.mouse.move(box!.x + box!.width / 2, box!.y + box!.height - 16)- if (input === "click") await alice.page.mouse.click(box!.x + box!.width / 2, box!.y + box!.height - 16)- else if (input === "wheel") await alice.page.mouse.wheel(0, 120)- else await alice.page.keyboard.press(input)- const after = await waitForCommittedGeometry(scroller)- expect(after.distanceToEnd).toBeLessThanOrEqual(1)- expect(Math.abs(after.scrollTop - before.scrollTop)).toBeLessThanOrEqual(1)- const body = `bottom input ${input} ${Date.now()}\n[keyboard target](https://example.com)`- tailId = await seedMessage("carol", channelId, body)- await expect.poll(() => proxy.frames.filter(frame => communityFrameEvents(frame).some(event =>- event.type === "community:message.create" && event.channelId === channelId && event.message?.id === tailId,- )).length).toBe(1)- await expect(alice.page.getByTestId(tid.message(tailId))).toBeVisible()- await waitForStableTail(scroller, `received-${input}`)- await expect(alice.page.getByTestId(tid.scrollToPresent)).toHaveCount(0)- }- })-- test("local history submission and passive remote append use distinct owners", async ({ caseActors }, testInfo) => {- test.setTimeout(120_000)- const actors = await caseActors(["alice", "bob", "carol"])- const asUser = tracedAsUser(actors)- const { userId, sessionCookie } = actors- const { serverId } = await seedScrollCase(actors)- const { seedChannel } = actors.seed- const channelId = await seedChannel("alice", serverId, `scroll-passive-threshold-${Date.now()}`)- await seedProfile(actors, channelId, 130, false, "rotate", 18)- const alice = await asUser("alice")- await alice.page.setViewportSize(VIEWPORT)- await installScrollTrace(alice.page)- const proxy = await proxyCommunityWebSockets(alice.context)- let composerPosts = 0- alice.page.on("request", request => {- if (request.method() === "POST" && new URL(request.url()).pathname === `/api/community/channels/${channelId}/messages`) composerPosts += 1- })- const documentResponse = alice.page.waitForResponse(response => response.request().isNavigationRequest()- && new URL(response.url()).pathname === `/c/channels/${serverId}/${channelId}`)- const anchorResponse = alice.page.waitForResponse(response => {- const url = new URL(response.url())- return response.request().method() === "GET" && url.pathname === `/api/community/channels/${channelId}/messages` && url.searchParams.get("entry") === "1"- })- await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${channelId}`)- const scroller = alice.page.getByTestId(tid.messageScroller)- await expect(scroller.locator('[data-message-list-content]')).toHaveAttribute("data-read-position-ready", "true")- const anchored = await anchorResponse- expect(anchored.status()).toBe(200)- expectPublicCommunityDocument(await (await documentResponse).text())- const anchorPage = await anchored.json() as CommunityConversationEntryRead- expect(anchorPage.selection.reason).toBe("read_pointer")- expect(anchorPage.page.hasMoreNewer).toBe(true)- let newestGets = 0- alice.page.on("request", request => {- const url = new URL(request.url())- if (request.method() === "GET" && url.pathname === `/api/community/channels/${channelId}/messages` && url.search === "") newestGets += 1- })- const newest = await holdNextRequest(actors, alice.page, `**/api/community/channels/${channelId}/messages**`, url => url.search === "")- await startScrollTrace(alice.page, {- scenario: "local-history-submission",- identity: identity(channelId),- })- await beginScrollTraceAnalysis(alice.page, "local-history-submission", {- dataTransitionSource: "optimistic-send",- commandDirection: "forward",- })- let localTracePending = true- const attachLocalTrace = async () => {- if (!localTracePending) return- localTracePending = false- await endScrollTraceAnalysis(alice.page, "local-history-submission")- await finishAndAttach(alice.page, testInfo)- }- // The case owner preserves the body error and captures before page teardown.- actors.onCleanup(attachLocalTrace)- const localContent = `local history submission ${Date.now()}`- const localPost = alice.page.waitForResponse(response => response.request().method() === "POST"- && new URL(response.url()).pathname === `/api/community/channels/${channelId}/messages`- && response.request().postDataJSON().content === localContent)- try {- await sendMessage(alice.page, localContent)- await newest.matched- newest.release()- const response = await localPost- expect(response.status()).toBe(201)- const nonce = response.request().postDataJSON().nonce as string- expect(nonce.length).toBeGreaterThan(0)- const result = await response.json() as { message: PostedMessageIdentity }- expect(result.message).toMatchObject({ authorId: userId("alice"), channelId, content: localContent })- await expect.poll(() => messageCreateCount(proxy.frames, channelId, localContent)).toBe(1)- await expectMessageCreateIdentity(proxy.frames, channelId, result.message, nonce)- await expect(alice.page.getByTestId(tid.message(result.message.id))).toBeVisible()- await expect(alice.page.getByText(localContent, { exact: true })).toHaveCount(1)- await waitForStableTail(scroller, "local-history-submission-ack")- expect(newestGets).toBe(1)- expect(composerPosts).toBe(1)- } finally {- await newest.dispose()- }- await attachLocalTrace()- const finishPassiveTrace = await startAnalyzedScrollTrace(alice.page, {- scenario: "passive-append-position-admission",- identity: identity(channelId),- dataTransitionSource: "overlay-ws",- })- const attachPassiveTrace = async () => {- await finishPassiveTrace(testInfo)- }- actors.onCleanup(attachPassiveTrace)- for (const author of ["bob", "alice"] as const) {- for (const distance of [0, 1, 2, 20, 100, 101]) {- await markScrollTrace(alice.page, `${author}-${distance}-admission-start`)- await establishScrollDistancePrecondition(scroller, `${author}-${distance}`, distance, 0.01)- const before = await waitForCommittedGeometry(scroller)- expect(before.firstVisibleId).not.toBeNull()- expect(Math.abs(before.distanceToEnd - distance)).toBeLessThanOrEqual(0.01)- await markScrollTrace(alice.page, `${author}-${distance}-precondition`, { detail: before })- const nonce = `scroll186_${author}_${distance}_${Date.now()}`- const content = `passive ${author} at ${distance} ${nonce}`- const response = await communityFixtureFetch(`${WEB_URL}/api/community/channels/${channelId}/messages`, {- method: "POST",- headers: { Cookie: sessionCookie(author), "Content-Type": "application/json", Origin: WEB_URL },- body: JSON.stringify({ content, nonce }),- })- expect(response.status).toBe(201)- const result = await response.json() as { message: PostedMessageIdentity }- expect(result.message).toMatchObject({ authorId: userId(author), channelId, content })- await expect.poll(() => proxy.frames.filter(frame => communityFrameEvents(frame).some(event =>- event.type === "community:message.create" && event.channelId === channelId && event.message?.id === result.message.id,- )).length).toBe(1)- await expectMessageCreateIdentity(proxy.frames, channelId, result.message, nonce)- if (distance <= 1) {- await expect(alice.page.getByTestId(tid.message(result.message.id))).toBeVisible()- await waitForStableTail(scroller, `${author}-${distance}-received`)- } else {- await alice.page.waitForTimeout(250)- const bodyOffset = await scroller.locator(`[data-msg-id="${before.firstVisibleId}"]`).evaluate((element, scrollerTestId) => {- const root = element.closest<HTMLElement>(`[data-testid="${scrollerTestId}"]`)!- return element.getBoundingClientRect().top - root.getBoundingClientRect().top- }, tid.messageScroller)- expect(Math.abs(bodyOffset - before.firstVisibleOffset!)).toBeLessThanOrEqual(1)- const after = await waitForCommittedGeometry(scroller)- expect(Math.abs(after.scrollTop - before.scrollTop)).toBeLessThanOrEqual(1)- expect(after.distanceToEnd).toBeGreaterThan(distance)- }- expect(composerPosts).toBe(1)- }- }- expect(newestGets).toBe(1)- await attachPassiveTrace()- })-- test("remote receive states and sustained upward input produce diagnostic traces", async ({ caseActors }, testInfo) => {- test.setTimeout(180_000)- const actors = await caseActors(["alice", "bob", "carol"])- const asUser = tracedAsUser(actors)- const { serverId, upwardChannelId, upwardProfile } = await seedScrollCase(actors)- const { seedMessage } = actors.seed-- const alice = await asUser("alice")- await alice.page.setViewportSize(VIEWPORT)- await installScrollTrace(alice.page)- const proxy = await proxyCommunityWebSockets(alice.context)- await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${upwardChannelId}`)- const scroller = alice.page.getByTestId(tid.messageScroller)- await expect(scroller).toBeVisible({ timeout: 30_000 })- const present = alice.page.getByTestId(tid.scrollToPresent)- await expect(present).toBeVisible({ timeout: 30_000 })- await present.click()- await expect(alice.page.getByTestId(tid.message(upwardProfile.ids.at(-1)!)))- .toBeVisible({ timeout: 30_000 })- await expect(present).toHaveCount(0)- await waitForStableTail(scroller, "remote-fixture-tail")- await startScrollTrace(alice.page, {- scenario: "remote-receive-and-upward-input",- commandDirection: "backward",- identity: identity(upwardChannelId),- estimatedSizes: upwardProfile.estimates,- })-- await markScrollTrace(alice.page, "stimulus:pin-tail")- const pinnedPrecondition = await establishExactPinnedPrecondition(scroller, "remote-pinned", 0)- await markScrollTrace(alice.page, "remote-pinned-precondition", {- detail: pinnedPrecondition,- })- await beginScrollTraceAnalysis(alice.page, "remote-pinned", {- dataTransitionSource: "overlay-ws",- })- const pinnedBody = `remote pinned ${Date.now()}`- await markScrollTrace(alice.page, "remote-pinned", { dataTransitionSource: "overlay-ws" })- const pinnedId = await seedMessage("bob", upwardChannelId, pinnedBody)- await expect(alice.page.getByTestId(tid.message(pinnedId))).toBeVisible({ timeout: 20_000 })- await expect.poll(() => scroller.evaluate((element) =>- Math.max(0, element.scrollHeight - element.clientHeight - element.scrollTop))).toBeLessThanOrEqual(1)- await endScrollTraceAnalysis(alice.page, "remote-pinned")-- await markScrollTrace(alice.page, "stimulus:away-101")- const awayPrecondition = await establishScrollDistancePrecondition(scroller, "remote-away-101", 101)- await markScrollTrace(alice.page, "remote-away-precondition", {- detail: awayPrecondition,- })- await beginScrollTraceAnalysis(alice.page, "remote-away-101", {- dataTransitionSource: "overlay-ws",- })- const awayBody = `remote away ${Date.now()}`- await markScrollTrace(alice.page, "remote-away", { dataTransitionSource: "overlay-ws" })- await seedMessage("carol", upwardChannelId, awayBody)- await expect.poll(() => messageCreateCount(proxy.frames, upwardChannelId, awayBody)).toBe(1)- const awayObservation = await scroller.evaluate((element, pillTestId) => ({- distanceToEnd: Math.max(0, element.scrollHeight - element.clientHeight - element.scrollTop),- pillVisible: !!document.querySelector(`[data-testid='${pillTestId}']`),- }), tid.scrollToPresent)- await markScrollTrace(alice.page, "remote-away-observed", { detail: awayObservation })- await endScrollTraceAnalysis(alice.page, "remote-away-101")-- await markScrollTrace(alice.page, "stimulus:mid-history")- const midHistoryPrecondition = await establishMidHistoryPrecondition(scroller)- await markScrollTrace(alice.page, "remote-mid-history-precondition", {- detail: midHistoryPrecondition,- })- await beginScrollTraceAnalysis(alice.page, "remote-mid-history-burst", {- dataTransitionSource: "overlay-ws",- })- for (let index = 0; index < 3; index += 1) {- await markScrollTrace(alice.page, `remote-burst-${index}`, { dataTransitionSource: "overlay-ws" })- await seedMessage(index % 2 === 0 ? "bob" : "carol", upwardChannelId, `remote burst ${index} ${Date.now()}`)- }- await endScrollTraceAnalysis(alice.page, "remote-mid-history-burst")- await beginScrollTraceAnalysis(alice.page, "remote-during-smooth", {- dataTransitionSource: "overlay-ws",- commandDirection: "forward",- })- const smoothBody = `remote during smooth ${Date.now()}`- await markScrollTrace(alice.page, "remote-during-smooth", { dataTransitionSource: "overlay-ws" })- await scroller.evaluate((element) => element.scrollTo({- top: element.scrollHeight,- behavior: "smooth",- }))- await seedMessage("bob", upwardChannelId, smoothBody)- await expect.poll(() => messageCreateCount(proxy.frames, upwardChannelId, smoothBody)).toBe(1)- await endScrollTraceAnalysis(alice.page, "remote-during-smooth")-- await markScrollTrace(alice.page, "stimulus:reset-tail")- const upwardPrecondition = await establishScrollDistancePrecondition(scroller, "upward-60x24", 0)- await markScrollTrace(alice.page, "upward-precondition", { detail: upwardPrecondition })- const box = await scroller.boundingBox()- expect(box).not.toBeNull()- await alice.page.mouse.move(box!.x + box!.width / 2, box!.y + box!.height / 2)- await beginScrollTraceAnalysis(alice.page, "upward-60x24", {- dataTransitionSource: "overlay-ws",- commandDirection: "backward",- })- await markScrollTrace(alice.page, "stimulus:upward-60x24")- const liveAppend = (async () => {- await alice.page.waitForTimeout(250)- await markScrollTrace(alice.page, "upward-live-append", { dataTransitionSource: "overlay-ws" })- return seedMessage("carol", upwardChannelId, `upward live ${Date.now()}`)- })()- for (let index = 0; index < 60; index += 1) {- await alice.page.mouse.wheel(0, -24)- await alice.page.waitForTimeout(24)- }- await liveAppend- await endScrollTraceAnalysis(alice.page, "upward-60x24")- const trace = await finishAndAttach(alice.page, testInfo)- expect(trace.externalEvents.filter((event) => event.type === "wheel")).toHaveLength(60)- expect(trace.marks.filter((mark) => mark.dataTransitionSource === "overlay-ws").length)- .toBeGreaterThanOrEqual(7)- })-- test("manual draft clear and optimistic send stay distinct through viewport changes", async ({ caseActors }, testInfo) => {- test.setTimeout(180_000)- const actors = await caseActors(["alice", "bob", "carol"])- const asUser = tracedAsUser(actors)- const { serverId, composerChannelId, composerProfile } = await seedScrollCase(actors)-- const alice = await asUser("alice")- await alice.page.setViewportSize(VIEWPORT)- await installScrollTrace(alice.page)- const proxy = await proxyCommunityWebSockets(alice.context)- let messagePosts = 0- alice.page.on("request", (request) => {- if (- request.method() === "POST"- && new URL(request.url()).pathname === `/api/community/channels/${composerChannelId}/messages`- ) messagePosts += 1- })- await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${composerChannelId}`)- const scroller = alice.page.getByTestId(tid.messageScroller)- const editable = composerEditable(alice.page)- await expect(editable).toBeVisible()- await startScrollTrace(alice.page, {- scenario: "composer-clear-send-and-viewport",- identity: identity(composerChannelId),- estimatedSizes: composerProfile.estimates,- })-- const typeSixLines = async (prefix: string) => {- await editable.click()- for (let line = 0; line < 6; line += 1) {- await editable.pressSequentially(`${prefix} line ${line} ${"content ".repeat(8)}`)- if (line < 5) await alice.page.keyboard.press("Shift+Enter")- }- }- await markScrollTrace(alice.page, "stimulus:prepare-pinned-draft")- await typeSixLines("pinned")- const pinnedDraftPrecondition = await establishScrollDistancePrecondition(- scroller,- "manual-delete-pinned",- 0,- )- await markScrollTrace(alice.page, "manual-delete-pinned-precondition", {- detail: pinnedDraftPrecondition,- })- await beginScrollTraceAnalysis(alice.page, "manual-delete-pinned")- await markScrollTrace(alice.page, "manual-delete-pinned")- await alice.page.keyboard.press("ControlOrMeta+A")- await alice.page.keyboard.press("Backspace")- await expect(alice.page.getByTestId(tid.composerInput)).toHaveText("")- expect(messagePosts).toBe(0)- expect(proxy.frames.flatMap(communityFrameEvents).filter((event) =>- event.type === "community:message.create" && event.channelId === composerChannelId)).toHaveLength(0)- await endScrollTraceAnalysis(alice.page, "manual-delete-pinned")-- await markScrollTrace(alice.page, "stimulus:prepare-away-draft")- await typeSixLines("away")- const awayDraftPrecondition = await establishScrollDistancePrecondition(- scroller,- "manual-delete-away",- 300,- )- await markScrollTrace(alice.page, "manual-delete-away-precondition", {- detail: awayDraftPrecondition,- })- await beginScrollTraceAnalysis(alice.page, "manual-delete-away")- await markScrollTrace(alice.page, "manual-delete-away")- await alice.page.keyboard.press("ControlOrMeta+A")- await alice.page.keyboard.press("Backspace")- await expect(alice.page.getByTestId(tid.composerInput)).toHaveText("")- expect(messagePosts).toBe(0)- await endScrollTraceAnalysis(alice.page, "manual-delete-away")-- await markScrollTrace(alice.page, "stimulus:pin-for-send")- const pinnedSendPrecondition = await establishScrollDistancePrecondition(- scroller,- "optimistic-send-pinned",- 0,- )- await markScrollTrace(alice.page, "optimistic-send-pinned-precondition", {- detail: pinnedSendPrecondition,- })- await beginScrollTraceAnalysis(alice.page, "optimistic-send-pinned", {- dataTransitionSource: "optimistic-send",- })- const pinnedSend = `optimistic pinned ${Date.now()}`- await markScrollTrace(alice.page, "optimistic-pinned", { dataTransitionSource: "optimistic-send" })- await sendMessage(alice.page, pinnedSend)- await expect(alice.page.getByText(pinnedSend, { exact: true })).toHaveCount(1)- await markScrollTrace(alice.page, "post-ack-pinned", { dataTransitionSource: "post-ack" })- await expect.poll(() => messageCreateCount(proxy.frames, composerChannelId, pinnedSend)).toBe(1)- await markScrollTrace(alice.page, "ws-dedupe-pinned", { dataTransitionSource: "ws-dedupe" })- await endScrollTraceAnalysis(alice.page, "optimistic-send-pinned")-- await markScrollTrace(alice.page, "stimulus:send-away")- const awaySendPrecondition = await establishScrollDistancePrecondition(- scroller,- "optimistic-send-away",- 300,- )- await markScrollTrace(alice.page, "optimistic-send-away-precondition", {- detail: awaySendPrecondition,- })- await beginScrollTraceAnalysis(alice.page, "optimistic-send-away", {- dataTransitionSource: "optimistic-send",- })- const awaySend = `optimistic away ${Date.now()}`- await markScrollTrace(alice.page, "optimistic-away", { dataTransitionSource: "optimistic-send" })- await sendMessage(alice.page, awaySend)- await expect(alice.page.getByText(awaySend, { exact: true })).toHaveCount(1)- await markScrollTrace(alice.page, "post-ack-away", { dataTransitionSource: "post-ack" })- await expect.poll(() => messageCreateCount(proxy.frames, composerChannelId, awaySend)).toBe(1)- await markScrollTrace(alice.page, "ws-dedupe-away", { dataTransitionSource: "ws-dedupe" })- await expect.poll(() => scroller.evaluate((element) =>- Math.max(0, element.scrollHeight - element.clientHeight - element.scrollTop))).toBeLessThanOrEqual(1)- expect(messagePosts).toBe(2)- await endScrollTraceAnalysis(alice.page, "optimistic-send-away")-- await beginScrollTraceAnalysis(alice.page, "viewport-keyboard-profile")- await markScrollTrace(alice.page, "stimulus:viewport-keyboard-profile")- await alice.page.setViewportSize({ width: 1280, height: 560 })- await alice.page.setViewportSize(VIEWPORT)- await endScrollTraceAnalysis(alice.page, "viewport-keyboard-profile")- const trace = await finishAndAttach(alice.page, testInfo)- expect(trace.marks.filter((mark) =>- ["optimistic-pinned", "optimistic-away"].includes(mark.name)- && mark.dataTransitionSource === "optimistic-send")).toHaveLength(2)- expect(trace.marks.filter((mark) => mark.dataTransitionSource === "post-ack")).toHaveLength(2)- expect(trace.marks.filter((mark) => mark.dataTransitionSource === "ws-dedupe")).toHaveLength(2)- expect(messageCreateCount(proxy.frames, composerChannelId, pinnedSend)).toBe(1)- expect(messageCreateCount(proxy.frames, composerChannelId, awaySend)).toBe(1)- })-- test("DM composer clear preserves pinned and away viewport geometry", async ({ caseActors }, testInfo) => {- test.setTimeout(180_000)- const actors = await caseActors(["alice", "bob", "carol"])- const asUser = tracedAsUser(actors)- const { userId } = actors- const composerDmId = await actors.seed.seedDm("alice", userId("bob"))- const composerDmProfile = await seedDmProfile(actors, composerDmId, 36)-- const alice = await asUser("alice")- await alice.page.setViewportSize(VIEWPORT)- await installScrollTrace(alice.page)- const proxy = await proxyCommunityWebSockets(alice.context)- let messagePosts = 0- alice.page.on("request", (request) => {- if (- request.method() === "POST"- && new URL(request.url()).pathname === `/api/community/channels/${composerDmId}/messages`- ) messagePosts += 1- })- await gotoAfterUserWsAuth(alice.page, `/c/me/${composerDmId}`)- const scroller = alice.page.getByTestId(tid.messageScroller)- const editable = composerEditable(alice.page)- await expect(editable).toBeVisible()- await expect(alice.page.getByTestId(tid.message(composerDmProfile.ids.at(-1)!)))- .toBeVisible({ timeout: 30_000 })- await scroller.evaluate((element) => {- element.scrollTop = element.scrollHeight- element.dispatchEvent(new Event("scroll"))- })- const tailGeometry = await alice.page.evaluate(({ scrollerId, messageId }) => {- const scrollerElement = document.querySelector<HTMLElement>(- `[data-testid="${scrollerId}"]`,- )!- const content = scrollerElement.querySelector<HTMLElement>("[data-message-list-content]")!- const finalMessage = document.querySelector<HTMLElement>(`[data-testid="${messageId}"]`)!- const composer = document.querySelector<HTMLElement>('[data-onboarding-target="dm-composer"]')!- return {- paddingBottom: Number.parseFloat(getComputedStyle(content).paddingBottom),- tailGap: scrollerElement.getBoundingClientRect().bottom- - finalMessage.getBoundingClientRect().bottom,- scrollerBottom: scrollerElement.getBoundingClientRect().bottom,- composerTop: composer.getBoundingClientRect().top,- }- }, {- scrollerId: tid.messageScroller,- messageId: tid.message(composerDmProfile.ids.at(-1)!),- })- expect(tailGeometry.paddingBottom).toBe(0)- expect(tailGeometry.tailGap).toBeGreaterThanOrEqual(39)- expect(tailGeometry.tailGap).toBeLessThanOrEqual(41)- expect(tailGeometry.scrollerBottom).toBeLessThanOrEqual(tailGeometry.composerTop + 1)- await startScrollTrace(alice.page, {- scenario: "dm-composer-clear-viewport",- identity: identity(composerDmId),- estimatedSizes: composerDmProfile.estimates,- })-- const composerLines = (prefix: string) => Array.from(- { length: 6 },- (_, line) => `${prefix} line ${line} ${"content ".repeat(8)}`,- ).join("\n")-- for (const distance of [0, 2, 100, 300]) {- await editable.fill(composerLines(`dm-${distance}`))- const precondition = distance === 0- ? await establishExactPinnedPrecondition(scroller, `dm-composer-${distance}`, 0)- : await establishScrollDistancePrecondition(scroller, `dm-composer-${distance}`, distance)- await markScrollTrace(alice.page, `dm-composer-${distance}-precondition`, {- detail: precondition,- })- const before = await waitForCommittedGeometry(scroller)- expectInFlowMessageGeometry(before, `dm-${distance}-before`)- expect(before.surfaceChannelId).toBe(composerDmId)-- await beginScrollTraceAnalysis(alice.page, `dm-composer-shrink-${distance}`)- await editable.click()- await alice.page.keyboard.press("ControlOrMeta+A")- await alice.page.keyboard.press("Backspace")- await expect(editable).toHaveText("")- await expect.poll(() => scroller.evaluate((element) => element.clientHeight))- .toBeGreaterThan(before.clientHeight)- const after = await waitForCommittedGeometry(scroller)- expectInFlowMessageGeometry(after, `dm-${distance}-after`)- expectResizeAnchorPreserved(before, after, distance, `dm-${distance}-after`)- await endScrollTraceAnalysis(alice.page, `dm-composer-shrink-${distance}`)- await advanceScrollTraceFrame(scroller)- }-- const trace = await finishAndAttach(alice.page, testInfo)- const segments = new Map(- summarizeScrollTrace(trace).analysisSegments.map((segment) => [segment.name, segment]),- )- for (const distance of [0, 2, 100, 300]) {- const segmentName = `dm-composer-shrink-${distance}`- expect(segments.get(segmentName)).toBeDefined()- expectContinuousResizeAnchorPreserved(trace, segmentName, distance)- }- expect(messagePosts).toBe(0)- expect(proxy.frames.flatMap(communityFrameEvents).filter((event) =>- event.type === "community:message.create" && event.channelId === composerDmId)).toHaveLength(0)-- await establishScrollDistancePrecondition(scroller, "dm-local-submit-away", 300)- const content = `dm local acceptance ${Date.now()}`- const post = alice.page.waitForResponse(response => response.request().method() === "POST"- && new URL(response.url()).pathname === `/api/community/channels/${composerDmId}/messages`- && response.request().postDataJSON().content === content)- await sendMessage(alice.page, content)- const response = await post- expect(response.status()).toBe(201)- const nonce = response.request().postDataJSON().nonce as string- expect(nonce.length).toBeGreaterThan(0)- const result = await response.json() as { message: PostedMessageIdentity }- expect(result.message).toMatchObject({ authorId: userId("alice"), channelId: composerDmId, content })- await expect.poll(() => messageCreateCount(proxy.frames, composerDmId, content)).toBe(1)- await expectMessageCreateIdentity(proxy.frames, composerDmId, result.message, nonce)- await expect(alice.page.getByTestId(tid.message(result.message.id))).toBeVisible()- await expect(alice.page.getByText(content, { exact: true })).toHaveCount(1)- await waitForStableTail(scroller, "dm-local-submit-ack")- expect(messagePosts).toBe(1)- })-- test("normal-flow composer resizes preserve semantic anchors and interaction boundaries", async ({ caseActors }, testInfo) => {- test.setTimeout(180_000)- const actors = await caseActors(["alice", "bob", "carol"])- const asUser = tracedAsUser(actors)- const { userId } = actors- const { serverId, composerChannelId, composerProfile } = await seedScrollCase(actors)- const { seedThread } = actors.seed-- const splitThreadId = await seedThread(- "alice",- composerProfile.ids.at(-1)!,- `scroll split ${Date.now()}`,- )- const splitProfile = await seedProfile(actors, splitThreadId, 24, false, "alice")- const alice = await asUser("alice")- const bob = await asUser("bob")- await alice.page.setViewportSize(VIEWPORT)- await bob.page.setViewportSize(VIEWPORT)- await installScrollTrace(alice.page)- const proxy = await proxyCommunityWebSockets(alice.context)- let mutationPosts = 0- alice.page.on("request", (request) => {- const pathname = new URL(request.url()).pathname- if (- request.method() === "POST"- && (pathname.endsWith("/messages") || pathname.includes("/attachments"))- ) mutationPosts += 1- })- await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${composerChannelId}`)- await gotoAfterUserWsAuth(bob.page, `/c/channels/${serverId}/${composerChannelId}`)- const scroller = alice.page.getByTestId(tid.messageScroller)- const editable = composerEditable(alice.page)- const bobEditable = composerEditable(bob.page)- await expect(editable).toBeVisible()- await expect(bobEditable).toBeVisible()- await startScrollTrace(alice.page, {- scenario: "composer-exact-pinned-resize-policy",- identity: identity(composerChannelId),- estimatedSizes: composerProfile.estimates,- })-- const composerLines = (prefix: string, count: number) => Array.from(- { length: count },- (_, line) => `${prefix} line ${line} ${"content ".repeat(8)}`,- ).join("\n")-- for (const distance of [0, 2, 100, 300]) {- await editable.fill(composerLines(`boundary-${distance}`, 8))- const precondition = distance === 0- ? await establishExactPinnedPrecondition(scroller, `composer-resize-${distance}`, 0)- : await establishScrollDistancePrecondition(- scroller,- `composer-resize-${distance}`,- distance,- )- await markScrollTrace(alice.page, `composer-resize-${distance}-precondition`, {- detail: precondition,- })- const before = await waitForCommittedGeometry(scroller)- expectInFlowMessageGeometry(before, `resize-${distance}-before`)-- // Match the user journey that exposed the regression: grow the composer,- // establish the reading position, then delete the draft. Positioning the- // scroller before growth misses the browser's shrink-time maxScrollTop clamp.- await beginScrollTraceAnalysis(alice.page, `composer-shrink-${distance}`)- await editable.click()- await alice.page.keyboard.press("ControlOrMeta+A")- await alice.page.keyboard.press("Backspace")- await expect(editable).toHaveText("")- await expect.poll(() => scroller.evaluate((element) => element.clientHeight))- .toBeGreaterThan(before.clientHeight)- const shrunk = await waitForCommittedGeometry(scroller)- expectInFlowMessageGeometry(shrunk, `resize-${distance}-shrunk`)- expectResizeAnchorPreserved(before, shrunk, distance, `resize-${distance}-shrunk`)- await endScrollTraceAnalysis(alice.page, `composer-shrink-${distance}`)- await advanceScrollTraceFrame(scroller)-- await beginScrollTraceAnalysis(alice.page, `composer-grow-${distance}`)- await editable.fill(composerLines(`boundary-${distance}`, 8))- await expect.poll(() => scroller.evaluate((element) => element.clientHeight))- .toBe(before.clientHeight)- const grown = await waitForCommittedGeometry(scroller)- expectInFlowMessageGeometry(grown, `resize-${distance}-grown`)- expectResizeAnchorPreserved(before, grown, distance, `resize-${distance}-grown`)- await endScrollTraceAnalysis(alice.page, `composer-grow-${distance}`)- await advanceScrollTraceFrame(scroller)- }-- await editable.fill("")- await advanceScrollTraceFrame(scroller)-- const selectionDraft = composerLines("selection-draft", 8)- await editable.fill(selectionDraft)- await establishScrollDistancePrecondition(scroller, "selection-footer-away", 300)- const selectionBase = await waitForCommittedGeometry(scroller)- const selectionTargetId = selectionBase.firstVisibleId!- const selectionTarget = alice.page.getByTestId(tid.message(selectionTargetId))- await beginScrollTraceAnalysis(alice.page, "selection-footer-away")- await selectionTarget.locator("div.group").first().dispatchEvent("pointerover", {- pointerId: 1,- pointerType: "mouse",- isPrimary: true,- })- const selectionAction = alice.page.getByTestId(tid.messageShare(selectionTargetId))- await expect(selectionAction).toBeVisible()- await selectionAction.evaluate((button) => (button as HTMLButtonElement).click())- await expect(alice.page.getByTestId(tid.messageSelectionToolbar)).toBeVisible()- const conversationFooter = alice.page.locator('[data-slot="community-conversation-footer"]')- await expect(conversationFooter).toHaveAttribute("data-selection-active", "true")- await expect(editable).toBeHidden()- const selectionOpen = await waitForCommittedGeometry(scroller)- expect(selectionOpen.clientHeight).toBeGreaterThan(selectionBase.clientHeight)- expect(selectionOpen.scrollHeight).toBe(selectionBase.scrollHeight)- expectViewportAnchorPreserved(selectionBase, selectionOpen, "selection-open-away")- await expect(editable).toContainText("selection-draft line 0")- await alice.page.getByRole("button", { name: "Cancel message selection" }).click()- await expect(alice.page.getByTestId(tid.messageSelectionToolbar)).toHaveCount(0)- await expect(conversationFooter).toHaveAttribute("data-selection-active", "false")- await expect(editable).toBeVisible()- const selectionClosed = await waitForCommittedGeometry(scroller)- expect(selectionClosed.clientHeight).toBe(selectionBase.clientHeight)- expect(selectionClosed.scrollHeight).toBe(selectionBase.scrollHeight)- expectViewportAnchorPreserved(selectionBase, selectionClosed, "selection-closed-away")- await expect(editable).toContainText("selection-draft line 7")- await editable.fill("")- await endScrollTraceAnalysis(alice.page, "selection-footer-away")- await advanceScrollTraceFrame(scroller)-- await establishExactPinnedPrecondition(scroller, "reply-resize-pinned", 0)- const replyBase = await waitForCommittedGeometry(scroller)- await beginScrollTraceAnalysis(alice.page, "reply-banner-pinned")- const replyTarget = alice.page.getByTestId(tid.message(composerProfile.ids.at(-1)!))- await expect(replyTarget).toBeVisible()- await replyTarget.locator("div.group").first().dispatchEvent("pointerover", {- pointerId: 1,- pointerType: "mouse",- isPrimary: true,- })- const replyButton = replyTarget.getByRole("button", { name: "Reply", exact: true })- await expect(replyButton).toBeVisible()- await expect(replyButton).toBeInViewport()- expect((await waitForCommittedGeometry(scroller)).distanceToEnd).toBeLessThanOrEqual(1)- await replyButton.evaluate((button) => (button as HTMLButtonElement).click())- await expect(alice.page.locator('[data-slot="composer-reply-preview"]')).toBeVisible()- const replyOpen = await waitForCommittedGeometry(scroller)- expect(replyOpen.clientHeight).toBeLessThan(replyBase.clientHeight)- expect(replyOpen.distanceToEnd).toBeLessThanOrEqual(1)- expectResizeAnchorPreserved(replyBase, replyOpen, 0, "reply-open")- expectInFlowMessageGeometry(replyOpen, "reply-open")- await alice.page.getByRole("button", { name: "Cancel reply" }).click()- await expect(alice.page.locator('[data-slot="composer-reply-preview"]')).toHaveCount(0)- const replyClosed = await waitForCommittedGeometry(scroller)- expect(replyClosed.clientHeight).toBe(replyBase.clientHeight)- expect(replyClosed.distanceToEnd).toBeLessThanOrEqual(1)- expectResizeAnchorPreserved(replyBase, replyClosed, 0, "reply-closed")- await endScrollTraceAnalysis(alice.page, "reply-banner-pinned")- await advanceScrollTraceFrame(scroller)-- await establishTailMessageBelowViewportPrecondition(- scroller,- "attachment-resize-away",- composerProfile.ids.at(-1)!,- )- const attachmentBase = await waitForCommittedGeometry(scroller)- await beginScrollTraceAnalysis(alice.page, "attachment-chip-away")- await alice.page.getByTestId(tid.composerFileInput).setInputFiles({- name: "geometry-only.txt",- mimeType: "text/plain",- buffer: Buffer.from("geometry only"),- })- await expect(alice.page.getByText("geometry-only.txt", { exact: true })).toBeVisible()- const attachmentOpen = await waitForCommittedGeometry(scroller)- expect(attachmentOpen.clientHeight).toBeLessThan(attachmentBase.clientHeight)- expectViewportAnchorPreserved(attachmentBase, attachmentOpen, "attachment-open-away")- expectInFlowMessageGeometry(attachmentOpen, "attachment-open-away")- await alice.page.getByRole("button", { name: "Remove file" }).click()- await expect(alice.page.getByText("geometry-only.txt", { exact: true })).toHaveCount(0)- const attachmentClosed = await waitForCommittedGeometry(scroller)- expect(attachmentClosed.clientHeight).toBe(attachmentBase.clientHeight)- expectViewportAnchorPreserved(attachmentBase, attachmentClosed, "attachment-closed-away")- await endScrollTraceAnalysis(alice.page, "attachment-chip-away")- await advanceScrollTraceFrame(scroller)-- await establishScrollDistancePrecondition(scroller, "typing-rail-away", 101)- const typingBase = await waitForCommittedGeometry(scroller)- await beginScrollTraceAnalysis(alice.page, "typing-rail-away")- await bobEditable.fill("typing rail geometry")- await expect(alice.page.getByTestId(tid.typingIndicator)).toBeVisible({ timeout: 20_000 })- const typingOpen = await waitForCommittedGeometry(scroller)- expect(typingOpen.clientHeight).toBe(typingBase.clientHeight)- expectViewportAnchorPreserved(typingBase, typingOpen, "typing-rail-away")- expect(typingOpen.railRect, "typing-rail-away: scoped Footer rail exists").not.toBeNull()- expectInFlowMessageGeometry(typingOpen, "typing-rail-away")- await bobEditable.fill("")- await endScrollTraceAnalysis(alice.page, "typing-rail-away")- await advanceScrollTraceFrame(scroller)-- const trace = await finishAndAttach(alice.page, testInfo)- const resizeSegments = new Map(- summarizeScrollTrace(trace).analysisSegments.map((segment) => [segment.name, segment]),- )- for (const distance of [0, 2, 100, 300]) {- const grow = resizeSegments.get(`composer-grow-${distance}`)- const shrink = resizeSegments.get(`composer-shrink-${distance}`)- expect(grow, `missing composer-grow-${distance}`).toBeDefined()- expect(shrink, `missing composer-shrink-${distance}`).toBeDefined()- expectContinuousResizeAnchorPreserved(trace, `composer-grow-${distance}`, distance)- expectContinuousResizeAnchorPreserved(trace, `composer-shrink-${distance}`, distance)- }- expect(resizeSegments.get("typing-rail-away")?.writerCount).toBe(0)- expectContinuousResizeAnchorPreserved(trace, "selection-footer-away", 300)- expect(mutationPosts).toBe(0)- expect(proxy.frames.flatMap(communityFrameEvents).filter((event) =>- event.type === "community:message.create" && event.channelId === composerChannelId)).toHaveLength(0)-- await alice.page.goto(`/c/channels/${serverId}/${splitThreadId}`, { waitUntil: "commit" })- const frame = await expectUniqueSsrCommunityFrame(alice.page)- const split = frame.getByTestId(tid.threadSplit)- await expect(split).toHaveCount(1)- await expect(split).toHaveAttribute("data-layout", "split", { timeout: 30_000 })- const parentPanel = split.getByTestId(tid.threadSplitParent)- const threadPanel = split.getByTestId(tid.threadSplitPanel)- const parentSurface = parentPanel.locator('[data-slot="community-conversation-surface"]')- const threadSurface = threadPanel.locator('[data-slot="community-conversation-surface"]')- await expect(parentSurface).toHaveAttribute("data-channel-id", composerChannelId)- await expect(threadSurface).toHaveAttribute("data-channel-id", splitThreadId)- await expect(parentSurface).toHaveCount(1)- await expect(threadSurface).toHaveCount(1)-- const parentEditable = composerEditable(alice.page, parentPanel)- const threadEditable = composerEditable(alice.page, threadPanel)- await parentEditable.fill(composerLines("split-parent", 2))- await threadEditable.fill(composerLines("split-thread", 6))- const parentScroller = parentPanel.getByTestId(tid.messageScroller)- const threadScroller = threadPanel.getByTestId(tid.messageScroller)- await establishTailMessageBelowViewportPrecondition(- parentScroller,- "split-parent-away",- composerProfile.ids.at(-1)!,- )- await establishTailMessageBelowViewportPrecondition(- threadScroller,- "split-thread-away",- splitProfile.ids.at(-1)!,- )- const parentGeometry = await waitForCommittedGeometry(parentScroller)- const threadGeometry = await waitForCommittedGeometry(threadScroller)- const parentComposerBox = await parentSurface- .locator('[data-slot="community-conversation-footer"]')- .boundingBox()- const threadComposerBox = await threadSurface- .locator('[data-slot="community-conversation-footer"]')- .boundingBox()- expect(parentGeometry.surfaceChannelId).toBe(composerChannelId)- expect(threadGeometry.surfaceChannelId).toBe(splitThreadId)- expect(parentComposerBox).not.toBeNull()- expect(threadComposerBox).not.toBeNull()- expect(Math.abs(parentGeometry.composerRect!.top - parentComposerBox!.y)).toBeLessThanOrEqual(1)- expect(Math.abs(threadGeometry.composerRect!.top - threadComposerBox!.y)).toBeLessThanOrEqual(1)- expect(threadGeometry.composerRect!.top).not.toBe(parentGeometry.composerRect!.top)- expectInFlowMessageGeometry(parentGeometry, "split-parent")- expectInFlowMessageGeometry(threadGeometry, "split-thread")- expect(mutationPosts).toBe(0)-- await parentEditable.fill("")- await threadEditable.fill("")- const parentBefore = await waitForCommittedGeometry(parentScroller)- const content = `thread local acceptance ${Date.now()}`- const post = alice.page.waitForResponse(response => response.request().method() === "POST"- && new URL(response.url()).pathname === `/api/community/channels/${splitThreadId}/messages`- && response.request().postDataJSON().content === content)- await sendMessage(alice.page, content, threadPanel)- const response = await post- expect(response.status()).toBe(201)- const nonce = response.request().postDataJSON().nonce as string- expect(nonce.length).toBeGreaterThan(0)- const result = await response.json() as { message: PostedMessageIdentity }- expect(result.message).toMatchObject({ authorId: userId("alice"), channelId: splitThreadId, content })- await expect.poll(() => messageCreateCount(proxy.frames, splitThreadId, content)).toBe(1)- await expectMessageCreateIdentity(proxy.frames, splitThreadId, result.message, nonce)- await expect(threadPanel.getByTestId(tid.message(result.message.id))).toBeVisible()- await expect(threadPanel.getByText(content, { exact: true })).toHaveCount(1)- await waitForStableTail(threadScroller, "thread-local-submit-ack")- const parentAfter = await waitForCommittedGeometry(parentScroller)- expectViewportAnchorPreserved(parentBefore, parentAfter, "thread-local-submit-parent")- })-})diff --git a/src/web/src/test/e2e-ui/55-peer-bottom-clamp-follow.spec.ts b/src/web/src/test/e2e-ui/55-peer-bottom-clamp-follow.spec.tsnew file mode 100644index 000000000..1451729e5--- /dev/null+++ b/src/web/src/test/e2e-ui/55-peer-bottom-clamp-follow.spec.ts@@ -0,0 +1,51 @@+import { test, expect } from "./_fixtures/case-fixture"+import { gotoAfterUserWsAuth } from "./_fixtures/actions"+import { communityFrameEvents, proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"+import { tid } from "./_fixtures/testids"+import { VIEWPORT, seedProfile, setReadCheckpoint, waitForCommittedGeometry, waitForStableTail, seedScrollServer, tracedAsUser } from "./_fixtures/message-scroll-characterization"++test.describe("message scroll characterization", () => {+test("peer receives follow after clamped bottom input without movement", async ({ caseActors }) => {+ test.setTimeout(120_000)+ const actors = await caseActors(["alice", "bob", "carol"])+ const asUser = tracedAsUser(actors)+ const serverId = await seedScrollServer(actors)+ const { seedChannel, seedMessage } = actors.seed++ const channelId = await seedChannel("alice", serverId, `scroll-bottom-input-${Date.now()}`)+ await seedProfile(actors, channelId, 18)+ let tailId = await seedMessage("bob", channelId, "bottom input start\n[keyboard target](https://example.com)")+ await setReadCheckpoint(actors, channelId, tailId)+ const alice = await asUser("alice")+ await alice.page.setViewportSize(VIEWPORT)+ const proxy = await proxyCommunityWebSockets(alice.context)+ await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${channelId}`)+ const scroller = alice.page.getByTestId(tid.messageScroller)+ await expect(scroller.locator('[data-message-list-content]')).toHaveAttribute("data-read-position-ready", "true")+ for (const input of ["click", "wheel", "ArrowDown", "PageDown", "End", "Space"]) {+ await waitForStableTail(scroller, `bottom-${input}`)+ if (input !== "click" && input !== "wheel") {+ await alice.page.getByTestId(tid.message(tailId)).getByRole("link", { name: "Link: https://example.com/" }).focus()+ }+ const before = await waitForCommittedGeometry(scroller)+ expect(before.distanceToEnd).toBeLessThanOrEqual(1)+ const box = await scroller.boundingBox()+ expect(box).not.toBeNull()+ await alice.page.mouse.move(box!.x + box!.width / 2, box!.y + box!.height - 16)+ if (input === "click") await alice.page.mouse.click(box!.x + box!.width / 2, box!.y + box!.height - 16)+ else if (input === "wheel") await alice.page.mouse.wheel(0, 120)+ else await alice.page.keyboard.press(input)+ const after = await waitForCommittedGeometry(scroller)+ expect(after.distanceToEnd).toBeLessThanOrEqual(1)+ expect(Math.abs(after.scrollTop - before.scrollTop)).toBeLessThanOrEqual(1)+ const body = `bottom input ${input} ${Date.now()}\n[keyboard target](https://example.com)`+ tailId = await seedMessage("carol", channelId, body)+ await expect.poll(() => proxy.frames.filter(frame => communityFrameEvents(frame).some(event =>+ event.type === "community:message.create" && event.channelId === channelId && event.message?.id === tailId,+ )).length).toBe(1)+ await expect(alice.page.getByTestId(tid.message(tailId))).toBeVisible()+ await waitForStableTail(scroller, `received-${input}`)+ await expect(alice.page.getByTestId(tid.scrollToPresent)).toHaveCount(0)+ }+ })+})diff --git a/src/web/src/test/e2e-ui/55-reaction-backward-reading.spec.ts b/src/web/src/test/e2e-ui/55-reaction-backward-reading.spec.tsnew file mode 100644index 000000000..eed3cb500--- /dev/null+++ b/src/web/src/test/e2e-ui/55-reaction-backward-reading.spec.ts@@ -0,0 +1,80 @@+import { test, expect } from "./_fixtures/case-fixture"+import { gotoAfterUserWsAuth } from "./_fixtures/actions"+import { communityFrameEvents, proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"+import { beginScrollTraceAnalysis, endScrollTraceAnalysis, installScrollTraceInCurrentDocument, markScrollTrace, startScrollTrace, type ScrollTraceResult } from "./_fixtures/scroll-trace"+import { tid } from "./_fixtures/testids"+import { cancelControlledBackwardGrowth, controlledBackwardGrowth } from "./_fixtures/backward-growth"+import { seedProfile, identity, finishAndAttach, waitForCommittedGeometry, advanceScrollTraceFrame, tracedAsUser } from "./_fixtures/message-scroll-characterization"++test.describe("message scroll characterization", () => {+test("measured reaction updates above the fold preserve reading during repeated controlled backward input", async ({ caseActors }, testInfo) => {+ test.setTimeout(120_000)+ const actors = await caseActors(["alice"])+ const serverId = await actors.seed.seedServer("alice", `Measured reactions ${Date.now()}`)+ const channelId = await actors.seed.seedChannel("alice", serverId, "measured-reactions")+ const { page } = await tracedAsUser(actors)("alice")+ await page.setViewportSize({ width: 390, height: 800 })+ await seedProfile(actors, channelId, 4, false, "alice")+ const messageId = await actors.seed.seedMessage("alice", channelId, "A measured historical message")+ await seedProfile(actors, channelId, 24, false, "alice")+ const reactionFrame = (frame: Parameters<typeof communityFrameEvents>[0]) => communityFrameEvents(frame).some(event =>+ event.type === "community:reaction.add" && event.messageId === messageId)+ const proxy = await proxyCommunityWebSockets(page.context(), { decide: frame => reactionFrame(frame) ? "hold" : "forward" })+ const batches = [["👍", "❤️", "😂", "🎉", "👀"], ["🚀", "✅", "🔥", "💯", "🤔"]]+ await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)+ const scroller = page.getByTestId(tid.messageScroller)+ await expect(scroller.locator('[data-message-list-content]')).toHaveAttribute("data-read-position-ready", "true")+ await waitForCommittedGeometry(scroller)+ await scroller.evaluate(element => { element.scrollTop = 0; element.dispatchEvent(new Event("scroll")) })+ await expect(page.getByTestId(tid.message(messageId))).toHaveCount(1)+ await scroller.evaluate((element, id) => {+ const row = element.querySelector<HTMLElement>(`[data-msg-id="${id}"]`)+ if (!row) throw new Error("The measured reaction message is required")+ element.scrollTop += row.getBoundingClientRect().bottom - element.getBoundingClientRect().top + 256+ element.dispatchEvent(new Event("scroll"))+ }, messageId)+ await waitForCommittedGeometry(scroller)+ await installScrollTraceInCurrentDocument(page)+ await startScrollTrace(page, { scenario: "measured-reactions-backward-growth", identity: identity(channelId, { width: 390, height: 800 }) })+ await beginScrollTraceAnalysis(page, "above-fold-repeated-growth", { commandDirection: "backward" })+ const samples: Array<{ at: number; rowHeight: number; lastInputAt: number }> = []+ let trace: ScrollTraceResult | undefined+ try {+ for (const [round, emojis] of batches.entries()) {+ for (const emoji of emojis) await actors.seed.seedReaction("alice", messageId, emoji)+ await expect.poll(() => proxy.frames.flatMap(communityFrameEvents).filter(event =>+ event.type === "community:reaction.add" && event.messageId === messageId).length).toBe((round + 1) * 5)+ await markScrollTrace(page, `stimulus:reactions-${round}`, { detail: { input: "controlled-wheel-and-scroll", emojis, messageId } })+ const before = await scroller.evaluate(controlledBackwardGrowth, { start: messageId })+ expect(before.growingBottom).toBeLessThan(0)+ expect(proxy.releaseHeld(reactionFrame)).toBeGreaterThan(0)+ await expect.poll(() => page.getByTestId(tid.message(messageId)).evaluate(element => element.closest("[data-index]")!.getBoundingClientRect().height))+ .toBeGreaterThan(before.rowHeight)+ const input = await scroller.evaluate(controlledBackwardGrowth, { finish: true as const })+ expect(input.measurement, "Native row growth must be measured during controlled input").not.toBeNull()+ expect(input.measurement!.direction).toBe("backward")+ expect(input.measurement!.at - input.measurement!.lastInputAt).toBeLessThan(150)+ expect(input.inputDelta).toBeLessThan(0)+ samples.push({ at: before.at, rowHeight: before.rowHeight, lastInputAt: input.measurement!.lastInputAt })+ await advanceScrollTraceFrame(scroller)+ const after = await page.getByTestId(tid.message(before.id)).evaluate(element => {+ const root = element.closest<HTMLElement>("[data-message-scroller-boundary]")?.querySelector<HTMLElement>("[data-pagination-enabled]")+ if (!root) throw new Error("The reading scroller is required")+ return element.getBoundingClientRect().top - root.getBoundingClientRect().top+ })+ await markScrollTrace(page, `observed:reactions-${round}`, { detail: { before, after, input } })+ expect.soft(Math.abs(after - before.top + input.inputDelta), `Reading drift after reaction batch ${round}`).toBeLessThanOrEqual(1)+ }+ } finally {+ await scroller.evaluate(cancelControlledBackwardGrowth)+ await endScrollTraceAnalysis(page, "above-fold-repeated-growth")+ trace = await finishAndAttach(page, testInfo)+ }+ if (!trace) throw new Error("The reaction-growth trace is required")+ for (const sample of samples) {+ const measurement = trace.measurements.find(row => row.id === messageId && row.timestamp >= sample.at && row.height > sample.rowHeight + 1)+ expect(measurement, "A real growing-row measurement must precede the 150ms backward reset").toBeDefined()+ expect(measurement!.timestamp - sample.lastInputAt).toBeLessThan(150)+ }+ })+})diff --git a/src/web/src/test/e2e-ui/55-scroll-loading-prepend-jump.spec.ts b/src/web/src/test/e2e-ui/55-scroll-loading-prepend-jump.spec.tsnew file mode 100644index 000000000..788436e84--- /dev/null+++ b/src/web/src/test/e2e-ui/55-scroll-loading-prepend-jump.spec.ts@@ -0,0 +1,193 @@+import { test, expect } from "./_fixtures/case-fixture"+import { beginScrollTraceAnalysis, endScrollTraceAnalysis, installScrollTrace, installScrollTraceInCurrentDocument, markScrollTrace, scrollTraceSelfTest, startScrollTrace } from "./_fixtures/scroll-trace"+import { tid } from "./_fixtures/testids"+import { VIEWPORT, holdNextRequest, seedProfile, identity, finishAndAttach, expectSkeletonTailGeometry, seedScrollCase, tracedAsUser } from "./_fixtures/message-scroll-characterization"++test.describe("message scroll characterization", () => {+test("cold and warm loading, older prepend, and jump-to-present remain observable", async ({ caseActors }, testInfo) => {+ test.setTimeout(180_000)+ const actors = await caseActors(["alice", "bob", "carol"])+ const asUser = tracedAsUser(actors)+ const { serverId, coldChannelId, loadingChannelId, loadingProfile } = await seedScrollCase(actors)++ const alice = await asUser("alice")+ await alice.page.setViewportSize(VIEWPORT)+ await installScrollTrace(alice.page)+ const initialMessages = await holdNextRequest(actors,+ alice.page,+ `**/api/community/channels/${coldChannelId}/messages**`,+ () => true,+ )+ const image = await holdNextRequest(actors,+ alice.page,+ "**/icon-512.png?scroll-trace=1",+ () => true,+ )+ await alice.page.goto(`/c/channels/${serverId}`, { waitUntil: "commit" })+ await alice.page.getByTestId(tid.channelRow(coldChannelId)).click()+ const initialUrl = await initialMessages.matched+ expect(initialUrl.searchParams.has("anchor")).toBe(false)+ const scroller = alice.page.getByTestId(tid.messageScroller)+ await expect(scroller.locator('[data-slot="skeleton"]').first()).toBeVisible({ timeout: 20_000 })+ await expectSkeletonTailGeometry(alice.page, 1280, "desktop cold skeleton")+ const selfTest = await scrollTraceSelfTest(alice.page)+ expect(selfTest).toMatchObject({+ getterValue: 7,+ methodValue: 8,+ setterError: "RangeError",+ methodError: "RangeError",+ receiverPreserved: true,+ restored: true,+ unsupportedUntouched: true,+ })+ await startScrollTrace(alice.page, {+ scenario: "cold-load-and-async-row",+ identity: identity(coldChannelId),+ })+ await beginScrollTraceAnalysis(alice.page, "cold-load-and-async-row", {+ dataTransitionSource: "initial-cold",+ })+ await markScrollTrace(alice.page, "cold-request-held", { dataTransitionSource: "initial-cold" })+ const coldProfile = await seedProfile(actors, coldChannelId, 12, true, "alice")+ initialMessages.release()+ await image.matched+ await expect(alice.page.getByTestId(tid.message(coldProfile.ids.at(-1)!))).toBeVisible({ timeout: 30_000 })+ await markScrollTrace(alice.page, "async-image-release", {+ detail: { position: "tail", asset: "local-fixture" },+ })+ image.release()+ await expect(alice.page.getByTestId(tid.message(coldProfile.ids.at(-1)!)).locator("img")).toBeVisible()+ await endScrollTraceAnalysis(alice.page, "cold-load-and-async-row")+ const cold = await finishAndAttach(alice.page, testInfo)+ expect(cold.frames.some((frame) => frame.loaders.top.mounted || frame.rows.length === 0)).toBe(true)+ await initialMessages.dispose()+ await image.dispose()++ const mobile = await asUser("alice")+ await mobile.page.setViewportSize({ width: 390, height: 844 })+ const mobileInitialMessages = await holdNextRequest(actors,+ mobile.page,+ `**/api/community/channels/${coldChannelId}/messages**`,+ () => true,+ )+ await mobile.page.goto(`/c/channels/${serverId}`, { waitUntil: "commit" })+ await mobile.page.getByTestId(tid.channelRow(coldChannelId)).click()+ await mobileInitialMessages.matched+ await expect(mobile.page.getByTestId(tid.messageScroller)+ .locator('[data-slot="skeleton"]').first()).toBeVisible({ timeout: 20_000 })+ await expectSkeletonTailGeometry(mobile.page, 390, "mobile cold skeleton")+ mobileInitialMessages.release()+ await expect(mobile.page.getByTestId(tid.message(coldProfile.ids.at(-1)!)))+ .toBeVisible({ timeout: 30_000 })+ await mobileInitialMessages.dispose()++ await installScrollTraceInCurrentDocument(alice.page)+ await alice.page.getByTestId(tid.channelRow(loadingChannelId)).click()+ await alice.page.waitForURL(new RegExp(loadingChannelId), { waitUntil: "commit" })+ await expect(alice.page.getByTestId(tid.messageScroller)).toBeVisible()+ const warmRequest = await holdNextRequest(actors,+ alice.page,+ `**/api/community/channels/${coldChannelId}/messages**`,+ () => true,+ { required: false },+ )+ await alice.page.getByTestId(tid.channelRow(coldChannelId)).click()+ await alice.page.waitForURL(new RegExp(coldChannelId), { waitUntil: "commit" })+ await expect(alice.page.getByTestId(tid.message(coldProfile.ids.at(-1)!))).toBeVisible({ timeout: 20_000 })+ await startScrollTrace(alice.page, {+ scenario: "warm-cache-reuse",+ identity: identity(coldChannelId),+ estimatedSizes: coldProfile.estimates,+ })+ await beginScrollTraceAnalysis(alice.page, "warm-cache-reuse", {+ dataTransitionSource: "initial-cache",+ })+ await markScrollTrace(alice.page, "cached-rows-painted", {+ dataTransitionSource: "initial-cache",+ detail: { renderedBeforeRelease: true, revalidationMatched: warmRequest.hasMatched() },+ })+ warmRequest.release()+ await endScrollTraceAnalysis(alice.page, "warm-cache-reuse")+ await finishAndAttach(alice.page, testInfo)+ await warmRequest.dispose()++ const anchored = await asUser("alice")+ await anchored.page.setViewportSize(VIEWPORT)+ await installScrollTrace(anchored.page)+ await anchored.page.goto(`/c/channels/${serverId}/${loadingChannelId}`, { waitUntil: "commit" })+ const anchoredNewDivider = anchored.page.getByTestId(tid.newDivider)+ await expect(async () => {+ expect(await anchoredNewDivider.count()).toBe(1)+ expect(await anchoredNewDivider.isVisible()).toBe(true)+ }).toPass({ timeout: 30_000 })+ await expect(anchored.page.getByTestId(tid.messageScroller)).toHaveAttribute("data-pagination-enabled", "true")+ const older = await holdNextRequest(actors,+ anchored.page,+ `**/api/community/channels/${loadingChannelId}/messages**`,+ (url) => url.searchParams.has("cursor"),+ )+ await startScrollTrace(anchored.page, {+ scenario: "older-loading-prepend",+ identity: identity(loadingChannelId),+ estimatedSizes: loadingProfile.estimates,+ })+ await beginScrollTraceAnalysis(anchored.page, "older-loading-prepend", {+ dataTransitionSource: "older-page",+ commandDirection: "backward",+ })+ await markScrollTrace(anchored.page, "stimulus:older-boundary", { dataTransitionSource: "older-page" })+ await anchored.page.getByTestId(tid.messageScroller).evaluate((element) => {+ element.scrollTop = 0+ element.dispatchEvent(new Event("scroll"))+ })+ await older.matched+ await expect(anchored.page.getByText("Loading older messages…", { exact: true })).toBeVisible()+ older.release()+ await expect(anchored.page.getByText("Loading older messages…", { exact: true })).toHaveCount(0)+ await endScrollTraceAnalysis(anchored.page, "older-loading-prepend")+ const olderTrace = await finishAndAttach(anchored.page, testInfo)+ expect(olderTrace.marks.filter((mark) =>+ mark.name === "stimulus:older-boundary"+ && mark.dataTransitionSource === "older-page")).toHaveLength(1)+ await older.dispose()++ await installScrollTraceInCurrentDocument(anchored.page)+ const present = anchored.page.getByTestId(tid.scrollToPresent)+ await expect(present).toBeVisible({ timeout: 30_000 })+ let newestGets = 0+ anchored.page.on("request", (request) => {+ const url = new URL(request.url())+ if (+ request.method() === "GET"+ && url.pathname === `/api/community/channels/${loadingChannelId}/messages`+ && url.search === ""+ ) newestGets += 1+ })+ const newest = await holdNextRequest(actors,+ anchored.page,+ `**/api/community/channels/${loadingChannelId}/messages**`,+ (url) => url.search === "",+ )+ await startScrollTrace(anchored.page, {+ scenario: "newer-loading-present",+ identity: identity(loadingChannelId),+ estimatedSizes: loadingProfile.estimates,+ })+ await beginScrollTraceAnalysis(anchored.page, "newer-loading-present", {+ dataTransitionSource: "newer-page",+ commandDirection: "forward",+ })+ await markScrollTrace(anchored.page, "stimulus:jump-present", { dataTransitionSource: "newer-page" })+ await present.click()+ await newest.matched+ newest.release()+ await expect(anchored.page.getByTestId(tid.message(loadingProfile.ids.at(-1)!))).toBeVisible({ timeout: 30_000 })+ await expect(present).toHaveCount(0)+ await endScrollTraceAnalysis(anchored.page, "newer-loading-present")+ await finishAndAttach(anchored.page, testInfo)+ await expect.poll(() => newestGets).toBe(1)+ await anchored.page.waitForTimeout(500)+ expect(newestGets).toBe(1)+ await newest.dispose()+ })+})diff --git a/src/web/src/test/e2e-ui/55-upward-release-resize.spec.ts b/src/web/src/test/e2e-ui/55-upward-release-resize.spec.tsnew file mode 100644index 000000000..bdc8e2623--- /dev/null+++ b/src/web/src/test/e2e-ui/55-upward-release-resize.spec.ts@@ -0,0 +1,55 @@+import { test, expect } from "./_fixtures/case-fixture"+import { gotoAfterUserWsAuth } from "./_fixtures/actions"+import { beginScrollTraceAnalysis, endScrollTraceAnalysis, installScrollTraceInCurrentDocument, markScrollTrace, startScrollTrace } from "./_fixtures/scroll-trace"+import { tid } from "./_fixtures/testids"+import { VIEWPORT, seedResizableHtmlPreview, seedProfile, identity, finishAndAttach, establishScrollDistancePrecondition, advanceScrollTraceFrame, tracedAsUser } from "./_fixtures/message-scroll-characterization"++test.describe("message scroll characterization", () => {+test("controlled upward release before native movement prevents HTML tail resize follow", async ({ caseActors }, testInfo) => {+ test.setTimeout(120_000)+ const actors = await caseActors(["alice"])+ const serverId = await actors.seed.seedServer("alice", `Released HTML ${Date.now()}`)+ const channelId = await actors.seed.seedChannel("alice", serverId, "released-html")+ const { page } = await tracedAsUser(actors)("alice")+ await page.setViewportSize(VIEWPORT)+ await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)+ await seedProfile(actors, channelId, 24, false, "alice")+ const { attachmentId } = await seedResizableHtmlPreview(page, channelId)+ const scroller = page.getByTestId(tid.messageScroller)+ const iframe = page.getByTestId(tid.htmlPreviewFrame(attachmentId))+ await expect(page.getByTestId(tid.htmlPreview(attachmentId))).toHaveAttribute("data-html-preview-status", "ready")+ await expect(iframe).toHaveCSS("height", "160px")+ await installScrollTraceInCurrentDocument(page)+ await startScrollTrace(page, { scenario: "released-html-tail-growth", identity: identity(channelId) })+ try {+ for (const distance of [0, 1, 2]) {+ await iframe.evaluate(element => (element as HTMLIFrameElement).contentWindow?.postMessage({ type: "scroll-fixture-height", height: 160 }, "*"))+ await expect(iframe).toHaveCSS("height", "160px")+ await establishScrollDistancePrecondition(scroller, `released-tail-${distance}`, distance, 0.05)+ await beginScrollTraceAnalysis(page, `released-tail-${distance}`)+ try {+ const before = await scroller.evaluate((element, frameId) => {+ const frame = element.querySelector<HTMLIFrameElement>(`[data-testid="${frameId}"]`)+ if (!frame?.contentWindow) throw new Error("A real mounted HTML preview is required")+ const wheel = new WheelEvent("wheel", { deltaY: -20, bubbles: true })+ element.dispatchEvent(wheel)+ const result = { top: element.scrollTop, distance: element.scrollHeight - element.clientHeight - element.scrollTop,+ trusted: wheel.isTrusted }+ frame.contentWindow.postMessage({ type: "scroll-fixture-height", height: 260 }, "*")+ return result+ }, tid.htmlPreviewFrame(attachmentId))+ await markScrollTrace(page, `stimulus:released-tail-${distance}`, { detail: before })+ await expect(iframe).toHaveCSS("height", "260px")+ await advanceScrollTraceFrame(scroller)+ const after = await scroller.evaluate(element => element.scrollTop)+ await markScrollTrace(page, `observed:released-tail-${distance}`, { detail: { before, after } })+ expect.soft(Math.abs(after - before.top), `Released reader movement at ${distance}px`).toBeLessThanOrEqual(1)+ } finally {+ await endScrollTraceAnalysis(page, `released-tail-${distance}`)+ }+ }+ } finally {+ await finishAndAttach(page, testInfo)+ }+ })+})diff --git a/src/web/src/test/e2e-ui/63-mobile-notification-activation.spec.ts b/src/web/src/test/e2e-ui/63-mobile-notification-activation.spec.tsnew file mode 100644index 000000000..d627e21a7--- /dev/null+++ b/src/web/src/test/e2e-ui/63-mobile-notification-activation.spec.ts@@ -0,0 +1,48 @@+import { devices } from "@playwright/test"+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"+import { expect, test } from "./_fixtures/case-fixture"+import { composerEditable } from "./_fixtures/actions"+import { tid } from "./_fixtures/testids"+import { WEB_URL } from "./_setup/paths"+import { type Bridge, installMobileBridge, resumeActivation, prepareCase1 } from "./_fixtures/mobile-notification-activation"++test.describe("mobile notification chat routes (native bridge simulation)", () => {+for (const mode of ["cold", "resume"] as const) {+for (const surface of ["dm", "channel"] as const) {+test(`${mode} ${surface} opens chat without a context sheet`, async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelId, channelMessageId, dmId, dmMessageId, captureMessageDoor } = await prepareCase1(actors)++ const { page } = await asUser("bob", devices["iPhone 13"])+ const targetId = surface === "dm" ? dmId : channelId+ const messageId = surface === "dm" ? dmMessageId : channelMessageId+ const activation = { notificationId: crypto.randomUUID(), targetId, messageId }+ await installMobileBridge(page, mode === "cold" ? activation : null)+ const door = await captureMessageDoor(page, targetId, messageId)+ await page.goto("/c/me/friends")+ if (mode === "resume") await resumeActivation(page, activation)+ const path = surface === "dm" ? `/c/me/${targetId}` : `/c/channels/${serverId}/${targetId}`+ await expect(page).toHaveURL(`${WEB_URL}${path}`)+ await expect.poll(() => page.evaluate(() => (+ window as typeof window & { __mobileNotificationQa: Bridge }+ ).__mobileNotificationQa.dismissed)).toEqual([activation.notificationId])+ expect(await page.evaluate(() => (window as typeof window & { __mobileNotificationQa: Bridge }).__mobileNotificationQa.documentLoads)).toBe(1)+ await expect(composerEditable(page)).toBeVisible({ timeout: 30_000 })+ await expect(page.getByTestId(tid.message(messageId))).toBeVisible()+ await expect(page.locator('[data-slot="sheet-content"]')).toHaveCount(0)+ const evidence = door.evidence()+ if (evidence) {+ expect(evidence.status).toBe(200)+ expect(evidence.payload.contractVersion).toBe(BUSINESS_SCHEMA_VERSION)+ expect(evidence.payload.message.id).toBe(messageId)+ expect(evidence.payload.message.channelId).toBe(targetId)+ expect(evidence.payload.channelId).toBe(targetId)+ }+ else expect(door.requestCount()).toBe(0)+ await testInfo.attach("message-door-evidence", { body: JSON.stringify({ simulation: "iPhone UA + Tauri command shim + browser visibility events", navigation: evidence ? "message resolution" : "cached conversation", evidence, messageDoorRequests: door.requestCount(), targetId, messageId, url: page.url() }), contentType: "application/json" })+ await testInfo.attach("chat", { body: await page.screenshot(), contentType: "image/png" })+ })+}+}+})diff --git a/src/web/src/test/e2e-ui/63-mobile-notification-cached-activation.spec.ts b/src/web/src/test/e2e-ui/63-mobile-notification-cached-activation.spec.tsnew file mode 100644index 000000000..9eeb4d488--- /dev/null+++ b/src/web/src/test/e2e-ui/63-mobile-notification-cached-activation.spec.ts@@ -0,0 +1,45 @@+import { devices } from "@playwright/test"+import { expect, test } from "./_fixtures/case-fixture"+import { composerEditable } from "./_fixtures/actions"+import { tid } from "./_fixtures/testids"+import { WEB_URL } from "./_setup/paths"+import { type Bridge, installMobileBridge, resumeActivation, foregroundActivation, prepareCase1 } from "./_fixtures/mobile-notification-activation"++test.describe("mobile notification chat routes (native bridge simulation)", () => {+for (const mode of ["foreground", "resume"] as const) {+for (const surface of ["dm", "channel"] as const) {+test(`cached ${mode} ${surface} opens directly in the same document`, async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["alice", "bob"])+ const { serverId, channelId, channelMessageId, dmId, dmMessageId, captureMessageDoor } = await prepareCase1(actors)+ const { page } = await actors.asUser("bob", devices["iPhone 13"])+ const targetId = surface === "dm" ? dmId : channelId+ const messageId = surface === "dm" ? dmMessageId : channelMessageId+ const path = surface === "dm" ? `/c/me/${targetId}` : `/c/channels/${serverId}/${targetId}`+ const parent = surface === "dm" ? "/c/me" : `/c/channels/${serverId}`+ const activation = { notificationId: crypto.randomUUID(), targetId, messageId }+ await installMobileBridge(page, null)+ const door = await captureMessageDoor(page, targetId, messageId)+ await page.goto(path)+ await expect(composerEditable(page)).toBeVisible({ timeout: 30_000 })+ await expect(page.getByTestId(tid.message(messageId))).toBeVisible()+ const timeOrigin = await page.evaluate(() => performance.timeOrigin)+ await page.getByRole("button", { name: "Back", exact: true }).click()+ await expect(page).toHaveURL(`${WEB_URL}${parent}`)+ if (mode === "foreground") await foregroundActivation(page, activation)+ else await resumeActivation(page, activation)+ await expect(page).toHaveURL(`${WEB_URL}${path}`)+ await expect(composerEditable(page)).toBeVisible()+ await expect(page.getByTestId(tid.message(messageId))).toBeVisible()+ await expect.poll(() => page.evaluate(() => (+ window as typeof window & { __mobileNotificationQa: Bridge }+ ).__mobileNotificationQa.dismissed)).toEqual([activation.notificationId])+ expect(door.requestCount()).toBe(0)+ expect(await page.evaluate(() => performance.timeOrigin)).toBe(timeOrigin)+ expect(await page.evaluate(() => (window as typeof window & { __mobileNotificationQa: Bridge }).__mobileNotificationQa.documentLoads)).toBe(1)+ await expect(page.locator('[data-slot="sheet-content"]')).toHaveCount(0)+ await testInfo.attach("cached-navigation-evidence", { body: JSON.stringify({ simulation: "iPhone UA + Tauri command shim", mode, surface, targetId, messageId, messageDoorRequests: door.requestCount(), timeOrigin, documentLoads: 1, url: page.url() }), contentType: "application/json" })+ await testInfo.attach("chat", { body: await page.screenshot(), contentType: "image/png" })+ })+}+}+})diff --git a/src/web/src/test/e2e-ui/63-mobile-notification-chat-route.spec.ts b/src/web/src/test/e2e-ui/63-mobile-notification-chat-route.spec.tsdeleted file mode 100644index 50bbcee16..000000000--- a/src/web/src/test/e2e-ui/63-mobile-notification-chat-route.spec.ts+++ /dev/null@@ -1,353 +0,0 @@-import type { z } from "zod"-import { communityFixtureFetch } from "./_fixtures/business-contract"-import { devices, type Page } from "@playwright/test"-import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER, DEFAULT_MESSAGE_PAGE_SIZE, type CommunityConversationEntryRead, CommunityMessageReadSchema } from "@alook/shared"-import { expect, test } from "./_fixtures/case-fixture"-import { composerEditable } from "./_fixtures/actions"-import { expectPublicCommunityDocument } from "./_fixtures/community-ssr-frame"--import { tid } from "./_fixtures/testids"-import { WEB_URL } from "./_setup/paths"-import type { CaseActors } from "./_fixtures/case-fixture"--type Activation = { notificationId: string; messageId: string; targetId: string }-type Bridge = { pending: Activation | null; listener: unknown; takes: number; dismissed: string[]; visibility: DocumentVisibilityState; documentLoads: number }--async function installMobileBridge(page: Page, activation: Activation | null) {- await page.addInitScript((initial) => {- const key = `qa-mobile-consumed:${initial?.notificationId}`- const dismissedKey = "qa-mobile-notification-dismissed"- const documentLoads = Number(sessionStorage.getItem("qa-mobile-document-loads") ?? "0") + 1- sessionStorage.setItem("qa-mobile-document-loads", String(documentLoads))- const state: Bridge = {- documentLoads,- pending: initial && !sessionStorage.getItem(key) ? initial : null,- listener: null,- takes: 0,- dismissed: JSON.parse(sessionStorage.getItem(dismissedKey) ?? "[]") as string[],- visibility: "visible",- }- Object.defineProperty(document, "visibilityState", { configurable: true, get: () => state.visibility })- Object.defineProperty(window, "__mobileNotificationQa", { configurable: true, value: state })- class Channel { onmessage?: (value: unknown) => void }- Object.defineProperty(window, "__TAURI__", {- configurable: true,- value: { core: { Channel, invoke: async (command: string, args?: Record<string, unknown>) => {- if (command === "mobile_system_notification_listen") { state.listener = args?.channel; return 1 }- if (command === "mobile_system_notification_take_activation") {- state.takes += 1- const value = state.pending- state.pending = null- if (value) sessionStorage.setItem(key, "1")- return value- }- if (command === "mobile_system_notification_check_permission" || command === "mobile_system_notification_request_permission") return { permissionState: "prompt" }- if (command === "mobile_system_notification_dismiss") {- state.dismissed.push(args?.notificationId as string)- sessionStorage.setItem(dismissedKey, JSON.stringify(state.dismissed))- return undefined- }- return undefined- } } },- })- }, activation)-}--async function resumeActivation(page: Page, activation: Activation) {- await expect.poll(() => page.evaluate(() => (window as typeof window & { __mobileNotificationQa: Bridge }).__mobileNotificationQa.takes)).toBeGreaterThan(0)- await page.evaluate((value) => {- const state = (window as typeof window & { __mobileNotificationQa: Bridge }).__mobileNotificationQa- state.visibility = "hidden"- document.dispatchEvent(new Event("visibilitychange"))- state.pending = value- state.visibility = "visible"- document.dispatchEvent(new Event("visibilitychange"))- }, activation)-}--async function foregroundActivation(page: Page, activation: Activation) {- await expect.poll(() => page.evaluate(() => Boolean((- window as typeof window & { __mobileNotificationQa: Bridge }- ).__mobileNotificationQa.listener))).toBe(true)- await page.evaluate((value) => {- const state = (window as typeof window & { __mobileNotificationQa: Bridge }).__mobileNotificationQa- state.pending = value- ;(state.listener as { onmessage: (value: unknown) => void }).onmessage({})- }, activation)-}--type MessageDoorEvidence = {- status: number- payload: z.infer<typeof CommunityMessageReadSchema>-}--test.describe("mobile notification chat routes (native bridge simulation)", () => {- async function prepareCase1(actors: CaseActors) {- async function deleteAsAlice(path: string) {- const response = await communityFixtureFetch(`${WEB_URL}${path}`, { method: "DELETE", headers: { Cookie: sessionCookie("alice"), Origin: WEB_URL } })- expect(response.ok, `${path}: ${response.status}`).toBeTruthy()- }- async function captureMessageDoor(page: Page, targetId: string, messageId: string) {- let observed: MessageDoorEvidence | undefined- let requests = 0- let capture!: (evidence: MessageDoorEvidence) => void- let fail!: (error: unknown) => void- const result = new Promise<MessageDoorEvidence>((resolve, reject) => {- capture = resolve- fail = reject- })- void result.catch(() => undefined)- await page.route((url) => url.pathname === `/api/community/messages/${messageId}`, async (route) => {- requests += 1- try {- const response = await route.fetch()- const payload = await response.json()- const evidence = { status: response.status(), payload }- if (response.ok())- expect(payload.channelId).toBe(targetId)- observed = evidence- await route.fulfill({ response })- capture(evidence)- }- catch (error) {- fail(error)- await route.abort()- }- })- return { result, evidence: () => observed, requestCount: () => requests }- }- const { sessionCookie, userId } = actors- const { seedChannel, seedDm, seedDmMessage, seedFriendship, seedJoinServer, seedMessage, seedServer } = actors.seed- const serverId: string = await seedServer("alice", `mobile-route-${Date.now()}`)- const channelId: string = await seedChannel("alice", serverId, "notification-chat")- await seedJoinServer("alice", "bob", serverId)- const channelMessageId: string = await seedMessage("alice", channelId, "Channel notification route evidence")- await seedFriendship("alice", "bob", userId("bob"))- const dmId: string = await seedDm("alice", userId("bob"))- const dmMessageId: string = await seedDmMessage("alice", dmId, "DM notification route evidence")- const seqs = await Promise.all([[dmId, dmMessageId], [channelId, channelMessageId]].map(async ([targetId, messageId]) => {- const response = await communityFixtureFetch(`${WEB_URL}/api/community/channels/${targetId}/messages?anchor=${messageId}&limit=1`, { headers: { Cookie: sessionCookie("bob") } })- expect(response.status).toBe(200)- const payload = await response.json() as {- messages: Array<{- id: string- seq: number- }>- }- return payload.messages.find((message) => message.id === messageId)!.seq- }));- const [dmSeq, channelSeq] = seqs- return { deleteAsAlice, serverId, channelId, channelMessageId, dmId, dmMessageId, dmSeq, channelSeq, captureMessageDoor }- }-- for (const mode of ["cold", "resume"] as const) {- for (const surface of ["dm", "channel"] as const) {- test(`${mode} ${surface} opens chat without a context sheet`, async ({ caseActors }, testInfo) => {- const actors = await caseActors(["alice", "bob"])- const { asUser } = actors- const { serverId, channelId, channelMessageId, dmId, dmMessageId, captureMessageDoor } = await prepareCase1(actors)-- const { page } = await asUser("bob", devices["iPhone 13"])- const targetId = surface === "dm" ? dmId : channelId- const messageId = surface === "dm" ? dmMessageId : channelMessageId- const activation = { notificationId: crypto.randomUUID(), targetId, messageId }- await installMobileBridge(page, mode === "cold" ? activation : null)- const door = await captureMessageDoor(page, targetId, messageId)- await page.goto("/c/me/friends")- if (mode === "resume") await resumeActivation(page, activation)- const path = surface === "dm" ? `/c/me/${targetId}` : `/c/channels/${serverId}/${targetId}`- await expect(page).toHaveURL(`${WEB_URL}${path}`)- await expect.poll(() => page.evaluate(() => (- window as typeof window & { __mobileNotificationQa: Bridge }- ).__mobileNotificationQa.dismissed)).toEqual([activation.notificationId])- expect(await page.evaluate(() => (window as typeof window & { __mobileNotificationQa: Bridge }).__mobileNotificationQa.documentLoads)).toBe(1)- await expect(composerEditable(page)).toBeVisible({ timeout: 30_000 })- await expect(page.getByTestId(tid.message(messageId))).toBeVisible()- await expect(page.locator('[data-slot="sheet-content"]')).toHaveCount(0)- const evidence = door.evidence()- if (evidence) {- expect(evidence.status).toBe(200)- expect(evidence.payload.contractVersion).toBe(BUSINESS_SCHEMA_VERSION)- expect(evidence.payload.message.id).toBe(messageId)- expect(evidence.payload.message.channelId).toBe(targetId)- expect(evidence.payload.channelId).toBe(targetId)- }- else expect(door.requestCount()).toBe(0)- await testInfo.attach("message-door-evidence", { body: JSON.stringify({ simulation: "iPhone UA + Tauri command shim + browser visibility events", navigation: evidence ? "message resolution" : "cached conversation", evidence, messageDoorRequests: door.requestCount(), targetId, messageId, url: page.url() }), contentType: "application/json" })- await testInfo.attach("chat", { body: await page.screenshot(), contentType: "image/png" })- })- }- }-- for (const mode of ["foreground", "resume"] as const) {- for (const surface of ["dm", "channel"] as const) {- test(`cached ${mode} ${surface} opens directly in the same document`, async ({ caseActors }, testInfo) => {- const actors = await caseActors(["alice", "bob"])- const { serverId, channelId, channelMessageId, dmId, dmMessageId, captureMessageDoor } = await prepareCase1(actors)- const { page } = await actors.asUser("bob", devices["iPhone 13"])- const targetId = surface === "dm" ? dmId : channelId- const messageId = surface === "dm" ? dmMessageId : channelMessageId- const path = surface === "dm" ? `/c/me/${targetId}` : `/c/channels/${serverId}/${targetId}`- const parent = surface === "dm" ? "/c/me" : `/c/channels/${serverId}`- const activation = { notificationId: crypto.randomUUID(), targetId, messageId }- await installMobileBridge(page, null)- const door = await captureMessageDoor(page, targetId, messageId)- await page.goto(path)- await expect(composerEditable(page)).toBeVisible({ timeout: 30_000 })- await expect(page.getByTestId(tid.message(messageId))).toBeVisible()- const timeOrigin = await page.evaluate(() => performance.timeOrigin)- await page.getByRole("button", { name: "Back", exact: true }).click()- await expect(page).toHaveURL(`${WEB_URL}${parent}`)- if (mode === "foreground") await foregroundActivation(page, activation)- else await resumeActivation(page, activation)- await expect(page).toHaveURL(`${WEB_URL}${path}`)- await expect(composerEditable(page)).toBeVisible()- await expect(page.getByTestId(tid.message(messageId))).toBeVisible()- await expect.poll(() => page.evaluate(() => (- window as typeof window & { __mobileNotificationQa: Bridge }- ).__mobileNotificationQa.dismissed)).toEqual([activation.notificationId])- expect(door.requestCount()).toBe(0)- expect(await page.evaluate(() => performance.timeOrigin)).toBe(timeOrigin)- expect(await page.evaluate(() => (window as typeof window & { __mobileNotificationQa: Bridge }).__mobileNotificationQa.documentLoads)).toBe(1)- await expect(page.locator('[data-slot="sheet-content"]')).toHaveCount(0)- await testInfo.attach("cached-navigation-evidence", { body: JSON.stringify({ simulation: "iPhone UA + Tauri command shim", mode, surface, targetId, messageId, messageDoorRequests: door.requestCount(), timeOrigin, documentLoads: 1, url: page.url() }), contentType: "application/json" })- await testInfo.attach("chat", { body: await page.screenshot(), contentType: "image/png" })- })- }- }-- for (const kind of ["deleted", "revoked"] as const) {- test(`${kind} target shows an unavailable message page with the normal Inbox action`, async ({ caseActors }, testInfo) => {- const actors = await caseActors(["alice", "bob"])- const { asUser, userId } = actors- const { seedCategory, seedChannel, seedChannelMember, seedMessage } = actors.seed- const { deleteAsAlice, serverId, captureMessageDoor } = await prepareCase1(actors)-- const categoryId = kind === "revoked" ? await seedCategory("alice", serverId, `private-${Date.now()}`, { private: true }) : undefined- const targetId = await seedChannel("alice", serverId, `${kind}-${Date.now()}`, "text", categoryId)- if (kind === "revoked") await seedChannelMember("alice", targetId, userId("bob"))- const messageId = await seedMessage("alice", targetId, `${kind} target evidence`)- await deleteAsAlice(kind === "deleted" ? `/api/community/channels/${targetId}` : `/api/community/channels/${targetId}/members/${userId("bob")}`)- const { page } = await asUser("bob", devices["iPhone 13"])- await installMobileBridge(page, null)- const door = await captureMessageDoor(page, targetId, messageId)- const route = `/c/channels/${serverId}`- await page.goto(route)- await expect(page.getByTestId(tid.inboxTrigger)).toBeVisible({ timeout: 30_000 })- const activation = { notificationId: crypto.randomUUID(), targetId, messageId }- await resumeActivation(page, activation)- const { status } = await door.result- expect([403, 404]).toContain(status)- await expect(page).toHaveURL(`${WEB_URL}/c/messages/${messageId}`)- const unavailableAlert = page.getByTestId(tid.messageRouteAlert(messageId))- await expect(unavailableAlert).toHaveCount(1)- await expect(unavailableAlert).toBeVisible()- await expect(unavailableAlert).toHaveText("This conversation is unavailable.")- await page.getByRole("button", { name: "Open Inbox", exact: true }).click()- await expect(page).toHaveURL(`${WEB_URL}/c/me`)- await expect(page.getByTestId(tid.inboxTrigger)).toBeVisible()- await expect(page.getByTestId(tid.inboxTrigger)).toHaveAttribute("aria-expanded", "true")- const inbox = page.getByTestId(tid.userBarExtension)- await expect(inbox).toHaveCount(1)- await expect(inbox).toBeVisible()- await expect(inbox.locator("xpath=ancestor::*[@inert or @aria-hidden='true']")).toHaveCount(0)- await expect.poll(() => page.evaluate(() => (- window as typeof window & { __mobileNotificationQa: Bridge }- ).__mobileNotificationQa.dismissed)).toEqual([activation.notificationId])- const inboxHref = page.url()- await page.getByRole("link", { name: /^Friends(?:, \d+ new requests)?$/ }).click()- await expect(page).toHaveURL(`${WEB_URL}/c/me/friends`)- await expect(page.getByTestId(tid.inboxTrigger)).toHaveAttribute("aria-expanded", "false")- await expect(page.getByTestId(tid.userBarExtension)).toHaveCount(0)- await expect.poll(() => page.evaluate(() => (- window as typeof window & { __mobileNotificationQa: Bridge }- ).__mobileNotificationQa.dismissed)).toEqual([activation.notificationId])- await testInfo.attach("fallback-evidence", { body: JSON.stringify({ kind, status, inboxHref, url: page.url() }), contentType: "application/json" })- })- }-- for (const surface of ["dm", "channel"] as const) {- test(`ordinary ${surface} seq permalink retains message context`, async ({ caseActors }, testInfo) => {- const actors = await caseActors(["alice", "bob"])- const { asUser } = actors- const { serverId, channelId, channelMessageId, dmId, dmMessageId, dmSeq, channelSeq } = await prepareCase1(actors)-- const { page } = await asUser("bob", devices["iPhone 13"])- const targetId = surface === "dm" ? dmId : channelId- const messageId = surface === "dm" ? dmMessageId : channelMessageId- const route = surface === "dm" ? `/c/me/${targetId}` : `/c/channels/${serverId}/${targetId}`- const responsePromise = page.waitForResponse((response) => {- const url = new URL(response.url())- return url.pathname === `/api/community/channels/${targetId}/messages`- && url.searchParams.get("anchor") === messageId && response.ok()- })- await page.goto(`${route}?seq=${surface === "dm" ? dmSeq : channelSeq}`)- const response = await responsePromise- const payload = await response.json()- const content = surface === "dm" ? "DM notification route evidence" : "Channel notification route evidence"- expect(payload.messages).toEqual(expect.arrayContaining([expect.objectContaining({ id: messageId, content })]))- const sheet = page.locator('[data-slot="sheet-content"]')- await expect(sheet).toBeVisible()- await expect(sheet.locator('[data-anchor-row="1"]').getByText(- content, { exact: true },- )).toBeVisible()- await testInfo.attach("permalink-context", { body: JSON.stringify({ status: response.status(), messageId, url: page.url() }), contentType: "application/json" })- await testInfo.attach("context", { body: await page.screenshot(), contentType: "image/png" })- })- }-- test("ordinary channel msg permalink retains its message anchor", async ({ caseActors }, testInfo) => {- const actors = await caseActors(["alice", "bob"])- const { asUser } = actors- const { serverId, channelId, channelMessageId } = await prepareCase1(actors)- const laterIds: string[] = []- for (let index = 0; index < DEFAULT_MESSAGE_PAGE_SIZE + 8; index += 1) {- laterIds.push(await actors.seed.seedMessage("alice", channelId, `Later window message ${index}`))- }- const readPointer = laterIds[DEFAULT_MESSAGE_PAGE_SIZE]- const checkpoint = await communityFixtureFetch(`${WEB_URL}/api/community/channels/${channelId}/read`, {- method: "PUT",- headers: { Cookie: actors.sessionCookie("bob"), Origin: WEB_URL, "Content-Type": "application/json" },- body: JSON.stringify({ lastReadMessageId: readPointer }),- })- expect(checkpoint.ok).toBe(true)- const defaultResponse = await communityFixtureFetch(`${WEB_URL}/api/community/channels/${channelId}/messages?entry=1`, { headers: { Cookie: actors.sessionCookie("bob"), [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })- expect(defaultResponse.ok, `entry precondition status ${defaultResponse.status}`).toBe(true)- const defaultEntry = await defaultResponse.json() as CommunityConversationEntryRead- expect(defaultEntry.selection).toEqual({ reason: "read_pointer", anchorMessageId: readPointer })- expect(defaultEntry.messages.some(message => message.id === channelMessageId)).toBe(false)- expect(readPointer).not.toBe(laterIds.at(-1))-- const { page } = await asUser("bob", devices["iPhone 13"])- const entryResponse = page.waitForResponse(response => {- const url = new URL(response.url())- return response.request().method() === "GET" && url.pathname === `/api/community/channels/${channelId}/messages`- && url.searchParams.get("entry") === "1" && url.searchParams.get("anchor") === channelMessageId- })- const response = await page.goto(`/c/channels/${serverId}/${channelId}?msg=${channelMessageId}`)- expect(response?.ok()).toBe(true)- const html = await response!.text()- expectPublicCommunityDocument(html)- const explicitResponse = await entryResponse- expect(explicitResponse.ok()).toBe(true)- const explicitEntry = await explicitResponse.json() as CommunityConversationEntryRead- expect(explicitEntry.selection).toEqual({ reason: "explicit_anchor", anchorMessageId: channelMessageId })- expect(explicitEntry.surfaceReceipt).toEqual({ channelId, surfaceKind: "channel" })- expect(explicitEntry.messages).toEqual(expect.arrayContaining([expect.objectContaining({ id: channelMessageId })]))- expect(explicitEntry.messages.some(message => message.id === readPointer)).toBe(false)- const target = page.getByTestId(tid.message(channelMessageId))- await expect(target).toBeVisible()- await expect(target.locator(".group").first()).toHaveClass(/bg-primary\/10/)- const position = () => target.evaluate((node, scrollerId) => {- const root = node.closest(`[data-testid="${scrollerId}"]`) as HTMLElement- const rect = node.getBoundingClientRect()- const viewport = root.getBoundingClientRect()- return { inView: rect.top >= viewport.top && rect.bottom <= viewport.bottom, scrollTop: root.scrollTop, ready: root.querySelector("[data-read-position-ready]")?.getAttribute("data-read-position-ready") }- }, tid.messageScroller)- await expect.poll(position).toMatchObject({ inView: true, ready: "true" })- await expect(page).toHaveURL(`${WEB_URL}/c/channels/${serverId}/${channelId}`)- await expect(composerEditable(page)).toBeVisible({ timeout: 30_000 })- await testInfo.attach("msg-anchor-evidence", { body: JSON.stringify({ status: response!.status(), htmlBytes: Buffer.byteLength(html), selection: explicitEntry.selection, surfaceReceipt: explicitEntry.surfaceReceipt, anchorId: channelMessageId, readPointer, latestId: laterIds.at(-1), defaultWindowIds: defaultEntry.messages.map(message => message.id), explicitWindowIds: explicitEntry.messages.map(message => message.id), position: await position(), url: page.url() }), contentType: "application/json" })- })--})diff --git a/src/web/src/test/e2e-ui/63-mobile-notification-msg-anchor.spec.ts b/src/web/src/test/e2e-ui/63-mobile-notification-msg-anchor.spec.tsnew file mode 100644index 000000000..893834d1c--- /dev/null+++ b/src/web/src/test/e2e-ui/63-mobile-notification-msg-anchor.spec.ts@@ -0,0 +1,65 @@+import { communityFixtureFetch } from "./_fixtures/business-contract"+import { devices } from "@playwright/test"+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER, DEFAULT_MESSAGE_PAGE_SIZE, type CommunityConversationEntryRead } from "@alook/shared"+import { expect, test } from "./_fixtures/case-fixture"+import { composerEditable } from "./_fixtures/actions"+import { expectPublicCommunityDocument } from "./_fixtures/community-ssr-frame"+import { tid } from "./_fixtures/testids"+import { WEB_URL } from "./_setup/paths"+import { prepareCase1 } from "./_fixtures/mobile-notification-activation"++test.describe("mobile notification chat routes (native bridge simulation)", () => {+test("ordinary channel msg permalink retains its message anchor", async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelId, channelMessageId } = await prepareCase1(actors)+ const laterIds: string[] = []+ for (let index = 0; index < DEFAULT_MESSAGE_PAGE_SIZE + 8; index += 1) {+ laterIds.push(await actors.seed.seedMessage("alice", channelId, `Later window message ${index}`))+ }+ const readPointer = laterIds[DEFAULT_MESSAGE_PAGE_SIZE]+ const checkpoint = await communityFixtureFetch(`${WEB_URL}/api/community/channels/${channelId}/read`, {+ method: "PUT",+ headers: { Cookie: actors.sessionCookie("bob"), Origin: WEB_URL, "Content-Type": "application/json" },+ body: JSON.stringify({ lastReadMessageId: readPointer }),+ })+ expect(checkpoint.ok).toBe(true)+ const defaultResponse = await communityFixtureFetch(`${WEB_URL}/api/community/channels/${channelId}/messages?entry=1`, { headers: { Cookie: actors.sessionCookie("bob"), [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })+ expect(defaultResponse.ok, `entry precondition status ${defaultResponse.status}`).toBe(true)+ const defaultEntry = await defaultResponse.json() as CommunityConversationEntryRead+ expect(defaultEntry.selection).toEqual({ reason: "read_pointer", anchorMessageId: readPointer })+ expect(defaultEntry.messages.some(message => message.id === channelMessageId)).toBe(false)+ expect(readPointer).not.toBe(laterIds.at(-1))++ const { page } = await asUser("bob", devices["iPhone 13"])+ const entryResponse = page.waitForResponse(response => {+ const url = new URL(response.url())+ return response.request().method() === "GET" && url.pathname === `/api/community/channels/${channelId}/messages`+ && url.searchParams.get("entry") === "1" && url.searchParams.get("anchor") === channelMessageId+ })+ const response = await page.goto(`/c/channels/${serverId}/${channelId}?msg=${channelMessageId}`)+ expect(response?.ok()).toBe(true)+ const html = await response!.text()+ expectPublicCommunityDocument(html)+ const explicitResponse = await entryResponse+ expect(explicitResponse.ok()).toBe(true)+ const explicitEntry = await explicitResponse.json() as CommunityConversationEntryRead+ expect(explicitEntry.selection).toEqual({ reason: "explicit_anchor", anchorMessageId: channelMessageId })+ expect(explicitEntry.surfaceReceipt).toEqual({ channelId, surfaceKind: "channel" })+ expect(explicitEntry.messages).toEqual(expect.arrayContaining([expect.objectContaining({ id: channelMessageId })]))+ expect(explicitEntry.messages.some(message => message.id === readPointer)).toBe(false)+ const target = page.getByTestId(tid.message(channelMessageId))+ await expect(target).toBeVisible()+ await expect(target.locator(".group").first()).toHaveClass(/bg-primary\/10/)+ const position = () => target.evaluate((node, scrollerId) => {+ const root = node.closest(`[data-testid="${scrollerId}"]`) as HTMLElement+ const rect = node.getBoundingClientRect()+ const viewport = root.getBoundingClientRect()+ return { inView: rect.top >= viewport.top && rect.bottom <= viewport.bottom, scrollTop: root.scrollTop, ready: root.querySelector("[data-read-position-ready]")?.getAttribute("data-read-position-ready") }+ }, tid.messageScroller)+ await expect.poll(position).toMatchObject({ inView: true, ready: "true" })+ await expect(page).toHaveURL(`${WEB_URL}/c/channels/${serverId}/${channelId}`)+ await expect(composerEditable(page)).toBeVisible({ timeout: 30_000 })+ await testInfo.attach("msg-anchor-evidence", { body: JSON.stringify({ status: response!.status(), htmlBytes: Buffer.byteLength(html), selection: explicitEntry.selection, surfaceReceipt: explicitEntry.surfaceReceipt, anchorId: channelMessageId, readPointer, latestId: laterIds.at(-1), defaultWindowIds: defaultEntry.messages.map(message => message.id), explicitWindowIds: explicitEntry.messages.map(message => message.id), position: await position(), url: page.url() }), contentType: "application/json" })+ })+})diff --git a/src/web/src/test/e2e-ui/63-mobile-notification-seq-context.spec.ts b/src/web/src/test/e2e-ui/63-mobile-notification-seq-context.spec.tsnew file mode 100644index 000000000..bee748d59--- /dev/null+++ b/src/web/src/test/e2e-ui/63-mobile-notification-seq-context.spec.ts@@ -0,0 +1,35 @@+import { devices } from "@playwright/test"+import { expect, test } from "./_fixtures/case-fixture"+import { prepareCase1 } from "./_fixtures/mobile-notification-activation"++test.describe("mobile notification chat routes (native bridge simulation)", () => {+for (const surface of ["dm", "channel"] as const) {+test(`ordinary ${surface} seq permalink retains message context`, async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser } = actors+ const { serverId, channelId, channelMessageId, dmId, dmMessageId, dmSeq, channelSeq } = await prepareCase1(actors)++ const { page } = await asUser("bob", devices["iPhone 13"])+ const targetId = surface === "dm" ? dmId : channelId+ const messageId = surface === "dm" ? dmMessageId : channelMessageId+ const route = surface === "dm" ? `/c/me/${targetId}` : `/c/channels/${serverId}/${targetId}`+ const responsePromise = page.waitForResponse((response) => {+ const url = new URL(response.url())+ return url.pathname === `/api/community/channels/${targetId}/messages`+ && url.searchParams.get("anchor") === messageId && response.ok()+ })+ await page.goto(`${route}?seq=${surface === "dm" ? dmSeq : channelSeq}`)+ const response = await responsePromise+ const payload = await response.json()+ const content = surface === "dm" ? "DM notification route evidence" : "Channel notification route evidence"+ expect(payload.messages).toEqual(expect.arrayContaining([expect.objectContaining({ id: messageId, content })]))+ const sheet = page.locator('[data-slot="sheet-content"]')+ await expect(sheet).toBeVisible()+ await expect(sheet.locator('[data-anchor-row="1"]').getByText(+ content, { exact: true },+ )).toBeVisible()+ await testInfo.attach("permalink-context", { body: JSON.stringify({ status: response.status(), messageId, url: page.url() }), contentType: "application/json" })+ await testInfo.attach("context", { body: await page.screenshot(), contentType: "image/png" })+ })+}+})diff --git a/src/web/src/test/e2e-ui/63-mobile-notification-unavailable.spec.ts b/src/web/src/test/e2e-ui/63-mobile-notification-unavailable.spec.tsnew file mode 100644index 000000000..3be883e9f--- /dev/null+++ b/src/web/src/test/e2e-ui/63-mobile-notification-unavailable.spec.ts@@ -0,0 +1,57 @@+import { devices } from "@playwright/test"+import { expect, test } from "./_fixtures/case-fixture"+import { tid } from "./_fixtures/testids"+import { WEB_URL } from "./_setup/paths"+import { type Bridge, installMobileBridge, resumeActivation, prepareCase1 } from "./_fixtures/mobile-notification-activation"++test.describe("mobile notification chat routes (native bridge simulation)", () => {+for (const kind of ["deleted", "revoked"] as const) {+test(`${kind} target shows an unavailable message page with the normal Inbox action`, async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["alice", "bob"])+ const { asUser, userId } = actors+ const { seedCategory, seedChannel, seedChannelMember, seedMessage } = actors.seed+ const { deleteAsAlice, serverId, captureMessageDoor } = await prepareCase1(actors)++ const categoryId = kind === "revoked" ? await seedCategory("alice", serverId, `private-${Date.now()}`, { private: true }) : undefined+ const targetId = await seedChannel("alice", serverId, `${kind}-${Date.now()}`, "text", categoryId)+ if (kind === "revoked") await seedChannelMember("alice", targetId, userId("bob"))+ const messageId = await seedMessage("alice", targetId, `${kind} target evidence`)+ await deleteAsAlice(kind === "deleted" ? `/api/community/channels/${targetId}` : `/api/community/channels/${targetId}/members/${userId("bob")}`)+ const { page } = await asUser("bob", devices["iPhone 13"])+ await installMobileBridge(page, null)+ const door = await captureMessageDoor(page, targetId, messageId)+ const route = `/c/channels/${serverId}`+ await page.goto(route)+ await expect(page.getByTestId(tid.inboxTrigger)).toBeVisible({ timeout: 30_000 })+ const activation = { notificationId: crypto.randomUUID(), targetId, messageId }+ await resumeActivation(page, activation)+ const { status } = await door.result+ expect([403, 404]).toContain(status)+ await expect(page).toHaveURL(`${WEB_URL}/c/messages/${messageId}`)+ const unavailableAlert = page.getByTestId(tid.messageRouteAlert(messageId))+ await expect(unavailableAlert).toHaveCount(1)+ await expect(unavailableAlert).toBeVisible()+ await expect(unavailableAlert).toHaveText("This conversation is unavailable.")+ await page.getByRole("button", { name: "Open Inbox", exact: true }).click()+ await expect(page).toHaveURL(`${WEB_URL}/c/me`)+ await expect(page.getByTestId(tid.inboxTrigger)).toBeVisible()+ await expect(page.getByTestId(tid.inboxTrigger)).toHaveAttribute("aria-expanded", "true")+ const inbox = page.getByTestId(tid.userBarExtension)+ await expect(inbox).toHaveCount(1)+ await expect(inbox).toBeVisible()+ await expect(inbox.locator("xpath=ancestor::*[@inert or @aria-hidden='true']")).toHaveCount(0)+ await expect.poll(() => page.evaluate(() => (+ window as typeof window & { __mobileNotificationQa: Bridge }+ ).__mobileNotificationQa.dismissed)).toEqual([activation.notificationId])+ const inboxHref = page.url()+ await page.getByRole("link", { name: /^Friends(?:, \d+ new requests)?$/ }).click()+ await expect(page).toHaveURL(`${WEB_URL}/c/me/friends`)+ await expect(page.getByTestId(tid.inboxTrigger)).toHaveAttribute("aria-expanded", "false")+ await expect(page.getByTestId(tid.userBarExtension)).toHaveCount(0)+ await expect.poll(() => page.evaluate(() => (+ window as typeof window & { __mobileNotificationQa: Bridge }+ ).__mobileNotificationQa.dismissed)).toEqual([activation.notificationId])+ await testInfo.attach("fallback-evidence", { body: JSON.stringify({ kind, status, inboxHref, url: page.url() }), contentType: "application/json" })+ })+}+})diff --git a/src/web/src/test/e2e-ui/_fixtures/bot-profile-audit.ts b/src/web/src/test/e2e-ui/_fixtures/bot-profile-audit.tsnew file mode 100644index 000000000..b2fb856c7--- /dev/null+++ b/src/web/src/test/e2e-ui/_fixtures/bot-profile-audit.ts@@ -0,0 +1,701 @@+import { communityFixtureFetch, currentCommunityFixtureError } from "./business-contract"+import type { Locator, Page, Route, TestInfo, WebSocket as BrowserSocket } from "@playwright/test"+import { expect } from "./case-fixture"+import { tid } from "./testids"+import { WEB_URL } from "../_setup/paths"+import { connectMachine } from "./community-machine"+import type { CaseActors, CaseResources, OwnedCaseResource } from "./case-fixture"++export async function prepareCase(actors: CaseActors, caseResources: CaseResources) {+ const { sessionCookie } = actors+ const createdBotIds = new Map<string, OwnedCaseResource<string>>()+ const createdMachineIds = new Map<string, OwnedCaseResource<string>>()+ async function cleanupCreatedResources(): Promise<void> {+ const errors: unknown[] = []+ for (const resource of [...createdBotIds.values(), ...createdMachineIds.values()]) {+ try {+ await resource.close()+ }+ catch (error) {+ errors.push(error)+ }+ }+ if (errors.length)+ throw new AggregateError(errors, "Bot preview resource cleanup failed")+ }+ function headersFor(key: UserKey, extra?: Record<string, string>) {+ return {+ Cookie: sessionCookie(key),+ Origin: WEB_URL,+ ...extra,+ }+ }+ async function jsonRequest<T>(key: UserKey, path: string, init?: RequestInit): Promise<T> {+ const response = await communityFixtureFetch(`${WEB_URL}${path}`, {+ ...init,+ headers: headersFor(key, {+ ...(init?.body ? { "Content-Type": "application/json" } : {}),+ ...(init?.headers as Record<string, string> | undefined),+ }),+ })+ expect(response.status, `${init?.method ?? "GET"} ${path}`).toBeLessThan(300)+ return response.json() as Promise<T>+ }+ async function pairMachine(): Promise<{+ credential: string+ machineId: string+ }> {+ const pair = await jsonRequest<{+ tokenId: string+ }>("alice", "/api/community/machines/pair", {+ method: "POST",+ })+ const activationProof: { response?: Response; machineId?: string } = {}+ const pairingToken = caseResources.own(pair.tokenId, async () => {+ if (!activationProof.response?.ok || !activationProof.machineId) throw new Error("Pairing token consumption is UNKNOWN; this case must stop")+ })+ const response = await fetch(`${WEB_URL}/api/community/daemon/activate`, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${pair.tokenId}`,+ "Content-Type": "application/json",+ Origin: WEB_URL,+ },+ body: JSON.stringify({+ hostname: `profile-preview-e2e-${Date.now()}`,+ platform: "darwin",+ arch: "arm64",+ runtimeReport: [{ id: "codex", status: "healthy" }],+ }),+ })+ expect(response.status).toBe(200)+ const data = await response.json() as {+ credential: string+ machineId: string+ }+ createdMachineIds.set(data.machineId, caseResources.own(data.machineId, async (machineId) => {+ const response = await communityFixtureFetch(`${WEB_URL}/api/community/machines/${machineId}`, { method: "DELETE", headers: headersFor("alice") })+ expect(response.status, `delete test machine ${machineId}`).toBe(204)+ createdMachineIds.delete(machineId)+ }))+ activationProof.response = response+ activationProof.machineId = data.machineId+ await pairingToken.close()+ return data+ }+ async function createBot(machineId: string, name: string): Promise<string> {+ const data = await jsonRequest<{+ bot: {+ id: string+ }+ }>("alice", "/api/community/bots", {+ method: "POST",+ body: JSON.stringify({ name, machineId, runtime: "codex" }),+ })+ createdBotIds.set(data.bot.id, caseResources.own(data.bot.id, async (botId) => {+ const response = await communityFixtureFetch(`${WEB_URL}/api/community/bots/${botId}`, { method: "DELETE", headers: headersFor("alice") })+ expect(response.status, `delete test bot ${botId}`).toBe(204)+ createdBotIds.delete(botId)+ }))+ return data.bot.id+ }+ async function joinBotToServer(runnerKey: string, botId: string, serverId: string): Promise<void> {+ const token = await actors.seed.createInvite("alice", serverId)+ const joined = await jsonRequest<{ serverId: string; member: { userId: string } }>(+ "alice",+ `/api/community/invites/${token}/join`,+ {+ method: "POST",+ headers: { Authorization: `Bearer ${runnerKey}` },+ body: "{}",+ },+ )+ expect(joined.serverId).toBe(serverId)+ expect(joined.member.userId).toBe(botId)+ }+ actors.onCleanup(cleanupCreatedResources)+ return { createdBotIds, createdMachineIds, cleanupCreatedResources, headersFor, jsonRequest, pairMachine, createBot, joinBotToServer }+}++type UserKey = "alice" | "bob"++type Rect = { x: number; y: number; width: number; height: number }++type PreviewFrameSample = {+ phase: "start" | "mutation" | "frame"+ rootOverflowX: number+ rootOverflowY: number+ scrollX: number+ scrollY: number+ ready: string | null+ visibility: string | null+ pointerEvents: string | null+ rect: Rect | null+ viewportWidth: number+ viewportHeight: number+}++async function rect(locator: Locator): Promise<Rect> {+ const value = await locator.boundingBox()+ expect(value).not.toBeNull()+ return value!+}++export async function settleSheet(sheet: Locator): Promise<void> {+ await expect(sheet).toBeVisible()+ await sheet.evaluate((element) => new Promise<void>((resolveStable) => {+ const deadline = performance.now() + 1_000+ let previous = ""+ let stableFrames = 0+ const sample = () => {+ const bounds = element.getBoundingClientRect()+ const style = getComputedStyle(element)+ const current = [+ bounds.x,+ bounds.y,+ bounds.width,+ bounds.height,+ style.opacity,+ style.transform,+ style.backgroundColor,+ style.borderTopColor,+ style.borderRightColor,+ style.borderBottomColor,+ style.borderLeftColor,+ ].join(":")+ stableFrames = current === previous ? stableFrames + 1 : 0+ previous = current+ if (stableFrames >= 3 || performance.now() >= deadline) resolveStable()+ else requestAnimationFrame(sample)+ }+ requestAnimationFrame(sample)+ }))+}++export async function expectSheetThemeTokens(sheet: Locator): Promise<void> {+ const colors = await sheet.evaluate((element) => {+ const probe = document.createElement("div")+ probe.style.cssText = [+ "position:fixed",+ "visibility:hidden",+ "background-color:var(--background)",+ "border:1px solid var(--border)",+ ].join(";")+ document.body.appendChild(probe)++ const sheetStyle = getComputedStyle(element)+ const probeStyle = getComputedStyle(probe)+ const header = element.querySelector<HTMLElement>("[data-slot='sheet-header']")+ const body = element.querySelector<HTMLElement>("[data-slot='sheet-body']")+ if (!header || !body) throw new Error("missing sheet surface")+ const result = {+ expectedBackground: probeStyle.backgroundColor,+ expectedBorder: probeStyle.borderLeftColor,+ sheetBackground: sheetStyle.backgroundColor,+ sheetBorder: sheetStyle.borderLeftColor,+ headerBackground: getComputedStyle(header).backgroundColor,+ headerBorder: getComputedStyle(header).borderBottomColor,+ bodyBackground: getComputedStyle(body).backgroundColor,+ }+ probe.remove()+ return result+ })++ expect(colors).toMatchObject({+ sheetBackground: colors.expectedBackground,+ sheetBorder: colors.expectedBorder,+ headerBackground: "rgba(0, 0, 0, 0)",+ headerBorder: colors.expectedBorder,+ bodyBackground: colors.expectedBackground,+ })+}++export async function attachPageScreenshot(testInfo: TestInfo, name: string, page: Page): Promise<void> {+ await testInfo.attach(`${name}.png`, {+ body: await page.screenshot(),+ contentType: "image/png",+ })+}++export async function expectActivityHeader(+ page: Page,+ testInfo: TestInfo,+ width: 390 | 1280,+): Promise<void> {+ await page.setViewportSize({ width, height: width === 390 ? 844 : 900 })+ const sheet = page.getByTestId(tid.botActivityModal)+ await settleSheet(sheet)+ const header = sheet.locator("[data-slot='sheet-header']")+ const avatar = header.locator("[data-slot='sheet-header-leading']")+ const title = header.locator("[data-slot='sheet-title']")+ const description = header.locator("[data-slot='sheet-description']")+ const close = sheet.getByRole("button", { name: "Close", exact: true })+ const [avatarRect, titleRect, descriptionRect, closeRect] = await Promise.all([+ rect(avatar), rect(title), rect(description), rect(close),+ ])++ expect(avatarRect.width).toBeCloseTo(32, 0)+ expect(avatarRect.height).toBeCloseTo(32, 0)+ expect(titleRect.x).toBeGreaterThanOrEqual(avatarRect.x + avatarRect.width + 11.5)+ expect(descriptionRect.x).toBeCloseTo(titleRect.x, 0)+ expect(titleRect.x + titleRect.width).toBeLessThanOrEqual(closeRect.x + 0.5)+ const styles = await title.evaluate((element) => {+ const titleStyle = getComputedStyle(element)+ const descriptionNode = element.parentElement?.querySelector<HTMLElement>("[data-slot='sheet-description']")+ if (!descriptionNode) throw new Error("missing Activity Log description")+ const descriptionStyle = getComputedStyle(descriptionNode)+ return {+ titleFontSize: titleStyle.fontSize,+ titleFontWeight: titleStyle.fontWeight,+ titleLineHeight: titleStyle.lineHeight,+ descriptionFontSize: descriptionStyle.fontSize,+ descriptionLineHeight: descriptionStyle.lineHeight,+ }+ })+ expect(styles).toMatchObject({+ titleFontSize: "18px",+ titleFontWeight: "600",+ descriptionFontSize: "14px",+ })+ expect(Number.parseFloat(styles.titleLineHeight)).toBeGreaterThan(Number.parseFloat(styles.titleFontSize))+ expect(Number.parseFloat(styles.descriptionLineHeight)).toBeGreaterThan(Number.parseFloat(styles.descriptionFontSize))+ await attachPageScreenshot(testInfo, `activity-log-header-${width}`, page)+}++export async function expectFooterGeometry(+ page: Page,+ title: string,+ actionNames: string[],+ width: 390 | 639 | 640,+): Promise<void> {+ await page.setViewportSize({ width, height: 844 })+ const sheet = page.getByRole("dialog", { name: title, exact: true })+ await settleSheet(sheet)+ const footer = sheet.locator("[data-slot='sheet-footer']")+ const actions = actionNames.map((name) => footer.getByRole("button", { name, exact: true }))+ const footerRect = await rect(footer)+ const actionRects = await Promise.all(actions.map(rect))+ const style = await footer.evaluate((element) => {+ const value = getComputedStyle(element)+ return {+ display: value.display,+ flexDirection: value.flexDirection,+ justifyContent: value.justifyContent,+ alignItems: value.alignItems,+ }+ })+ expect(style).toEqual({+ display: "flex",+ flexDirection: "row",+ justifyContent: "flex-end",+ alignItems: "center",+ })+ for (const actionRect of actionRects) {+ expect(actionRect.width).toBeLessThan(footerRect.width * 0.75)+ if (width < 640) expect(actionRect.height).toBeGreaterThanOrEqual(44)+ }+ for (let index = 1; index < actionRects.length; index++) {+ expect(actionRects[index]!.x).toBeGreaterThan(actionRects[index - 1]!.x)+ expect(actionRects[index]!.y).toBeCloseTo(actionRects[0]!.y, 0)+ }+ const finalAction = actionRects.at(-1)!+ expect(footerRect.x + footerRect.width - (finalAction.x + finalAction.width))+ .toBe(width < 640 ? 16 : 24)+}++export async function enrollBot(credential: string, botId: string): Promise<string> {+ const response = await fetch(`${WEB_URL}/api/community/daemon/enroll-agent`, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${credential}`,+ "Content-Type": "application/json",+ Origin: WEB_URL,+ },+ body: JSON.stringify({ agentId: botId }),+ })+ expect(response.status).toBe(200)+ const data = await response.json() as { runnerKey: string }+ return data.runnerKey+}++export async function sendBotMessage(+ runnerKey: string,+ channel: string,+ text: string,+ seenUpToSeq = 0,+): Promise<{ seq: number }> {+ const response = await fetch(`${WEB_URL}/api/community/channels/resolve/messages`, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${runnerKey}`,+ "Content-Type": "application/json",+ Origin: WEB_URL,+ },+ body: JSON.stringify({+ channel,+ content: { text },+ attachments: [],+ seenUpToSeq,+ nonce: `profile-preview:${crypto.randomUUID()}`,+ }),+ })+ expect(response.status).toBe(200)+ const data = await response.json() as { state: string; message: { seq: string } }+ expect(data.state).toBe("sent")+ const seq = Number(data.message.seq.replace(/^#/, ""))+ expect(Number.isInteger(seq) && seq > 0).toBe(true)+ return { seq }+}++export async function setBotMark(+ runnerKey: string,+ channel: string,+ seq: number,+): Promise<void> {+ const response = await fetch(`${WEB_URL}/api/community/messages/resolve/properties`, {+ method: "PUT",+ headers: {+ Authorization: `Bearer ${runnerKey}`,+ "Content-Type": "application/json",+ Origin: WEB_URL,+ },+ body: JSON.stringify({+ channel,+ seq,+ property: { type: "mark", value: true },+ }),+ })+ expect(response.status).toBe(200)+ await expect(response.json()).resolves.toMatchObject({ type: "mark", value: true })+}++export async function openBotProfile(page: Page, botName: string): Promise<void> {+ await page.getByRole("button", { name: botName, exact: true }).click()+ await expect(page.getByTestId(tid.profileCard)).toBeVisible()+}++async function installPreviewFrameProbe(page: Page): Promise<void> {+ await page.evaluate((dockTestId) => {+ type ProbeState = {+ active: boolean+ observer: MutationObserver+ samples: PreviewFrameSample[]+ }+ const target = window as typeof window & { __previewFrameProbe?: ProbeState }+ const samples: PreviewFrameSample[] = []+ const sample = (phase: PreviewFrameSample["phase"]) => {+ if (samples.length >= 500) return+ const root = document.documentElement+ const dock = document.querySelector<HTMLElement>(`[data-testid="${dockTestId}"]`)+ const style = dock ? getComputedStyle(dock) : null+ const bounds = dock?.getBoundingClientRect()+ samples.push({+ phase,+ rootOverflowX: root.scrollWidth - root.clientWidth,+ rootOverflowY: root.scrollHeight - root.clientHeight,+ scrollX: window.scrollX,+ scrollY: window.scrollY,+ ready: dock?.getAttribute("data-measurement-ready") ?? null,+ visibility: style?.visibility ?? null,+ pointerEvents: style?.pointerEvents ?? null,+ rect: bounds+ ? { x: bounds.x, y: bounds.y, width: bounds.width, height: bounds.height }+ : null,+ viewportWidth: window.innerWidth,+ viewportHeight: window.innerHeight,+ })+ }+ const observer = new MutationObserver(() => sample("mutation"))+ observer.observe(document.body, {+ attributes: true,+ attributeFilter: ["class", "data-measurement-ready", "style"],+ childList: true,+ subtree: true,+ })+ target.__previewFrameProbe = { active: true, observer, samples }+ sample("start")+ const frame = () => {+ const state = target.__previewFrameProbe+ if (!state?.active) return+ sample("frame")+ requestAnimationFrame(frame)+ }+ requestAnimationFrame(frame)+ }, tid.botAuditPreviewDock)+}++async function finishPreviewFrameProbe(page: Page): Promise<PreviewFrameSample[]> {+ return page.evaluate(async () => {+ await new Promise<void>((resolveFrames) => {+ requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(+ () => resolveFrames(),+ )))+ })+ const target = window as typeof window & {+ __previewFrameProbe?: {+ active: boolean+ observer: MutationObserver+ samples: PreviewFrameSample[]+ }+ }+ const state = target.__previewFrameProbe+ if (!state) throw new Error("preview frame probe was not installed")+ state.active = false+ state.observer.disconnect()+ return state.samples+ })+}++function expectPreviewFrames(samples: PreviewFrameSample[], label: string): void {+ expect(samples.length, `${label}: captured frames`).toBeGreaterThan(1)+ const baseline = samples[0]!+ expect(baseline.rootOverflowX, `${label}: baseline root X overflow`).toBe(0)+ expect(baseline.rootOverflowY, `${label}: baseline root Y overflow`).toBe(0)+ const visible = samples.filter((sample) => sample.ready === "true"+ && sample.visibility === "visible"+ && sample.rect)+ expect(visible.length, `${label}: visible positioned frames`).toBeGreaterThan(0)++ for (const [index, sample] of samples.entries()) {+ expect(sample.rootOverflowX, `${label}: frame ${index} root X overflow`).toBe(0)+ expect(sample.rootOverflowY, `${label}: frame ${index} root Y overflow`).toBe(0)+ expect(sample.scrollX, `${label}: frame ${index} root scrollX`).toBe(baseline.scrollX)+ expect(sample.scrollY, `${label}: frame ${index} root scrollY`).toBe(baseline.scrollY)+ if (sample.ready === "false") {+ expect(sample.visibility, `${label}: frame ${index} hidden measurement`).toBe("hidden")+ expect(sample.pointerEvents, `${label}: frame ${index} inert measurement`).toBe("none")+ }+ if (sample.ready !== "true" || sample.visibility !== "visible" || !sample.rect) continue+ expect(sample.rect.x, `${label}: frame ${index} left boundary`).toBeGreaterThanOrEqual(7.5)+ expect(sample.rect.y, `${label}: frame ${index} top boundary`).toBeGreaterThanOrEqual(7.5)+ expect(+ sample.rect.x + sample.rect.width,+ `${label}: frame ${index} right boundary`,+ ).toBeLessThanOrEqual(sample.viewportWidth - 7.5)+ expect(+ sample.rect.y + sample.rect.height,+ `${label}: frame ${index} bottom boundary`,+ ).toBeLessThanOrEqual(sample.viewportHeight - 7.5)+ }+}++export async function probeOwnedBotProfile(+ page: Page,+ author: Locator,+ label: string,+): Promise<PreviewFrameSample[]> {+ await expect(author).toBeVisible({ timeout: 20_000 })+ await installPreviewFrameProbe(page)+ await author.click()+ const dock = page.getByTestId(tid.botAuditPreviewDock)+ await expect(dock).toHaveAttribute("data-measurement-ready", "true")+ await expect(dock).toBeVisible()+ const samples = await finishPreviewFrameProbe(page)+ expectPreviewFrames(samples, label)+ return samples+}++export type ActivityAnchorPage = {+ events: Array<{ id: string; createdAt: string }>+ nextCursor: { beforeCreatedAt: string; beforeId: string } | null+}++export async function activityAnchorSnapshot(scroller: Locator) {+ return scroller.evaluate(element => {+ const root = element.getBoundingClientRect()+ return {+ scrollTop: element.scrollTop,+ scrollHeight: element.scrollHeight,+ clientHeight: element.clientHeight,+ overflowAnchor: getComputedStyle(element).overflowAnchor,+ events: [...element.querySelectorAll<HTMLElement>("[data-activity-event-id]")].flatMap(wrapper => {+ const body = wrapper.firstElementChild+ if (!(body instanceof HTMLElement)) return []+ const rect = body.getBoundingClientRect()+ return [{ id: wrapper.dataset.activityEventId!, top: rect.top - root.top, bottom: rect.bottom - root.top, height: rect.height }]+ }),+ }+ })+}++export async function settleActivityPosition(scroller: Locator, target: number) {+ return scroller.evaluate(async (element, target) => {+ const samples: Array<{ scrollTop: number; scrollHeight: number; clientHeight: number; events: Array<{ id: string; top: number; bottom: number }> }> = []+ let previous = ""+ let stableFrames = 0+ for (let frame = 0; frame < 120; frame += 1) {+ await new Promise<void>(resolveFrame => requestAnimationFrame(() => resolveFrame()))+ if (!element.isConnected) return { settled: false, samples }+ const root = element.getBoundingClientRect()+ const sample = {+ scrollTop: element.scrollTop,+ scrollHeight: element.scrollHeight,+ clientHeight: element.clientHeight,+ events: [...element.querySelectorAll<HTMLElement>("[data-activity-event-id]")].flatMap(wrapper => {+ const body = wrapper.firstElementChild+ if (!(body instanceof HTMLElement)) return []+ const rect = body.getBoundingClientRect()+ return [{ id: wrapper.dataset.activityEventId!, top: rect.top - root.top, bottom: rect.bottom - root.top }]+ }),+ }+ samples.push(sample)+ const signature = JSON.stringify(sample)+ stableFrames = Math.abs(sample.scrollTop - target) <= 1 && sample.events.length > 0 && signature === previous ? stableFrames + 1 : 0+ if (stableFrames === 2) return { settled: true, samples }+ previous = signature+ }+ return { settled: false, samples }+ }, target)+}++export async function gateOlderActivityPages(page: Page, botId: string, caseResources: CaseResources) {+ const entries: Array<{ url: string; release: (status?: 503) => void }> = []+ const running = new Set<Promise<void>>()+ let closing = false+ const matches = (url: URL) => url.pathname === `/api/community/bots/${botId}/audit-log`+ const handler = (route: Route) => {+ const url = new URL(route.request().url())+ if (!url.searchParams.has("beforeId")) return route.continue()+ if (closing) return route.abort("failed")+ let release!: (status?: 503) => void+ const ready = new Promise<503 | undefined>(resolveGate => { release = resolveGate })+ const operation = (async () => {+ const status = await ready+ if (page.isClosed()) return+ if (closing) await route.abort("failed")+ else if (status) await route.fulfill(currentCommunityFixtureError("Injected Activity older-page failure", status))+ else await route.continue()+ })()+ entries.push({ url: url.toString(), release })+ running.add(operation)+ return operation.finally(() => running.delete(operation))+ }+ const owned = caseResources.own(entries, async () => {+ closing = true+ for (const entry of entries) entry.release()+ await Promise.all(running)+ if (!page.isClosed()) await page.unroute(matches, handler)+ })+ await page.route(matches, handler)+ return { entries, close: () => owned.close() }+}++type ActivityJsonRequest = Awaited<ReturnType<typeof prepareCase>>["jsonRequest"]++export async function seedActivityHistory({ machine, botId, suffix, scenario, caseResources, jsonRequest, testInfo }: {+ machine: ReturnType<typeof connectMachine>+ botId: string+ suffix: string+ scenario: "same-day" | "cross-day"+ caseResources: CaseResources+ jsonRequest: ActivityJsonRequest+ testInfo: TestInfo+}) {+ const now = new Date()+ const start = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() - 5, 12)+ const history = Array.from({ length: 200 }, (_, index) => ({+ id: `bae_anchor_${suffix}_${String(index).padStart(3, "0")}`,+ createdAt: new Date(start + (scenario === "cross-day" ? Math.floor(index / 60) * 86_400_000 + index % 60 * 1_000 : index * 1_000)).toISOString(),+ }))+ const acknowledged = new Set<string>()+ const acknowledgements: Array<{ type: string; eventId: string }> = []+ const expectedIds = new Set(history.map(event => event.id))+ const onMessage = (raw: unknown) => {+ const frame = JSON.parse(String(raw)) as { type?: string; eventId?: string }+ if (frame.type === "bot_audit_event_ack" && frame.eventId && expectedIds.has(frame.eventId)) {+ acknowledged.add(frame.eventId)+ acknowledgements.push({ type: frame.type, eventId: frame.eventId })+ }+ }+ const listener = caseResources.own(onMessage, async captured => { machine.socket.off("message", captured) })+ machine.socket.on("message", onMessage)+ for (const event of history) machine.socket.send(JSON.stringify({+ type: "bot_audit_event",+ eventId: event.id,+ occurredAt: event.createdAt,+ agentId: botId,+ sessionId: `anchor-session-${suffix}`,+ launchId: `anchor-launch-${suffix}`,+ event: { kind: "session_reset", payload: { trigger: "idle_timeout" } },+ }))+ await expect.poll(() => acknowledged.size, { timeout: 30_000 }).toBe(history.length)+ await listener.close()+ const headPath = `/api/community/bots/${botId}/audit-log?limit=50`+ const head = await jsonRequest<ActivityAnchorPage>("alice", headPath)+ await testInfo.attach("activity-history-backend", {+ body: JSON.stringify({ botId, scenario, history, acknowledgements, headPath, head }),+ contentType: "application/json",+ })+ expect(head.events.map(event => ({ id: event.id, createdAt: event.createdAt }))).toEqual(history.slice(-50).reverse())+ expect(head.nextCursor).toEqual({ beforeCreatedAt: history[150].createdAt, beforeId: history[150].id })+ return history+}++export function observeActivityFrames(page: Page, caseResources: CaseResources) {+ const frames: Array<{ id: string; botId: string; createdAt: string }> = []+ const onSocket = (socket: BrowserSocket) => {+ const onFrame = ({ payload }: { payload: string | Buffer }) => {+ let frame: { type?: string; id?: string; botId?: string; createdAt?: string }+ try { frame = JSON.parse(String(payload)) } catch { return }+ if (frame.type === "community:bot.audit_event" && frame.id && frame.botId && frame.createdAt) {+ frames.push({ id: frame.id, botId: frame.botId, createdAt: frame.createdAt })+ }+ }+ socket.on("framereceived", onFrame)+ caseResources.own(socket, async captured => { captured.off("framereceived", onFrame) })+ }+ page.on("websocket", onSocket)+ caseResources.own(onSocket, async captured => { page.off("websocket", captured) })+ return frames+}++export async function publishActivityReset({ machine, botId, suffix, id, createdAt, frames, caseResources, jsonRequest, testInfo }: {+ machine: ReturnType<typeof connectMachine>+ botId: string+ suffix: string+ id: string+ createdAt: string+ frames: ReturnType<typeof observeActivityFrames>+ caseResources: CaseResources+ jsonRequest: ActivityJsonRequest+ testInfo: TestInfo+}) {+ let acknowledged = false+ const onMessage = (raw: unknown) => {+ const frame = JSON.parse(String(raw)) as { type?: string; eventId?: string }+ if (frame.type === "bot_audit_event_ack" && frame.eventId === id) acknowledged = true+ }+ const listener = caseResources.own(onMessage, async captured => { machine.socket.off("message", captured) })+ machine.socket.on("message", onMessage)+ machine.socket.send(JSON.stringify({+ type: "bot_audit_event", eventId: id, occurredAt: createdAt, agentId: botId,+ sessionId: `anchor-session-${suffix}`, launchId: `anchor-launch-${suffix}`,+ event: { kind: "session_reset", payload: { trigger: "idle_timeout" } },+ }))+ await expect.poll(() => acknowledged).toBe(true)+ await listener.close()+ await expect.poll(() => frames.some(frame => frame.id === id && frame.botId === botId && frame.createdAt === createdAt)).toBe(true)+ const cursor = new URLSearchParams({ limit: "50", beforeCreatedAt: new Date(Date.parse(createdAt) + 1).toISOString(), beforeId: id })+ const path = `/api/community/bots/${botId}/audit-log?${cursor}`+ const persisted = await jsonRequest<ActivityAnchorPage>("alice", path)+ await testInfo.attach(`activity-live-${id}`, {+ body: JSON.stringify({ id, botId, createdAt, acknowledged, received: frames.filter(frame => frame.id === id), path, persisted }),+ contentType: "application/json",+ })+ expect(persisted.events[0]).toMatchObject({ id, createdAt })+}++export async function expectActivityPosition(scroller: Locator, anchor: { id: string; top: number }) {+ await expect.poll(async () => {+ const snapshot = await activityAnchorSnapshot(scroller)+ const kept = snapshot.events.find(event => event.id === anchor.id)+ return kept ? Math.abs(kept.top - anchor.top) : Number.POSITIVE_INFINITY+ }).toBeLessThanOrEqual(1)+}++export async function visibleActivityAnchor(scroller: Locator) {+ const snapshot = await activityAnchorSnapshot(scroller)+ const anchor = snapshot.events.find(event => event.top >= 32 && event.bottom <= snapshot.clientHeight)+ expect(anchor).toBeDefined()+ return anchor!+}diff --git a/src/web/src/test/e2e-ui/_fixtures/community-ws-reconnect.ts b/src/web/src/test/e2e-ui/_fixtures/community-ws-reconnect.tsnew file mode 100644index 000000000..b3ec57ced--- /dev/null+++ b/src/web/src/test/e2e-ui/_fixtures/community-ws-reconnect.ts@@ -0,0 +1,25 @@+import type { Page } from "@playwright/test"++export const USER_WS_AUTH_CONSUMED_ATTRIBUTE = "data-e2e-user-ws-auth-consumed"++export async function installUserWsAuthConsumedBarrier(page: Page) {+ await page.addInitScript(({ attribute }) => {+ const NativeWebSocket = window.WebSocket+ window.WebSocket = class extends NativeWebSocket {+ constructor(...args: ConstructorParameters<typeof WebSocket>) {+ super(...args)+ if (!new URL(this.url).pathname.endsWith("/user")) return+ this.addEventListener("message", (event) => {+ if (typeof event.data !== "string") return+ try {+ const message = JSON.parse(event.data) as { type?: string }+ if (message.type !== "auth.ok") return+ setTimeout(() => {+ document.documentElement.setAttribute(attribute, "true")+ }, 0)+ } catch {}+ })+ }+ }+ }, { attribute: USER_WS_AUTH_CONSUMED_ATTRIBUTE })+}diff --git a/src/web/src/test/e2e-ui/_fixtures/message-scroll-characterization.ts b/src/web/src/test/e2e-ui/_fixtures/message-scroll-characterization.tsnew file mode 100644index 000000000..232572fb4--- /dev/null+++ b/src/web/src/test/e2e-ui/_fixtures/message-scroll-characterization.ts@@ -0,0 +1,542 @@+import { communityFixtureFetch, confirmCommunityFixtureApiResponse, CURRENT_COMMUNITY_FIXTURE_HEADERS } from "./business-contract"+import type { Locator, Page, Route, TestInfo } from "@playwright/test"+import { expect, type CaseActors } from "./case-fixture"+import { communityFrameEvents, proxyCommunityWebSockets } from "./community-ws-proxy"+import { abortScrollTrace, attachScrollTrace, createScrollTraceIdentity, finishScrollTrace, markScrollTrace, type ScrollTraceResult } from "./scroll-trace"+import { tid } from "./testids"+import { WEB_URL } from "../_setup/paths"++export const VIEWPORT = { width: 1280, height: 800 }++type HeldRequest = {+ matched: Promise<URL>+ hasMatched: () => boolean+ release: () => void+ dispose: () => Promise<void>+}++export async function holdNextRequest(+ actors: CaseActors,+ page: Page,+ pattern: string,+ predicate: (url: URL) => boolean,+ options: { required?: boolean } = {},+): Promise<HeldRequest> {+ let resolveMatched!: (url: URL) => void+ let release!: () => void+ let consumed = false+ let timeout: ReturnType<typeof setTimeout> | undefined+ const matched = new Promise<URL>((resolveValue, reject) => {+ resolveMatched = (url) => {+ if (timeout) clearTimeout(timeout)+ resolveValue(url)+ }+ if (options.required !== false) timeout = setTimeout(() => reject(new Error(`held request did not match ${pattern}`)), 20_000)+ })+ const gate = new Promise<void>((resolveValue) => { release = resolveValue })+ const handler = async (route: Route) => {+ const url = new URL(route.request().url())+ if (!consumed && predicate(url)) {+ consumed = true+ resolveMatched(url)+ await gate+ }+ await route.continue()+ }+ await page.route(pattern, handler)+ const held = {+ matched,+ hasMatched: () => consumed,+ release,+ dispose: async () => {+ if (timeout) clearTimeout(timeout)+ release()+ if (!page.isClosed()) await page.unroute(pattern, handler)+ },+ }+ actors.onCleanup(() => held.dispose())+ return held+}++function profileContent(index: number): string {+ const shape = index % 8+ if (shape === 0) return `short row ${index}`+ if (shape === 1) return Array.from({ length: 4 }, (_, line) => `row ${index} line ${line}`).join("\n")+ if (shape === 2) return Array.from({ length: 12 }, (_, line) => `row ${index} variable line ${line} ${"x".repeat(line * 2)}`).join("\n")+ if (shape === 3) return `long-token-${"characterization".repeat(18)}-${index}`+ if (shape === 4) return `- list ${index}\n- second item ${"wide ".repeat(12)}\n- third item`+ if (shape === 5) return `> quote ${index}\n> ${"quoted content ".repeat(15)}`+ if (shape === 6) return `\`\`\`ts\nconst row${index} = ${JSON.stringify("code ".repeat(18))}\n\`\`\``+ return `**bold ${index}** ${"wrapping markdown ".repeat(22)}`+}++function estimatePlainMessage(content: string): number {+ return 24 + Math.min(Math.max(1, Math.ceil(content.length / 55)) * 20, 400)+}++export async function seedResizableHtmlPreview(page: Page, channelId: string) {+ const html = '<!doctype html><html><body><div id="content" style="height:160px">Asynchronous content</div><script>addEventListener("message",event=>{if(event.source===parent&&event.data?.type==="scroll-fixture-height"&&Number.isFinite(event.data.height))document.getElementById("content").style.height=event.data.height+"px"})</script></body></html>'+ const upload = await confirmCommunityFixtureApiResponse(page.request.post(`/api/community/channels/${channelId}/attachments`, {+ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS,+ multipart: { file: { name: "scroll-resize.html", mimeType: "text/html", buffer: Buffer.from(html) } },+ }))+ expect(upload.status()).toBe(200)+ const attachmentId = (await upload.json() as { id: string }).id+ const posted = await confirmCommunityFixtureApiResponse(page.request.post(`/api/community/channels/${channelId}/messages`, {+ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS,+ data: { content: `[alook-html-preview](${attachmentId})`, attachments: [attachmentId] },+ }))+ expect(posted.status()).toBe(201)+ const messageId = (await posted.json() as { message: { id: string } }).message.id+ return { messageId, attachmentId }+}++export async function seedProfile(+ actors: CaseActors,+ channelId: string,+ count: number,+ imageAtTail = false,+ authors: "rotate" | "alice" = "rotate",+ checkpointAt?: number,+): Promise<{ ids: string[]; estimates: Record<string, number> }> {+ const { seedMessage } = actors.seed+ const ids: string[] = []+ const estimates: Record<string, number> = {}+ for (let index = 0; index < count; index += 1) {+ const content = imageAtTail && index === count - 1+ ? `async image row ${index}\n`+ : profileContent(index)+ const afterCheckpoint = checkpointAt !== undefined && index > checkpointAt+ const author = afterCheckpoint+ ? index % 2 === 0 ? "bob" : "carol"+ : authors === "alice"+ ? "alice"+ : index % 3 === 0 ? "alice" : index % 3 === 1 ? "bob" : "carol"+ const id = await seedMessage(author, channelId, content)+ ids.push(id)+ estimates[id] = estimatePlainMessage(content)+ if (index === checkpointAt) await setReadCheckpoint(actors, channelId, id)+ }+ return { ids, estimates }+}++export async function seedDmProfile(+ actors: CaseActors,+ dmId: string,+ count: number,+): Promise<{ ids: string[]; estimates: Record<string, number> }> {+ const { seedDmMessage } = actors.seed+ const ids: string[] = []+ const estimates: Record<string, number> = {}+ for (let index = 0; index < count; index += 1) {+ const content = profileContent(index)+ const id = await seedDmMessage("alice", dmId, content)+ ids.push(id)+ estimates[id] = estimatePlainMessage(content)+ }+ return { ids, estimates }+}++export async function setReadCheckpoint(actors: CaseActors, channelId: string, messageId: string): Promise<void> {+ const response = await communityFixtureFetch(`${WEB_URL}/api/community/channels/${channelId}/read`, {+ method: "PUT",+ headers: {+ Cookie: actors.sessionCookie("alice"),+ "Content-Type": "application/json",+ Origin: WEB_URL,+ },+ body: JSON.stringify({ lastReadMessageId: messageId }),+ })+ expect(response.ok).toBe(true)+}++export function identity(channelId: string, viewport = VIEWPORT) {+ return createScrollTraceIdentity({+ account: "alice",+ channel: channelId,+ viewport: { ...viewport, dpr: 1 },+ })+}++export async function finishAndAttach(page: Page, testInfo: TestInfo): Promise<ScrollTraceResult> {+ await markScrollTrace(page, "final-stimulus")+ const result = await finishScrollTrace(page)+ await attachScrollTrace(testInfo, result)+ return result+}++export async function establishScrollDistancePrecondition(+ scroller: Locator,+ label: string,+ targetDistanceToEnd: number,+ tolerance = 1,+): Promise<{ scrollTop: number; scrollHeight: number; clientHeight: number; distanceToEnd: number }> {+ const readGeometry = () => scroller.evaluate((element) => ({+ scrollTop: element.scrollTop,+ scrollHeight: element.scrollHeight,+ clientHeight: element.clientHeight,+ distanceToEnd: Math.max(0, element.scrollHeight - element.clientHeight - element.scrollTop),+ })).then((geometry) => ({+ ...geometry,+ targetDistanceToEnd,+ atTarget: Math.abs(geometry.distanceToEnd - targetDistanceToEnd) <= tolerance,+ }))+ const driveToTarget = async () => {+ const geometry = await readGeometry()+ if (geometry.atTarget) return geometry+ await scroller.evaluate((element, targetDistance) => {+ element.scrollTop = Math.max(0, element.scrollHeight - element.clientHeight - targetDistance)+ element.dispatchEvent(new Event("scroll"))+ }, targetDistanceToEnd)+ return readGeometry()+ }+ await scroller.evaluate((element, targetDistance) => {+ element.scrollTop = Math.max(0, element.scrollHeight - element.clientHeight - targetDistance)+ element.dispatchEvent(new Event("scroll"))+ }, targetDistanceToEnd)+ await expect.poll(driveToTarget, {+ timeout: 20_000,+ message: `${label}: scroller must reach ${targetDistanceToEnd}px from end before the stimulus`,+ }).toMatchObject({ atTarget: true })+ await scroller.evaluate(() => new Promise<void>((resolveValue) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolveValue()))+ }))+ await expect.poll(driveToTarget, {+ timeout: 20_000,+ message: `${label}: ${targetDistanceToEnd}px distance must survive two committed RAFs`,+ }).toMatchObject({ atTarget: true })+ await scroller.evaluate(() => new Promise<void>((resolveValue) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolveValue()))+ }))+ await expect.poll(readGeometry, {+ timeout: 20_000,+ message: `${label}: ${targetDistanceToEnd}px distance must remain stable without another write`,+ }).toMatchObject({ atTarget: true })+ const { atTarget: _atTarget, targetDistanceToEnd: _target, ...geometry } = await readGeometry()+ return geometry+}++export async function establishExactPinnedPrecondition(+ scroller: Locator,+ label: string,+ targetDistanceToEnd: 0 | 1,+): Promise<{ scrollTop: number; scrollHeight: number; clientHeight: number; distanceToEnd: number }> {+ // The resize latch is intentionally monotonic: same-position/clamp events+ // at the end cannot recover false. Exercise its one valid recovery path by+ // first establishing away geometry, then scrolling forward into <=1px.+ await establishScrollDistancePrecondition(scroller, `${label}-away-first`, 8)+ return establishScrollDistancePrecondition(scroller, label, targetDistanceToEnd)+}++export async function establishTailMessageBelowViewportPrecondition(+ scroller: Locator,+ label: string,+ tailMessageId: string,+): Promise<void> {+ const driveTailBelowViewport = () => scroller.evaluate((element, messageId) => {+ const root = element as HTMLElement+ const rootRect = root.getBoundingClientRect()+ const tail = Array.from(root.querySelectorAll<HTMLElement>("[data-msg-id]"))+ .find((row) => row.dataset.msgId === messageId)+ const distanceToEnd = Math.max(0, root.scrollHeight - root.clientHeight - root.scrollTop)+ // A fresh virtualizer may not have mounted the known tail row yet even+ // while the viewport is still pinned. Only accept an absent row after an+ // actual away position has been established.+ const tailBelowViewport = tail+ ? tail.getBoundingClientRect().top >= rootRect.bottom - 1+ : distanceToEnd >= Math.max(1, root.clientHeight / 2)+ if (!tailBelowViewport) {+ root.scrollTop = Math.max(0, root.scrollTop - Math.max(400, root.clientHeight / 2))+ root.dispatchEvent(new Event("scroll"))+ }+ return { tailBelowViewport, scrollTop: root.scrollTop, distanceToEnd }+ }, tailMessageId)++ await expect.poll(driveTailBelowViewport, {+ timeout: 20_000,+ message: `${label}: tail row must leave the viewport so the accessory rail is semantically required`,+ }).toMatchObject({ tailBelowViewport: true })+ await scroller.evaluate(() => new Promise<void>((resolveValue) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolveValue()))+ }))+}++type MessageViewportGeometry = {+ scrollTop: number+ scrollHeight: number+ clientHeight: number+ distanceToEnd: number+ firstVisibleId: string | null+ firstVisibleOffset: number | null+ contentPaddingBottom: number+ railPosition: string | null+ railRect: { top: number; bottom: number; height: number } | null+ accessoryPosition: string | null+ accessoryRect: { top: number; bottom: number; height: number } | null+ railInFooter: boolean+ railInScroller: boolean+ composerRect: { top: number; bottom: number } | null+ surfaceChannelId: string | null+ scrollerRect: { top: number; bottom: number }+}++async function readMessageViewportGeometry(scroller: Locator): Promise<MessageViewportGeometry> {+ return scroller.evaluate((element, accessoryRailTestId) => {+ const root = element as HTMLElement+ const rootRect = root.getBoundingClientRect()+ const surface = root.closest<HTMLElement>('[data-slot="community-conversation-surface"]')+ const firstVisible = Array.from(root.querySelectorAll<HTMLElement>("[data-msg-id]"))+ .find((row) => {+ const rect = row.getBoundingClientRect()+ return rect.bottom > rootRect.top + 1 && rect.top < rootRect.bottom - 1+ }) ?? null+ const firstRect = firstVisible?.getBoundingClientRect() ?? null+ const content = root.querySelector<HTMLElement>("[data-message-list-content]")+ const composer = surface?.querySelector<HTMLElement>('[data-slot="community-conversation-footer"]')+ const composerRect = composer?.getBoundingClientRect() ?? null+ const accessory = composer?.querySelector<HTMLElement>('[data-slot="community-composer-accessory-slot"]')+ const accessoryRect = accessory?.getBoundingClientRect() ?? null+ const rail = accessory?.querySelector<HTMLElement>(`[data-testid="${accessoryRailTestId}"]`)+ const railRect = rail?.getBoundingClientRect() ?? null+ return {+ scrollTop: root.scrollTop,+ scrollHeight: root.scrollHeight,+ clientHeight: root.clientHeight,+ distanceToEnd: Math.max(0, root.scrollHeight - root.clientHeight - root.scrollTop),+ firstVisibleId: firstVisible?.dataset.msgId ?? null,+ firstVisibleOffset: firstRect ? firstRect.top - rootRect.top : null,+ contentPaddingBottom: content ? Number.parseFloat(getComputedStyle(content).paddingBottom) : 0,+ railPosition: rail ? getComputedStyle(rail).position : null,+ railRect: railRect ? { top: railRect.top, bottom: railRect.bottom, height: railRect.height } : null,+ accessoryPosition: accessory ? getComputedStyle(accessory).position : null,+ accessoryRect: accessoryRect ? { top: accessoryRect.top, bottom: accessoryRect.bottom, height: accessoryRect.height } : null,+ railInFooter: !!rail && rail.parentElement === accessory && rail.closest('[data-slot="community-conversation-footer"]') === composer,+ railInScroller: !!rail && !!rail.closest("[data-message-scroller-boundary]"),+ composerRect: composerRect ? { top: composerRect.top, bottom: composerRect.bottom } : null,+ surfaceChannelId: surface?.dataset.channelId ?? null,+ scrollerRect: { top: rootRect.top, bottom: rootRect.bottom },+ }+ }, tid.composerAccessoryRail)+}++export async function waitForCommittedGeometry(scroller: Locator): Promise<MessageViewportGeometry> {+ await scroller.evaluate(() => new Promise<void>((resolveValue) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolveValue()))+ }))+ let previous = ""+ let settled: MessageViewportGeometry | null = null+ await expect.poll(async () => {+ const geometry = await readMessageViewportGeometry(scroller)+ const signature = JSON.stringify(geometry)+ const stable = signature === previous+ previous = signature+ if (stable) settled = geometry+ return stable+ }, { timeout: 20_000 }).toBe(true)+ return settled!+}++export async function expectSkeletonTailGeometry(+ page: Page,+ _width: 390 | 1280,+ label: string,+): Promise<void> {+ const geometry = await page.locator("[data-message-list-skeleton-tail]").first().evaluate((tail, scrollerTestId) => {+ const tailRect = tail.getBoundingClientRect()+ const scroller = tail.closest<HTMLElement>("[data-message-list-content]")+ ?.closest<HTMLElement>(`[data-testid="${scrollerTestId}"]`)+ const scrollerRect = scroller?.getBoundingClientRect()+ const content = tail.closest<HTMLElement>("[data-message-list-content]")+ return {+ tailHeight: tailRect.height,+ tailBottom: tailRect.bottom,+ scrollerBottom: scrollerRect?.bottom ?? null,+ contentPaddingBottom: content+ ? Number.parseFloat(getComputedStyle(content).paddingBottom)+ : null,+ }+ }, tid.messageScroller)+ const expectedTail = 40+ expect(geometry.contentPaddingBottom, `${label}: outer padding`).toBe(0)+ expect(geometry.tailHeight, `${label}: placeholder height`).toBe(expectedTail)+ expect(geometry.scrollerBottom, `${label}: scroller boundary`).not.toBeNull()+ expect(+ Math.abs(geometry.tailBottom - geometry.scrollerBottom!),+ `${label}: placeholder ends at scroller bottom`,+ ).toBeLessThanOrEqual(1)+}++export async function waitForStableTail(scroller: Locator, label: string): Promise<void> {+ await expect.poll(async () => {+ const before = await readMessageViewportGeometry(scroller)+ await scroller.evaluate(() => new Promise<void>((resolveValue) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolveValue()))+ }))+ const after = await readMessageViewportGeometry(scroller)+ return {+ atTail: after.distanceToEnd <= 1,+ stable: Math.abs(after.scrollTop - before.scrollTop) <= 1+ && Math.abs(after.scrollHeight - before.scrollHeight) <= 1,+ }+ }, {+ timeout: 20_000,+ message: `${label}: product scroll-to-bottom must finish before exact-pinned setup`,+ }).toMatchObject({ atTail: true, stable: true })+}++export async function advanceScrollTraceFrame(scroller: Locator): Promise<void> {+ await scroller.evaluate(() => new Promise<void>((resolveValue) => {+ requestAnimationFrame(() => resolveValue())+ }))+}++export function expectViewportAnchorPreserved(+ before: MessageViewportGeometry,+ after: MessageViewportGeometry,+ label: string,+): void {+ expect(Math.abs(after.scrollTop - before.scrollTop), `${label}: scrollTop`).toBeLessThanOrEqual(1)+ expect(after.firstVisibleId, `${label}: first visible row`).toBe(before.firstVisibleId)+ expect(+ Math.abs((after.firstVisibleOffset ?? 0) - (before.firstVisibleOffset ?? 0)),+ `${label}: first visible offset`,+ ).toBeLessThanOrEqual(1)+}++export function expectResizeAnchorPreserved(+ before: MessageViewportGeometry,+ after: MessageViewportGeometry,+ distance: number,+ label: string,+): void {+ if (distance <= 100) {+ expect(+ Math.abs(after.distanceToEnd - before.distanceToEnd),+ `${label}: distance to tail`,+ ).toBeLessThanOrEqual(1)+ return+ }+ expectViewportAnchorPreserved(before, after, label)+}++export function expectContinuousResizeAnchorPreserved(+ trace: ScrollTraceResult,+ segmentName: string,+ distance: number,+): void {+ const start = trace.marks.find((mark) => mark.name === `analysis-start:${segmentName}`)+ const end = trace.marks.find((mark) => mark.name === `analysis-end:${segmentName}`)+ expect(start, `${segmentName}: start mark`).toBeDefined()+ expect(end, `${segmentName}: end mark`).toBeDefined()+ const frames = trace.frames.filter((frame) => (+ frame.frame >= start!.frame && frame.frame <= end!.frame+ ))+ expect(frames.length, `${segmentName}: continuous frames`).toBeGreaterThan(1)++ const baseline = frames[0]!+ if (distance <= 100) {+ for (const frame of frames) {+ expect(+ Math.abs(frame.distanceToEnd - baseline.distanceToEnd),+ `${segmentName}: frame ${frame.frame} tail-distance drift`,+ ).toBeLessThanOrEqual(1)+ }+ return+ }++ for (const frame of frames) {+ expect(frame.firstVisibleId, `${segmentName}: frame ${frame.frame} visible row`)+ .toBe(baseline.firstVisibleId)+ expect(+ Math.abs((frame.firstVisibleOffset ?? 0) - (baseline.firstVisibleOffset ?? 0)),+ `${segmentName}: frame ${frame.frame} visible-anchor drift`,+ ).toBeLessThanOrEqual(1)+ }+}++export function expectInFlowMessageGeometry(geometry: MessageViewportGeometry, label: string): void {+ expect(geometry.contentPaddingBottom, `${label}: outer tail padding removed`).toBe(0)+ expect(geometry.composerRect, `${label}: scoped composer`).not.toBeNull()+ if (geometry.railRect) {+ expect(geometry.railPosition, `${label}: rail position`).toBe("static")+ expect(geometry.railInFooter, `${label}: Footer owns rail`).toBe(true)+ expect(geometry.railInScroller, `${label}: rail outside scroller`).toBe(false)+ expect(geometry.accessoryPosition, `${label}: accessory position`).toBe("absolute")+ expect(geometry.accessoryRect, `${label}: accessory slot`).not.toBeNull()+ expect(geometry.accessoryRect!.height, `${label}: accessory height`).toBe(40)+ expect(geometry.railRect.height, `${label}: rail height`).toBe(32)+ expect(Math.abs(geometry.railRect.top - geometry.accessoryRect!.top - 4), `${label}: upper center gap`).toBeLessThanOrEqual(1)+ expect(Math.abs(geometry.accessoryRect!.bottom - geometry.railRect.bottom - 4), `${label}: lower center gap`).toBeLessThanOrEqual(1)+ expect(Math.abs(geometry.accessoryRect!.bottom - geometry.composerRect!.top), `${label}: slot ends at Footer`).toBeLessThanOrEqual(1)+ expect(geometry.railRect.top, `${label}: rail top`).toBeGreaterThanOrEqual(geometry.scrollerRect.top - 1)+ expect(geometry.railRect.bottom, `${label}: rail bottom`).toBeLessThanOrEqual(geometry.scrollerRect.bottom + 1)+ expect(geometry.railRect.bottom, `${label}: rail clears composer`).toBeLessThanOrEqual(+ geometry.composerRect!.top + 1,+ )+ }+}++export function messageCreateCount(+ frames: Awaited<ReturnType<typeof proxyCommunityWebSockets>>["frames"],+ channelId: string,+ body: string,+): number {+ return frames.filter((frame) => communityFrameEvents(frame).some((event) =>+ event.type === "community:message.create"+ && event.channelId === channelId+ && event.message?.content?.includes(body))).length+}++export type PostedMessageIdentity = { id: string; seq: number; channelId: string; authorId: string; content: string }++export async function expectMessageCreateIdentity(+ frames: Awaited<ReturnType<typeof proxyCommunityWebSockets>>["frames"],+ channelId: string,+ message: PostedMessageIdentity,+ nonce: string,+): Promise<void> {+ expect(message.id.length).toBeGreaterThan(0)+ expect(message.seq).toBeGreaterThan(0)+ await expect.poll(() => frames.flatMap(communityFrameEvents).filter(event =>+ event.type === "community:message.create" && event.channelId === channelId && event.message?.id === message.id,+ ).length).toBe(1)+ const created = frames.flatMap(communityFrameEvents).find(event =>+ event.type === "community:message.create" && event.channelId === channelId && event.message?.id === message.id,+ )!+ expect(created.message).toMatchObject({ id: message.id, seq: message.seq, authorId: message.authorId, clientNonce: nonce })+}++export async function seedScrollServer(actors: CaseActors) {+ const { seedServer, seedJoinServer } = actors.seed+ const serverId = await seedServer("alice", `Scroll characterization ${Date.now()}`)+ await seedJoinServer("alice", "bob", serverId)+ await seedJoinServer("alice", "carol", serverId)+ return serverId+}++export async function seedScrollCase(actors: CaseActors) {+ const { seedChannel, seedDm } = actors.seed+ const { userId } = actors+ const stamp = Date.now()+ const serverId = await seedScrollServer(actors)+ const coldChannelId = await seedChannel("alice", serverId, `scroll-cold-${stamp}`)+ const loadingChannelId = await seedChannel("alice", serverId, `scroll-loading-${stamp}`)+ const upwardChannelId = await seedChannel("alice", serverId, `scroll-upward-${stamp}`)+ const composerChannelId = await seedChannel("alice", serverId, `scroll-composer-${stamp}`)+ const composerDmId = await seedDm("alice", userId("bob"))+ const loadingProfile = await seedProfile(actors, loadingChannelId, 130, false, "rotate", 64)+ const upwardProfile = await seedProfile(actors, upwardChannelId, 72, false, "rotate", 23)+ const composerProfile = await seedProfile(actors, composerChannelId, 36, true, "alice")+ const composerDmProfile = await seedDmProfile(actors, composerDmId, 36)+ return { serverId, coldChannelId, loadingChannelId, upwardChannelId, composerChannelId, composerDmId, loadingProfile, upwardProfile, composerProfile, composerDmProfile }+}++export function tracedAsUser(actors: CaseActors): CaseActors["asUser"] {+ return async (key, options) => {+ const opened = await actors.asUser(key, options)+ actors.onCleanup(async () => {+ if (!opened.page.isClosed()) await abortScrollTrace(opened.page)+ })+ return opened+ }+}diff --git a/src/web/src/test/e2e-ui/_fixtures/mobile-notification-activation.ts b/src/web/src/test/e2e-ui/_fixtures/mobile-notification-activation.tsnew file mode 100644index 000000000..7aaee8f3a--- /dev/null+++ b/src/web/src/test/e2e-ui/_fixtures/mobile-notification-activation.ts@@ -0,0 +1,137 @@+import type { z } from "zod"+import { communityFixtureFetch } from "./business-contract"+import { type Page } from "@playwright/test"+import { CommunityMessageReadSchema } from "@alook/shared"+import { expect } from "./case-fixture"+import { WEB_URL } from "../_setup/paths"+import type { CaseActors } from "./case-fixture"++type Activation = { notificationId: string; messageId: string; targetId: string }++export type Bridge = { pending: Activation | null; listener: unknown; takes: number; dismissed: string[]; visibility: DocumentVisibilityState; documentLoads: number }++export async function installMobileBridge(page: Page, activation: Activation | null) {+ await page.addInitScript((initial) => {+ const key = `qa-mobile-consumed:${initial?.notificationId}`+ const dismissedKey = "qa-mobile-notification-dismissed"+ const documentLoads = Number(sessionStorage.getItem("qa-mobile-document-loads") ?? "0") + 1+ sessionStorage.setItem("qa-mobile-document-loads", String(documentLoads))+ const state: Bridge = {+ documentLoads,+ pending: initial && !sessionStorage.getItem(key) ? initial : null,+ listener: null,+ takes: 0,+ dismissed: JSON.parse(sessionStorage.getItem(dismissedKey) ?? "[]") as string[],+ visibility: "visible",+ }+ Object.defineProperty(document, "visibilityState", { configurable: true, get: () => state.visibility })+ Object.defineProperty(window, "__mobileNotificationQa", { configurable: true, value: state })+ class Channel { onmessage?: (value: unknown) => void }+ Object.defineProperty(window, "__TAURI__", {+ configurable: true,+ value: { core: { Channel, invoke: async (command: string, args?: Record<string, unknown>) => {+ if (command === "mobile_system_notification_listen") { state.listener = args?.channel; return 1 }+ if (command === "mobile_system_notification_take_activation") {+ state.takes += 1+ const value = state.pending+ state.pending = null+ if (value) sessionStorage.setItem(key, "1")+ return value+ }+ if (command === "mobile_system_notification_check_permission" || command === "mobile_system_notification_request_permission") return { permissionState: "prompt" }+ if (command === "mobile_system_notification_dismiss") {+ state.dismissed.push(args?.notificationId as string)+ sessionStorage.setItem(dismissedKey, JSON.stringify(state.dismissed))+ return undefined+ }+ return undefined+ } } },+ })+ }, activation)+}++export async function resumeActivation(page: Page, activation: Activation) {+ await expect.poll(() => page.evaluate(() => (window as typeof window & { __mobileNotificationQa: Bridge }).__mobileNotificationQa.takes)).toBeGreaterThan(0)+ await page.evaluate((value) => {+ const state = (window as typeof window & { __mobileNotificationQa: Bridge }).__mobileNotificationQa+ state.visibility = "hidden"+ document.dispatchEvent(new Event("visibilitychange"))+ state.pending = value+ state.visibility = "visible"+ document.dispatchEvent(new Event("visibilitychange"))+ }, activation)+}++export async function foregroundActivation(page: Page, activation: Activation) {+ await expect.poll(() => page.evaluate(() => Boolean((+ window as typeof window & { __mobileNotificationQa: Bridge }+ ).__mobileNotificationQa.listener))).toBe(true)+ await page.evaluate((value) => {+ const state = (window as typeof window & { __mobileNotificationQa: Bridge }).__mobileNotificationQa+ state.pending = value+ ;(state.listener as { onmessage: (value: unknown) => void }).onmessage({})+ }, activation)+}++type MessageDoorEvidence = {+ status: number+ payload: z.infer<typeof CommunityMessageReadSchema>+}++export async function prepareCase1(actors: CaseActors) {+ async function deleteAsAlice(path: string) {+ const response = await communityFixtureFetch(`${WEB_URL}${path}`, { method: "DELETE", headers: { Cookie: sessionCookie("alice"), Origin: WEB_URL } })+ expect(response.ok, `${path}: ${response.status}`).toBeTruthy()+ }+ async function captureMessageDoor(page: Page, targetId: string, messageId: string) {+ let observed: MessageDoorEvidence | undefined+ let requests = 0+ let capture!: (evidence: MessageDoorEvidence) => void+ let fail!: (error: unknown) => void+ const result = new Promise<MessageDoorEvidence>((resolve, reject) => {+ capture = resolve+ fail = reject+ })+ void result.catch(() => undefined)+ await page.route((url) => url.pathname === `/api/community/messages/${messageId}`, async (route) => {+ requests += 1+ try {+ const response = await route.fetch()+ const payload = await response.json()+ const evidence = { status: response.status(), payload }+ if (response.ok())+ expect(payload.channelId).toBe(targetId)+ observed = evidence+ await route.fulfill({ response })+ capture(evidence)+ }+ catch (error) {+ fail(error)+ await route.abort()+ }+ })+ return { result, evidence: () => observed, requestCount: () => requests }+ }+ const { sessionCookie, userId } = actors+ const { seedChannel, seedDm, seedDmMessage, seedFriendship, seedJoinServer, seedMessage, seedServer } = actors.seed+ const serverId: string = await seedServer("alice", `mobile-route-${Date.now()}`)+ const channelId: string = await seedChannel("alice", serverId, "notification-chat")+ await seedJoinServer("alice", "bob", serverId)+ const channelMessageId: string = await seedMessage("alice", channelId, "Channel notification route evidence")+ await seedFriendship("alice", "bob", userId("bob"))+ const dmId: string = await seedDm("alice", userId("bob"))+ const dmMessageId: string = await seedDmMessage("alice", dmId, "DM notification route evidence")+ const seqs = await Promise.all([[dmId, dmMessageId], [channelId, channelMessageId]].map(async ([targetId, messageId]) => {+ const response = await communityFixtureFetch(`${WEB_URL}/api/community/channels/${targetId}/messages?anchor=${messageId}&limit=1`, { headers: { Cookie: sessionCookie("bob") } })+ expect(response.status).toBe(200)+ const payload = await response.json() as {+ messages: Array<{+ id: string+ seq: number+ }>+ }+ return payload.messages.find((message) => message.id === messageId)!.seq+ }));+ const [dmSeq, channelSeq] = seqs+ return { deleteAsAlice, serverId, channelId, channelMessageId, dmId, dmMessageId, dmSeq, channelSeq, captureMessageDoor }+ }diff --git a/src/web/src/test/e2e-ui/_setup/paths.ts b/src/web/src/test/e2e-ui/_setup/paths.tsindex ea9ba037d..ab74b6453 100644--- a/src/web/src/test/e2e-ui/_setup/paths.ts+++ b/src/web/src/test/e2e-ui/_setup/paths.ts@@ -54,3 +54,10 @@ export const MACHINE_WS_URL = resolveMachineWsUrl({wsUrl: WS_URL,singleRuntime: SINGLE_RUNTIME,})++export function requiredE2EZones(input = process.env.ALOOK_E2E_ZONES): Array<"web" | "blog"> {+ const zones: unknown = input === undefined ? ["web", "blog"] : JSON.parse(input)+ if (!Array.isArray(zones) || !zones.includes("web") || new Set(zones).size !== zones.length+ || zones.some(zone => zone !== "web" && zone !== "blog")) throw new Error("Invalid E2E service zones")+ return zones+}diff --git a/src/web/src/test/e2e-ui/_setup/services.ts b/src/web/src/test/e2e-ui/_setup/services.tsindex df31b37ad..4bcbd7da8 100644--- a/src/web/src/test/e2e-ui/_setup/services.ts+++ b/src/web/src/test/e2e-ui/_setup/services.ts@@ -4,7 +4,7 @@ import { createHash } from "node:crypto"import { chmodSync, closeSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "fs"import { dirname, resolve } from "path"import { assertPublicStaticWriteSeparation, canonicalPhasePath, readPhaseFile, readPublicStaticManifest } from "../../../../scripts/dev-zone-processes.mjs"-import { AUTH_DIR, QUEUE_URL, REPO_ROOT, resolveWsUrl, SERVICE_LOG_DIR, SERVICE_STATE_PATH, SINGLE_RUNTIME, WEB_URL } from "./paths"+import { AUTH_DIR, QUEUE_URL, REPO_ROOT, requiredE2EZones, resolveWsUrl, SERVICE_LOG_DIR, SERVICE_STATE_PATH, SINGLE_RUNTIME, WEB_URL } from "./paths"import {addServiceProcess,applyHealthProbe,@@ -334,10 +334,11 @@ export function serviceBuildCommands(singleRuntime = SINGLE_RUNTIME,prebuilt = process.env.ALOOK_E2E_PREBUILT === "1",root = REPO_ROOT,-): Array<{ name: string; args: string[] }> {+ zones = requiredE2EZones(),+): Array<{ name: string; command: string; args: string[] }> {if (!singleRuntime) return []if (prebuilt) {- for (const entrypoint of E2E_PREBUILT_ENTRYPOINTS) {+ for (const entrypoint of E2E_PREBUILT_ENTRYPOINTS.filter(path => !path.includes("/blog/") || zones.includes("blog"))) {const path = resolve(root, entrypoint)if (!existsSync(path) || !statSync(path).isFile()) {throw new Error(`prebuilt OpenNext worker entrypoint is missing: ${path}`)@@ -345,16 +346,11 @@ export function serviceBuildCommands(}return []}- return [- {- name: "web worker",- args: ["--filter", "@alook/web", "exec", "opennextjs-cloudflare", "build"],- },- {- name: "Blog worker",- args: ["--filter", "@alook/web", "build:blog"],- },- ]+ return zones.map(zone => ({+ name: zone === "web" ? "web worker" : "Blog worker",+ command: "node",+ args: ["scripts/ci/run-turbo.mjs", "run", zone === "web" ? "@alook/web#build" : "@alook/web#build:blog"],+ }))}export function prepareServices(): void {@@ -362,7 +358,7 @@ export function prepareServices(): void {const builds = phaseManifest ? [] : serviceBuildCommands()backupState()for (const build of builds) {- const res = spawnSync("pnpm", build.args, {+ const res = spawnSync(build.command, build.args, {cwd: REPO_ROOT,stdio: "inherit",env: {@@ -434,7 +430,7 @@ function killPortOrphans(ports: number[]): void {}}-export function serviceDefinitions(singleRuntime = SINGLE_RUNTIME): ServiceDefinition[] {+export function serviceDefinitions(singleRuntime = SINGLE_RUNTIME, zones = requiredE2EZones()): ServiceDefinition[] {const webHealth = `${WEB_URL}/api/health`if (!singleRuntime) {const wsHealth = `${resolveWsUrl({@@ -472,6 +468,7 @@ export function serviceDefinitions(singleRuntime = SINGLE_RUNTIME): ServiceDefinconst runtime = resolveE2EWranglerRuntime()const phaseManifest = publicStaticQaManifest(false)+ if (phaseManifest && !zones.includes("blog")) throw new Error("Public static release phases require both zones")return [{name: "web-zones",command: "pnpm",@@ -482,6 +479,7 @@ export function serviceDefinitions(singleRuntime = SINGLE_RUNTIME): ServiceDefin"--with-ws-do","--wrangler-entry",runtime.entry,+ ...(!zones.includes("blog") ? ["--web-only"] : []),...(phaseManifest ? ["--public-static-manifest", resolve(process.env.ALOOK_E2E_RELEASE_MANIFEST!), "--public-static-owner-root", AUTH_DIR] : []),],healthUrl: webHealth,diff --git a/src/web/src/test/react-dom-setup.ts b/src/web/src/test/react-dom-setup.tsindex b9e762299..9149c4ca1 100644--- a/src/web/src/test/react-dom-setup.ts+++ b/src/web/src/test/react-dom-setup.ts@@ -1 +1,7 @@-import "@testing-library/jest-dom/vitest"+import { expect } from "vitest"+import * as matchers from "@testing-library/jest-dom/matchers"+import type {} from "@testing-library/jest-dom/vitest"++// Use the current runner's expect. The external Vitest adapter can load a+// second pnpm peer instance when these projects run from the repository root.+expect.extend(matchers)diff --git a/src/web/tsconfig.eslint.json b/src/web/tsconfig.eslint.jsonindex 25de43e55..7fe3d8b7b 100644--- a/src/web/tsconfig.eslint.json+++ b/src/web/tsconfig.eslint.json@@ -9,10 +9,14 @@"src/**/*","src/app/.well-known/**/*.ts","scripts/**/*",- "app-store-capture/**/*"+ "app-store-capture/**/*",+ "readme-capture/**/*"],"exclude": [- "node_modules"+ "node_modules",+ "**/.next/**",+ "**/.open-next/**",+ "**/.wrangler/**"],"files": ["src/components/community/messages/composer-accessory-rail.dom.test.tsx"diff --git a/src/web/vitest.config.ts b/src/web/vitest.config.tsindex 17c24b481..6106ffee9 100644--- a/src/web/vitest.config.ts+++ b/src/web/vitest.config.ts@@ -1,21 +1,10 @@-import path from "path"-import { defineConfig, mergeConfig } from "vitest/config"-import shared from "../../vitest.shared"+import { webTestConfig } from "./vitest.shared"-export default mergeConfig(shared, defineConfig({- resolve: {- alias: {- "@": path.resolve(__dirname, "src"),- "@blog": path.resolve(__dirname, "blog/src"),- "./.open-next/worker.js": path.resolve(__dirname, "src/test-runtime/open-next-node-stub.ts"),- "./.open-next/server-functions/default/src/web/.next/required-server-files.json": path.resolve(__dirname, "test-runtime/next-config-stub.json"),- },- },+export default webTestConfig({test: {name: "web-node",- testTimeout: 30_000,- hookTimeout: 30_000,- include: ["src/**/*.test.ts", "scripts/**/*.test.ts", "blog/**/*.test.ts", "readme-capture/**/*.test.ts", "app-store-capture/**/*.test.ts"],- exclude: ["**/*.dom.test.{ts,tsx}", "src/test/e2e/**", "src/test/e2e-ui/**"],+ server: { deps: { inline: ["better-auth"] } },+ include: ["src/**/*.test.ts"],+ exclude: ["**/*.dom.test.{ts,tsx}", "src/test/e2e/**", "src/test/e2e-ui/**", "src/test/architecture/**", "src/**/*.architecture.test.ts", "src/test/e2e-*.test.ts"],},-}))+})diff --git a/src/web/vitest.contracts.config.ts b/src/web/vitest.contracts.config.tsnew file mode 100644index 000000000..c5d7574f8--- /dev/null+++ b/src/web/vitest.contracts.config.ts@@ -0,0 +1,8 @@+import { webTestConfig } from "./vitest.shared"++export default webTestConfig({+ test: {+ name: "web-contracts",+ include: ["src/test/architecture/**/*.test.ts", "src/**/*.architecture.test.ts"],+ },+})diff --git a/src/web/vitest.dom.config.ts b/src/web/vitest.dom.config.tsindex 347ab4a55..d5c597358 100644--- a/src/web/vitest.dom.config.ts+++ b/src/web/vitest.dom.config.ts@@ -1,29 +1,11 @@-import path from "path"-import { defineConfig, mergeConfig } from "vitest/config"-import shared from "../../vitest.shared"+import { webTestConfig } from "./vitest.shared"-export default mergeConfig(shared, defineConfig({- resolve: {- alias: {- "@": path.resolve(__dirname, "src"),- "@blog": path.resolve(__dirname, "blog/src"),- "./.open-next/worker.js": path.resolve(__dirname, "src/test-runtime/open-next-node-stub.ts"),- "./.open-next/server-functions/default/src/web/.next/required-server-files.json": path.resolve(__dirname, "test-runtime/next-config-stub.json"),- },- },+export default webTestConfig({test: {name: "web-dom",environment: "jsdom",- testTimeout: 30_000,- hookTimeout: 30_000,- include: [- "src/**/*.dom.test.{ts,tsx}",- "blog/**/*.dom.test.{ts,tsx}",- "scripts/**/*.dom.test.{ts,tsx}",- "readme-capture/**/*.dom.test.{ts,tsx}",- "app-store-capture/**/*.dom.test.{ts,tsx}",- ],+ include: ["src/**/*.dom.test.{ts,tsx}", "scripts/**/*.dom.test.{ts,tsx}", "readme-capture/**/*.dom.test.{ts,tsx}", "app-store-capture/**/*.dom.test.{ts,tsx}"],exclude: ["src/test/e2e/**", "src/test/e2e-ui/**"],setupFiles: ["src/test/react-dom-setup.ts"],},-}))+})diff --git a/src/web/vitest.runtime.config.mts b/src/web/vitest.runtime.config.mtsindex 5334ccaf0..663084939 100644--- a/src/web/vitest.runtime.config.mts+++ b/src/web/vitest.runtime.config.mts@@ -9,7 +9,7 @@ export default defineProject({alias: {"@": path.resolve(import.meta.dirname, "src"),"./.open-next/server-functions/default/src/web/.next/required-server-files.json": path.resolve(import.meta.dirname, "test-runtime/next-config-stub.json"),- "./.open-next/worker.js": path.resolve(+ "#open-next-worker": path.resolve(import.meta.dirname,"test-runtime/open-next-worker-stub.ts",),diff --git a/src/web/vitest.shared.ts b/src/web/vitest.shared.tsnew file mode 100644index 000000000..c0b13615a--- /dev/null+++ b/src/web/vitest.shared.ts@@ -0,0 +1,18 @@+import path from "node:path"+import { defineConfig, mergeConfig, type ViteUserConfig } from "vitest/config"+import shared from "../../vitest.shared"++export function webTestConfig(config: ViteUserConfig) {+ return mergeConfig(mergeConfig(shared, defineConfig({+ root: import.meta.dirname,+ resolve: {+ alias: {+ "@": path.resolve(import.meta.dirname, "src"),+ "@blog": path.resolve(import.meta.dirname, "blog/src"),+ "#open-next-worker": path.resolve(import.meta.dirname, "src/test-runtime/open-next-node-stub.ts"),+ "./.open-next/server-functions/default/src/web/.next/required-server-files.json": path.resolve(import.meta.dirname, "test-runtime/next-config-stub.json"),+ },+ },+ test: { testTimeout: 30_000, hookTimeout: 30_000 },+ })), config)+}diff --git a/src/web/vitest.tooling.config.ts b/src/web/vitest.tooling.config.tsnew file mode 100644index 000000000..3e4c1328c--- /dev/null+++ b/src/web/vitest.tooling.config.ts@@ -0,0 +1,9 @@+import { webTestConfig } from "./vitest.shared"++export default webTestConfig({+ test: {+ name: "web-tooling",+ include: ["src/test/e2e-*.test.ts", "scripts/**/*.test.ts", "readme-capture/**/*.test.ts", "app-store-capture/**/*.test.ts"],+ exclude: ["**/*.dom.test.{ts,tsx}"],+ },+})diff --git a/src/web/vitest.workspace.config.ts b/src/web/vitest.workspace.config.tsindex 1cc804012..511c10915 100644--- a/src/web/vitest.workspace.config.ts+++ b/src/web/vitest.workspace.config.ts@@ -1,13 +1,5 @@import { defineConfig } from "vitest/config"export default defineConfig({- test: {- projects: [- "./vitest.config.ts",- "./vitest.dom.config.ts",- "./vitest.runtime.config.mts",- "./auth/vitest.config.ts",- "./auth/vitest.runtime.config.mts",- ],- },+ test: { projects: ["./vitest.config.ts", "./vitest.dom.config.ts"] },})diff --git a/src/ws-do/package.json b/src/ws-do/package.jsonindex ebd7886f5..47d7311f7 100644--- a/src/ws-do/package.json+++ b/src/ws-do/package.json@@ -6,8 +6,10 @@"dev": "node ../../scripts/dev-with-wrangler-registry.mjs ../../.wrangler/registry wrangler dev --persist-to ../web/.wrangler/state","deploy": "wrangler deploy","knip": "knip",- "test": "vitest run --config vitest.workspace.config.ts",- "typecheck": "tsc --noEmit -p tsconfig.typecheck.json"+ "test": "vitest run --config vitest.config.ts",+ "typecheck": "tsc --noEmit -p tsconfig.typecheck.json",+ "test:runtime": "vitest run --config vitest.runtime.config.mts",+ "build": "wrangler deploy --dry-run --outdir dist"},"dependencies": {"@alook/shared": "workspace:*"@@ -18,7 +20,7 @@"@types/node": "^25.9.4","knip": "^6.32.2","typescript": "^6.0.3",- "vitest": "4.1.12",+ "vitest": "5.1.0","wrangler": "4.152.0"}}diff --git a/tests/utils/package.json b/tests/utils/package.jsonindex fb42c5b43..2ebeaac0b 100644--- a/tests/utils/package.json+++ b/tests/utils/package.json@@ -18,6 +18,6 @@"@types/better-sqlite3": "^7.6.13","@types/node": "^25.9.4","typescript": "^6.0.3",- "vitest": "4.1.12"+ "vitest": "5.1.0"}}diff --git a/turbo.json b/turbo.jsonindex 2f613f504..e30ea80a7 100644--- a/turbo.json+++ b/turbo.json@@ -1,11 +1,885 @@{"$schema": "https://turbo.build/schema.json","tasks": {- "build": { "dependsOn": ["^build"], "outputs": ["dist/**"] },- "test": { "dependsOn": ["^build"] },- "typecheck": { "dependsOn": ["^build"] },- "lint": {},- "knip": {},- "dev": { "cache": false, "persistent": true }- }+ "source": {+ "dependsOn": [+ "^source"+ ]+ },+ "build": {+ "dependsOn": [+ "^build"+ ],+ "outputs": [+ "dist/**"+ ],+ "env": [+ "ALOOK_TASK_BUN"+ ],+ "inputs": [+ "$TURBO_DEFAULT$",+ "$TURBO_ROOT$/scripts/ci/run-turbo.mjs"+ ]+ },+ "test": {+ "dependsOn": [+ "^source"+ ],+ "inputs": [+ "$TURBO_DEFAULT$",+ "$TURBO_ROOT$/vitest.shared.ts",+ "$TURBO_ROOT$/vitest.config.ts"+ ],+ "outputs": []+ },+ "test:runtime": {+ "dependsOn": [+ "^source"+ ],+ "inputs": [+ "$TURBO_DEFAULT$",+ "$TURBO_ROOT$/vitest.shared.ts",+ "$TURBO_ROOT$/vitest.config.ts"+ ],+ "outputs": [],+ "cache": false+ },+ "typecheck": {+ "dependsOn": [+ "^source"+ ],+ "inputs": [+ "$TURBO_DEFAULT$"+ ]+ },+ "lint": {+ "dependsOn": [+ "^source"+ ]+ },+ "knip": {+ "dependsOn": [+ "^source"+ ]+ },+ "dev": {+ "cache": false,+ "persistent": true+ },+ "@alook/web#typecheck": {+ "dependsOn": [+ "^source"+ ],+ "inputs": [+ "package.json",+ "tsconfig*.json",+ "eslint.config.mjs",+ "vitest*.{ts,mts}",+ "src/**",+ "scripts/**",+ "public/**",+ "test-runtime/**",+ "migrations/**",+ "custom-worker.ts",+ "next.config.ts",+ "open-next.config.ts",+ "postcss.config.mjs",+ "wrangler*.toml",+ "readme-capture/**",+ "app-store-capture/**",+ "$TURBO_ROOT$/vitest.shared.ts",+ "$TURBO_ROOT$/vitest.config.ts",+ "cloudflare-env.d.ts",+ "!**/{node_modules,.next,.open-next,.wrangler,.turbo,dist,coverage}/**",+ "!**/{test-results,blob-report,e2e-service-logs,e2e-shard-manifest,.auth}/**",+ "!public/sw.js",+ "!public/sw.js.map",+ "!public/community-shell/**",+ "!**/*.tsbuildinfo",+ "!blog/package.json",+ "!blog/public/alook.svg",+ "!blog/public/apple-touch-icon.png",+ "!blog/public/favicon.ico",+ "!blog/public/icon-192.png",+ "!blog/public/fonts/dm-sans-600.ttf",+ "open-next-worker.d.ts",+ "open-next-handler.d.ts"+ ]+ },+ "@alook/web#lint": {+ "dependsOn": [+ "^source"+ ],+ "inputs": [+ "package.json",+ "tsconfig*.json",+ "eslint.config.mjs",+ "vitest*.{ts,mts}",+ "src/**",+ "scripts/**",+ "public/**",+ "test-runtime/**",+ "migrations/**",+ "custom-worker.ts",+ "next.config.ts",+ "open-next.config.ts",+ "postcss.config.mjs",+ "wrangler*.toml",+ "readme-capture/**",+ "app-store-capture/**",+ "$TURBO_ROOT$/vitest.shared.ts",+ "$TURBO_ROOT$/vitest.config.ts",+ "cloudflare-env.d.ts",+ "!**/{node_modules,.next,.open-next,.wrangler,.turbo,dist,coverage}/**",+ "!**/{test-results,blob-report,e2e-service-logs,e2e-shard-manifest,.auth}/**",+ "!public/sw.js",+ "!public/sw.js.map",+ "!public/community-shell/**",+ "!**/*.tsbuildinfo",+ "!blog/package.json",+ "!blog/public/alook.svg",+ "!blog/public/apple-touch-icon.png",+ "!blog/public/favicon.ico",+ "!blog/public/icon-192.png",+ "!blog/public/fonts/dm-sans-600.ttf",+ "open-next-worker.d.ts",+ "open-next-handler.d.ts"+ ]+ },+ "@alook/web#test": {+ "dependsOn": [+ "^source"+ ],+ "inputs": [+ "package.json",+ "tsconfig*.json",+ "eslint.config.mjs",+ "vitest*.{ts,mts}",+ "src/**",+ "scripts/**",+ "public/**",+ "test-runtime/**",+ "migrations/**",+ "custom-worker.ts",+ "next.config.ts",+ "open-next.config.ts",+ "postcss.config.mjs",+ "wrangler*.toml",+ "readme-capture/**",+ "app-store-capture/**",+ "$TURBO_ROOT$/vitest.shared.ts",+ "$TURBO_ROOT$/vitest.config.ts",+ "$TURBO_ROOT$/assets/**",+ "$TURBO_ROOT$/README.md",+ "$TURBO_ROOT$/src/desktop/src-tauri/{tauri.conf.json,Cargo.toml}",+ "cloudflare-env.d.ts",+ "!**/{node_modules,.next,.open-next,.wrangler,.turbo,dist,coverage}/**",+ "!**/{test-results,blob-report,e2e-service-logs,e2e-shard-manifest,.auth}/**",+ "!public/sw.js",+ "!public/sw.js.map",+ "!public/community-shell/**",+ "!**/*.tsbuildinfo",+ "!blog/package.json",+ "!blog/public/alook.svg",+ "!blog/public/apple-touch-icon.png",+ "!blog/public/favicon.ico",+ "!blog/public/icon-192.png",+ "!blog/public/fonts/dm-sans-600.ttf",+ "open-next-worker.d.ts",+ "open-next-handler.d.ts"+ ],+ "outputs": []+ },+ "@alook/web#typecheck:blog": {+ "dependsOn": [+ "^source"+ ],+ "inputs": [+ "package.json",+ "tsconfig*.json",+ "eslint.config.mjs",+ "vitest*.{ts,mts}",+ "blog/**",+ "public/alook.svg",+ "public/apple-touch-icon.png",+ "public/icon-192.png",+ "public/fonts/**",+ "src/app/_og/**",+ "src/app/fonts.ts",+ "src/app/globals.css",+ "src/hooks/**",+ "src/stores/**",+ "src/lib/**",+ "src/test/{react-dom*,test-harness*,testids*}",+ "$TURBO_ROOT$/vitest.shared.ts",+ "$TURBO_ROOT$/vitest.config.ts",+ "cloudflare-env.d.ts",+ "src/components/**",+ "!src/components/auth/**",+ "!src/components/download/**",+ "src/contexts/**",+ "src/*.d.ts",+ "src/app/favicon.ico",+ "!**/{node_modules,.next,.open-next,.wrangler,.turbo,dist,coverage}/**",+ "!**/{test-results,blob-report,e2e-service-logs,e2e-shard-manifest,.auth}/**",+ "!public/sw.js",+ "!public/sw.js.map",+ "!public/community-shell/**",+ "!**/*.tsbuildinfo",+ "!blog/package.json",+ "!blog/public/alook.svg",+ "!blog/public/apple-touch-icon.png",+ "!blog/public/favicon.ico",+ "!blog/public/icon-192.png",+ "!blog/public/fonts/dm-sans-600.ttf",+ "open-next-worker.d.ts",+ "open-next-handler.d.ts"+ ]+ },+ "@alook/web#lint:blog": {+ "dependsOn": [+ "^source"+ ],+ "inputs": [+ "package.json",+ "tsconfig*.json",+ "eslint.config.mjs",+ "vitest*.{ts,mts}",+ "blog/**",+ "public/alook.svg",+ "public/apple-touch-icon.png",+ "public/icon-192.png",+ "public/fonts/**",+ "src/app/_og/**",+ "src/app/fonts.ts",+ "src/app/globals.css",+ "src/hooks/**",+ "src/stores/**",+ "src/lib/**",+ "src/test/{react-dom*,test-harness*,testids*}",+ "$TURBO_ROOT$/vitest.shared.ts",+ "$TURBO_ROOT$/vitest.config.ts",+ "cloudflare-env.d.ts",+ "src/components/**",+ "!src/components/auth/**",+ "!src/components/download/**",+ "src/contexts/**",+ "src/*.d.ts",+ "src/app/favicon.ico",+ "!**/{node_modules,.next,.open-next,.wrangler,.turbo,dist,coverage}/**",+ "!**/{test-results,blob-report,e2e-service-logs,e2e-shard-manifest,.auth}/**",+ "!public/sw.js",+ "!public/sw.js.map",+ "!public/community-shell/**",+ "!**/*.tsbuildinfo",+ "!blog/package.json",+ "!blog/public/alook.svg",+ "!blog/public/apple-touch-icon.png",+ "!blog/public/favicon.ico",+ "!blog/public/icon-192.png",+ "!blog/public/fonts/dm-sans-600.ttf",+ "open-next-worker.d.ts",+ "open-next-handler.d.ts"+ ]+ },+ "@alook/web#test:blog": {+ "dependsOn": [+ "^source"+ ],+ "inputs": [+ "package.json",+ "tsconfig*.json",+ "eslint.config.mjs",+ "vitest*.{ts,mts}",+ "blog/**",+ "public/alook.svg",+ "public/apple-touch-icon.png",+ "public/icon-192.png",+ "public/fonts/**",+ "src/app/_og/**",+ "src/app/fonts.ts",+ "src/app/globals.css",+ "src/hooks/**",+ "src/stores/**",+ "src/lib/**",+ "src/test/{react-dom*,test-harness*,testids*}",+ "$TURBO_ROOT$/vitest.shared.ts",+ "$TURBO_ROOT$/vitest.config.ts",+ "cloudflare-env.d.ts",+ "src/components/**",+ "!src/components/auth/**",+ "!src/components/download/**",+ "src/contexts/**",+ "src/*.d.ts",+ "src/app/favicon.ico",+ "!**/{node_modules,.next,.open-next,.wrangler,.turbo,dist,coverage}/**",+ "!**/{test-results,blob-report,e2e-service-logs,e2e-shard-manifest,.auth}/**",+ "!public/sw.js",+ "!public/sw.js.map",+ "!public/community-shell/**",+ "!**/*.tsbuildinfo",+ "!blog/package.json",+ "!blog/public/alook.svg",+ "!blog/public/apple-touch-icon.png",+ "!blog/public/favicon.ico",+ "!blog/public/icon-192.png",+ "!blog/public/fonts/dm-sans-600.ttf",+ "open-next-worker.d.ts",+ "open-next-handler.d.ts"+ ],+ "outputs": []+ },+ "@alook/web#typecheck:auth": {+ "dependsOn": [],+ "inputs": [+ "package.json",+ "tsconfig*.json",+ "eslint.config.mjs",+ "vitest*.{ts,mts}",+ "auth/**",+ "src/lib/avatar/**",+ "$TURBO_ROOT$/vitest.shared.ts",+ "$TURBO_ROOT$/vitest.config.ts",+ "cloudflare-env.d.ts",+ "!**/{node_modules,.next,.open-next,.wrangler,.turbo,dist,coverage}/**",+ "!**/{test-results,blob-report,e2e-service-logs,e2e-shard-manifest,.auth}/**",+ "!public/sw.js",+ "!public/sw.js.map",+ "!public/community-shell/**",+ "!**/*.tsbuildinfo",+ "!blog/package.json",+ "!blog/public/alook.svg",+ "!blog/public/apple-touch-icon.png",+ "!blog/public/favicon.ico",+ "!blog/public/icon-192.png",+ "!blog/public/fonts/dm-sans-600.ttf",+ "open-next-worker.d.ts",+ "open-next-handler.d.ts"+ ]+ },+ "@alook/web#lint:auth": {+ "dependsOn": [],+ "inputs": [+ "package.json",+ "tsconfig*.json",+ "eslint.config.mjs",+ "vitest*.{ts,mts}",+ "auth/**",+ "src/lib/avatar/**",+ "$TURBO_ROOT$/vitest.shared.ts",+ "$TURBO_ROOT$/vitest.config.ts",+ "cloudflare-env.d.ts",+ "!**/{node_modules,.next,.open-next,.wrangler,.turbo,dist,coverage}/**",+ "!**/{test-results,blob-report,e2e-service-logs,e2e-shard-manifest,.auth}/**",+ "!public/sw.js",+ "!public/sw.js.map",+ "!public/community-shell/**",+ "!**/*.tsbuildinfo",+ "!blog/package.json",+ "!blog/public/alook.svg",+ "!blog/public/apple-touch-icon.png",+ "!blog/public/favicon.ico",+ "!blog/public/icon-192.png",+ "!blog/public/fonts/dm-sans-600.ttf",+ "open-next-worker.d.ts",+ "open-next-handler.d.ts"+ ]+ },+ "@alook/web#test:auth": {+ "dependsOn": [],+ "inputs": [+ "package.json",+ "tsconfig*.json",+ "eslint.config.mjs",+ "vitest*.{ts,mts}",+ "auth/**",+ "src/lib/avatar/**",+ "$TURBO_ROOT$/vitest.shared.ts",+ "$TURBO_ROOT$/vitest.config.ts",+ "public/alook.svg",+ "cloudflare-env.d.ts",+ "!**/{node_modules,.next,.open-next,.wrangler,.turbo,dist,coverage}/**",+ "!**/{test-results,blob-report,e2e-service-logs,e2e-shard-manifest,.auth}/**",+ "!public/sw.js",+ "!public/sw.js.map",+ "!public/community-shell/**",+ "!**/*.tsbuildinfo",+ "!blog/package.json",+ "!blog/public/alook.svg",+ "!blog/public/apple-touch-icon.png",+ "!blog/public/favicon.ico",+ "!blog/public/icon-192.png",+ "!blog/public/fonts/dm-sans-600.ttf",+ "open-next-worker.d.ts",+ "open-next-handler.d.ts"+ ],+ "outputs": []+ },+ "@alook/web#test:runtime": {+ "dependsOn": [+ "^source"+ ],+ "inputs": [+ "package.json",+ "tsconfig*.json",+ "eslint.config.mjs",+ "vitest*.{ts,mts}",+ "src/**",+ "scripts/**",+ "public/**",+ "test-runtime/**",+ "migrations/**",+ "custom-worker.ts",+ "next.config.ts",+ "open-next.config.ts",+ "postcss.config.mjs",+ "wrangler*.toml",+ "readme-capture/**",+ "app-store-capture/**",+ "$TURBO_ROOT$/vitest.shared.ts",+ "$TURBO_ROOT$/vitest.config.ts",+ "cloudflare-env.d.ts",+ "!**/{node_modules,.next,.open-next,.wrangler,.turbo,dist,coverage}/**",+ "!**/{test-results,blob-report,e2e-service-logs,e2e-shard-manifest,.auth}/**",+ "!public/sw.js",+ "!public/sw.js.map",+ "!public/community-shell/**",+ "!**/*.tsbuildinfo",+ "!blog/package.json",+ "!blog/public/alook.svg",+ "!blog/public/apple-touch-icon.png",+ "!blog/public/favicon.ico",+ "!blog/public/icon-192.png",+ "!blog/public/fonts/dm-sans-600.ttf",+ "open-next-worker.d.ts",+ "open-next-handler.d.ts"+ ],+ "outputs": [],+ "cache": false+ },+ "@alook/web#test:auth:runtime": {+ "dependsOn": [],+ "inputs": [+ "package.json",+ "tsconfig*.json",+ "eslint.config.mjs",+ "vitest*.{ts,mts}",+ "auth/**",+ "src/lib/avatar/**",+ "$TURBO_ROOT$/vitest.shared.ts",+ "$TURBO_ROOT$/vitest.config.ts",+ "cloudflare-env.d.ts",+ "!**/{node_modules,.next,.open-next,.wrangler,.turbo,dist,coverage}/**",+ "!**/{test-results,blob-report,e2e-service-logs,e2e-shard-manifest,.auth}/**",+ "!public/sw.js",+ "!public/sw.js.map",+ "!public/community-shell/**",+ "!**/*.tsbuildinfo",+ "!blog/package.json",+ "!blog/public/alook.svg",+ "!blog/public/apple-touch-icon.png",+ "!blog/public/favicon.ico",+ "!blog/public/icon-192.png",+ "!blog/public/fonts/dm-sans-600.ttf",+ "open-next-worker.d.ts",+ "open-next-handler.d.ts"+ ],+ "outputs": [],+ "cache": false+ },+ "@alook/web#build": {+ "dependsOn": [+ "^source"+ ],+ "inputs": [+ "package.json",+ "tsconfig*.json",+ "eslint.config.mjs",+ "vitest*.{ts,mts}",+ "src/**",+ "scripts/**",+ "public/**",+ "test-runtime/**",+ "migrations/**",+ "custom-worker.ts",+ "next.config.ts",+ "open-next.config.ts",+ "postcss.config.mjs",+ "wrangler*.toml",+ "readme-capture/**",+ "app-store-capture/**",+ "$TURBO_ROOT$/src/daemon/package.json",+ "cloudflare-env.d.ts",+ "$TURBO_ROOT$/scripts/ci/run-turbo.mjs",+ ".dev.vars*",+ "!**/{node_modules,.next,.open-next,.wrangler,.turbo,dist,coverage}/**",+ "!**/{test-results,blob-report,e2e-service-logs,e2e-shard-manifest,.auth}/**",+ "!public/sw.js",+ "!public/sw.js.map",+ "!public/community-shell/**",+ "!**/*.tsbuildinfo",+ "!blog/package.json",+ "!blog/public/alook.svg",+ "!blog/public/apple-touch-icon.png",+ "!blog/public/favicon.ico",+ "!blog/public/icon-192.png",+ "!blog/public/fonts/dm-sans-600.ttf",+ "open-next-worker.d.ts",+ "!next-env.d.ts",+ "open-next-handler.d.ts"+ ],+ "outputs": [+ ".next/**",+ "!.next/cache/**",+ "public/sw.js",+ "public/community-shell/**",+ ".open-next/**",+ "next-env.d.ts"+ ],+ "env": [+ "ALOOK_*",+ "ALOOK_TASK_BUN",+ "AUTH_*",+ "BLOG_*",+ "CF_PAGES_COMMIT_SHA",+ "FARO_*",+ "GITHUB_SHA",+ "NEXT_PUBLIC_*",+ "SOURCE_DATE_EPOCH",+ "VERCEL_GIT_COMMIT_SHA",+ "WEB_*",+ "WS_*",+ "WORKERS_CI_COMMIT_SHA"+ ]+ },+ "@alook/web#build:blog": {+ "dependsOn": [+ "^source"+ ],+ "inputs": [+ "package.json",+ "tsconfig*.json",+ "eslint.config.mjs",+ "vitest*.{ts,mts}",+ "blog/**",+ "public/alook.svg",+ "public/apple-touch-icon.png",+ "public/icon-192.png",+ "public/fonts/**",+ "src/app/_og/**",+ "src/app/fonts.ts",+ "src/app/globals.css",+ "src/hooks/**",+ "src/stores/**",+ "src/lib/**",+ "src/test/{react-dom*,test-harness*,testids*}",+ "cloudflare-env.d.ts",+ "src/components/**",+ "!src/components/auth/**",+ "!src/components/download/**",+ "src/contexts/**",+ "src/*.d.ts",+ "$TURBO_ROOT$/scripts/ci/run-turbo.mjs",+ ".dev.vars*",+ "blog/.dev.vars*",+ "src/app/favicon.ico",+ "!**/{node_modules,.next,.open-next,.wrangler,.turbo,dist,coverage}/**",+ "!**/{test-results,blob-report,e2e-service-logs,e2e-shard-manifest,.auth}/**",+ "!public/sw.js",+ "!public/sw.js.map",+ "!public/community-shell/**",+ "!**/*.tsbuildinfo",+ "!blog/package.json",+ "!blog/public/alook.svg",+ "!blog/public/apple-touch-icon.png",+ "!blog/public/favicon.ico",+ "!blog/public/icon-192.png",+ "!blog/public/fonts/dm-sans-600.ttf",+ "open-next-worker.d.ts",+ "!blog/next-env.d.ts",+ "open-next-handler.d.ts",+ "!blog/public/blog/_generated/**",+ "!blog/src/lib/blog/image-assets.json"+ ],+ "outputs": [+ "blog/.next/**",+ "!blog/.next/cache/**",+ "blog/.open-next/**",+ "blog/public/alook.svg",+ "blog/public/apple-touch-icon.png",+ "blog/public/favicon.ico",+ "blog/public/icon-192.png",+ "blog/public/fonts/dm-sans-600.ttf",+ "blog/next-env.d.ts",+ "blog/public/blog/_generated/**",+ "blog/src/lib/blog/image-assets.json"+ ],+ "env": [+ "ALOOK_*",+ "ALOOK_TASK_BUN",+ "AUTH_*",+ "BLOG_*",+ "CF_PAGES_COMMIT_SHA",+ "FARO_*",+ "GITHUB_SHA",+ "NEXT_PUBLIC_*",+ "SOURCE_DATE_EPOCH",+ "VERCEL_GIT_COMMIT_SHA",+ "WEB_*",+ "WS_*",+ "WORKERS_CI_COMMIT_SHA"+ ]+ },+ "@alook/web#build:auth": {+ "inputs": [+ "package.json",+ "tsconfig*.json",+ "eslint.config.mjs",+ "vitest*.{ts,mts}",+ "auth/**",+ "src/lib/avatar/**",+ "cloudflare-env.d.ts",+ "$TURBO_ROOT$/scripts/ci/run-turbo.mjs",+ "auth/.dev.vars*",+ "!**/{node_modules,.next,.open-next,.wrangler,.turbo,dist,coverage}/**",+ "!**/{test-results,blob-report,e2e-service-logs,e2e-shard-manifest,.auth}/**",+ "!public/sw.js",+ "!public/sw.js.map",+ "!public/community-shell/**",+ "!**/*.tsbuildinfo",+ "!blog/package.json",+ "!blog/public/alook.svg",+ "!blog/public/apple-touch-icon.png",+ "!blog/public/favicon.ico",+ "!blog/public/icon-192.png",+ "!blog/public/fonts/dm-sans-600.ttf",+ "open-next-worker.d.ts",+ "open-next-handler.d.ts"+ ],+ "outputs": [+ "auth/dist/**"+ ],+ "env": [+ "ALOOK_*",+ "ALOOK_TASK_BUN",+ "AUTH_*",+ "BLOG_*",+ "CF_PAGES_COMMIT_SHA",+ "FARO_*",+ "GITHUB_SHA",+ "NEXT_PUBLIC_*",+ "SOURCE_DATE_EPOCH",+ "VERCEL_GIT_COMMIT_SHA",+ "WEB_*",+ "WS_*"+ ]+ },+ "@alook/agent-driver#lint": {+ "inputs": [+ "$TURBO_DEFAULT$",+ "$TURBO_ROOT$/src/daemon/eslint.config.ts"+ ]+ },+ "@alook/agent-driver#test": {+ "dependsOn": [+ "build"+ ],+ "inputs": [+ "$TURBO_DEFAULT$",+ "$TURBO_ROOT$/vitest.shared.ts",+ "$TURBO_ROOT$/vitest.config.ts"+ ],+ "outputs": []+ },+ "@alook/daemon#test": {+ "dependsOn": [+ "^source",+ "@alook/agent-driver#build"+ ],+ "inputs": [+ "$TURBO_DEFAULT$",+ "$TURBO_ROOT$/vitest.shared.ts",+ "$TURBO_ROOT$/vitest.config.ts"+ ],+ "outputs": []+ },+ "@alook/app#build": {+ "dependsOn": [+ "@alook/daemon#build"+ ],+ "outputs": [+ "dist/**"+ ],+ "env": [+ "ALOOK_TASK_BUN"+ ],+ "inputs": [+ "$TURBO_DEFAULT$",+ "$TURBO_ROOT$/scripts/ci/run-turbo.mjs"+ ]+ },+ "@alook/ws-do#test:runtime": {+ "dependsOn": [+ "^source"+ ],+ "inputs": [+ "$TURBO_DEFAULT$",+ "$TURBO_ROOT$/vitest.shared.ts",+ "$TURBO_ROOT$/vitest.config.ts",+ "$TURBO_ROOT$/src/web/migrations/**"+ ],+ "outputs": [],+ "cache": false+ },+ "@alook/email-worker#test:runtime": {+ "dependsOn": [+ "^source"+ ],+ "inputs": [+ "$TURBO_DEFAULT$",+ "$TURBO_ROOT$/vitest.shared.ts",+ "$TURBO_ROOT$/vitest.config.ts",+ "$TURBO_ROOT$/src/web/migrations/**"+ ],+ "outputs": [],+ "cache": false+ },+ "@alook/queue-worker#test:runtime": {+ "dependsOn": [+ "^source"+ ],+ "inputs": [+ "$TURBO_DEFAULT$",+ "$TURBO_ROOT$/vitest.shared.ts",+ "$TURBO_ROOT$/vitest.config.ts",+ "$TURBO_ROOT$/src/web/migrations/**"+ ],+ "outputs": [],+ "cache": false+ },+ "@alook/web#test:contracts": {+ "dependsOn": [+ "^source"+ ],+ "inputs": [+ "$TURBO_DEFAULT$",+ "$TURBO_ROOT$/vitest.shared.ts",+ "$TURBO_ROOT$/vitest.config.ts",+ "$TURBO_ROOT$/scripts/**",+ "$TURBO_ROOT$/.github/workflows/**",+ "cloudflare-env.d.ts",+ "!**/{node_modules,.next,.open-next,.wrangler,.turbo,dist,coverage}/**",+ "!**/{test-results,blob-report,e2e-service-logs,e2e-shard-manifest,.auth}/**",+ "!public/sw.js",+ "!public/sw.js.map",+ "!public/community-shell/**",+ "!**/*.tsbuildinfo",+ "!blog/package.json",+ "!blog/public/alook.svg",+ "!blog/public/apple-touch-icon.png",+ "!blog/public/favicon.ico",+ "!blog/public/icon-192.png",+ "!blog/public/fonts/dm-sans-600.ttf",+ "open-next-worker.d.ts",+ "open-next-handler.d.ts"+ ],+ "outputs": []+ },+ "@alook/web#test:tooling": {+ "dependsOn": [+ "^source"+ ],+ "inputs": [+ "$TURBO_DEFAULT$",+ "$TURBO_ROOT$/vitest.shared.ts",+ "$TURBO_ROOT$/vitest.config.ts",+ "$TURBO_ROOT$/scripts/**",+ "$TURBO_ROOT$/.github/workflows/**",+ "$TURBO_ROOT$/assets/**",+ "$TURBO_ROOT$/README.md",+ "$TURBO_ROOT$/src/desktop/src-tauri/{tauri.conf.json,Cargo.toml}",+ "cloudflare-env.d.ts",+ "!**/{node_modules,.next,.open-next,.wrangler,.turbo,dist,coverage}/**",+ "!**/{test-results,blob-report,e2e-service-logs,e2e-shard-manifest,.auth}/**",+ "!public/sw.js",+ "!public/sw.js.map",+ "!public/community-shell/**",+ "!**/*.tsbuildinfo",+ "!blog/package.json",+ "!blog/public/alook.svg",+ "!blog/public/apple-touch-icon.png",+ "!blog/public/favicon.ico",+ "!blog/public/icon-192.png",+ "!blog/public/fonts/dm-sans-600.ttf",+ "open-next-worker.d.ts",+ "open-next-handler.d.ts"+ ],+ "outputs": []+ },+ "@alook/daemon#typecheck": {+ "dependsOn": [+ "^source",+ "@alook/agent-driver#build"+ ]+ },+ "@alook/daemon#lint": {+ "dependsOn": [+ "^source",+ "@alook/agent-driver#build"+ ]+ },+ "@alook/daemon#build": {+ "dependsOn": [+ "^source",+ "@alook/agent-driver#build"+ ],+ "inputs": [+ "$TURBO_DEFAULT$",+ "$TURBO_ROOT$/LICENSE",+ "$TURBO_ROOT$/scripts/ci/run-turbo.mjs"+ ],+ "outputs": [+ "dist/**",+ "LICENSE"+ ],+ "env": [+ "ALOOK_TASK_BUN"+ ]+ },+ "@alook/agent-driver#build": {+ "inputs": [+ "$TURBO_DEFAULT$",+ "$TURBO_ROOT$/LICENSE",+ "$TURBO_ROOT$/scripts/ci/run-turbo.mjs"+ ],+ "outputs": [+ "dist/**",+ "LICENSE"+ ]+ },+ "@alook/app#test": {+ "dependsOn": [+ "^source"+ ],+ "inputs": [+ "$TURBO_DEFAULT$",+ "$TURBO_ROOT$/vitest.shared.ts",+ "$TURBO_ROOT$/vitest.config.ts",+ "$TURBO_ROOT$/src/web/package.json",+ "$TURBO_ROOT$/src/web/src/lib/**"+ ],+ "outputs": []+ }+ },+ "futureFlags": {+ "affectedUsingTaskInputs": true+ },+ "globalEnv": [+ "ALOOK_TASK_NODE",+ "ALOOK_TASK_PLATFORM",+ "ALOOK_TASK_WORKSPACE",+ "CI",+ "NODE_ENV",+ "NODE_OPTIONS"+ ]}diff --git a/vitest.config.ts b/vitest.config.tsindex 3ebff90be..0bb7a3fa3 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -1,10 +1,15 @@import { defineConfig } from "vitest/config"+import turbo from "./turbo.json"export default defineConfig({test: {projects: ["src/shared","src/web",+ "src/web/vitest.contracts.config.ts",+ "src/web/vitest.tooling.config.ts",+ "src/web/blog/vitest.config.mts",+ "src/web/blog/vitest.dom.config.mts","src/web/auth/vitest.config.ts","src/web/auth/vitest.runtime.config.mts","src/daemon",@@ -25,6 +30,7 @@ export default defineConfig({provider: "istanbul",include: ["src/**/*.{ts,tsx,js,jsx}", "scripts/ci/**/*.mjs"],exclude: [+ ...turbo.tasks["@alook/web#build"].outputs.filter(pattern => !pattern.startsWith("!")).map(pattern => "src/web/" + pattern),"**/*.test.*","**/*.spec.*","**/node_modules/**",diff --git a/vitest.shared.ts b/vitest.shared.tsindex d0479bed3..c709ca101 100644--- a/vitest.shared.ts+++ b/vitest.shared.ts@@ -3,6 +3,7 @@ import { defineConfig } from "vitest/config"export default defineConfig({test: {globals: true,+ css: { include: [/\?raw(?:&|$)/] },environment: "node",},})