diff --git a/.github/actions/setup-ci-dependencies/action.yml b/.github/actions/setup-ci-dependencies/action.yml index 0a78e542c91..e219d04a70a 100644 --- a/.github/actions/setup-ci-dependencies/action.yml +++ b/.github/actions/setup-ci-dependencies/action.yml @@ -85,7 +85,11 @@ runs: shell: bash working-directory: ${{ inputs.working-directory }} run: | - pnpm run preflight:workspace-links + if [ -f scripts/ensure-workspace-package-links.mjs ]; then + node scripts/ensure-workspace-package-links.mjs + else + pnpm run preflight:workspace-links + fi node scripts/ensure-plugin-build-deps.mjs - name: Save installed dependencies diff --git a/.github/ci-task-matrix.json b/.github/ci-task-matrix.json index 067ab518009..c63e7423cee 100644 --- a/.github/ci-task-matrix.json +++ b/.github/ci-task-matrix.json @@ -196,7 +196,16 @@ }, { "group": "general-workspaces-b", - "group_label": "workspaces-b", + "group_label": "workspaces-b (1/2)", + "shard_index": 0, + "shard_count": 2, + "task": "ci:workspaces-b" + }, + { + "group": "general-workspaces-b", + "group_label": "workspaces-b (2/2)", + "shard_index": 1, + "shard_count": 2, "task": "ci:workspaces-b" }, { diff --git a/.github/scripts/tests/ci-plan.test.mjs b/.github/scripts/tests/ci-plan.test.mjs index 6eae69eeb9c..b8563b0d3ba 100644 --- a/.github/scripts/tests/ci-plan.test.mjs +++ b/.github/scripts/tests/ci-plan.test.mjs @@ -114,8 +114,8 @@ test("PR workflow keeps Build fast and passes PR-mode context to typecheck and V const e2e = workflow.split("\n e2e_shards:\n")[1].split("\n e2e:\n")[0]; const releaseVerify = readFileSync(new URL(".github/workflows/release-verify.yml", root), "utf8"); const releaseBuild = releaseVerify.split("\n build:\n")[1].split("\n runner_binary_targets:\n")[0]; - const prKey = e2e.match(/key: (e2e-ui-dist-v1-.+)/)?.[1]; - const releaseKey = releaseBuild.match(/key: (e2e-ui-dist-v1-.+)/)?.[1]; + const prKey = e2e.match(/key: (e2e-ui-dist-v2-.+)/)?.[1]; + const releaseKey = releaseBuild.match(/key: (e2e-ui-dist-v2-.+)/)?.[1]; assert.ok(prKey && releaseKey, "both pr-trusted.yml and release-verify.yml must define the E2E UI dist cache key"); assert.equal(prKey, releaseKey, "E2E UI dist reader and writer keys must match exactly"); assert.doesNotMatch(e2e.split("Restore prebuilt UI assets")[1].split("Run e2e tests")[0], /restore-keys:/); @@ -374,7 +374,7 @@ else process.exit(3); else { assert.notEqual(value, "plan=", `${JSON.stringify(overrides)}: ${result.stderr}`); const resultPlan = JSON.parse(value.slice("plan=".length)); - assert.equal(resultPlan.jobs.general_tests.selected, overrides.PROFILE_CI || overrides.STACK_JSON ? 29 : 2); + assert.equal(resultPlan.jobs.general_tests.selected, overrides.PROFILE_CI || overrides.STACK_JSON ? 30 : 2); assert.equal(resultPlan.diff.base, base); assert.deepEqual(resultPlan.changed, ["ui/src/components/Sidebar.tsx"]); } diff --git a/.github/workflows/pr-trusted.yml b/.github/workflows/pr-trusted.yml index 9963714fc9e..685848b978b 100644 --- a/.github/workflows/pr-trusted.yml +++ b/.github/workflows/pr-trusted.yml @@ -251,6 +251,20 @@ jobs: - name: Test e2e shard partition run: node "$CI_NODE_TEST" ./scripts/__tests__/e2e-shard.test.mjs + - name: Check CI test budget policy + run: | + if [[ -f ./scripts/check-test-budget.mjs ]]; then + base_sha="${{ github.event.pull_request.base.sha }}" + if [[ -n "$base_sha" ]]; then + node ./scripts/check-test-budget.mjs --base "$base_sha" + else + node ./scripts/check-test-budget.mjs + fi + fi + if [[ -f ./scripts/check-test-budget.test.mjs ]]; then + node "$CI_NODE_TEST" ./scripts/check-test-budget.test.mjs + fi + - name: Test release verify workflow wiring run: | tests=(./scripts/__tests__/release-verify-workflow.test.mjs ./scripts/__tests__/eval-schedule-monitor.test.mjs ./scripts/__tests__/prepare-runner-release-image.test.mjs ./scripts/cloud-source-verification.test.mjs ./scripts/cloud-readiness-runner-loss.test.mjs ./scripts/standard-image-contract.test.mjs ./scripts/reuse-canary-image.test.mjs) @@ -521,7 +535,7 @@ jobs: strategy: fail-fast: false max-parallel: ${{ needs.gate.outputs.runner == 'ubuntu-latest' && 4 || 256 }} - matrix: ${{ fromJSON((needs.test_selection.outputs.plan || needs.gate.outputs.plan) != '' && toJSON(fromJSON((needs.test_selection.outputs.plan || needs.gate.outputs.plan)).jobs.general_tests.matrix) || '{"include":[{"group":"general-server-without-chat","group_label":"server (1/20)","shard_index":0,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (2/20)","shard_index":1,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (3/20)","shard_index":2,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (4/20)","shard_index":3,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (5/20)","shard_index":4,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (6/20)","shard_index":5,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (7/20)","shard_index":6,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (8/20)","shard_index":7,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (9/20)","shard_index":8,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (10/20)","shard_index":9,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (11/20)","shard_index":10,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (12/20)","shard_index":11,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (13/20)","shard_index":12,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (14/20)","shard_index":13,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (15/20)","shard_index":14,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (16/20)","shard_index":15,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (17/20)","shard_index":16,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (18/20)","shard_index":17,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (19/20)","shard_index":18,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (20/20)","shard_index":19,"shard_count":20,"task":"ci:server"},{"group":"general-chat","group_label":"chat (1/5)","shard_index":0,"shard_count":5,"task":"ci:chat"},{"group":"general-chat","group_label":"chat (2/5)","shard_index":1,"shard_count":5,"task":"ci:chat"},{"group":"general-chat","group_label":"chat (3/5)","shard_index":2,"shard_count":5,"task":"ci:chat"},{"group":"general-chat","group_label":"chat (4/5)","shard_index":3,"shard_count":5,"task":"ci:chat"},{"group":"general-chat","group_label":"chat (5/5)","shard_index":4,"shard_count":5,"task":"ci:chat"},{"group":"general-workspaces-a","group_label":"workspaces-a (1/2)","shard_index":0,"shard_count":2,"task":"ci:workspaces-a"},{"group":"general-workspaces-a","group_label":"workspaces-a (2/2)","shard_index":1,"shard_count":2,"task":"ci:workspaces-a"},{"group":"general-workspaces-b","group_label":"workspaces-b","task":"ci:workspaces-b"},{"group":"general-workspaces-c","group_label":"workspaces-c","task":"ci:db"}]}') }} + matrix: ${{ fromJSON((needs.test_selection.outputs.plan || needs.gate.outputs.plan) != '' && toJSON(fromJSON((needs.test_selection.outputs.plan || needs.gate.outputs.plan)).jobs.general_tests.matrix) || '{"include":[{"group":"general-server-without-chat","group_label":"server (1/20)","shard_index":0,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (2/20)","shard_index":1,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (3/20)","shard_index":2,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (4/20)","shard_index":3,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (5/20)","shard_index":4,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (6/20)","shard_index":5,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (7/20)","shard_index":6,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (8/20)","shard_index":7,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (9/20)","shard_index":8,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (10/20)","shard_index":9,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (11/20)","shard_index":10,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (12/20)","shard_index":11,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (13/20)","shard_index":12,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (14/20)","shard_index":13,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (15/20)","shard_index":14,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (16/20)","shard_index":15,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (17/20)","shard_index":16,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (18/20)","shard_index":17,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (19/20)","shard_index":18,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (20/20)","shard_index":19,"shard_count":20,"task":"ci:server"},{"group":"general-chat","group_label":"chat (1/5)","shard_index":0,"shard_count":5,"task":"ci:chat"},{"group":"general-chat","group_label":"chat (2/5)","shard_index":1,"shard_count":5,"task":"ci:chat"},{"group":"general-chat","group_label":"chat (3/5)","shard_index":2,"shard_count":5,"task":"ci:chat"},{"group":"general-chat","group_label":"chat (4/5)","shard_index":3,"shard_count":5,"task":"ci:chat"},{"group":"general-chat","group_label":"chat (5/5)","shard_index":4,"shard_count":5,"task":"ci:chat"},{"group":"general-workspaces-a","group_label":"workspaces-a (1/2)","shard_index":0,"shard_count":2,"task":"ci:workspaces-a"},{"group":"general-workspaces-a","group_label":"workspaces-a (2/2)","shard_index":1,"shard_count":2,"task":"ci:workspaces-a"},{"group":"general-workspaces-b","group_label":"workspaces-b (1/2)","shard_index":0,"shard_count":2,"task":"ci:workspaces-b"},{"group":"general-workspaces-b","group_label":"workspaces-b (2/2)","shard_index":1,"shard_count":2,"task":"ci:workspaces-b"},{"group":"general-workspaces-c","group_label":"workspaces-c","task":"ci:db"}]}') }} env: PAPERCLIP_CI_FULL: ${{ (contains(github.event.pull_request.labels.*.name, 'full-ci') || vars.CI_INCREMENTAL_MODE == 'full') && '1' || '' }} @@ -1740,7 +1754,7 @@ jobs: uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: server/ui-dist - key: e2e-ui-dist-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml', 'tsconfig*.json', 'ui/package.json', 'ui/index.html', 'ui/vite.config.*', 'ui/tsconfig*.json', 'ui/src/**', 'ui/public/**', 'packages/shared/src/**', 'packages/adapter-utils/src/**', 'packages/adapters/*/src/**', 'packages/plugins/sdk/src/**') }} + key: e2e-ui-dist-v2-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml', 'tsconfig*.json', 'ui/package.json', 'ui/index.html', 'ui/vite.config.*', 'ui/tsconfig*.json', 'ui/src/**', 'ui/public/**', 'packages/shared/package.json', 'packages/shared/src/**', 'packages/adapter-utils/package.json', 'packages/adapter-utils/src/**', 'packages/adapters/*/package.json', 'packages/adapters/*/src/**', 'packages/plugins/sdk/package.json', 'packages/plugins/sdk/src/**', 'announcements/examples/animated/**') }} - name: Run e2e tests env: diff --git a/.github/workflows/release-verify.yml b/.github/workflows/release-verify.yml index 55044cb9a1c..e7513ffa0c7 100644 --- a/.github/workflows/release-verify.yml +++ b/.github/workflows/release-verify.yml @@ -573,7 +573,7 @@ jobs: with: lookup-only: true path: server/ui-dist - key: e2e-ui-dist-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml', 'tsconfig*.json', 'ui/package.json', 'ui/index.html', 'ui/vite.config.*', 'ui/tsconfig*.json', 'ui/src/**', 'ui/public/**', 'packages/shared/src/**', 'packages/adapter-utils/src/**', 'packages/adapters/*/src/**', 'packages/plugins/sdk/src/**') }} + key: e2e-ui-dist-v2-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml', 'tsconfig*.json', 'ui/package.json', 'ui/index.html', 'ui/vite.config.*', 'ui/tsconfig*.json', 'ui/src/**', 'ui/public/**', 'packages/shared/package.json', 'packages/shared/src/**', 'packages/adapter-utils/package.json', 'packages/adapter-utils/src/**', 'packages/adapters/*/package.json', 'packages/adapters/*/src/**', 'packages/plugins/sdk/package.json', 'packages/plugins/sdk/src/**', 'announcements/examples/animated/**') }} - name: Stage prebuilt UI assets for E2E cache if: ${{ github.repository == 'paperclipai/paperclip' && github.event_name == 'push' && github.ref == 'refs/heads/master' && inputs.ref == github.sha && steps.e2e_ui_dist.outputs.cache-hit != 'true' }} @@ -584,7 +584,7 @@ jobs: uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: server/ui-dist - key: e2e-ui-dist-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml', 'tsconfig*.json', 'ui/package.json', 'ui/index.html', 'ui/vite.config.*', 'ui/tsconfig*.json', 'ui/src/**', 'ui/public/**', 'packages/shared/src/**', 'packages/adapter-utils/src/**', 'packages/adapters/*/src/**', 'packages/plugins/sdk/src/**') }} + key: e2e-ui-dist-v2-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml', 'tsconfig*.json', 'ui/package.json', 'ui/index.html', 'ui/vite.config.*', 'ui/tsconfig*.json', 'ui/src/**', 'ui/public/**', 'packages/shared/package.json', 'packages/shared/src/**', 'packages/adapter-utils/package.json', 'packages/adapter-utils/src/**', 'packages/adapters/*/package.json', 'packages/adapters/*/src/**', 'packages/plugins/sdk/package.json', 'packages/plugins/sdk/src/**', 'announcements/examples/animated/**') }} runner_binary_targets: if: inputs.runner_binaries_only diff --git a/.greptile/files.json b/.greptile/files.json index 080b8aa1fe8..061c6a67430 100644 --- a/.greptile/files.json +++ b/.greptile/files.json @@ -161,6 +161,17 @@ "server/src/routes/sidebar-preferences.ts", "server/src/services/sidebar-preferences.ts" ] + }, + { + "path": "rules/test-budget.mdc", + "description": "CI test budget: prevent unbudgeted real-clock sleeps >1s, historical SQL migration test sprawl, brittle static prose-grep tests, and tiny standalone embedded-Postgres files while keeping core invariants on PRs.", + "scope": [ + "packages/db/src/**/*.test.ts", + "server/src/**/*.test.ts", + "ui/src/**/*.test.ts", + "ui/src/**/*.test.tsx", + "tests/e2e/**/*.spec.ts" + ] } ] } diff --git a/maps/agent-access-map/connection-setup.md b/maps/agent-access-map/connection-setup.md index 8f47af39dd3..e67fda9544d 100644 --- a/maps/agent-access-map/connection-setup.md +++ b/maps/agent-access-map/connection-setup.md @@ -189,7 +189,7 @@ Gaps: This individual operation has source review but no recorded HTTP verificat API: `present` — `POST /api/tools/oauth/{connectionId}/start`; JSON REST. Agent access: `available` — agent REST and default native `search_api` / `call_api`. Policy: `tools:manage_connections`; [shared management policy](../../doc/plans/2026-10-13-connection-api-parity.md#authorization-contract). Resolved resources and every affected target are checked; personal ownership remains the responsible user. Returns the saved setup without issuing agent-bound OAuth state; the human browser initiates provider consent. -Evidence: `verified` — [authenticated integration fixtures](../../server/src/__tests__/connection-management.integration.test.ts) passed through production authentication and database persistence, including saved Google service choices addressed to the responsible user. [Service-picker tests](../../ui/src/features/connections/GoogleWorkspaceServices.test.tsx) cover restoring only that user's request and retaining newer consent. +Evidence: `verified` — [authenticated integration fixtures](../../server/src/__tests__/connection-management.integration.test.ts) passed through production authentication and database persistence, including saved Google service choices addressed to the responsible user. (Mocked `GoogleWorkspaceServices` UI service-picker tests were removed; verify UI consent-picker restoration manually.) Verification: `passed` — deterministic local fixture; no live provider qualification. Gaps: Provider fixtures do not qualify live provider setup or availability. diff --git a/maps/feature-map/agent-chat.md b/maps/feature-map/agent-chat.md index bb1af2be115..6e58f009883 100644 --- a/maps/feature-map/agent-chat.md +++ b/maps/feature-map/agent-chat.md @@ -61,7 +61,7 @@ uses real app APIs and a deterministic process agent to verify first-chat discov unread state across reloads, source navigation and follow-up context. It does not qualify live PR retrieval or a model's editorial choices. -Automated: [composer picker](../../ui/src/components/task-chat/ComposerRunSettingsPicker.test.tsx) covers fixed-agent model/effort selection on desktop and mobile; [composer](../../ui/src/components/task-chat/TaskChatComposer.test.tsx) covers Coordinator gating and settings submission without reassignment. (Mocked `IssueDetail` UI tests for canonical first/existing-chat IDs and settings-before-comment ordering were removed; verify those page-level flows manually.) These tests mock the API and do not prove provider execution with the chosen model. +Automated: [composer](../../ui/src/components/task-chat/TaskChatComposer.test.tsx) covers Coordinator gating and settings submission without reassignment. (Mocked `ComposerRunSettingsPicker` and `IssueDetail` UI tests for model/effort selection, canonical first/existing-chat IDs, and settings-before-comment ordering were removed; verify those UI flows manually.) These tests mock the API and do not prove provider execution with the chosen model. Automated: [thread and composer](../../ui/src/components/TaskChatThread.test.tsx) keeps an in-flight attachment through first-chat creation on desktop and mobile, diff --git a/maps/feature-map/connection-setup.md b/maps/feature-map/connection-setup.md index 797b2725338..446fd0223b5 100644 --- a/maps/feature-map/connection-setup.md +++ b/maps/feature-map/connection-setup.md @@ -242,10 +242,10 @@ Slack setup does not qualify Discord, Telegram, GitHub, email, or iMessage. Automated: [agent-authenticated integration](../../server/src/__tests__/connection-management.integration.test.ts) uses production agent creation, persistent keys, run JWTs, native tool bindings, human sessions, PostgreSQL and deterministic provider fixtures. It covers saved -setup, ownership, attribution, scope, trust, work modes and revocation. The -[Google service picker tests](../../ui/src/features/connections/GoogleWorkspaceServices.test.tsx) -cover pending choices, consent precedence and failed grant loading with API mocks. -These are separate from live provider setup and model success. +setup, ownership, attribution, scope, trust, work modes and revocation. (Mocked +`GoogleWorkspaceServices` UI service-picker tests were removed; verify pending +choices and consent-picker UI manually.) These are separate from live provider +setup and model success. Manual: Have the agent perform authorized setup, then open its saved handoff as the addressed person. Reload before completing the required human step; verify diff --git a/maps/feature-map/steering.md b/maps/feature-map/steering.md index 2605e60ea48..fe1cd5d771f 100644 --- a/maps/feature-map/steering.md +++ b/maps/feature-map/steering.md @@ -65,12 +65,11 @@ unsupported steering without treating an absent capability as a product failure. ### `task-composer` -Automated: [queued-message UI](../../ui/src/components/task-chat/TaskChatQueuedMessages.test.tsx) -covers order, failure restoration, unavailable steering, stale revisions, and -discard acknowledgements. [Queue routes](../../server/src/__tests__/issue-queued-comments-routes.test.ts) +Automated: [Queue routes](../../server/src/__tests__/issue-queued-comments-routes.test.ts) cover durable ordering, authorization, steering acknowledgements, interrupt recovery, and concurrent dispatch. [Composer](../../ui/src/components/task-chat/TaskChatComposer.test.tsx) -covers drafts and uncertain saves. +covers drafts and uncertain saves. (Mocked `TaskChatQueuedMessages` UI tests were +removed; verify queued-message UI rendering manually.) Mocked `IssueDetail` delivery-race UI tests were removed (verify late send-response and queue-snapshot races manually). Expected behavior: a started @@ -186,4 +185,4 @@ Capability ID: `steering/approval-queue`. Scope: ui Storybook: Answered question/accepted approval delivery waiting, eligible steer/interrupt, failed delivery and fresh-session-only approval. Production: Keep response delivery durable and distinct from editable comments; coalesce once, enforce fresh-session restrictions and deduplicate concurrent/retried continuation. -Sources: Source: [TaskChatQueuedMessages.tsx](../../ui/src/components/task-chat/TaskChatQueuedMessages.tsx), [question-response-delivery.ts](../../server/src/services/question-response-delivery.ts). Tests: [TaskChatQueuedMessages.test.tsx](../../ui/src/components/task-chat/TaskChatQueuedMessages.test.tsx), [question-response-delivery.test.ts](../../server/src/__tests__/question-response-delivery.test.ts), [issue-queued-comments-routes.test.ts](../../server/src/__tests__/issue-queued-comments-routes.test.ts) +Sources: Source: [TaskChatQueuedMessages.tsx](../../ui/src/components/task-chat/TaskChatQueuedMessages.tsx), [question-response-delivery.ts](../../server/src/services/question-response-delivery.ts). Tests: [question-response-delivery.test.ts](../../server/src/__tests__/question-response-delivery.test.ts), [issue-queued-comments-routes.test.ts](../../server/src/__tests__/issue-queued-comments-routes.test.ts) diff --git a/package.json b/package.json index 416070f08a9..d9d6052ec03 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "scripts": { "perf:workspace-admission": "node --import ./server/node_modules/tsx/dist/loader.mjs server/scripts/benchmark-workspace-admission.ts", "postinstall": "node scripts/link-plugin-dev-sdk.mjs", - "preflight:workspace-links": "node cli/node_modules/tsx/dist/cli.mjs scripts/ensure-workspace-package-links.ts", + "preflight:workspace-links": "node scripts/ensure-workspace-package-links.mjs", "dev": "pnpm --filter @paperclipai/server exec tsx ../scripts/dev-runner.ts watch", "dev:watch": "pnpm --filter @paperclipai/server exec tsx ../scripts/dev-runner.ts watch", "dev:once": "pnpm --filter @paperclipai/server exec tsx ../scripts/dev-runner.ts dev", @@ -28,8 +28,8 @@ "test:run": "pnpm run preflight:workspace-links && node scripts/run-vitest-stable.mjs", "test:runner-acceptance": "vitest run --config tests/runner-acceptance/vitest.config.ts", "test:runner-acceptance:typecheck": "tsc -p tests/runner-acceptance/tsconfig.json", - "test:run:general": "pnpm run preflight:workspace-links && pnpm --filter @paperclipai/plugin-sdk ensure-build-deps && node scripts/run-vitest-stable.mjs --mode general", - "test:run:serialized": "pnpm run preflight:workspace-links && pnpm --filter @paperclipai/plugin-sdk ensure-build-deps && node scripts/run-vitest-stable.mjs --mode serialized", + "test:run:general": "node scripts/ensure-workspace-package-links.mjs && node scripts/ensure-plugin-build-deps.mjs && node scripts/run-vitest-stable.mjs --mode general", + "test:run:serialized": "node scripts/ensure-workspace-package-links.mjs && node scripts/ensure-plugin-build-deps.mjs && node scripts/run-vitest-stable.mjs --mode serialized", "db:generate": "pnpm --filter @paperclipai/db generate", "db:migrate": "pnpm --filter @paperclipai/db migrate", "issue-references:backfill": "pnpm run preflight:workspace-links && tsx scripts/backfill-issue-reference-mentions.ts", @@ -95,7 +95,7 @@ "test:lifecycle-baseline": "node tests/lifecycle-baseline/run.mjs", "test:lifecycle-baseline:support": "node --test tests/lifecycle-baseline/report.test.mjs", "test:lifecycle-baseline:typecheck": "node scripts/typecheck-test-projects.mjs tests/lifecycle-baseline", - "verify": "node --import ./cli/node_modules/tsx/dist/loader.mjs scripts/ensure-workspace-package-links.ts && node scripts/local-verify.mjs" + "verify": "node scripts/ensure-workspace-package-links.mjs && node scripts/local-verify.mjs" }, "devDependencies": { "@playwright/test": "^1.62.1", diff --git a/packages/db/src/test-embedded-postgres.ts b/packages/db/src/test-embedded-postgres.ts index 0e2488523c6..13895a6285b 100644 --- a/packages/db/src/test-embedded-postgres.ts +++ b/packages/db/src/test-embedded-postgres.ts @@ -203,11 +203,30 @@ async function stopEmbeddedPostgresBounded( // a fresh port and a fresh data directory, so a transient collision clears. const EMBEDDED_POSTGRES_START_MAX_ATTEMPTS = 5; +export type EmbeddedPostgresTestDatabaseOptions = { + maxConnections?: number; +}; + +function applyPostgresConfigOverrides(dataDir: string, options?: EmbeddedPostgresTestDatabaseOptions): void { + const maxConnections = options?.maxConnections; + if (!maxConnections || !Number.isInteger(maxConnections) || maxConnections < 1) { + return; + } + const configPath = path.join(dataDir, "postgresql.conf"); + if (!fs.existsSync(configPath)) { + return; + } + fs.appendFileSync(configPath, `\nmax_connections = ${maxConnections}\n`, "utf8"); +} + // Start one embedded Postgres cluster with a bounded retry. Each attempt gets a // fresh port and a fresh data directory. On a failed attempt we stop the cluster // and remove its data directory before the next attempt. After the last attempt // we throw with the real Postgres output so the failure is loud and diagnosable. -async function startEmbeddedPostgresWithRetry(tempDirPrefix: string): Promise<{ +async function startEmbeddedPostgresWithRetry( + tempDirPrefix: string, + options?: EmbeddedPostgresTestDatabaseOptions, +): Promise<{ port: number; dataDir: string; instance: EmbeddedPostgresInstance; @@ -218,6 +237,7 @@ async function startEmbeddedPostgresWithRetry(tempDirPrefix: string): Promise<{ const created = await createEmbeddedPostgresTestInstance(tempDirPrefix); try { await created.instance.initialise(); + applyPostgresConfigOverrides(created.dataDir, options); await created.instance.start(); return { port: created.port, dataDir: created.dataDir, instance: created.instance }; } catch (error) { @@ -542,6 +562,7 @@ function resetTemplateDirCache(): void { async function startEmbeddedPostgresFromTemplateWithRetry( templateDir: string, tempDirPrefix: string, + options?: EmbeddedPostgresTestDatabaseOptions, ): Promise<{ port: number; dataDir: string; instance: EmbeddedPostgresInstance }> { let lastError = new Error("embedded Postgres startup from template failed"); @@ -556,6 +577,7 @@ async function startEmbeddedPostgresFromTemplateWithRetry( fs.cpSync(templateDir, dataDir, { recursive: true }); // Postgres refuses a data directory that is group or world accessible. fs.chmodSync(dataDir, 0o700); + applyPostgresConfigOverrides(dataDir, options); created = await createEmbeddedPostgresTestInstanceAt(dataDir); await created.instance.start(); return { port: created.port, dataDir: rootDir, instance: created.instance }; @@ -640,12 +662,13 @@ export async function getEmbeddedPostgresTestSupport(): Promise { const templateDir = await getEmbeddedPostgresTemplateDir(); if (templateDir !== null) { try { - const started = await startEmbeddedPostgresFromTemplateWithRetry(templateDir, tempDirPrefix); + const started = await startEmbeddedPostgresFromTemplateWithRetry(templateDir, tempDirPrefix, options); return { ...started, mode: "template" }; } catch (error) { if (error instanceof TestPostgresShutdownError) throw error; @@ -663,16 +686,17 @@ async function startEmbeddedPostgresClusterForSuite( // The bounded retry hardens the cluster start against the port race. It throws // with the real Postgres output if every attempt fails. - const started = await startEmbeddedPostgresWithRetry(tempDirPrefix); + const started = await startEmbeddedPostgresWithRetry(tempDirPrefix, options); return { ...started, mode: "fresh" }; } export async function startEmbeddedPostgresTestDatabase( tempDirPrefix: string, + options?: EmbeddedPostgresTestDatabaseOptions, ): Promise { const adminUrl = testPostgresAdminUrl(); if (adminUrl) return startTestPostgresDatabase(adminUrl); - const { port, dataDir, instance, mode } = await startEmbeddedPostgresClusterForSuite(tempDirPrefix); + const { port, dataDir, instance, mode } = await startEmbeddedPostgresClusterForSuite(tempDirPrefix, options); lastStartMode = mode; try { diff --git a/packages/db/src/test-postgres-command.ts b/packages/db/src/test-postgres-command.ts index dcedaac7254..2ae85e503a7 100644 --- a/packages/db/src/test-postgres-command.ts +++ b/packages/db/src/test-postgres-command.ts @@ -16,7 +16,10 @@ try { let adminUrl = testPostgresAdminUrl(); if (adminUrl) await checkTestPostgresAdmin(adminUrl); else { - server = await startEmbeddedPostgresTestDatabase("paperclip-test-command-"); + // Shared multi-worker test server: raise max_connections above Postgres's + // default 100 so 7-8 parallel Vitest fork workers (each with main + private + // pools) never exhaust backend slots on 8-core runners or dev workstations. + server = await startEmbeddedPostgresTestDatabase("paperclip-test-command-", { maxConnections: 300 }); const url = new URL(server.connectionString); url.pathname = "/postgres"; adminUrl = url.toString(); diff --git a/rules/test-budget.mdc b/rules/test-budget.mdc new file mode 100644 index 00000000000..10c3a5e7cc4 --- /dev/null +++ b/rules/test-budget.mdc @@ -0,0 +1,42 @@ +--- +description: Keep PR tests fast and high-signal: avoid unbudgeted real-clock sleeps >1s, historical SQL migration replay sprawl, brittle static prose-grep tests, and tiny standalone embedded-Postgres files. +alwaysApply: false +globs: packages/db/src/**/*.test.ts, server/src/**/*.test.ts, ui/src/**/*.test.ts, ui/src/**/*.test.tsx, tests/e2e/**/*.spec.ts +--- + +# CI test budget + +This rule applies to Vitest and Playwright test files across `packages/db`, `server`, `ui`, and `tests/e2e`. + +## Required behavior + +1. **No unbudgeted real-clock sleeps over 1 second in PR tests.** + - Use fake timers (`vi.useFakeTimers()`), deterministic event/condition waits, or direct service calls instead of `setTimeout(..., >1000)`, `delay(>1000)`, or `page.waitForTimeout(>1000)`. + - True real-clock soak, lease-expiry, restart, crash-recovery, retention-sweep, and load/benchmark suites must be registered in `scripts/ci/nightly-only-suites.json` so they run on `master`, `release-verify`, `cloud-readiness`, local `pnpm test:run`, and `PAPERCLIP_CI_FULL=1` without blocking ordinary PRs. + - If a PR test genuinely requires a real-clock wait over 1s (for example testing a real idle-timeout or socket deadline), annotate the line with `// test-budget:allow-sleep: `. + +2. **No historical one-time SQL migration replay sprawl.** + - Do not add standalone `*-migration.test.ts` files that tear down schema and replay already-shipped SQL migrations against embedded Postgres. + - Test ongoing migration-runner invariants, safety rules, and schema/snapshot integrity in the core owner suites: `packages/db/src/client.test.ts`, `packages/db/src/check-migration-safety.test.ts`, `packages/db/src/migration-compatibility.test.ts`, and `packages/db/src/migration-snapshot-drift.test.ts`. + - Active runtime migration services (not historical SQL replay) are exempt, and long-running migration soaks belong in `scripts/ci/nightly-only-suites.json`. + +3. **No brittle static prose-grep tests.** + - Do not add `*-guidance.test.ts` suites that `readFileSync` / `readFile` markdown docs, skill prose, or `ui/src/*.tsx` solely to assert exact wording or copy strings. + - Security, authz, and safety static guards (such as `cli-invocation-safety.test.ts`, `authz-existence-oracle-guard.test.ts`, and `app-private-hostname-gate.test.ts`) are explicit exceptions. + +4. **Extend existing owner suites instead of adding tiny standalone embedded-Postgres files.** + - Each standalone server/DB test file pays isolated Vitest worker import, transform, and disposable-database setup cost. + - Do not create a new `<= 80` LOC test file that boots embedded Postgres (`startEmbeddedPostgresTestDatabase` / `createTestPostgres`) for one narrow regression case; add the test case to the owning service or route suite instead. + - If a standalone file is required for process or environment isolation, annotate the file with `// test-budget:allow-standalone-db: `. + +5. **Preserve core control-plane invariants on every PR.** + - Never demote suites covering company isolation, board/agent authz, atomic checkout, single-assignee rules, approval gates, budget hard-stops, mutation activity logging, secrets/CSRF/redaction/privacy, or telemetry/Sentry contracts into `scripts/ci/nightly-only-suites.json`. + +## Automated guardrail + +Run `node scripts/check-test-budget.mjs` (or `--base ` / `--files `) to validate `scripts/ci/nightly-only-suites.json` integrity and enforce the budget rules on new or changed test files. + +## Review criteria + +- Flag new PR test files with unannotated sleeps `> 1000ms`, historical SQL migration replay files, static prose-grep guidance tests, or tiny `<= 80` LOC embedded-Postgres files that belong in an existing owner suite. +- Flag any edit to `scripts/ci/nightly-only-suites.json` that adds missing/duplicate paths or demotes a core control-plane or security/privacy invariant suite. diff --git a/scripts/__tests__/ci-typecheck-lane.test.mjs b/scripts/__tests__/ci-typecheck-lane.test.mjs index 04c745a0de6..938de3de91a 100644 --- a/scripts/__tests__/ci-typecheck-lane.test.mjs +++ b/scripts/__tests__/ci-typecheck-lane.test.mjs @@ -4,8 +4,11 @@ import { getPriority } from "node:os"; import test from "node:test"; import { BACKGROUND_PRIORITY, + BUILD_SERVER_EMIT_ONLY, + computeResourceProfile, createReporter, planLane, + PREPARE_RUNNER_VENDOR, resolveScope, runLane, selectBuildGapPackages, @@ -23,12 +26,19 @@ const plan = () => const quietReporter = (lines = []) => createReporter({ write: (text) => lines.push(text), github: false }); const node = (name, source, needs) => ({ name, command: process.execPath, args: ["-e", source], needs }); -test("the shared outputs are written before the parallel checks start", () => { +test("the shared outputs are written before dependent checks start, while emit-only server build overlaps", () => { const { prepare, tasks } = plan(); - const names = prepare.map((task) => task.name); - const build = prepare.find((task) => task.args.includes("@paperclipai/server") && task.args.includes("build")); - assert.deepEqual(build.env, { PAPERCLIP_TSC_EMIT_ONLY: "1" }); - assert.ok(names.indexOf("check server runtime assets") > names.indexOf(build.name)); + const byName = new Map(tasks.map((task) => [task.name, task])); + assert.ok(!prepare.some((task) => task.name === BUILD_SERVER_EMIT_ONLY)); + assert.ok(!prepare.some((task) => task.name === "check server runtime assets")); + const build = byName.get(BUILD_SERVER_EMIT_ONLY); + assert.deepEqual(build.env, { + PAPERCLIP_TSC_EMIT_ONLY: "1", + PAPERCLIP_RUNNER_VENDOR_REQUIRE_CURRENT: "1", + }); + assert.deepEqual(build.needs, [PREPARE_RUNNER_VENDOR]); + assert.equal(build.background, true); + assert.deepEqual(byName.get("check server runtime assets").needs, [BUILD_SERVER_EMIT_ONLY]); assert.ok(prepare.some((task) => task.args.join(" ") === "scripts/typecheck-test-programs.mjs --prepare-only")); for (const name of SERIAL_BUILD_GAPS) { assert.ok(prepare.some((task) => task.name === `typecheck ${name}`), name); @@ -37,22 +47,26 @@ test("the shared outputs are written before the parallel checks start", () => { const guidance = prepare.find((task) => task.name === "CLI guidance safety"); assert.ok(guidance.args.includes("server/src/__tests__/cli-invocation-safety.test.ts")); assert.equal(guidance.background, undefined); - const programs = tasks.find((task) => task.name === "typecheck test programs"); + const programs = byName.get("typecheck test programs"); assert.ok(programs.args.includes("--skip-prepare")); + assert.deepEqual(programs.needs, [PREPARE_RUNNER_VENDOR]); for (const task of tasks) { assert.ok(!(task.args.includes("@paperclipai/server") && task.args.includes("typecheck")), task.name); } }); -test("every check of the sequential job is planned, and only declaration readers wait", () => { +test("every check of the sequential job is planned with exact DAG dependencies", () => { const { tasks } = plan(); const byName = new Map(tasks.map((task) => [task.name, task])); + assert.deepEqual(byName.get(PREPARE_RUNNER_VENDOR).args, ["--filter", "@paperclipai/server", "run", "prepare:runner-vendor"]); + assert.equal(byName.get(PREPARE_RUNNER_VENDOR).needs, undefined); assert.deepEqual(byName.get("server declarations").args, [ "server/scripts/typecheck-layers.mjs", "--declarations-only", "--checkers", "2", ]); + assert.deepEqual(byName.get("server declarations").needs, [PREPARE_RUNNER_VENDOR]); for (const layer of ["tests", "test-tree-0"]) { const task = byName.get(`server layer ${layer}`); assert.deepEqual(task.args, ["server/scripts/typecheck-layers.mjs", "--layer", layer, "--checkers", "1"]); @@ -65,15 +79,68 @@ test("every check of the sequential job is planned, and only declaration readers assert.deepEqual(task.needs, ["server declarations"]); } for (const name of ["paperclipai", "@paperclipai/ui"]) assert.ok(byName.has(`typecheck ${name}`), name); + assert.deepEqual(byName.get("typecheck paperclipai").needs, [PREPARE_RUNNER_VENDOR]); + assert.equal(byName.get("typecheck @paperclipai/ui").needs, undefined); assert.deepEqual(byName.get("typecheck @paperclipai/ui").env, { GOMAXPROCS: "2" }); assert.deepEqual(byName.get("release registry tests").args, ["run", "test:release-registry"]); + assert.equal(byName.get("release registry tests").needs, undefined); assert.ok(!byName.has("CLI guidance safety")); - const waiting = tasks.filter((task) => task.needs); - assert.equal(waiting.length, 2 + PROJECTS.length); - assert.deepEqual( - tasks.filter((task) => !task.background).map((task) => task.name), - ["server declarations", "release registry tests", ...waiting.map((task) => task.name)], - ); + const declarationReaders = tasks.filter((task) => task.needs?.includes("server declarations")); + assert.equal(declarationReaders.length, 2 + PROJECTS.length); +}); + +test("computeResourceProfile scales concurrency, checkers, and UI GOMAXPROCS across 2/4/8-core runners", () => { + const GiB = 1024 ** 3; + assert.deepEqual(computeResourceProfile({ cpus: 2, totalMemoryBytes: 8 * GiB }), { + laneConcurrency: 2, + serverDeclCheckers: 1, + serverLayerCheckers: 1, + testProjectCheckers: 1, + uiGomaxprocs: 1, + testProgramsConcurrency: 1, + testProgramsCheckers: 1, + }); + assert.deepEqual(computeResourceProfile({ cpus: 4, totalMemoryBytes: 16 * GiB }), { + laneConcurrency: 3, + serverDeclCheckers: 2, + serverLayerCheckers: 1, + testProjectCheckers: 1, + uiGomaxprocs: 2, + testProgramsConcurrency: 2, + testProgramsCheckers: 1, + }); + // 8-core / 16 GiB (c8i.2xlarge): 4 concurrent tasks so all 4 server layers finish in 1 wave under 16 GiB. + const c8i = computeResourceProfile({ cpus: 8, totalMemoryBytes: 16 * GiB }); + assert.deepEqual(c8i, { + laneConcurrency: 4, + serverDeclCheckers: 3, + serverLayerCheckers: 1, + testProjectCheckers: 1, + uiGomaxprocs: 4, + testProgramsConcurrency: 3, + testProgramsCheckers: 1, + }); + // 8-core / 32 GiB (m8i.2xlarge): higher checkers and concurrency. + const m8i = computeResourceProfile({ cpus: 8, totalMemoryBytes: 32 * GiB }); + assert.deepEqual(m8i, { + laneConcurrency: 6, + serverDeclCheckers: 4, + serverLayerCheckers: 2, + testProjectCheckers: 2, + uiGomaxprocs: 4, + testProgramsConcurrency: 4, + testProgramsCheckers: 2, + }); + + const { tasks } = planLane({ + buildGapPackages: ["@paperclipai/ui"], + testLayers: ["tests"], + resources: c8i, + }); + const byName = new Map(tasks.map((t) => [t.name, t])); + assert.deepEqual(byName.get("server declarations").args.slice(-2), ["--checkers", "3"]); + assert.deepEqual(byName.get("typecheck @paperclipai/ui").env, { GOMAXPROCS: "4" }); + assert.ok(byName.get("typecheck test programs").args.join(" ").includes("--concurrency 3")); }); test("resolveScope uses CI_PLAN in PR mode, honors PAPERCLIP_CI_FULL, and fails closed", () => { @@ -138,11 +205,14 @@ test("PR mode for a server-only change skips release registry, UI, runner, sandb const prepareNames = prepare.map((task) => task.name); const taskNames = tasks.map((task) => task.name); - assert.ok(prepareNames.includes("build server without type checks")); + assert.ok(!prepareNames.includes("build server without type checks")); assert.ok(prepareNames.includes("CLI guidance safety")); assert.ok(!prepareNames.includes("install test program dependencies")); assert.ok(!prepareNames.includes("typecheck @paperclipai/paperclip-runner")); + assert.ok(taskNames.includes(PREPARE_RUNNER_VENDOR)); + assert.ok(taskNames.includes(BUILD_SERVER_EMIT_ONLY)); + assert.ok(taskNames.includes("check server runtime assets")); assert.ok(taskNames.includes("server declarations")); assert.ok(taskNames.includes("server layer tests")); assert.ok(taskNames.includes("typecheck paperclipai")); @@ -167,6 +237,8 @@ test("selectTestProjects follows the import graph so imported UI and server help assert.deepEqual(selectTestProjects(["ui/src/components/Sidebar.tsx"]), []); assert.ok(selectTestProjects(["server/src/services/issues.ts"]).includes("tests/runner-e2e")); assert.ok(selectTestProjects(["server/src/services/issues.ts"]).includes("server/src/__tests__/helpers/maintenance")); + assert.ok(selectTestProjects(["server/src/index.ts"]).includes("tests/e2e")); + assert.ok(selectTestProjects(["packages/db/src/test-embedded-postgres.ts"]).includes("tests/e2e")); assert.ok(selectTestProjects(["tests/unknown-new-project/a.ts"], [...PROJECTS, "tests/unknown-new-project"]).includes("tests/unknown-new-project")); const uiHelperPlan = planLane({ @@ -222,6 +294,10 @@ test("PR mode fails closed for unknown build-gap packages and global typecheck i assert.deepEqual(selectBuildGapPackages(["@paperclipai/ui", "@paperclipai/new-pkg"], ["server/src/a.ts"]), [ "@paperclipai/new-pkg", ]); + assert.deepEqual( + selectBuildGapPackages(["@paperclipai/ui"], ["packages/paperclip-runner/src/drivers/acpx/pi-extension-adapter.ts"]), + ["@paperclipai/ui"], + ); const globalPlan = planLane({ buildGapPackages: ["paperclipai", "@paperclipai/paperclip-runner", "@paperclipai/ui"], testLayers: ["tests"], diff --git a/scripts/__tests__/e2e-shard.test.mjs b/scripts/__tests__/e2e-shard.test.mjs index d19d0eba92a..f71afb68578 100644 --- a/scripts/__tests__/e2e-shard.test.mjs +++ b/scripts/__tests__/e2e-shard.test.mjs @@ -9,6 +9,7 @@ import test from "node:test"; import { defaultSuiteWeight, loadShardDurations } from "../general-server-shard.mjs"; import { DEFAULT_PARALLEL_WORKERS, + EFFECTIVE_PARALLEL_SPEEDUP, IGNORED_SPECS, SERIAL_SPECS, isSerialE2eSpec, @@ -152,10 +153,12 @@ test("the serial spec list matches playwright.config.ts SERIAL_SPECS and never m } }); -test("playwright.config.ts supports skipping the UI build when PAPERCLIP_E2E_SKIP_UI_BUILD=1", () => { +test("playwright.config.ts supports skipping the UI build when PAPERCLIP_E2E_SKIP_UI_BUILD=1 and uses unminified inline builds", () => { const config = readFileSync(playwrightConfig, "utf8"); assert.match(config, /PAPERCLIP_E2E_SKIP_UI_BUILD/); assert.match(config, /ui-dist.*index\.html/); + assert.match(config, /--minify false/); + assert.match(config, /availableParallelism/); }); test("the duration manifest only names specs that still exist", () => { @@ -172,11 +175,11 @@ test("the weighted partition keeps the shards close to balanced", () => { const specs = listE2eSpecs(); const fallbackWeight = defaultSuiteWeight(durations); const shards = partitionE2eShards(specs, SHARD_COUNT, durations, { - parallelWorkers: DEFAULT_PARALLEL_WORKERS, + parallelWorkers: EFFECTIVE_PARALLEL_SPEEDUP, }); const wallWeights = shards.map((shard) => { const serialSum = shard.files.reduce((sum, file) => sum + (durations[file] ?? fallbackWeight), 0); - return shard.mode === "parallel" ? serialSum / DEFAULT_PARALLEL_WORKERS : serialSum; + return shard.mode === "parallel" ? serialSum / EFFECTIVE_PARALLEL_SPEEDUP : serialSum; }); const heaviest = Math.max(...wallWeights); diff --git a/scripts/__tests__/run-vitest-stable-pr-mode.test.mjs b/scripts/__tests__/run-vitest-stable-pr-mode.test.mjs index 0e53b26f544..867719a20f3 100644 --- a/scripts/__tests__/run-vitest-stable-pr-mode.test.mjs +++ b/scripts/__tests__/run-vitest-stable-pr-mode.test.mjs @@ -6,6 +6,13 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import test from "node:test"; import { selectionHash } from "../ci/test-selection-manifest.mjs"; +import { + defaultServerParallelWorkers, + resolveServerParallelWorkers, + resolveWorkspaceParallelWorkers, +} from "../ci/vitest-workers.mjs"; +import { partitionWorkspaceProjects, selectWorkspaceProjectsShard } from "../ci/workspaces-b-shard.mjs"; +import { discoverWorkspacePackagePaths, ensureAllWorkspaceLinksCurrent } from "../ensure-workspace-package-links.mjs"; const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); const script = path.join(repoRoot, "scripts", "run-vitest-stable.mjs"); @@ -19,6 +26,7 @@ function workflowEnv(envOverrides = {}) { "PAPERCLIP_CI_EXCLUDE_NIGHTLY", "PAPERCLIP_CI_NIGHTLY_SUITES_FILE", "PAPERCLIP_VITEST_MAX_WORKERS", + "PAPERCLIP_VITEST_CPU_COUNT", "PAPERCLIP_TEST_POSTGRES_ADMIN_URL", "PAPERCLIP_CI_TEST_SELECTION", "PAPERCLIP_CI_SELECTION_HASH", @@ -74,6 +82,7 @@ test("general-workspaces-b and general-workspaces-a batch all projects into one const aProjectsArg = aCalls[0].flatMap((arg, index) => (arg === "--project" ? [aCalls[0][index + 1]] : [])); assert.deepEqual(aProjectsArg, workspacesAProjects); assert.ok(aCalls[0].includes("--shard=2/2")); + assert.ok(aCalls[0].some((arg) => /^--maxWorkers=\d+$/.test(arg)), `expected top-level --maxWorkers in ${aCalls[0].join(" ")}`); } finally { rmSync(directory, { recursive: true, force: true }); } @@ -233,3 +242,152 @@ test("shared Postgres wrapper skips non-Postgres workspace groups even when opte rmSync(directory, { recursive: true, force: true }); } }); + +test("dynamic server workers scale cleanly across 4-core and 8-core runners while honoring explicit overrides", { skip: process.platform === "win32" }, () => { + assert.equal(defaultServerParallelWorkers("general", 1), 1); + assert.equal(defaultServerParallelWorkers("general", 4), 4); + assert.equal(defaultServerParallelWorkers("general", 8), 7); + assert.equal(defaultServerParallelWorkers("general", 16), 8); + + assert.equal(defaultServerParallelWorkers("serialized", 1), 1); + assert.equal(defaultServerParallelWorkers("serialized", 4), 3); + assert.equal(defaultServerParallelWorkers("serialized", 8), 5); + assert.equal(defaultServerParallelWorkers("serialized", 16), 6); + + assert.equal(resolveServerParallelWorkers("general", { PAPERCLIP_VITEST_CPU_COUNT: "8" }), 7); + assert.equal(resolveServerParallelWorkers("serialized", { PAPERCLIP_VITEST_CPU_COUNT: "8" }), 5); + assert.equal(resolveWorkspaceParallelWorkers({ PAPERCLIP_VITEST_CPU_COUNT: "4" }), 4); + assert.equal(resolveWorkspaceParallelWorkers({ PAPERCLIP_VITEST_CPU_COUNT: "8" }), 7); + assert.equal(resolveWorkspaceParallelWorkers({ PAPERCLIP_VITEST_CPU_COUNT: "8", PAPERCLIP_VITEST_MAX_WORKERS: "3" }), 3); + assert.equal( + resolveServerParallelWorkers("general", { PAPERCLIP_VITEST_CPU_COUNT: "8", PAPERCLIP_VITEST_MAX_WORKERS: "2" }), + 2, + ); + assert.throws(() => resolveServerParallelWorkers("general", { PAPERCLIP_VITEST_MAX_WORKERS: "0" })); + + const directory = mkdtempSync(path.join(os.tmpdir(), "dynamic-workers-")); + const receipt = path.join(directory, "args.json"); + const fakePnpm = path.join(directory, "pnpm"); + writeFileSync(fakePnpm, `#!/usr/bin/env node\nrequire('node:fs').writeFileSync(${JSON.stringify(receipt)}, JSON.stringify(process.argv.slice(2)));\n`); + chmodSync(fakePnpm, 0o755); + try { + for (const [cpuCount, expectedGeneral, expectedSerialized] of [ + ["4", 4, 3], + ["8", 7, 5], + ]) { + for (const [modeArgs, expectedWorkers] of [ + [["--mode", "general", "--group", "general-server-without-chat-or-native-runner", "--shard-index", "0", "--shard-count", "12"], expectedGeneral], + [["--mode", "general", "--group", "general-server-native-runner"], expectedGeneral], + [["--mode", "serialized", "--shard-index", "0", "--shard-count", "9"], expectedSerialized], + ]) { + const result = spawnSync(process.execPath, [script, ...modeArgs], { + cwd: repoRoot, + encoding: "utf8", + env: workflowEnv({ + PATH: `${directory}${path.delimiter}${process.env.PATH}`, + PAPERCLIP_CI_PROFILE: "false", + PAPERCLIP_TEST_POSTGRES_SHARED: "0", + PAPERCLIP_VITEST_CPU_COUNT: cpuCount, + }), + }); + assert.equal(result.status, 0, result.stdout + result.stderr); + const args = JSON.parse(readFileSync(receipt, "utf8")); + assert.ok(args.includes(`--maxWorkers=${expectedWorkers}`), `cpu=${cpuCount} expected --maxWorkers=${expectedWorkers} in ${args.join(" ")}`); + } + } + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); + +test("general-workspaces-b 2-shard split partitions projects cleanly without Vitest --shard and balances adapter-utils", { skip: process.platform === "win32" }, () => { + const unsharded = dryRunJson(["--mode", "general", "--group", "general-workspaces-b"]); + const shard0 = dryRunJson(["--mode", "general", "--group", "general-workspaces-b", "--shard-index", "0", "--shard-count", "2"]); + const shard1 = dryRunJson(["--mode", "general", "--group", "general-workspaces-b", "--shard-index", "1", "--shard-count", "2"]); + + assert.equal(shard0.workspacesVitestShard, null); + assert.equal(shard1.workspacesVitestShard, null); + assert.deepEqual(shard0.workspaceProjects, ["@paperclipai/adapter-utils"]); + assert.ok(shard1.workspaceProjects.length === unsharded.workspaceProjects.length - 1); + + const combined = [...shard0.workspaceProjects, ...shard1.workspaceProjects].sort(); + assert.deepEqual(combined, [...unsharded.workspaceProjects].sort(), "2-shard partition must cover every project exactly once"); + + // Unknown future projects get default weight and are still partitioned cleanly. + const withFuture = partitionWorkspaceProjects([...unsharded.workspaceProjects, "@paperclipai/future-pkg"], 2); + assert.ok(withFuture.flatMap((s) => s.projects).includes("@paperclipai/future-pkg")); + assert.deepEqual(selectWorkspaceProjectsShard(unsharded.workspaceProjects, 0, 1), unsharded.workspaceProjects); + + const directory = mkdtempSync(path.join(os.tmpdir(), "workspaces-b-shards-")); + const receipt = path.join(directory, "calls.ndjson"); + const fakePnpm = path.join(directory, "pnpm"); + writeFileSync(fakePnpm, `#!/usr/bin/env node\nrequire('node:fs').appendFileSync(${JSON.stringify(receipt)}, JSON.stringify(process.argv.slice(2)) + '\\n');\n`); + chmodSync(fakePnpm, 0o755); + try { + const run = (args) => { + rmSync(receipt, { force: true }); + const result = spawnSync(process.execPath, [script, ...args], { + cwd: repoRoot, + encoding: "utf8", + env: workflowEnv({ + PATH: `${directory}${path.delimiter}${process.env.PATH}`, + PAPERCLIP_CI_PROFILE: "false", + PAPERCLIP_TEST_POSTGRES_SHARED: "0", + }), + }); + assert.equal(result.status, 0, result.stdout + result.stderr); + return existsSync(receipt) + ? readFileSync(receipt, "utf8").trim().split("\n").map((line) => JSON.parse(line)) + : []; + }; + + for (const [index, expectedProjects] of [ + ["0", shard0.workspaceProjects], + ["1", shard1.workspaceProjects], + ]) { + const calls = run(["--mode", "general", "--group", "general-workspaces-b", "--shard-index", index, "--shard-count", "2"]); + assert.equal(calls.length, 1, `workspaces-b shard ${index}/2 must invoke vitest once`); + const projectsArg = calls[0].flatMap((arg, i) => (arg === "--project" ? [calls[0][i + 1]] : [])); + assert.deepEqual(projectsArg, expectedProjects); + assert.ok(!calls[0].some((arg) => arg.startsWith("--shard=")), "project-partitioned shard must not pass --shard"); + } + + // Over-sharded empty bucket skips vitest rather than running unfiltered. + const emptyCalls = run(["--mode", "general", "--group", "general-workspaces-b", "--shard-index", "20", "--shard-count", "25"]); + assert.deepEqual(emptyCalls, []); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); + +test("ensure-workspace-package-links discovers workspace packages and repairs stale links without tsx", { skip: process.platform === "win32" }, async () => { + const discovered = discoverWorkspacePackagePaths(repoRoot); + for (const name of ["@paperclipai/server", "@paperclipai/ui", "@paperclipai/shared", "@paperclipai/db", "@paperclipai/plugin-sdk", "paperclipai"]) { + assert.ok(discovered.has(name), `expected workspace package ${name}`); + } + + const fixtureRoot = mkdtempSync(path.join(os.tmpdir(), "ws-links-fixture-")); + const { mkdirSync, symlinkSync, realpathSync } = await import("node:fs"); + try { + const sharedDir = path.join(fixtureRoot, "packages", "shared"); + const staleDir = path.join(fixtureRoot, "stale-target"); + const serverDir = path.join(fixtureRoot, "server"); + mkdirSync(path.join(sharedDir, "src"), { recursive: true }); + mkdirSync(staleDir, { recursive: true }); + mkdirSync(path.join(serverDir, "node_modules", "@paperclipai"), { recursive: true }); + writeFileSync(path.join(sharedDir, "package.json"), JSON.stringify({ name: "@paperclipai/shared" })); + writeFileSync(path.join(serverDir, "package.json"), JSON.stringify({ + name: "@paperclipai/server", + dependencies: { "@paperclipai/shared": "workspace:*" }, + })); + symlinkSync(staleDir, path.join(serverDir, "node_modules", "@paperclipai", "shared")); + + await ensureAllWorkspaceLinksCurrent(fixtureRoot); + assert.equal( + realpathSync(path.join(serverDir, "node_modules", "@paperclipai", "shared")), + realpathSync(sharedDir), + ); + } finally { + rmSync(fixtureRoot, { recursive: true, force: true }); + } +}); diff --git a/scripts/__tests__/run-vitest-stable-shard.test.mjs b/scripts/__tests__/run-vitest-stable-shard.test.mjs index 8868e8301c5..2f3b9cb8cc2 100644 --- a/scripts/__tests__/run-vitest-stable-shard.test.mjs +++ b/scripts/__tests__/run-vitest-stable-shard.test.mjs @@ -15,6 +15,7 @@ import { import { assertManifestSource } from "../ci/pr-run-durations.mjs"; import { assertSelectedTests, partitionTestLines } from "../test-line-shard.mjs"; import { chatManifestData, entryDurations } from "../ci/refresh-chat-shard-durations.mjs"; +import { defaultServerParallelWorkers } from "../ci/vitest-workers.mjs"; const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); const script = path.join(repoRoot, "scripts", "run-vitest-stable.mjs"); @@ -37,6 +38,7 @@ function workflowEnv(envOverrides = {}) { "PAPERCLIP_CI_EXCLUDE_NIGHTLY", "PAPERCLIP_CI_NIGHTLY_SUITES_FILE", "PAPERCLIP_VITEST_MAX_WORKERS", + "PAPERCLIP_VITEST_CPU_COUNT", "PAPERCLIP_TEST_POSTGRES_ADMIN_URL", ]) { if (!(key in envOverrides)) { @@ -101,12 +103,10 @@ test("general shards retain scripts and route-named suites outside the serialize ]) assert.ok(general.selectedGeneralServerSuites.includes(file), `missing configured server suite: ${file}`); }); -for (const group of ["general-workspaces-b", "general-workspaces-c"]) { - test(`shard flags are rejected for the ${group} group`, () => { - const result = dryRun(["--mode", "general", "--group", group, "--shard-index", "0", "--shard-count", "3"]); - assert.notEqual(result.status, 0, `${group} must not accept shard flags`); - }); -} +test("shard flags are rejected for the general-workspaces-c group", () => { + const result = dryRun(["--mode", "general", "--group", "general-workspaces-c", "--shard-index", "0", "--shard-count", "3"]); + assert.notEqual(result.status, 0, "general-workspaces-c must not accept shard flags"); +}); test("workspace lanes cover every non-server project in the root Vitest configuration", () => { const config = readFileSync(path.join(repoRoot, "vitest.config.ts"), "utf8"); @@ -183,11 +183,19 @@ test("workspaces-c runs the db project alone and workspaces-b no longer carries const sharded = entries.filter(entry => entry.group === "general-workspaces-a"); assert.ok(sharded.length > 0 && sharded.every(entry => entry.keys.includes("shard_index") && entry.keys.includes("shard_count")), `${workflow} must carry the sharded workspaces-a entries`); - for (const group of ["general-workspaces-b", "general-workspaces-c"]) { - const matching = entries.filter(entry => entry.group === group); - assert.equal(matching.length, 1, `${workflow} must run ${group} exactly once`); - assert.ok(matching[0].keys.includes("group_label"), `${workflow} must label the ${group} job`); - assert.deepEqual(matching[0].keys.filter(key => key.startsWith("shard_")), [], `${workflow} must run ${group} unsharded`); + const workspacesCEntries = entries.filter(entry => entry.group === "general-workspaces-c"); + assert.equal(workspacesCEntries.length, 1, `${workflow} must run general-workspaces-c exactly once`); + assert.ok(workspacesCEntries[0].keys.includes("group_label"), `${workflow} must label the general-workspaces-c job`); + assert.deepEqual(workspacesCEntries[0].keys.filter(key => key.startsWith("shard_")), [], `${workflow} must run general-workspaces-c unsharded`); + + const workspacesBEntries = entries.filter(entry => entry.group === "general-workspaces-b"); + assert.ok(workspacesBEntries.length >= 1, `${workflow} must run general-workspaces-b`); + assert.ok(workspacesBEntries.every(entry => entry.keys.includes("group_label")), `${workflow} must label every general-workspaces-b job`); + if (workspacesBEntries.length === 1) { + assert.deepEqual(workspacesBEntries[0].keys.filter(key => key.startsWith("shard_")), [], `${workflow} single general-workspaces-b entry must be unsharded`); + } else { + assert.ok(workspacesBEntries.every(entry => entry.keys.includes("shard_index") && entry.keys.includes("shard_count")), + `${workflow} multi-shard general-workspaces-b entries must declare shard_index and shard_count`); } } }); @@ -885,11 +893,12 @@ test("a failed chat child fails the job after its sibling finishes", { skip: pro } }); -for (const [label, modeArgs, parallelWorkers] of [ - ["general-server-native-runner", ["--mode", "general", "--group", "general-server-native-runner"], 4], - ["general-server-without-chat-or-native-runner", ["--mode", "general", "--group", "general-server-without-chat-or-native-runner", "--shard-index", "0", "--shard-count", "12"], 4], - ["serialized", ["--mode", "serialized", "--shard-index", "4", "--shard-count", "9"], 3], +for (const [label, modeArgs, lane] of [ + ["general-server-native-runner", ["--mode", "general", "--group", "general-server-native-runner"], "general"], + ["general-server-without-chat-or-native-runner", ["--mode", "general", "--group", "general-server-without-chat-or-native-runner", "--shard-index", "0", "--shard-count", "12"], "general"], + ["serialized", ["--mode", "serialized", "--shard-index", "4", "--shard-count", "9"], "serialized"], ]) test(`${label} files overlap only when their database fixtures are isolated`, { skip: process.platform === "win32" }, () => { + const parallelWorkers = defaultServerParallelWorkers(lane); const directory = mkdtempSync(path.join(os.tmpdir(), "native-file-workers-")); const receipt = path.join(directory, "args.json"); const fakePnpm = path.join(directory, "pnpm"); diff --git a/scripts/check-test-budget.mjs b/scripts/check-test-budget.mjs new file mode 100644 index 00000000000..dfd0423b332 --- /dev/null +++ b/scripts/check-test-budget.mjs @@ -0,0 +1,469 @@ +#!/usr/bin/env node +import { execFileSync } from "node:child_process"; +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const repoRootDefault = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +export const NIGHTLY_MANIFEST_REL = "scripts/ci/nightly-only-suites.json"; + +const TEST_FILE_PATTERN = /^(?:packages\/db\/src|server\/src|ui\/src)\/.+\.test\.tsx?$|^tests\/e2e\/.+\.spec\.ts$/; +const SLEEP_CALL_START_PATTERN = /\b(setTimeout|delay|waitForTimeout)\s*\(/g; +const READ_FILE_START_PATTERN = /\breadFile(?:Sync)?\s*\(/g; +const HISTORICAL_MIGRATION_FILE_PATTERN = /^(?:packages\/db\/src|server\/src)\/.*migration\.test\.ts$/; +const HISTORICAL_MIGRATION_CONTENT_PATTERN = /\b0\d{3}_[a-z0-9_]+\.sql\b|--> statement-breakpoint/; +const GUIDANCE_FILE_PATTERN = /-guidance\.test\.ts$/; +const PROSE_TARGET_PATTERN = /\.(?:md|tsx)\b|SKILL\.md|AGENTS\.md|README\.md/; +const EMBEDDED_PG_PATTERN = /\b(?:startEmbeddedPostgresTestDatabase|createTestPostgres)\b/; + +export const PROTECTED_INVARIANT_PATTERN = + /(?:auth|authz|-access(?:\.|\/|$)|company-access|isolation|checkout|assignee|approval|(?:^|\/)budget-|budget-policy|budget-cancellation|budget-evaluation|budget-hold|activity-log|secret|csrf|redaction|guard|security|tenant|privacy|sentry|telemetry|otel|observability|injection|ssrf|oracle|cli-invocation-safety|webhook-ingress|credential|signature|device-login|policy-sweep|connection-management|document-scope)/i; + +const MAX_PR_SLEEP_MS = 1_000; +const TINY_DB_FILE_MAX_LOC = 80; + +function extractBalancedCallArgs(text, openParenIndex) { + let depth = 0; + let quote = null; + let escaped = false; + let argStart = openParenIndex + 1; + const args = []; + for (let i = openParenIndex; i < text.length; i += 1) { + const ch = text[i]; + if (quote) { + if (escaped) { + escaped = false; + } else if (ch === "\\") { + escaped = true; + } else if (ch === quote) { + quote = null; + } + continue; + } + if (ch === "'" || ch === '"' || ch === "`") { + quote = ch; + continue; + } + if (ch === "(" || ch === "[" || ch === "{") { + depth += 1; + continue; + } + if (ch === ")" || ch === "]" || ch === "}") { + depth -= 1; + if (depth === 0) { + args.push(text.slice(argStart, i)); + return { args, endIndex: i }; + } + continue; + } + if (ch === "," && depth === 1) { + args.push(text.slice(argStart, i)); + argStart = i + 1; + } + } + return null; +} + +function evaluateDurationExprMs(expr) { + const cleaned = expr.replace(/\/\*[\s\S]*?\*\//g, "").trim(); + if (!cleaned) return 0; + // Match pure numeric expressions like `2500`, `1_500`, `60 * 1000`, `5 * 60 * 1_000`, `2_000 + 500`. + if (/^[\d_\s+*().]+$/.test(cleaned)) { + const sumTerms = cleaned.replace(/[()]/g, "").split("+"); + let total = 0; + for (const term of sumTerms) { + const factors = term.split("*").map((part) => Number(part.trim().replaceAll("_", ""))); + if (factors.some((n) => !Number.isFinite(n))) return 0; + total += factors.reduce((acc, n) => acc * n, 1); + } + return total; + } + // Fallback: inspect the largest standalone numeric literal inside a compound expression. + let max = 0; + for (const m of cleaned.matchAll(/\b(\d[\d_]*)\b/g)) { + const value = Number(m[1].replaceAll("_", "")); + if (Number.isFinite(value) && value > max) max = value; + } + return max; +} + +function lineNumberAt(source, offset) { + let line = 1; + for (let i = 0; i < offset; i += 1) { + if (source.charCodeAt(i) === 10) line += 1; + } + return line; +} + +function hasProseSourceRead(source) { + READ_FILE_START_PATTERN.lastIndex = 0; + let match; + while ((match = READ_FILE_START_PATTERN.exec(source)) !== null) { + const openParen = match.index + match[0].length - 1; + const call = extractBalancedCallArgs(source, openParen); + const firstArg = call?.args[0] ?? ""; + if (PROSE_TARGET_PATTERN.test(firstArg)) { + return true; + } + } + return false; +} + +function fakeTimersFakesSetTimeout(rawArgs) { + const args = (rawArgs ?? "").trim(); + if (!args) return true; + const toFakeMatch = args.match(/\btoFake\s*:\s*\[([^\]]*)\]/); + if (toFakeMatch) { + return /['"`]setTimeout['"`]/.test(toFakeMatch[1]); + } + const doNotFakeMatch = args.match(/\bdoNotFake\s*:\s*\[([^\]]*)\]/); + if (doNotFakeMatch && /['"`]setTimeout['"`]/.test(doNotFakeMatch[1])) { + return false; + } + return true; +} + +function buildFakeTimeoutRanges(source) { + // Walk timer-mode transitions and test boundaries in source order so partial + // fakes (e.g. `toFake: ["Date"]`) and real-clock tests in mixed-clock files + // are still checked for unbudgeted `setTimeout` sleeps. + const events = []; + const hookRanges = []; + const hookRe = /\b(beforeEach|beforeAll|afterEach|afterAll)\s*\(/g; + let m; + while ((m = hookRe.exec(source)) !== null) { + const call = extractBalancedCallArgs(source, m.index + m[0].length - 1); + if (!call) continue; + hookRanges.push({ kind: m[1], start: m.index, end: call.endIndex }); + } + const hookKindAt = (offset) => { + for (const h of hookRanges) { + if (offset >= h.start && offset <= h.end) return h.kind; + } + return null; + }; + + const fakeRe = /\b(?:vi|jest)\.useFakeTimers\s*\(/g; + while ((m = fakeRe.exec(source)) !== null) { + const call = extractBalancedCallArgs(source, m.index + m[0].length - 1); + const fakesSetTimeout = fakeTimersFakesSetTimeout(call?.args[0] ?? ""); + const hook = hookKindAt(m.index); + events.push({ + offset: m.index, + kind: hook === "beforeEach" || hook === "beforeAll" ? "hook-fake" : "fake", + fakesSetTimeout, + }); + } + + const realRe = /\b(?:vi|jest)\.useRealTimers\s*\(/g; + while ((m = realRe.exec(source)) !== null) { + const hook = hookKindAt(m.index); + if (hook === "afterEach" || hook === "afterAll") continue; + events.push({ offset: m.index, kind: "real", fakesSetTimeout: false }); + } + + const testBoundaryRe = /^\s*(?:it|test|describe)(?:\.(?:only|skip|concurrent|sequential|each))?\s*\(/gm; + while ((m = testBoundaryRe.exec(source)) !== null) { + events.push({ offset: m.index, kind: "boundary", fakesSetTimeout: false }); + } + + events.sort((a, b) => a.offset - b.offset); + + return function isSetTimeoutFakedAt(offset) { + let hookFake = false; + let localFake = false; + for (const ev of events) { + if (ev.offset > offset) break; + if (ev.kind === "hook-fake") { + hookFake = ev.fakesSetTimeout; + localFake = hookFake; + } else if (ev.kind === "boundary") { + localFake = hookFake; + } else if (ev.kind === "fake") { + localFake = ev.fakesSetTimeout; + } else if (ev.kind === "real") { + localFake = false; + } + } + return localFake; + }; +} + +export function findUnbudgetedSleeps(source, { onlyLineNumbers = null } = {}) { + const violations = []; + const lines = source.split(/\r?\n/); + const isSetTimeoutFakedAt = buildFakeTimeoutRanges(source); + const clearedHandles = new Set( + [...source.matchAll(/\bclearTimeout\s*\(\s*([A-Za-z_$][\w$]*)\s*\)/g)].map((m) => m[1]), + ); + SLEEP_CALL_START_PATTERN.lastIndex = 0; + let match; + while ((match = SLEEP_CALL_START_PATTERN.exec(source)) !== null) { + const lineNumber = lineNumberAt(source, match.index); + const line = lines[lineNumber - 1] ?? ""; + if (/^\s*\/\//.test(line)) continue; + const openParen = match.index + match[0].length - 1; + const call = extractBalancedCallArgs(source, openParen); + if (!call) continue; + const endLineNumber = lineNumberAt(source, call.endIndex); + if (onlyLineNumbers) { + let touchesAdded = false; + for (let ln = lineNumber; ln <= endLineNumber; ln += 1) { + if (onlyLineNumbers.has(ln)) { + touchesAdded = true; + break; + } + } + if (!touchesAdded) continue; + } + let allowed = false; + for (let ln = lineNumber; ln <= endLineNumber; ln += 1) { + if ((lines[ln - 1] ?? "").includes("test-budget:allow-sleep")) { + allowed = true; + break; + } + } + if (allowed) continue; + + const callee = match[1]; + if (callee === "setTimeout") { + if (isSetTimeoutFakedAt(match.index)) continue; + // Ignore cancellable deadline timers (e.g. `const timer = setTimeout(...); ... clearTimeout(timer)`). + const beforeOnLine = source.slice(Math.max(0, match.index - 80), match.index); + const assignedVar = beforeOnLine.match(/([A-Za-z_$][\w$]*)\s*=\s*$/); + if (assignedVar && clearedHandles.has(assignedVar[1])) { + continue; + } + } + const delayArg = callee === "setTimeout" ? call.args[1] ?? "" : call.args[0] ?? ""; + const ms = evaluateDurationExprMs(delayArg); + if (ms > MAX_PR_SLEEP_MS) { + violations.push({ + rule: "sleep-over-1s", + line: lineNumber, + message: `Unbudgeted real-clock sleep (${ms}ms > ${MAX_PR_SLEEP_MS}ms). Use fake timers/condition waits, move soak suite to ${NIGHTLY_MANIFEST_REL}, or annotate with // test-budget:allow-sleep: .`, + }); + } + } + return violations; +} + +export function validateNightlyManifest(root = repoRootDefault, manifestRel = NIGHTLY_MANIFEST_REL) { + const fullPath = path.join(root, manifestRel); + const violations = []; + if (!existsSync(fullPath)) { + return { paths: new Set(), violations: [{ file: manifestRel, rule: "nightly-manifest", message: "Missing nightly manifest." }] }; + } + + let parsed; + try { + parsed = JSON.parse(readFileSync(fullPath, "utf8")); + } catch (error) { + return { + paths: new Set(), + violations: [{ file: manifestRel, rule: "nightly-manifest", message: `Invalid JSON: ${error.message}` }], + }; + } + + if (!Array.isArray(parsed?.suites)) { + return { + paths: new Set(), + violations: [{ file: manifestRel, rule: "nightly-manifest", message: "Manifest must contain a suites array." }], + }; + } + + const seen = new Set(); + for (const entry of parsed.suites) { + const suitePath = typeof entry === "string" ? entry : entry?.path; + if (typeof suitePath !== "string" || !suitePath.trim()) { + violations.push({ file: manifestRel, rule: "nightly-manifest", message: "Suite entry is missing a non-empty string path." }); + continue; + } + if (suitePath.startsWith("/") || suitePath.includes("\\") || suitePath.split("/").includes("..")) { + violations.push({ file: manifestRel, rule: "nightly-manifest", message: `Invalid non-repo-relative path: ${suitePath}` }); + continue; + } + if (seen.has(suitePath)) { + violations.push({ file: manifestRel, rule: "nightly-manifest", message: `Duplicate suite path: ${suitePath}` }); + continue; + } + seen.add(suitePath); + if (!existsSync(path.join(root, suitePath))) { + violations.push({ file: manifestRel, rule: "nightly-manifest", message: `Nightly suite does not exist on disk: ${suitePath}` }); + } + if (PROTECTED_INVARIANT_PATTERN.test(suitePath)) { + violations.push({ + file: manifestRel, + rule: "protected-invariant", + message: `Core control-plane / security / privacy invariant suite must remain on PRs, not in ${manifestRel}: ${suitePath}`, + }); + } + } + + return { paths: seen, violations }; +} + +export function checkTestFileBudget(fileRel, source, { isNew = true, nightlyPaths = new Set(), addedLineNumbers = null } = {}) { + if (!TEST_FILE_PATTERN.test(fileRel)) return []; + const violations = []; + const isNightly = nightlyPaths.has(fileRel); + + if (!isNightly) { + for (const v of findUnbudgetedSleeps(source, { onlyLineNumbers: isNew ? null : addedLineNumbers })) { + violations.push({ file: fileRel, ...v }); + } + } + + if (isNew) { + if ( + HISTORICAL_MIGRATION_FILE_PATTERN.test(fileRel) && + HISTORICAL_MIGRATION_CONTENT_PATTERN.test(source) && + !source.includes("test-budget:allow-migration-test") + ) { + violations.push({ + file: fileRel, + rule: "historical-migration-test", + message: "Do not add standalone historical SQL migration replay tests; extend core runner tests in packages/db/src/client.test.ts or migration-compatibility.test.ts.", + }); + } + + if ( + GUIDANCE_FILE_PATTERN.test(fileRel) && + hasProseSourceRead(source) && + !source.includes("test-budget:allow-prose-check") + ) { + violations.push({ + file: fileRel, + rule: "prose-guidance-grep", + message: "Do not add brittle static prose-grep guidance tests over .md/.tsx files.", + }); + } + + const lineCount = source.split(/\r?\n/).length; + if ( + !isNightly && + lineCount <= TINY_DB_FILE_MAX_LOC && + EMBEDDED_PG_PATTERN.test(source) && + !source.includes("test-budget:allow-standalone-db") + ) { + violations.push({ + file: fileRel, + rule: "tiny-standalone-db-test", + message: `New embedded-Postgres test file is only ${lineCount} LOC (<= ${TINY_DB_FILE_MAX_LOC}). Extend the owning service/route suite instead, or annotate with // test-budget:allow-standalone-db: .`, + }); + } + } + + return violations; +} + +function addedLinesFromDiff(root, baseRef, fileRel) { + const diff = execFileSync("git", ["diff", "-U0", `${baseRef}...HEAD`, "--", fileRel], { + cwd: root, + encoding: "utf8", + }); + const added = new Set(); + let currentLine = 0; + for (const line of diff.split(/\r?\n/)) { + const hunk = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/); + if (hunk) { + currentLine = Number(hunk[1]); + continue; + } + if (line.startsWith("+") && !line.startsWith("+++")) { + added.add(currentLine); + currentLine += 1; + } else if (!line.startsWith("-")) { + currentLine += 1; + } + } + return added; +} + +function changedTestFilesFromBase(root, baseRef) { + const out = execFileSync("git", ["diff", "--diff-filter=AM", "--name-status", `${baseRef}...HEAD`], { + cwd: root, + encoding: "utf8", + }); + const entries = []; + for (const raw of out.split(/\r?\n/)) { + if (!raw.trim()) continue; + const [status, fileRel] = raw.split("\t"); + if (!fileRel || !TEST_FILE_PATTERN.test(fileRel)) continue; + entries.push({ fileRel, isNew: status === "A" }); + } + return entries; +} + +export function parseBudgetArgs(argv) { + const options = { base: null, files: [], root: repoRootDefault, manifestOnly: false }; + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + if (arg === "--base") { + options.base = argv[++i] ?? null; + } else if (arg.startsWith("--base=")) { + options.base = arg.slice("--base=".length); + } else if (arg === "--root") { + options.root = path.resolve(argv[++i] ?? repoRootDefault); + } else if (arg === "--manifest-only") { + options.manifestOnly = true; + } else if (arg === "--files") { + while (i + 1 < argv.length && !argv[i + 1].startsWith("--")) { + options.files.push(argv[++i]); + } + } else if (!arg.startsWith("--")) { + options.files.push(arg); + } + } + return options; +} + +export function runTestBudgetCheck(options) { + const root = options.root ?? repoRootDefault; + const { paths: nightlyPaths, violations } = validateNightlyManifest(root); + + if (options.manifestOnly) { + return { nightlyCount: nightlyPaths.size, checkedFiles: 0, violations }; + } + + let targets = []; + if (options.files?.length) { + targets = options.files.map((fileRel) => ({ fileRel, isNew: true, addedLineNumbers: null })); + } else if (options.base) { + targets = changedTestFilesFromBase(root, options.base).map((entry) => ({ + ...entry, + addedLineNumbers: entry.isNew ? null : addedLinesFromDiff(root, options.base, entry.fileRel), + })); + } + + for (const target of targets) { + const absPath = path.join(root, target.fileRel); + if (!existsSync(absPath)) continue; + const source = readFileSync(absPath, "utf8"); + violations.push( + ...checkTestFileBudget(target.fileRel, source, { + isNew: target.isNew, + nightlyPaths, + addedLineNumbers: target.addedLineNumbers, + }), + ); + } + + return { nightlyCount: nightlyPaths.size, checkedFiles: targets.length, violations }; +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const options = parseBudgetArgs(process.argv.slice(2)); + const result = runTestBudgetCheck(options); + if (result.violations.length > 0) { + console.error(`[check-test-budget] FAILED with ${result.violations.length} violation(s):`); + for (const v of result.violations) { + const loc = v.line ? `${v.file}:${v.line}` : v.file; + console.error(` - [${v.rule}] ${loc}: ${v.message}`); + } + process.exit(1); + } + console.log( + `[check-test-budget] PASS (${result.nightlyCount} nightly suites validated, ${result.checkedFiles} test file(s) checked).`, + ); +} diff --git a/scripts/check-test-budget.test.mjs b/scripts/check-test-budget.test.mjs new file mode 100644 index 00000000000..6ad05fc8241 --- /dev/null +++ b/scripts/check-test-budget.test.mjs @@ -0,0 +1,212 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { + checkTestFileBudget, + findUnbudgetedSleeps, + runTestBudgetCheck, + validateNightlyManifest, +} from "./check-test-budget.mjs"; + +const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); + +test("checked-in scripts/ci/nightly-only-suites.json passes full manifest & invariant validation", () => { + const result = runTestBudgetCheck({ manifestOnly: true }); + assert.deepEqual(result.violations, []); + assert.ok(result.nightlyCount > 0, "expected non-empty nightly-only-suites.json"); +}); + +test("findUnbudgetedSleeps flags real-clock sleeps >1000ms (including inline callbacks and products) and respects allow-sleep annotations", () => { + const source = [ + "await delay(500);", + "await delay(1000);", + "await delay(1_500);", + "await setTimeout(resolve, 2500);", + "await new Promise((resolve) => setTimeout(() => resolve(), 2500));", + "await new Promise((resolve) => setTimeout(() => { resolve(); }, 60 * 1000));", + "await delay(2 * 1000);", + "await page.waitForTimeout(3000);", + "await delay(5000); // test-budget:allow-sleep: socket idle check", + "// await delay(9000);", + ].join("\n"); + + const violations = findUnbudgetedSleeps(source); + assert.deepEqual( + violations.map((v) => ({ rule: v.rule, line: v.line })), + [ + { rule: "sleep-over-1s", line: 3 }, + { rule: "sleep-over-1s", line: 4 }, + { rule: "sleep-over-1s", line: 5 }, + { rule: "sleep-over-1s", line: 6 }, + { rule: "sleep-over-1s", line: 7 }, + { rule: "sleep-over-1s", line: 8 }, + ], + ); + + // Cancellable deadline timers and full fake-timer scopes must not produce false positives. + assert.deepEqual( + findUnbudgetedSleeps( + "const timer = setTimeout(() => reject(new Error('timeout')), 60_000);\nclearTimeout(timer);", + ), + [], + ); + assert.deepEqual( + findUnbudgetedSleeps("vi.useFakeTimers();\nsetTimeout(() => done(), 10_000);"), + [], + ); + assert.deepEqual( + findUnbudgetedSleeps( + 'beforeEach(() => { vi.useFakeTimers(); });\nafterEach(() => { vi.useRealTimers(); });\nit("faked", () => {\n setTimeout(() => done(), 5000);\n});', + ), + [], + ); + assert.deepEqual( + findUnbudgetedSleeps( + 'vi.useFakeTimers({ toFake: ["Date", "setTimeout"] });\nsetTimeout(() => done(), 2500);', + ), + [], + ); + + // Partial fake timers (e.g. Date-only) and real-clock tests in mixed-clock files MUST still be flagged. + assert.deepEqual( + findUnbudgetedSleeps( + 'vi.useFakeTimers({ toFake: ["Date"] });\nawait new Promise((resolve) => setTimeout(resolve, 2500));', + ).map((v) => ({ rule: v.rule, line: v.line })), + [{ rule: "sleep-over-1s", line: 2 }], + ); + assert.deepEqual( + findUnbudgetedSleeps( + 'vi.useFakeTimers({ doNotFake: ["setTimeout"] });\nawait new Promise((resolve) => setTimeout(resolve, 2500));', + ).map((v) => ({ rule: v.rule, line: v.line })), + [{ rule: "sleep-over-1s", line: 2 }], + ); + assert.deepEqual( + findUnbudgetedSleeps( + [ + 'it("faked", () => {', + " vi.useFakeTimers();", + " setTimeout(() => done(), 5000);", + "});", + 'it("real", async () => {', + " await new Promise((resolve) => setTimeout(resolve, 2500));", + "});", + ].join("\n"), + ).map((v) => ({ rule: v.rule, line: v.line })), + [{ rule: "sleep-over-1s", line: 6 }], + ); + assert.deepEqual( + findUnbudgetedSleeps( + [ + 'it("restores", async () => {', + " vi.useFakeTimers();", + " setTimeout(() => done(), 5000);", + " vi.useRealTimers();", + " await new Promise((resolve) => setTimeout(resolve, 2500));", + "});", + ].join("\n"), + ).map((v) => ({ rule: v.rule, line: v.line })), + [{ rule: "sleep-over-1s", line: 5 }], + ); +}); + +test("checkTestFileBudget enforces migration, prose-guidance, and tiny embedded-PG rules on new files", () => { + const mig = checkTestFileBudget( + "packages/db/src/old-backfill-migration.test.ts", + 'const sql = readFileSync("./migrations/0420_backfill.sql", "utf8");', + { isNew: true }, + ); + assert.deepEqual(mig.map((v) => v.rule), ["historical-migration-test"]); + + const guidance = checkTestFileBudget( + "server/src/__tests__/foo-guidance.test.ts", + 'const text = readFileSync("ui/src/App.tsx", "utf8"); expect(text).toContain("Settings");', + { isNew: true }, + ); + assert.deepEqual(guidance.map((v) => v.rule), ["prose-guidance-grep"]); + + const nestedGuidance = checkTestFileBudget( + "server/src/__tests__/bar-guidance.test.ts", + 'const text = readFileSync(path.join(dir, "README.md"), "utf8"); expect(text).toContain("Usage");', + { isNew: true }, + ); + assert.deepEqual(nestedGuidance.map((v) => v.rule), ["prose-guidance-grep"]); + + const tinyPg = checkTestFileBudget( + "server/src/__tests__/tiny-one-off.test.ts", + 'import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";\nit("works", async () => {});', + { isNew: true }, + ); + assert.deepEqual(tinyPg.map((v) => v.rule), ["tiny-standalone-db-test"]); + + const tinyPgAllowed = checkTestFileBudget( + "server/src/__tests__/tiny-one-off.test.ts", + '// test-budget:allow-standalone-db: needs isolated process env\nimport { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";', + { isNew: true }, + ); + assert.deepEqual(tinyPgAllowed, []); + + // Nightly-registered suites are exempt from PR sleep & tiny-DB limits. + const nightly = checkTestFileBudget( + "server/src/__tests__/soak-example.test.ts", + 'import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";\nawait delay(5000);', + { isNew: true, nightlyPaths: new Set(["server/src/__tests__/soak-example.test.ts"]) }, + ); + assert.deepEqual(nightly, []); +}); + +test("validateNightlyManifest rejects missing files, duplicates, and protected core invariant suites", () => { + const tmp = mkdtempSync(path.join(os.tmpdir(), "paperclip-test-budget-")); + try { + mkdirSync(path.join(tmp, "scripts/ci"), { recursive: true }); + mkdirSync(path.join(tmp, "server/src/__tests__"), { recursive: true }); + mkdirSync(path.join(tmp, "server/src/services/connectors"), { recursive: true }); + writeFileSync(path.join(tmp, "server/src/__tests__/authz-company-access.test.ts"), "// authz\n"); + writeFileSync(path.join(tmp, "server/src/services/connectors/slack-access.test.ts"), "// access\n"); + writeFileSync(path.join(tmp, "server/src/services/budget-resume-continuation.test.ts"), "// budget\n"); + writeFileSync(path.join(tmp, "server/src/__tests__/webhook-ingress.test.ts"), "// webhook\n"); + writeFileSync(path.join(tmp, "server/src/__tests__/storage-s3-credential-rotation.test.ts"), "// cred\n"); + writeFileSync(path.join(tmp, "server/src/__tests__/connection-management.integration.test.ts"), "// isolation\n"); + writeFileSync(path.join(tmp, "server/src/__tests__/real-soak.test.ts"), "// soak\n"); + writeFileSync( + path.join(tmp, "scripts/ci/nightly-only-suites.json"), + JSON.stringify({ + suites: [ + { path: "server/src/__tests__/real-soak.test.ts" }, + { path: "server/src/__tests__/real-soak.test.ts" }, + { path: "server/src/__tests__/missing-suite.test.ts" }, + { path: "server/src/__tests__/authz-company-access.test.ts" }, + { path: "server/src/services/connectors/slack-access.test.ts" }, + { path: "server/src/services/budget-resume-continuation.test.ts" }, + { path: "server/src/__tests__/webhook-ingress.test.ts" }, + { path: "server/src/__tests__/storage-s3-credential-rotation.test.ts" }, + { path: "server/src/__tests__/connection-management.integration.test.ts" }, + ], + }), + ); + + const { violations } = validateNightlyManifest(tmp); + assert.deepEqual( + violations.map((v) => v.rule), + [ + "nightly-manifest", + "nightly-manifest", + "protected-invariant", + "protected-invariant", + "protected-invariant", + "protected-invariant", + "protected-invariant", + "protected-invariant", + ], + ); + } finally { + rmSync(tmp, { recursive: true, force: true }); + } +}); + +test("pr-trusted.yml invokes check-test-budget.mjs with --base on pull requests", () => { + const workflow = readFileSync(path.join(repoRoot, ".github/workflows/pr-trusted.yml"), "utf8"); + assert.match(workflow, /node \.\/scripts\/check-test-budget\.mjs --base "\$base_sha"/); +}); diff --git a/scripts/ci-dependency-cache.mjs b/scripts/ci-dependency-cache.mjs index cca636cfb45..1b267340fd7 100644 --- a/scripts/ci-dependency-cache.mjs +++ b/scripts/ci-dependency-cache.mjs @@ -1,10 +1,13 @@ -import { execFileSync } from "node:child_process"; +import { execFile } from "node:child_process"; import { createHash } from "node:crypto"; import { appendFileSync, existsSync, readFileSync, realpathSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; import { readPluginsUnder } from "./link-plugin-dev-sdk.mjs"; +const execFileAsync = promisify(execFile); + const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const postinstallHooks = new Map([ @@ -55,9 +58,16 @@ export function cachePlan({ files, read, scope, packageDirs }) { } if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { - const files = execFileSync("git", ["ls-files", "-z"], { cwd: root }).toString().split("\0").filter(Boolean); - const command = (args) => execFileSync("pnpm", args, { cwd: root, encoding: "utf8" }).trim(); - const workspaces = JSON.parse(command(['-r', 'list', '--depth=-1', '--json'])); + const command = (bin, args) => + execFileAsync(bin, args, { cwd: root, encoding: "utf8", maxBuffer: 16 * 1024 * 1024 }).then(({ stdout }) => stdout); + const [gitFilesRaw, workspacesRaw, pnpmVersionRaw, pnpmStoreRaw] = await Promise.all([ + command("git", ["ls-files", "-z"]), + command("pnpm", ["-r", "list", "--depth=-1", "--json"]), + command("pnpm", ["--version"]), + command("pnpm", ["store", "path", "--silent"]), + ]); + const files = gitFilesRaw.split("\0").filter(Boolean); + const workspaces = JSON.parse(workspacesRaw.trim()); const packageDirs = ['.', ...workspaces.map((workspace) => path.relative(root, workspace.path).split(path.sep).join('/') || '.'), ...readPluginsUnder(path.join(root, 'packages/plugins/sandbox-providers')).map((directory) => path.relative(root, directory).split(path.sep).join('/')), @@ -71,7 +81,7 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me root: realpathSync(root), node: process.version, abi: process.versions.modules, platform: process.platform, arch: process.arch, libc: process.report.getReport().header.glibcVersionRuntime ?? null, - pnpm: command(["--version"]), store: command(["store", "path", "--silent"]), + pnpm: pnpmVersionRaw.trim(), store: pnpmStoreRaw.trim(), }, }); const output = [ diff --git a/scripts/ci-typecheck-lane.mjs b/scripts/ci-typecheck-lane.mjs index 3595963956f..eb8bd50bf69 100644 --- a/scripts/ci-typecheck-lane.mjs +++ b/scripts/ci-typecheck-lane.mjs @@ -1,7 +1,7 @@ #!/usr/bin/env node import { execFileSync, spawn, spawnSync } from "node:child_process"; -import { availableParallelism, setPriority } from "node:os"; +import { availableParallelism, setPriority, totalmem } from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { listLayers } from "../server/scripts/typecheck-layers.mjs"; @@ -13,10 +13,72 @@ export const SERIAL_BUILD_GAPS = ["@paperclipai/paperclip-runner"]; export const BACKGROUND_PRIORITY = 10; export const DEFAULT_MAX_CONCURRENCY = 3; export const DEFAULT_TEST_PROGRAMS_CONCURRENCY = 2; +export const PREPARE_RUNNER_VENDOR = "prepare runner vendor"; +export const BUILD_SERVER_EMIT_ONLY = "build server without type checks"; const SERVER_DECLARATIONS = "server declarations"; export const CLI_GUIDANCE_SAFETY = "CLI guidance safety"; const lowMemory = { [LOW_MEMORY_VARIABLE]: "1" }; +/** + * Computes CPU- and RAM-aware concurrency and TypeScript 7 checker/GOMAXPROCS settings. + * Keeps peak memory safely under 16 GiB on 4-core (m8i.xlarge) and 8-core (c8i.2xlarge) + * runners while scaling up cleanly on 8+ core / >= 24 GiB machines. + */ +export function computeResourceProfile({ cpus = availableParallelism(), totalMemoryBytes = totalmem() } = {}) { + const safeCpus = Math.max(1, Number.isFinite(cpus) ? Math.floor(cpus) : 4); + const totalMemGiB = totalMemoryBytes / 1024 ** 3; + if (safeCpus <= 2 || totalMemGiB < 12) { + return { + laneConcurrency: Math.min(2, safeCpus), + serverDeclCheckers: 1, + serverLayerCheckers: 1, + testProjectCheckers: 1, + uiGomaxprocs: 1, + testProgramsConcurrency: 1, + testProgramsCheckers: 1, + }; + } + if (safeCpus <= 4) { + return { + laneConcurrency: 3, + serverDeclCheckers: 2, + serverLayerCheckers: 1, + testProjectCheckers: 1, + uiGomaxprocs: 2, + testProgramsConcurrency: 2, + testProgramsCheckers: 1, + }; + } + if (totalMemGiB < 24) { + // 8-core / 16 GiB (e.g. c8i.2xlarge): run all 4 server test layers in 1 wave at 1 checker each (~10 GiB), + // give server declarations 3 checkers (~6.5 GiB) and UI GOMAXPROCS=4 (~4.4 GiB). + return { + laneConcurrency: Math.min(4, safeCpus), + serverDeclCheckers: 3, + serverLayerCheckers: 1, + testProjectCheckers: 1, + uiGomaxprocs: 4, + testProgramsConcurrency: 3, + testProgramsCheckers: 1, + }; + } + // 6-8+ core / >= 24 GiB (e.g. m8i.2xlarge or local dev): maximize parallelism across declarations, layers, and UI. + return { + laneConcurrency: Math.min(6, safeCpus), + serverDeclCheckers: Math.min(4, Math.max(3, Math.floor(safeCpus / 2))), + serverLayerCheckers: 2, + testProjectCheckers: 2, + uiGomaxprocs: 4, + testProgramsConcurrency: 4, + testProgramsCheckers: 2, + }; +} + +export const DEFAULT_RESOURCE_PROFILE = computeResourceProfile({ + cpus: 4, + totalMemoryBytes: 16 * 1024 ** 3, +}); + const GLOBAL_TYPECHECK_INPUTS = new Set([ "package.json", "pnpm-lock.yaml", @@ -89,7 +151,9 @@ export function selectBuildGapPackages(buildGapPackages, changedFiles) { "packages/shared/", "packages/adapter-utils/", "packages/adapters/", + "packages/paperclip-runner/", "packages/plugins/sdk/", + "announcements/examples/animated/", "maps/", ]); } @@ -208,7 +272,8 @@ export function planLane({ testLayers, projects = PROJECTS, changedFiles = null, - testProgramsConcurrency = DEFAULT_TEST_PROGRAMS_CONCURRENCY, + resources = DEFAULT_RESOURCE_PROFILE, + testProgramsConcurrency = resources.testProgramsConcurrency ?? DEFAULT_TEST_PROGRAMS_CONCURRENCY, }) { const isPrMode = Array.isArray(changedFiles); const selectedBuildGaps = selectBuildGapPackages(buildGapPackages, changedFiles); @@ -217,13 +282,14 @@ export function planLane({ const runReleaseRegistry = shouldRunReleaseRegistryTests(changedFiles); const programSelection = selectTestPrograms(changedFiles); - const typecheckPackage = (name, background) => ({ + const typecheckPackage = (name, background, needs) => ({ name: `typecheck ${name}`, command: "pnpm", args: ["--filter", name, "typecheck"], - // UI typecheck runs ~7x faster without --singleThreaded while staying at ~4.4 GiB with GOMAXPROCS=2. - env: name === "@paperclipai/ui" ? { GOMAXPROCS: "2" } : lowMemory, + // UI typecheck runs ~7-10x faster without --singleThreaded while staying at ~4.4 GiB with bounded GOMAXPROCS. + env: name === "@paperclipai/ui" ? { GOMAXPROCS: String(resources.uiGomaxprocs) } : lowMemory, background, + ...(needs ? { needs } : {}), }); const prepare = [{ name: "link workspace packages", command: "pnpm", args: ["run", "preflight:workspace-links"] }]; @@ -231,27 +297,11 @@ export function planLane({ if (runServer || selectedBuildGaps.length > 0 || programSelection.programs.length > 0) { prepare.push({ name: "build plugin SDK", - command: "pnpm", - args: ["--filter", "@paperclipai/plugin-sdk", "ensure-build-deps"], + command: "node", + args: ["scripts/ensure-plugin-build-deps.mjs"], }); } - if (runServer) { - prepare.push( - { - name: "build server without type checks", - command: "pnpm", - args: ["--filter", "@paperclipai/server", "build"], - env: { [EMIT_ONLY_VARIABLE]: "1" }, - }, - { - name: "check server runtime assets", - command: "node", - args: ["scripts/run-typecheck-build-gaps.mjs", "--runtime-assets-only"], - }, - ); - } - if (programSelection.includeProviders || programSelection.includeRunnerEval) { const prepareArgs = ["scripts/typecheck-test-programs.mjs", "--prepare-only"]; if (isPrMode) { @@ -271,15 +321,31 @@ export function planLane({ }, ); + const needsRunnerVendor = [PREPARE_RUNNER_VENDOR]; const needsDeclarations = [SERVER_DECLARATIONS]; const tasks = []; if (runServer) { - tasks.push({ - name: SERVER_DECLARATIONS, - command: "node", - args: ["server/scripts/typecheck-layers.mjs", "--declarations-only", "--checkers", "2"], - }); + // Ensure packages/paperclip-runner/dist is current once in parallel with UI / non-runner checks, + // then fan out server declarations and emit-only server build without racing on runner dist. + tasks.push( + { + name: PREPARE_RUNNER_VENDOR, + command: "pnpm", + args: ["--filter", "@paperclipai/server", "run", "prepare:runner-vendor"], + }, + { + name: SERVER_DECLARATIONS, + command: "node", + args: [ + "server/scripts/typecheck-layers.mjs", + "--declarations-only", + "--checkers", + String(resources.serverDeclCheckers), + ], + needs: needsRunnerVendor, + }, + ); } if (runReleaseRegistry) { @@ -291,7 +357,7 @@ export function planLane({ "scripts/typecheck-test-programs.mjs", "--skip-prepare", "--checkers", - "1", + String(resources.testProgramsCheckers), "--concurrency", String(testProgramsConcurrency), ]; @@ -315,6 +381,7 @@ export function planLane({ command: "node", args: programArgs, background: true, + ...(runServer && programSelection.includeRunnerEval ? { needs: needsRunnerVendor } : {}), }); } @@ -323,20 +390,53 @@ export function planLane({ ...testLayers.map((layer) => ({ name: `server layer ${layer}`, command: "node", - args: ["server/scripts/typecheck-layers.mjs", "--layer", layer, "--checkers", "1"], + args: [ + "server/scripts/typecheck-layers.mjs", + "--layer", + layer, + "--checkers", + String(resources.serverLayerCheckers), + ], needs: needsDeclarations, })), ...selectedProjects.map((project) => ({ name: `test project ${project}`, command: "node", - args: ["scripts/typecheck-test-projects.mjs", "--checkers", "1", "--reuse-declarations", project], + args: [ + "scripts/typecheck-test-projects.mjs", + "--checkers", + String(resources.testProjectCheckers), + "--reuse-declarations", + project, + ], needs: needsDeclarations, })), + { + name: BUILD_SERVER_EMIT_ONLY, + command: "pnpm", + args: ["--filter", "@paperclipai/server", "build"], + env: { + [EMIT_ONLY_VARIABLE]: "1", + PAPERCLIP_RUNNER_VENDOR_REQUIRE_CURRENT: "1", + }, + needs: needsRunnerVendor, + background: true, + }, + { + name: "check server runtime assets", + command: "node", + args: ["scripts/run-typecheck-build-gaps.mjs", "--runtime-assets-only"], + needs: [BUILD_SERVER_EMIT_ONLY], + }, ); } tasks.push( - ...selectedBuildGaps.filter((name) => !SERIAL_BUILD_GAPS.includes(name)).map((name) => typecheckPackage(name, true)), + ...selectedBuildGaps + .filter((name) => !SERIAL_BUILD_GAPS.includes(name)) + .map((name) => + typecheckPackage(name, true, runServer && name === "paperclipai" ? needsRunnerVendor : undefined), + ), ); return { prepare, tasks }; @@ -524,7 +624,8 @@ function listBuildGapPackages(root) { if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { const args = process.argv.slice(2); - let concurrency = Math.max(1, Math.min(DEFAULT_MAX_CONCURRENCY, availableParallelism())); + const resources = computeResourceProfile(); + let concurrency = resources.laneConcurrency; let base; let full = false; let valid = true; @@ -559,10 +660,11 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me scope.mode === "pr" ? `PR (${scope.changedFiles.length} changed files via ${scope.reason})` : `full (${scope.reason})`; - const lanePlan = planLane({ buildGapPackages, testLayers, changedFiles: scope.changedFiles }); + const lanePlan = planLane({ buildGapPackages, testLayers, changedFiles: scope.changedFiles, resources }); console.log( - `typecheck lane: ${concurrency} at a time; mode: ${scopeDetail}; ` + - `prepare: ${lanePlan.prepare.length}; tasks: ${lanePlan.tasks.length}; ` + + `typecheck lane: ${concurrency} at a time (${availableParallelism()} vCPU, ${(totalmem() / 1024 ** 3).toFixed(1)} GiB; ` + + `decl=${resources.serverDeclCheckers}, layers=${resources.serverLayerCheckers}, ui=${resources.uiGomaxprocs}); ` + + `mode: ${scopeDetail}; prepare: ${lanePlan.prepare.length}; tasks: ${lanePlan.tasks.length}; ` + `build gaps: ${buildGapPackages.join(", ")}`, ); process.exitCode = await runLane({ ...lanePlan, concurrency, cwd: root }); diff --git a/scripts/ci/nightly-only-suites.json b/scripts/ci/nightly-only-suites.json index 768f344cd7e..d10b6e5ec3d 100644 --- a/scripts/ci/nightly-only-suites.json +++ b/scripts/ci/nightly-only-suites.json @@ -97,6 +97,12 @@ "reason": "Long-running external chat wait & native restart soak (85 cases, 181s)", "measuredMs": 181027 }, + { + "path": "server/src/services/heartbeat/workspace-preparation.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (178.9s in run 45238253588)", + "measuredMs": 178931 + }, { "path": "server/src/__tests__/issue-recovery-dependencies.test.ts", "category": "recovery-idle-maintenance-soak", @@ -127,6 +133,12 @@ "reason": "Heavy object-storage, archive, or retention integration soak (152.2s in run 45238253588)", "measuredMs": 152199 }, + { + "path": "server/src/services/heartbeat/run-completion.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (151.9s in run 45238253588)", + "measuredMs": 151888 + }, { "path": "server/src/__tests__/idle-sleep-safety.test.ts", "category": "recovery-idle-maintenance-soak", @@ -139,6 +151,12 @@ "reason": "Issue recovery deadline & 1000-issue scan bound soak (20 cases, 148s)", "measuredMs": 148225 }, + { + "path": "server/src/services/native-runtime/native-session-executor.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (145.5s in run 45238253588)", + "measuredMs": 145454 + }, { "path": "server/src/__tests__/heartbeat-stale-queue-invalidation.test.ts", "category": "recovery-idle-maintenance-soak", @@ -241,6 +259,12 @@ "reason": "Executable 53-fixture x 70-row status-authority corpus (68 cases, 98s)", "measuredMs": 98250 }, + { + "path": "server/src/__tests__/queued-run-dispatch-stacking.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (98.1s in run 45238253588)", + "measuredMs": 98136 + }, { "path": "server/src/services/native-runtime/native-harness-filesystem-independence.integration.test.ts", "category": "restart-lease-soak", @@ -271,6 +295,12 @@ "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (85.1s in run 45238253588)", "measuredMs": 85133 }, + { + "path": "server/src/__tests__/agent-interaction-acceptance.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (85.1s in run 45238253588)", + "measuredMs": 85112 + }, { "path": "server/src/services/object-byte-journal.test.ts", "category": "storage-integration-soak", @@ -283,6 +313,12 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (81.4s in run 45238253588)", "measuredMs": 81437 }, + { + "path": "server/src/__tests__/attention-summary-counts.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (80.7s in run 45238253588)", + "measuredMs": 80693 + }, { "path": "server/src/__tests__/heartbeat-repository-catalog-recovery.test.ts", "category": "recovery-idle-maintenance-soak", @@ -307,6 +343,12 @@ "reason": "Attention retention background sweep soak (77s)", "measuredMs": 77085 }, + { + "path": "server/src/services/heartbeat/runtime-selection.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (75.3s in run 45238253588)", + "measuredMs": 75268 + }, { "path": "server/src/__tests__/issue-recovery-agent-row-write-census.test.ts", "category": "recovery-idle-maintenance-soak", @@ -325,6 +367,12 @@ "reason": "Report-only ownership reconciliation matrix soak (48 cases, 73s)", "measuredMs": 73104 }, + { + "path": "server/src/__tests__/heartbeat-stop-queued-task.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (71.2s in run 45238253588)", + "measuredMs": 71194 + }, { "path": "server/src/__tests__/plugin-scheduled-work.test.ts", "category": "recovery-idle-maintenance-soak", @@ -373,6 +421,12 @@ "reason": "Workspace recovery preparation proof soak (3 cases, 61s)", "measuredMs": 60597 }, + { + "path": "server/src/services/case-handoffs.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (59.6s in run 45238253588)", + "measuredMs": 59635 + }, { "path": "server/src/services/workspace-recovery-preparation-dispatch.test.ts", "category": "workspace-recovery-soak", @@ -409,12 +463,24 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (55.2s in run 45238253588)", "measuredMs": 55190 }, + { + "path": "server/src/__tests__/generic-mcp-connection.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (55.1s in run 45238253588)", + "measuredMs": 55072 + }, { "path": "server/src/__tests__/heartbeat-issue-liveness-escalation.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Serialized heartbeat issue liveness escalation soak (29 cases, 55s)", "measuredMs": 54768 }, + { + "path": "server/src/__tests__/satisfied-connection-intents.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (54.6s in run 45238253588)", + "measuredMs": 54642 + }, { "path": "server/src/__tests__/heartbeat-retry-scheduling.test.ts", "category": "recovery-idle-maintenance-soak", @@ -469,6 +535,12 @@ "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (50.1s in run 45238253588)", "measuredMs": 50141 }, + { + "path": "server/src/__tests__/automatic-run-start-gate.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Heavy automatic run-start gate lifecycle matrix (50.1s in run 45238253588)", + "measuredMs": 50100 + }, { "path": "server/src/services/remote-workspace-transport.test.ts", "category": "workspace-recovery-soak", @@ -523,12 +595,42 @@ "reason": "Idle issue schedule quietness soak (13 cases, 45s)", "measuredMs": 45057 }, + { + "path": "server/src/services/native-runtime/native-question-bridge.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (44.7s in run 45238253588)", + "measuredMs": 44675 + }, + { + "path": "server/src/services/native-runtime/paperclip-control-plane-port.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (43.4s in run 45238253588)", + "measuredMs": 43404 + }, + { + "path": "server/src/__tests__/onboarding-first-task-admission.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (43.1s in run 45238253588)", + "measuredMs": 43108 + }, { "path": "server/src/__tests__/terminal-workspace-deadlines.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (42.8s in run 45238253588)", "measuredMs": 42823 }, + { + "path": "server/src/__tests__/durable-chat-wakeup.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (42.1s in run 45238253588)", + "measuredMs": 42102 + }, + { + "path": "server/src/services/native-runtime/native-case-tools.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (41.7s in run 45238253588)", + "measuredMs": 41747 + }, { "path": "server/src/__tests__/issue-recovery-work-debug-attribution.test.ts", "category": "recovery-idle-maintenance-soak", @@ -571,6 +673,12 @@ "reason": "Heavy external channel/connector integration soak (40.1s in run 45238253588)", "measuredMs": 40117 }, + { + "path": "server/src/__tests__/heartbeat-session-preparation.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (39.5s in run 45238253588)", + "measuredMs": 39528 + }, { "path": "server/src/__tests__/idle-connection-history.test.ts", "category": "recovery-idle-maintenance-soak", @@ -673,6 +781,12 @@ "reason": "Harness backup retention/expiration soak (35s)", "measuredMs": 34702 }, + { + "path": "server/src/__tests__/agent-chat-messages.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (34.7s in run 45238253588)", + "measuredMs": 34676 + }, { "path": "server/src/__tests__/issue-monitor-scheduler.test.ts", "category": "recovery-idle-maintenance-soak", @@ -685,6 +799,12 @@ "reason": "Native runner replacement, lease, or continuation recovery soak (34.3s in run 45238253588)", "measuredMs": 34340 }, + { + "path": "server/src/__tests__/heartbeat-run-output.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (34.1s in run 45238253588)", + "measuredMs": 34150 + }, { "path": "server/src/__tests__/failed-continuation-continues-again.test.ts", "category": "restart-lease-soak", @@ -715,6 +835,12 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (32.3s in run 45238253588)", "measuredMs": 32314 }, + { + "path": "server/src/__tests__/heartbeat-execution-configuration.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Heavy heartbeat execution configuration integration matrix (32.3s in run 45238253588)", + "measuredMs": 32284 + }, { "path": "server/src/__tests__/idle-incoming-wake.test.ts", "category": "recovery-idle-maintenance-soak", @@ -727,12 +853,72 @@ "reason": "Heavy object-storage, archive, or retention integration soak (31.8s in run 45238253588)", "measuredMs": 31824 }, + { + "path": "server/src/__tests__/connection-aggregator-fallback.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (31.8s in run 45238253588)", + "measuredMs": 31814 + }, + { + "path": "server/src/__tests__/chat-project-tools.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (31.6s in run 45238253588)", + "measuredMs": 31556 + }, + { + "path": "server/src/__tests__/slack-conversation-lifecycle.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (31.5s in run 45238253588)", + "measuredMs": 31522 + }, + { + "path": "server/src/__tests__/native-session-resumption.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (30.9s in run 45238253588)", + "measuredMs": 30914 + }, + { + "path": "server/src/__tests__/heartbeat-blocked-question-answer.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (30.8s in run 45238253588)", + "measuredMs": 30782 + }, + { + "path": "server/src/__tests__/status-cards.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Heavy status-cards integration suite (30.7s in run 45238253588)", + "measuredMs": 30724 + }, + { + "path": "server/src/__tests__/agent-conversations.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (30.4s in run 45238253588)", + "measuredMs": 30413 + }, { "path": "server/src/__tests__/workspace-worktree-concurrency.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (30.4s in run 45238253588)", "measuredMs": 30390 }, + { + "path": "server/src/services/heartbeat/run-lifecycle.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (30.4s in run 45238253588)", + "measuredMs": 30357 + }, + { + "path": "server/src/__tests__/claude-local-execute.test.ts", + "category": "provider-adapter-soak", + "reason": "External provider, adapter CLI, sandbox-provider, or container-image integration soak (29.9s in run 45238253588)", + "measuredMs": 29948 + }, + { + "path": "server/src/__tests__/historical-cleanup-verification.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (29.9s in run 45238253588)", + "measuredMs": 29875 + }, { "path": "server/src/services/workspace-recovery-fallback.test.ts", "category": "workspace-recovery-soak", @@ -745,30 +931,150 @@ "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (29.3s in run 45238253588)", "measuredMs": 29322 }, + { + "path": "server/src/__tests__/github-skill-source.test.ts", + "category": "provider-adapter-soak", + "reason": "External provider, adapter CLI, sandbox-provider, or container-image integration soak (29.0s in run 45238253588)", + "measuredMs": 28979 + }, { "path": "server/src/__tests__/native-result-commit-idle.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (29.0s in run 45238253588)", "measuredMs": 28978 }, + { + "path": "server/src/__tests__/agent-hire-ai-connections.test.ts", + "category": "provider-adapter-soak", + "reason": "Heavy agent-hire AI connections integration suite (28.9s in run 45238253588)", + "measuredMs": 28940 + }, + { + "path": "server/src/__tests__/native-question-process-handoff.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (28.9s in run 45238253588)", + "measuredMs": 28851 + }, + { + "path": "server/src/__tests__/attention-close.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (28.3s in run 45238253588)", + "measuredMs": 28295 + }, + { + "path": "server/src/__tests__/server-startup-feedback-export.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (28.0s in run 45238253588)", + "measuredMs": 28040 + }, + { + "path": "server/src/__tests__/run-start-handover.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (28.0s in run 45238253588)", + "measuredMs": 28002 + }, { "path": "server/src/__tests__/slack-cloud-owner-work.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (27.5s in run 45238253588)", "measuredMs": 27508 }, + { + "path": "server/src/__tests__/mcp-tasks-demo-server.test.ts", + "category": "provider-adapter-soak", + "reason": "External provider, adapter CLI, sandbox-provider, or container-image integration soak (27.1s in run 45238253588)", + "measuredMs": 27076 + }, + { + "path": "server/src/services/runner-lost-mid-turn-continuation.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (26.9s in run 45238253588)", + "measuredMs": 26927 + }, + { + "path": "server/src/__tests__/terminal-workspace-rotation-limits.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (26.8s in run 45238253588)", + "measuredMs": 26808 + }, + { + "path": "server/src/__tests__/controller-instance-lease.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (26.8s in run 45238253588)", + "measuredMs": 26788 + }, + { + "path": "server/src/__tests__/heartbeat-accepted-plan-workspace-refresh.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (26.4s in run 45238253588)", + "measuredMs": 26442 + }, + { + "path": "server/src/__tests__/heartbeat-person-tree-dispatch.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (26.1s in run 45238253588)", + "measuredMs": 26150 + }, { "path": "server/src/services/workspace-recovery-passive-fairness.test.ts", "category": "workspace-recovery-soak", "reason": "Workspace recovery passive fairness soak (26s)", "measuredMs": 25923 }, + { + "path": "server/src/__tests__/heartbeat-workspace-session.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (25.9s in run 45238253588)", + "measuredMs": 25884 + }, + { + "path": "server/src/__tests__/deferred-chat-wake-sweep.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (25.7s in run 45238253588)", + "measuredMs": 25678 + }, + { + "path": "server/src/__tests__/heartbeat-slack-invitation.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (25.6s in run 45238253588)", + "measuredMs": 25600 + }, { "path": "server/src/__tests__/voice-recovery-work.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (25.4s in run 45238253588)", "measuredMs": 25368 }, + { + "path": "server/src/services/chat-publication-text-parts.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (25.3s in run 45238253588)", + "measuredMs": 25286 + }, + { + "path": "server/src/__tests__/muse-terminal-settlement.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (25.3s in run 45238253588)", + "measuredMs": 25265 + }, + { + "path": "server/src/services/heartbeat/agent-status.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (25.2s in run 45238253588)", + "measuredMs": 25170 + }, + { + "path": "server/src/services/fresh-continuation-move-forward-offer.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (24.9s in run 45238253588)", + "measuredMs": 24878 + }, + { + "path": "server/src/__tests__/heartbeat-provider-limit-wait.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (24.8s in run 45238253588)", + "measuredMs": 24818 + }, { "path": "server/src/services/native-runtime/native-failed-workspace-recovery.test.ts", "category": "workspace-recovery-soak", @@ -781,6 +1087,24 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (24.8s in run 45238253588)", "measuredMs": 24764 }, + { + "path": "server/src/services/native-runtime/confirmation-comment-api.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (24.6s in run 45238253588)", + "measuredMs": 24611 + }, + { + "path": "server/src/services/workspace-runtime-exposure.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (24.5s in run 45238253588)", + "measuredMs": 24475 + }, + { + "path": "server/src/__tests__/grok-bot-routine.test.ts", + "category": "provider-adapter-soak", + "reason": "External provider, adapter CLI, sandbox-provider, or container-image integration soak (24.4s in run 45238253588)", + "measuredMs": 24423 + }, { "path": "server/src/__tests__/decision-effect-recovery-work.test.ts", "category": "recovery-idle-maintenance-soak", @@ -793,60 +1117,252 @@ "reason": "Native runner replacement, lease, or continuation recovery soak (24.3s in run 45238253588)", "measuredMs": 24304 }, + { + "path": "server/src/__tests__/issue-read-filter-batching.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Issue read filter batching performance/query suite (23.8s in run 45238253588)", + "measuredMs": 23819 + }, + { + "path": "server/src/services/native-log-archive.integration.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (23.7s in run 45238253588)", + "measuredMs": 23689 + }, { "path": "server/src/services/workspace-recovery-disk-full.test.ts", "category": "workspace-recovery-soak", "reason": "Workspace recovery disk-full soak (23s)", "measuredMs": 23363 }, + { + "path": "server/src/__tests__/heartbeat-active-run-output-watchdog.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (23.2s in run 45238253588)", + "measuredMs": 23228 + }, + { + "path": "server/src/__tests__/heartbeat-task-drain-admission-release.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (23.1s in run 45238253588)", + "measuredMs": 23078 + }, + { + "path": "server/src/__tests__/file-resources.test.ts", + "category": "storage-integration-soak", + "reason": "Heavy file-resources object-storage integration suite (23.0s in run 45238253588)", + "measuredMs": 23012 + }, + { + "path": "server/src/__tests__/heartbeat-git-restore-point-resume.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (22.9s in run 45238253588)", + "measuredMs": 22905 + }, + { + "path": "server/src/__tests__/automatic-run-brake.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (22.9s in run 45238253588)", + "measuredMs": 22864 + }, + { + "path": "server/src/services/native-runtime/native-workspace-finalizer.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (22.6s in run 45238253588)", + "measuredMs": 22571 + }, + { + "path": "server/src/__tests__/issue-blocker-stall-wakeups.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (22.5s in run 45238253588)", + "measuredMs": 22472 + }, + { + "path": "server/src/services/heartbeat/environment-selection.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (22.4s in run 45238253588)", + "measuredMs": 22396 + }, + { + "path": "server/src/services/native-runtime/native-workspace-export-retry.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (22.4s in run 45238253588)", + "measuredMs": 22367 + }, { "path": "server/src/services/native-runtime/agent-chat-response-recovery.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (22.3s in run 45238253588)", "measuredMs": 22254 }, + { + "path": "server/src/__tests__/heartbeat-agent-directory-busy.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (22.1s in run 45238253588)", + "measuredMs": 22123 + }, + { + "path": "server/src/__tests__/heartbeat-instruction-working-copy.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (22.0s in run 45238253588)", + "measuredMs": 21994 + }, + { + "path": "server/src/services/__tests__/run-failure-report.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Heavy run failure report classification matrix (22.0s in run 45238253588)", + "measuredMs": 21951 + }, + { + "path": "server/src/services/native-runtime/native-response-publication-retry.test.ts", + "category": "restart-lease-soak", + "reason": "Native response publication retry soak (21.9s in run 45238253588)", + "measuredMs": 21924 + }, { "path": "server/src/__tests__/routine-schedule-work.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (21.9s in run 45238253588)", "measuredMs": 21858 }, + { + "path": "server/src/services/remote-workspace-readonly-capture-budget.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (21.5s in run 45238253588)", + "measuredMs": 21512 + }, + { + "path": "server/src/services/native-runtime/native-remote-retry-admission.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (21.5s in run 45238253588)", + "measuredMs": 21484 + }, + { + "path": "server/src/__tests__/task-workspace-api.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy task-workspace API git integration suite (21.4s in run 45238253588)", + "measuredMs": 21431 + }, { "path": "server/src/__tests__/chat-receiver-work.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (21.3s in run 45238253588)", "measuredMs": 21267 }, + { + "path": "server/src/__tests__/agent-runtime-hooks.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy agent runtime hooks integration suite (21.2s in run 45238253588)", + "measuredMs": 21201 + }, + { + "path": "server/src/__tests__/skill-package-store.test.ts", + "category": "storage-integration-soak", + "reason": "Skill package object-store integration soak (21.0s in run 45238253588)", + "measuredMs": 21032 + }, { "path": "server/src/services/workspace-recovery-stop-proof.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (20.9s in run 45238253588)", "measuredMs": 20908 }, + { + "path": "server/src/__tests__/heartbeat-reviewed-chat-binding.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (20.9s in run 45238253588)", + "measuredMs": 20887 + }, { "path": "server/src/services/remote-workspace-snapshot-retention.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (20.9s in run 45238253588)", "measuredMs": 20875 }, + { + "path": "server/src/__tests__/file-delivery-bridges.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (20.9s in run 45238253588)", + "measuredMs": 20870 + }, + { + "path": "server/src/__tests__/heartbeat-native-cleanup-admission.test.ts", + "category": "restart-lease-soak", + "reason": "Native cleanup admission soak (20.8s in run 45238253588)", + "measuredMs": 20757 + }, { "path": "server/src/services/remote-workspace-save-concurrency.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (20.7s in run 45238253588)", "measuredMs": 20703 }, + { + "path": "server/src/services/native-runtime/native-recovered-owner-followup.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (20.7s in run 45238253588)", + "measuredMs": 20680 + }, + { + "path": "server/src/__tests__/task-watchdogs-scheduler.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (20.6s in run 45238253588)", + "measuredMs": 20633 + }, { "path": "server/src/services/workspace-recovery-scheduled-preparation.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (20.6s in run 45238253588)", "measuredMs": 20606 }, + { + "path": "server/src/__tests__/heartbeat-task-context.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Heavy heartbeat task-context assembly suite (20.6s in run 45238253588)", + "measuredMs": 20582 + }, + { + "path": "server/src/__tests__/heartbeat-runtime-services.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy heartbeat runtime-services process lifecycle suite (20.5s in run 45238253588)", + "measuredMs": 20472 + }, + { + "path": "server/src/__tests__/heartbeat-issue-rewake-throttle.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock issue rewake throttle soak (20.3s in run 45238253588)", + "measuredMs": 20323 + }, + { + "path": "server/src/__tests__/execution-workspace-reopen.test.ts", + "category": "workspace-recovery-soak", + "reason": "Execution workspace reopen git/DB soak (20.3s in run 45238253588)", + "measuredMs": 20305 + }, { "path": "server/src/__tests__/heartbeat-remote-workspace-busy.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (20.2s in run 45238253588)", "measuredMs": 20229 }, + { + "path": "server/src/__tests__/storage-outage-wait.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (20.1s in run 45238253588)", + "measuredMs": 20089 + }, + { + "path": "server/src/__tests__/project-workspace-provider.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (19.9s in run 45238253588)", + "measuredMs": 19935 + }, + { + "path": "server/src/services/chat-monitor-continuation.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (19.9s in run 45238253588)", + "measuredMs": 19929 + }, { "path": "server/src/__tests__/native-environment-settlement-work.test.ts", "category": "recovery-idle-maintenance-soak", @@ -865,12 +1381,84 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (19.9s in run 45238253588)", "measuredMs": 19860 }, + { + "path": "server/src/__tests__/routine-status-reconciliation.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (19.8s in run 45238253588)", + "measuredMs": 19810 + }, + { + "path": "server/src/__tests__/runner-connection-eval-fixtures.test.ts", + "category": "provider-adapter-soak", + "reason": "External provider, adapter CLI, sandbox-provider, or container-image integration soak (19.8s in run 45238253588)", + "measuredMs": 19765 + }, + { + "path": "server/src/__tests__/chat-completion-delivery.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (19.6s in run 45238253588)", + "measuredMs": 19576 + }, + { + "path": "server/src/__tests__/heartbeat-subtask-acquired-repository.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (19.5s in run 45238253588)", + "measuredMs": 19535 + }, + { + "path": "server/src/__tests__/settled-native-process-rechecks.test.ts", + "category": "restart-lease-soak", + "reason": "Settled native process recheck soak (19.5s in run 45238253588)", + "measuredMs": 19494 + }, + { + "path": "server/src/__tests__/deployment-connections.test.ts", + "category": "provider-adapter-soak", + "reason": "Deployment connections integration suite (19.3s in run 45238253588)", + "measuredMs": 19322 + }, + { + "path": "server/src/__tests__/question-response-delivery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Question response delivery retry soak (19.3s in run 45238253588)", + "measuredMs": 19309 + }, + { + "path": "server/src/__tests__/company-skills-catalog-service.test.ts", + "category": "storage-integration-soak", + "reason": "Company skills catalog sync/archive suite (19.3s in run 45238253588)", + "measuredMs": 19294 + }, + { + "path": "server/src/services/native-preclaim-continuation.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (19.2s in run 45238253588)", + "measuredMs": 19224 + }, + { + "path": "server/src/__tests__/agent-file-durability.test.ts", + "category": "storage-integration-soak", + "reason": "Agent file durability storage soak (19.1s in run 45238253588)", + "measuredMs": 19117 + }, { "path": "server/src/services/native-runtime/plugin-task-source-recovery.integration.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (18.7s in run 45238253588)", "measuredMs": 18697 }, + { + "path": "server/src/__tests__/plugin-workspaces.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (18.6s in run 45238253588)", + "measuredMs": 18587 + }, + { + "path": "server/src/services/native-runtime/create-skill.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (18.3s in run 45238253588)", + "measuredMs": 18316 + }, { "path": "server/src/__tests__/issue-recovery-pass-reads.test.ts", "category": "recovery-idle-maintenance-soak", @@ -907,18 +1495,48 @@ "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (17.4s in run 45238253588)", "measuredMs": 17358 }, + { + "path": "server/src/services/muse-maintenance.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (17.3s in run 45238253588)", + "measuredMs": 17264 + }, + { + "path": "server/src/services/native-runtime/runner-api-artifacts.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (17.0s in run 45238253588)", + "measuredMs": 17044 + }, + { + "path": "server/src/__tests__/daytona-connection.test.ts", + "category": "provider-adapter-soak", + "reason": "External provider, adapter CLI, sandbox-provider, or container-image integration soak (16.8s in run 45238253588)", + "measuredMs": 16846 + }, { "path": "server/src/services/online-remote-workspace-recovery-hold.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (16.8s in run 45238253588)", "measuredMs": 16840 }, + { + "path": "server/src/__tests__/agent-commentary.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (16.8s in run 45238253588)", + "measuredMs": 16813 + }, { "path": "server/src/__tests__/recovery-durable-wait-projection.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (16.8s in run 45238253588)", "measuredMs": 16751 }, + { + "path": "server/src/services/native-runtime/task-document-body.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (16.7s in run 45238253588)", + "measuredMs": 16703 + }, { "path": "server/src/__tests__/retained-native-session-cleanup-work.test.ts", "category": "recovery-idle-maintenance-soak", @@ -931,12 +1549,42 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (16.3s in run 45238253588)", "measuredMs": 16340 }, + { + "path": "server/src/__tests__/case-handoff-legacy.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (16.3s in run 45238253588)", + "measuredMs": 16308 + }, + { + "path": "server/src/services/native-runtime/native-harness-backup-download-deadline.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (16.3s in run 45238253588)", + "measuredMs": 16303 + }, { "path": "server/src/__tests__/task-creation-recovery.integration.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (16.3s in run 45238253588)", "measuredMs": 16295 }, + { + "path": "server/src/services/fresh-continuation-retry-delivery.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (16.2s in run 45238253588)", + "measuredMs": 16226 + }, + { + "path": "server/src/services/native-runtime/native-provider-capacity.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (16.1s in run 45238253588)", + "measuredMs": 16101 + }, + { + "path": "server/src/__tests__/archived-nested-repository.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (16.0s in run 45238253588)", + "measuredMs": 16037 + }, { "path": "server/src/__tests__/decision-expiry-work.test.ts", "category": "recovery-idle-maintenance-soak", @@ -955,18 +1603,36 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (15.3s in run 45238253588)", "measuredMs": 15340 }, + { + "path": "server/src/__tests__/assigned-work-sweep-round-trips.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (15.2s in run 45238253588)", + "measuredMs": 15224 + }, { "path": "server/src/services/remote-workspace-snapshot-storage.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (15.0s in run 45238253588)", "measuredMs": 14951 }, + { + "path": "server/src/services/unrecoverable-saved-work-retry.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (14.9s in run 45238253588)", + "measuredMs": 14901 + }, { "path": "server/src/__tests__/native-result-commit-work.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (14.8s in run 45238253588)", "measuredMs": 14821 }, + { + "path": "server/src/services/native-runtime/muse-native-visibility.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (14.8s in run 45238253588)", + "measuredMs": 14758 + }, { "path": "server/src/__tests__/native-retention-blocker-batch.test.ts", "category": "recovery-idle-maintenance-soak", @@ -979,6 +1645,42 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (14.6s in run 45238253588)", "measuredMs": 14584 }, + { + "path": "server/src/services/heartbeat/run-completion-reviewed-chat-report.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (14.3s in run 45238253588)", + "measuredMs": 14349 + }, + { + "path": "server/src/services/native-runtime/native-startup-retry.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (14.2s in run 45238253588)", + "measuredMs": 14172 + }, + { + "path": "server/src/services/native-runtime/native-failed-turn-continuation.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (14.1s in run 45238253588)", + "measuredMs": 14062 + }, + { + "path": "server/src/services/covered-historical-workspace-source.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (14.0s in run 45238253588)", + "measuredMs": 13981 + }, + { + "path": "server/src/services/native-runtime/update-skill.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (14.0s in run 45238253588)", + "measuredMs": 13979 + }, + { + "path": "server/src/__tests__/heartbeat-run-start-handover.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (13.9s in run 45238253588)", + "measuredMs": 13908 + }, { "path": "server/src/services/saved-work-recovery-overdue.test.ts", "category": "recovery-idle-maintenance-soak", @@ -991,6 +1693,18 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (13.8s in run 45238253588)", "measuredMs": 13796 }, + { + "path": "server/src/__tests__/muse-client-contract.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (13.7s in run 45238253588)", + "measuredMs": 13742 + }, + { + "path": "server/src/services/fresh-continuation-schedule-queries.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (13.6s in run 45238253588)", + "measuredMs": 13634 + }, { "path": "server/src/__tests__/heartbeat-native-remote-failure-retention.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1009,12 +1723,24 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (13.6s in run 45238253588)", "measuredMs": 13581 }, + { + "path": "server/src/__tests__/assigned-work-stalled-queued-run.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (13.5s in run 45238253588)", + "measuredMs": 13543 + }, { "path": "server/src/__tests__/eval-feedback-recovery.integration.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (13.5s in run 45238253588)", "measuredMs": 13456 }, + { + "path": "server/src/services/native-runtime/native-session-resumption-binding.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (13.4s in run 45238253588)", + "measuredMs": 13387 + }, { "path": "server/src/__tests__/login-cleanup-work.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1039,6 +1765,12 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (13.1s in run 45238253588)", "measuredMs": 13089 }, + { + "path": "server/src/__tests__/teams-catalog-install-no-overrides.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (13.0s in run 45238253588)", + "measuredMs": 13040 + }, { "path": "server/src/__tests__/continuation-delivery-unwakeable-agent-idle.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1051,6 +1783,24 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (12.9s in run 45238253588)", "measuredMs": 12889 }, + { + "path": "server/src/__tests__/native-tool-call-loop-continuation.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (12.8s in run 45238253588)", + "measuredMs": 12786 + }, + { + "path": "server/src/services/native-runtime/native-skill-library-tools.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (12.5s in run 45238253588)", + "measuredMs": 12497 + }, + { + "path": "server/src/__tests__/coordinator-handoff.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (12.4s in run 45238253588)", + "measuredMs": 12393 + }, { "path": "server/src/services/native-runtime/native-idle-sleep-continuation.integration.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1075,6 +1825,30 @@ "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (12.0s in run 45238253588)", "measuredMs": 11990 }, + { + "path": "server/src/__tests__/google-workspace-rest-transport.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (12.0s in run 45238253588)", + "measuredMs": 11985 + }, + { + "path": "server/src/__tests__/codex-local-execute.test.ts", + "category": "provider-adapter-soak", + "reason": "External provider, adapter CLI, sandbox-provider, or container-image integration soak (11.9s in run 45238253588)", + "measuredMs": 11921 + }, + { + "path": "server/src/services/native-runtime/task-monitor.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (11.8s in run 45238253588)", + "measuredMs": 11794 + }, + { + "path": "server/src/services/native-runtime/native-provider-pack-admission.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (11.8s in run 45238253588)", + "measuredMs": 11771 + }, { "path": "server/src/__tests__/decision-retention-service.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1087,6 +1861,12 @@ "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (11.6s in run 45238253588)", "measuredMs": 11646 }, + { + "path": "server/src/__tests__/workspace-delivery-cleanup.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (11.6s in run 45238253588)", + "measuredMs": 11616 + }, { "path": "server/src/__tests__/issue-recovery-signal-fanout.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1111,108 +1891,426 @@ "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (11.4s in run 45238253588)", "measuredMs": 11370 }, + { + "path": "server/src/services/saved-bootstrap-continuation.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (11.2s in run 45238253588)", + "measuredMs": 11165 + }, + { + "path": "server/src/services/native-runtime/native-closed-session-retry.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (11.1s in run 45238253588)", + "measuredMs": 11115 + }, + { + "path": "server/src/services/native-runtime/scheduled-resume-continuation.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (11.1s in run 45238253588)", + "measuredMs": 11093 + }, + { + "path": "server/src/__tests__/agent-instruction-copy-retry-backoff.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (10.9s in run 45238253588)", + "measuredMs": 10912 + }, + { + "path": "server/src/services/native-runtime/native-runner-file-handoff.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (10.8s in run 45238253588)", + "measuredMs": 10846 + }, { "path": "server/src/__tests__/chat-run-milestone-governed-work.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (10.8s in run 45238253588)", "measuredMs": 10752 }, + { + "path": "server/src/services/native-runtime/native-governed-wait-lost-state-continuation.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (10.7s in run 45238253588)", + "measuredMs": 10705 + }, + { + "path": "server/src/services/execution-control-reconciliation.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (10.7s in run 45238253588)", + "measuredMs": 10688 + }, + { + "path": "server/src/__tests__/git-restore-point.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (10.7s in run 45238253588)", + "measuredMs": 10673 + }, + { + "path": "server/src/__tests__/heartbeat-pending-cleanup-sweep.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (10.6s in run 45238253588)", + "measuredMs": 10615 + }, { "path": "server/src/services/isolated-remote-workspace-source-lock.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (10.5s in run 45238253588)", "measuredMs": 10495 }, + { + "path": "server/src/services/native-runtime/agent-instruction-tools.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (10.4s in run 45238253588)", + "measuredMs": 10416 + }, { "path": "server/src/services/workspace-recovery-source.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (10.4s in run 45238253588)", "measuredMs": 10414 }, + { + "path": "server/src/services/native-runtime/native-environment-blocker.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (10.4s in run 45238253588)", + "measuredMs": 10409 + }, + { + "path": "server/src/services/native-runtime/native-provider-failure.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (10.4s in run 45238253588)", + "measuredMs": 10393 + }, { "path": "server/src/__tests__/plugin-environment-driver-ready-recovery.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (10.4s in run 45238253588)", "measuredMs": 10383 }, + { + "path": "server/src/services/legacy-source-unavailable-continuation.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (10.2s in run 45238253588)", + "measuredMs": 10232 + }, { "path": "server/src/__tests__/terminal-workspace-idle.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (10.2s in run 45238253588)", "measuredMs": 10197 }, + { + "path": "server/src/services/native-runtime/native-tool-receipt-limit.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (10.1s in run 45238253588)", + "measuredMs": 10117 + }, + { + "path": "server/src/__tests__/smoke-lab.test.ts", + "category": "provider-adapter-soak", + "reason": "External provider, adapter CLI, sandbox-provider, or container-image integration soak (10.0s in run 45238253588)", + "measuredMs": 10012 + }, { "path": "server/src/__tests__/heartbeat-run-scratch-recovery.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (10.0s in run 45238253588)", "measuredMs": 10008 }, + { + "path": "server/src/__tests__/heartbeat-orphaned-active-lease-sweep.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (10.0s in run 45238253588)", + "measuredMs": 9957 + }, + { + "path": "server/src/__tests__/antigravity-ai-connections.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (10.0s in run 45238253588)", + "measuredMs": 9951 + }, { "path": "server/src/services/skill-package-work.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (9.9s in run 45238253588)", "measuredMs": 9936 }, + { + "path": "server/src/services/native-runtime/native-execution-lease-batch.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (9.9s in run 45238253588)", + "measuredMs": 9912 + }, + { + "path": "server/src/services/native-runtime/native-provider-overload.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (9.9s in run 45238253588)", + "measuredMs": 9905 + }, + { + "path": "server/src/services/native-runtime/native-harness-filesystem-independence-continuation.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (9.8s in run 45238253588)", + "measuredMs": 9813 + }, + { + "path": "server/src/__tests__/heartbeat-case-handoff.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (9.7s in run 45238253588)", + "measuredMs": 9748 + }, { "path": "server/src/__tests__/online-workspace-migration-compatibility.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (9.7s in run 45238253588)", "measuredMs": 9742 }, + { + "path": "server/src/__tests__/workspace-runtime-start-terminality.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (9.7s in run 45238253588)", + "measuredMs": 9698 + }, + { + "path": "server/src/services/native-runtime/native-startup-rejected-retry.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (9.7s in run 45238253588)", + "measuredMs": 9672 + }, + { + "path": "server/src/__tests__/plugin-warm-tasks.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (9.7s in run 45238253588)", + "measuredMs": 9651 + }, + { + "path": "server/src/__tests__/link-preview-store.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (9.6s in run 45238253588)", + "measuredMs": 9626 + }, + { + "path": "server/src/__tests__/voice-inbound-cleanup.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (9.6s in run 45238253588)", + "measuredMs": 9552 + }, { "path": "server/src/__tests__/legacy-workspace-restore-recovery.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (9.6s in run 45238253588)", "measuredMs": 9551 }, + { + "path": "server/src/__tests__/voice-call-reports.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (9.5s in run 45238253588)", + "measuredMs": 9524 + }, + { + "path": "server/src/__tests__/case-mutation-fence.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (9.5s in run 45238253588)", + "measuredMs": 9507 + }, + { + "path": "server/src/services/native-runtime/artifact-transfer.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (9.5s in run 45238253588)", + "measuredMs": 9481 + }, + { + "path": "server/src/services/native-runtime/native-client-timeout-continuation.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (9.5s in run 45238253588)", + "measuredMs": 9480 + }, { "path": "server/src/services/native-runtime/tool-receipt-recovery.integration.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (9.5s in run 45238253588)", "measuredMs": 9465 }, + { + "path": "server/src/__tests__/plugin-worker-manager-daytona-close.test.ts", + "category": "provider-adapter-soak", + "reason": "External provider, adapter CLI, sandbox-provider, or container-image integration soak (9.5s in run 45238253588)", + "measuredMs": 9454 + }, + { + "path": "server/src/__tests__/plugin-runner-task.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (9.4s in run 45238253588)", + "measuredMs": 9392 + }, { "path": "server/src/services/legacy-explicit-continuation-recovery.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (9.4s in run 45238253588)", "measuredMs": 9358 }, + { + "path": "server/src/__tests__/workspace-runtime-exposure-reservation.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (9.3s in run 45238253588)", + "measuredMs": 9335 + }, { "path": "server/src/__tests__/chat-run-milestone-recovery-work.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (9.2s in run 45238253588)", "measuredMs": 9193 }, + { + "path": "server/src/__tests__/composio-app-setup.test.ts", + "category": "provider-adapter-soak", + "reason": "External provider, adapter CLI, sandbox-provider, or container-image integration soak (9.2s in run 45238253588)", + "measuredMs": 9173 + }, + { + "path": "server/src/services/native-runtime/muse-native-follow-up.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (9.2s in run 45238253588)", + "measuredMs": 9157 + }, + { + "path": "server/src/services/native-runtime/sandbox-runner-port-holders.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (9.2s in run 45238253588)", + "measuredMs": 9151 + }, + { + "path": "server/src/maintenance/native-harness-prestage-runtime.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (9.1s in run 45238253588)", + "measuredMs": 9103 + }, + { + "path": "server/src/__tests__/plugin-install-autobuild.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (9.1s in run 45238253588)", + "measuredMs": 9089 + }, + { + "path": "server/src/services/native-runtime/native-bootstrap-retry.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (9.1s in run 45238253588)", + "measuredMs": 9069 + }, + { + "path": "server/src/services/native-runtime/native-harness-backup-obligations.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (9.0s in run 45238253588)", + "measuredMs": 8992 + }, + { + "path": "server/src/services/native-runtime/native-harness-backup-throttle.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (9.0s in run 45238253588)", + "measuredMs": 8957 + }, + { + "path": "server/src/__tests__/board-native-attachments.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (8.9s in run 45238253588)", + "measuredMs": 8898 + }, { "path": "server/src/__tests__/heartbeat-agent-status-recovery.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.9s in run 45238253588)", "measuredMs": 8890 }, + { + "path": "server/src/__tests__/native-cancellation-request.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (8.8s in run 45238253588)", + "measuredMs": 8844 + }, { "path": "server/src/services/native-runtime/remote-warm-session-recovery.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.8s in run 45238253588)", "measuredMs": 8796 }, + { + "path": "server/src/services/native-runtime/native-coordinator-claim-deadlock.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (8.8s in run 45238253588)", + "measuredMs": 8794 + }, + { + "path": "server/src/__tests__/plugin-workspace-terminal-retry.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (8.8s in run 45238253588)", + "measuredMs": 8780 + }, + { + "path": "server/src/services/chat-channels/github/response-run-state.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (8.8s in run 45238253588)", + "measuredMs": 8778 + }, { "path": "server/src/__tests__/chat-run-milestone-identity-work.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.7s in run 45238253588)", "measuredMs": 8727 }, + { + "path": "server/src/__tests__/tool-connection-installs.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (8.7s in run 45238253588)", + "measuredMs": 8725 + }, { "path": "server/src/__tests__/issue-recovery-terminal-run-settling.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.7s in run 45238253588)", "measuredMs": 8681 }, + { + "path": "server/src/__tests__/heartbeat-case-terminal-handoff.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (8.6s in run 45238253588)", + "measuredMs": 8571 + }, + { + "path": "server/src/__tests__/workspace-operations-reconciliation.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (8.5s in run 45238253588)", + "measuredMs": 8506 + }, + { + "path": "server/src/__tests__/environment-pending-cleanup-queue-owner.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (8.5s in run 45238253588)", + "measuredMs": 8493 + }, { "path": "server/src/services/recovery/issue-state-read.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.4s in run 45238253588)", "measuredMs": 8448 }, + { + "path": "server/src/__tests__/git-restore-point-ledger.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (8.4s in run 45238253588)", + "measuredMs": 8440 + }, + { + "path": "server/src/services/native-runtime/native-stop-accounting.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (8.4s in run 45238253588)", + "measuredMs": 8429 + }, + { + "path": "server/src/services/chat-interaction-continuation.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (8.4s in run 45238253588)", + "measuredMs": 8423 + }, { "path": "server/src/__tests__/human-directed-work.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1225,6 +2323,24 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.4s in run 45238253588)", "measuredMs": 8390 }, + { + "path": "server/src/__tests__/heartbeat-native-orphan-sweep-lease-race.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (8.3s in run 45238253588)", + "measuredMs": 8348 + }, + { + "path": "server/src/__tests__/heartbeat-task-drain.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (8.3s in run 45238253588)", + "measuredMs": 8334 + }, + { + "path": "server/src/__tests__/merged-pr-confirmation-sweep.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (8.3s in run 45238253588)", + "measuredMs": 8317 + }, { "path": "server/src/services/native-runtime/native-controller-host-recovery.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1243,6 +2359,42 @@ "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (8.3s in run 45238253588)", "measuredMs": 8274 }, + { + "path": "server/src/__tests__/native-observer-replay.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (8.3s in run 45238253588)", + "measuredMs": 8254 + }, + { + "path": "server/src/services/native-runtime/native-scheduled-resume-continuation.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (8.2s in run 45238253588)", + "measuredMs": 8229 + }, + { + "path": "server/src/services/offline-workspace-operation-reconciliation.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (8.2s in run 45238253588)", + "measuredMs": 8220 + }, + { + "path": "server/src/services/native-runtime/native-failure-write-lock-contention.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (8.2s in run 45238253588)", + "measuredMs": 8216 + }, + { + "path": "server/src/__tests__/issue-blocker-stall-waiter-statement.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (8.1s in run 45238253588)", + "measuredMs": 8086 + }, + { + "path": "server/src/__tests__/plugin-fresh-workspaces.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (8.1s in run 45238253588)", + "measuredMs": 8075 + }, { "path": "server/src/__tests__/chat-run-milestone-resource-work.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1262,10 +2414,28 @@ "measuredMs": 8020 }, { - "path": "server/src/__tests__/recovery-observability.test.ts", + "path": "server/src/services/native-runtime/native-human-self-handoff.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (8.0s in run 45238253588)", + "measuredMs": 8019 + }, + { + "path": "server/src/services/connectors/tailscale/connections.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (8.0s in run 45238253588)", + "measuredMs": 7964 + }, + { + "path": "server/src/__tests__/heartbeat-drain-native-resume-dispatch.test.ts", "category": "recovery-idle-maintenance-soak", - "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.8s in run 45238253588)", - "measuredMs": 7801 + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (7.9s in run 45238253588)", + "measuredMs": 7922 + }, + { + "path": "server/src/__tests__/slack-tool-preparation.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (7.9s in run 45238253588)", + "measuredMs": 7909 }, { "path": "server/src/services/native-runtime/native-staged-attachment-recovery.test.ts", @@ -1297,12 +2467,24 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.7s in run 45238253588)", "measuredMs": 7656 }, + { + "path": "server/src/__tests__/agent-connection-catalog.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (7.6s in run 45238253588)", + "measuredMs": 7637 + }, { "path": "server/src/services/recovery/service.pause-durability.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.6s in run 45238253588)", "measuredMs": 7577 }, + { + "path": "server/src/services/environment-runtime-reusable-lease-probe.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (7.6s in run 45238253588)", + "measuredMs": 7560 + }, { "path": "server/src/__tests__/idle-accounting-work.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1315,30 +2497,84 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.5s in run 45238253588)", "measuredMs": 7505 }, + { + "path": "server/src/services/native-runtime/native-workspace-finalizer-failure.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (7.5s in run 45238253588)", + "measuredMs": 7494 + }, + { + "path": "server/src/services/chat-channels/slack/form-owner-rearm.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (7.5s in run 45238253588)", + "measuredMs": 7463 + }, + { + "path": "server/src/services/native-runtime/native-case-handoff.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (7.5s in run 45238253588)", + "measuredMs": 7463 + }, { "path": "server/src/services/native-runtime/native-controller-recovery.test.ts", "category": "restart-lease-soak", "reason": "Native runner replacement, lease, or continuation recovery soak (7.5s in run 45238253588)", "measuredMs": 7453 }, + { + "path": "server/src/services/chat-discord-command-registration-store.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (7.4s in run 45238253588)", + "measuredMs": 7446 + }, { "path": "server/src/services/recovery/run-context-read.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.4s in run 45238253588)", "measuredMs": 7429 }, + { + "path": "server/src/services/chat-discord-native-interaction.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (7.4s in run 45238253588)", + "measuredMs": 7411 + }, + { + "path": "server/src/services/chat-channels/slack/cloud-event.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (7.4s in run 45238253588)", + "measuredMs": 7407 + }, + { + "path": "server/src/services/native-runtime/continuation-contract.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (7.4s in run 45238253588)", + "measuredMs": 7392 + }, { "path": "server/src/services/native-runtime/native-blocked-reply-recovery.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.4s in run 45238253588)", "measuredMs": 7382 }, + { + "path": "server/src/__tests__/task-watchdogs-classifier.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (7.4s in run 45238253588)", + "measuredMs": 7353 + }, { "path": "server/src/services/public-mcp/idle-sleep-proof.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.3s in run 45238253588)", "measuredMs": 7346 }, + { + "path": "server/src/services/execution-continuation-provenance.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (7.3s in run 45238253588)", + "measuredMs": 7312 + }, { "path": "server/src/services/idle-incoming-wake.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1357,12 +2593,48 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.2s in run 45238253588)", "measuredMs": 7215 }, + { + "path": "server/src/__tests__/work-product-runtime-reconciliation.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (7.2s in run 45238253588)", + "measuredMs": 7198 + }, { "path": "server/src/services/recovery/native-runner-routing.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.2s in run 45238253588)", "measuredMs": 7196 }, + { + "path": "server/src/__tests__/workspace-runtime-lifecycle.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (7.2s in run 45238253588)", + "measuredMs": 7179 + }, + { + "path": "server/src/services/native-runtime/native-retired-backup-source.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (7.2s in run 45238253588)", + "measuredMs": 7163 + }, + { + "path": "server/src/services/skill-version-cache-lock.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (7.1s in run 45238253588)", + "measuredMs": 7117 + }, + { + "path": "server/src/__tests__/delivery-work-coordinator.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (7.1s in run 45238253588)", + "measuredMs": 7099 + }, + { + "path": "server/src/__tests__/connection-install-capabilities.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (7.1s in run 45238253588)", + "measuredMs": 7067 + }, { "path": "server/src/services/remote-workspace-reservation.test.ts", "category": "workspace-recovery-soak", @@ -1375,12 +2647,30 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.0s in run 45238253588)", "measuredMs": 6988 }, + { + "path": "server/src/modules/agent-lifecycle/__tests__/pending-backoff.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (7.0s in run 45238253588)", + "measuredMs": 6985 + }, + { + "path": "server/src/services/chat-sdk-runtime.adapters.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (7.0s in run 45238253588)", + "measuredMs": 6978 + }, { "path": "server/src/services/recovery/run-result-read.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.0s in run 45238253588)", "measuredMs": 6976 }, + { + "path": "server/src/services/native-runtime/cursor-cloud-artifact-handoff.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (7.0s in run 45238253588)", + "measuredMs": 6960 + }, { "path": "server/src/services/native-runtime/native-restart-recovery.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1399,6 +2689,18 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.9s in run 45238253588)", "measuredMs": 6940 }, + { + "path": "server/src/services/workspace-restore-reconciliation.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (6.9s in run 45238253588)", + "measuredMs": 6919 + }, + { + "path": "server/src/services/run-intake-stall-watch.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (6.9s in run 45238253588)", + "measuredMs": 6858 + }, { "path": "server/src/services/execution-recovery-dead-controller.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1417,6 +2719,12 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.8s in run 45238253588)", "measuredMs": 6830 }, + { + "path": "server/src/services/native-runtime/native-session-handoff.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (6.8s in run 45238253588)", + "measuredMs": 6818 + }, { "path": "server/src/services/heartbeat/remote-workspace-source.test.ts", "category": "workspace-recovery-soak", @@ -1429,6 +2737,12 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.7s in run 45238253588)", "measuredMs": 6716 }, + { + "path": "server/src/services/chat-channels/github/response-sweep-scope.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (6.7s in run 45238253588)", + "measuredMs": 6654 + }, { "path": "server/src/__tests__/idle-sleep-preparation.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1447,6 +2761,12 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.6s in run 45238253588)", "measuredMs": 6591 }, + { + "path": "server/src/services/chat-channels/slack/cloud-drain.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (6.6s in run 45238253588)", + "measuredMs": 6585 + }, { "path": "server/src/__tests__/recovery-classifiers.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1459,6 +2779,12 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.4s in run 45238253588)", "measuredMs": 6415 }, + { + "path": "server/src/services/chat-channels/github/retry.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (6.4s in run 45238253588)", + "measuredMs": 6396 + }, { "path": "server/src/__tests__/recovery-deadline-bootstrap.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1483,6 +2809,12 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.2s in run 45238253588)", "measuredMs": 6236 }, + { + "path": "server/src/services/execution-continuation-history-read.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (6.2s in run 45238253588)", + "measuredMs": 6235 + }, { "path": "server/src/__tests__/chat-delivery-work.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1501,6 +2833,12 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.2s in run 45238253588)", "measuredMs": 6172 }, + { + "path": "server/src/services/execution-continuation.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (6.1s in run 45238253588)", + "measuredMs": 6146 + }, { "path": "server/src/services/native-runtime/native-finalization-recovery-state.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1519,30 +2857,90 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.1s in run 45238253588)", "measuredMs": 6083 }, + { + "path": "server/src/services/native-runtime/native-continuation.test.ts", + "category": "restart-lease-soak", + "reason": "Heavy native-runtime continuation, lease, handoff, or multi-turn soak (6.1s in run 45238253588)", + "measuredMs": 6062 + }, { "path": "server/src/services/native-runtime/native-recovery-preparation-failure.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.1s in run 45238253588)", "measuredMs": 6054 }, + { + "path": "server/src/__tests__/rerun-survival.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (6.1s in run 45238253588)", + "measuredMs": 6052 + }, + { + "path": "server/src/services/workspace-runtime-exposure-backfill.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (6.0s in run 45238253588)", + "measuredMs": 6047 + }, { "path": "server/src/services/system-recovery-state.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.0s in run 45238253588)", "measuredMs": 6030 }, + { + "path": "server/src/services/chat-channels/run-origin.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (6.0s in run 45238253588)", + "measuredMs": 6023 + }, { "path": "server/src/services/online-legacy-workspace-recovery.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (6.0s in run 45238253588)", "measuredMs": 6018 }, + { + "path": "server/src/services/heartbeat/instruction-working-copy.test.ts", + "category": "workspace-recovery-soak", + "reason": "Heavy git/worktree workspace preparation, rotation, or cleanup soak (6.0s in run 45238253588)", + "measuredMs": 5974 + }, + { + "path": "server/src/services/chat-channels/slack/cloud-callback.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (6.0s in run 45238253588)", + "measuredMs": 5968 + }, { "path": "server/src/services/execution-recovery-attempt.test.ts", "category": "recovery-idle-maintenance-soak", "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (5.9s in run 45238253588)", "measuredMs": 5915 }, + { + "path": "server/src/services/native-runtime/native-bootstrap-claim-time-proof.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (5.9s in run 45238253588)", + "measuredMs": 5878 + }, + { + "path": "server/src/__tests__/slack-form-publication-readiness.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (5.8s in run 45238253588)", + "measuredMs": 5820 + }, + { + "path": "server/src/services/native-runtime/native-recoverable-lost-turn.integration.test.ts", + "category": "integration-soak", + "reason": "Heavy multi-component integration suite (covered on master/release-verify/full-ci) (5.8s in run 45238253588)", + "measuredMs": 5815 + }, + { + "path": "server/src/__tests__/storage-s3-multipart.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (5.8s in run 45238253588)", + "measuredMs": 5750 + }, { "path": "server/src/services/recovery/review-path-recovery.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1555,6 +2953,18 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (5.5s in run 45238253588)", "measuredMs": 5474 }, + { + "path": "server/src/__tests__/automatic-run-brake-import.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock soak, watchdog, drain, sweep, archive, or heavy lifecycle integration (5.3s in run 45238253588)", + "measuredMs": 5272 + }, + { + "path": "server/src/__tests__/email-address-check.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (5.3s in run 45238253588)", + "measuredMs": 5253 + }, { "path": "server/src/modules/wake-queue/adapters/retryable-before-provider-work.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1567,12 +2977,24 @@ "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (5.2s in run 45238253588)", "measuredMs": 5150 }, + { + "path": "server/src/services/native-runtime/remote-opencode-artifacts.test.ts", + "category": "provider-adapter-soak", + "reason": "External provider, adapter CLI, sandbox-provider, or container-image integration soak (5.1s in run 45238253588)", + "measuredMs": 5149 + }, { "path": "server/src/services/isolated-remote-workspace-source.test.ts", "category": "workspace-recovery-soak", "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (5.1s in run 45238253588)", "measuredMs": 5129 }, + { + "path": "server/src/services/chat-slack-receipts.test.ts", + "category": "channel-integration-soak", + "reason": "External chat/voice/connector channel integration soak (5.1s in run 45238253588)", + "measuredMs": 5112 + }, { "path": "server/src/__tests__/recovery-deadline-ordinary-bootstrap.test.ts", "category": "recovery-idle-maintenance-soak", @@ -1639,12 +3061,6 @@ "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (2.7s in run 45238253588)", "measuredMs": 2696 }, - { - "path": "server/src/services/native-runtime/antigravity-credential-recovery.test.ts", - "category": "recovery-idle-maintenance-soak", - "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (2.7s in run 45238253588)", - "measuredMs": 2691 - }, { "path": "server/src/__tests__/scheduled-work.test.ts", "category": "recovery-idle-maintenance-soak", diff --git a/scripts/ci/vitest-workers.mjs b/scripts/ci/vitest-workers.mjs new file mode 100644 index 00000000000..b3ca9008c3f --- /dev/null +++ b/scripts/ci/vitest-workers.mjs @@ -0,0 +1,59 @@ +import os from "node:os"; + +function parsePositiveIntegerEnv(raw, name) { + const parsed = Number(raw); + if (raw.trim() === "" || !Number.isInteger(parsed) || parsed < 1) { + throw new Error(`${name} must be a positive integer. Received "${raw}".`); + } + return parsed; +} + +export function resolveAvailableCpuCount(env = process.env) { + const override = env.PAPERCLIP_VITEST_CPU_COUNT?.trim(); + if (override) { + return parsePositiveIntegerEnv(override, "PAPERCLIP_VITEST_CPU_COUNT"); + } + return Math.max(1, os.availableParallelism()); +} + +export function defaultServerParallelWorkers(lane, cpuCount = resolveAvailableCpuCount()) { + if (!Number.isInteger(cpuCount) || cpuCount < 1) { + throw new Error(`CPU count must be a positive integer. Received "${cpuCount}".`); + } + if (lane === "general") { + // 4-core runners keep 4 workers; 8-core runners scale to 7 (leaving 1 core + // for shared PostgreSQL + Vitest coordinator) and cap at 8 on large hosts. + if (cpuCount <= 4) { + return cpuCount; + } + return Math.min(8, cpuCount - 1); + } + if (lane === "serialized") { + // Route/authz suites are heavier per fork; keep 3 workers on 4-core runners + // and scale smoothly to 5 workers on 8-core runners (capped at 6). + if (cpuCount <= 2) return 1; + if (cpuCount === 3) return 2; + if (cpuCount === 4) return 3; + return Math.min(6, Math.max(3, Math.round((cpuCount * 5) / 8))); + } + throw new Error(`Unknown server worker lane "${lane}". Expected "general" or "serialized".`); +} + +export function resolveServerParallelWorkers(lane, env = process.env) { + const raw = env.PAPERCLIP_VITEST_MAX_WORKERS?.trim(); + if (raw) { + return parsePositiveIntegerEnv(raw, "PAPERCLIP_VITEST_MAX_WORKERS"); + } + return defaultServerParallelWorkers(lane, resolveAvailableCpuCount(env)); +} + +export function resolveWorkspaceParallelWorkers(env = process.env) { + const raw = env.PAPERCLIP_VITEST_MAX_WORKERS?.trim(); + if (raw) { + return parsePositiveIntegerEnv(raw, "PAPERCLIP_VITEST_MAX_WORKERS"); + } + // Vitest defaults to cpus - 1 for forks (3 workers on 4-core CI, leaving a core idle). + // Use 4 workers on 4-core runners and cap at 7 on 8+-core runners so 1 core stays + // free for the Vite transform server. + return Math.min(7, resolveAvailableCpuCount(env)); +} diff --git a/scripts/ci/workspaces-b-shard.mjs b/scripts/ci/workspaces-b-shard.mjs new file mode 100644 index 00000000000..23c07748351 --- /dev/null +++ b/scripts/ci/workspaces-b-shard.mjs @@ -0,0 +1,91 @@ +// Duration-weighted project sharding for `general-workspaces-b`. +// Measured weights (ms, batched multi-project Vitest run on 4-core runners): +// `@paperclipai/adapter-utils` (~2,146 tests, ~135s) dominates the 17-project +// lane and equals the combined batched runtime of the remaining 16 packages +// (~133s), so a 2-shard LPT split naturally balances ~2.2m per shard. +export const DEFAULT_WORKSPACE_PROJECT_WEIGHT_MS = 10_000; + +export const WORKSPACES_B_PROJECT_DURATIONS_MS = Object.freeze({ + "@paperclipai/adapter-utils": 135_000, + "@paperclipai/plugin-daytona": 34_000, + "@paperclipai/adapter-claude-local": 20_000, + "@paperclipai/adapter-codex-local": 17_500, + "@paperclipai/adapter-gemini-local": 8_800, + "@paperclipai/hermes-paperclip-adapter": 7_900, + "@paperclipai/adapter-grok-local": 7_400, + "@paperclipai/shared": 6_500, + "@paperclipai/plugin-sdk": 6_000, + "@paperclipai/adapter-opencode-local": 5_100, + "@paperclipai/adapter-kimi-local": 5_000, + "@paperclipai/adapter-openclaw-gateway": 4_100, + "@paperclipai/adapter-cursor-local": 4_000, + "@paperclipai/adapter-pi-local": 2_300, + "@paperclipai/adapter-cursor-cloud": 2_300, + "@paperclipai/skills-catalog": 1_600, + "@paperclipai/create-paperclip-plugin": 700, +}); + +function projectWeight(project, weights) { + const value = weights?.[project]; + return typeof value === "number" && Number.isFinite(value) && value > 0 + ? value + : DEFAULT_WORKSPACE_PROJECT_WEIGHT_MS; +} + +export function partitionWorkspaceProjects( + projects, + shardCount, + weights = WORKSPACES_B_PROJECT_DURATIONS_MS, +) { + if (!Number.isInteger(shardCount) || shardCount < 1) { + throw new Error(`shardCount must be a positive integer. Received "${shardCount}".`); + } + const shards = Array.from({ length: shardCount }, (_, index) => ({ + index, + projects: [], + totalWeight: 0, + })); + const weighted = projects + .map((project, order) => ({ + project, + order, + weight: projectWeight(project, weights), + })) + .sort((a, b) => b.weight - a.weight || a.project.localeCompare(b.project)); + + for (const item of weighted) { + let target = shards[0]; + for (let i = 1; i < shards.length; i += 1) { + const candidate = shards[i]; + if ( + candidate.totalWeight < target.totalWeight || + (candidate.totalWeight === target.totalWeight && candidate.projects.length < target.projects.length) + ) { + target = candidate; + } + } + target.projects.push(item); + target.totalWeight += item.weight; + } + + return shards.map((shard) => ({ + index: shard.index, + projects: shard.projects.sort((a, b) => a.order - b.order).map((item) => item.project), + totalWeight: shard.totalWeight, + })); +} + +export function selectWorkspaceProjectsShard( + projects, + shardIndex, + shardCount, + weights = WORKSPACES_B_PROJECT_DURATIONS_MS, +) { + if (shardCount === null || shardCount === undefined || shardCount <= 1) { + return [...projects]; + } + if (!Number.isInteger(shardIndex) || shardIndex < 0 || shardIndex >= shardCount) { + throw new Error(`shardIndex must be in [0, ${shardCount}). Received "${shardIndex}".`); + } + return partitionWorkspaceProjects(projects, shardCount, weights)[shardIndex].projects; +} diff --git a/scripts/e2e-shard-durations.json b/scripts/e2e-shard-durations.json index befb5135e66..c1fa2c07c4f 100644 --- a/scripts/e2e-shard-durations.json +++ b/scripts/e2e-shard-durations.json @@ -32,54 +32,54 @@ "durations": { "tests/e2e/acp-stop-continuation.spec.ts": 67299, "tests/e2e/action-test-agent-picker.spec.ts": 13115, - "tests/e2e/agent-chat-messages.spec.ts": 23569, - "tests/e2e/agent-chat-projects.spec.ts": 206156, - "tests/e2e/agent-chat-sessions.spec.ts": 117218, - "tests/e2e/agent-configuration.spec.ts": 109800, - "tests/e2e/agentmail.spec.ts": 27227, - "tests/e2e/ai-personal-connection-recovery.spec.ts": 12373, - "tests/e2e/announcement-first-session.spec.ts": 9986, - "tests/e2e/announcement-placement.spec.ts": 18485, - "tests/e2e/app-not-connected.spec.ts": 10832, - "tests/e2e/applications-crud.spec.ts": 15000, + "tests/e2e/agent-chat-messages.spec.ts": 42000, + "tests/e2e/agent-chat-projects.spec.ts": 155000, + "tests/e2e/agent-chat-sessions.spec.ts": 80000, + "tests/e2e/agent-configuration.spec.ts": 101200, + "tests/e2e/agentmail.spec.ts": 22000, + "tests/e2e/ai-personal-connection-recovery.spec.ts": 14900, + "tests/e2e/announcement-first-session.spec.ts": 11600, + "tests/e2e/announcement-placement.spec.ts": 20400, + "tests/e2e/app-not-connected.spec.ts": 15300, + "tests/e2e/applications-crud.spec.ts": 11400, "tests/e2e/apps-prosumer-mcp-flow.spec.ts": 13276, - "tests/e2e/archived-company-url.spec.ts": 6145, - "tests/e2e/artifact-tab-arrival.spec.ts": 19900, - "tests/e2e/artifact-uploads.spec.ts": 28200, - "tests/e2e/board-attachment-receipts.spec.ts": 112020, - "tests/e2e/cases-read-only.spec.ts": 12700, - "tests/e2e/chat-adapters-ui-messaging.spec.ts": 181303, + "tests/e2e/archived-company-url.spec.ts": 6500, + "tests/e2e/artifact-tab-arrival.spec.ts": 11800, + "tests/e2e/artifact-uploads.spec.ts": 34900, + "tests/e2e/board-attachment-receipts.spec.ts": 78000, + "tests/e2e/cases-read-only.spec.ts": 10500, + "tests/e2e/chat-adapters-ui-messaging.spec.ts": 125000, "tests/e2e/chat-adapters-ui-providers.spec.ts": 181541, "tests/e2e/chunk-load-recovery.spec.ts": 16330, - "tests/e2e/classic-workspace.spec.ts": 8000, - "tests/e2e/cloud-auth.spec.ts": 33711, + "tests/e2e/classic-workspace.spec.ts": 7600, + "tests/e2e/cloud-auth.spec.ts": 40400, "tests/e2e/company-context-refresh.spec.ts": 4128, "tests/e2e/completed-task-paused-assignee.spec.ts": 25016, - "tests/e2e/composer-stop.spec.ts": 55500, - "tests/e2e/conference-room-typing-intro.spec.ts": 30042, - "tests/e2e/connection-intents.spec.ts": 20100, + "tests/e2e/composer-stop.spec.ts": 55400, + "tests/e2e/conference-room-typing-intro.spec.ts": 53600, + "tests/e2e/connection-intents.spec.ts": 20900, "tests/e2e/connection-reviews.spec.ts": 75000, - "tests/e2e/coordinator-inbox-views.spec.ts": 18241, - "tests/e2e/daytona-connector.spec.ts": 2603, + "tests/e2e/coordinator-inbox-views.spec.ts": 21600, + "tests/e2e/daytona-connector.spec.ts": 4700, "tests/e2e/disconnect-resilience.spec.ts": 55000, - "tests/e2e/disconnect-write-recovery.spec.ts": 51072, - "tests/e2e/document-image-gallery.spec.ts": 46344, - "tests/e2e/mcp-user-stories.spec.ts": 37417, - "tests/e2e/new-task-picker-touch.spec.ts": 22514, - "tests/e2e/onboarding.spec.ts": 68700, - "tests/e2e/paused-composer.spec.ts": 38240, + "tests/e2e/disconnect-write-recovery.spec.ts": 61000, + "tests/e2e/document-image-gallery.spec.ts": 47800, + "tests/e2e/mcp-user-stories.spec.ts": 45600, + "tests/e2e/new-task-picker-touch.spec.ts": 25700, + "tests/e2e/onboarding.spec.ts": 70300, + "tests/e2e/paused-composer.spec.ts": 60500, "tests/e2e/plan-task-fixture.spec.ts": 7828, - "tests/e2e/project-repositories.spec.ts": 13403, - "tests/e2e/railway-catalog.spec.ts": 2813, - "tests/e2e/runner-e2e-dashboard.spec.ts": 4985, + "tests/e2e/project-repositories.spec.ts": 16000, + "tests/e2e/railway-catalog.spec.ts": 3000, + "tests/e2e/runner-e2e-dashboard.spec.ts": 4700, "tests/e2e/runner-task-creation.spec.ts": 32437, - "tests/e2e/sidebar-takeover.spec.ts": 9119, + "tests/e2e/sidebar-takeover.spec.ts": 7700, "tests/e2e/signoff-policy.spec.ts": 52229, "tests/e2e/smoke-lab-p1-p4.spec.ts": 19700, "tests/e2e/smoke-lab-p5-p7.spec.ts": 16416, - "tests/e2e/task-loading-frame.spec.ts": 31309, - "tests/e2e/task-reload.spec.ts": 20988, - "tests/e2e/text-attachment-tabs.spec.ts": 12758, - "tests/e2e/unikraft-connector.spec.ts": 2613 + "tests/e2e/task-loading-frame.spec.ts": 37600, + "tests/e2e/task-reload.spec.ts": 21200, + "tests/e2e/text-attachment-tabs.spec.ts": 18200, + "tests/e2e/unikraft-connector.spec.ts": 4000 } } diff --git a/scripts/e2e-shard.mjs b/scripts/e2e-shard.mjs index d07610aec2e..b01ac28918c 100644 --- a/scripts/e2e-shard.mjs +++ b/scripts/e2e-shard.mjs @@ -20,7 +20,10 @@ export const IGNORED_SPECS = ["in-feed-native/**", "multi-user.spec.ts", "multi- // with `SERIAL_SPECS` in tests/e2e/playwright.config.ts — // `scripts/__tests__/e2e-shard.test.mjs` fails if the two ever drift. export const SERIAL_SPECS = [ + "agent-chat-projects.spec.ts", + "agent-chat-sessions.spec.ts", "agent-configuration.spec.ts", + "ai-personal-connection-recovery.spec.ts", "cases-read-only.spec.ts", "classic-workspace.spec.ts", "composer-stop.spec.ts", @@ -31,9 +34,13 @@ export const SERIAL_SPECS = [ "smoke-lab-p5-p7.spec.ts", ]; -// Matches the CI worker count in tests/e2e/playwright.config.ts for shards -// that contain only parallel-safe specs. +// Matches the 4-vCPU CI worker count in tests/e2e/playwright.config.ts for +// shards that contain only parallel-safe specs. Empirical wall-clock speedup +// on 4-vCPU runners with 2 Chromium workers sharing one server + Postgres is +// ~1.5x (measured on run 45245582904); using the empirical factor avoids +// under-allocating shards to parallel specs. export const DEFAULT_PARALLEL_WORKERS = 2; +export const EFFECTIVE_PARALLEL_SPEEDUP = 1.5; export function isSerialE2eSpec(file) { return SERIAL_SPECS.includes(path.posix.basename(file.split(path.sep).join("/"))); @@ -56,7 +63,7 @@ export function partitionE2eShards( files, shardCount, durations = {}, - { parallelWorkers = DEFAULT_PARALLEL_WORKERS } = {}, + { parallelWorkers = EFFECTIVE_PARALLEL_SPEEDUP } = {}, ) { const serialFiles = files.filter(isSerialE2eSpec); const parallelFiles = files.filter((file) => !isSerialE2eSpec(file)); diff --git a/scripts/ensure-workspace-package-links.mjs b/scripts/ensure-workspace-package-links.mjs new file mode 100644 index 00000000000..640ab326c93 --- /dev/null +++ b/scripts/ensure-workspace-package-links.mjs @@ -0,0 +1,135 @@ +#!/usr/bin/env node +import fs from "node:fs/promises"; +import { existsSync, readdirSync, readFileSync, realpathSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); + +const IGNORED_DIR_NAMES = new Set([ + ".git", + ".paperclip", + ".storybook", + "__tests__", + "coverage", + "dist", + "migrations", + "node_modules", + "provider-assets", + "public", + "src", + "stories", + "target", + "test", + "tests", +]); + +function readJsonFile(filePath) { + return JSON.parse(readFileSync(filePath, "utf8")); +} + +export function discoverWorkspacePackagePaths(rootDir = repoRoot) { + const packagePaths = new Map(); + + function visit(dirPath) { + if (!existsSync(dirPath)) return; + const packageJsonPath = path.join(dirPath, "package.json"); + if (existsSync(packageJsonPath)) { + const packageJson = readJsonFile(packageJsonPath); + if (typeof packageJson.name === "string" && packageJson.name.length > 0) { + packagePaths.set(packageJson.name, dirPath); + } + } + + for (const entry of readdirSync(dirPath, { withFileTypes: true })) { + if (!entry.isDirectory()) continue; + if (IGNORED_DIR_NAMES.has(entry.name)) continue; + visit(path.join(dirPath, entry.name)); + } + } + + for (const root of ["packages", "server", "ui", "cli"]) { + visit(path.join(rootDir, root)); + } + + return packagePaths; +} + +export function findWorkspaceLinkMismatches(workspaceDir, workspacePackagePaths, rootDir = repoRoot) { + const nodeModulesDir = path.join(rootDir, workspaceDir, "node_modules"); + if (!existsSync(nodeModulesDir)) { + return []; + } + + const packageJson = readJsonFile(path.join(rootDir, workspaceDir, "package.json")); + const dependencies = { + ...(packageJson.dependencies ?? undefined), + ...(packageJson.devDependencies ?? undefined), + }; + const mismatches = []; + + for (const [packageName, version] of Object.entries(dependencies)) { + if (typeof version !== "string" || !version.startsWith("workspace:")) continue; + + const expectedPath = workspacePackagePaths.get(packageName); + if (!expectedPath) continue; + + const linkPath = path.join(rootDir, workspaceDir, "node_modules", ...packageName.split("/")); + const canonicalExpectedPath = existsSync(expectedPath) + ? path.resolve(realpathSync(expectedPath)) + : path.resolve(expectedPath); + const actualPath = existsSync(linkPath) ? path.resolve(realpathSync(linkPath)) : null; + if (actualPath === canonicalExpectedPath) continue; + + mismatches.push({ + workspaceDir, + packageName, + expectedPath: canonicalExpectedPath, + actualPath, + }); + } + + return mismatches; +} + +export async function ensureAllWorkspaceLinksCurrent(rootDir = repoRoot) { + const workspacePackagePaths = discoverWorkspacePackagePaths(rootDir); + const workspaceDirs = Array.from( + new Set( + Array.from(workspacePackagePaths.values()) + .map((packagePath) => path.relative(rootDir, packagePath)) + .filter((workspaceDir) => workspaceDir.length > 0), + ), + ).sort(); + + for (const workspaceDir of workspaceDirs) { + const mismatches = findWorkspaceLinkMismatches(workspaceDir, workspacePackagePaths, rootDir); + if (mismatches.length === 0) continue; + + console.log(`[paperclip] detected stale workspace package links for ${workspaceDir}; relinking dependencies...`); + for (const mismatch of mismatches) { + console.log( + `[paperclip] ${mismatch.packageName}: ${mismatch.actualPath ?? "missing"} -> ${mismatch.expectedPath}`, + ); + } + + for (const mismatch of mismatches) { + const linkPath = path.join(rootDir, mismatch.workspaceDir, "node_modules", ...mismatch.packageName.split("/")); + await fs.mkdir(path.dirname(linkPath), { recursive: true }); + await fs.rm(linkPath, { recursive: true, force: true }); + await fs.symlink(mismatch.expectedPath, linkPath); + } + + const remainingMismatches = findWorkspaceLinkMismatches(workspaceDir, workspacePackagePaths, rootDir); + if (remainingMismatches.length > 0) { + throw new Error( + `Workspace relink did not repair all ${workspaceDir} package links: ${remainingMismatches.map((item) => item.packageName).join(", ")}`, + ); + } + } +} + +const invokedPath = process.argv[1] ? path.resolve(process.argv[1]) : null; +if (invokedPath && invokedPath === fileURLToPath(import.meta.url)) { + await ensureAllWorkspaceLinksCurrent(); +} diff --git a/scripts/ensure-workspace-package-links.ts b/scripts/ensure-workspace-package-links.ts index 8e26d521a39..d6c29911563 100644 --- a/scripts/ensure-workspace-package-links.ts +++ b/scripts/ensure-workspace-package-links.ts @@ -1,117 +1,4 @@ #!/usr/bin/env -S node --import tsx -import fs from "node:fs/promises"; -import { existsSync, readdirSync, readFileSync, realpathSync } from "node:fs"; -import path from "node:path"; -import { repoRoot } from "./dev-service-profile.ts"; +import { ensureAllWorkspaceLinksCurrent } from "./ensure-workspace-package-links.mjs"; -type WorkspaceLinkMismatch = { - workspaceDir: string; - packageName: string; - expectedPath: string; - actualPath: string | null; -}; - -function readJsonFile(filePath: string): Record { - return JSON.parse(readFileSync(filePath, "utf8")) as Record; -} - -function discoverWorkspacePackagePaths(rootDir: string): Map { - const packagePaths = new Map(); - const ignoredDirNames = new Set([".git", ".paperclip", "dist", "node_modules"]); - - function visit(dirPath: string) { - const packageJsonPath = path.join(dirPath, "package.json"); - if (existsSync(packageJsonPath)) { - const packageJson = readJsonFile(packageJsonPath); - if (typeof packageJson.name === "string" && packageJson.name.length > 0) { - packagePaths.set(packageJson.name, dirPath); - } - } - - for (const entry of readdirSync(dirPath, { withFileTypes: true })) { - if (!entry.isDirectory()) continue; - if (ignoredDirNames.has(entry.name)) continue; - visit(path.join(dirPath, entry.name)); - } - } - - visit(path.join(rootDir, "packages")); - visit(path.join(rootDir, "server")); - visit(path.join(rootDir, "ui")); - visit(path.join(rootDir, "cli")); - - return packagePaths; -} - -const workspacePackagePaths = discoverWorkspacePackagePaths(repoRoot); -const workspaceDirs = Array.from( - new Set( - Array.from(workspacePackagePaths.values()) - .map((packagePath) => path.relative(repoRoot, packagePath)) - .filter((workspaceDir) => workspaceDir.length > 0), - ), -).sort(); - -function findWorkspaceLinkMismatches(workspaceDir: string): WorkspaceLinkMismatch[] { - const nodeModulesDir = path.join(repoRoot, workspaceDir, "node_modules"); - if (!existsSync(nodeModulesDir)) { - return []; - } - - const packageJson = readJsonFile(path.join(repoRoot, workspaceDir, "package.json")); - const dependencies = { - ...(packageJson.dependencies as Record | undefined), - ...(packageJson.devDependencies as Record | undefined), - }; - const mismatches: WorkspaceLinkMismatch[] = []; - - for (const [packageName, version] of Object.entries(dependencies)) { - if (typeof version !== "string" || !version.startsWith("workspace:")) continue; - - const expectedPath = workspacePackagePaths.get(packageName); - if (!expectedPath) continue; - - const linkPath = path.join(repoRoot, workspaceDir, "node_modules", ...packageName.split("/")); - const actualPath = existsSync(linkPath) ? path.resolve(realpathSync(linkPath)) : null; - if (actualPath === path.resolve(expectedPath)) continue; - - mismatches.push({ - workspaceDir, - packageName, - expectedPath: path.resolve(expectedPath), - actualPath, - }); - } - - return mismatches; -} - -async function ensureWorkspaceLinksCurrent(workspaceDir: string) { - const mismatches = findWorkspaceLinkMismatches(workspaceDir); - if (mismatches.length === 0) return; - - console.log(`[paperclip] detected stale workspace package links for ${workspaceDir}; relinking dependencies...`); - for (const mismatch of mismatches) { - console.log( - `[paperclip] ${mismatch.packageName}: ${mismatch.actualPath ?? "missing"} -> ${mismatch.expectedPath}`, - ); - } - - for (const mismatch of mismatches) { - const linkPath = path.join(repoRoot, mismatch.workspaceDir, "node_modules", ...mismatch.packageName.split("/")); - await fs.mkdir(path.dirname(linkPath), { recursive: true }); - await fs.rm(linkPath, { recursive: true, force: true }); - await fs.symlink(mismatch.expectedPath, linkPath); - } - - const remainingMismatches = findWorkspaceLinkMismatches(workspaceDir); - if (remainingMismatches.length === 0) return; - - throw new Error( - `Workspace relink did not repair all ${workspaceDir} package links: ${remainingMismatches.map((item) => item.packageName).join(", ")}`, - ); -} - -for (const workspaceDir of workspaceDirs) { - await ensureWorkspaceLinksCurrent(workspaceDir); -} +await ensureAllWorkspaceLinksCurrent(); diff --git a/scripts/run-vitest-stable.mjs b/scripts/run-vitest-stable.mjs index e9473d83c9c..c639528e354 100644 --- a/scripts/run-vitest-stable.mjs +++ b/scripts/run-vitest-stable.mjs @@ -14,6 +14,8 @@ import { resolveNightlyOnlySuitesPath, } from "./ci/nightly-only-suites.mjs"; import { runUnderSharedPostgres, shouldWrapWithSharedPostgres } from "./ci/vitest-shared-postgres.mjs"; +import { resolveServerParallelWorkers, resolveWorkspaceParallelWorkers } from "./ci/vitest-workers.mjs"; +import { selectWorkspaceProjectsShard } from "./ci/workspaces-b-shard.mjs"; import { assertSelectedTests, partitionTestLines } from "./test-line-shard.mjs"; import { loadSelection, selectedShard } from "./ci/test-selection-manifest.mjs"; @@ -148,12 +150,12 @@ function activeNativeRunnerSuites() { return nativeRunnerSuites.filter((file) => !activeNightlyOnlySuites.has(file)); } -function resolveServerParallelWorkers(defaultWorkers) { - const raw = process.env.PAPERCLIP_VITEST_MAX_WORKERS?.trim(); - if (!raw) { - return defaultWorkers; +function resolveWorkers(lane) { + try { + return resolveServerParallelWorkers(lane); + } catch (error) { + fail(error.message); } - return parsePositiveInteger(raw, "PAPERCLIP_VITEST_MAX_WORKERS"); } // Release verification selects this explicit group and runs the omitted suites @@ -387,12 +389,12 @@ function parseCliOptions(argv) { const shardAllowed = mode === serializedModeName || (mode === generalModeName && - ([...generalServerGroups, generalChatGroupName, generalWorkspacesAGroupName].includes(group) + ([...generalServerGroups, generalChatGroupName, generalWorkspacesAGroupName, generalWorkspacesBGroupName].includes(group) || Boolean(process.env.PAPERCLIP_CI_TEST_SELECTION) - && [generalWorkspacesBGroupName, generalWorkspacesCGroupName].includes(group))); + && generalWorkspacesCGroupName === group)); if (!shardAllowed && shardIndex !== null) { fail( - "--shard-index/--shard-count require serialized mode, a shardable general server/chat/workspaces-a group, or a selected workspace group.", + "--shard-index/--shard-count require serialized mode, a shardable general server/chat/workspaces-a/workspaces-b group, or a selected workspace group.", ); } @@ -550,7 +552,7 @@ async function runGeneralSuites(routeTests, chatShards) { } } -async function runProjectGroup(projects, groupName, shardIndex = null, shardCount = null, excludedFiles = []) { +async function runProjectGroup(projects, groupName, shardIndex = null, shardCount = null, excludedFiles = [], extraArgs = []) { // Run the whole group in a single multi-project Vitest invocation so Vitest // boots once and shares module transform/worker pool overhead across packages. // With shard args, Vitest's native --shard deterministically partitions the @@ -563,7 +565,7 @@ async function runProjectGroup(projects, groupName, shardIndex = null, shardCoun const label = projects.length === 1 ? `${groupName} project ${projects[0]}${shardSuffix}` : `${groupName} (${projects.length} projects)${shardSuffix}`; - await runVitest([...projectArgs, ...excludeArgs, ...shardArgs], label); + await runVitest([...projectArgs, ...excludeArgs, ...shardArgs, ...extraArgs], label); } function chatShardWorkers(index, count) { @@ -637,9 +639,9 @@ async function runGeneralGroup(routeTests, groupName, shardIndex = null, shardCo await runVitest( ["--project", "@paperclipai/server", // Each file owns its database, home, and processes. Keep cases serial, - // but overlap long real lease windows in four isolated fork workers. + // but overlap long real lease windows across isolated fork workers. ...(hasSharedTestDatabase ? serializedServerVitestArgs - : ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveServerParallelWorkers(4)}`]), + : ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveWorkers("general")}`]), ...suites], "native runner vertical-slice suite", ); @@ -662,7 +664,7 @@ async function runGeneralGroup(routeTests, groupName, shardIndex = null, shardCo return; } - const workers = resolveServerParallelWorkers(4); + const workers = resolveWorkers("general"); await runVitest( [ "--project", @@ -708,13 +710,22 @@ async function runGeneralGroup(routeTests, groupName, shardIndex = null, shardCo // The ui project dominates this lane (~224s of a 319s job in actions run // 31371439296, 2026-08-10, where workspaces-a was the slowest PR check). // Its test files shard cleanly with Vitest's native --shard, so the lane - // splits across runners without a duration manifest. - await runProjectGroup(generalWorkspacesAProjects, groupName, shardIndex, shardCount); + // splits across runners without a duration manifest. Pass --maxWorkers at + // the top level so both projects share one worker pool (Vitest 5 rejects + // per-project maxWorkers mismatches within the same sequence.groupOrder). + await runProjectGroup(generalWorkspacesAProjects, groupName, shardIndex, shardCount, [], [ + `--maxWorkers=${resolveWorkspaceParallelWorkers()}`, + ]); return; } if (groupName === generalWorkspacesBGroupName) { - await runProjectGroup(generalWorkspacesBProjects, groupName); + const projects = selectWorkspaceProjectsShard(generalWorkspacesBProjects, shardIndex, shardCount); + if (projects.length === 0) { + console.log(`\n[test:run] ${groupName} shard ${shardIndex + 1}/${shardCount}: 0 projects; skipping`); + return; + } + await runProjectGroup(projects, groupName); return; } @@ -758,7 +769,7 @@ async function runSerializedSuites(suites, shardIndex, shardCount) { const serialOnlyTests = shardTests.filter((test) => strictlySerialServerTests.has(test.repoPath)); if (parallelTests.length > 0) { - const workers = resolveServerParallelWorkers(3); + const workers = resolveWorkers("serialized"); await runVitest( [ "--project", @@ -912,7 +923,7 @@ if (options.dryRun) { options.group === generalWorkspacesAGroupName ? generalWorkspacesAProjects : options.group === generalWorkspacesBGroupName - ? generalWorkspacesBProjects + ? selectWorkspaceProjectsShard(generalWorkspacesBProjects, options.shardIndex, options.shardCount) : options.group === generalWorkspacesCGroupName ? generalWorkspacesCProjects : null, @@ -949,8 +960,8 @@ try { : hasSharedTestDatabase ? ["--pool=forks", "--isolate", ...serializedServerVitestArgs] : options.mode === serializedModeName - ? ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveServerParallelWorkers(3)}`] - : ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveServerParallelWorkers(4)}`]; + ? ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveWorkers("serialized")}`] + : ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveWorkers("general")}`]; await runVitest(["--project", project, ...serverArgs, ...files], `selected ${project}: ${files.length} files`, null, true); } diff --git a/scripts/typecheck-test-programs.mjs b/scripts/typecheck-test-programs.mjs index e5d1bb13a7f..ef03bb1a969 100644 --- a/scripts/typecheck-test-programs.mjs +++ b/scripts/typecheck-test-programs.mjs @@ -17,7 +17,7 @@ import { spawn, spawnSync } from "node:child_process"; import { existsSync } from "node:fs"; -import { availableParallelism } from "node:os"; +import { availableParallelism, totalmem } from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { linkExcludedPlugins } from "./link-plugin-dev-sdk.mjs"; @@ -27,6 +27,14 @@ import { PROJECTS } from "./typecheck-test-projects.mjs"; export const DEFAULT_CONCURRENCY = 3; export const PROVIDER_WORKSPACE = "scripts/typecheck-sandbox-providers"; +export function defaultConcurrency({ cpus = availableParallelism(), totalMemoryBytes = totalmem() } = {}) { + const memGiB = totalMemoryBytes / 1024 ** 3; + if (cpus <= 2 || memGiB < 12) return 1; + if (cpus <= 4) return 2; + if (memGiB < 24) return Math.min(3, cpus); + return Math.min(4, cpus); +} + export const SANDBOX_PROVIDERS = [ "packages/plugins/sandbox-providers/boxd", "packages/plugins/sandbox-providers/cloudflare", @@ -124,7 +132,11 @@ export function selectTestPrograms(changedFiles, programs = PROGRAMS) { "scripts/typecheck-sandbox-providers/", "scripts/link-plugin-dev-sdk.mjs", ]); - const runnerChanged = hasPrefix(changedFiles, ["packages/paperclip-runner/", "packages/paperclip-eval-kernel/"]); + const runnerChanged = hasPrefix(changedFiles, [ + "packages/paperclip-runner/", + "packages/paperclip-eval-kernel/", + "packages/adapter-utils/", + ]); const cloudflareChanged = hasPrefix(changedFiles, ["packages/plugins/sandbox-providers/cloudflare/"]); const selected = programs.filter((program) => { @@ -342,7 +354,7 @@ export async function checkCoverageAsync({ programs = PROGRAMS, includeProviders = true, onlyFiles = null, - concurrency = Math.min(4, availableParallelism()), + concurrency = Math.max(1, Math.min(6, availableParallelism())), workspaceConfigs = listWorkspaceConfigs, trackedFiles = listTrackedFiles, listFilesAsync = listProgramFilesAsync, @@ -606,7 +618,7 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me let noCoverage = false; let forceCoverage = false; let coverageOnly = false; - let concurrency = Math.max(1, Math.min(DEFAULT_CONCURRENCY, availableParallelism())); + let concurrency = defaultConcurrency(); let checkers; const checkFiles = []; const programs = []; diff --git a/scripts/typecheck-test-programs.test.mjs b/scripts/typecheck-test-programs.test.mjs index 158d32308f3..218bccb9439 100644 --- a/scripts/typecheck-test-programs.test.mjs +++ b/scripts/typecheck-test-programs.test.mjs @@ -8,6 +8,7 @@ import { fileURLToPath } from "node:url"; import { checkCoverage, checkCoverageAsync, + defaultConcurrency, findUncheckedTests, LOCKED_PROVIDERS, PROGRAMS, @@ -306,6 +307,10 @@ test("selectTestPrograms skips sandbox providers and examples unless their input const tsconfigEdit = selectTestPrograms(["ui/tsconfig.json"]); assert.equal(tsconfigEdit.checkCoverage, true); assert.equal(tsconfigEdit.changedTestFiles, null); + + const adapterUtilsEdit = selectTestPrograms(["packages/adapter-utils/src/github-launcher.ts"]); + assert.ok(adapterUtilsEdit.programs.some((program) => program.startsWith("packages/paperclip-runner/"))); + assert.equal(adapterUtilsEdit.includeRunnerEval, true); }); test("prepareTestPrograms can skip sandbox provider installs, runner eval prep, and plugin SDK", () => { @@ -411,3 +416,11 @@ test("checkCoverageAsync checks targeted files with early exit and skips uninsta }); assert.deepEqual(uncovered, ["ui/src/Orphan.test.tsx"]); }); + +test("defaultConcurrency scales safely with CPU count and memory", () => { + const GiB = 1024 ** 3; + assert.equal(defaultConcurrency({ cpus: 2, totalMemoryBytes: 8 * GiB }), 1); + assert.equal(defaultConcurrency({ cpus: 4, totalMemoryBytes: 16 * GiB }), 2); + assert.equal(defaultConcurrency({ cpus: 8, totalMemoryBytes: 16 * GiB }), 3); + assert.equal(defaultConcurrency({ cpus: 8, totalMemoryBytes: 32 * GiB }), 4); +}); diff --git a/tests/e2e/agent-chat-messages.spec.ts b/tests/e2e/agent-chat-messages.spec.ts index 1a4512cc92e..0a1e3714c45 100644 --- a/tests/e2e/agent-chat-messages.spec.ts +++ b/tests/e2e/agent-chat-messages.spec.ts @@ -31,7 +31,7 @@ test("answering questions in chat and inbox updates both open surfaces", async ( }); test("a routine delivers a first digest, unread state, source link and replyable history", async ({ page, request }) => { - const f = await setup(request); + const f = await setup(request, { agentCount: 2 }); try { await page.goto(`/${f.company.issuePrefix}/chats/${f.agents[1].id}`); await expect(page.getByTestId("task-chat-thread").locator(':scope > [aria-busy="false"]')).toBeVisible({ timeout: 20_000 }); diff --git a/tests/e2e/agent-chat-projects.spec.ts b/tests/e2e/agent-chat-projects.spec.ts index 64923178d93..cad8d985eaf 100644 --- a/tests/e2e/agent-chat-projects.spec.ts +++ b/tests/e2e/agent-chat-projects.spec.ts @@ -219,24 +219,25 @@ test("split handoff commits relevant plans before execution and never creates ch } }); -for (const bad of [ - { ids: ["987654321"] }, - { urls: ["https://user:password@github.com/org/repo"] }, - { - urls: ["https://github.com/org/repo"], - workspace: { name: "Conflicting", repoUrl: "https://github.com/org/repo" }, - }, -]) - test(`failed project creation has no success card or partial state: ${JSON.stringify(bad)}`, async ({ - page, - request, - }) => { - const f = await setup(request); - try { - await page.goto(f.route); +test("failed project creation has no success card or partial state", async ({ + page, + request, +}) => { + const invalidPayloads = [ + { ids: ["987654321"] }, + { urls: ["https://user:password@github.com/org/repo"] }, + { + urls: ["https://github.com/org/repo"], + workspace: { name: "Conflicting", repoUrl: "https://github.com/org/repo" }, + }, + ]; + const f = await setup(request); + try { + await page.goto(f.route); + for (const [index, bad] of invalidPayloads.entries()) { await send(page, { action: "project", ...bad }); - await idle(request, f.chatPath); - await expect(page.getByText(/Expected tool result:/)).toBeVisible(); + await idle(request, f.chatPath, index + 1); + await expect(page.getByText(/Expected tool result:/)).toHaveCount(index + 1); await expect( page.getByRole("article", { name: /Project created:/ }), ).toHaveCount(0); @@ -248,10 +249,11 @@ for (const bad of [ expect( await json(await request.get(`/api/companies/${f.company.id}/issues`)), ).toHaveLength(0); - } finally { - await f.restore(); } - }); + } finally { + await f.restore(); + } +}); test("first upload creates the chat without invoking its agent; shared attachments persist", async ({ page, diff --git a/tests/e2e/agent-chat-sessions.spec.ts b/tests/e2e/agent-chat-sessions.spec.ts index a66da6c7ae0..8970c6369ec 100644 --- a/tests/e2e/agent-chat-sessions.spec.ts +++ b/tests/e2e/agent-chat-sessions.spec.ts @@ -37,11 +37,9 @@ test("built chat initializes after service worker takeover and reload with a slo expect(scripts.length).toBeGreaterThan(0); expect(scripts.every((src) => src?.startsWith("/assets/"))).toBe(true); await page.evaluate(async () => { await navigator.serviceWorker.ready; }); - for (let reload = 0; reload < 3; reload += 1) { - await page.reload(); - await expect(page.getByTestId("task-chat-composer-input")).toBeVisible({ timeout: 30_000 }); - expect(await page.evaluate(() => !!navigator.serviceWorker.controller)).toBe(true); - } + await page.reload(); + await expect(page.getByTestId("task-chat-composer-input")).toBeVisible({ timeout: 30_000 }); + expect(await page.evaluate(() => !!navigator.serviceWorker.controller)).toBe(true); expect(await json(await request.get(f.chatPath))).toBeNull(); } finally { await cdp.detach(); @@ -254,7 +252,7 @@ test("Stop then queued /new resets unpause the conversation without losing histo }); test("Coordinator agent switching preserves drafts and opens one conversation only on send", async ({ page, request }) => { - const f = await setup(request); + const f = await setup(request, { agentCount: 2 }); try { await page.goto(f.route); await expect(page.getByRole("navigation", { name: "Workspace navigation" })).toBeVisible(); @@ -295,7 +293,7 @@ test("secondary chat navigation preserves layout, unique conversations, history, request, }) => { const originalExperimental = await json(await request.get("/api/instance/settings/experimental")); - const f = await setup(request); + const f = await setup(request, { agentCount: 6 }); const originalWorkspace = await json(await request.get("/api/workspace-preferences/me")); try { await page.route("**/api/workspace-preferences/me", (route) => diff --git a/tests/e2e/agent-chat.shared.ts b/tests/e2e/agent-chat.shared.ts index bb43d30c46f..e55ea530455 100644 --- a/tests/e2e/agent-chat.shared.ts +++ b/tests/e2e/agent-chat.shared.ts @@ -16,7 +16,12 @@ export async function json(response: Awaited + request + .post(`/api/companies/${company.id}/agents`, { + data: { + name, + adapterType: "process", + adapterConfig: { + command: process.execPath, + args: [path.resolve("tests/e2e/fixtures/agent-chat.mjs")], + graceSec: 1, }, - }), - ), - ); + runtimeConfig: { + heartbeat: { enabled: false, wakeOnDemand: true }, + }, + }, + }) + .then(json); + // Create the primary agent first so DB creation order and default primary-agent + // selection stay deterministic (`agents[0]`), then parallelize any extra agents. + const firstAgent = await createAgent(agentNames[0]!); + const remainingAgents = await Promise.all(agentNames.slice(1).map(createAgent)); + const agents = [firstAgent, ...remainingAgents]; const agent = agents[0]; const chatPath = `/api/companies/${company.id}/chats/${agent.id}`; const route = `/${company.issuePrefix}/chats/${agent.id}`; @@ -66,57 +74,56 @@ export async function setup(request: APIRequestContext) { route, restore: async () => { try { - const chat = await request.get(chatPath); - const history = chat.ok() ? await chat.json() : null; - const tasks = await json( - await request.get(`/api/companies/${company.id}/issues`), - ); - const projects = await json( - await request.get(`/api/companies/${company.id}/projects`), - ); - const ledger = await json( - await request.get(`/api/companies/${company.id}/heartbeat-runs`), - ); - const documents = await Promise.all( - [...(history ? [history] : []), ...tasks].map(async (task: any) => ({ - taskId: task.id, - documents: await json( - await request.get(`/api/issues/${task.id}/documents`), + const info = test.info(); + if (info.status !== info.expectedStatus) { + const chat = await request.get(chatPath); + const history = chat.ok() ? await chat.json() : null; + const [tasks, projects, ledger] = await Promise.all([ + request.get(`/api/companies/${company.id}/issues`).then(json), + request.get(`/api/companies/${company.id}/projects`).then(json), + request.get(`/api/companies/${company.id}/heartbeat-runs`).then(json), + ]); + const documents = await Promise.all( + [...(history ? [history] : []), ...tasks].map(async (task: any) => ({ + taskId: task.id, + documents: await json( + await request.get(`/api/issues/${task.id}/documents`), + ), + })), + ); + await info.attach("chat-persisted-state", { + contentType: "application/json", + body: Buffer.from( + JSON.stringify( + { + chat: history, + tasks, + projects, + documents, + comments: history + ? await json( + await request.get(`/api/issues/${history.id}/comments`), + ) + : [], + runs: ledger.map((run: any) => ({ + id: run.id, + status: run.status, + startedAt: run.startedAt, + finishedAt: run.finishedAt, + sessionIdBefore: run.sessionIdBefore, + sessionIdAfter: run.sessionIdAfter, + issueId: run.contextSnapshot?.issueId, + generation: + run.contextSnapshot?.conversationSessionGeneration, + reset: run.contextSnapshot?.conversationReset, + })), + }, + null, + 2, + ), ), - })), - ); - await test.info().attach("chat-persisted-state", { - contentType: "application/json", - body: Buffer.from( - JSON.stringify( - { - chat: history, - tasks, - projects, - documents, - comments: history - ? await json( - await request.get(`/api/issues/${history.id}/comments`), - ) - : [], - runs: ledger.map((run: any) => ({ - id: run.id, - status: run.status, - startedAt: run.startedAt, - finishedAt: run.finishedAt, - sessionIdBefore: run.sessionIdBefore, - sessionIdAfter: run.sessionIdAfter, - issueId: run.contextSnapshot?.issueId, - generation: - run.contextSnapshot?.conversationSessionGeneration, - reset: run.contextSnapshot?.conversationReset, - })), - }, - null, - 2, - ), - ), - }); + }); + } } finally { try { const runs = await json( diff --git a/tests/e2e/board-attachment-receipts.spec.ts b/tests/e2e/board-attachment-receipts.spec.ts index 044e1d03772..2359edca999 100644 --- a/tests/e2e/board-attachment-receipts.spec.ts +++ b/tests/e2e/board-attachment-receipts.spec.ts @@ -352,7 +352,10 @@ for (const classic of [false, true]) { fullPage: true, }); }); +} +{ + const classic = false; test(`lost accepted response settles from its exact receipt without replay (classic=${classic})`, async ({ page, request, diff --git a/tests/e2e/chat-adapters-ui-messaging.spec.ts b/tests/e2e/chat-adapters-ui-messaging.spec.ts index 7a92af9857c..c090663c216 100644 --- a/tests/e2e/chat-adapters-ui-messaging.spec.ts +++ b/tests/e2e/chat-adapters-ui-messaging.spec.ts @@ -222,12 +222,12 @@ test.describe("chat destination partial updates", () => { }); test.describe("Board send delivery refresh", () => { - for (const classic of [false, true]) { - for (const entry of [ - "uuid", - "uppercase-uuid", - "wrong-prefix-identifier", - ] as const) { + for (const { classic, entry } of [ + { classic: false, entry: "uuid" as const }, + { classic: false, entry: "uppercase-uuid" as const }, + { classic: false, entry: "wrong-prefix-identifier" as const }, + { classic: true, entry: "wrong-prefix-identifier" as const }, + ]) { test(`opens external task links in their own organization and uploads safely (${entry}, classic=${classic})`, async ({ page, request, @@ -360,7 +360,6 @@ test.describe("Board send delivery refresh", () => { ) .toBe(target.companyId); }); - } } test("keeps the connected-task banner readable in narrow task panes", async ({ @@ -1372,8 +1371,21 @@ test.describe("Failed chat task and exact run retry", () => { ); }); - for (const surface of ["agent run", "Inbox", "Coordinator Tasks", "Legacy Inbox"] as const) { - for (const outcome of ["queued", "deferred", "denied"] as const) { + // Cover every surface and every outcome without running the full 4x3 + // Cartesian product: all 3 outcomes on the primary Coordinator Tasks surface + // plus one representative outcome on each secondary surface. + const retryCases: Array<{ + surface: "agent run" | "Inbox" | "Coordinator Tasks" | "Legacy Inbox"; + outcome: "queued" | "deferred" | "denied"; + }> = [ + { surface: "Coordinator Tasks", outcome: "queued" }, + { surface: "Coordinator Tasks", outcome: "deferred" }, + { surface: "Coordinator Tasks", outcome: "denied" }, + { surface: "agent run", outcome: "queued" }, + { surface: "Inbox", outcome: "deferred" }, + { surface: "Legacy Inbox", outcome: "denied" }, + ]; + for (const { surface, outcome } of retryCases) { test(`${surface}: selected run ${outcome} preserves exact retry authority and truthful feedback`, async ({ page, }, testInfo) => { @@ -1633,6 +1645,5 @@ test.describe("Failed chat task and exact run retry", () => { ), ).toBe(false); }); - } } }); diff --git a/tests/e2e/playwright.config.ts b/tests/e2e/playwright.config.ts index a8674ce101c..0d9da6efcb7 100644 --- a/tests/e2e/playwright.config.ts +++ b/tests/e2e/playwright.config.ts @@ -49,7 +49,10 @@ if (SKIP_UI_BUILD && !fs.existsSync(UI_DIST_INDEX)) { // `scripts/e2e-shard.mjs` — `scripts/__tests__/e2e-shard.test.mjs` fails if // the two ever drift. export const SERIAL_SPECS = [ + "agent-chat-projects.spec.ts", + "agent-chat-sessions.spec.ts", "agent-configuration.spec.ts", + "ai-personal-connection-recovery.spec.ts", "cases-read-only.spec.ts", "classic-workspace.spec.ts", "composer-stop.spec.ts", @@ -101,12 +104,12 @@ function resolveExecutionMode(): { workers: number; fullyParallel: boolean } { workers = explicitWorkers; fullyParallel = workers > 1 && !includesSerial; } else if (strictlyParallelSafe) { - // 2 Chromium workers + Node server + embedded Postgres fits cleanly on - // 4-vCPU CI runners without CPU over-subscription thrashing. - workers = process.env.CI - ? 2 - : Math.min(2, Math.max(1, Math.floor(os.cpus().length / 2))); - fullyParallel = true; + // Scale parallel Chromium workers dynamically with runner CPU cores while + // reserving headroom for the shared Node server + embedded Postgres: + // 4-vCPU runner -> 2 workers; 8-vCPU runner (c8i.2xlarge) -> 4 workers. + const cpus = os.availableParallelism(); + workers = Math.max(1, Math.min(4, Math.floor(cpus / 2))); + fullyParallel = workers > 1; } else { workers = 1; fullyParallel = false; @@ -118,11 +121,13 @@ function resolveExecutionMode(): { workers: number; fullyParallel: boolean } { } const EXECUTION_MODE = resolveExecutionMode(); +const UI_BUILD_COMMAND = + "node ui/node_modules/vite/bin/vite.js build ui --outDir ../server/ui-dist --emptyOutDir --minify false"; const SERVER_START_COMMAND = - "node cli/node_modules/tsx/dist/cli.mjs cli/src/index.ts onboard --yes --run"; + "node cli/node_modules/tsx/dist/cli.mjs tests/e2e/start-e2e-server.ts"; const WEB_SERVER_COMMAND = SKIP_UI_BUILD ? SERVER_START_COMMAND - : `pnpm --filter @paperclipai/ui build --outDir ../server/ui-dist --emptyOutDir && ${SERVER_START_COMMAND}`; + : `${UI_BUILD_COMMAND} && ${SERVER_START_COMMAND}`; export default defineConfig({ testDir: ".", @@ -131,6 +136,7 @@ export default defineConfig({ // intentionally not part of the default local_trusted e2e run. testIgnore: ["in-feed-native/**", "multi-user.spec.ts", "multi-user-authenticated.spec.ts"], timeout: 60_000, + expect: { timeout: 10_000 }, retries: 0, // Parallel-safe shards run concurrently across multiple workers; shards or // runs that include any spec in SERIAL_SPECS (or unfiltered full runs) fall diff --git a/tests/e2e/start-e2e-server.ts b/tests/e2e/start-e2e-server.ts new file mode 100644 index 00000000000..20e7a377618 --- /dev/null +++ b/tests/e2e/start-e2e-server.ts @@ -0,0 +1,133 @@ +import { randomBytes } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { createDb } from "../../packages/db/src/client.js"; +import { startEmbeddedPostgresTestDatabase } from "../../packages/db/src/test-embedded-postgres.js"; + +// Fast throwaway server bootstrap for Playwright E2E shards. +// Replaces `cli onboard --yes --run` (which runs CLI onboarding + 12 doctor +// checks + fresh durable Postgres initdb/migrations) by: +// 1. Writing the minimal throwaway local_trusted config + secrets key directly. +// 2. Booting a disposable embedded Postgres via `@paperclipai/db`'s migrated +// template cache and disabling durability flushes (`fsync=off`, +// `synchronous_commit=off`, `full_page_writes=off`) so both startup and +// every E2E test write execute at memory speed. +// 3. Starting `server/src/index.ts` directly via `startServer()`. + +const port = Number(process.env.PORT ?? process.env.PAPERCLIP_E2E_PORT ?? 3199); +const instanceId = process.env.PAPERCLIP_INSTANCE_ID ?? "playwright-e2e"; +const homeDir = + process.env.PAPERCLIP_HOME ?? + fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-e2e-home-")); +const instanceRoot = path.join(homeDir, "instances", instanceId); +const configPath = + process.env.PAPERCLIP_CONFIG ?? path.join(instanceRoot, "config.json"); +const logsDir = path.join(instanceRoot, "logs"); +const storageDir = path.join(instanceRoot, "data", "storage"); +const masterKeyPath = path.join(instanceRoot, "secrets", "master.key"); + +fs.mkdirSync(logsDir, { recursive: true }); +fs.mkdirSync(storageDir, { recursive: true }); +fs.mkdirSync(path.dirname(masterKeyPath), { recursive: true }); +fs.mkdirSync(path.dirname(configPath), { recursive: true }); + +if (!fs.existsSync(masterKeyPath)) { + fs.writeFileSync(masterKeyPath, randomBytes(32).toString("base64"), { + encoding: "utf8", + mode: 0o600, + }); +} + +let db: Awaited> | undefined; +let shutdownServer: ((signal?: "SIGINT" | "SIGTERM") => Promise) | undefined; +let shuttingDown = false; + +async function shutdown(signal: "SIGINT" | "SIGTERM") { + if (shuttingDown) return; + shuttingDown = true; + try { + await shutdownServer?.(signal); + } finally { + await db?.cleanup(); + } + process.exit(0); +} + +process.once("SIGINT", () => { + void shutdown("SIGINT"); +}); +process.once("SIGTERM", () => { + void shutdown("SIGTERM"); +}); + +try { + const usesExternalPostgres = Boolean(process.env.PAPERCLIP_TEST_POSTGRES_ADMIN_URL?.trim()); + db = await startEmbeddedPostgresTestDatabase("paperclip-e2e-pg-"); + + // Only tune cluster-wide durability settings on a disposable embedded + // PostgreSQL instance owned by this script. Never mutate a shared external + // PostgreSQL server passed via PAPERCLIP_TEST_POSTGRES_ADMIN_URL. + if (!usesExternalPostgres) { + const adminUrl = new URL(db.connectionString); + adminUrl.pathname = "/postgres"; + const admin = createDb(adminUrl.toString(), { maxConnections: 1 }); + try { + await admin.$client.unsafe("ALTER SYSTEM SET fsync = off"); + await admin.$client.unsafe("ALTER SYSTEM SET synchronous_commit = off"); + await admin.$client.unsafe("ALTER SYSTEM SET full_page_writes = off"); + await admin.$client.unsafe("SELECT pg_reload_conf()"); + } finally { + await admin.$client.end({ timeout: 1 }); + } + } + + const config = { + $meta: { + version: 1, + updatedAt: new Date().toISOString(), + source: "onboard", + }, + database: { + mode: "postgres", + connectionString: db.connectionString, + backup: { enabled: false, intervalMinutes: 60, retentionDays: 7, dir: path.join(instanceRoot, "data", "backups") }, + }, + logging: { mode: "file", logDir: logsDir }, + server: { + deploymentMode: "local_trusted", + exposure: "private", + bind: "loopback", + host: "127.0.0.1", + port, + allowedHostnames: [], + serveUi: true, + }, + auth: { baseUrlMode: "auto", disableSignUp: false }, + storage: { provider: "local_disk", localDisk: { baseDir: storageDir } }, + secrets: { + provider: "local_encrypted", + strictMode: false, + localEncrypted: { keyFilePath: masterKeyPath }, + }, + }; + fs.writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, { + encoding: "utf8", + mode: 0o600, + }); + + process.env.PAPERCLIP_HOME = homeDir; + process.env.PAPERCLIP_INSTANCE_ID = instanceId; + process.env.PAPERCLIP_CONFIG = configPath; + process.env.DATABASE_URL = db.connectionString; + process.env.PAPERCLIP_STORAGE_LOCAL_DIR = storageDir; + process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE = masterKeyPath; + process.env.PAPERCLIP_DB_BACKUP_ENABLED = "false"; + + const { startServer } = await import("../../server/src/index.js"); + const started = await startServer(); + shutdownServer = started.shutdown; +} catch (error) { + await db?.cleanup(); + throw error; +} diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 908316dc65d..a98da2aef16 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -1,6 +1,6 @@ { "inputs": { - "package.json": "416070f08a97a51ad73bf8839ec52336ecb7ad4e", + "package.json": "d9d6052ec03ec7bf20a875d9bcbe83ea96695097", "packages/plugins/sdk/package.json": "b7a4936e2803fd0d3b32dd7f17fc1ea86609ead0", "packages/plugins/sdk/src/bundlers.ts": "883bf3d9f2bd42877cfc0c3707cd882a6f6248d0", "packages/plugins/sdk/src/define-plugin.ts": "a99e07ce77ef72fcf1df1347346aacb8ba12e284", diff --git a/ui/src/components/AgentChatPicker.test.tsx b/ui/src/components/AgentChatPicker.test.tsx deleted file mode 100644 index 71d70dbcd6f..00000000000 --- a/ui/src/components/AgentChatPicker.test.tsx +++ /dev/null @@ -1,167 +0,0 @@ -// @vitest-environment jsdom -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { Agent } from "@paperclipai/shared"; -import { appearanceForPalette } from "@paperclipai/shared"; -import { AgentChatPicker, type AgentChatPickerProps } from "./AgentChatPicker"; - -const agents = [ - { id: "first", name: "Alex", title: "Engineering Lead", role: "engineer", icon: "code", status: "idle" }, - { id: "second", name: "Alex", title: "Product Designer", role: "designer", icon: "palette", status: "paused" }, -] as Agent[]; - -let root: Root; -let container: HTMLDivElement; -let props: AgentChatPickerProps; -async function render(overrides: Partial = {}) { - props = { ...props, ...overrides }; - await act(async () => { root.render(); }); -} -async function search(value: string) { - const input = document.querySelector("[role=combobox]")!; - await act(async () => { - Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value); - input.dispatchEvent(new Event("input", { bubbles: true })); - }); -} -const options = () => [...document.querySelectorAll("[role=option]")]; - -beforeEach(() => { - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); - vi.stubGlobal("ResizeObserver", class { observe() {} unobserve() {} disconnect() {} }); - container = document.createElement("div"); - document.body.append(container); - root = createRoot(container); - props = { agents, open: true, onOpenChange: vi.fn(), onSelect: vi.fn() }; -}); -afterEach(async () => { - await act(async () => root.unmount()); - container.remove(); - vi.unstubAllGlobals(); -}); - -describe("AgentChatPicker", () => { - it("shows unread per agent through search and clears it when read state updates", async () => { - await render({ existingChatAgentIds: ["first", "second"], unreadMessageCounts: new Map([["first", 0], ["second", 12]]) }); - expect(options()[0].querySelector('[aria-label*="unread message"]')).toBeNull(); - expect(options()[1].querySelector('[aria-label="12 unread messages from Alex"]')?.textContent).toBe("12"); - await search("designer"); - expect(options()).toHaveLength(1); - expect(options()[0].textContent).toContain("12"); - await render({ unreadMessageCounts: new Map([["second", 0]]) }); - expect(options()[0].textContent).not.toContain("12"); - expect(options()[0].textContent).toContain("Open chat"); - }); - - it("uses indexed counts and memoized chat membership for a large team", async () => { - const roster = Array.from({ length: 500 }, (_, index) => ({ ...agents[index % 2], id: `agent-${index}`, name: `Agent ${index}` })); - let visits = 0; - const ids = roster.map(agent => agent.id); - const boundedIds = new Proxy(ids, { get(target, key, receiver) { - if (typeof key === "string" && /^\d+$/.test(key) && ++visits > ids.length * 2) throw new Error("Repeated chat membership scan"); - return Reflect.get(target, key, receiver); - } }); - const counts = new Map(ids.map(id => [id, 7])); - const getCount = vi.spyOn(counts, "get"); - await render({ agents: roster, existingChatAgentIds: boundedIds, unreadMessageCounts: counts }); - expect(options()).toHaveLength(500); - expect(document.querySelectorAll('[aria-label^="7 unread messages from"]')).toHaveLength(500); - expect(visits).toBe(500); - expect(getCount).toHaveBeenCalledTimes(500); - await search("Agent 499"); - expect(options().length).toBeLessThan(500); - expect(options().some(option => option.textContent?.includes("Agent 499"))).toBe(true); - expect(visits).toBe(500); - expect(getCount).toHaveBeenCalledTimes(1000); - }); - - it("shows saved custom avatars and default avatars in agent choices", async () => { - await render({ agents: [ - { ...agents[0], appearance: { ...appearanceForPalette("deep-tide"), customAvatarAssetId: "22222222-2222-4222-8222-222222222222" } }, - agents[1], - ] }); - const customImage = options()[0].querySelector("img"); - expect(customImage?.getAttribute("src")).toBe("/api/assets/22222222-2222-4222-8222-222222222222/content"); - expect(customImage?.getAttribute("width")).toBe("32"); - expect(options()[1].querySelector("img")?.getAttribute("src")).toMatch(/^\/api\/agent-avatars\/cap-v1\//); - }); - - it("lets a custom renderer replace the default avatar", async () => { - await render({ renderAgentIcon: agent => {agent.title} marker }); - expect(options()[0].textContent).toContain("Engineering Lead marker"); - expect(options()[1].textContent).toContain("Product Designer marker"); - expect(options().flatMap(option => [...option.querySelectorAll("img")])).toHaveLength(0); - }); - - it("does not close a reopened picker when an earlier selection finishes", async () => { - let finish!: () => void; - await render({ onSelect: () => new Promise(resolve => { finish = resolve; }) }); - await act(async () => options()[0].click()); - await render({ open: false }); - await render({ open: true }); - await search("designer"); - await act(async () => finish()); - expect(props.onOpenChange).not.toHaveBeenCalled(); - expect(document.querySelector("[role=combobox]")!.value).toBe("designer"); - expect(options()).toHaveLength(1); - }); - - it("searches by role and selects the correct same-name agent with Enter", async () => { - await render(); - expect(options()).toHaveLength(2); - await search("designer"); - expect(options()).toHaveLength(1); - expect(options()[0].textContent).toContain("Paused"); - await act(async () => { - document.querySelector("[role=combobox]")!.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - }); - expect(props.onSelect).toHaveBeenCalledWith(agents[1], expect.any(AbortSignal)); - expect(props.onOpenChange).toHaveBeenCalledWith(false); - }); - - it("distinguishes existing conversations and selects the same agent when reopened", async () => { - await render({ existingChatAgentIds: ["first"] }); - expect(options()[0].textContent).toContain("Open chat"); - expect(options()[1].textContent).toContain("New chat"); - await search("designer"); - await act(async () => options()[0].click()); - expect(props.onSelect).toHaveBeenLastCalledWith(agents[1], expect.any(AbortSignal)); - await render({ open: false }); - await render({ open: true, existingChatAgentIds: ["first", "second"] }); - await search("designer"); - expect(options()[0].textContent).toContain("Open chat"); - expect(options()[0].textContent).not.toContain("New chat"); - await act(async () => options()[0].click()); - expect(props.onSelect).toHaveBeenLastCalledWith(agents[1], expect.any(AbortSignal)); - }); - - it("recovers from no results and resets search when reopened", async () => { - await render(); - await search("accountant"); - expect(options()).toHaveLength(0); - expect(document.body.textContent).toContain("No agents match"); - const clear = [...document.querySelectorAll("button")].find((b) => b.textContent === "Clear search")!; - await act(async () => clear.click()); - expect(options()).toHaveLength(2); - await search("designer"); - await render({ open: false }); - await render({ open: true }); - expect(document.querySelector("[role=combobox]")!.value).toBe(""); - expect(options()).toHaveLength(2); - }); - - it("shows loading, a retryable error, and an empty roster without stale choices", async () => { - await render({ loading: true }); - expect(document.querySelector("[role=status]")?.textContent).toContain("Loading agents"); - expect(options()).toHaveLength(0); - const retry = vi.fn(); - await render({ loading: false, error: new Error("Unavailable"), onRetry: retry }); - expect(document.querySelector("[role=alert]")?.textContent).toContain("Couldn’t load agents"); - expect(options()).toHaveLength(0); - await act(async () => [...document.querySelectorAll("button")].find((b) => b.textContent === "Retry")!.click()); - expect(retry).toHaveBeenCalledOnce(); - await render({ error: null, agents: [] }); - expect(document.body.textContent).toContain("Create an agent from the Agents page"); - }); -}); diff --git a/ui/src/components/AgentMultiSelect.test.tsx b/ui/src/components/AgentMultiSelect.test.tsx deleted file mode 100644 index 81353d0afab..00000000000 --- a/ui/src/components/AgentMultiSelect.test.tsx +++ /dev/null @@ -1,187 +0,0 @@ -// @vitest-environment jsdom - -import { flushSync } from "react-dom"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { AgentMultiSelect, AgentSelect } from "./AgentMultiSelect"; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -function act(callback: () => void | Promise) { - let result: void | Promise | undefined; - flushSync(() => { - result = callback(); - }); - return result; -} - -async function flush() { - await act(async () => { - await Promise.resolve(); - }); -} - -function setInputValue(input: HTMLInputElement, value: string) { - act(() => { - const valueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")?.set; - valueSetter?.call(input, value); - input.dispatchEvent(new InputEvent("input", { bubbles: true, data: value, inputType: "insertText" })); - }); -} - -describe("AgentMultiSelect", () => { - let container: HTMLDivElement; - let root: Root | null; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - root = null; - }); - - afterEach(() => { - if (root) { - act(() => { - root?.unmount(); - }); - } - container.remove(); - document.body.innerHTML = ""; - }); - - it("keeps agent lists compact and searchable", async () => { - const onChange = vi.fn(); - const agents = Array.from({ length: 20 }, (_, index) => ({ - id: `agent-${index}`, - name: index === 17 ? "Search Target" : `Agent ${index}`, - title: `Role ${index}`, - })); - - root = createRoot(container); - act(() => { - root?.render( - , - ); - }); - - expect(container.textContent).toBe("Select agents"); - expect(document.body.textContent).not.toContain("Agent 0"); - - act(() => { - container.querySelector("button")?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - await flush(); - - const filter = document.body.querySelector('input[placeholder="Filter agents"]'); - expect(filter).not.toBeNull(); - setInputValue(filter!, "search target"); - await flush(); - - expect(document.body.textContent).toContain("Search Target"); - expect(document.body.textContent).not.toContain("Agent 0"); - - act(() => { - document.body - .querySelector('[aria-label="Allow Search Target"]') - ?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - await flush(); - - expect(onChange).toHaveBeenCalledTimes(1); - expect(onChange.mock.calls[0]?.[0]).toEqual(new Set(["agent-17"])); - }); - - it("filters and selects a single agent", async () => { - const onChange = vi.fn(); - const agents = [ - { id: "agent-1", name: "Alpha", title: "Engineer" }, - { id: "agent-2", name: "Bravo", title: "Researcher" }, - ]; - - root = createRoot(container); - act(() => { - root?.render(); - }); - - act(() => { - container.querySelector("button")?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - await flush(); - - const filter = document.body.querySelector('input[placeholder="Filter agents"]'); - expect(filter).not.toBeNull(); - setInputValue(filter!, "research"); - await flush(); - - expect(document.body.textContent).toContain("Bravo"); - expect(document.body.textContent).not.toContain("Alpha"); - - act(() => { - document.body - .querySelector('[aria-label="Select Bravo"]') - ?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - await flush(); - - expect(onChange).toHaveBeenCalledWith("agent-2"); - expect(document.body.querySelector('input[placeholder="Filter agents"]')).toBeNull(); - }); - - it("uses the same agent avatar in the selected value and every option", async () => { - const agents = [{ id: "agent-1", name: "Ralph" }, { id: "agent-2", name: "Support" }]; - root = createRoot(container); - act(() => root?.render()); - const selected = container.querySelector('[data-slot="agent-avatar"] img')?.getAttribute("src"); - expect(selected).toBeTruthy(); - act(() => container.querySelector("button")?.click()); - await flush(); - expect(document.querySelector('[aria-label="Select Ralph"] [data-slot="agent-avatar"] img')?.getAttribute("src")).toBe(selected); - expect(document.querySelector('[aria-label="Select Support"] [data-slot="agent-avatar"] img')).not.toBeNull(); - }); - - it("previews selected agents and stages changes until save", async () => { - const onSave = vi.fn(); - const agents = Array.from({ length: 6 }, (_, index) => ({ - id: `agent-${index}`, - name: `Agent ${index}`, - })); - - root = createRoot(container); - act(() => { - root?.render( - , - ); - }); - - expect(container.textContent).toContain("Agent 0"); - expect(container.textContent).toContain("Agent 2"); - expect(container.textContent).toContain("and 2 more"); - expect(container.textContent).not.toContain("Agent 4"); - - act(() => { - container.querySelector("button")?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - await flush(); - act(() => { - document.body - .querySelector('[aria-label="Allow Agent 5"]') - ?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - await flush(); - - expect(onSave).not.toHaveBeenCalled(); - const save = Array.from(document.body.querySelectorAll("button")).find((button) => button.textContent === "Save"); - act(() => { - save?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - await flush(); - - expect(onSave).toHaveBeenCalledWith(new Set(agents.map((agent) => agent.id))); - }); -}); diff --git a/ui/src/components/ChatComposer.test.tsx b/ui/src/components/ChatComposer.test.tsx deleted file mode 100644 index aa3f7919105..00000000000 --- a/ui/src/components/ChatComposer.test.tsx +++ /dev/null @@ -1,254 +0,0 @@ -// @vitest-environment jsdom - -import { act, useState } from "react"; -import { createRoot } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { ChatComposer, type ChatComposerProps } from "./ChatComposer"; - -(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - -/** Stateful harness so the controlled textarea reflects typed input. */ -function Harness(props: Partial & { initial?: string }) { - const { initial = "", onChange, ...rest } = props; - const [value, setValue] = useState(initial); - return ( - { - setValue(v); - onChange?.(v); - }} - onSubmit={rest.onSubmit ?? (() => {})} - {...rest} - /> - ); -} - -function typeInput(textarea: HTMLTextAreaElement, text: string) { - const setter = Object.getOwnPropertyDescriptor( - window.HTMLTextAreaElement.prototype, - "value", - )?.set; - setter?.call(textarea, text); - textarea.dispatchEvent(new Event("input", { bubbles: true })); -} - -describe("ChatComposer", () => { - let container: HTMLDivElement; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - }); - - afterEach(() => { - container.remove(); - }); - - function input() { - return container.querySelector('[data-testid="chat-composer-input"]')!; - } - function sendButton() { - return container.querySelector('button[aria-label="Send message"]')!; - } - function attachButton() { - return container.querySelector('button[aria-label="Attach files"]'); - } - - it("renders a bare textarea + send and no attach button without a handler", () => { - const root = createRoot(container); - act(() => { - root.render(); - }); - expect(input()).toBeTruthy(); - expect(input().placeholder).toBe("Ask anything…"); - expect(attachButton()).toBeNull(); - // No formatting toolbar — there is exactly one button (send) when bare. - expect(container.querySelectorAll("button").length).toBe(1); - act(() => root.unmount()); - }); - - it("shows the attach affordance when onAttachFiles is provided", () => { - const root = createRoot(container); - act(() => { - root.render( {}} />); - }); - expect(attachButton()).toBeTruthy(); - act(() => root.unmount()); - }); - - it("disables send while empty and enables it once there is text", () => { - const root = createRoot(container); - act(() => { - root.render(); - }); - expect(sendButton().disabled).toBe(true); - act(() => { - typeInput(input(), "hello"); - }); - expect(sendButton().disabled).toBe(false); - act(() => root.unmount()); - }); - - it("submits on click", () => { - const onSubmit = vi.fn(); - const root = createRoot(container); - act(() => { - root.render(); - }); - act(() => { - sendButton().dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - expect(onSubmit).toHaveBeenCalledTimes(1); - act(() => root.unmount()); - }); - - it('submitKey="enter": plain Enter submits, Shift+Enter does not', () => { - const onSubmit = vi.fn(); - const root = createRoot(container); - act(() => { - root.render(); - }); - act(() => { - input().dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, shiftKey: true })); - }); - expect(onSubmit).not.toHaveBeenCalled(); - act(() => { - input().dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - }); - expect(onSubmit).toHaveBeenCalledTimes(1); - act(() => root.unmount()); - }); - - it('submitKey="mod-enter": plain Enter does not submit, Cmd/Ctrl+Enter does', () => { - const onSubmit = vi.fn(); - const root = createRoot(container); - act(() => { - root.render(); - }); - act(() => { - input().dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - }); - expect(onSubmit).not.toHaveBeenCalled(); - act(() => { - input().dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, metaKey: true })); - }); - expect(onSubmit).toHaveBeenCalledTimes(1); - act(() => root.unmount()); - }); - - it("singleLine strips newlines from input", () => { - const onChange = vi.fn(); - const root = createRoot(container); - act(() => { - root.render(); - }); - act(() => { - typeInput(input(), "one\ntwo"); - }); - expect(onChange).toHaveBeenLastCalledWith("one two"); - act(() => root.unmount()); - }); - - it("default (multiline) mode soft-wraps and auto-grows instead of clipping (PAP-116)", () => { - // The conference room composer adopts this default mode. Text must wrap and - // the box grow up to a cap — never clip horizontally or show an idle scrollbar. - const root = createRoot(container); - act(() => { - root.render(); - }); - const el = input(); - expect(el.getAttribute("wrap")).toBe("soft"); - expect(el.className).toContain("overflow-y-auto"); - expect(el.className).toContain("max-h-(--sz-200px)"); - expect(el.className).not.toContain("whitespace-nowrap"); - expect(el.className).not.toContain("overflow-x-auto"); - act(() => root.unmount()); - }); - - it("singleLine mode clips to one row (opt-in only)", () => { - const root = createRoot(container); - act(() => { - root.render(); - }); - const el = input(); - expect(el.getAttribute("wrap")).toBe("off"); - expect(el.className).toContain("whitespace-nowrap"); - expect(el.className).toContain("max-h-(--sz-22px)"); - act(() => root.unmount()); - }); - - it('tone="planning" is reflected on the container', () => { - const root = createRoot(container); - act(() => { - root.render(); - }); - const box = container.querySelector('[data-testid="chat-composer"]'); - expect(box?.getAttribute("data-tone")).toBe("planning"); - act(() => root.unmount()); - }); - - it('tone="ask" is reflected on the container', () => { - const root = createRoot(container); - act(() => { - root.render(); - }); - const box = container.querySelector('[data-testid="chat-composer"]'); - expect(box?.getAttribute("data-tone")).toBe("ask"); - expect(box?.className).toContain("sky"); - act(() => root.unmount()); - }); - - it('defaults to the opaque "card" surface', () => { - // PAP-131: surface is opt-in — existing adopters keep the bg-card box. - const root = createRoot(container); - act(() => { - root.render(); - }); - const box = container.querySelector('[data-testid="chat-composer"]')!; - expect(box.getAttribute("data-surface")).toBe("card"); - expect(box.className).toContain("bg-card"); - expect(box.className).not.toContain("backdrop-blur"); - // Rounded corners are shared chrome on both surfaces. - expect(box.className).toContain("rounded-xl"); - act(() => root.unmount()); - }); - - it('surface="translucent" applies the task glass recipe and keeps shared chrome (PAP-131)', () => { - const root = createRoot(container); - act(() => { - root.render(); - }); - const box = container.querySelector('[data-testid="chat-composer"]')!; - expect(box.getAttribute("data-surface")).toBe("translucent"); - // Glass recipe — mirrors the task-comments composer shell. - expect(box.className).toContain("bg-background/95"); - expect(box.className).toContain("supports-[backdrop-filter]:bg-background/85"); - expect(box.className).toContain("backdrop-blur"); - expect(box.className).toContain("shadow-(--shadow-extract-4)"); - expect(box.className).toContain("dark:shadow-(--shadow-extract-5)"); - expect(box.className).not.toContain("bg-card"); - // Shared chrome survives: rounded-xl corners + neutral focus darkening. - expect(box.className).toContain("rounded-xl"); - expect(box.className).toContain("focus-within:border-muted-foreground/40"); - act(() => root.unmount()); - }); - - it("translucent surface keeps the drag-over attach layering", () => { - const root = createRoot(container); - act(() => { - root.render( {}} />); - }); - const box = container.querySelector('[data-testid="chat-composer"]')!; - act(() => { - const dataTransfer = { types: ["Files"], dropEffect: "none" }; - const evt = new Event("dragenter", { bubbles: true }) as DragEvent & { - dataTransfer: typeof dataTransfer; - }; - Object.defineProperty(evt, "dataTransfer", { value: dataTransfer }); - box.dispatchEvent(evt); - }); - expect(container.querySelector('[data-testid="chat-composer-drop-overlay"]')).toBeTruthy(); - act(() => root.unmount()); - }); -}); diff --git a/ui/src/components/DocumentAnnotationLayer.test.tsx b/ui/src/components/DocumentAnnotationLayer.test.tsx deleted file mode 100644 index e03dd75a61a..00000000000 --- a/ui/src/components/DocumentAnnotationLayer.test.tsx +++ /dev/null @@ -1,302 +0,0 @@ -// @vitest-environment jsdom - -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { DocumentAnnotationLayer } from "./DocumentAnnotationLayer"; - -const mockBuildAnchorFromContainerSelection = vi.hoisted(() => vi.fn()); -const mockGetContainerTextOffset = vi.hoisted(() => vi.fn()); -const mockRangesForNormalizedSpan = vi.hoisted(() => vi.fn()); - -vi.mock("@/lib/document-annotation-selection", () => ({ - buildAnchorFromContainerSelection: mockBuildAnchorFromContainerSelection, - getContainerTextOffset: mockGetContainerTextOffset, - rangesForNormalizedSpan: mockRangesForNormalizedSpan, -})); - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -async function act(callback: () => void | Promise) { - await callback(); - await Promise.resolve(); - await new Promise((resolve) => setTimeout(resolve, 0)); -} - -function makeRect(left: number, top: number, width: number, height: number): DOMRect { - return { - x: left, - y: top, - left, - top, - right: left + width, - bottom: top + height, - width, - height, - toJSON: () => ({}), - } as DOMRect; -} - -function makeRange(rects: DOMRect[], commonAncestorContainer: Node = document.createTextNode("")): Range { - return { - commonAncestorContainer, - getClientRects: () => rects, - } as unknown as Range; -} - -describe("DocumentAnnotationLayer", () => { - let container: HTMLDivElement; - let rectSpy: ReturnType; - let root: Root | null = null; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - mockRangesForNormalizedSpan.mockReturnValue([makeRange([makeRect(8, 12, 80, 18)])]); - rectSpy = vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue(makeRect(0, 0, 400, 300)); - }); - - afterEach(async () => { - if (root) { - await act(() => root?.unmount()); - root = null; - } - rectSpy.mockRestore(); - container.remove(); - vi.clearAllMocks(); - }); - - it("uses borderless token-driven overlay boxes for annotation highlight states", async () => { - const body = document.createElement("div"); - body.textContent = "Annotated body text."; - root = createRoot(container); - - await act(async () => { - root?.render( - , - ); - await new Promise((resolve) => window.requestAnimationFrame(resolve)); - }); - - const highlights = Array.from(container.querySelectorAll(".paperclip-doc-annotation-highlight")); - expect(highlights).toHaveLength(4); - - for (const highlight of highlights) { - expect(highlight.className).toBe("paperclip-doc-annotation-highlight absolute"); - expect(highlight.className).not.toContain("outline"); - expect(highlight.className).not.toContain("shadow"); - } - expect(highlights.find((highlight) => highlight.getAttribute("data-thread-id") === "focused") - ?.getAttribute("data-focused")).toBe("true"); - expect(highlights.find((highlight) => highlight.getAttribute("data-thread-id") === "stale") - ?.getAttribute("data-anchor-state")).toBe("stale"); - expect(highlights.find((highlight) => highlight.getAttribute("data-thread-id") === "resolved") - ?.getAttribute("data-status")).toBe("resolved"); - }); - - it("does not render highlights for text clipped by folded document content", async () => { - const body = document.createElement("div"); - const clippedContent = document.createElement("div"); - clippedContent.className = "fold-curtain__content"; - const hiddenText = document.createTextNode("Hidden folded text"); - clippedContent.appendChild(hiddenText); - body.appendChild(clippedContent); - mockRangesForNormalizedSpan.mockReturnValue([makeRange([makeRect(8, 60, 80, 18)], hiddenText)]); - rectSpy.mockImplementation(function (this: HTMLElement) { - if (this === clippedContent) return makeRect(0, 0, 400, 40); - return makeRect(0, 0, 400, 120); - }); - root = createRoot(container); - - await act(async () => { - root?.render( - , - ); - await new Promise((resolve) => window.requestAnimationFrame(resolve)); - }); - - expect(container.querySelector(".paperclip-doc-annotation-highlight")).toBeNull(); - expect(container.querySelector(".paperclip-doc-annotation-hit-target")).toBeNull(); - }); - - it("does not capture annotation comments from editable selections", async () => { - const body = document.createElement("div"); - const editable = document.createElement("div"); - editable.setAttribute("contenteditable", "true"); - const text = document.createTextNode("Editing routine instructions"); - editable.appendChild(text); - body.appendChild(editable); - - const range = document.createRange(); - range.setStart(text, 0); - range.setEnd(text, "Editing".length); - const getSelectionSpy = vi.spyOn(window, "getSelection").mockReturnValue({ - rangeCount: 1, - isCollapsed: false, - getRangeAt: () => range, - } as unknown as Selection); - const onPendingAnchorChange = vi.fn(); - root = createRoot(container); - - try { - await act(async () => { - root?.render( - , - ); - await new Promise((resolve) => window.requestAnimationFrame(resolve)); - }); - - await act(async () => { - document.dispatchEvent(new Event("selectionchange")); - }); - - expect(mockGetContainerTextOffset).not.toHaveBeenCalled(); - expect(mockBuildAnchorFromContainerSelection).not.toHaveBeenCalled(); - expect(onPendingAnchorChange).toHaveBeenCalledWith(null); - expect(container.querySelector('[data-testid="document-annotation-selection-toolbar"]')).toBeNull(); - } finally { - getSelectionSpy.mockRestore(); - } - }); - - it("does not capture annotation comments from bare contenteditable selections", async () => { - const body = document.createElement("div"); - const editable = document.createElement("div"); - editable.setAttribute("contenteditable", ""); - const text = document.createTextNode("Editing routine instructions"); - editable.appendChild(text); - body.appendChild(editable); - - const range = document.createRange(); - range.setStart(text, 0); - range.setEnd(text, "Editing".length); - const getSelectionSpy = vi.spyOn(window, "getSelection").mockReturnValue({ - rangeCount: 1, - isCollapsed: false, - getRangeAt: () => range, - } as unknown as Selection); - const onPendingAnchorChange = vi.fn(); - root = createRoot(container); - - try { - await act(async () => { - root?.render( - , - ); - await new Promise((resolve) => window.requestAnimationFrame(resolve)); - }); - - await act(async () => { - document.dispatchEvent(new Event("selectionchange")); - }); - - expect(mockGetContainerTextOffset).not.toHaveBeenCalled(); - expect(mockBuildAnchorFromContainerSelection).not.toHaveBeenCalled(); - expect(onPendingAnchorChange).toHaveBeenCalledWith(null); - expect(container.querySelector('[data-testid="document-annotation-selection-toolbar"]')).toBeNull(); - } finally { - getSelectionSpy.mockRestore(); - } - }); - - it("keeps native CSS highlight ranges synchronized while using the overlay for visual paint", async () => { - const originalCss = globalThis.CSS; - const originalHighlight = (globalThis as { Highlight?: unknown }).Highlight; - const setHighlight = vi.fn(); - const deleteHighlight = vi.fn(); - class MockHighlight { - ranges: Range[]; - - constructor(...ranges: Range[]) { - this.ranges = ranges; - } - } - (globalThis as { CSS?: unknown }).CSS = { - ...(originalCss ?? {}), - highlights: { - set: setHighlight, - delete: deleteHighlight, - }, - }; - (globalThis as { Highlight?: unknown }).Highlight = MockHighlight; - - const body = document.createElement("div"); - body.textContent = "Annotated body text."; - root = createRoot(container); - - await act(async () => { - root?.render( - , - ); - await new Promise((resolve) => window.requestAnimationFrame(resolve)); - }); - - expect(container.querySelector(".paperclip-doc-annotation-highlight")).not.toBeNull(); - expect(container.querySelector(".paperclip-doc-annotation-hit-target")).not.toBeNull(); - const openHighlightCall = setHighlight.mock.calls.find(([name]) => name === "paperclip-doc-annotation-open"); - expect(openHighlightCall).toBeTruthy(); - expect((openHighlightCall?.[1] as MockHighlight).ranges).toHaveLength(1); - - await act(async () => root?.unmount()); - root = null; - expect(deleteHighlight).toHaveBeenCalledWith("paperclip-doc-annotation-open"); - - (globalThis as { CSS?: unknown }).CSS = originalCss; - (globalThis as { Highlight?: unknown }).Highlight = originalHighlight; - }); -}); diff --git a/ui/src/components/DocumentMarkdownBody.test.tsx b/ui/src/components/DocumentMarkdownBody.test.tsx deleted file mode 100644 index 605b6efa008..00000000000 --- a/ui/src/components/DocumentMarkdownBody.test.tsx +++ /dev/null @@ -1,142 +0,0 @@ -// @vitest-environment jsdom -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { MemoryRouter, useLocation, useNavigate } from "react-router-dom"; -import { afterEach, describe, expect, it } from "vitest"; -import { ThemeProvider } from "@/context/ThemeContext"; -import { DocumentMarkdownBody } from "./DocumentMarkdownBody"; - -(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; -let root: Root; -let container: HTMLDivElement; -afterEach(async () => { - await act(async () => root?.unmount()); - container?.remove(); -}); - -const body = "![First](/first.png)\n\n![Second][shot]\n\n![Repeated](/first.png)\n\n[shot]: https://example.com/second.png"; -function LocationProbe() { - const location = useLocation(); - const navigate = useNavigate(); - return <>{location.pathname}{location.search}{location.hash}; -} -async function render(hash = "", markdown = body, revisionId?: string, documentIssueId?: string, currentIssueId?: string) { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); - await act(async () => { - root.render( - - {markdown} - - - ); - }); -} -async function click(selector: string) { - const element = document.querySelector(selector)!; - expect(element).not.toBeNull(); - await act(async () => element.click()); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); -} -async function key(key: string) { - await act(async () => document.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }))); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); -} -function dialog() { return document.querySelector('[role="dialog"]'); } - -describe("document image gallery", () => { - it("keeps fragment links scoped to the saved document's task after the URL changes", async () => { - await render("#document-local", "[Evidence](#document-evidence&thread=note)\n\n[Explicit](#document-brief&documentIssue=other)\n\n[Section](#section)", "old", "owner", "current"); - expect([...container.querySelectorAll(".paperclip-markdown a")].map(link => link.getAttribute("href"))).toEqual([ - "#document-evidence&thread=note&documentIssue=owner", - "#document-brief&documentIssue=other", - "#section", - ]); - }); - - it("opens a clicked occurrence, navigates all rendered images, and updates the URL", async () => { - await render("#document-report&viewer=full&thread=thread-1"); - await click('[aria-label="Open image: Repeated"]'); - expect(dialog()?.textContent).toContain("3 / 3"); - expect(dialog()?.querySelector("img")?.getAttribute("src")).toBe("/first.png"); - expect(container.querySelector("output")?.textContent).toBe("/PAP/issues/example?keep=1#document-report&thread=thread-1&viewer=full&image=3"); - await key("ArrowRight"); - expect(dialog()?.textContent).toContain("1 / 3"); - await click('button[title="Next"]'); - expect(dialog()?.querySelector("img")?.getAttribute("src")).toBe("https://example.com/second.png"); - expect(container.querySelector("output")?.textContent).toContain("image=2"); - await key("ArrowLeft"); - expect(dialog()?.textContent).toContain("1 / 3"); - await click('button[title="Previous"]'); - expect(dialog()?.textContent).toContain("3 / 3"); - await key("Escape"); - expect(dialog()).toBeNull(); - expect(container.querySelector("output")?.textContent).not.toContain("image="); - expect(container.querySelector("output")?.textContent).toContain("viewer=full"); - expect(document.activeElement?.getAttribute("aria-label")).toBe("Open image: Repeated"); - }); - - it("loads a shared image URL for the exact revision and retains it on close", async () => { - await render("#document-report&revision=old&interaction=review&documentIssue=owner&image=2", body, "old", "owner"); - expect(dialog()?.textContent).toContain("2 / 3"); - expect(dialog()?.querySelector("a")?.getAttribute("href")).toBe("https://example.com/second.png"); - await click('button[title="Close"]'); - expect(container.querySelector("output")?.textContent).toContain("#document-report&revision=old&interaction=review&documentIssue=owner"); - expect(dialog()).toBeNull(); - }); - - it("opens a saved owner after the URL has changed to another document", async () => { - await render("#document-local&documentIssue=wrong-owner", body, "old", "owner"); - await click('[aria-label="Open image: First"]'); - expect(dialog()?.textContent).toContain("1 / 3"); - expect(container.querySelector("output")?.textContent).toContain("#document-report&revision=old&documentIssue=owner&image=1"); - await key("ArrowRight"); - expect(container.querySelector("output")?.textContent).toContain("documentIssue=owner&image=2"); - }); - - it("opens an explicit current-task link and keeps review parameters through navigation and reopening", async () => { - await render("#document-report&revision=old&interaction=review&viewer=full&documentIssue=current-task&image=2", body, "old", undefined, "current-task"); - expect(dialog()?.textContent).toContain("2 / 3"); - await key("ArrowRight"); - expect(dialog()?.textContent).toContain("3 / 3"); - await click('button[title="Close"]'); - expect(dialog()).toBeNull(); - await click('[aria-label="Open image: First"]'); - expect(dialog()?.textContent).toContain("1 / 3"); - const url = container.querySelector("output")?.textContent; - expect(url).toContain("revision=old"); - expect(url).toContain("interaction=review"); - expect(url).toContain("viewer=full"); - expect(url).toContain("documentIssue=current-task"); - }); - - it("does not match another task's saved tab to an implicit current-task link", async () => { - await render("#document-report&revision=old&image=2", body, "old", "other-task", "current-task"); - expect(dialog()).toBeNull(); - await click('[aria-label="Open image: First"]'); - expect(dialog()?.textContent).toContain("1 / 3"); - expect(container.querySelector("output")?.textContent).toContain("documentIssue=other-task"); - }); - - it.each(["#document-other&image=1", "#document-report&image=100", "#document-report&image=0", "#document-report&revision=old&image=1"])("does not open an unavailable image target: %s", async (hash) => { - await render(hash); - expect(dialog()).toBeNull(); - }); - - it("opens a single image from the keyboard without navigation controls", async () => { - await render("", "![Only](/only.png)"); - const image = container.querySelector("img")!; - await act(async () => { - image.focus(); - image.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true })); - }); - expect(dialog()?.textContent).toContain("1 / 1"); - expect(dialog()?.querySelector('button[title="Next"]')).toBeNull(); - await click('[role="dialog"]'); - expect(dialog()).toBeNull(); - expect(document.activeElement).toBe(image); - }); -}); diff --git a/ui/src/components/EnvVarEditor.test.tsx b/ui/src/components/EnvVarEditor.test.tsx deleted file mode 100644 index fc0b8515f28..00000000000 --- a/ui/src/components/EnvVarEditor.test.tsx +++ /dev/null @@ -1,127 +0,0 @@ -// @vitest-environment jsdom - -import { createRoot, type Root } from "react-dom/client"; -import { flushSync } from "react-dom"; -import type { CompanySecret, EnvBinding, UserSecretDefinition } from "@paperclipai/shared"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { EnvironmentVariablesEditor } from "./environment-variables-editor"; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -const definition: UserSecretDefinition = { - id: "def-1", - companyId: "c1", - key: "PERSONAL_GH_TOKEN", - name: "Personal GitHub token", - description: null, - status: "active", - provider: "local_encrypted", - managedMode: "paperclip_managed", - providerConfigId: null, - providerMetadata: null, - usageGuidance: null, - createdByAgentId: null, - createdByUserId: null, - updatedByAgentId: null, - updatedByUserId: null, - deletedAt: null, - createdAt: new Date(), - updatedAt: new Date(), -}; - -async function act(callback: () => void | Promise) { - let result: void | Promise = undefined; - flushSync(() => { - result = callback(); - }); - await result; -} - -let container: HTMLDivElement; -let root: Root; - -beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); -}); - -afterEach(() => { - act(() => root.unmount()); - container.remove(); -}); - -function render(props: Partial>) { - root = createRoot(container); - return act(() => { - root.render( - , - ); - }); -} - -describe("EnvironmentVariablesEditor user secret binding", () => { - it("renders an existing user_secret_ref as a User secret row with the definition and requirement", async () => { - const value: Record = { - GH_TOKEN: { type: "user_secret_ref", key: "PERSONAL_GH_TOKEN", required: true }, - }; - await render({ value, userSecretDefinitions: [definition] }); - - const keyInput = container.querySelector('input[placeholder="KEY"]'); - expect(keyInput?.value).toBe("GH_TOKEN"); - // Radix Select triggers render the selected label as text. - expect(container.textContent).toContain("User secret"); - expect(container.textContent).toContain("Personal GitHub token"); - expect(container.textContent).toContain("Required"); - }); - - it("explains user-secret bindings when a user secret row is present", async () => { - await render({ - value: { GH_TOKEN: { type: "user_secret_ref", key: "PERSONAL_GH_TOKEN", required: true } }, - userSecretDefinitions: [definition], - }); - expect(container.textContent).toContain("Personal GitHub token"); - expect(container.textContent).toContain("User secrets resolve from the user responsible for the run."); - }); - - it("keeps working for company secrets when no user definitions are provided", async () => { - const secret: CompanySecret = { - id: "sec-1", - companyId: "c1", - scope: "company", - ownerUserId: null, - userSecretDefinitionId: null, - key: "api_key", - name: "API key", - provider: "local_encrypted", - status: "active", - managedMode: "paperclip_managed", - externalRef: null, - providerConfigId: null, - providerMetadata: null, - latestVersion: 2, - description: null, - lastResolvedAt: null, - lastRotatedAt: null, - deletedAt: null, - createdByAgentId: null, - createdByUserId: null, - createdAt: new Date(), - updatedAt: new Date(), - }; - const value: Record = { - API_KEY: { type: "secret_ref", secretId: "sec-1", version: "latest" }, - }; - await render({ value, secrets: [secret] }); - - const keyInput = container.querySelector('input[placeholder="KEY"]'); - expect(keyInput?.value).toBe("API_KEY"); - expect(container.textContent).toContain("API key"); - }); -}); diff --git a/ui/src/components/FileTree.test.tsx b/ui/src/components/FileTree.test.tsx deleted file mode 100644 index 2bf88810200..00000000000 --- a/ui/src/components/FileTree.test.tsx +++ /dev/null @@ -1,231 +0,0 @@ -// @vitest-environment jsdom - -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { FileTree, buildFileTree } from "./FileTree"; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -describe("FileTree", () => { - let container: HTMLDivElement; - let root: Root; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - }); - - afterEach(() => { - act(() => { - root.unmount(); - }); - container.remove(); - }); - - function row(path: string) { - return container.querySelector(`[data-file-tree-path="${path}"]`) as HTMLDivElement | null; - } - - it("preserves readable plugin error details and retry without exposing raw codes", () => { - const retry = vi.fn(); - const renderError = (message: string) => act(() => root.render( - {}} onToggleDir={() => {}} error={{ message, retry }} />, - )); - renderError("The wiki source was removed. Choose another source."); - expect(container.textContent).toContain("The wiki source was removed. Choose another source."); - act(() => Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Retry")!.click()); - expect(retry).toHaveBeenCalledOnce(); - renderError("source_unavailable"); - expect(container.textContent).not.toContain("source_unavailable"); - }); - - it("selects file rows and expands directory rows", () => { - const onSelectFile = vi.fn(); - const onToggleDir = vi.fn(); - const nodes = buildFileTree({ - "README.md": "", - "docs/guide.md": "", - }); - - act(() => { - root.render( - , - ); - }); - - expect(row("README.md")?.getAttribute("aria-selected")).toBe("true"); - - act(() => { - row("docs/guide.md")?.click(); - }); - expect(onSelectFile).toHaveBeenCalledWith("docs/guide.md"); - - act(() => { - row("docs")?.click(); - }); - expect(onToggleDir).toHaveBeenCalledWith("docs"); - }); - - it("marks partially selected directories as indeterminate", () => { - const nodes = buildFileTree({ - "docs/a.md": "", - "docs/b.md": "", - }); - - act(() => { - root.render( - {}} - onToggleDir={() => {}} - onToggleCheck={() => {}} - />, - ); - }); - - const input = row("docs")?.querySelector("input[type='checkbox']") as HTMLInputElement | null; - expect(input?.checked).toBe(false); - expect(input?.indeterminate).toBe(true); - expect(row("docs")?.getAttribute("aria-checked")).toBe("mixed"); - }); - - it("renders file badges and host-only file extras", () => { - const nodes = buildFileTree({ - "wiki/very-long-page-slug.md": "", - }); - - act(() => { - root.render( - {}} - onToggleDir={() => {}} - fileBadges={{ - "wiki/very-long-page-slug.md": { - label: "fresh", - status: "ok", - tooltip: "Synced", - }, - }} - renderFileExtra={(node) => ( - node.kind === "file" ? {node.name.length} chars : null - )} - />, - ); - }); - - expect(container.textContent).toContain("fresh"); - expect(container.querySelector("[title='Synced']")).not.toBeNull(); - expect(container.querySelector("[data-testid='file-extra']")?.textContent).toBe("22 chars"); - }); - - it("wraps long labels by default and can opt back into truncation", () => { - const nodes = buildFileTree({ - "wiki/extremely-long-page-slug-that-wraps-on-mobile.md": "", - }); - - act(() => { - root.render( - {}} - onToggleDir={() => {}} - />, - ); - }); - - expect(row("wiki/extremely-long-page-slug-that-wraps-on-mobile.md")?.innerHTML).toContain("break-all"); - - act(() => { - root.render( - {}} - onToggleDir={() => {}} - wrapLabels={false} - />, - ); - }); - - expect(row("wiki/extremely-long-page-slug-that-wraps-on-mobile.md")?.innerHTML).toContain("truncate"); - }); - - it("supports tree keyboard expansion and checkbox toggling", () => { - const onToggleDir = vi.fn(); - const onToggleCheck = vi.fn(); - const nodes = buildFileTree({ - "docs/a.md": "", - }); - - act(() => { - root.render( - {}} - onToggleDir={onToggleDir} - onToggleCheck={onToggleCheck} - />, - ); - }); - - const docsRow = row("docs"); - act(() => { - docsRow?.focus(); - docsRow?.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true })); - }); - expect(onToggleDir).toHaveBeenCalledWith("docs"); - - act(() => { - docsRow?.dispatchEvent(new KeyboardEvent("keydown", { key: " ", bubbles: true })); - }); - expect(onToggleCheck).toHaveBeenCalledWith("docs", "dir"); - }); - - it("keeps hidden descendants in folder selection and restores a tab stop when filtering", () => { - const nodes = buildFileTree({ "docs/a.md": "", "docs/b.md": "" }); - const props = { nodes, selectedFile: null, expandedDirs: new Set(["docs"]), checkedFiles: new Set(["docs/a.md"]), onSelectFile: () => {}, onToggleDir: () => {} }; - act(() => root.render()); - act(() => row("docs/b.md")?.focus()); - act(() => root.render( {node.name} description} />)); - expect(row("docs/b.md")).toBeNull(); - expect(row("docs")?.getAttribute("aria-checked")).toBe("mixed"); - expect(row("docs")?.tabIndex).toBe(0); - expect(row("docs/a.md")?.textContent).toContain("a.md description"); - }); - - it("blocks mouse and keyboard changes while disabled", () => { - const onToggleDir = vi.fn(); - const onToggleCheck = vi.fn(); - const onSelectFile = vi.fn(); - act(() => root.render()); - act(() => { - row("docs/a.md")?.click(); - row("docs")?.dispatchEvent(new KeyboardEvent("keydown", { key: " ", bubbles: true })); - container.querySelector('[aria-label="Collapse docs"]')?.click(); - }); - expect(onToggleCheck).not.toHaveBeenCalled(); - expect(onSelectFile).not.toHaveBeenCalled(); - expect(onToggleDir).not.toHaveBeenCalled(); - expect(container.querySelector('input[type="checkbox"]')?.disabled).toBe(true); - }); -}); diff --git a/ui/src/components/InlineEntitySelector.test.tsx b/ui/src/components/InlineEntitySelector.test.tsx deleted file mode 100644 index c831fc1d43d..00000000000 --- a/ui/src/components/InlineEntitySelector.test.tsx +++ /dev/null @@ -1,500 +0,0 @@ -// @vitest-environment jsdom - -import { createRoot } from "react-dom/client"; -import { flushSync } from "react-dom"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { Dialog, DialogContent, DialogTitle } from "./ui/dialog"; -import { InlineEntitySelector } from "./InlineEntitySelector"; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -async function act(callback: () => void | Promise) { - let result: void | Promise = undefined; - flushSync(() => { - result = callback(); - }); - await result; -} - -describe("InlineEntitySelector", () => { - let container: HTMLDivElement; - let originalMatchMedia: typeof window.matchMedia; - - beforeEach(() => { - originalMatchMedia = window.matchMedia; - container = document.createElement("div"); - document.body.appendChild(container); - }); - - afterEach(() => { - window.matchMedia = originalMatchMedia; - container.remove(); - document.body.innerHTML = ""; - }); - - it.each([false, true])("allows wheel and touch scrolling outside a parent dialog (mobile: %s)", async (mobile) => { - window.matchMedia = vi.fn().mockImplementation((query: string) => ({ - matches: mobile && query === "(max-width: 40rem)", - media: query, - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - })); - const root = createRoot(container); - await act(() => { - root.render( - - - New task - ({ id: `agent-${index}`, label: `Agent ${index}` }))} - placeholder="Assignee" - noneLabel="No assignee" - searchPlaceholder="Search assignees..." - emptyMessage="No assignees found." - onChange={vi.fn()} - triggerTestId="nested-assignee-picker" - openOnFocus={false} - modal - /> - - , - ); - }); - try { - await act(() => { - document.querySelector("[data-testid=nested-assignee-picker]")!.click(); - }); - // Let both real Radix scroll locks install their document listeners. - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - const list = document.querySelector("[data-mobile-entity-picker-list]")!; - expect(list).not.toBeNull(); - expect(document.querySelector("[data-slot=dialog-content]")!.contains(list)).toBe(false); - // jsdom has no layout; supply the geometry of a list with more rows than fit. - list.style.overflowY = "auto"; - Object.defineProperties(list, { - scrollHeight: { configurable: true, value: 1000 }, - clientHeight: { configurable: true, value: 200 }, - }); - const option = list.querySelector("button")!; - const wheel = new WheelEvent("wheel", { bubbles: true, cancelable: true, deltaY: 100 }); - option.dispatchEvent(wheel); - expect(wheel.defaultPrevented).toBe(false); - const touch = (type: string, y: number) => { - const event = new Event(type, { bubbles: true, cancelable: true }); - Object.defineProperties(event, { - touches: { value: [{ clientX: 100, clientY: y }] }, - changedTouches: { value: [{ clientX: 100, clientY: y }] }, - }); - option.dispatchEvent(event); - return event; - }; - touch("touchstart", 150); - expect(touch("touchmove", 100).defaultPrevented).toBe(false); - // The background stays locked while the picker is open. - const outsideMove = new Event("touchmove", { bubbles: true, cancelable: true }); - Object.defineProperties(outsideMove, { - touches: { value: [{ clientX: 100, clientY: 100 }] }, - changedTouches: { value: [{ clientX: 100, clientY: 100 }] }, - }); - document.body.dispatchEvent(outsideMove); - expect(outsideMove.defaultPrevented).toBe(true); - } finally { - await act(() => root.unmount()); - } - }); - - it("opens on the next keyboard focus after a desktop outside dismissal", async () => { - const root = createRoot(container); - await act(() => { - root.render(<> - - - ); - }); - try { - const trigger = container.querySelector("[data-testid=desktop-assignee-picker]")!; - const outside = container.querySelector("[data-testid=outside-picker]")!; - await act(() => trigger.click()); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - await act(() => { - outside.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true, cancelable: true })); - outside.focus(); - outside.click(); - }); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - expect(document.querySelector("[data-mobile-entity-picker]")).toBeNull(); - expect(document.activeElement).toBe(outside); - await act(() => trigger.focus()); - expect(document.querySelector("[data-mobile-entity-picker]")).not.toBeNull(); - } finally { - await act(() => root.unmount()); - } - }); - - it("dismisses the mobile project sheet from its backdrop and preserves the task dialog", async () => { - window.matchMedia = vi.fn().mockImplementation((query: string) => ({ - matches: query === "(max-width: 40rem)", - media: query, - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - })); - const onChange = vi.fn(); - const root = createRoot(container); - await act(() => { - root.render( - - - New task - - - , - ); - }); - try { - const trigger = document.querySelector('[data-testid="project-picker"]')!; - await act(() => trigger.click()); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - const backdrop = document.querySelector("[data-mobile-entity-picker]")!.parentElement!; - await act(() => { - const pointerDown = new MouseEvent("pointerdown", { bubbles: true, cancelable: true }); - Object.defineProperty(pointerDown, "pointerType", { value: "touch" }); - backdrop.dispatchEvent(pointerDown); - backdrop.click(); - }); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - expect(document.querySelector("[data-mobile-entity-picker]")).toBeNull(); - expect(document.querySelector("[data-slot=dialog-content]")).not.toBeNull(); - expect(trigger.textContent).toContain("Board UI"); - expect(document.activeElement).toBe(trigger); - expect(onChange).not.toHaveBeenCalled(); - await act(() => trigger.click()); - expect(document.querySelector("[data-mobile-entity-picker]")).not.toBeNull(); - } finally { - await act(() => root.unmount()); - } - }); - - it("keeps handled search navigation keys inside the popover", async () => { - const root = createRoot(container); - const onChange = vi.fn(); - const documentKeyDown = vi.fn(); - document.addEventListener("keydown", documentKeyDown); - - act(() => { - root.render( - , - ); - }); - - const trigger = container.querySelector("button") as HTMLButtonElement | null; - expect(trigger).not.toBeNull(); - - await act(async () => { - trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - - const searchInput = document.querySelector('input[placeholder="Search responsible..."]') as HTMLInputElement | null; - expect(searchInput).not.toBeNull(); - searchInput?.focus(); - - await act(async () => { - await Promise.resolve(); - }); - - await act(async () => { - searchInput?.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key: "ArrowDown" })); - }); - - expect(documentKeyDown).not.toHaveBeenCalled(); - - await act(async () => { - searchInput?.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key: "Enter" })); - }); - - expect(documentKeyDown).not.toHaveBeenCalled(); - expect(onChange).toHaveBeenCalledWith("agent:agent-1"); - - document.removeEventListener("keydown", documentKeyDown); - act(() => { - root.unmount(); - }); - }); - - it("focuses the search input when opened on coarse pointers", async () => { - window.matchMedia = vi.fn().mockImplementation((query: string) => ({ - matches: query === "(pointer: coarse)" || query === "(max-width: 40rem)", - media: query, - onchange: null, - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - addListener: vi.fn(), - removeListener: vi.fn(), - dispatchEvent: vi.fn(), - })); - - const root = createRoot(container); - - act(() => { - root.render( - , - ); - }); - - const trigger = container.querySelector("button") as HTMLButtonElement | null; - expect(trigger).not.toBeNull(); - - await act(async () => { - trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - - const searchInput = document.querySelector('input[placeholder="Search responsible..."]') as HTMLInputElement | null; - expect(searchInput).not.toBeNull(); - expect(searchInput?.className).toContain("text-base"); - expect(document.querySelector("[data-mobile-entity-picker]")).not.toBeNull(); - expect(container.contains(document.querySelector("[data-mobile-entity-picker]"))).toBe(false); - expect(document.querySelector("[data-mobile-entity-picker-header]")?.textContent).toContain("Responsible"); - expect(document.querySelector('button[aria-label="Close selector"]')).not.toBeNull(); - expect(document.activeElement).toBe(searchInput); - - await act(async () => { - (document.querySelector('button[aria-label="Close selector"]') as HTMLButtonElement | null)?.click(); - await Promise.resolve(); - }); - expect(document.querySelector("[data-mobile-entity-picker]")).toBeNull(); - - act(() => { - root.unmount(); - }); - }); - - it("opens on programmatic focus without toggling an open popover closed", async () => { - const root = createRoot(container); - - act(() => { - root.render( - , - ); - }); - - const trigger = container.querySelector("button") as HTMLButtonElement | null; - expect(trigger).not.toBeNull(); - - await act(async () => { - trigger?.focus(); - await Promise.resolve(); - }); - expect( - document.querySelector('input[placeholder="Search projects..."]'), - ).not.toBeNull(); - - await act(async () => { - trigger?.focus(); - await Promise.resolve(); - }); - expect( - document.querySelector('input[placeholder="Search projects..."]'), - ).not.toBeNull(); - - act(() => { - root.unmount(); - }); - }); - - it("keeps the no-selection action first when requested", async () => { - const root = createRoot(container); - const onChange = vi.fn(); - - act(() => { - root.render( - , - ); - }); - - const trigger = container.querySelector("button") as HTMLButtonElement; - await act(() => trigger.click()); - - const options = Array.from( - document.querySelectorAll("[data-mobile-entity-picker-list] > button"), - ); - expect(options.map((option) => option.textContent)).toEqual([ - "No project", - "Project One", - "Project Two", - ]); - - const searchInput = document.querySelector('input[placeholder="Search projects..."]'); - const nativeInputValue = Object.getOwnPropertyDescriptor( - window.HTMLInputElement.prototype, - "value", - )?.set; - await act(() => { - nativeInputValue?.call(searchInput, "Two"); - searchInput?.dispatchEvent(new Event("input", { bubbles: true })); - }); - - const filteredOptions = Array.from( - document.querySelectorAll("[data-mobile-entity-picker-list] > button"), - ); - expect(filteredOptions.map((option) => option.textContent)).toEqual([ - "No project", - "Project Two", - ]); - - await act(() => { - searchInput?.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key: "Enter" })); - }); - expect(onChange).toHaveBeenCalledWith("project-2"); - - act(() => root.unmount()); - }); - - it("does not open the popover when disabled", async () => { - const root = createRoot(container); - const onChange = vi.fn(); - - act(() => { - root.render( - , - ); - }); - - const trigger = container.querySelector("button") as HTMLButtonElement | null; - expect(trigger).not.toBeNull(); - expect(trigger?.disabled).toBe(true); - - await act(async () => { - trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - - expect(document.querySelector('input[placeholder="Search responsible..."]')).toBeNull(); - expect(onChange).not.toHaveBeenCalled(); - - act(() => { - root.unmount(); - }); - }); - - it("filters options as the user types in the search box", async () => { - const root = createRoot(container); - const onChange = vi.fn(); - - act(() => { - root.render( - , - ); - }); - - const trigger = container.querySelector("button") as HTMLButtonElement | null; - await act(async () => { - trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - - const searchInput = document.querySelector('input[placeholder="Search responsible..."]') as HTMLInputElement | null; - expect(searchInput).not.toBeNull(); - - const nativeInputValue = Object.getOwnPropertyDescriptor( - window.HTMLInputElement.prototype, - "value", - )?.set; - await act(async () => { - nativeInputValue?.call(searchInput, "design"); - searchInput?.dispatchEvent(new Event("input", { bubbles: true })); - }); - - const optionLabels = Array.from(document.querySelectorAll("[role='dialog'] button, .max-h-56 button")).map( - (el) => el.textContent ?? "", - ); - const joined = optionLabels.join("|"); - expect(joined).toContain("DesignBot"); - expect(joined).not.toContain("CodexCoder"); - - act(() => { - root.unmount(); - }); - }); -}); diff --git a/ui/src/components/InteractionGovernancePanel.test.tsx b/ui/src/components/InteractionGovernancePanel.test.tsx deleted file mode 100644 index d05da735774..00000000000 --- a/ui/src/components/InteractionGovernancePanel.test.tsx +++ /dev/null @@ -1,241 +0,0 @@ -// @vitest-environment jsdom - -import { act as reactAct } from "react"; -import { flushSync } from "react-dom"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, describe, expect, it, vi } from "vitest"; -import { - ISSUE_THREAD_INTERACTION_KINDS, - type InteractionResolverGovernance, -} from "@paperclipai/shared"; - -// Routine offers are always answered by a person, so they have no audience row. -const INTERACTION_KINDS = ISSUE_THREAD_INTERACTION_KINDS.filter((kind) => kind !== "suggest_routine" && kind !== "propose_responsibility_bar" && kind !== "propose_automation" && kind !== "propose_dashboard_changes"); -import { - GOVERNANCE_UNSET, - InteractionGovernancePanel, - applyGovernanceChange, - toGovernanceSelectValue, -} from "./InteractionGovernancePanel"; -import { TooltipProvider } from "./ui/tooltip"; - -let root: Root | null = null; -let container: HTMLDivElement | null = null; - -(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - -async function act(callback: () => void | Promise) { - if (typeof reactAct === "function") { - await reactAct(callback); - return; - } - let result: void | Promise = undefined; - flushSync(() => { - result = callback(); - }); - await result; -} - -function renderPanel(governance: InteractionResolverGovernance = {}, onChange = vi.fn()) { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => { - root?.render( - - - , - ); - }); - return { host: container, onChange }; -} - -/** Exact visible text of a closed select trigger (the chevron contributes none). */ -function triggerText(host: HTMLElement, testId: string): string { - const trigger = host.querySelector(`[data-testid="${testId}"]`); - expect(trigger).toBeTruthy(); - return (trigger?.textContent ?? "").replace(/\s+/g, " ").trim(); -} - -afterEach(() => { - if (root) { - act(() => root?.unmount()); - } - container?.remove(); - root = null; - container = null; -}); - -describe("InteractionGovernancePanel", () => { - it("presents Anyone as the visible default for a company with no overrides", () => { - const { host } = renderPanel(); - - const defaultSelect = host.querySelector('[data-testid="governance-request_confirmation-default"]'); - expect(defaultSelect?.textContent).toContain("Anyone (default)"); - const cap = host.querySelector('[data-testid="governance-request_confirmation-cap"]'); - expect(cap?.textContent).toContain("No cap"); - }); - - it("describes the open default without presenting it as board-required", () => { - const { host } = renderPanel(); - const copy = host.textContent ?? ""; - - expect(copy).toContain("Thread interactions are open by default"); - expect(copy).toContain("the board or any agent, including the one that asked"); - expect(copy).not.toContain("Board only"); - expect(copy).not.toContain("always require the board"); - // Governed tool approvals keep their human-only guarantee. - expect(copy).toContain("Tool-approval confirmations always stay"); - expect(copy).toContain("Human only"); - }); - - it("shows a stored narrowing override on the matching row", () => { - const { host } = renderPanel({ - request_confirmation: { defaultPolicy: "human_only", cap: "not_creator" }, - }); - - expect( - host.querySelector('[data-testid="governance-request_confirmation-default"]')?.textContent, - ).toContain("Human only"); - expect( - host.querySelector('[data-testid="governance-request_confirmation-cap"]')?.textContent, - ).toContain("Anyone except creator"); - // Untouched kinds still read as open. - expect( - host.querySelector('[data-testid="governance-suggest_tasks-default"]')?.textContent, - ).toContain("Anyone (default)"); - }); - - /** - * PAP-17297: an empty `` lets Radix portal the selected - * option's whole subtree — label *and* effect sentence — into the closed - * trigger, where `line-clamp-1` clipped it. `toContain` assertions cannot see - * that, so these check the trigger's exact text. - */ - it("shows only the complete selected label in a closed trigger", () => { - const { host } = renderPanel(); - - for (const kind of INTERACTION_KINDS) { - expect(triggerText(host, `governance-${kind}-default`)).toBe("Anyone (default)"); - expect(triggerText(host, `governance-${kind}-cap`)).toBe("No cap"); - } - }); - - it("keeps a narrowed trigger free of the option effect sentence", () => { - const { host } = renderPanel({ - request_confirmation: { defaultPolicy: "human_only", cap: "not_creator" }, - }); - - expect(triggerText(host, "governance-request_confirmation-default")).toBe("Human only"); - expect(triggerText(host, "governance-request_confirmation-cap")).toBe("Anyone except creator"); - // The effect prose belongs to the option list, never the trigger. - expect(host.textContent).not.toContain("New cards wait for a person on the board"); - expect(host.textContent).not.toContain("narrowed to exclude its creator"); - expect(host.textContent).not.toContain("New cards are open"); - }); - - it("still offers the effect sentence inside the open option list", async () => { - const { host } = renderPanel(); - const trigger = host.querySelector( - '[data-testid="governance-request_confirmation-default"]', - ); - expect(trigger).toBeTruthy(); - - await act(() => { - trigger?.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })); - }); - - const listbox = document.querySelector('[data-slot="select-content"]'); - const listText = listbox?.textContent ?? ""; - expect(listText).toContain("Anyone (default)"); - expect(listText).toContain( - "New cards are open — the board or any agent can respond, including the one that asked.", - ); - expect(listText).toContain("New cards wait for a person on the board. Agents are turned away."); - // Each option keeps a label-only typeahead value so keyboard search does not - // match the effect prose. - expect( - Array.from(listbox?.querySelectorAll('[data-slot="select-item"]') ?? []).length, - ).toBe(3); - // Reflow guard: the popover is capped so long prose wraps instead of - // stretching past a narrow viewport. - expect(listbox?.className).toContain("max-w-(--sz-280px)"); - }); - - it("renders a select for every governable interaction kind", () => { - const { host } = renderPanel(); - expect(host.querySelector('[data-testid="governance-suggest_routine-default"]')).toBeNull(); - expect(host.querySelector('[data-testid="governance-propose_responsibility_bar-default"]')).toBeNull(); - expect(host.querySelector('[data-testid="governance-propose_automation-default"]')).toBeNull(); - expect(host.querySelector('[data-testid="governance-propose_dashboard_changes-default"]')).toBeNull(); - expect(host.querySelectorAll('[data-testid$="-default"]')).toHaveLength( - INTERACTION_KINDS.length, - ); - expect(host.querySelectorAll('[data-testid$="-cap"]')).toHaveLength( - INTERACTION_KINDS.length, - ); - }); - - it("surfaces a save failure", () => { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => { - root?.render( - - - , - ); - }); - expect(container.textContent).toContain("Failed to save interaction governance"); - }); -}); - -describe("toGovernanceSelectValue", () => { - it("treats an absent override as the open default", () => { - expect(toGovernanceSelectValue(undefined)).toBe(GOVERNANCE_UNSET); - }); - - it("treats a stored open audience — canonical or legacy alias — as the default", () => { - expect(toGovernanceSelectValue("anyone")).toBe(GOVERNANCE_UNSET); - expect(toGovernanceSelectValue("board_or_agents")).toBe(GOVERNANCE_UNSET); - }); - - it("canonicalizes stored narrowing values, including the legacy board_only alias", () => { - expect(toGovernanceSelectValue("not_creator")).toBe("not_creator"); - expect(toGovernanceSelectValue("human_only")).toBe("human_only"); - expect(toGovernanceSelectValue("board_only")).toBe("human_only"); - }); -}); - -describe("applyGovernanceChange", () => { - it("stores a narrowing override", () => { - expect(applyGovernanceChange({}, "request_confirmation", "defaultPolicy", "human_only")).toEqual({ - request_confirmation: { defaultPolicy: "human_only" }, - }); - }); - - it("clears the override when the open default is re-selected", () => { - const current: InteractionResolverGovernance = { - request_confirmation: { defaultPolicy: "human_only" }, - }; - expect( - applyGovernanceChange(current, "request_confirmation", "defaultPolicy", GOVERNANCE_UNSET), - ).toEqual({}); - // Immutable: the caller's map is untouched. - expect(current.request_confirmation?.defaultPolicy).toBe("human_only"); - }); - - it("keeps a sibling field when only one is cleared", () => { - const current: InteractionResolverGovernance = { - request_confirmation: { defaultPolicy: "human_only", cap: "not_creator" }, - }; - expect(applyGovernanceChange(current, "request_confirmation", "cap", GOVERNANCE_UNSET)).toEqual({ - request_confirmation: { defaultPolicy: "human_only" }, - }); - }); -}); diff --git a/ui/src/components/IssueRow.test.tsx b/ui/src/components/IssueRow.test.tsx deleted file mode 100644 index 0d03ba29ac7..00000000000 --- a/ui/src/components/IssueRow.test.tsx +++ /dev/null @@ -1,968 +0,0 @@ -// @vitest-environment jsdom - -import { act as reactAct } from "react"; -import { flushSync } from "react-dom"; -import { createRoot } from "react-dom/client"; -import type { Issue } from "@paperclipai/shared"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { IssueRow } from "./IssueRow"; -import { StatusIcon } from "./StatusIcon"; -import { TooltipProvider } from "./ui/tooltip"; - -vi.mock("@/lib/router", () => ({ - Link: ({ - children, - className, - to, - disableIssueQuicklook: _disableIssueQuicklook, - issuePrefetch, - ...props - }: React.ComponentProps<"a"> & { to?: string; disableIssueQuicklook?: boolean; issuePrefetch?: Issue | null }) => ( - - {children} - - ), -})); - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -function act(callback: () => void) { - if (typeof reactAct === "function") { - reactAct(callback); - return; - } - - flushSync(callback); -} - -function createIssue(overrides: Partial = {}): Issue { - return { - id: "issue-1", - identifier: "PAP-1", - companyId: "company-1", - projectId: null, - projectWorkspaceId: null, - goalId: null, - parentId: null, - title: "Inbox item", - description: null, - status: "todo", - priority: "medium", - reviewPolicy: null, - assigneeAgentId: null, - assigneeUserId: null, - responsibleUserId: null, - createdByAgentId: null, - createdByUserId: null, - issueNumber: 1, - requestDepth: 0, - billingCode: null, - assigneeAdapterOverrides: null, - executionWorkspaceId: null, - executionWorkspacePreference: null, - executionWorkspaceSettings: null, - checkoutRunId: null, - executionRunId: null, - executionAgentNameKey: null, - executionLockedAt: null, - startedAt: null, - completedAt: null, - cancelledAt: null, - hiddenAt: null, - createdAt: new Date("2026-03-11T00:00:00.000Z"), - updatedAt: new Date("2026-03-11T00:00:00.000Z"), - labels: [], - labelIds: [], - myLastTouchAt: null, - lastExternalCommentAt: null, - isUnreadForMe: false, - ...overrides, - workMode: overrides.workMode ?? "standard", - }; -} - -describe("IssueRow", () => { - let container: HTMLDivElement; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - }); - - afterEach(() => { - container.remove(); - vi.unstubAllGlobals(); - }); - - it("renders the list status glyph at md (16px)", () => { - const root = createRoot(container); - - act(() => { - root.render(); - }); - - // jsdom 30 does not value-match a CSS attribute selector against a - // mixed-case SVG attribute name, so `svg[viewBox="0 0 24 24"]` matches - // nothing. Select the glyph SVGs by attribute presence, then compare the - // viewBox value with getAttribute to keep the exact-value assertion. - const glyphs = Array.from(container.querySelectorAll("svg[viewBox]")).filter( - (svg) => svg.getAttribute("viewBox") === "0 0 24 24", - ); - expect(glyphs.length).toBeGreaterThan(0); - glyphs.forEach((glyph) => { - expect(glyph.getAttribute("width")).toBe("16"); - expect(glyph.getAttribute("height")).toBe("16"); - }); - - act(() => { - root.unmount(); - }); - }); - - it("uses stable canonical identifier and timestamp columns at the trailing edge", () => { - const root = createRoot(container); - - act(() => { - root.render( - Live} - actions={} - trailingMeta="Updated now" - />, - ); - }); - - const row = container.querySelector('[data-slot="task-row"]'); - const leading = row?.querySelector('[data-slot="task-row-leading"]'); - const title = row?.querySelector('[data-slot="task-row-title"]'); - const metadata = row?.querySelector('[data-slot="task-row-metadata"]'); - const identifier = row?.querySelector('[data-slot="task-row-identifier"]'); - const timestamp = row?.querySelector('[data-slot="task-row-timestamp"]'); - const actions = row?.querySelector('[data-slot="task-row-actions"]'); - const link = row?.querySelector('[data-inbox-issue-link]'); - - expect(leading?.querySelector("svg")).not.toBeNull(); - expect(title?.textContent).toContain("Canonical task"); - expect(metadata?.textContent).toBe("Live"); - expect(identifier?.textContent).toBe("PAP-42"); - expect(timestamp?.textContent).toBe("Updated now"); - expect(actions?.textContent).toBe("More"); - expect(identifier?.className).toContain("w-20"); - expect(timestamp?.className).toContain("w-24"); - if (!link || !metadata || !identifier || !timestamp || !actions) throw new Error("Expected canonical task row slots"); - expect(link.contains(actions)).toBe(false); - expect(metadata.compareDocumentPosition(actions) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); - expect(actions.compareDocumentPosition(identifier) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); - expect(identifier.compareDocumentPosition(timestamp) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); - expect(timestamp.nextElementSibling).toBeNull(); - - act(() => root.unmount()); - }); - - it("keeps the canonical archive action within the shared task-row height", () => { - const root = createRoot(container); - - act(() => { - root.render( - undefined} - />, - ); - }); - - const archiveButton = container.querySelector('button[aria-label="Archive"]'); - expect(archiveButton?.className).toContain("h-5"); - expect(archiveButton?.className).toContain("py-0"); - expect(archiveButton?.className).not.toContain("py-1"); - - act(() => root.unmount()); - }); - - it("restores a task independently of its row link", () => { - const root = createRoot(container); - const restore = vi.fn(); - act(() => root.render( - - - , - )); - - const button = container.querySelector('button[aria-label="Restore from archive"]')!; - expect(button.closest("a")).toBeNull(); - act(() => button.click()); - expect(restore).toHaveBeenCalledOnce(); - act(() => root.unmount()); - }); - - it("starts a truncated title reveal on link focus and keeps actions independent", async () => { - const bounds = vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 0, 200, 16)); - const createRange = document.createRange.bind(document); - const rangeBounds = vi.spyOn(document, "createRange").mockImplementation(() => Object.assign(createRange(), { - getBoundingClientRect: () => new DOMRect(0, 0, 400, 16), - })); - vi.stubGlobal("ResizeObserver", class { - observe() {} - unobserve() {} - disconnect() {} - }); - const root = createRoot(container); - const title = "Define connector health states, failure recovery, and escalation ownership across teams"; - const onExpand = vi.fn(); - const onArchive = vi.fn(); - const onMarkRead = vi.fn(); - - act(() => { - root.render( - - Expand subtasks} - onArchive={onArchive} - /> - , - ); - }); - - const link = container.querySelector("[data-inbox-issue-link]"); - const expand = container.querySelector('button:not([aria-label])'); - const archive = container.querySelector('button[aria-label="Archive"]'); - expect(link?.href).toContain("/issues/PAP-1"); - expect(link?.contains(expand)).toBe(false); - expect(link?.contains(archive)).toBe(false); - // An inbox callback must not restore the old unread dot or its reserved slot. - expect(container.querySelector('button[aria-label="Mark as read"]')).toBeNull(); - expect(container.querySelector('[data-testid="issue-row-unread-slot"]')).toBeNull(); - - await reactAct(async () => link?.focus()); - expect(document.activeElement).toBe(link); - expect(container.querySelector('[data-slot="task-row-title"]')?.getAttribute("data-revealing")).toBe("true"); - expect(container.querySelector('[data-slot="task-row-title-text"]')?.textContent).toBe(title); - expect(document.querySelector('[role="tooltip"]')).toBeNull(); - - act(() => link?.dispatchEvent(new MouseEvent("mouseout", { bubbles: true, relatedTarget: document.body }))); - expect(container.querySelector('[data-slot="task-row-title"]')?.getAttribute("data-revealing")).toBeNull(); - await reactAct(async () => { link?.blur(); link?.focus(); }); - expect(container.querySelector('[data-slot="task-row-title"]')?.getAttribute("data-revealing")).toBe("true"); - - act(() => { - link?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); - expand?.click(); - archive?.click(); - }); - expect(document.querySelector('[role="tooltip"]')).toBeNull(); - expect(container.querySelector('[data-slot="task-row-title"]')?.getAttribute("data-revealing")).toBeNull(); - expect(onExpand).toHaveBeenCalledTimes(1); - expect(onArchive).toHaveBeenCalledTimes(1); - - act(() => root.unmount()); - bounds.mockRestore(); - rangeBounds.mockRestore(); - }); - - it("preserves the legacy archive action density", () => { - const root = createRoot(container); - - act(() => { - root.render( undefined} />); - }); - - const archiveButton = container.querySelector('button[aria-label="Archive"]'); - expect(archiveButton?.className).toContain("py-1"); - expect(archiveButton?.className).not.toContain("h-5"); - - act(() => root.unmount()); - }); - - it("emphasizes unread canonical titles and overlays the accessible mark-read control", () => { - const root = createRoot(container); - const onMarkRead = vi.fn(); - act(() => { - root.render( - , - ); - }); - - const row = container.querySelector('[data-slot="task-row"]'); - const title = row?.querySelector('[data-slot="task-row-title"]'); - const unreadSlot = row?.querySelector('[data-testid="issue-row-unread-slot"]'); - const markReadButton = unreadSlot?.querySelector('button[aria-label="Mark as read"]'); - expect(row?.getAttribute("data-unread")).toBe("true"); - expect(title?.className).toContain("font-semibold"); - expect(unreadSlot).not.toBeNull(); - expect(unreadSlot?.className).toContain("absolute"); - expect(markReadButton).not.toBeNull(); - expect(markReadButton?.closest("a")).toBeNull(); - - act(() => markReadButton?.click()); - expect(onMarkRead).toHaveBeenCalledTimes(1); - - act(() => root.unmount()); - }); - - it("keeps read and unread rows aligned while allowing a smaller plain-row gutter", () => { - const root = createRoot(container); - act(() => { - root.render( - <> - - - - , - ); - }); - - const rows = Array.from(container.querySelectorAll('[data-slot="task-row"]')); - const unreadSlot = rows[0]?.querySelector('[data-testid="issue-row-unread-slot"]'); - expect(rows).toHaveLength(3); - expect(rows[0]?.className).toBe(rows[2]?.className); - expect(rows[1]?.className).toContain("pl-2 sm:pl-4"); - expect(unreadSlot).not.toBeNull(); - expect(unreadSlot?.className).toContain("absolute"); - expect(unreadSlot?.querySelector('button[aria-label="Mark as read"]')).toBeNull(); - expect(rows[1]?.querySelector('[data-testid="issue-row-unread-slot"]')).toBeNull(); - - act(() => root.unmount()); - }); - - it("preserves task-tree indentation slots in the canonical layout", () => { - const root = createRoot(container); - act(() => { - root.render( - Expand} - />, - ); - }); - - expect(container.querySelectorAll('[data-slot="task-row-tree-guide"]')).toHaveLength(2); - expect(container.querySelector('[data-slot="task-row-leading"]')?.textContent).toContain("Expand"); - for (const connector of container.querySelectorAll('[data-slot="task-row-tree-connector"]')) { - expect(connector.className).toContain("left-7"); - } - act(() => root.unmount()); - }); - - it("keeps editable row controls keyboard-accessible and outside the navigation link", () => { - const root = createRoot(container); - - act(() => { - root.render( - undefined} />} - />, - ); - }); - - const link = container.querySelector("[data-inbox-issue-link]"); - const statusButton = container.querySelector( - 'button[aria-label="Change status (current: Todo)"]', - ); - - expect(link).not.toBeNull(); - expect(statusButton).not.toBeNull(); - expect(statusButton?.tabIndex).toBe(0); - expect(link?.contains(statusButton)).toBe(false); - - act(() => { - root.unmount(); - }); - }); - - it("suppresses accent hover styling when the row is selected", () => { - const root = createRoot(container); - const issue = createIssue(); - - act(() => { - root.render(); - }); - - // The hover wash lives on the ROOT row band (not the overlay link) so the - // tint paints behind the content. Selected rows suppress the accent hover. - const row = container.firstElementChild as HTMLElement | null; - const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null; - expect(row).not.toBeNull(); - expect(row?.className).toContain("hover:bg-transparent"); - expect(row?.className).not.toContain("hover:bg-accent/50"); - // The overlay link no longer carries the hover wash. - expect(link?.className ?? "").not.toContain("hover:bg-transparent"); - expect(link?.className ?? "").not.toContain("hover:bg-accent/50"); - - act(() => { - root.unmount(); - }); - }); - - it("neutralizes selected status and unread dot accents", () => { - const root = createRoot(container); - - act(() => { - root.render(); - }); - - const markReadButton = container.querySelector('button[aria-label="Mark as read"]'); - const unreadDot = markReadButton?.querySelector("span"); - // Selected rows neutralize the status glyph to muted via `!`-important - // utilities, which override the glyph's inline colour var. The glyph is an - // (SVGAnimatedString className), so match on the class attribute. - const statusGlyph = container.querySelector('svg[class*="text-muted-foreground"]'); - - expect(markReadButton).not.toBeNull(); - expect(markReadButton?.className).toContain("hover:bg-muted/80"); - expect(markReadButton?.className).not.toContain("hover:bg-blue-500/20"); - expect(unreadDot).not.toBeNull(); - expect(unreadDot?.className).toContain("bg-muted-foreground/70"); - expect(unreadDot?.className).not.toContain("bg-blue-600"); - expect(statusGlyph).not.toBeNull(); - expect(statusGlyph?.getAttribute("class")).toContain("!text-muted-foreground"); - expect(statusGlyph?.getAttribute("class")).toContain("!border-muted-foreground"); - - act(() => { - root.unmount(); - }); - }); - - it("reserves the leading dot slot on read rows so unread rows never indent past them", () => { - const root = createRoot(container); - act(() => { - // A read inbox row still supplies `unreadState` (as "hidden"). - root.render(); - }); - - // The desktop dot slot is reserved even when read (empty), so unread rows - // add no column and line up with read rows. - const slot = container.querySelector('[data-testid="issue-row-unread-slot"]'); - expect(slot).not.toBeNull(); - expect(slot?.className).toContain("w-4"); - expect(slot?.className).toContain("sm:inline-flex"); - // In flow, not an absolute overlay. - expect(slot?.className).not.toContain("absolute"); - // Read rows carry no dot button in the slot. - expect(slot?.querySelector('button[aria-label="Mark as read"]')).toBeNull(); - - act(() => { - root.unmount(); - }); - }); - - it("puts the unread dot in the reserved desktop slot and overlays it on mobile", () => { - const root = createRoot(container); - act(() => { - root.render(); - }); - - // Desktop: the dot lives in the reserved leading slot (far left, ahead of - // any leading control such as a parent's collapse caret). - const slot = container.querySelector('[data-testid="issue-row-unread-slot"]'); - expect(slot).not.toBeNull(); - expect(slot?.querySelector('button[aria-label="Mark as read"]')).not.toBeNull(); - - // Mobile: all inbox rows reserve a gutter and the dot stays fully inside - // it, so the control cannot be clipped or indent the status/title. - const mobileDot = container - .querySelector('button[aria-label="Mark as read"].sm\\:hidden, span.sm\\:hidden button[aria-label="Mark as read"]') - ?.closest("span.sm\\:hidden"); - expect(mobileDot).not.toBeNull(); - expect(mobileDot?.className).toContain("absolute"); - expect(mobileDot?.className).toContain("left-0"); - expect(mobileDot?.className).not.toContain("order-first"); - expect(container.firstElementChild?.className).toContain("pl-4"); - - act(() => { - root.unmount(); - }); - }); - - it("preserves the issue detail breadcrumb source and href in the link target", () => { - const root = createRoot(container); - const issue = createIssue(); - const state = { - issueDetailBreadcrumb: { label: "Inbox", href: "/PAP/inbox/mine" }, - issueDetailSource: "inbox", - }; - - act(() => { - root.render(); - }); - - const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null; - expect(link).not.toBeNull(); - expect(link?.getAttribute("to") ?? link?.getAttribute("href")).toBe("/issues/PAP-1"); - - act(() => { - root.unmount(); - }); - }); - - it("opts issue quicklook out for dense inbox rows", () => { - const root = createRoot(container); - - act(() => { - root.render(); - }); - - const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null; - expect(link).not.toBeNull(); - expect(link?.getAttribute("data-disable-issue-quicklook")).toBe("true"); - - act(() => { - root.unmount(); - }); - }); - - it("passes the visible row issue into the navigation prefetch path", () => { - const root = createRoot(container); - - act(() => { - root.render(); - }); - - const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null; - expect(link?.getAttribute("data-issue-prefetch-id")).toBe("issue-1"); - - act(() => { - root.unmount(); - }); - }); - - it("renders titleSuffix inline after the issue title", () => { - const root = createRoot(container); - const issue = createIssue({ title: "Parent task" }); - - act(() => { - root.render( - (3 sub-tasks)} - />, - ); - }); - - const titleEl = container.querySelector(".line-clamp-2, .truncate"); - expect(titleEl?.textContent).toContain("Parent task"); - expect(titleEl?.textContent).toContain("(3 sub-tasks)"); - expect(container.querySelector('[data-testid="suffix"]')).not.toBeNull(); - - act(() => { - root.unmount(); - }); - }); - - it("renders checklist step numbers beside the issue identifier", () => { - const root = createRoot(container); - - act(() => { - root.render( - , - ); - }); - - const metaRow = Array.from(container.querySelectorAll("span.flex.items-center.gap-2")) - .find((element) => element.textContent?.includes("PAP-42")); - - expect(metaRow).not.toBeUndefined(); - expect(metaRow?.textContent?.replace(/\s+/g, "")).toContain("2.1.PAP-42"); - - act(() => { - root.unmount(); - }); - }); - - it("marks the current checklist step without adding a left border", () => { - const root = createRoot(container); - - act(() => { - root.render( - , - ); - }); - - // `aria-current="step"` stays on the overlay link (the focusable target), - // but the current-step wash moved to the ROOT row band alongside the hover - // wash so it paints behind the content. - const row = container.firstElementChild as HTMLElement | null; - const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null; - - expect(link).not.toBeNull(); - expect(link?.getAttribute("aria-current")).toBe("step"); - expect(row?.className).toContain("bg-primary/5"); - expect(row?.className).not.toContain("border-l-"); - expect(link?.className ?? "").not.toContain("bg-primary/5"); - - act(() => { - root.unmount(); - }); - }); - - it("does not render a planning mode marker for planning work mode issues", () => { - const root = createRoot(container); - - act(() => { - root.render(); - }); - - const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null; - expect(link).not.toBeNull(); - expect(link?.textContent).not.toContain("Planning"); - - act(() => { - root.unmount(); - }); - }); - - it("renders without error when titleSuffix is omitted", () => { - const root = createRoot(container); - - act(() => { - root.render(); - }); - - const titleEl = container.querySelector(".line-clamp-2, .truncate"); - expect(titleEl?.textContent).toContain("Inbox item"); - - act(() => { - root.unmount(); - }); - }); - - it("flags rows blocked by an assigned-backlog leaf with a parked-work badge", () => { - const root = createRoot(container); - const issue = createIssue({ - blockedBy: [ - { - id: "blocker-1", - identifier: "PAP-2", - title: "Parked child", - status: "backlog", - priority: "high", - assigneeAgentId: "agent-99", - assigneeUserId: null, - }, - ], - }); - - act(() => { - root.render(); - }); - - const badges = container.querySelectorAll('[data-testid="issue-row-parked-blocker"]'); - expect(badges.length).toBeGreaterThan(0); - expect(badges[0]?.textContent).toContain("Blocked by parked work"); - - act(() => { - root.unmount(); - }); - }); - - it("does not show the parked-work badge when assigned blocker is not in backlog", () => { - const root = createRoot(container); - const issue = createIssue({ - blockedBy: [ - { - id: "blocker-1", - identifier: "PAP-2", - title: "Active child", - status: "in_progress", - priority: "high", - assigneeAgentId: "agent-99", - assigneeUserId: null, - }, - ], - }); - - act(() => { - root.render(); - }); - - expect(container.querySelector('[data-testid="issue-row-parked-blocker"]')).toBeNull(); - - act(() => { - root.unmount(); - }); - }); - - it("renders no bottom divider by default", () => { - const root = createRoot(container); - - act(() => { - root.render(); - }); - - // Dividers are opt-in: without `showDivider` no row-separating border - // renders on either the root band or the overlay link. - const row = container.firstElementChild as HTMLElement | null; - const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null; - expect(row).not.toBeNull(); - expect(row?.className).not.toContain("border-b"); - expect(link?.className ?? "").not.toContain("border-b"); - - act(() => { - root.unmount(); - }); - }); - - it("renders an opt-in bottom divider on the row root when showDivider is set", () => { - const root = createRoot(container); - - act(() => { - root.render(); - }); - - // The divider lives on the ROOT row band with `last:border-b-0` so the real - // last row drops its border — it is not on the overlay link. - const row = container.firstElementChild as HTMLElement | null; - const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null; - expect(row?.className).toContain("border-b"); - expect(row?.className).toContain("last:border-b-0"); - expect(link?.className ?? "").not.toContain("border-b"); - - act(() => { - root.unmount(); - }); - }); - - it("never renders a horizontal divider in canonical task presentation", () => { - const root = createRoot(container); - - act(() => { - root.render(); - }); - - const row = container.querySelector('[data-slot="task-row"]'); - expect(row?.className).not.toContain("border-b"); - - act(() => root.unmount()); - }); - - it("keeps the hover wash on the row root while the overlay link stays a bare positioning layer", () => { - const root = createRoot(container); - - act(() => { - root.render(); - }); - - const row = container.firstElementChild as HTMLElement | null; - const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null; - // Hover wash paints behind the content on the root band... - expect(row?.className).toContain("hover:bg-accent/50"); - expect(link?.className ?? "").not.toContain("hover:bg-accent/50"); - // ...and the overlay link keeps only positioning + focus concerns. - expect(link?.className).toContain("absolute"); - expect(link?.className).toContain("inset-0"); - - act(() => { - root.unmount(); - }); - }); - - describe("recovery chip liveness", () => { - const NOW = new Date("2026-08-18T12:00:00.000Z"); - - beforeEach(() => { - vi.useFakeTimers(); - vi.setSystemTime(NOW); - }); - - afterEach(() => { - vi.useRealTimers(); - }); - - function at(offsetMs: number) { - return new Date(NOW.getTime() + offsetMs).toISOString(); - } - - function recoveryIssue(retryAt: string, scheduledRetry: Issue["scheduledRetry"] = null): Issue { - return createIssue({ - status: "in_progress", - scheduledRetry, - activeRecoveryAction: { - id: "action-1", - companyId: "company-1", - sourceIssueId: "issue-1", - recoveryIssueId: null, - kind: "deliberate_wait_without_target", - status: "active", - ownerType: "agent", - ownerAgentId: "agent-owner", - ownerUserId: null, - previousOwnerAgentId: "agent-owner", - returnOwnerAgentId: "agent-owner", - cause: "deliberate_wait_without_target", - fingerprint: "fp", - evidence: {}, - nextAction: "Record a real next step.", - wakePolicy: { - type: "bounded_owner_disposition_repair", - retryAgentId: "agent-owner", - attempt: 1, - maxAttempts: 5, - retryAt, - scheduledRunId: "run-2", - }, - monitorPolicy: null, - attemptCount: 1, - maxAttempts: 5, - timeoutAt: retryAt, - lastAttemptAt: retryAt, - outcome: null, - resolutionNote: null, - resolvedAt: null, - createdAt: at(-10 * 60_000), - updatedAt: at(-10 * 60_000), - }, - }); - } - - function renderChip(issue: Issue): HTMLElement | null { - const root = createRoot(container); - act(() => { - root.render(); - }); - const chip = container.querySelector( - "[data-testid='issue-row-recovery-indicator']", - ); - const snapshot = chip?.cloneNode(true) as HTMLElement | null; - act(() => { - root.unmount(); - }); - return snapshot; - } - - it.each(["working", "retry_scheduled", "failed"] as const)( - "omits %s system interruption feedback without exposing legacy recovery in list rows", - (state) => { - const root = createRoot(container); - const issue = recoveryIssue(at(3 * 60_000)); - issue.interruption = { - intentId: "saved-input", responsibility: "system", state, - nextRetryAt: state === "retry_scheduled" ? at(3 * 60_000) : null, - canRetry: state === "failed", userAction: null, - sourceRunIds: ["run-1"], observedRunId: "run-1", - }; - try { - for (const presentation of ["task", "legacy"] as const) { - act(() => root.render()); - expect(container.textContent).toContain(issue.title); - expect(container.querySelector("[data-inbox-issue-link]")?.getAttribute("href")).toBe("/issues/PAP-1"); - expect(container.textContent).not.toMatch(/Retry available|Thinking|Trying again soon|Recovery in progress/); - expect(container.querySelector("[data-testid='issue-row-recovery-indicator']")).toBeNull(); - } - } finally { - act(() => root.unmount()); - } - }, - ); - - it("shows native export activity from the action even without a scheduled retry", () => { - const issue = recoveryIssue(at(-5 * 60_000)); - Object.assign(issue.activeRecoveryAction!, { - kind: "active_run_watchdog", cause: "native_finalization_invalid", - wakePolicy: { kind: "resume_native_run", runId: "native-run", notBefore: at(-5 * 60_000) }, - nativeRunActivity: { runId: "native-run", status: "running", workspaceOperationId: "export-operation" }, - }); - const chip = renderChip(issue); - expect(chip?.getAttribute("data-recovery-state")).toBe("in_progress"); - expect(chip?.getAttribute("aria-label")).not.toContain("missed"); - }); - - it("stays calm while the next attempt is still ahead", () => { - const chip = renderChip(recoveryIssue(at(3 * 60_000))); - expect(chip?.getAttribute("data-recovery-state")).toBe("in_progress"); - expect(chip?.getAttribute("aria-label")).toContain("next try in 3m"); - }); - - it("warns once the stored attempt came due and never ran", () => { - // The inbox chip must reach the same verdict as the source card, so a parent scanning - // the inbox is not told recovery is running when nothing is. - const chip = renderChip(recoveryIssue(at(-5 * 60_000))); - expect(chip?.getAttribute("data-recovery-state")).toBe("needed"); - const label = chip?.getAttribute("aria-label") ?? ""; - expect(label).toContain("Recovery needed"); - expect(label).toContain("retry missed 5m ago"); - expect(label).not.toContain("next try"); - }); - - it.each(["task", "legacy"] as const)( - "places the recovery chip immediately after the title in %s list rows", - (presentation) => { - const root = createRoot(container); - act(() => { - root.render( - , - ); - }); - - const titleCluster = container.querySelector('[data-slot="task-row-title-cluster"]'); - const title = titleCluster?.querySelector('[data-slot="task-row-title"]'); - const chip = titleCluster?.querySelector('[data-testid="issue-row-recovery-indicator"]'); - expect(titleCluster).not.toBeNull(); - expect(title).not.toBeNull(); - expect(chip).not.toBeNull(); - if (!title || !chip) throw new Error("Expected the title and recovery chip"); - expect(title.compareDocumentPosition(chip) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); - - act(() => { - root.unmount(); - }); - }, - ); - - it("stays calm when the overdue attempt is a verified live run", () => { - const chip = renderChip( - recoveryIssue(at(-5 * 60_000), { - runId: "run-2", - status: "running", - agentId: "agent-owner", - agentName: "CodexCoder", - retryOfRunId: null, - scheduledRetryAt: at(-5 * 60_000), - scheduledRetryAttempt: 1, - scheduledRetryReason: null, - }), - ); - expect(chip?.getAttribute("data-recovery-state")).toBe("in_progress"); - expect(chip?.getAttribute("aria-label")).toContain("attempt running now"); - }); - }); -}); diff --git a/ui/src/components/MarkdownEditor.autocomplete.test.tsx b/ui/src/components/MarkdownEditor.autocomplete.test.tsx deleted file mode 100644 index 9e5181e2b4f..00000000000 --- a/ui/src/components/MarkdownEditor.autocomplete.test.tsx +++ /dev/null @@ -1,135 +0,0 @@ -// @vitest-environment jsdom - -import { act, useState } from "react"; -import { createRoot } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { $getSelection, $isRangeSelection, getNearestEditorFromDOMNode } from "lexical"; -import { buildSkillMentionHref } from "@paperclipai/shared"; -import { MarkdownEditor, type MentionOption } from "./MarkdownEditor"; -import type { SlashCommandOption } from "../context/EditorAutocompleteContext"; - -const mentions: MentionOption[] = [ - { id: "agent:ada", kind: "agent", agentId: "ada", name: "Ada" }, - { id: "user:pat", kind: "user", userId: "pat", name: "Pat" }, - { id: "project:paperclip", kind: "project", projectId: "paperclip", name: "Paperclip" }, - { id: "issue:task", kind: "issue", issueIdentifier: "TST-123", name: "TST-123 Example task" }, -]; - -const commands: SlashCommandOption[] = [ - { - id: "skill:deploy", kind: "skill", skillId: "deploy", key: "deploy", name: "Deploy", - slug: "deploy", description: null, href: buildSkillMentionHref("deploy", "deploy"), aliases: ["deploy"], - }, - { - id: "routine:nightly", kind: "routine", routineId: "nightly", name: "Nightly", - status: "active", href: "routine://nightly", aliases: ["routine:Nightly"], - }, - { id: "action:goal", kind: "action", command: "goal", name: "Goal", description: "Set a goal", aliases: ["goal"] }, -]; - -describe("MarkdownEditor autocomplete separators", () => { - let container: HTMLDivElement; - let root: ReturnType; - let originalRangeRect: typeof Range.prototype.getBoundingClientRect; - - beforeEach(() => { - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); - vi.stubGlobal("ResizeObserver", class { - observe() {} - unobserve() {} - disconnect() {} - }); - originalRangeRect = Range.prototype.getBoundingClientRect; - Range.prototype.getBoundingClientRect = () => new DOMRect(0, 0, 10, 20); - container = document.createElement("div"); - document.body.append(container); - root = createRoot(container); - }); - - afterEach(async () => { - await act(async () => root.unmount()); - container.remove(); - Range.prototype.getBoundingClientRect = originalRangeRect; - vi.restoreAllMocks(); - vi.unstubAllGlobals(); - }); - - it.each([ - ["skill", "/dep", "/deploy", true, ""], - ["routine", "/routine:Nigh", "/routine:Nightly", true, ""], - ["action", "/go", "/goal", false, ""], - ["agent", "@Ada", "@Ada", true, ""], - ["user", "@Pat", "@Pat", true, ""], - ["project", "@Paper", "@Paperclip", true, ""], - ["task", "@TST", "TST-123", true, ""], - ["project after a typed space", "@Paperclip", "@Paperclip", true, " "], - ["routine after typed spaces", "/routine:Nightly", "/routine:Nightly", true, " "], - ])("keeps a space after a completed %s and types outside its link", async (_kind, value, completion, linked, typedSuffix) => { - const onChange = vi.fn(); - function ControlledEditor() { - const [markdown, setMarkdown] = useState(value); - return { - onChange(next); - setMarkdown(next); - }} actionCommands={commands} mentions={mentions} />; - } - await act(async () => { - root.render(); - }); - - const editable = container.querySelector('[contenteditable="true"]')!; - expect(editable).not.toBeNull(); - await act(async () => { - editable.focus(); - const range = document.createRange(); - range.selectNodeContents(editable.querySelector('[data-lexical-text="true"]')!.firstChild!); - range.collapse(false); - const selection = window.getSelection()!; - selection.removeAllRanges(); - selection.addRange(range); - document.dispatchEvent(new Event("selectionchange")); - }); - if (typedSuffix) { - const editor = getNearestEditorFromDOMNode(editable)!; - await act(async () => { - editor.update(() => { - const selection = $getSelection(); - expect($isRangeSelection(selection)).toBe(true); - if ($isRangeSelection(selection)) selection.insertText(typedSuffix); - }); - }); - await act(async () => document.dispatchEvent(new Event("selectionchange"))); - } - await vi.waitFor(() => expect(document.querySelector('[data-testid="mention-autocomplete-menu"]')).not.toBeNull()); - - await act(async () => { - editable.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true, cancelable: true })); - }); - await vi.waitFor(() => { - expect(editable.textContent).toBe(`${completion} `); - expect(editable.querySelector("a")?.textContent ?? null).toBe(linked ? completion : null); - const caretPrefix = document.createRange(); - caretPrefix.selectNodeContents(editable); - const selection = window.getSelection()!; - caretPrefix.setEnd(selection.anchorNode!, selection.anchorOffset); - expect(caretPrefix.toString()).toBe(`${completion} `); - }); - expect(onChange.mock.lastCall?.[0]).toMatch(/ $/); - expect(onChange.mock.lastCall?.[0]).not.toContain("\u00a0"); - expect(document.querySelector('[data-testid="mention-autocomplete-menu"]')).toBeNull(); - - const editor = getNearestEditorFromDOMNode(editable)!; - await act(async () => { - document.dispatchEvent(new Event("selectionchange")); - editor.update(() => { - const selection = $getSelection(); - expect($isRangeSelection(selection)).toBe(true); - if ($isRangeSelection(selection)) selection.insertText("next"); - }); - }); - expect(editable.textContent).toBe(`${completion} next`); - expect(editable.querySelector("a")?.textContent ?? null).toBe(linked ? completion : null); - expect(onChange.mock.lastCall?.[0]).toMatch(/ next$/); - expect(onChange.mock.lastCall?.[0]).not.toContain("\u00a0"); - }); -}); diff --git a/ui/src/components/QueryView.test.tsx b/ui/src/components/QueryView.test.tsx deleted file mode 100644 index d3a7990337d..00000000000 --- a/ui/src/components/QueryView.test.tsx +++ /dev/null @@ -1,306 +0,0 @@ -// @vitest-environment jsdom - -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { ApiError } from "@/api/client"; -import { ConnectivityProvider, createConnectivityStore, type ConnectivityStore } from "@/lib/connectivity"; -import { QueryErrorState, QueryView, queryViewKind, useQueryView, type QueryViewState } from "./QueryView"; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -const unavailable = () => new ApiError("Paperclip is restarting.", 503, { error: "tenant_app_unavailable" }); -const notFound = () => new ApiError("Issue not found", 404, { error: "Issue not found" }); -const forbidden = () => new ApiError("Forbidden", 403, { error: "Forbidden" }); - -describe("queryViewKind", () => { - const base = { data: undefined, error: null, status: "pending" as const, fetchStatus: "fetching" as const }; - - it("loads, then is ready", () => { - expect(queryViewKind(base)).toBe("loading"); - expect(queryViewKind({ ...base, data: 1, status: "success", fetchStatus: "idle" })).toBe("ready"); - expect(queryViewKind({ ...base, data: 1, status: "success", fetchStatus: "fetching" })).toBe("ready"); - }); - - it("keeps data through a transient failure (stale) and shows an error only for real failures", () => { - expect(queryViewKind({ ...base, data: 1, status: "error", error: unavailable() })).toBe("stale"); - expect(queryViewKind({ ...base, data: 1, status: "error", error: notFound() })).toBe("error"); - expect(queryViewKind({ ...base, data: 1, status: "error", error: forbidden() })).toBe("error"); - }); - - it("reconnects quietly when nothing has loaded yet and the app is waiting out an outage", () => { - expect(queryViewKind({ ...base, status: "error", error: unavailable() }, "reconnecting")).toBe("reconnecting"); - expect(queryViewKind({ ...base, status: "error", error: unavailable() }, "offline")).toBe("reconnecting"); - expect(queryViewKind({ ...base, status: "error", error: new TypeError("Failed to fetch") }, "reconnecting")).toBe("reconnecting"); - expect(queryViewKind({ ...base, status: "error", error: notFound() }, "reconnecting")).toBe("error"); - expect(queryViewKind({ ...base, status: "error", error: new Error("boom") }, "reconnecting")).toBe("error"); - }); - - it("shows retryable copy when a route keeps failing while the server is reachable", () => { - // Nothing would refetch these: the probe loop only runs while the app is - // not online. A placeholder here would never fill in. - expect(queryViewKind({ ...base, status: "error", error: unavailable() })).toBe("error"); - expect(queryViewKind({ ...base, status: "error", error: new ApiError("Gateway timeout", 504, "upstream timed out") })).toBe("error"); - expect(queryViewKind({ ...base, status: "error", error: new TypeError("Failed to fetch") })).toBe("error"); - }); - - it("shows retryable copy for a route-level blip with no data, but keeps data through it", () => { - const busy = new ApiError("Too many requests", 429, { error: "rate_limited" }); - const worker = new ApiError("WORKER_UNAVAILABLE", 503, { code: "WORKER_UNAVAILABLE", message: "restarting" }); - expect(queryViewKind({ ...base, status: "error", error: busy })).toBe("error"); - expect(queryViewKind({ ...base, status: "error", error: worker })).toBe("error"); - expect(queryViewKind({ ...base, status: "error", error: busy }, "reconnecting")).toBe("reconnecting"); - expect(queryViewKind({ ...base, data: 1, status: "error", error: busy })).toBe("stale"); - expect(queryViewKind({ ...base, data: 1, status: "error", error: worker })).toBe("stale"); - }); - - it("treats a paused fetch and in-flight transient retries as an outage", () => { - expect(queryViewKind({ ...base, fetchStatus: "paused" })).toBe("reconnecting"); - expect(queryViewKind({ ...base, failureReason: unavailable() })).toBe("reconnecting"); - expect(queryViewKind({ ...base, data: 1, status: "success", fetchStatus: "paused" })).toBe("stale"); - expect(queryViewKind({ ...base, data: 1, status: "success", failureReason: unavailable() })).toBe("stale"); - }); - - it("follows the app-wide connectivity state", () => { - expect(queryViewKind({ ...base, data: 1, status: "success", fetchStatus: "fetching" }, "reconnecting")).toBe("stale"); - expect(queryViewKind({ ...base, data: 1, status: "success", fetchStatus: "idle" }, "reconnecting")).toBe("stale"); - expect(queryViewKind(base, "offline")).toBe("reconnecting"); - // A disabled query is not waiting on the network. - expect(queryViewKind({ ...base, fetchStatus: "idle" }, "reconnecting")).toBe("loading"); - }); - - it("does not treat null data as missing", () => { - expect(queryViewKind({ ...base, data: null, status: "success", fetchStatus: "idle" })).toBe("ready"); - expect(queryViewKind({ ...base, data: null, status: "error", error: unavailable() })).toBe("stale"); - }); -}); - -type Deferred = { promise: Promise; resolve: (value: T) => void; reject: (error: unknown) => void }; -function deferred(): Deferred { - let resolve!: (value: T) => void; - let reject!: (error: unknown) => void; - const promise = new Promise((nextResolve, nextReject) => { - resolve = nextResolve; - reject = nextReject; - }); - return { promise, resolve, reject }; -} - -describe("useQueryView and ", () => { - let container: HTMLDivElement; - let root: Root; - let client: QueryClient; - let store: ConnectivityStore; - let probe: ReturnType Promise<{ reachable: true }>>>; - let attempts: Deferred<{ title: string }>[]; - let fetchCount: number; - let views: QueryViewState<{ title: string }>[]; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - client = new QueryClient({ defaultOptions: { queries: { retry: false, networkMode: "always" } } }); - probe = vi.fn(async () => ({ reachable: true as const })); - store = createConnectivityStore({ probe, browserOnline: true }); - attempts = []; - fetchCount = 0; - views = []; - }); - - afterEach(() => { - act(() => root.unmount()); - container.remove(); - client.clear(); - store.dispose(); - }); - - function Harness({ staleHint = false, notFound }: { staleHint?: boolean; notFound?: React.ReactNode }) { - const query = useQuery({ - queryKey: ["thing"], - queryFn: () => { - const attempt = deferred<{ title: string }>(); - attempts.push(attempt); - fetchCount += 1; - return attempt.promise; - }, - }); - views.push(useQueryView(query)); - return ( - - {(data) =>

{data.title}

} - - ); - } - - function mount(props: { staleHint?: boolean; notFound?: React.ReactNode } = {}) { - act(() => { - root.render( - - - - - , - ); - }); - } - - const last = () => views[views.length - 1]!; - // React Query batches observer notifications on a timer, so flush macrotasks. - const settle = async () => { - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 0)); - await new Promise((resolve) => setTimeout(resolve, 0)); - }); - }; - - it("shows a placeholder, then the data", async () => { - mount(); - expect(last().kind).toBe("loading"); - expect(container.querySelector('[data-query-view="placeholder"]')).not.toBeNull(); - attempts[0]!.resolve({ title: "Loaded" }); - await settle(); - expect(last().kind).toBe("ready"); - expect(container.querySelector('[data-testid="data"]')?.textContent).toBe("Loaded"); - }); - - it("keeps loaded data on screen when a refetch fails with a transient error", async () => { - mount({ staleHint: true }); - attempts[0]!.resolve({ title: "Loaded" }); - await settle(); - await act(async () => { - void client.refetchQueries({ queryKey: ["thing"] }); - }); - attempts[1]!.reject(unavailable()); - await settle(); - expect(last().kind).toBe("stale"); - expect(last().data).toEqual({ title: "Loaded" }); - expect(container.querySelector('[data-testid="data"]')?.textContent).toBe("Loaded"); - expect(container.querySelector('[data-query-view="stale"]')).not.toBeNull(); - expect(container.querySelector('[data-query-view="error"]')).toBeNull(); - expect(container.querySelector(".text-destructive")).toBeNull(); - }); - - it("shows a quiet placeholder when the first load fails during an outage", async () => { - // The server is down: the probe fails, so the store is reconnecting and - // will refetch every live query on recovery. - probe.mockResolvedValue({ reachable: false, retryAfterMs: null } as unknown as { reachable: true }); - mount(); - attempts[0]!.reject(unavailable()); - store.reportError(unavailable()); - await settle(); - expect(store.getSnapshot().status).toBe("reconnecting"); - expect(last().kind).toBe("reconnecting"); - expect(container.querySelector('[data-query-view="placeholder"]')).not.toBeNull(); - expect(container.querySelector('[data-query-view="error"]')).toBeNull(); - expect(container.textContent).not.toContain("tenant_app_unavailable"); - }); - - it("shows readable copy with Retry when one route keeps failing while the server is reachable", async () => { - // The probe says the server is fine, so no recovery loop will ever refetch - // this query: a placeholder would spin forever. - mount(); - attempts[0]!.reject(unavailable()); - store.reportError(unavailable()); - await settle(); - expect(store.getSnapshot().status).toBe("online"); - expect(last().kind).toBe("error"); - expect(last().errorKind).toBe("transient"); - const alert = container.querySelector('[data-query-view="error"]'); - expect(alert).not.toBeNull(); - expect(alert?.textContent).not.toContain("tenant_app_unavailable"); - expect(alert?.querySelector("button")?.textContent).toContain("Retry"); - expect(container.querySelector('[data-query-view="placeholder"]')).toBeNull(); - await act(async () => { - alert!.querySelector("button")!.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - expect(fetchCount).toBe(2); - attempts[1]!.resolve({ title: "Recovered" }); - await settle(); - expect(last().kind).toBe("ready"); - expect(container.querySelector('[data-testid="data"]')?.textContent).toBe("Recovered"); - }); - - it("shows readable copy and retries for a real error", async () => { - mount(); - attempts[0]!.reject(new ApiError("Request failed: 500", 500, { error: "internal_error" })); - await settle(); - expect(last().kind).toBe("error"); - expect(last().errorKind).toBe("unknown"); - const alert = container.querySelector('[data-query-view="error"]'); - expect(alert?.textContent).toContain("Couldn't load the thing"); - expect(alert?.textContent).not.toContain("internal_error"); - const retry = alert?.querySelector("button"); - expect(retry?.textContent).toContain("Retry"); - await act(async () => { - retry!.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - expect(fetchCount).toBe(2); - attempts[1]!.resolve({ title: "Recovered" }); - await settle(); - expect(last().kind).toBe("ready"); - expect(container.querySelector('[data-testid="data"]')?.textContent).toBe("Recovered"); - }); - - it("renders not_found only for a real 404", async () => { - mount({ notFound:

Gone

}); - attempts[0]!.reject(notFound()); - await settle(); - expect(last().errorKind).toBe("not_found"); - expect(container.querySelector('[data-testid="missing"]')?.textContent).toBe("Gone"); - }); - - it("retry probes the server during an outage", async () => { - mount(); - attempts[0]!.reject(unavailable()); - await settle(); - // The failed query made the store suspect an outage and probe; make the probe fail so the store is reconnecting. - probe.mockResolvedValueOnce({ reachable: false, retryAfterMs: null } as unknown as { reachable: true }); - await settle(); - store.reportError(unavailable()); - await settle(); - probe.mockClear(); - act(() => last().retry()); - expect(fetchCount).toBe(2); - if (store.getSnapshot().status !== "online") expect(probe).toHaveBeenCalled(); - }); -}); - -describe("", () => { - let container: HTMLDivElement; - let root: Root; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - }); - - afterEach(() => { - act(() => root.unmount()); - container.remove(); - }); - - it("uses readable copy and leaves out Retry for errors a retry cannot fix", () => { - act(() => { - root.render( undefined} size="inline" />); - }); - expect(container.textContent).toContain("Forbidden"); - expect(container.querySelector("button")).toBeNull(); - - act(() => { - root.render( undefined} />); - }); - expect(container.textContent).not.toContain("access_denied"); - expect(container.textContent).toContain("permission"); - expect(container.querySelector("button")).toBeNull(); - - act(() => { - root.render( undefined} size="page" />); - }); - expect(container.textContent).not.toContain("stale_revision"); - expect(container.querySelector("button")?.textContent).toContain("Retry"); - }); -}); diff --git a/ui/src/components/ScheduleEditor.test.tsx b/ui/src/components/ScheduleEditor.test.tsx deleted file mode 100644 index e7baa766464..00000000000 --- a/ui/src/components/ScheduleEditor.test.tsx +++ /dev/null @@ -1,133 +0,0 @@ -// @vitest-environment jsdom - -import { useState } from "react"; -import { flushSync } from "react-dom"; -import { createRoot } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { - ScheduleEditor, - buildCron, - getScheduleCronValidation, - parseCronToPreset, -} from "./ScheduleEditor"; - -(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - -function Harness({ - initial, - onChange, - onValidityChange, -}: { - initial: string; - onChange?: (value: string) => void; - onValidityChange?: (valid: boolean) => void; -}) { - const [value, setValue] = useState(initial); - return ( - { - setValue(cron); - onChange?.(cron); - }} - /> - ); -} - -function typeCron(input: HTMLInputElement, value: string) { - const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")?.set; - setter?.call(input, value); - input.dispatchEvent(new Event("input", { bubbles: true })); -} - -function act(callback: () => void) { - flushSync(callback); -} - -describe("ScheduleEditor cron helpers", () => { - it("classifies unknown valid 5-field cron expressions as custom", () => { - expect(parseCronToPreset("0 8-18/2 * * 1-5").preset).toBe("custom"); - expect(getScheduleCronValidation("0 8-18/2 * * 1-5").valid).toBe(true); - }); - - it("still recognizes supported presets and emits their expected cron", () => { - expect(parseCronToPreset("0 10 * * 1-5")).toMatchObject({ - preset: "weekdays", - hour: "10", - minute: "0", - }); - expect(buildCron("weekdays", "8", "15", "1", "1")).toBe("15 8 * * 1-5"); - }); - - it("reports partial cron edits as invalid without treating them as presets", () => { - const validation = getScheduleCronValidation("0 8-18/2 *"); - expect(validation.valid).toBe(false); - expect(validation.message).toContain("5 fields"); - }); -}); - -describe("ScheduleEditor", () => { - let container: HTMLDivElement; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - }); - - afterEach(() => { - container.remove(); - document.body.innerHTML = ""; - }); - - function cronInput() { - return container.querySelector('input[aria-label="Cron expression"]'); - } - - it("renders unknown valid cron expressions in Custom with the original text", () => { - const root = createRoot(container); - act(() => { - root.render(); - }); - - expect(container.textContent).toContain("Custom (cron)"); - expect(cronInput()?.value).toBe("0 8-18/2 * * 1-5"); - expect(container.textContent).toContain("Valid cron."); - - act(() => root.unmount()); - }); - - it("keeps Custom open while partial edits and pasted valid cron values round-trip through parent state", () => { - const onChange = vi.fn(); - const onValidityChange = vi.fn(); - const root = createRoot(container); - act(() => { - root.render( - , - ); - }); - - act(() => { - typeCron(cronInput()!, "0 8-18/2 *"); - }); - expect(cronInput()?.value).toBe("0 8-18/2 *"); - expect(cronInput()?.getAttribute("aria-invalid")).toBe("true"); - expect(container.textContent).toContain("Use exactly 5 fields"); - expect(onChange).not.toHaveBeenCalledWith("0 8-18/2 *"); - expect(onValidityChange).toHaveBeenLastCalledWith(false); - - act(() => { - typeCron(cronInput()!, "0 8-18/2 * * 1-5"); - }); - expect(cronInput()?.value).toBe("0 8-18/2 * * 1-5"); - expect(cronInput()?.getAttribute("aria-invalid")).toBe("false"); - expect(onChange).toHaveBeenLastCalledWith("0 8-18/2 * * 1-5"); - expect(onValidityChange).toHaveBeenLastCalledWith(true); - - act(() => root.unmount()); - }); -}); diff --git a/ui/src/components/SearchableSelect.test.tsx b/ui/src/components/SearchableSelect.test.tsx deleted file mode 100644 index 4b3d4c5ffbf..00000000000 --- a/ui/src/components/SearchableSelect.test.tsx +++ /dev/null @@ -1,539 +0,0 @@ -// @vitest-environment jsdom - -import { flushSync } from "react-dom"; -import { createRoot, type Root } from "react-dom/client"; -import type { ReactNode } from "react"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { SearchableSelect, type SearchableSelectGroup, type SearchableSelectOption } from "./SearchableSelect"; -import { Dialog, DialogContent, DialogTitle } from "./ui/dialog"; -import { - buildReusableExecutionWorkspaceOptionGroups, - reusableWorkspaceOptionMatches, - type ReusableExecutionWorkspaceLike, - type ReusableWorkspaceOption, -} from "@/lib/reusable-execution-workspaces"; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -function act(callback: () => void | Promise) { - let result: void | Promise | undefined; - flushSync(() => { - result = callback(); - }); - return result; -} - -async function flush() { - await act(async () => { - await Promise.resolve(); - }); -} - -function render(node: ReactNode, container: HTMLElement) { - const root = createRoot(container); - act(() => { - root.render(node); - }); - return root; -} - -function setInputValue(input: HTMLInputElement, value: string) { - act(() => { - const valueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")?.set; - valueSetter?.call(input, value); - input.dispatchEvent(new InputEvent("input", { bubbles: true, data: value, inputType: "insertText" })); - }); -} - -function keyDown(target: Element, key: string) { - act(() => { - target.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true })); - }); -} - -function workspace(overrides: Partial): ReusableExecutionWorkspaceLike { - return { - id: overrides.id ?? "workspace-id", - name: overrides.name ?? "Workspace", - cwd: overrides.cwd ?? null, - lastUsedAt: overrides.lastUsedAt ?? "2026-06-24T00:00:00.000Z", - status: overrides.status, - branchName: overrides.branchName, - }; -} - -function buildWorkspaceSelectGroups(workspaces: readonly ReusableExecutionWorkspaceLike[]) { - return buildReusableExecutionWorkspaceOptionGroups(workspaces, { - now: "2026-06-24T12:00:00.000Z", - }).map((group) => ({ - id: group.id, - label: group.label, - options: group.options, - })) satisfies SearchableSelectGroup[]; -} - -describe("SearchableSelect", () => { - let container: HTMLDivElement; - let root: Root | null; - let originalResizeObserver: typeof ResizeObserver | undefined; - - beforeEach(() => { - originalResizeObserver = globalThis.ResizeObserver; - globalThis.ResizeObserver = class ResizeObserver { - observe() {} - unobserve() {} - disconnect() {} - }; - container = document.createElement("div"); - document.body.appendChild(container); - root = null; - }); - - afterEach(() => { - if (root) { - act(() => { - root?.unmount(); - }); - } - globalThis.ResizeObserver = originalResizeObserver!; - container.remove(); - document.body.innerHTML = ""; - }); - - it("renders grouped duplicate options while keeping selection by value", async () => { - const onValueChange = vi.fn(); - const alpha: SearchableSelectOption = { key: "recent:alpha", value: "alpha", label: "Alpha" }; - const groups: SearchableSelectGroup[] = [ - { id: "recent", label: "Recent", options: [alpha] }, - { id: "all", label: "All", options: [{ ...alpha, key: "all:alpha" }] }, - ]; - - root = render( - {option.label}} - />, - container, - ); - - const trigger = container.querySelector("button[role='combobox']") as HTMLButtonElement | null; - expect(trigger?.textContent).toContain("Alpha"); - - act(() => { - trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - await flush(); - - expect(container.querySelector("[data-option-key='recent:alpha']")).not.toBeNull(); - expect(container.querySelector("[data-option-key='all:alpha']")).not.toBeNull(); - expect(container.querySelector("[data-mobile-entity-picker]")).not.toBeNull(); - expect(container.querySelector("[data-mobile-entity-picker-header]")?.textContent).toContain("Pick one"); - expect(container.querySelector('button[aria-label="Close selector"]')).not.toBeNull(); - }); - - it("filters options and returns the selected option object", async () => { - const onValueChange = vi.fn(); - const bravo = { key: "all:bravo", value: "bravo", label: "Bravo", searchText: "secondary branch" }; - const groups: SearchableSelectGroup[] = [ - { - id: "all", - label: "All", - options: [ - { key: "all:alpha", value: "alpha", label: "Alpha", searchText: "primary branch" }, - bravo, - ], - }, - ]; - - root = render( - , - container, - ); - - const trigger = container.querySelector("button[role='combobox']") as HTMLButtonElement | null; - act(() => { - trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - await flush(); - - const input = container.querySelector("input[placeholder='Search options...']") as HTMLInputElement | null; - expect(input).not.toBeNull(); - setInputValue(input!, "sec br"); - await flush(); - - expect(container.textContent).not.toContain("Alpha"); - expect(container.textContent).toContain("Bravo"); - - const bravoItem = Array.from(container.querySelectorAll("[cmdk-item]")).find((item) => item.textContent?.includes("Bravo")); - expect(bravoItem).not.toBeUndefined(); - act(() => { - bravoItem?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - - expect(onValueChange).toHaveBeenCalledWith("bravo", bravo); - }); - - it("ranks visible label matches ahead of lower-quality search text matches", async () => { - const onValueChange = vi.fn(); - const groups: SearchableSelectGroup[] = [ - { - id: "all", - label: "All", - options: [ - { - key: "all:path-only", - value: "path-only", - label: "Paperclip app", - searchText: "/srv/paperclip/mobile-checkout", - }, - { - key: "all:mobile", - value: "mobile", - label: "Mobile agent chat", - searchText: "/srv/paperclip/agent-chat", - }, - ], - }, - ]; - - root = render( - {option.label}} - />, - container, - ); - - const trigger = container.querySelector("button[role='combobox']") as HTMLButtonElement | null; - act(() => { - trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - await flush(); - - const input = container.querySelector("input[placeholder='Search options...']") as HTMLInputElement | null; - expect(input).not.toBeNull(); - setInputValue(input!, "mobile"); - await flush(); - - const renderedKeys = Array.from(container.querySelectorAll("[data-option-key]")).map((item) => - item.getAttribute("data-option-key"), - ); - expect(renderedKeys).toEqual(["all:mobile", "all:path-only"]); - - const commandList = container.querySelector("[data-slot='command-list']"); - expect(commandList?.className).toContain("overscroll-contain"); - expect(commandList?.className).toContain("touch-pan-y"); - }); - - it("applies custom filtering before custom scoring", async () => { - const groups: SearchableSelectGroup[] = [ - { - id: "all", - options: [ - { key: "all:alpha", value: "alpha", label: "Alpha", searchText: "visible" }, - { key: "all:hidden", value: "hidden", label: "Hidden", searchText: "visible" }, - ], - }, - ]; - - root = render( - option.value !== "hidden" && option.searchText === query} - scoreOption={() => 0} - renderOption={(option) => {option.label}} - />, - container, - ); - - const trigger = container.querySelector("button[role='combobox']") as HTMLButtonElement | null; - act(() => { - trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - await flush(); - - const input = container.querySelector("input[placeholder='Search options...']") as HTMLInputElement | null; - expect(input).not.toBeNull(); - setInputValue(input!, "visible"); - await flush(); - - const renderedKeys = Array.from(container.querySelectorAll("[data-option-key]")).map((item) => - item.getAttribute("data-option-key"), - ); - expect(renderedKeys).toEqual(["all:alpha"]); - }); - - it("shows loading, empty, and disabled states", async () => { - const onValueChange = vi.fn(); - - root = render( - , - container, - ); - - const trigger = container.querySelector("button[role='combobox']") as HTMLButtonElement | null; - act(() => { - trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - await flush(); - expect(container.textContent).toContain("Loading choices..."); - - act(() => { - root?.render( - , - ); - }); - const input = container.querySelector("input[placeholder='Search options...']") as HTMLInputElement | null; - expect(input).not.toBeNull(); - setInputValue(input!, "zzz"); - await flush(); - expect(container.textContent).toContain("Nothing matched."); - - act(() => { - root?.render( - , - ); - }); - expect(container.querySelector("button[role='combobox']")?.hasAttribute("disabled")).toBe(true); - }); - - it("opens on focus and closes with Escape", async () => { - root = render( - , - container, - ); - - const trigger = container.querySelector("button[role='combobox']") as HTMLButtonElement | null; - expect(trigger).not.toBeNull(); - act(() => { - trigger?.focus(); - }); - await flush(); - - const input = container.querySelector("input[placeholder='Search options...']") as HTMLInputElement | null; - expect(input).not.toBeNull(); - expect(trigger?.getAttribute("aria-expanded")).toBe("true"); - - keyDown(input!, "Escape"); - await flush(); - - expect(container.querySelector("input[placeholder='Search options...']")).toBeNull(); - expect(trigger?.getAttribute("aria-expanded")).toBe("false"); - - act(() => { - trigger?.dispatchEvent(new Event("pointerdown", { bubbles: true, cancelable: true })); - trigger?.focus(); - trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - await flush(); - - expect(container.querySelector("input[placeholder='Search options...']")).not.toBeNull(); - expect(trigger?.getAttribute("aria-expanded")).toBe("true"); - - const reopenedInput = container.querySelector("input[placeholder='Search options...']") as HTMLInputElement | null; - expect(reopenedInput).not.toBeNull(); - setInputValue(reopenedInput!, "alp"); - await flush(); - - keyDown(reopenedInput!, "Escape"); - await flush(); - - expect(container.querySelector("input[placeholder='Search options...']")).toBeNull(); - expect(trigger?.getAttribute("aria-expanded")).toBe("false"); - }); - - it.each([false, true])("dismisses outside a nested worktree picker (modal=%s) without reopening or closing the task", async (modal) => { - const onValueChange = vi.fn(); - root = render( - - - New task - - - - , - container, - ); - await flush(); - const trigger = document.querySelector('button[role="combobox"]')!; - const outside = document.querySelector('[data-testid="outside-worktree"]')!; - act(() => trigger.click()); - // Radix installs its outside pointer listener after the opening event. - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - const picker = document.querySelector("[data-mobile-entity-picker]")!; - const outsideTarget = modal ? picker.parentElement! : outside; - act(() => { - const pointerDown = new MouseEvent("pointerdown", { bubbles: true, cancelable: true }); - Object.defineProperty(pointerDown, "pointerType", { value: modal ? "touch" : "mouse" }); - outsideTarget.dispatchEvent(pointerDown); - if (!modal) outside.focus(); - outsideTarget.click(); - }); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - expect(document.querySelector("[data-mobile-entity-picker]")).toBeNull(); - expect(document.querySelector("[data-slot=dialog-content]")).not.toBeNull(); - expect(trigger.getAttribute("aria-expanded")).toBe("false"); - expect(trigger.textContent).toContain("New worktree"); - expect(onValueChange).not.toHaveBeenCalled(); - if (modal) expect(document.activeElement).toBe(trigger); - act(() => { - outside.focus(); - trigger.focus(); - }); - await flush(); - expect(document.querySelector("[data-mobile-entity-picker]")).not.toBeNull(); - }); - - it("filters workspace options, moves with arrows, and selects the workspace id with Enter", async () => { - const onValueChange = vi.fn(); - const groups = buildWorkspaceSelectGroups([ - workspace({ - id: "workspace-paperclip", - name: "Paperclip app", - cwd: "/srv/paperclip/home/paperclipai/paperclip/.paperclip/worktrees/PAP-11722-new-existing-workspace-selector", - branchName: "feature/reusable-workspaces", - status: "running", - lastUsedAt: "2026-06-24T10:00:00.000Z", - }), - workspace({ - id: "workspace-marketing", - name: "Marketing site", - cwd: "/srv/paperclip/home/marketing-site", - branchName: "landing-refresh", - status: "idle", - lastUsedAt: "2026-06-20T10:00:00.000Z", - }), - ]); - - root = render( - - value="" - groups={groups} - onValueChange={onValueChange} - placeholder="Choose an existing workspace" - searchPlaceholder="Search workspaces..." - filterOption={(option, query) => reusableWorkspaceOptionMatches(option, query)} - disablePortal - renderOption={(option, { selected }) => ( - - {option.label} - - )} - />, - container, - ); - - const trigger = container.querySelector("button[role='combobox']") as HTMLButtonElement | null; - act(() => { - trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - await flush(); - - const input = container.querySelector("input[placeholder='Search workspaces...']") as HTMLInputElement | null; - expect(input).not.toBeNull(); - expect(container.textContent).toContain("Recent"); - expect(container.textContent).toContain("All workspaces"); - - setInputValue(input!, "pclip reusable"); - await flush(); - - expect(container.textContent).toContain("Paperclip app"); - expect(container.textContent).not.toContain("Marketing site"); - - const selectedOptionKey = () => ( - container.querySelector("[cmdk-item][aria-selected='true'] [data-option-key]")?.getAttribute("data-option-key") - ); - - expect(selectedOptionKey()).toBe("recent:workspace-paperclip"); - keyDown(input!, "ArrowDown"); - await flush(); - expect(selectedOptionKey()).toBe("all:workspace-paperclip"); - - keyDown(input!, "ArrowUp"); - await flush(); - expect(selectedOptionKey()).toBe("recent:workspace-paperclip"); - - keyDown(input!, "ArrowDown"); - await flush(); - keyDown(input!, "Enter"); - await flush(); - - expect(onValueChange).toHaveBeenCalledWith( - "workspace-paperclip", - expect.objectContaining({ - key: "all:workspace-paperclip", - value: "workspace-paperclip", - workspaceId: "workspace-paperclip", - }), - ); - expect(container.querySelector("input[placeholder='Search workspaces...']")).toBeNull(); - expect(trigger?.getAttribute("aria-expanded")).toBe("false"); - - act(() => { - trigger?.focus(); - }); - await flush(); - - expect(container.querySelector("input[placeholder='Search workspaces...']")).toBeNull(); - expect(trigger?.getAttribute("aria-expanded")).toBe("false"); - }); -}); diff --git a/ui/src/components/StandaloneBrowserControls.test.tsx b/ui/src/components/StandaloneBrowserControls.test.tsx deleted file mode 100644 index 829ee5ec13e..00000000000 --- a/ui/src/components/StandaloneBrowserControls.test.tsx +++ /dev/null @@ -1,170 +0,0 @@ -// @vitest-environment jsdom - -import { createRoot } from "react-dom/client"; -import { flushSync } from "react-dom"; -import { afterEach, beforeEach, describe, expect, it } from "vitest"; -import { TooltipProvider } from "@/components/ui/tooltip"; -import { ToastProvider } from "../context/ToastContext"; -import { StandaloneBrowserControls } from "./StandaloneBrowserControls"; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -async function act(callback: () => void | Promise) { - let result: void | Promise = undefined; - flushSync(() => { - result = callback(); - }); - await result; -} - -async function flushReact() { - await act(async () => { - await Promise.resolve(); - await new Promise((resolve) => window.setTimeout(resolve, 0)); - }); -} - -function installMatchMedia(initialMatches: Record = {}) { - type Listener = (event: MediaQueryListEvent) => void; - const queries = new Map }>(); - - function getQuery(query: string) { - let entry = queries.get(query); - if (!entry) { - entry = { matches: initialMatches[query] ?? false, listeners: new Set() }; - queries.set(query, entry); - } - - return { - get matches() { - return entry.matches; - }, - media: query, - addEventListener: (_type: "change", listener: Listener) => { - entry.listeners.add(listener); - }, - removeEventListener: (_type: "change", listener: Listener) => { - entry.listeners.delete(listener); - }, - addListener: (listener: Listener) => { - entry.listeners.add(listener); - }, - removeListener: (listener: Listener) => { - entry.listeners.delete(listener); - }, - } as unknown as MediaQueryList; - } - - Object.defineProperty(window, "matchMedia", { - configurable: true, - value: (query: string) => getQuery(query), - }); - - return { - setMatches(query: string, matches: boolean) { - const entry = queries.get(query) ?? { matches: false, listeners: new Set() }; - entry.matches = matches; - queries.set(query, entry); - entry.listeners.forEach((listener) => listener({ matches, media: query } as MediaQueryListEvent)); - }, - }; -} - -describe("StandaloneBrowserControls", () => { - let container: HTMLDivElement; - const originalMatchMedia = window.matchMedia; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - Object.defineProperty(navigator, "standalone", { configurable: true, value: true }); - }); - - afterEach(() => { - delete (navigator as Navigator & { standalone?: boolean }).standalone; - if (originalMatchMedia) { - Object.defineProperty(window, "matchMedia", { configurable: true, value: originalMatchMedia }); - } else { - Object.defineProperty(window, "matchMedia", { configurable: true, value: undefined }); - } - container.remove(); - document.body.innerHTML = ""; - }); - - it("shows refresh, share, and open-in-browser controls in mobile standalone mode", async () => { - const root = createRoot(container); - - await act(async () => { - root.render( - - - - - , - ); - }); - await flushReact(); - - expect(container.querySelector('[aria-label="Refresh"]')).not.toBeNull(); - expect(container.querySelector('[aria-label="Share"]')).not.toBeNull(); - expect(container.querySelector('[aria-label="Open in Browser"]')).not.toBeNull(); - - await act(async () => { - root.unmount(); - }); - }); - - it("hides controls in normal mobile browser mode", async () => { - Object.defineProperty(navigator, "standalone", { configurable: true, value: false }); - installMatchMedia(); - const root = createRoot(container); - - await act(async () => { - root.render( - - - - - , - ); - }); - await flushReact(); - - expect(container.querySelector('[aria-label="Refresh"]')).toBeNull(); - - await act(async () => { - root.unmount(); - }); - }); - - it("responds to all chromeless display-mode media query changes", async () => { - Object.defineProperty(navigator, "standalone", { configurable: true, value: false }); - const media = installMatchMedia(); - const root = createRoot(container); - - await act(async () => { - root.render( - - - - - , - ); - }); - await flushReact(); - - expect(container.querySelector('[aria-label="Refresh"]')).toBeNull(); - - await act(() => { - media.setMatches("(display-mode: fullscreen)", true); - }); - await flushReact(); - - expect(container.querySelector('[aria-label="Refresh"]')).not.toBeNull(); - - await act(async () => { - root.unmount(); - }); - }); -}); diff --git a/ui/src/components/folders/FolderControls.test.tsx b/ui/src/components/folders/FolderControls.test.tsx deleted file mode 100644 index 6940e0840ae..00000000000 --- a/ui/src/components/folders/FolderControls.test.tsx +++ /dev/null @@ -1,480 +0,0 @@ -// @vitest-environment jsdom - -import { flushSync } from "react-dom"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { FolderListResult } from "@paperclipai/shared"; -import { - AllUnfiledBanner, - BulkBar, - DeleteFolderDialog, - FolderFormDialog, - FolderRail, - MobileFolderSheet, - MoveToMenu, - folderSearchValue, - normalizeFolderSelection, -} from "./FolderControls"; -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu"; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -if (!globalThis.PointerEvent) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (globalThis as any).PointerEvent = MouseEvent; -} -if (!Element.prototype.hasPointerCapture) { - Element.prototype.hasPointerCapture = () => false; -} -if (!Element.prototype.scrollIntoView) { - Element.prototype.scrollIntoView = () => undefined; -} - -function act(callback: () => void | Promise) { - let result: void | Promise | undefined; - flushSync(() => { - result = callback(); - }); - return result; -} - -const folderResult: FolderListResult = { - kind: "routine", - allCount: 4, - unfiledCount: 1, - folders: [ - { - id: "folder-reporting", - companyId: "company-1", - kind: "routine", - parentId: null, - name: "Reporting", - slug: "reporting", - systemKey: null, - path: "reporting", - depth: 1, - color: "indigo", - position: 0, - itemCount: 3, - createdAt: new Date("2026-07-01T00:00:00.000Z"), - updatedAt: new Date("2026-07-01T00:00:00.000Z"), - }, - ], -}; - -const skillFolderResult: FolderListResult = { - kind: "skill", - allCount: 8, - unfiledCount: 1, - folders: [ - { - ...folderResult.folders[0]!, - id: "my", - kind: "skill", - name: "my", - slug: "my", - systemKey: "my", - path: "my", - itemCount: 1, - }, - { - ...folderResult.folders[0]!, - id: "engineering", - kind: "skill", - name: "Engineering", - slug: "engineering", - path: "engineering", - itemCount: 3, - }, - { - ...folderResult.folders[0]!, - id: "code-review", - kind: "skill", - parentId: "engineering", - name: "Code Review", - slug: "code-review", - path: "engineering/code-review", - depth: 2, - itemCount: 2, - }, - { - ...folderResult.folders[0]!, - id: "projects", - kind: "skill", - name: "projects", - slug: "projects", - systemKey: "projects", - path: "projects", - itemCount: 2, - }, - { - ...folderResult.folders[0]!, - id: "bundled", - kind: "skill", - name: "bundled", - slug: "bundled", - systemKey: "bundled", - path: "bundled", - itemCount: 1, - }, - ], -}; - -describe("FolderControls", () => { - let container: HTMLDivElement; - let root: Root | null; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - root = null; - }); - - afterEach(() => { - if (root) { - act(() => { - root?.unmount(); - }); - } - container.remove(); - document.body.innerHTML = ""; - }); - - it("normalizes URL selection values for folder persistence", () => { - expect(normalizeFolderSelection(null)).toBe("all"); - expect(normalizeFolderSelection("unfiled")).toBe("unfiled"); - expect(normalizeFolderSelection("folder-reporting")).toBe("folder-reporting"); - expect(folderSearchValue("all")).toBe(""); - expect(folderSearchValue("unfiled")).toBe("unfiled"); - expect(folderSearchValue("folder-reporting")).toBe("folder-reporting"); - }); - - it("renders All, user folders, and Unfiled with counts and selection callbacks", () => { - const onSelect = vi.fn(); - root = createRoot(container); - - act(() => { - root?.render( - , - ); - }); - - expect(container.textContent).toContain("All routines"); - expect(container.textContent).toContain("Reporting"); - expect(container.textContent).toContain("Unfiled"); - expect(container.textContent).toContain("4"); - expect(container.textContent).toContain("3"); - expect(container.textContent).toContain("1"); - - const reportingButton = Array.from(container.querySelectorAll("button")).find((button) => - button.textContent?.includes("Reporting"), - ); - expect(reportingButton).toBeTruthy(); - - act(() => { - reportingButton?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - - expect(onSelect).toHaveBeenCalledWith("folder-reporting"); - }); - - it("marks the active row with aria-current, including virtual Unfiled", () => { - root = createRoot(container); - act(() => { - root?.render( - , - ); - }); - - const current = container.querySelector('[aria-current="page"]'); - expect(current?.textContent).toContain("Unfiled"); - }); - - it("renames a folder inline via double-click and Enter", () => { - const onRename = vi.fn(); - root = createRoot(container); - act(() => { - root?.render( - , - ); - }); - - const nameButton = Array.from(container.querySelectorAll("button")).find((button) => - button.textContent?.includes("Reporting"), - ); - act(() => { - nameButton?.dispatchEvent(new MouseEvent("dblclick", { bubbles: true, cancelable: true })); - }); - - const input = container.querySelector("input"); - expect(input).toBeTruthy(); - expect(input?.value).toBe("Reporting"); - - act(() => { - if (!input) return; - const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set; - setter?.call(input, "Monthly reports"); - input.dispatchEvent(new Event("input", { bubbles: true })); - }); - act(() => { - input?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); - }); - - expect(onRename).toHaveBeenCalledWith(folderResult.folders[0], "Monthly reports"); - }); - - it("moves via MoveToMenu: Unfiled, a folder, and new-folder chaining", () => { - const onMove = vi.fn(); - const onCreateAndMove = vi.fn(); - root = createRoot(container); - act(() => { - root?.render( - - - - - - - - , - ); - }); - - const subTrigger = Array.from(document.querySelectorAll("[data-radix-collection-item]")).find( - (element) => element.textContent?.includes("Move to"), - ); - expect(subTrigger).toBeTruthy(); - act(() => { - subTrigger?.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true })); - }); - - const menuItems = Array.from(document.querySelectorAll('[role="menuitem"]')); - const unfiledItem = menuItems.find((element) => element.textContent?.includes("Unfiled")); - const folderItem = menuItems.find((element) => element.textContent?.includes("Reporting")); - const newFolderItem = menuItems.find((element) => element.textContent?.includes("New folder")); - expect(unfiledItem).toBeTruthy(); - expect(folderItem).toBeTruthy(); - expect(newFolderItem).toBeTruthy(); - - act(() => { - unfiledItem?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - expect(onMove).toHaveBeenCalledWith(null); - - act(() => { - folderItem?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - expect(onMove).toHaveBeenCalledWith("folder-reporting"); - - act(() => { - newFolderItem?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - expect(onCreateAndMove).toHaveBeenCalled(); - }); - - it("creates a folder through FolderFormDialog and disables submit on empty name", () => { - const onSubmit = vi.fn(); - root = createRoot(container); - act(() => { - root?.render( - , - ); - }); - - const submit = Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent === "Create folder", - ) as HTMLButtonElement | undefined; - expect(submit).toBeTruthy(); - expect(submit?.disabled).toBe(true); - - const nameInput = document.querySelector("#folder-name"); - act(() => { - if (!nameInput) return; - const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set; - setter?.call(nameInput, "Reporting"); - nameInput.dispatchEvent(new Event("input", { bubbles: true })); - }); - - expect(submit?.disabled).toBe(false); - act(() => { - submit?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - expect(onSubmit).toHaveBeenCalledWith({ name: "Reporting", color: expect.any(String) }); - }); - - it("states the forgiving delete behavior and confirms", () => { - const onConfirm = vi.fn(); - root = createRoot(container); - act(() => { - root?.render( - , - ); - }); - - expect(document.body.textContent).toContain("3 routines in this folder won't be deleted"); - expect(document.body.textContent).toContain("They'll move to Unfiled"); - - const confirmButton = Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent === "Delete folder", - ); - act(() => { - confirmButton?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - expect(onConfirm).toHaveBeenCalled(); - }); - - it("selects a folder from the mobile sheet and dismisses", () => { - const onSelect = vi.fn(); - const onOpenChange = vi.fn(); - root = createRoot(container); - act(() => { - root?.render( - , - ); - }); - - expect(document.body.textContent).toContain("All routines"); - expect(document.body.textContent).toContain("Unfiled"); - - const reportingRow = Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.includes("Reporting"), - ); - act(() => { - reportingRow?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - - expect(onSelect).toHaveBeenCalledWith("folder-reporting"); - expect(onOpenChange).toHaveBeenCalledWith(false); - }); - - it("preserves skill root grouping and child hierarchy in the mobile sheet", () => { - root = createRoot(container); - act(() => { - root?.render( - , - ); - }); - - const body = document.body.textContent ?? ""; - expect(body.indexOf("My Skills")).toBeLessThan(body.indexOf("Organization")); - expect(body.indexOf("Organization")).toBeLessThan(body.indexOf("Engineering")); - expect(body.indexOf("Engineering")).toBeLessThan(body.indexOf("Code Review")); - expect(body.indexOf("Code Review")).toBeLessThan(body.indexOf("Projects")); - expect(body.indexOf("Projects")).toBeLessThan(body.indexOf("Bundled")); - expect(document.querySelector('[data-folder-id="engineering"] > .pl-3 [data-folder-id="code-review"]')).not.toBeNull(); - }); - - it("persists AllUnfiledBanner dismissal across mounts", () => { - const storageKey = "paperclip:test-folder-nudge"; - window.localStorage.removeItem(storageKey); - const onCreateFolder = vi.fn(); - root = createRoot(container); - act(() => { - root?.render( - , - ); - }); - - expect(container.textContent).toContain("Create your first folder"); - - const dismissButton = container.querySelector( - 'button[aria-label="Dismiss folder suggestion"]', - ); - act(() => { - dismissButton?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); - }); - - expect(container.textContent).not.toContain("Create your first folder"); - expect(window.localStorage.getItem(storageKey)).toBe("1"); - - act(() => { - root?.unmount(); - }); - root = createRoot(container); - act(() => { - root?.render( - , - ); - }); - expect(container.textContent).not.toContain("Create your first folder"); - window.localStorage.removeItem(storageKey); - }); -}); diff --git a/ui/src/components/folders/SkillFolderTree.test.tsx b/ui/src/components/folders/SkillFolderTree.test.tsx deleted file mode 100644 index 53caaea15b7..00000000000 --- a/ui/src/components/folders/SkillFolderTree.test.tsx +++ /dev/null @@ -1,131 +0,0 @@ -// @vitest-environment jsdom - -import { flushSync } from "react-dom"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { FolderListResult } from "@paperclipai/shared"; -import { SkillFolderRail } from "./SkillFolderTree"; - -function pointerEvent(type: string, clientX: number) { - const event = new MouseEvent(type, { bubbles: true, clientX }); - Object.defineProperty(event, "pointerId", { value: 1 }); - return event; -} - -const result: FolderListResult = { - kind: "skill", - allCount: 12, - unfiledCount: 2, - folders: [ - { - id: "my-root", - companyId: "company-1", - kind: "skill", - parentId: null, - name: "My Skills", - slug: "my", - systemKey: "my", - path: "my", - depth: 1, - color: null, - position: 0, - itemCount: 4, - createdAt: new Date("2026-07-16T00:00:00.000Z"), - updatedAt: new Date("2026-07-16T00:00:00.000Z"), - }, - { - id: "personal-root", - companyId: "company-1", - kind: "skill", - parentId: "my-root", - name: "Ada", - slug: "ada", - systemKey: "my:user-1", - path: "my/ada", - depth: 2, - color: null, - position: 0, - itemCount: 4, - createdAt: new Date("2026-07-16T00:00:00.000Z"), - updatedAt: new Date("2026-07-16T00:00:00.000Z"), - }, - ], -}; - -describe("SkillFolderRail", () => { - let container: HTMLDivElement; - let root: Root; - const onSelect = vi.fn<(selection: string) => void>(); - - beforeEach(() => { - window.localStorage.clear(); - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - onSelect.mockClear(); - flushSync(() => { - root.render( - , - ); - }); - }); - - afterEach(() => { - flushSync(() => root.unmount()); - container.remove(); - window.localStorage.clear(); - }); - - it("uses the wider default and persists drag resizing", () => { - const rail = container.firstElementChild as HTMLDivElement; - const separator = container.querySelector('[role="separator"]') as HTMLDivElement; - expect(rail.style.width).toBe("288px"); - separator.setPointerCapture = vi.fn(); - - flushSync(() => { - separator.dispatchEvent(pointerEvent("pointerdown", 288)); - separator.dispatchEvent(pointerEvent("pointermove", 320)); - separator.dispatchEvent(pointerEvent("pointerup", 320)); - }); - - expect(rail.style.width).toBe("320px"); - expect(window.localStorage.getItem("paperclip.skills.folderRail.width")).toBe("320"); - }); - - it("keeps virtual and folder counts on the same grid column", () => { - const allRow = Array.from(container.querySelectorAll("button")) - .find((button) => button.textContent?.includes("All skills")); - const myLabel = Array.from(container.querySelectorAll("button")) - .find((button) => button.textContent?.includes("My Skills")); - const myRow = myLabel?.parentElement; - - expect(allRow?.className).toContain("grid-cols-(--gtc-folder-row-actions)"); - expect(myRow?.className).toContain("grid-cols-(--gtc-folder-row-actions)"); - expect(allRow?.querySelector(".tabular-nums")?.textContent).toBe("12"); - expect(myRow?.querySelector(".tabular-nums")?.textContent).toBe("4"); - }); - - it("selects and toggles a folder when its row label is clicked", () => { - const myLabel = Array.from(container.querySelectorAll("button")) - .find((button) => button.textContent?.includes("My Skills")); - - expect(container.textContent).not.toContain("Ada"); - flushSync(() => myLabel?.click()); - - expect(onSelect).toHaveBeenCalledWith("my-root"); - expect(container.textContent).toContain("Ada"); - expect(container.querySelector('[aria-label="Collapse folder"]')).not.toBeNull(); - }); -}); diff --git a/ui/src/components/mcp-app/McpAppIssueContext.test.tsx b/ui/src/components/mcp-app/McpAppIssueContext.test.tsx deleted file mode 100644 index a6cee8846cd..00000000000 --- a/ui/src/components/mcp-app/McpAppIssueContext.test.tsx +++ /dev/null @@ -1,100 +0,0 @@ -// @vitest-environment jsdom -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { act, type ReactNode } from "react"; -import { createRoot } from "react-dom/client"; -import { afterEach, describe, expect, it, vi } from "vitest"; -import type { McpAppViewSummary } from "@paperclipai/shared"; - -const list = vi.fn<(issueId: string) => Promise>(); -vi.mock("@/api/mcpApps", () => ({ mcpAppsApi: { list: (issueId: string) => list(issueId) } })); - -const { McpAppIssueProvider, useMcpAppViewsForRun } = await import("./McpAppIssueContext"); - -function view(id: string, runId: string): McpAppViewSummary { - return { - id, issueId: "issue-1", runId, connectionId: "conn-1", applicationName: "Circleback", - toolName: "mcp.circleback:displaymeetings", upstreamToolName: "DisplayMeetings", - resourceUri: "ui://circleback/meetings", toolInput: {}, createdAt: "2026-11-12T00:00:00.000Z", - }; -} - -function wrapper(client: QueryClient) { - return ({ children }: { children: ReactNode }) => ( - - {children} - - ); -} - -(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - -async function renderHook(hook: (props: P) => R, options: { wrapper: (props: { children: ReactNode }) => ReactNode; initialProps?: P }) { - const result = { current: undefined as unknown as R }; - const container = document.createElement("div"); - const root = createRoot(container); - const Wrapper = options.wrapper; - function Probe({ props }: { props: P }) { - result.current = hook(props); - return null; - } - const render = (props: P) => act(() => root.render()); - await render(options.initialProps as P); - return { result, rerender: (props: P) => render(props), unmount: () => act(() => root.unmount()) }; -} - -async function waitFor(check: () => void, timeoutMs = 2000) { - const started = Date.now(); - for (;;) { - try { - check(); - return; - } catch (error) { - if (Date.now() - started > timeoutMs) throw error; - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 10)); }); - } - } -} - -afterEach(() => list.mockReset()); - -describe("useMcpAppViewsForRun", () => { - it("refreshes the task's list once when a live run completes another MCP tool call", async () => { - list.mockResolvedValueOnce([]).mockResolvedValueOnce([view("v1", "run-1")]); - const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); - const { result, rerender } = await renderHook( - ({ refreshKey }: { refreshKey: string }) => useMcpAppViewsForRun("run-1", { refreshKey }), - { wrapper: wrapper(client), initialProps: { refreshKey: "0:running" } }, - ); - await waitFor(() => expect(list).toHaveBeenCalledTimes(1)); - expect(result.current.views).toEqual([]); - await rerender({ refreshKey: "1:running" }); - await waitFor(() => expect(list).toHaveBeenCalledTimes(2)); - await waitFor(() => expect(result.current.views.map((v) => v.id)).toEqual(["v1"])); - await rerender({ refreshKey: "1:running" }); - expect(list).toHaveBeenCalledTimes(2); - }); - - it("refreshes once for a settled reply newer than the loaded list", async () => { - list.mockResolvedValueOnce([]).mockResolvedValue([view("v1", "run-1")]); - const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); - const { result } = await renderHook( - () => useMcpAppViewsForRun("run-1", { notBeforeMs: Date.now() + 60_000 }), - { wrapper: wrapper(client) }, - ); - await waitFor(() => expect(result.current.views.map((v) => v.id)).toEqual(["v1"])); - await new Promise((resolve) => setTimeout(resolve, 20)); - expect(list).toHaveBeenCalledTimes(2); - }); - - it("does not refresh for a reply older than the loaded list", async () => { - list.mockResolvedValue([view("v1", "run-1")]); - const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); - const { result } = await renderHook( - () => useMcpAppViewsForRun("run-1", { notBeforeMs: Date.now() - 60_000 }), - { wrapper: wrapper(client) }, - ); - await waitFor(() => expect(result.current.views).toHaveLength(1)); - await new Promise((resolve) => setTimeout(resolve, 20)); - expect(list).toHaveBeenCalledTimes(1); - }); -}); diff --git a/ui/src/components/mcp-app/McpAppTurnViews.test.tsx b/ui/src/components/mcp-app/McpAppTurnViews.test.tsx deleted file mode 100644 index bee89cdb6c6..00000000000 --- a/ui/src/components/mcp-app/McpAppTurnViews.test.tsx +++ /dev/null @@ -1,111 +0,0 @@ -// @vitest-environment jsdom -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { act } from "react"; -import { createRoot } from "react-dom/client"; -import { afterEach, describe, expect, it, vi } from "vitest"; -import type { McpAppViewSummary } from "@paperclipai/shared"; -import { queryKeys } from "@/lib/queryKeys"; - -const detail = vi.fn(() => new Promise(() => undefined)); -vi.mock("@/api/mcpApps", () => ({ mcpAppsApi: { list: vi.fn(), detail: (...args: unknown[]) => detail(...(args as [])), callTool: vi.fn() } })); - -const { McpAppIssueProvider } = await import("./McpAppIssueContext"); -const { McpAppTurnViews } = await import("./McpAppTurnViews"); - -(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - -function views(count: number): McpAppViewSummary[] { - return Array.from({ length: count }, (_, index) => ({ - id: `00000000-0000-4000-8000-00000000000${index}`, issueId: "issue-1", runId: "run-1", connectionId: "conn-1", - applicationName: "Circleback", toolName: "mcp.circleback:displaymeetings", upstreamToolName: "DisplayMeetings", - resourceUri: "ui://circleback/meetings", toolInput: {}, createdAt: "2026-11-12T00:00:00.000Z", - })); -} - -let observers: Array<{ callback: IntersectionObserverCallback; targets: Element[] }> = []; -class FakeIntersectionObserver { - targets: Element[] = []; - constructor(public callback: IntersectionObserverCallback) { observers.push(this); } - observe(target: Element) { this.targets.push(target); } - disconnect() { this.targets = []; } - unobserve() {} - takeRecords() { return []; } -} - -async function render(input: number | McpAppViewSummary[]) { - const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); - client.setQueryData(queryKeys.mcpApps.views("issue-1"), typeof input === "number" ? views(input) : input); - const container = document.createElement("div"); - const root = createRoot(container); - await act(async () => root.render( - - - , - )); - return { container, root }; -} - -afterEach(() => { - observers = []; - detail.mockClear(); - vi.unstubAllGlobals(); -}); - -describe("McpAppTurnViews", () => { - const identityViews = (): McpAppViewSummary[] => views(4).map((view) => ({ - ...view, - id: `profile-${view.id}`, - applicationName: "GitHub", - toolName: "mcp.github:get-me", - upstreamToolName: "get_me", - resourceUri: "ui://github-mcp-server/get-me", - })); - - it("renders no cards or documents for repeated saved GitHub identity lookups", async () => { - vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver); - const { container, root } = await render(identityViews()); - expect(container.childElementCount).toBe(0); - expect(observers).toHaveLength(0); - expect(detail).not.toHaveBeenCalled(); - await act(async () => root.unmount()); - }); - - it("counts only visible widgets toward the per-run limit", async () => { - vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver); - const { container, root } = await render([...identityViews(), ...views(7)]); - expect(container.querySelectorAll("[data-testid=mcp-app-turn-view]")).toHaveLength(5); - expect(container.textContent).not.toContain("Get me"); - const more = [...container.querySelectorAll("button")].find((button) => button.textContent === "Show 2 more"); - expect(more).toBeTruthy(); - await act(async () => more!.click()); - expect(container.querySelectorAll("[data-testid=mcp-app-turn-view]")).toHaveLength(7); - expect(container.textContent).not.toContain("Get me"); - expect(detail).not.toHaveBeenCalled(); - await act(async () => root.unmount()); - }); - - it("loads a view's document only when it nears the viewport", async () => { - vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver); - vi.stubGlobal("navigation", { addEventListener: () => undefined }); - const { container, root } = await render(2); - expect(container.querySelectorAll("[data-testid=mcp-app-view-placeholder]")).toHaveLength(2); - expect(detail).not.toHaveBeenCalled(); - const first = observers[0]!; - await act(async () => first.callback([{ isIntersecting: true, target: first.targets[0]! } as IntersectionObserverEntry], first as unknown as IntersectionObserver)); - expect(detail).toHaveBeenCalledTimes(1); - expect(container.querySelectorAll("[data-testid=mcp-app-view-placeholder]")).toHaveLength(1); - await act(async () => root.unmount()); - }); - - it("shows five views per run and the rest on request", async () => { - vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver); - const { container, root } = await render(7); - expect(container.querySelectorAll("[data-testid=mcp-app-turn-view]")).toHaveLength(5); - const more = [...container.querySelectorAll("button")].find((button) => button.textContent === "Show 2 more")!; - expect(more).toBeTruthy(); - await act(async () => more.click()); - expect(container.querySelectorAll("[data-testid=mcp-app-turn-view]")).toHaveLength(7); - expect(detail).not.toHaveBeenCalled(); - await act(async () => root.unmount()); - }); -}); diff --git a/ui/src/components/mcp-app/McpAppView.test.tsx b/ui/src/components/mcp-app/McpAppView.test.tsx deleted file mode 100644 index c415d48fcf1..00000000000 --- a/ui/src/components/mcp-app/McpAppView.test.tsx +++ /dev/null @@ -1,131 +0,0 @@ -// @vitest-environment jsdom -import { act } from "react"; -import { createRoot } from "react-dom/client"; -import { afterEach, describe, expect, it, vi } from "vitest"; -vi.mock("@/api/mcpApps", () => ({ mcpAppsApi: { messageSent: vi.fn(async () => ({ commentId: "c1" })) } })); -import type { McpAppViewDetail } from "@paperclipai/shared"; -import { McpAppViewContent, useMcpAppMessageProposal, type McpAppViewContentProps } from "./McpAppView"; -import { McpAppFrame } from "./McpAppFrame"; -import { McpAppIssueProvider } from "./McpAppIssueContext"; -import { mcpAppNavigationGuardSupported } from "./mcp-app-host"; - -(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - -const detail: McpAppViewDetail = { - id: "view-1", issueId: "issue-1", runId: "run-1", connectionId: "conn-1", applicationName: "Circleback", - toolName: "mcp.circleback:displaymeetings", upstreamToolName: "DisplayMeetings", resourceUri: "ui://circleback/meetings", - toolInput: {}, createdAt: "2026-11-12T00:00:00.000Z", - toolResult: { content: [] }, - resource: { uri: "ui://circleback/meetings", html: "

cards

", csp: {}, permissions: {}, prefersBorder: true }, -}; - -async function render(props: Partial = {}) { - const container = document.createElement("div"); - document.body.appendChild(container); - const root = createRoot(container); - await act(async () => root.render( - ({ content: [] })} displayName="Display meetings" {...props} />, - )); - return { container, root }; -} - -function button(label: string): HTMLButtonElement { - const found = [...document.querySelectorAll("button")].find((element) => element.textContent?.trim() === label); - if (!found) throw new Error(`No button "${label}"`); - return found as HTMLButtonElement; -} - -afterEach(() => vi.unstubAllGlobals()); - -describe("McpAppViewContent", () => { - it("does not mount a view where the navigation guard cannot work", async () => { - expect(mcpAppNavigationGuardSupported()).toBe(false); - const { container, root } = await render(); - expect(container.querySelector("iframe")).toBeNull(); - expect(container.textContent).toContain("This browser can't show this app's widget safely."); - await act(async () => root.unmount()); - }); - - it("mounts the view where the Navigation API is available", async () => { - vi.stubGlobal("navigation", { addEventListener: () => undefined }); - const { container, root } = await render(); - expect(container.querySelector("iframe")).not.toBeNull(); - await act(async () => root.unmount()); - }); - - it("shows a view's proposed message under the widget and sends it only on Send", async () => { - vi.stubGlobal("navigation", { addEventListener: () => undefined }); - const onSendProposal = vi.fn(); - const onDismissProposal = vi.fn(); - const { container, root } = await render({ - proposal: { text: "Summarize the Heavybit meeting", status: "pending" }, onSendProposal, onDismissProposal, - }); - const card = container.querySelector("[data-testid=mcp-app-message-proposal]")!; - expect(card.textContent).toContain("Circleback wants to send:"); - expect(card.textContent).toContain("Summarize the Heavybit meeting"); - // The card comes after the widget. - expect(container.querySelector("iframe")!.compareDocumentPosition(card) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); - expect(onSendProposal).not.toHaveBeenCalled(); - await act(async () => button("Dismiss").click()); - expect(onDismissProposal).toHaveBeenCalledTimes(1); - await act(async () => button("Send").click()); - expect(onSendProposal).toHaveBeenCalledTimes(1); - await act(async () => root.unmount()); - container.remove(); - }); - - it("shows the view full screen in a dialog, with one frame at a time", async () => { - vi.stubGlobal("navigation", { addEventListener: () => undefined }); - const onDisplayModeChange = vi.fn(); - const { container, root } = await render({ displayMode: "fullscreen", onDisplayModeChange }); - const dialog = document.querySelector("[data-testid=mcp-app-fullscreen]")!; - expect(dialog).not.toBeNull(); - expect(dialog.querySelectorAll("iframe")).toHaveLength(1); - expect(dialog.querySelector("iframe")!.getAttribute("data-display-mode")).toBe("fullscreen"); - expect(document.querySelectorAll("iframe")).toHaveLength(1); - expect(container.querySelector("[data-testid=mcp-app-view-fullscreen-placeholder]")).not.toBeNull(); - await act(async () => button("Exit full screen").click()); - expect(onDisplayModeChange).toHaveBeenCalledWith("inline"); - await act(async () => root.unmount()); - container.remove(); - }); - - it("starts a new frame when the host's capabilities change, so the view handshakes again", async () => { - const container = document.createElement("div"); - const root = createRoot(container); - const frame = (proposeMessage?: (text: string) => Promise) => ( - ({ content: [] })} proposeMessage={proposeMessage} /> - ); - await act(async () => root.render(frame())); - const first = container.querySelector("iframe"); - await act(async () => root.render(frame(async () => undefined))); - expect(container.querySelector("iframe")).not.toBe(first); - await act(async () => root.unmount()); - }); - - it("retries a failed Send with the same request id, so the comment is posted once", async () => { - const sendMessage = vi.fn() - .mockRejectedValueOnce(new Error("Network error")) - .mockResolvedValueOnce(undefined); - let api: ReturnType | null = null; - function Harness() { - api = useMcpAppMessageProposal("issue-1", "view-1"); - return null; - } - const container = document.createElement("div"); - const root = createRoot(container); - await act(async () => root.render()); - let settled = false; - await act(async () => { void api!.proposeMessage!("Summarize m1").then(() => { settled = true; }); }); - await act(async () => { api!.onSend!(); }); - expect(api!.proposal).toMatchObject({ status: "error" }); - expect(settled).toBe(false); - await act(async () => { api!.onSend!(); }); - expect(sendMessage).toHaveBeenCalledTimes(2); - expect(sendMessage.mock.calls[0]![1]).toBe(sendMessage.mock.calls[1]![1]); - expect(settled).toBe(true); - expect(api!.proposal).toBeNull(); - await act(async () => root.unmount()); - }); -}); diff --git a/ui/src/components/task-chat/ComposerFileDropTarget.test.tsx b/ui/src/components/task-chat/ComposerFileDropTarget.test.tsx deleted file mode 100644 index 19ac1465d27..00000000000 --- a/ui/src/components/task-chat/ComposerFileDropTarget.test.tsx +++ /dev/null @@ -1,226 +0,0 @@ -// @vitest-environment jsdom -import { act, type ReactElement } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { MarkdownEditor } from "../MarkdownEditor"; -import { IssueAttachmentsSection } from "../IssueAttachmentsSection"; -import { ArtifactDropzone } from "../artifacts/ArtifactDropzone"; -import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover"; -import { Dialog, DialogContent, DialogTitle } from "../ui/dialog"; -import { ComposerFileDropTarget } from "./ComposerFileDropTarget"; - -let host: HTMLDivElement; -let root: Root; -const file = new File(["image"], "screenshot.png", { type: "image/png" }); -function render(content: ReactElement) { act(() => root.render(content)); } -function drag(type: string, target: EventTarget = document.body, types = ["Files"], relatedTarget: EventTarget | null = null) { - const event = new MouseEvent(type, { bubbles: true, cancelable: true }); - Object.defineProperties(event, { - dataTransfer: { value: { types, files: types.includes("Files") ? [file] : [], items: types.includes("Files") ? [{ kind: "file", type: file.type, getAsFile: () => file }] : [], dropEffect: "none" } }, - relatedTarget: { value: relatedTarget }, - }); - act(() => { target.dispatchEvent(event); }); - return event; -} -const overlay = () => document.querySelector('[data-testid="composer-file-drop-overlay"]'); -beforeEach(() => { vi.stubGlobal("DragEvent", MouseEvent); host = document.createElement("div"); document.body.append(host); root = createRoot(host); }); -afterEach(() => { act(() => root.unmount()); host.remove(); vi.unstubAllGlobals(); }); - -describe("composer screen file drops", () => { - it("accepts a drop outside the composer exactly once and clears the overlay", () => { - const onFiles = vi.fn(); - render(); - expect(drag("dragenter").defaultPrevented).toBe(true); - expect(overlay()?.textContent).toContain("Drop files to attach"); - expect(drag("dragover").defaultPrevented).toBe(true); - const downstream = vi.fn(); - document.body.addEventListener("drop", downstream, { once: true }); - expect(drag("drop").defaultPrevented).toBe(true); - expect(onFiles).toHaveBeenCalledExactlyOnceWith([file]); - expect(downstream).not.toHaveBeenCalled(); - document.body.removeEventListener("drop", downstream); - expect(overlay()).toBeNull(); - }); - - it("keeps the overlay while moving between children, then clears on exit or cancellation", () => { - render(); - drag("dragenter"); drag("dragenter", host); drag("dragleave", document.body, ["Files"], host); - expect(overlay()).not.toBeNull(); - drag("dragleave", host); - expect(overlay()).toBeNull(); - for (const cancel of ["dragend", "blur"]) { - drag("dragenter"); - act(() => { window.dispatchEvent(new Event(cancel)); }); - expect(overlay()).toBeNull(); - } - }); - - it("clears a nested drag when the pointer leaves the window", () => { - render(); - drag("dragenter"); drag("dragenter", host); - drag("dragleave", document.documentElement); - expect(overlay()).toBeNull(); - }); - - it("preserves description editor file uploads and clears both overlays", async () => { - const onFiles = vi.fn(); const onDropFile = vi.fn().mockResolvedValue(undefined); - render(<> - - ); - const editor = host.querySelector('[contenteditable="true"]')!; - expect(editor).not.toBeNull(); - drag("dragenter"); expect(overlay()).not.toBeNull(); - drag("dragenter", editor); drag("dragover", editor); - expect(overlay()).toBeNull(); - expect(host.textContent).toContain("Drop file to upload"); - const attachment = new File(["notes"], "notes.txt", { type: "text/plain" }); - const event = new MouseEvent("drop", { bubbles: true, cancelable: true }); - Object.defineProperty(event, "dataTransfer", { value: { types: ["Files"], files: [attachment] } }); - await act(async () => { editor.dispatchEvent(event); }); - expect(onDropFile).toHaveBeenCalledExactlyOnceWith(attachment); - expect(onFiles).not.toHaveBeenCalled(); - expect(host.textContent).not.toContain("Drop file to upload"); - expect(overlay()).toBeNull(); - drag("drop"); expect(onFiles).toHaveBeenCalledExactlyOnceWith([file]); - }); - - it("keeps image drops in the description image plugin", async () => { - const onFiles = vi.fn(); - const uploadImage = vi.fn().mockResolvedValue("/description-image.png"); - render(<> - - ); - const editor = host.querySelector('[contenteditable="true"]')!; - drag("dragenter", editor); expect(overlay()).toBeNull(); - expect(host.textContent).toContain("Drop image to upload"); - await act(async () => { drag("drop", editor); }); - expect(uploadImage).toHaveBeenCalledExactlyOnceWith(file); - expect(onFiles).not.toHaveBeenCalled(); - expect(host.textContent).not.toContain("Drop image to upload"); - }); - - it.each(["parent", "readOnly"])("leaves %s editor drops with the composer", (mode) => { - const onFiles = vi.fn(); const onDropFile = vi.fn(); - render(<> - - ); - drag("drop", host.querySelector(".paperclip-mdxeditor-scope")!); - expect(onFiles).toHaveBeenCalledExactlyOnceWith([file]); - expect(onDropFile).not.toHaveBeenCalled(); - }); - - it("preserves the task attachments section drop handler", () => { - const onFiles = vi.fn(); const onDrop = vi.fn(); - render(<> - - ); - const label = Array.from(host.querySelectorAll("h3")).find(item => item.textContent === "Attachments")!; - drag("drop", label); - expect(onDrop).toHaveBeenCalledOnce(); expect(onFiles).not.toHaveBeenCalled(); - }); - - it("ignores text and link drags", () => { - const onFiles = vi.fn(); - render(); - expect(drag("dragenter", host, ["text/plain", "text/uri-list"]).defaultPrevented).toBe(false); - expect(drag("drop", host, ["text/plain"]).defaultPrevented).toBe(false); - expect(overlay()).toBeNull(); - expect(onFiles).not.toHaveBeenCalled(); - }); - - it("gives the open dialog exclusive ownership and restores the task on close", () => { - const taskFiles = vi.fn(); const newFiles = vi.fn(); - const content = (open: boolean, enabled = true) => <> - - {open ? New task : null} - ; - render(content(true)); - drag("dragenter"); - expect(overlay()?.textContent).toContain("your new task"); - drag("drop"); - expect(newFiles).toHaveBeenCalledExactlyOnceWith([file]); - expect(taskFiles).not.toHaveBeenCalled(); - render(content(true, false)); - drag("dragenter"); drag("drop"); - expect(overlay()).toBeNull(); - expect(taskFiles).not.toHaveBeenCalled(); - render(content(false)); - drag("drop"); - expect(taskFiles).toHaveBeenCalledExactlyOnceWith([file]); - }); - - it("does not send files to the underlying task while another dialog is open", () => { - const onFiles = vi.fn(); - render(<>Settings); - drag("dragenter"); drag("drop"); - expect(overlay()).toBeNull(); expect(onFiles).not.toHaveBeenCalled(); - }); - - it.each([false, true])("preserves artifact uploads with an external target: %s", (external) => { - const onFiles = vi.fn(); const onUpload = vi.fn(); - const frame = document.createElement("div"); - const header = document.createElement("button"); - frame.append(header); document.body.append(frame); - try { - render(<> - ); - const destination = external ? header : host.querySelector("[data-artifact-file]")!; - drag("dragenter"); expect(overlay()).not.toBeNull(); - drag("dragenter", destination); drag("dragover", destination); - expect(overlay()).toBeNull(); - expect(document.querySelector("[data-artifact-drop-overlay]")).not.toBeNull(); - expect(drag("drop", destination).defaultPrevented).toBe(true); - expect(onUpload).toHaveBeenCalledExactlyOnceWith([file]); - expect(onFiles).not.toHaveBeenCalled(); - drag("dragenter"); expect(overlay()).not.toBeNull(); drag("drop"); - expect(onFiles).toHaveBeenCalledExactlyOnceWith([file]); - render(
); - expect(frame.hasAttribute("data-file-drop-target")).toBe(false); - } finally { frame.remove(); } - }); - - it("keeps composer drops available while a portaled picker is open", () => { - const onFiles = vi.fn(); - render(<> - ModelChoose model); - const picker = document.querySelector('[data-slot="popover-content"]')!; - expect(picker.getAttribute("role")).toBe("dialog"); - expect(host.contains(picker)).toBe(false); - drag("dragenter"); expect(overlay()).not.toBeNull(); - expect(drag("drop", picker).defaultPrevented).toBe(true); - expect(onFiles).toHaveBeenCalledExactlyOnceWith([file]); - }); - - it("prevents browser navigation while the new task is read-only", () => { - const onFiles = vi.fn(); - render(New task - - ); - expect(drag("dragenter").defaultPrevented).toBe(true); - expect(drag("dragover").defaultPrevented).toBe(true); - expect(drag("drop").defaultPrevented).toBe(true); - expect(overlay()).toBeNull(); expect(onFiles).not.toHaveBeenCalled(); - }); - - it("does not accept drops for a concealed composer", () => { - const onFiles = vi.fn(); - render(
); - drag("dragenter"); drag("drop"); - expect(overlay()).toBeNull(); expect(onFiles).not.toHaveBeenCalled(); - }); - - it("uses the latest callback and clears on disable and unmount", () => { - const previous = vi.fn(); const next = vi.fn(); - render(); - drag("dragenter"); - render(); - expect(overlay()).toBeNull(); drag("drop"); - render(); - drag("drop"); - expect(next).toHaveBeenCalledExactlyOnceWith([file]); expect(previous).not.toHaveBeenCalled(); - drag("dragenter"); render(
); - expect(overlay()).toBeNull(); - expect(drag("drop").defaultPrevented).toBe(false); - }); -}); diff --git a/ui/src/components/task-chat/ComposerRunSettingsPicker.test.tsx b/ui/src/components/task-chat/ComposerRunSettingsPicker.test.tsx deleted file mode 100644 index 2f89c34dfd4..00000000000 --- a/ui/src/components/task-chat/ComposerRunSettingsPicker.test.tsx +++ /dev/null @@ -1,453 +0,0 @@ -// @vitest-environment jsdom -import { sampleHarnesses } from "@/test-support/harness-availability"; - -import { act, useState, type ComponentProps } from "react"; -import { flushSync } from "react-dom"; -import { createRoot } from "react-dom/client"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import type { Agent } from "@paperclipai/shared"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { agentsApi } from "@/api/agents"; -import { ComposerRunSettingsPicker } from "./ComposerRunSettingsPicker"; -import { queryKeys } from "@/lib/queryKeys"; -import type { ComposerRunSettings } from "./composer-run-settings"; -import { getLastComposerEffort, rememberComposerEffort } from "@/lib/recent-composer-effort"; -import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"; - -const agent = { - id: "a1", companyId: "company-1", name: "Clippy", - role: "Engineering Lead", - adapterType: "codex_local", adapterConfig: { model: "gpt-6-sol" }, -} as unknown as Agent; -const options = [{ id: "agent:a1", label: "Clippy" }]; -const agents = new Map([[agent.id, agent]]); -let container: HTMLDivElement | null = null; -let root: ReturnType | null = null; -globalThis.ResizeObserver = class { - observe() {} - disconnect() {} - unobserve() {} -}; -(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - -async function click(label: string) { - const button = document.querySelector(`button[aria-label="${label}"]`) - ?? [...document.querySelectorAll('button[role="option"]')].find((item) => item.textContent?.trim().startsWith(label)); - expect(button).toBeDefined(); - flushSync(() => button!.click()); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); -} - -function render(onAssigneeChange: (value: string) => void, onSettingsChange: () => void, useCatalog = false, props: Partial> = {}, insideDialog = false) { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); - const picker = - - ; - flushSync(() => root!.render(insideDialog ? New task{picker} : picker)); - return queryClient; -} - -beforeEach(() => localStorage.clear()); -afterEach(() => { - vi.restoreAllMocks(); - flushSync(() => root?.unmount()); - root = null; - container?.remove(); - container = null; -}); - -describe("composer assignee picker", () => { - it.each(["antigravity", "copilot"])("applies the Cloud allowlist to saved %s model settings", async acpxAgent => { - const selectedAgent = { ...agent, adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent, model: "saved-model" } } as Agent; - const client = render(vi.fn(), vi.fn(), false, { agents: new Map([[selectedAgent.id, selectedAgent]]) }); - await act(async () => { - client.setQueryData(queryKeys.health, { status: "ok", cloud: { managed: true, availableHarnesses: sampleHarnesses } }); - await new Promise(resolve => setTimeout(resolve, 0)); - }); - expect(document.querySelector('[aria-label="Select model and effort"]') !== null).toBe(acpxAgent === "copilot"); - if (acpxAgent === "copilot") { - await click("Select model and effort"); - expect(document.querySelector('[aria-label="Choose exact model"]')).not.toBeNull(); - } - }); - - it.each([false, true])("allows model and effort changes with a fixed conversation agent (mobile: %s)", async (mobile) => { - const onAssigneeChange = vi.fn(); - const onSettingsChange = vi.fn(); - render(onAssigneeChange, onSettingsChange, false, { allowAssigneeChange: false, mobile, - modelOptionsOverride: [{ id: "gpt-6-astra", label: "GPT-6 Astra" }] }); - expect(container!.querySelector('[aria-label="Select assignee"]')).toBeNull(); - await click("Select model and effort"); - expect(document.querySelector('[aria-label="Choose assignee"]')).toBeNull(); - expect(document.querySelector('input[aria-label="Effort"]')).not.toBeNull(); - await click("Choose exact model"); - await click("GPT-6 Astra"); - expect(onSettingsChange).toHaveBeenLastCalledWith({ model: "gpt-6-astra", effort: "high", fast: false }); - expect(onAssigneeChange).not.toHaveBeenCalled(); - }); - - it.each([false, true])("keeps the trigger stable until the picker closes (mobile: %s)", async (mobile) => { - function ControlledPicker() { - const [settings, setSettings] = useState({ model: "gpt-6-sol", effort: "high", fast: false }); - return setSettings(next! as typeof settings)} - onAssigneeChange={vi.fn()} mobile={mobile} modelOptionsOverride={[{ id: "gpt-6-sol", label: "GPT-6 Sol" }, { id: "gpt-6-astra", label: "GPT-6 Astra" }]} />; - } - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - const queryClient = new QueryClient(); - flushSync(() => root!.render()); - const label = () => container!.querySelector('[data-testid="task-chat-composer-model-label"]')!.textContent; - expect(label()).toBe("GPT-6 Sol"); - await click("Select model and effort"); - expect(label()).toBe("Select model"); - const range = document.querySelector('input[aria-label="Effort"]')!; - flushSync(() => { - Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")!.set!.call(range, "1"); - range.dispatchEvent(new Event("input", { bubbles: true })); - }); - expect(range.getAttribute("aria-valuetext")).toBe("Low"); - expect(label()).toBe("Select model"); - expect(container!.querySelector('[aria-label="Select model and effort"]')!.textContent).not.toContain("Low"); - await click("Choose assignee"); - expect(label()).toBe("Select model"); - await click("Clippy"); - expect(label()).toBe("GPT-6 Sol"); - expect(container!.querySelector('[aria-label="Select model and effort"]')!.textContent).toContain("Low"); - await click("Select model and effort"); - await click("Choose exact model"); - await click("GPT-6 Astra"); - expect(label()).toBe("Select model"); - if (mobile) await click("Close picker"); - else { - await act(async () => { - document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); - await new Promise((resolve) => setTimeout(resolve, 0)); - }); - } - expect(label()).toBe("GPT-6 Astra"); - expect(container!.querySelector('[aria-label="Select model and effort"]')!.textContent).toContain("Low"); - }); - - it.each([ - { mobile: false, view: "settings" as const }, - { mobile: false, view: "models" as const }, - { mobile: false, view: "agents" as const }, - { mobile: true, view: "settings" as const }, - { mobile: true, view: "models" as const }, - { mobile: true, view: "agents" as const }, - ])("allows wheel and touch scrolling in a nested $view picker (mobile: $mobile)", async ({ mobile, view }) => { - render(vi.fn(), vi.fn(), false, { mobile, initialOpen: true, initialView: view }, true); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - const list = document.querySelector(view === "settings" - ? '[data-testid="composer-run-settings-view"]' - : `[role="listbox"][aria-label="${view === "models" ? "Models" : "Assignees"}"]`)!; - expect(list).not.toBeNull(); - list.style.overflowY = "auto"; - Object.defineProperties(list, { - scrollHeight: { configurable: true, value: 1000 }, - clientHeight: { configurable: true, value: 200 }, - }); - const option = list.querySelector("button")!; - const wheel = new WheelEvent("wheel", { bubbles: true, cancelable: true, deltaY: 100 }); - option.dispatchEvent(wheel); - expect(wheel.defaultPrevented).toBe(false); - const touch = (type: string, y: number) => { - const event = new Event(type, { bubbles: true, cancelable: true }); - Object.defineProperties(event, { - touches: { value: [{ clientX: 100, clientY: y }] }, - changedTouches: { value: [{ clientX: 100, clientY: y }] }, - }); - option.dispatchEvent(event); - return event; - }; - touch("touchstart", 150); - expect(touch("touchmove", 100).defaultPrevented).toBe(false); - const outsideWheel = new WheelEvent("wheel", { bubbles: true, cancelable: true, deltaY: 100 }); - document.body.dispatchEvent(outsideWheel); - expect(outsideWheel.defaultPrevented).toBe(true); - }); - - it.each([ - { adapterType: "claude_local", config: {}, label: "Default" }, - { adapterType: "claude_local", config: { model: "claude-opus-5" }, label: "Claude Opus 5" }, - { adapterType: "claude_local", config: { env: { ANTHROPIC_MODEL: "claude-opus-5" } }, label: "Claude Opus 5" }, - { adapterType: "codex_local", config: {}, label: "Default" }, - ])("labels the $adapterType default honestly", ({ adapterType, config, label }) => { - const defaultAgent = { ...agent, adapterType, adapterConfig: config } as Agent; - render(vi.fn(), vi.fn(), false, { settings: null, agents: new Map([[agent.id, defaultAgent]]), - modelOptionsOverride: [{ id: "claude-opus-5", label: "Claude Opus 5" }] }); - expect(container!.querySelector('[data-testid="task-chat-composer-model-label"]')?.textContent).toBe(label); - }); - - it("does not offer effort levels for an unknown Claude default", async () => { - const defaultAgent = { ...agent, adapterType: "claude_local", adapterConfig: {} } as Agent; - render(vi.fn(), vi.fn(), false, { settings: null, agents: new Map([[agent.id, defaultAgent]]), - modelOptionsOverride: [{ id: "claude-opus-5", label: "Claude Opus 5" }] }); - await click("Select model and effort"); - expect(document.querySelector('[aria-label="Effort"]')).toBeNull(); - }); - - it.each([ - { remembered: "high", settings: null, overrides: null, restored: "high" }, - { remembered: "off", settings: null, overrides: null, restored: null }, - { remembered: "high", settings: { model: null, effort: "low", fast: false }, overrides: null, restored: null }, - { remembered: "high", settings: null, overrides: { adapterConfig: { modelReasoningEffort: "low" } }, restored: null }, - ])("restores compatible history ($remembered) without replacing explicit settings", ({ remembered, settings, overrides, restored }) => { - rememberComposerEffort("company-1", remembered); - const onSettingsChange = vi.fn(); - render(vi.fn(), onSettingsChange, false, { settings, overrides }); - if (restored) expect(onSettingsChange).toHaveBeenCalledWith({ model: null, effort: restored, fast: false }); - else expect(onSettingsChange).not.toHaveBeenCalled(); - }); - - it("records effort changes and preserves effort when changing to a compatible model", async () => { - const onSettingsChange = vi.fn(); - render(vi.fn(), onSettingsChange, false, { modelOptionsOverride: [{ id: "gpt-6-astra", label: "GPT-6 Astra" }] }); - await click("Select model and effort"); - const range = document.querySelector('input[aria-label="Effort"]')!; - flushSync(() => { - Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")!.set!.call(range, "1"); - range.dispatchEvent(new Event("change", { bubbles: true })); - range.dispatchEvent(new Event("input", { bubbles: true })); - }); - expect(getLastComposerEffort("company-1")).toBe("low"); - await click("Choose exact model"); - await click("GPT-6 Astra"); - expect(onSettingsChange).toHaveBeenLastCalledWith({ model: "gpt-6-astra", effort: "high", fast: false }); - await click("Reset to agent default"); - expect(getLastComposerEffort("company-1")).toBeNull(); - }); - it("lets the assignee and model use the available composer width", () => { - render(vi.fn(), vi.fn()); - const trigger = container!.querySelector('[data-testid="task-chat-composer-assignee"]'); - const assignee = trigger!.querySelector('[data-testid="task-chat-composer-assignee-label"]'); - const model = container!.querySelector('[data-testid="task-chat-composer-model-label"]'); - - expect(trigger?.className).toContain("max-w-full"); - expect(trigger?.className).not.toContain("max-w-64"); - expect(assignee?.className).toContain("min-w-0"); - expect(assignee?.className).not.toContain("max-w-24"); - expect(model?.className).toContain("min-w-0"); - expect(assignee?.className).toContain("truncate"); - expect(model?.className).toContain("truncate"); - }); - - it("finds assignees by their displayed role and harness", async () => { - render(vi.fn(), vi.fn()); - await click("Select assignee"); - const input = document.querySelector('input[aria-label="Search assignees"]'); - expect(input).not.toBeNull(); - const setValue = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")!.set!; - for (const query of ["Engineering Lead", "Codex"]) { - flushSync(() => { - setValue.call(input, query); - input!.dispatchEvent(new Event("input", { bubbles: true })); - }); - expect([...document.querySelectorAll('button[role="option"]')] - .some((option) => option.textContent?.includes("Clippy"))).toBe(true); - } - }); - - it("offers the Codex CLI catalog instead of unrelated OpenAI API models", async () => { - vi.spyOn(agentsApi, "adapterModels").mockResolvedValueOnce([ - { id: "gpt-6-sol", label: "GPT-6 Sol" }, - { id: "gpt-5.5", label: "GPT-5.5" }, - ]); - render(vi.fn(), vi.fn(), true); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - await click("Select model and effort"); - await click("Choose exact model"); - const options = [...document.querySelectorAll('button[role="option"]')] - .map((item) => item.textContent ?? ""); - expect(options.some((item) => item.includes("gpt-5.5"))).toBe(true); - expect(options.some((item) => item.includes("gpt-6-sol"))).toBe(true); - expect(options.some((item) => item.includes("gpt-image"))).toBe(false); - expect(options.some((item) => item.includes("text-embedding"))).toBe(false); - expect(document.body.textContent).not.toContain("Loading models…"); - }); - - it("shows an instance-declared Codex model list instead of bundled alternatives", async () => { - const loadModels = vi.spyOn(agentsApi, "adapterModels").mockResolvedValueOnce([ - { id: "private-codex", label: "Private Codex" }, - ]); - render(vi.fn(), vi.fn(), true); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - expect(loadModels).toHaveBeenCalledWith("company-1", "codex_local", { - environmentId: null, - provider: undefined, - }); - await click("Select model and effort"); - await click("Choose exact model"); - const choices = [...document.querySelectorAll('button[role="option"]')] - .map((item) => item.textContent ?? ""); - expect(choices.some((item) => item.includes("Private Codex"))).toBe(true); - expect(choices.some((item) => item.includes("GPT-6 Sol"))).toBe(false); - }); - - it.each(["copilot", "antigravity"])("keeps %s discovery passive during reconnect reconciliation and refreshes on opening", async acpxAgent => { - const copilot = { ...agent, adapterType: "paperclip_runner", defaultEnvironmentId: "daytona-1", - adapterConfig: { provider: "acpx", acpxAgent, model: "gpt-5.6-luna" } } as Agent; - const loadModels = vi.spyOn(agentsApi, "adapterModels") - .mockResolvedValueOnce([{ id: "gpt-5.6-luna", label: "Copilot Luna" }]) - .mockResolvedValue([{ id: "gpt-5.6-luna", label: "Updated Copilot Luna" }]); - const client = render(vi.fn(), vi.fn(), true, { agents: new Map([[agent.id, copilot]]), settings: null }); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - expect(loadModels).not.toHaveBeenCalled(); - await act(async () => { await client.invalidateQueries({ type: "active" }, { cancelRefetch: false }); }); - expect(loadModels).not.toHaveBeenCalled(); - await click("Select model and effort"); - expect(loadModels).toHaveBeenCalledTimes(1); - await act(async () => { await client.invalidateQueries({ type: "active" }, { cancelRefetch: false }); }); - expect(loadModels).toHaveBeenCalledTimes(1); - await act(async () => { - document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); - await new Promise((resolve) => setTimeout(resolve, 0)); - }); - await click("Select model and effort"); - expect(loadModels).toHaveBeenCalledTimes(2); - await click("Choose exact model"); - expect(document.body.textContent).toContain("Updated Copilot Luna"); - }); - - it.each([ - { name: "Copilot", acpxAgent: "copilot", provider: "github", method: "api_key", model: "gpt-5.6-luna", label: "Copilot Luna" }, - { name: "Antigravity", acpxAgent: "antigravity", provider: "google", method: "subscription", model: "gemini-exact", label: "Personal Gemini" }, - ] as const)("discovers $name task models with the assignee connection and environment", async ({ acpxAgent, provider, method, model, label }) => { - const binding = { provider, method, mode: "shared", connectionId: "11111111-1111-4111-8111-111111111111", grantId: "33333333-3333-4333-8333-333333333333" } as const; - const selectedAgent = { ...agent, adapterType: "paperclip_runner", defaultEnvironmentId: "daytona-1", - adapterConfig: { provider: "acpx", acpxAgent, model }, runtimeConfig: { aiConnection: binding } } as Agent; - const loadModels = vi.spyOn(agentsApi, "adapterModels").mockResolvedValueOnce([{ id: model, label }]); - render(vi.fn(), vi.fn(), true, { agents: new Map([[agent.id, selectedAgent]]), settings: null }); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - expect(loadModels).not.toHaveBeenCalled(); - await click("Select model and effort"); - expect(loadModels).toHaveBeenCalledWith("company-1", "paperclip_runner", { - environmentId: "daytona-1", provider: "acpx", poolId: undefined, - acpxAgent, agentId: agent.id, aiConnection: binding, - }); - await click("Choose exact model"); - expect(document.body.textContent).toContain(label); - expect(document.body.textContent).not.toContain("Claude Sonnet"); - }); - - it.each(["subscription", "api_key"] as const)("allows an exact Antigravity model absent from its %s catalog", async method => { - const selectedAgent = { ...agent, adapterType: "paperclip_runner", - adapterConfig: { provider: "acpx", acpxAgent: "antigravity", model: "gemini-default" }, - runtimeConfig: { aiConnection: { provider: "google", method, mode: "responsible_user" } } } as Agent; - vi.spyOn(agentsApi, "adapterModels").mockResolvedValue([{ id: "gemini-listed", label: "Listed native model" }]); - const onSettingsChange = vi.fn(); - render(vi.fn(), onSettingsChange, true, { agents: new Map([[agent.id, selectedAgent]]), settings: null, - initialOpen: true, initialView: "models", initialModelSearch: "gemini-custom-exact" }); - await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); - const manual = [...document.querySelectorAll("button")].find(button => button.textContent?.includes("Use exact ID")); - expect(manual?.disabled).toBe(false); - await act(async () => manual!.click()); - expect(onSettingsChange).toHaveBeenLastCalledWith(expect.objectContaining({ model: "gemini-custom-exact" })); - }); - - it("preserves settings when the selected assignee is chosen again", async () => { - const onAssigneeChange = vi.fn(); - const onSettingsChange = vi.fn(); - render(onAssigneeChange, onSettingsChange); - await click("Select assignee"); - await click("Clippy"); - expect(onAssigneeChange).not.toHaveBeenCalled(); - expect(onSettingsChange).not.toHaveBeenCalled(); - expect(document.querySelector('[role="listbox"]')).toBeNull(); - }); - - it("offers No assignee and clears settings when selected", async () => { - const onAssigneeChange = vi.fn(); - const onSettingsChange = vi.fn(); - render(onAssigneeChange, onSettingsChange); - await click("Select assignee"); - await click("No assignee"); - expect(onAssigneeChange).toHaveBeenCalledWith(""); - expect(onSettingsChange).toHaveBeenCalledWith(null); - expect(document.querySelector('[role="listbox"]')).toBeNull(); - }); - - it.each(["", "user:me"])("hides model and effort for %s and opens assignees in one click", async (assigneeValue) => { - const loadModels = vi.spyOn(agentsApi, "adapterModels"); - render(vi.fn(), vi.fn(), true, { - assigneeValue, - currentAssigneeValue: assigneeValue, - options: [...options, { id: "user:me", label: "Me" }], - }); - expect(container!.querySelector('[data-testid="task-chat-composer-model-label"]')).toBeNull(); - expect(container!.querySelector('[aria-label="Select model and effort"]')).toBeNull(); - expect(container!.textContent).not.toContain("Harness default"); - expect(container!.textContent).not.toContain("High"); - await click("Select assignee"); - expect(document.querySelector('[aria-label="Search assignees"]')).not.toBeNull(); - expect(document.querySelector('[aria-label="Effort"]')).toBeNull(); - expect(document.querySelector('[aria-label="Choose exact model"]')).toBeNull(); - expect(document.body.textContent).not.toContain("Choose an agent"); - expect(loadModels).not.toHaveBeenCalled(); - }); - - it.each([false, true])("hides unsupported Muse settings without loading a catalog (mobile: %s)", async (mobile) => { - const loadModels = vi.spyOn(agentsApi, "adapterModels").mockResolvedValue([]); - const onSettingsChange = vi.fn(); - const muse = { ...agent, adapterType: "paperclip_runner", adapterConfig: { provider: "muse", model: "old-model" } } as Agent; - rememberComposerEffort("company-1", "high"); - render(vi.fn(), onSettingsChange, true, { mobile, settings: null, agents: new Map([[muse.id, muse]]) }); - expect(container!.querySelector('[aria-label="Select model and effort"]')).toBeNull(); - expect(container!.querySelector('[data-testid="task-chat-composer-model-label"]')).toBeNull(); - await click("Select assignee"); - expect(document.querySelector('[aria-label="Search assignees"]')).not.toBeNull(); - expect(document.querySelector('[aria-label="Choose exact model"]')).toBeNull(); - expect(document.querySelector('[aria-label="Effort"]')).toBeNull(); - expect(loadModels).not.toHaveBeenCalled(); - expect(onSettingsChange).not.toHaveBeenCalled(); - }); - - it.each([false, true])("removes an open model menu when the same agent switches to Muse (mobile: %s)", async (mobile) => { - const onSettingsChange = vi.fn(); - function ControlledPicker() { - const [muse, setMuse] = useState(false); - const [settings, setSettings] = useState({ model: "gpt-6-sol", effort: "high", fast: true }); - const selectedAgent = muse - ? { ...agent, adapterType: "paperclip_runner", adapterConfig: { provider: "muse" } } as Agent - : agent; - return <> - - { onSettingsChange(next); setSettings(next); }} onAssigneeChange={vi.fn()} mobile={mobile} - modelOptionsOverride={[{ id: "gpt-6-sol", label: "GPT-6 Sol" }]} /> - ; - } - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - flushSync(() => root!.render()); - await click("Select model and effort"); - await click("Choose exact model"); - expect(document.querySelector('[aria-label="Search or paste a model ID"]')).not.toBeNull(); - await click("Switch to Muse"); - expect(container!.querySelector('[aria-label="Select model and effort"]')).toBeNull(); - expect(document.querySelector('[aria-label="Search or paste a model ID"]')).toBeNull(); - expect(document.querySelector('[aria-label="Choose exact model"]')).toBeNull(); - expect(document.querySelector('[aria-label="Effort"]')).toBeNull(); - expect(document.querySelector('[data-testid="model-unavailable"]')?.textContent).toContain("Muse chooses its model and effort"); - expect(onSettingsChange).toHaveBeenCalledOnce(); - expect(onSettingsChange).toHaveBeenCalledWith(null); - }); - - it("opens the assignee list directly on mobile", async () => { - render(vi.fn(), vi.fn(), false, { mobile: true }); - await click("Select assignee"); - expect(document.querySelector('[data-testid="composer-mobile-dialog"]')).not.toBeNull(); - expect(document.querySelector('[aria-label="Search assignees"]')).not.toBeNull(); - expect(document.querySelector('[aria-label="Choose exact model"]')).toBeNull(); - }); -}); diff --git a/ui/src/components/task-chat/TaskChatQueuedMessages.test.tsx b/ui/src/components/task-chat/TaskChatQueuedMessages.test.tsx deleted file mode 100644 index 0f72986da4f..00000000000 --- a/ui/src/components/task-chat/TaskChatQueuedMessages.test.tsx +++ /dev/null @@ -1,705 +0,0 @@ -// @vitest-environment jsdom - -import { act, type ComponentProps } from "react"; -import { flushSync } from "react-dom"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { IssueQueuedCommentQueue } from "@paperclipai/shared"; -import { mergePendingIssueQueuedComments } from "@/lib/issue-queued-comment-queue"; -import { ThemeProvider } from "@/context/ThemeContext"; -import { MemoryRouter } from "@/lib/router"; -import { - reorderQueuedMessageEntries, - TaskChatQueuedMessages, -} from "./TaskChatQueuedMessages"; - -function deferred() { - let resolve!: (value: T) => void; - let reject!: (error: Error) => void; - const promise = new Promise((innerResolve, innerReject) => { - resolve = innerResolve; - reject = innerReject; - }); - return { promise, resolve, reject }; -} - -const queue: IssueQueuedCommentQueue = { - issueId: "issue-1", - queueId: "wake-1", - state: "deferred", - targetRunId: "run-1", - revision: "rev-1", - protocol: "paperclip_runner_v1", - steeringDisposition: "available", - entries: ["First queued message", "Second queued message"].map( - (body, position) => ({ - comment: { - id: `comment-${position + 1}`, - companyId: "company-1", - issueId: "issue-1", - authorType: "user", - authorAgentId: null, - authorUserId: "user-1", - body, - presentation: null, - metadata: null, - createdAt: new Date(), - updatedAt: new Date(), - }, - position, - canEdit: true, - canDiscard: true, - }), - ), -}; - -describe("TaskChatQueuedMessages", () => { - let container: HTMLDivElement; - let root: Root; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - }); - - afterEach(() => { - flushSync(() => root.unmount()); - container.remove(); - }); - - function render( - overrides: Partial> = {}, - ) { - const props = { - queue, - onEdit: vi.fn(), - onReorder: vi.fn().mockResolvedValue(undefined), - onSteer: vi.fn().mockResolvedValue(undefined), - onDiscard: vi.fn().mockResolvedValue(undefined), - ...overrides, - }; - flushSync(() => root.render()); - return props; - } - - it("keeps saved input visible without duplicating the task status", () => { - const message = "Waiting for the previous environment to stop. Your message will start automatically."; - render({ queue: { ...queue, executionWait: { reason: "remote_cleanup", message } } }); - expect(container.textContent).not.toContain(message); - expect(container.textContent).toContain("First queued message"); - render(); - expect(container.textContent).not.toContain(message); - }); - - it("says why a chat message held in the outbox waits, without offering queue actions", () => { - const message = "CEO reached its daily run limit. Your message is saved and sends automatically when the limit resets at 00:00 UTC."; - render({ queue: { ...queue, queueId: null, targetRunId: null, steeringDisposition: "unsupported", - executionWait: { reason: "heartbeat.daily_run_limit", message }, - entries: queue.entries.slice(0, 1).map(entry => ({ ...entry, canEdit: false, canDiscard: false })) } }); - expect([...container.querySelectorAll('p[role="status"]')].map(node => node.textContent)).toEqual([message]); - expect(container.textContent).toContain("First queued message"); - expect(container.querySelector('[data-testid="task-chat-queued-interrupt-comment-1"]')?.disabled ?? true).toBe(true); - expect(container.querySelector('[data-testid="task-chat-queued-discard-comment-1"]')?.disabled).toBe(true); - }); - - it("renders each queued message once as a compact one-line row", () => { - render(); - const pane = container.querySelector( - '[data-testid="task-chat-queued-messages"]', - ); - expect(pane?.classList).toContain("mx-3"); - expect(pane?.classList).toContain("rounded-b-none"); - expect(pane?.classList).toContain("border-b-0"); - expect(pane?.classList).toContain("-mb-px"); - expect( - container.querySelectorAll('[data-testid^="task-chat-queued-message-"]'), - ).toHaveLength(2); - expect(container.textContent).toContain("First queued message"); - expect(container.textContent).toContain("Second queued message"); - }); - - it("renders queued Markdown and screenshot thumbnails without showing image syntax", () => { - const body = "Check **mobile** and *desktop* with `pnpm verify`.\n\n![mobile.png](/api/attachments/mobile/content)\n![desktop.png](/api/attachments/desktop/content)"; - render({ queue: { ...queue, entries: [{ ...queue.entries[0], comment: { ...queue.entries[0].comment, body } }] } }); - const row = container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')!; - expect(row.querySelector("strong")?.textContent).toBe("mobile"); - expect(row.querySelector("em")?.textContent).toBe("desktop"); - expect(row.querySelector("code")?.textContent).toBe("pnpm verify"); - expect([...row.querySelectorAll("img")].map(img => [img.alt, img.getAttribute("src")])).toEqual([ - ["mobile.png", "/api/attachments/mobile/content"], - ["desktop.png", "/api/attachments/desktop/content"], - ]); - expect(row.textContent).not.toContain("!["); - expect(row.textContent).not.toContain("/api/attachments"); - }); - - it("shows a thumbnail for an image-only queued message", () => { - const body = "![screen.png](/api/attachments/screen/content)"; - render({ queue: { ...queue, entries: [{ ...queue.entries[0], comment: { ...queue.entries[0].comment, body } }] } }); - expect(container.querySelector('img[alt="screen.png"]')?.getAttribute("src")).toBe("/api/attachments/screen/content"); - expect(container.textContent).not.toContain(body); - }); - - it("only loads local attachment images and counts the remaining screenshots", () => { - const urls = [ - "/api/attachments/first/content", "/api/assets/second/content?download=0", - "/api/attachments/third/content", "/api/attachments/fourth/content", - "https://other.example/api/attachments/pixel/content", "//other.example/pixel.png", - "javascript:alert", "data:image/png;base64,AAAA", "/other/pixel.png", - "/api/attachments/first/content/extra", "/api/attachments/first/content#fragment", - ]; - const body = urls.map((url, index) => `![screen-${index}](${url})`).join("\n"); - render({ queue: { ...queue, entries: [{ ...queue.entries[0], comment: { ...queue.entries[0].comment, body } }] } }); - const row = container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')!; - expect([...row.querySelectorAll("img")].map(image => image.getAttribute("src"))).toEqual(urls.slice(0, 3)); - expect(row.querySelector('[aria-label="Queued images"]')?.textContent).toBe("+1"); - }); - - it("omits inline images from the compact text without exposing their URLs", () => { - const body = "Check ![inline](/api/attachments/inline/content) then **retry**."; - render({ queue: { ...queue, entries: [{ ...queue.entries[0], comment: { ...queue.entries[0].comment, body } }] } }); - const row = container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')!; - expect(row.querySelector("strong")?.textContent).toBe("retry"); - expect(row.textContent).toContain("Check then retry."); - expect(row.textContent).not.toContain("/api/attachments"); - expect(row.querySelector("img")).toBeNull(); - }); - - it.each(["legacy", "native", "native-plan"] as const)("shows a read-only response and sends it only on click for %s", async (runtime) => { - const entry = { ...queue.entries[0], canEdit: false, canDiscard: false, - comment: { ...queue.entries[0].comment, body: 'Accepted: Build the app\n\n{"revision": "v1"}' }, - source: { kind: "interaction" as const, interactionId: "confirmation-1", interactionKind: "request_confirmation", - requiresFreshSession: runtime === "native-plan" } }; - const props = render({ queue: { ...queue, entries: [entry], - protocol: runtime === "legacy" ? "legacy" : "paperclip_runner_v1" }, - onInterrupt: vi.fn().mockResolvedValue(undefined) }); - expect(props.onSteer).not.toHaveBeenCalled(); - expect(props.onInterrupt).not.toHaveBeenCalled(); - expect(container.textContent).toContain("Accepted: Build the app"); - expect(container.textContent).not.toContain('"revision"'); - expect(container.querySelector('[aria-label^="Reorder"]')?.disabled).toBe(true); - expect(container.querySelector('[data-testid^="task-chat-queued-discard-"]')?.disabled).toBe(true); - expect(reorderQueuedMessageEntries([entry, queue.entries[1]], "comment-1", "comment-2")).toBeNull(); - const action = runtime === "native" ? "steer" : "interrupt"; - await act(async () => { container.querySelector(`[data-testid="task-chat-queued-${action}-comment-1"]`)!.click(); }); - if (action === "steer") expect(props.onSteer).toHaveBeenCalledWith("comment-1", "rev-1"); - else expect(props.onInterrupt).toHaveBeenCalledOnce(); - }); - - it("shows a declined connection request as readable text, never its raw JSON receipt (BUG-08)", () => { - const receipt = JSON.stringify({ interactionId: "slack-1", kind: "connection_intent", status: "rejected", - payload: { serviceSlug: "slack", serviceName: "Slack" }, result: { outcome: "declined" } }, null, 2); - const entry = { ...queue.entries[0], canEdit: false, canDiscard: false, - comment: { ...queue.entries[0].comment, id: "slack-1", body: `Rejected: Connect Slack\n\n${receipt}` }, - source: { kind: "interaction" as const, interactionId: "slack-1", interactionKind: "connection_intent", - summary: "Declined: Slack connection" } }; - render({ queue: { ...queue, entries: [entry], steeringDisposition: "temporarily_unavailable" } }); - const row = container.querySelector('[data-testid="task-chat-queued-message-slack-1"]')!; - const hoverAndLabels = [...row.querySelectorAll("[title], [aria-label]")] - .flatMap((element) => [element.getAttribute("title"), element.getAttribute("aria-label")]) - .filter((text): text is string => Boolean(text)); - expect(hoverAndLabels.length).toBeGreaterThan(0); - for (const text of hoverAndLabels) { - expect(text).not.toContain("{"); - expect(text).not.toContain("interactionId"); - } - expect(row.textContent).toContain("Declined: Slack connection"); - expect(row.querySelector('[title="Declined: Slack connection"]')).not.toBeNull(); - }); - - it("reorders the complete queue and rewrites contiguous positions", () => { - const next = reorderQueuedMessageEntries( - queue.entries, - "comment-2", - "comment-1", - ); - - expect(next?.map((entry) => entry.comment.id)).toEqual([ - "comment-2", - "comment-1", - ]); - expect(next?.map((entry) => entry.position)).toEqual([0, 1]); - }); - - it("removes the selected steering row before the provider acknowledges it", async () => { - const acknowledgement = deferred(); - const props = render({ - onSteer: vi.fn().mockReturnValue(acknowledgement.promise), - }); - await act(async () => { - container - .querySelector( - '[data-testid="task-chat-queued-steer-comment-1"]', - ) - ?.click(); - await Promise.resolve(); - }); - expect(props.onSteer).toHaveBeenCalledWith("comment-1", "rev-1"); - expect( - container.querySelector( - '[data-testid="task-chat-queued-message-comment-1"]', - ), - ).toBeNull(); - expect(container.textContent).toContain("Steering queued message."); - expect( - container.querySelector( - '[data-testid="task-chat-queued-message-comment-2"]', - ), - ).not.toBeNull(); - - await act(async () => { - render({ ...props, queue: { ...queue, entries: [...queue.entries] } }); - }); - expect(container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')).toBeNull(); - - await act(async () => { - acknowledgement.resolve(); - await acknowledgement.promise; - }); - }); - - it("clears the entire interrupt queue immediately and restores it inline on failure", async () => { - let rejectInterrupt!: (error: Error) => void; - const interrupted = new Promise((_, reject) => { rejectInterrupt = reject; }); - const props = render({ queue: { ...queue, protocol: "legacy", steeringDisposition: "unsupported" }, - onInterrupt: vi.fn().mockReturnValue(interrupted) }); - await act(async () => { - container.querySelector('[data-testid="task-chat-queued-interrupt-comment-1"]')!.click(); - }); - expect(props.onInterrupt).toHaveBeenCalledOnce(); - expect(container.querySelector('[data-testid="task-chat-queued-messages"]')).toBeNull(); - await act(async () => { rejectInterrupt(new Error("Connection lost")); await interrupted.catch(() => undefined); }); - expect(container.querySelectorAll('[data-testid^="task-chat-queued-message-"]')).toHaveLength(2); - expect(container.textContent).toContain("Couldn’t interrupt. Message is still queued."); - }); - - it.each(["steer", "interrupt"] as const)("shows a delivery error even when the queue becomes empty while %s is pending", async action => { - const delivery = deferred(); - const props = render({ queue: { ...queue, protocol: action === "interrupt" ? "legacy" : "paperclip_runner_v1" }, - onSteer: vi.fn().mockReturnValue(delivery.promise), onInterrupt: vi.fn().mockReturnValue(delivery.promise) }); - await act(async () => { container.querySelector(`[data-testid="task-chat-queued-${action}-comment-1"]`)!.click(); }); - await act(async () => { render({ ...props, queue: { ...props.queue, revision: "empty-poll", entries: [] } }); }); - await act(async () => { delivery.reject(new Error("Connection lost")); await delivery.promise.catch(() => undefined); }); - const error = action === "steer" ? "Couldn’t steer." : "Couldn’t interrupt."; - expect([...container.querySelectorAll('[role="status"]')].some(status => status.textContent?.includes(error))).toBe(true); - expect(container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')).toBeNull(); - }); - - it("does not restore a message discarded elsewhere while steering was pending", async () => { - let rejectSteer!: (error: Error) => void; - const delivery = new Promise((_, reject) => { rejectSteer = reject; }); - const props = render({ onSteer: vi.fn().mockReturnValue(delivery) }); - await act(async () => { container.querySelector('[data-testid="task-chat-queued-steer-comment-1"]')!.click(); }); - await act(async () => { render({ ...props, queue: { ...queue, revision: "rev-2", entries: [queue.entries[1]] } }); }); - await act(async () => { rejectSteer(new Error("Queue changed")); await delivery.catch(() => undefined); }); - expect(container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')).toBeNull(); - expect(container.querySelector('[data-testid="task-chat-queued-message-comment-2"]')).not.toBeNull(); - expect(container.textContent).toContain("Couldn’t steer."); - }); - - it("keeps a row queued when steering fails and announces the retryable state", async () => { - render({ - onSteer: vi.fn().mockRejectedValue(new Error("steering_timeout")), - }); - await act(async () => { - container - .querySelector( - '[data-testid="task-chat-queued-steer-comment-1"]', - ) - ?.click(); - }); - expect( - container.querySelector( - '[data-testid="task-chat-queued-message-comment-1"]', - ), - ).not.toBeNull(); - expect(container.textContent).toContain( - "Couldn’t steer. Message is still queued.", - ); - }); - - it("disables steering when the provider does not advertise it", () => { - render({ queue: { ...queue, steeringDisposition: "unsupported" } }); - expect( - container.querySelector( - '[data-testid="task-chat-queued-steer-comment-1"]', - )?.disabled, - ).toBe(true); - }); - - it.each(["temporarily_unavailable", "unsupported"] as const)( - "offers an explicit interrupt fallback when native steering is %s", - async (steeringDisposition) => { - const props = render({ - queue: { ...queue, steeringDisposition }, - onInterrupt: vi.fn().mockResolvedValue(undefined), - }); - const interrupt = container.querySelector( - '[data-testid="task-chat-queued-interrupt-comment-1"]', - ); - expect(interrupt).not.toBeNull(); - expect(interrupt!.disabled).toBe(false); - expect(interrupt!.textContent).toContain("Interrupt"); - await act(async () => { interrupt!.click(); }); - expect(props.onInterrupt).toHaveBeenCalledOnce(); - expect(props.onSteer).not.toHaveBeenCalled(); - expect(container.querySelector('[data-testid="task-chat-queued-messages"]')).toBeNull(); - }, - ); - - it("keeps same-turn steering when the provider is available, even with an interrupt callback", async () => { - const props = render({ onInterrupt: vi.fn().mockResolvedValue(undefined) }); - expect(container.querySelector('[data-testid="task-chat-queued-interrupt-comment-1"]')).toBeNull(); - await act(async () => { - container.querySelector('[data-testid="task-chat-queued-steer-comment-1"]')!.click(); - }); - expect(props.onSteer).toHaveBeenCalledWith("comment-1", "rev-1"); - expect(props.onInterrupt).not.toHaveBeenCalled(); - }); - - it("waits for authoritative discard acknowledgement before removing the row", async () => { - const acknowledgement = deferred(); - render({ onDiscard: vi.fn().mockReturnValue(acknowledgement.promise) }); - await act(async () => { - container - .querySelector( - '[data-testid="task-chat-queued-discard-comment-1"]', - ) - ?.click(); - await Promise.resolve(); - }); - expect( - container.querySelector( - '[data-testid="task-chat-queued-message-comment-1"]', - ), - ).not.toBeNull(); - expect(container.textContent).not.toContain("Queued message discarded."); - - await act(async () => { - acknowledgement.resolve(); - await acknowledgement.promise; - }); - expect( - container.querySelector( - '[data-testid="task-chat-queued-message-comment-1"]', - ), - ).toBeNull(); - expect(container.textContent).toContain("Queued message discarded."); - }); - - it.each(["wake-1", null])("keeps a too-late discard visible with an explicit error (queue=%s)", async (queueId) => { - render({ - queue: { ...queue, queueId }, - onDiscard: vi.fn().mockRejectedValue({ - body: { details: { code: "queued_comment_already_dispatching" } }, - }), - }); - await act(async () => { - container - .querySelector( - '[data-testid="task-chat-queued-discard-comment-1"]', - ) - ?.click(); - }); - expect( - container.querySelector( - '[data-testid="task-chat-queued-message-comment-1"]', - ), - ).not.toBeNull(); - expect(container.textContent).toContain( - "Too late to discard: this message is already being sent.", - ); - }); - - it("shows stale revisions without announcing a discard", async () => { - render({ - onDiscard: vi.fn().mockRejectedValue({ - body: { details: { code: "queued_comment_revision_conflict" } }, - }), - }); - await act(async () => { - container - .querySelector( - '[data-testid="task-chat-queued-discard-comment-1"]', - ) - ?.click(); - }); - expect(container.textContent).toContain( - "The queue changed in another session. Review it and try again.", - ); - expect(container.textContent).not.toContain("Queued message discarded."); - }); - - it("can discard a saved message while queue acknowledgement is pending", async () => { - const merged = mergePendingIssueQueuedComments({ - issueId: queue.issueId, - authoritativeQueue: queue, - pendingComments: [{ - comment: { ...queue.entries[0].comment, id: "optimistic-next" }, - targetRunId: queue.targetRunId, - }], - fallbackProtocol: queue.protocol, - })!; - expect(merged.queueId).toBeNull(); - const props = render({ queue: merged }); - const discard = container.querySelector( - '[data-testid="task-chat-queued-discard-comment-1"]', - ); - expect(discard?.disabled).toBe(false); - expect(container.querySelector( - '[data-testid="task-chat-queued-steer-comment-1"]', - )?.disabled).toBe(true); - await act(async () => { discard!.click(); }); - expect(props.onDiscard).toHaveBeenCalledWith("comment-1", "rev-1"); - expect(container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')).toBeNull(); - }); - - it("keeps another author's saved message protected while acknowledgement is pending", () => { - const props = render({ - queue: { - ...queue, - queueId: null, - entries: [{ ...queue.entries[0], canDiscard: false }], - }, - }); - const discard = container.querySelector( - '[data-testid="task-chat-queued-discard-comment-1"]', - ); - expect(discard?.disabled).toBe(true); - discard!.click(); - expect(props.onDiscard).not.toHaveBeenCalled(); - }); - - it("can discard a local optimistic row before the queue id is acknowledged", async () => { - const optimisticQueue = { - ...queue, - queueId: null, - state: "deferred" as const, - entries: [ - { - ...queue.entries[0], - comment: { - ...queue.entries[0].comment, - id: "optimistic-local-1", - }, - }, - ], - }; - const props = render({ queue: optimisticQueue }); - - await act(async () => { - container - .querySelector( - '[data-testid="task-chat-queued-discard-optimistic-local-1"]', - ) - ?.click(); - }); - - expect(props.onDiscard).toHaveBeenCalledWith("optimistic-local-1", "rev-1"); - expect( - container.querySelector( - '[data-testid="task-chat-queued-message-optimistic-local-1"]', - ), - ).toBeNull(); - }); - - it("delivers legacy queued messages to a live target", async () => { - const targetRunId = "run-1"; - const onInterrupt = vi.fn().mockResolvedValue(undefined); - render({ - queue: { - ...queue, - targetRunId, - protocol: "legacy", - steeringDisposition: "unsupported", - }, - onInterrupt, - }); - - await act(async () => { - container - .querySelector( - '[data-testid="task-chat-queued-interrupt-comment-1"]', - ) - ?.click(); - }); - - expect(onInterrupt).toHaveBeenCalledOnce(); - expect( - container.querySelector( - '[data-testid="task-chat-queued-steer-comment-1"]', - ), - ).toBeNull(); - expect( - container.querySelector( - '[data-testid="task-chat-queued-message-comment-1"]', - ), - ).toBeNull(); - }); - it("keeps deferred sends visible and explains their current wait", async () => { - const saved = { ...queue, targetRunId: null, executionWait: { reason: "decision_pending", message: "Resolve the pending approval before sending." } }; - const onInterrupt = vi.fn().mockResolvedValue(saved); - render({ queue: saved, onInterrupt }); - await act(async () => { container.querySelector('[data-testid="task-chat-queued-interrupt-comment-1"]')!.click(); }); - expect(container.textContent).toContain("First queued message"); - expect(container.textContent).toContain(saved.executionWait.message); - expect(container.querySelector('[data-testid="task-chat-queued-interrupt-comment-1"]')?.disabled).toBe(false); - }); - it("shows an Interrupt as sent while the stopped turn hands off, with no wait or error text", async () => { - const handoff = { ...queue, targetRunId: null, - executionWait: { reason: "interrupt_handoff", message: "Sending your messages." } }; - const onInterrupt = vi.fn().mockResolvedValue(handoff); - render({ queue: { ...queue, steeringDisposition: "temporarily_unavailable" }, onInterrupt }); - await act(async () => { container.querySelector('[data-testid="task-chat-queued-interrupt-comment-1"]')!.click(); }); - // A poll during the hand-off still lists the saved messages. - render({ queue: handoff, onInterrupt }); - await act(async () => {}); - expect(container.textContent).not.toContain("First queued message"); - expect(container.textContent).not.toContain("Sending your messages."); - expect(container.textContent).not.toContain("Couldn’t"); - expect(container.querySelector('[data-testid="task-chat-queued-messages"]')).toBeNull(); - }); - it("clears a deferred wait message when a refreshed queue finishes sending", async () => { - const saved = { ...queue, targetRunId: null, executionWait: { reason: "decision_pending", message: "Resolve the pending approval before sending." } }; - render({ queue: saved, onInterrupt: vi.fn().mockResolvedValue(saved) }); - await act(async () => { container.querySelector('[data-testid="task-chat-queued-interrupt-comment-1"]')!.click(); }); - expect(container.textContent).toContain(saved.executionWait.message); - render({ queue: { ...saved, queueId: null, entries: [], state: null, executionWait: null } }); - await act(async () => {}); - expect(container.textContent).not.toContain(saved.executionWait.message); - expect(container.querySelector('[data-testid="task-chat-queued-messages"]')).toBeNull(); - }); - it.each(["legacy", "paperclip_runner_v1"] as const)("sends a saved %s queue explicitly after Stop", async (protocol) => { - const onInterrupt = vi.fn().mockResolvedValue(undefined); - render({ queue: { ...queue, targetRunId: null, protocol, steeringDisposition: "temporarily_unavailable" }, onInterrupt }); - expect(onInterrupt).not.toHaveBeenCalled(); - const send = container.querySelector('[data-testid="task-chat-queued-interrupt-comment-1"]'); - expect(send?.textContent).toBe("Send"); - expect(send?.getAttribute("aria-label")).toBe("Send queued messages"); - expect(send?.disabled).toBe(false); - await act(async () => { send!.click(); }); - expect(onInterrupt).toHaveBeenCalledOnce(); - expect(container.querySelector('[data-testid="task-chat-queued-steer-comment-1"]')).toBeNull(); - }); - - - describe("automatic steering", () => { - const delay = 5_000; - const fresh = (overrides: Partial = {}): IssueQueuedCommentQueue => { - const at = new Date(Date.now()); - return { ...queue, ...overrides, entries: queue.entries.slice(0, 1).map(entry => ({ - ...entry, comment: { ...entry.comment, createdAt: at, updatedAt: at } })) }; - }; - const advance = async (ms: number) => { await act(async () => { vi.advanceTimersByTime(ms); await Promise.resolve(); }); }; - const countdown = () => container.querySelector('[data-testid="task-chat-queued-auto-steer-comment-1"]'); - - beforeEach(() => { vi.useFakeTimers({ now: new Date("2026-11-07T12:00:00Z") }); }); - afterEach(() => { vi.useRealTimers(); }); - - it("shows a countdown with Edit and Cancel, then steers into the live turn", async () => { - const props = render({ queue: fresh(), autoSteerDelayMs: delay }); - expect(countdown()?.textContent).toContain("Sending in 5s"); - expect(container.querySelector('[data-testid="task-chat-queued-steer-comment-1"]')).toBeNull(); - await advance(2_100); - expect(countdown()?.textContent).toContain("Sending in 3s"); - expect(props.onSteer).not.toHaveBeenCalled(); - await advance(3_000); - expect(props.onSteer).toHaveBeenCalledOnce(); - expect(props.onSteer).toHaveBeenCalledWith("comment-1", "rev-1"); - }); - - it("gives a saved edit a full window while another row's countdown keeps the clock running", async () => { - const start = Date.now(); - const twoRows: IssueQueuedCommentQueue = { ...queue, entries: queue.entries.slice(0, 2).map((entry, index) => { - const at = new Date(start + index * 4_000); - return { ...entry, comment: { ...entry.comment, createdAt: at, updatedAt: at } }; - }) }; - // comment-1 counts down first; the person opens it for editing at 1 s. - const props = render({ queue: twoRows, autoSteerDelayMs: delay }); - await advance(1_000); - await act(async () => { render({ ...props, editingCommentId: "comment-1" }); }); - // comment-2 counts down to start + 9 s and keeps the clock ticking past - // comment-1's old deadline. - await advance(5_000); - expect(props.onSteer).not.toHaveBeenCalled(); - const saved = { ...twoRows, revision: "rev-2", entries: twoRows.entries.map((entry, index) => index === 0 - ? { ...entry, comment: { ...entry.comment, body: "Edited", updatedAt: new Date(Date.now()) } } : entry) }; - await act(async () => { render({ ...props, queue: saved, editingCommentId: null }); }); - await advance(500); - expect(props.onSteer).not.toHaveBeenCalledWith("comment-1", expect.anything()); - expect(countdown()?.textContent).toContain("Sending in"); - await advance(5_000); - expect(props.onSteer).toHaveBeenCalledWith("comment-1", "rev-2"); - }); - - it("keeps a cancelled message in the queue with its explicit Steer button", async () => { - const props = render({ queue: fresh(), autoSteerDelayMs: delay }); - await act(async () => { - container.querySelector('[data-testid="task-chat-queued-auto-steer-cancel-comment-1"]')?.click(); - await Promise.resolve(); - }); - await advance(10_000); - expect(props.onSteer).not.toHaveBeenCalled(); - expect(countdown()).toBeNull(); - expect(container.querySelector('[data-testid="task-chat-queued-steer-comment-1"]')).not.toBeNull(); - }); - - it("waits while the message is being edited and restarts from the saved revision", async () => { - const queued = fresh(); - const props = render({ queue: queued, autoSteerDelayMs: delay }); - await act(async () => { - container.querySelector('[data-testid="task-chat-queued-auto-steer-edit-comment-1"]')?.click(); - await Promise.resolve(); - }); - expect(props.onEdit).toHaveBeenCalledWith("comment-1"); - render({ ...props, editingCommentId: "comment-1" }); - await advance(10_000); - expect(props.onSteer).not.toHaveBeenCalled(); - // The save changes the comment; its countdown starts again from that change. - const saved = { ...queued, revision: "rev-2", entries: queued.entries.map(entry => ({ - ...entry, comment: { ...entry.comment, body: "Edited", updatedAt: new Date(Date.now()) } })) }; - await act(async () => { render({ ...props, queue: saved, editingCommentId: null }); }); - expect(countdown()?.textContent).toContain("Sending in 5s"); - await advance(5_100); - expect(props.onSteer).toHaveBeenCalledWith("comment-1", "rev-2"); - }); - - it("keeps the ordinary queue while steering is unavailable or unsupported", async () => { - for (const steeringDisposition of ["temporarily_unavailable", "unsupported"] as const) { - const props = render({ queue: fresh({ steeringDisposition }), autoSteerDelayMs: delay }); - expect(countdown()).toBeNull(); - await advance(10_000); - expect(props.onSteer).not.toHaveBeenCalled(); - } - }); - - it("tries each message revision once, then leaves it queued after a failure", async () => { - const props = render({ queue: fresh(), autoSteerDelayMs: delay, onSteer: vi.fn().mockRejectedValue(new Error("rejected")) }); - await advance(5_100); - await advance(10_000); - expect(props.onSteer).toHaveBeenCalledOnce(); - expect(container.textContent).toContain("Couldn’t steer. Message is still queued."); - expect(countdown()).toBeNull(); - }); - - it("never sends someone else’s message or a saved card response automatically", async () => { - const notMine = fresh(); - notMine.entries = notMine.entries.map(entry => ({ ...entry, canEdit: false })); - const card = fresh(); - card.entries = card.entries.map(entry => ({ ...entry, source: { kind: "interaction", summary: "Approved" } as never })); - for (const candidate of [notMine, card]) { - const props = render({ queue: candidate, autoSteerDelayMs: delay }); - await advance(10_000); - expect(props.onSteer).not.toHaveBeenCalled(); - } - }); - - it("stays off unless the caller enables it", async () => { - const props = render({ queue: fresh() }); - expect(countdown()).toBeNull(); - await advance(10_000); - expect(props.onSteer).not.toHaveBeenCalled(); - }); - }); -}); diff --git a/ui/src/components/task-chat/TaskChatRunnerTurn.test.tsx b/ui/src/components/task-chat/TaskChatRunnerTurn.test.tsx deleted file mode 100644 index a79889ab350..00000000000 --- a/ui/src/components/task-chat/TaskChatRunnerTurn.test.tsx +++ /dev/null @@ -1,1712 +0,0 @@ -// @vitest-environment jsdom - -import type { ExecutionProjection } from "@paperclipai/shared"; -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { ThemeProvider } from "@/context/ThemeContext"; -import { MemoryRouter } from "@/lib/router"; -import { TaskChatRunnerTurn } from "./TaskChatRunnerTurn"; -import { TaskChatRequestHistoryContext } from "./TaskChatComposerTakeoverContext"; -import { transcriptToTaskChatItems } from "./transcript-adapter"; -import type { - TaskChatItem, - TaskChatProviderActivityFamily, - TaskChatProviderActivityItem, - TaskChatRuntimeRequestDecision, - TaskChatRuntimeRequestItem, -} from "./task-chat-model"; - -describe("TaskChatRunnerTurn", () => { - let container: HTMLDivElement; - let root: Root; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - }); - - afterEach(() => { - act(() => root.unmount()); - container.remove(); - }); - - const render = ( - items: TaskChatItem[], - status = "running", - runId: string | null = "run-1", - onRuntimeRequestDecision?: ( - item: TaskChatRuntimeRequestItem, - decision: TaskChatRuntimeRequestDecision, - ) => void, - awaitingContinuation = false, - continuedAfterSteering = false, - execution?: ExecutionProjection, - preparationLabel?: string, - ) => - act(() => - root.render( - - - - - - - , - ), - ); - - it.each([null, "run-1"].flatMap(runId => [false, true].map(projected => ({ runId, projected }))))( - "shows Working and Thinking during ordinary admission (runId=$runId, projected=$projected)", - ({ runId, projected }) => { - render([], "queued", runId, undefined, false, false, projected ? { - phase: "queued", label: "Queued", cause: null, - lastConfirmedActivityAt: null, retryAt: null, attempt: 1, maxAttempts: 3, - recoveryOwner: null, nextAction: null, permittedActions: ["inspect_run"], - predecessorRunId: null, successorRunId: null, - } : undefined); - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent).toContain("Working"); - if (!runId) { - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent).toBe("Working"); - } - const activity = container.querySelector('[data-testid="task-chat-current-activity-label"]'); - expect(activity?.textContent).toBe("Thinking"); - expect(activity?.classList.contains("shimmer-text")).toBe(true); - expect(container.textContent).not.toContain("Queued"); - }, - ); - - it("preserves a specific preparation label before a run ID exists", () => { - render([], "queued", null, undefined, false, false, undefined, "Preparing workspace"); - expect(container.querySelector('[data-testid="task-chat-current-activity-label"]')?.textContent).toBe("Preparing workspace"); - }); - - it.each([ - ["task_drain", "Waiting for maintenance"], - ["agent_setup_pending", "Waiting for agent setup"], - ["agent_setup_failed", "Agent setup needs attention"], - ["server_restarting", "Waiting for server restart"], - ["previous_run_settling", "Waiting for previous run to stop"], - ["routine_execution_in_progress", "Waiting for PAP-5656 to finish"], - ])("shows the server's %s wait while admission is held", (cause, label) => { - render([], "queued", "run-1", undefined, false, false, { - phase: "queued", label, cause, - lastConfirmedActivityAt: null, retryAt: null, attempt: 1, maxAttempts: 3, - recoveryOwner: null, nextAction: "Starts automatically when maintenance finishes.", - permittedActions: ["inspect_run"], predecessorRunId: null, successorRunId: null, - }); - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent).toContain(label); - expect(container.textContent?.split(label)).toHaveLength(2); - expect(container.querySelector('[data-testid="task-chat-current-activity"]')).toBeNull(); - expect(container.textContent).not.toContain("Thinking"); - }); - - it("keeps startup feedback briefly, then says a queued turn with no named hold is waiting to start", () => { - vi.useFakeTimers(); - try { - vi.setSystemTime(new Date("2026-11-13T17:39:05Z")); - render([], "queued"); - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent).toContain("Working"); - expect(container.querySelector('[data-testid="task-chat-current-activity-label"]')?.textContent).toBe("Thinking"); - // The fixture's run was queued 2 s before render: the grace ends at +28 s. - act(() => { vi.advanceTimersByTime(27_000); }); - expect(container.textContent).not.toContain("Waiting to start"); - act(() => { vi.advanceTimersByTime(2_000); }); - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent).toContain("Waiting to start"); - expect(container.textContent?.split("Waiting to start")).toHaveLength(2); - expect(container.querySelector('[data-testid="task-chat-current-activity"]')).toBeNull(); - expect(container.textContent).not.toContain("Working"); - } finally { - vi.useRealTimers(); - } - }); - - it("does not repeat the agent's waiting line in the turn body", () => { - // The shared header (rendered by the thread) shows the waiting line; the body adds no second line. - act(() => root.render( - - - , - )); - expect(container.textContent).not.toContain("Waiting for Codie"); - expect(container.querySelector('[data-testid="task-chat-current-activity"]')).toBeNull(); - }); - - it("does not call a running turn waiting, however long it runs", () => { - vi.useFakeTimers(); - try { - render([], "running"); - act(() => { vi.advanceTimersByTime(10 * 60_000); }); - expect(container.textContent).not.toContain("Waiting to start"); - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent).toContain("Working"); - } finally { - vi.useRealTimers(); - } - }); - - const resolvedQuestion = ( - id: string, - prompt: string, - ): TaskChatRuntimeRequestItem => ({ - id, - kind: "protocol", - surface: "runtime_request", - runId: "run-1", - requestId: id, - requestKind: "user_input", - turnId: "turn-1", - requestType: "input", - status: "resolved", - prompt: "Codex needs your input.", - choices: [], - fields: [], - questionSet: { - schema: "paperclip.question_set.v1", - questions: [ - { id: `${id}-field`, prompt, required: true, answerMode: "text" }, - ], - }, - response: { - schema: "paperclip.question_response.v1", - answers: { [`${id}-field`]: { text: "Answered" } }, - }, - }); - - it("shows a stable Working header with Thinking at the turn tail", () => { - render([], "running"); - expect(container.textContent).toContain("Thinking"); - expect(container.textContent).toContain("Runner"); - expect( - container.querySelector( - '[data-testid="task-chat-runner-disclosure-caret"]', - ), - ).toBeNull(); - expect( - container.querySelector( - '[data-testid="task-chat-current-activity-icon"]', - ), - ).toBeNull(); - expect( - container.querySelector( - '[data-testid="task-chat-current-activity-label"]', - )?.textContent, - ).toBe("Thinking"); - expect( - container.querySelector('[data-testid="task-chat-current-activity"]') - ?.tagName, - ).toBe("DIV"); - expect( - container.querySelector('[data-testid="task-chat-turn-status-header"]') - ?.textContent, - ).toContain("Working for"); - expect(container.textContent).not.toContain("Waiting for transcript"); - const identity = container.querySelector( - '[data-testid="task-chat-agent-identity"]', - ); - const status = container.querySelector( - '[data-testid="task-chat-turn-status-header"]', - ); - const identityRow = container.querySelector( - '[data-testid="task-chat-runner-identity-row"]', - ); - const activity = container.querySelector( - '[data-testid="task-chat-current-activity"]', - ); - expect(identity?.parentElement).toBe(identityRow); - expect(status?.parentElement).toBe(identityRow); - expect(status?.getAttribute("data-turn-position")).toBe("identity"); - expect(identity?.compareDocumentPosition(activity!)).toBe( - Node.DOCUMENT_POSITION_FOLLOWING, - ); - expect(activity?.getAttribute("data-turn-position")).toBe("tail"); - expect(activity?.classList.contains("px-1")).toBe(true); - expect(activity?.firstElementChild?.hasAttribute("aria-hidden")).toBe( - false, - ); - }); - - it.each(["reconnecting", "retry_scheduled"] as const)( - "keeps the active turn and Thinking tail visible with a %s projection", - (phase) => { - const execution = { phase } as ExecutionProjection; - render([], "running", "run-1", undefined, false, false, execution); - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent) - .toContain("Working for"); - expect(container.querySelector('[data-testid="task-chat-current-activity-label"]')?.textContent) - .toBe("Thinking"); - render([], "succeeded", "run-1", undefined, false, false, execution); - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent) - .toContain("Worked"); - expect(container.querySelector('[data-testid="task-chat-current-activity"]')).toBeNull(); - render([], "failed", "run-1", undefined, false, false, execution); - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent) - .toContain("Stopped"); - expect(container.textContent).not.toContain("Reconnecting"); - }, - ); - - it.each(["Muse", "Dot"])("shows Waiting for %s until native acceptance, without a Thinking claim", provider => { - const waiting = { phase: "waiting_for_provider", label: `Waiting for ${provider}` } as ExecutionProjection; - render([], "running", "run-1", undefined, false, false, waiting); - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent) - .toContain(`Waiting for ${provider}`); - const tail = container.querySelector('[data-testid="task-chat-current-activity-label"]'); - expect(tail?.textContent).toBe(`Waiting for ${provider}`); - expect(tail?.classList.contains("shimmer-text")).toBe(false); - expect(container.textContent).not.toContain("Working"); - expect(container.textContent).not.toContain("Thinking"); - - // Re-render the same live turn after the native acceptance projection changes. - render([], "running", "run-1", undefined, false, false, - { phase: "working", label: "Working" } as ExecutionProjection); - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent) - .toContain("Working for"); - expect(container.querySelector('[data-testid="task-chat-current-activity-label"]')?.textContent) - .toBe("Thinking"); - - // A stale waiting projection must never override a terminal run outcome. - render([], "failed", "run-1", undefined, false, false, waiting); - expect(container.querySelector('[data-testid="task-chat-turn-status-header"]')?.textContent) - .toContain("Stopped"); - expect(container.querySelector('[data-testid="task-chat-current-activity"]')).toBeNull(); - expect(container.textContent).not.toContain(`Waiting for ${provider}`); - }); - - it("labels the streaming tail as a continuation after steering", () => { - render([], "running", "run-1", undefined, false, true); - - expect( - container.querySelector('[data-testid="task-chat-turn-status-header"]') - ?.textContent, - ).toContain("Continued after steering · Working for"); - }); - - it("renders completed progress exactly once when the live run returns to Thinking", () => { - const text = "Understood—I’ll use a two-second wait instead."; - const items = transcriptToTaskChatItems( - [ - { - kind: "thinking", - ts: "2026-09-04T13:39:20.000Z", - text: "", - lifecycle: "started", - channel: "summary", - itemId: "reasoning-1", - }, - { - kind: "thinking", - ts: "2026-09-04T13:39:20.100Z", - text: "", - lifecycle: "completed", - channel: "summary", - itemId: "reasoning-1", - }, - { - kind: "assistant", - ts: "2026-09-04T13:39:21.100Z", - text, - channel: "progress", - itemId: "message-1", - }, - ], - { runId: "run-1", agentName: "Runner", running: true }, - ); - - render(items); - - expect(container.textContent?.split(text)).toHaveLength(2); - expect( - container.querySelector('[data-testid="task-chat-phase-interstitial"]') - ?.textContent, - ).toContain(text); - expect( - container.querySelector('[data-testid="task-chat-live-narration"]'), - ).toBeNull(); - expect( - container.querySelector( - '[data-testid="task-chat-current-activity-label"]', - )?.textContent, - ).toBe("Thinking"); - }); - - it("keeps progress mounted above its grouped current command", () => { - render([ - { - id: "p1", - kind: "message", - author: "agent", - text: "Running the exact command now.", - interstitial: true, - channel: "progress", - streaming: true, - }, - { - id: "t1", - kind: "tool", - name: "command", - rawName: "Bash", - target: "for i in 1 2 3 4; do echo STREAM-$i; done", - status: "in_progress", - detail: "STREAM-1\n", - }, - ]); - const commentary = container.querySelector('[data-testid="task-chat-phase-interstitial"]'); - const activity = container.querySelector('[data-testid="task-chat-activity-viewport"]'); - expect(commentary?.textContent).toContain("Running the exact command now."); - expect(activity?.textContent).toContain("Running$ "); - expect(activity?.textContent).toContain("STREAM-$i"); - expect(container.querySelector('[data-testid="task-chat-current-activity"]')).toBeNull(); - expect(commentary?.compareDocumentPosition(activity!)).toBe(Node.DOCUMENT_POSITION_FOLLOWING); - - }); - - it("keeps the timer at the top and moves resumed Thinking below completed activity", () => { - render([ - { - id: "commentary", - kind: "message", - author: "agent", - text: "I’ll inspect the workspace.", - interstitial: true, - channel: "progress", - }, - { - id: "tool", - kind: "tool", - name: "Command", - rawName: "bash", - status: "completed", - }, - { - id: "thinking", - kind: "thinking", - lines: [], - lifecycleOnly: true, - streaming: true, - }, - ]); - - const header = container.querySelector('[data-testid="task-chat-turn-status-header"]'); - const activity = container.querySelector('[data-testid="task-chat-activity-viewport"]'); - expect(header?.textContent).toContain("Working for"); - expect(activity?.textContent).toBe("Thinking"); - expect(header?.compareDocumentPosition(activity!)).toBe(Node.DOCUMENT_POSITION_FOLLOWING); - expect(container.querySelector('[data-testid="task-chat-current-activity"]')).toBeNull(); - - }); - - it("keeps earlier commentary mounted when later commentary streams", () => { - render([ - { - id: "commentary", - kind: "message", - author: "agent", - text: "I’ll inspect the card.", - interstitial: true, - channel: "progress", - transcriptIndex: 1, - }, - { - id: "reasoning", - kind: "thinking", - lines: ["The saved preview can be reused."], - streaming: true, - channel: "summary", - transcriptIndex: 2, - }, - ]); - expect( - container.querySelector('[data-testid="task-chat-phase-interstitial"]') - ?.textContent, - ).toContain("I’ll inspect the card."); - - render([ - { - id: "commentary", - kind: "message", - author: "agent", - text: "I’ll inspect the card.", - interstitial: true, - channel: "progress", - transcriptIndex: 1, - }, - { - id: "reasoning", - kind: "thinking", - lines: ["The saved preview can be reused."], - streaming: true, - channel: "summary", - transcriptIndex: 2, - }, - { - id: "commentary-later", - kind: "message", - author: "agent", - text: "I’ve found the rendering seam.", - interstitial: true, - channel: "progress", - transcriptIndex: 3, - }, - ]); - const commentary = container.querySelectorAll( - '[data-testid="task-chat-phase-interstitial"]', - ); - expect(commentary).toHaveLength(2); - expect(commentary[0]?.textContent).toContain("I’ll inspect the card."); - expect(commentary[1]?.textContent).toContain( - "I’ve found the rendering seam.", - ); - expect( - container.querySelector('[data-testid="task-chat-runner-activity-list"]'), - ).toBeNull(); - act(() => - container - .querySelector( - '[data-testid="task-chat-activity-phase-toggle"]', - ) - ?.click(), - ); - expect( - container.querySelector('[data-testid="task-chat-runner-activity-list"]') - ?.textContent, - ).toContain("Thought"); - }); - - it("keeps the latest provider-authored reasoning line visible while activity is folded", () => { - render([ - { - id: "reasoning", - kind: "thinking", - lines: ["Inspecting the task state.", "Checking the steering path."], - streaming: true, - channel: "summary", - transcriptIndex: 2, - }, - ]); - - const ticker = container.querySelector( - '[data-testid="task-chat-activity-viewport"]', - ); - expect(ticker?.textContent).toContain("Checking the steering path."); - expect( - container.querySelector('[data-testid="task-chat-runner-activity-list"]'), - ).toBeNull(); - }); - - it("keeps a visible fallback when completion tools are filtered before the final reply", () => { - render([{ id: "finish", kind: "tool", name: "paperclip_finish", status: "in_progress" }]); - expect(container.querySelector('[data-testid="task-chat-current-activity"]')?.textContent).toContain("Thinking"); - expect(container.querySelector('[data-testid="task-chat-activity-phase"]')).toBeNull(); - render([{ id: "finish-provider", kind: "protocol", surface: "provider_activity", family: "tool_execution", eventType: "tool.execution.started", status: "running", title: "Finish", details: [{ label: "Name", value: "paperclip_finish" }], steps: [], links: [], children: [] }]); - expect(container.querySelector('[data-testid="task-chat-current-activity"]')?.textContent).toContain("Thinking"); - expect(container.querySelector('[data-testid="task-chat-activity-phase"]')).toBeNull(); - }); - - it("surfaces native activity transport failure while retrying", () => { - act(() => - root.render( - - - - - , - ), - ); - - expect( - container.querySelector('[data-testid="task-chat-activity-unavailable"]') - ?.textContent, - ).toContain("temporarily unavailable"); - }); - - it("starts a separate activity group at every commentary boundary", () => { - render([ - { - id: "commentary-one", - kind: "message", - author: "agent", - text: "First phase.", - interstitial: true, - channel: "progress", - }, - { - id: "tool-one", - kind: "tool", - name: "Read", - rawName: "read_file", - status: "completed", - }, - { - id: "commentary-two", - kind: "message", - author: "agent", - text: "Second phase.", - interstitial: true, - channel: "progress", - }, - { - id: "tool-two", - kind: "tool", - name: "Bash", - rawName: "bash", - status: "completed", - }, - ]); - const rows = container.querySelectorAll( - '[data-testid="task-chat-turn-timeline-row"]', - ); - expect(rows).toHaveLength(2); - expect(rows[0]?.textContent).toContain("First phase."); - expect(rows[0]?.textContent).toContain("Read file"); - expect(rows[1]?.textContent).toContain("Second phase."); - expect(rows[1]?.textContent).toContain("Ran a command"); - act(() => - rows[0] - ?.querySelector( - '[data-testid="task-chat-activity-phase-toggle"]', - ) - ?.click(), - ); - expect( - rows[0] - ?.querySelector('[data-activity-icon] svg') - ?.parentElement?.classList.contains("size-5"), - ).toBe(true); - }); - - it("keeps internal reasoning nested inside its activity group", () => { - render([ - { - id: "summary", - kind: "thinking", - lines: ["Inspect the current card."], - streaming: false, - channel: "summary", - transcriptIndex: 1, - }, - { - id: "detail", - kind: "thinking", - lines: ["Keep the canonical revision atomic."], - streaming: true, - channel: "detail", - transcriptIndex: 2, - }, - ]); - expect( - container.querySelectorAll('[data-testid="task-chat-thinking"]'), - ).toHaveLength(0); - act(() => - container - .querySelector( - '[data-testid="task-chat-activity-phase-toggle"]', - ) - ?.click(), - ); - const history = container.querySelector('[data-testid="task-chat-runner-activity-list"]'); - expect(container.querySelector('[data-testid="task-chat-runner-activity-rail"]')).toBeNull(); - expect(history?.querySelectorAll("li")).toHaveLength(2); - expect(history?.textContent).toContain("ThoughtInspect the current card."); - expect(history?.textContent).toContain("ThinkingKeep the canonical revision atomic."); - expect(container.querySelector('[data-testid="task-chat-runner-activity-detail"]')).toBeNull(); - - }); - - it("renders only the current reasoning block as active", () => { - render([ - { - id: "old-reasoning", - kind: "thinking", - lines: ["Inspect the current card."], - streaming: true, - transcriptIndex: 1, - }, - { - id: "read", - kind: "tool", - name: "Read files", - rawName: "Read", - status: "completed", - }, - { - id: "current-reasoning", - kind: "thinking", - lines: ["Verify the updated state."], - streaming: true, - transcriptIndex: 3, - }, - ]); - - act(() => - container - .querySelector( - '[data-testid="task-chat-activity-phase-toggle"]', - ) - ?.click(), - ); - - expect(container.querySelector('[data-activity-item-id="old-reasoning"]')?.textContent).toContain("ThoughtInspect the current card."); - expect(container.querySelector('[data-activity-item-id="current-reasoning"]')?.textContent).toContain("ThinkingVerify the updated state."); - - }); - - it("does not let a textless reasoning lifecycle remove sticky commentary", () => { - render([ - { - id: "commentary", - kind: "message", - author: "agent", - text: "Old commentary", - interstitial: true, - channel: "progress", - transcriptIndex: 1, - }, - { - id: "reasoning", - kind: "thinking", - lines: [], - lifecycleOnly: true, - streaming: true, - transcriptIndex: 2, - }, - ]); - expect( - container.querySelector('[data-testid="task-chat-phase-interstitial"]') - ?.textContent, - ).toContain("Old commentary"); - expect( - container.querySelector('[data-testid="task-chat-current-activity"]'), - ).toBeNull(); - expect( - container.querySelector( - '[data-testid="task-chat-activity-viewport"]', - )?.textContent, - ).toBe("Thinking"); - }); - - it("keeps the within-turn plan in activity history without rendering a Plan document preview", () => { - const activity: TaskChatProviderActivityItem = { - id: "live-plan", - kind: "protocol", - surface: "provider_activity", - family: "plan", - eventType: "plan.updated", - status: "running", - title: "Plan", - details: [{ label: "Revision", value: "4" }], - steps: [ - { - id: "one", - label: "Extract the shared preview", - status: "in_progress", - }, - ], - links: [], - children: [], - transcriptIndex: 1, - }; - render([activity]); - expect( - container.querySelector('[data-testid="task-chat-live-plan-preview"]'), - ).toBeNull(); - const disclosure = container.querySelector( - '[data-testid="task-chat-activity-phase-toggle"]', - ); - expect(disclosure?.getAttribute("aria-label")).toContain("Expand 1 activity"); - act(() => disclosure?.click()); - const history = container.querySelector( - '[data-testid="task-chat-runner-activity-list"]', - ); - expect(history?.textContent).toContain("Updating the plan"); - expect( - history?.querySelector('[data-activity-family="plan"]'), - ).not.toBeNull(); - expect( - history - ?.querySelector('[data-activity-icon] svg') - ?.parentElement?.classList.contains("size-5"), - ).toBe(true); - }); - - it("shows canonical web research as the current Codex-style activity", () => { - render([ - { - id: "research-1", - kind: "protocol", - surface: "provider_activity", - family: "research", - eventType: "research.started", - status: "running", - title: "Research", - summary: "site:openai.com model guide GPT-5.4", - details: [ - { label: "Query", value: "site:openai.com model guide GPT-5.4" }, - ], - steps: [], - links: [], - children: [], - }, - ]); - - const activity = container.querySelector( - '[data-testid="task-chat-activity-viewport"]', - ); - expect(activity?.textContent).toContain("Searching the web"); - expect(activity?.textContent).toContain( - "site:openai.com model guide GPT-5.4", - ); - expect(activity?.querySelector("[data-activity-family]")?.getAttribute("data-activity-family")).toBe("research"); - }); - - it("has a purpose-built current-activity presentation for every provider family", () => { - const cases: Array<{ - family: TaskChatProviderActivityFamily; - eventType: string; - status: TaskChatProviderActivityItem["status"]; - expected: string; - details?: TaskChatProviderActivityItem["details"]; - }> = [ - { - family: "plan", - eventType: "plan.updated", - status: "running", - expected: "Updating the plan", - }, - { - family: "tool_execution", - eventType: "tool.execution.started", - status: "running", - expected: "Running an unnamed tool", - }, - { - family: "research", - eventType: "research.started", - status: "running", - expected: "Searching the web", - details: [{ label: "Action", value: "search" }], - }, - { - family: "delegation", - eventType: "delegation.started", - status: "running", - expected: "Starting a subagent", - details: [{ label: "Action", value: "spawn" }], - }, - { - family: "model_identity", - eventType: "model.route.changed", - status: "informational", - expected: "Switched models", - }, - { - family: "context", - eventType: "context.compacted", - status: "completed", - expected: "Compacted context", - }, - { - family: "artifact", - eventType: "artifact.generated", - status: "running", - expected: "Generating an artifact", - }, - { - family: "review", - eventType: "review.mode.changed", - status: "informational", - expected: "Entered review mode", - details: [{ label: "State", value: "entered" }], - }, - { - family: "hook", - eventType: "hook.started", - status: "running", - expected: "Running a hook", - }, - { - family: "memory", - eventType: "memory.citation.referenced", - status: "informational", - expected: "Referenced memory", - }, - { - family: "safety", - eventType: "safety.review.started", - status: "running", - expected: "Auto-reviewing", - }, - { - family: "terminal", - eventType: "terminal.input.sent", - status: "informational", - expected: "Sent terminal input", - }, - { - family: "wait", - eventType: "wait.started", - status: "running", - expected: "Waiting", - }, - { - family: "provider_notice", - eventType: "provider.notice.recorded", - status: "informational", - expected: "Provider notice", - }, - ]; - - expect(cases.map((entry) => entry.family)).toEqual([ - "plan", - "tool_execution", - "research", - "delegation", - "model_identity", - "context", - "artifact", - "review", - "hook", - "memory", - "safety", - "terminal", - "wait", - "provider_notice", - ] satisfies TaskChatProviderActivityFamily[]); - - for (const entry of cases) { - render([ - { - id: `provider-${entry.family}`, - kind: "protocol", - surface: "provider_activity", - family: entry.family, - eventType: entry.eventType, - status: entry.status, - title: entry.family, - details: entry.details ?? [], - steps: [], - links: [], - children: [], - }, - ]); - const activity = container.querySelector( - '[data-testid="task-chat-activity-viewport"]', - ); - expect(activity?.querySelector("[data-activity-family]")?.getAttribute("data-activity-family"), entry.family).toBe( - entry.family, - ); - expect(activity?.textContent, entry.family).toContain(entry.expected); - } - }); - - it("shows provider failures and interruptions instead of a successful past-tense label", () => { - const provider = ( - status: "failed" | "interrupted", - ): TaskChatProviderActivityItem => ({ - id: `research-${status}`, - kind: "protocol", - surface: "provider_activity", - family: "research", - eventType: "research.completed", - status, - title: "Research", - details: [], - steps: [], - links: [], - children: [], - }); - render([provider("failed")]); - expect( - container.querySelector('[data-testid="task-chat-activity-viewport"]') - ?.textContent, - ).toContain("Web search failed"); - render([provider("interrupted")]); - expect( - container.querySelector('[data-testid="task-chat-activity-viewport"]') - ?.textContent, - ).toContain("Web search stopped"); - }); - - it("surfaces workspace changes and file references as current activity", () => { - render([ - { - id: "workspace-change", - kind: "protocol", - surface: "workspace_change", - changeSetId: "change-1", - revision: 1, - source: "harness_reported", - complete: false, - files: [], - totals: { files: 2, additions: 3, deletions: 1 }, - patchArtifactRef: null, - }, - ]); - const card = container.querySelector( - '[data-testid="task-chat-workspace-change"]', - ); - expect(card).not.toBeNull(); - expect( - card?.closest('[data-testid="task-chat-activity-phase"]'), - ).toBeNull(); - - render([ - { - id: "workspace-file", - kind: "protocol", - surface: "workspace_file", - referenceId: "file-1", - source: "runner_verified", - path: "ui/src/App.tsx", - displayName: "App.tsx", - mediaType: "text/typescript", - presentation: "code", - line: 42, - preview: null, - previewTruncated: false, - }, - ]); - const activity = container.querySelector( - '[data-testid="task-chat-activity-viewport"]', - ); - expect(activity?.textContent).toContain("Referenced a file"); - expect(activity?.textContent).toContain("ui/src/App.tsx:42"); - const icon = activity?.querySelector( - '[data-activity-icon] svg', - ); - expect(icon).not.toBeNull(); - expect(icon?.parentElement?.classList.contains("size-5")).toBe(true); - expect(icon?.parentElement?.classList.contains("justify-center")).toBe( - true, - ); - }); - - it("streams the final response in its durable slot and settles the disclosure", () => { - render( - [ - { - id: "p1", - kind: "message", - author: "agent", - text: "Checking.", - interstitial: true, - channel: "progress", - }, - { - id: "f1", - kind: "message", - author: "agent", - authorName: "Runner", - text: "Completed successfully.", - channel: "final", - streaming: true, - }, - ], - "succeeded", - ); - expect( - container.querySelector('[data-testid="task-chat-final-response"]') - ?.textContent, - ).toContain("Completed successfully."); - expect( - container.querySelectorAll('[data-testid="task-chat-agent-avatar"]'), - ).toHaveLength(1); - expect( - container.querySelector('[data-testid="task-chat-turn-status-header"]') - ?.textContent, - ).toContain("Worked for"); - expect( - container.querySelector('[data-testid="task-chat-phase-interstitial"]') - ?.textContent, - ).toContain("Checking."); - }); - - it("collapses progress text repeated verbatim by the final response", () => { - const repeated = "BASELINE-DONE"; - render( - [ - { - id: "progress", - kind: "message", - author: "agent", - text: repeated, - interstitial: true, - channel: "progress", - }, - { - id: "tool", - kind: "tool", - name: "Command", - status: "completed", - }, - { - id: "final", - kind: "message", - author: "agent", - text: repeated, - channel: "final", - }, - ], - "succeeded", - ); - - expect(container.textContent?.split(repeated)).toHaveLength(2); - expect( - container.querySelector('[data-testid="task-chat-phase-interstitial"]'), - ).toBeNull(); - expect( - container.querySelector('[data-testid="task-chat-final-response"]') - ?.textContent, - ).toContain(repeated); - }); - - it("clears provider wait prose when the run is accepted as yielded", () => { - const providerWait: TaskChatItem = { - id: "provider-wait", - kind: "message", - author: "agent", - authorName: "Runner", - text: "Waiting for Review browser RTS plan.", - channel: "final", - streaming: false, - }; - render([providerWait], "succeeded"); - expect( - container.querySelector('[data-testid="task-chat-final-response"]'), - ).not.toBeNull(); - - render( - [ - providerWait, - { - id: "result", - kind: "protocol", - surface: "run_result", - disposition: "yielded", - summary: "Waiting for Review browser RTS plan.", - objectiveSatisfied: false, - verification: [], - remainingWork: [], - blocker: null, - artifacts: [], - }, - ], - "succeeded", - ); - - expect( - container.querySelector('[data-testid="task-chat-final-response"]'), - ).toBeNull(); - }); - - it("clears provider wait prose as soon as interaction authority is known", () => { - const providerWait: TaskChatItem = { - id: "provider-wait-before-result", - kind: "message", - author: "agent", - authorName: "Runner", - text: "Waiting for structured input.", - channel: "final", - streaming: false, - }; - render([providerWait], "running"); - expect( - container.querySelector('[data-testid="task-chat-final-response"]'), - ).not.toBeNull(); - - render([providerWait], "running", "run-1", undefined, true); - expect( - container.querySelector('[data-testid="task-chat-final-response"]'), - ).toBeNull(); - }); - - it("waits for settlement before using a structured result fallback", () => { - const items: TaskChatItem[] = [ - { - id: "result", - kind: "protocol", - surface: "run_result", - disposition: "done", - summary: "Structured fallback.", - objectiveSatisfied: true, - verification: [], - remainingWork: [], - blocker: null, - artifacts: [], - }, - ]; - - render(items, "running"); - - expect( - container.querySelector('[data-testid="task-chat-final-response"]'), - ).toBeNull(); - }); - - it("lets a shorter provider final replace a structured result fallback", () => { - const result: TaskChatItem = { - id: "result", - kind: "protocol", - surface: "run_result", - disposition: "done", - summary: "A much longer structured summary fallback.", - objectiveSatisfied: true, - verification: [], - remainingWork: [], - blocker: null, - artifacts: [], - }; - - render([result], "succeeded"); - expect(container.textContent).toContain( - "A much longer structured summary fallback.", - ); - - render( - [ - result, - { - id: "provider-final", - kind: "message", - author: "agent", - text: "Done.", - channel: "final", - streaming: false, - }, - ], - "succeeded", - ); - - expect( - container.querySelector('[data-testid="task-chat-final-response"]') - ?.textContent, - ).toContain("Done."); - expect(container.textContent).not.toContain( - "A much longer structured summary fallback.", - ); - }); - - it("collapses terminal reasoning to the existing Worked summary", () => { - render( - [ - { - id: "reasoning", - kind: "thinking", - lines: ["Provider-authored trace"], - channel: "summary", - transcriptIndex: 1, - }, - ], - "succeeded", - ); - expect( - container.querySelector('[data-testid="task-chat-live-narration"]'), - ).toBeNull(); - expect( - container.querySelector('[data-testid="task-chat-turn-status-header"]') - ?.textContent, - ).toContain("Worked for"); - expect( - container.querySelector('[data-testid="task-chat-activity-phase-toggle"]') - ?.textContent, - ).toContain("Thought"); - }); - - it("keeps final text mounted through a transient replay gap", () => { - render([ - { - id: "f1", - kind: "message", - author: "agent", - authorName: "Runner", - text: "Completed successfully.", - channel: "final", - streaming: true, - }, - ]); - render([ - { id: "t1", kind: "tool", name: "Paperclip_finish", status: "completed" }, - ]); - - expect( - container.querySelector('[data-testid="task-chat-final-response"]') - ?.textContent, - ).toContain("Completed successfully."); - expect( - container.querySelectorAll('[data-testid="task-chat-final-response"]'), - ).toHaveLength(1); - }); - - it("clears replay-latched final text when the next run takes over the lane", () => { - render( - [ - { - id: "f1", - kind: "message", - author: "agent", - authorName: "Runner", - text: "First answer.", - channel: "final", - }, - ], - "running", - "run-1", - ); - render([], "running", "run-2"); - - expect(container.textContent).not.toContain("First answer."); - expect( - container.querySelector('[data-testid="task-chat-current-activity"]') - ?.textContent, - ).toContain("Thinking"); - }); - - it("omits runner lifecycle and token noise while preserving useful history", () => { - render([ - { - id: "session", - kind: "marker", - variant: "session_start", - label: "Session started", - detail: "session-id", - }, - { - id: "start", - kind: "marker", - variant: "turn_boundary", - label: "Turn started", - }, - { - id: "usage", - kind: "usage", - usage: { - used: 10_520, - size: 0, - inputTokens: 10_254, - outputTokens: 266, - }, - }, - { - id: "tool", - kind: "tool", - name: "Paperclip_finish", - rawName: "paperclip_finish", - target: "reportedWorkDisposition: done", - status: "completed", - }, - { - id: "interrupt", - kind: "marker", - variant: "interrupted", - label: "Interrupted", - }, - { - id: "complete", - kind: "marker", - variant: "turn_boundary", - label: "Turn completed", - }, - ]); - - expect(container.textContent).not.toContain("Paperclip_finish"); - expect(container.textContent).toContain("Interrupted"); - expect(container.textContent).not.toContain("Session started"); - expect(container.textContent).not.toContain("Turn started"); - expect(container.textContent).not.toContain("Turn completed"); - expect(container.textContent).not.toContain("10,520"); - act(() => - container - .querySelector( - '[data-testid="task-chat-activity-phase-toggle"]', - ) - ?.click(), - ); - expect( - container - .querySelector('[data-activity-icon] svg') - ?.parentElement?.classList.contains("size-5"), - ).toBe(true); - }); - - it("keeps a compact pending runtime entry without duplicating composer controls", async () => { - const onDecision = vi.fn(); - render( - [ - { - id: "request", - kind: "protocol", - surface: "runtime_request", - runId: "run-1", - requestId: "request-1", - requestKind: "command_approval", - turnId: "turn-1", - requestType: "permission", - status: "pending", - prompt: "Allow command?", - choices: [{ key: "accept", label: "Allow once" }], - fields: [], - }, - ], - "running", - "run-1", - onDecision, - ); - - expect( - container.querySelector( - '[data-testid="task-chat-runtime-request-marker"]', - ), - ).toBeNull(); - expect( - container.querySelector('[data-testid="task-chat-runtime-request"]'), - ).toBeNull(); - expect(container.querySelector('[data-testid="task-chat-pending-runtime-request"]')?.textContent).toContain("Allow command?"); - expect(onDecision).not.toHaveBeenCalled(); - }); - - it("keeps a resolved question as a compact expandable receipt outside folded activity", () => { - render( - [ - { - id: "resolved-request", - kind: "protocol", - surface: "runtime_request", - runId: "run-1", - requestId: "request-1", - requestKind: "runtime", - turnId: "turn-1", - requestType: "input", - status: "resolved", - prompt: "Codex needs your input.", - choices: [], - fields: [], - questionSet: { - schema: "paperclip.question_set.v1", - questions: [ - { - id: "goal", - prompt: "What should the server do?", - required: true, - answerMode: "text", - }, - ], - }, - response: { - schema: "paperclip.question_response.v1", - answers: { goal: { text: "Serve a small JSON API." } }, - }, - }, - ], - "succeeded", - ); - - const receipt = container.querySelector( - '[data-testid="task-chat-runtime-request"]', - ); - const history = receipt?.querySelector( - '[data-testid="task-chat-runtime-request-history"]', - ); - expect(receipt?.open).toBe(false); - expect(receipt?.querySelector("summary")?.textContent).toBe( - "Questions answered", - ); - expect(history?.closest(".tc-turn-fold")).toBeNull(); - expect(history?.textContent).toContain("What should the server do?"); - expect(history?.textContent).toContain("Serve a small JSON API."); - }); - - it("renders the DOT-217 mixed turn in exact transcript order", () => { - render( - [ - { - id: "commentary-1", - kind: "message", - author: "agent", - text: "I’ll inspect the workspace first.", - interstitial: true, - channel: "progress", - }, - { - id: "tool-1", - kind: "tool", - name: "Read", - rawName: "read_file", - status: "completed", - }, - { - id: "tool-2", - kind: "tool", - name: "Read", - rawName: "read_file", - status: "completed", - }, - { - id: "commentary-2", - kind: "message", - author: "agent", - text: "I need the first product choices.", - interstitial: true, - channel: "progress", - }, - resolvedQuestion("questions-1", "Which core loop?"), - { - id: "commentary-3", - kind: "message", - author: "agent", - text: "Now I’ll pin down the simulation.", - interstitial: true, - channel: "progress", - }, - { - id: "tool-3", - kind: "tool", - name: "Search", - rawName: "web_search", - status: "completed", - }, - resolvedQuestion("questions-2", "How should time work?"), - { - id: "commentary-4", - kind: "message", - author: "agent", - text: "The final implementation shape is clear.", - interstitial: true, - channel: "progress", - }, - { - id: "tool-4", - kind: "tool", - name: "Bash", - rawName: "bash", - status: "completed", - }, - { - id: "final", - kind: "message", - author: "agent", - text: "The plan is ready.", - channel: "final", - }, - ], - "succeeded", - ); - - const timeline = container.querySelector( - '[data-testid="task-chat-turn-timeline"]', - ); - const rows = Array.from( - timeline?.querySelectorAll( - '[data-testid="task-chat-turn-timeline-row"]', - ) ?? [], - ); - expect(rows.map((row) => row.getAttribute("data-timeline-row-id"))).toEqual( - [ - "commentary-1:phase", - "commentary-2:phase", - "questions-1", - "commentary-3:phase", - "questions-2", - "commentary-4:phase", - ], - ); - expect(rows[0]?.textContent).toContain("Read file"); - expect(rows[2]?.textContent).toContain("Questions answered"); - expect(rows[3]?.textContent).toContain("Searched the web"); - expect(rows[5]?.textContent).toContain("Ran commands"); - const worked = container.querySelector( - '[data-testid="task-chat-turn-status-header"]', - ); - const identityRow = container.querySelector( - '[data-testid="task-chat-runner-identity-row"]', - ); - const identity = container.querySelector( - '[data-testid="task-chat-agent-identity"]', - ); - const final = container.querySelector( - '[data-testid="task-chat-final-response"]', - ); - expect(worked?.getAttribute("data-turn-position")).toBe("identity"); - expect(worked?.parentElement).toBe(identityRow); - expect(identity?.parentElement).toBe(identityRow); - expect(identityRow?.classList.contains("items-center")).toBe(true); - expect(worked?.classList.contains("border-b")).toBe(false); - expect(worked?.compareDocumentPosition(timeline!)).toBe( - Node.DOCUMENT_POSITION_FOLLOWING, - ); - expect(timeline?.compareDocumentPosition(final!)).toBe( - Node.DOCUMENT_POSITION_FOLLOWING, - ); - }); - - it("expands a grouped live phase without hiding its commentary", () => { - render([ - { - id: "thinking-empty", - kind: "thinking", - lines: [], - streaming: false, - lifecycleOnly: true, - }, - { - id: "commentary", - kind: "message", - author: "agent", - text: "Checking the current implementation.", - interstitial: true, - channel: "progress", - }, - { - id: "tool", - kind: "tool", - name: "Read", - rawName: "read_file", - target: "ui/src/App.tsx", - status: "completed", - detail: "export function App() {}", - }, - ]); - - const disclosure = container.querySelector( - '[data-testid="task-chat-activity-phase-toggle"]', - ); - expect(disclosure?.getAttribute("aria-expanded")).toBe("false"); - expect( - container.querySelectorAll('[data-testid="task-chat-thinking"]'), - ).toHaveLength(0); - - act(() => disclosure?.click()); - - expect(disclosure?.getAttribute("aria-expanded")).toBe("true"); - expect( - container.querySelector('[data-testid="task-chat-runner-activity-list"]'), - ).not.toBeNull(); - expect( - container.querySelector('[data-testid="task-chat-phase-interstitial"]') - ?.textContent, - ).toContain("Checking the current implementation."); - expect(container.textContent).toContain("ui/src/App.tsx"); - }); - - it("preserves an open phase while the live run becomes terminal", () => { - const items: TaskChatItem[] = [ - { - id: "tool", - kind: "tool", - name: "Search", - rawName: "web_search", - target: "smoked pork shoulder", - status: "in_progress", - }, - ]; - render(items); - const disclosure = container.querySelector( - '[data-testid="task-chat-activity-phase-toggle"]', - ); - act(() => disclosure?.click()); - expect(disclosure?.getAttribute("aria-expanded")).toBe("true"); - - render( - [{ ...items[0], kind: "tool", status: "completed" } as TaskChatItem], - "succeeded", - ); - - const settled = container.querySelector( - '[data-testid="task-chat-activity-phase-toggle"]', - ); - expect(settled?.getAttribute("aria-expanded")).toBe("true"); - expect( - container.querySelector('[data-testid="task-chat-turn-status-header"]') - ?.textContent, - ).toContain("Worked for"); - }); - - it("resets phase disclosure state when a different run takes over", () => { - const items: TaskChatItem[] = [ - { - id: "tool", - kind: "tool", - name: "Read", - rawName: "read_file", - target: "ui/src/App.tsx", - status: "completed", - }, - ]; - render(items, "running", "run-1"); - act(() => - container - .querySelector( - '[data-testid="task-chat-activity-phase-toggle"]', - ) - ?.click(), - ); - expect( - container - .querySelector('[data-testid="task-chat-activity-phase-toggle"]') - ?.getAttribute("aria-expanded"), - ).toBe("true"); - - render(items, "running", "run-2"); - - expect( - container - .querySelector('[data-testid="task-chat-activity-phase-toggle"]') - ?.getAttribute("aria-expanded"), - ).toBe("false"); - }); - - it("renders a failed terminal disclosure without treating prose as status authority", () => { - render( - [ - { - id: "final", - kind: "message", - author: "agent", - text: "I finished the draft.", - channel: "final", - }, - { - id: "tool", - kind: "tool", - name: "Command", - rawName: "bash", - target: "pnpm test", - status: "failed", - }, - ], - "failed", - ); - - expect( - container.querySelector('[data-testid="task-chat-turn-status-header"]') - ?.textContent, - ).toContain("Stopped after"); - expect( - container.querySelector('[data-testid="task-chat-final-response"]') - ?.textContent, - ).toContain("I finished the draft."); - }); -}); diff --git a/ui/src/components/task-chat/TaskMessageScroller.test.tsx b/ui/src/components/task-chat/TaskMessageScroller.test.tsx deleted file mode 100644 index 83b64236d03..00000000000 --- a/ui/src/components/task-chat/TaskMessageScroller.test.tsx +++ /dev/null @@ -1,686 +0,0 @@ -// @vitest-environment jsdom - -import { flushSync } from "react-dom"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { TaskMessageScroller } from "./TaskMessageScroller"; -import { TaskChatScrollNavigation } from "./scroll-navigation"; - -const PILL_SELECTOR = 'button[aria-label="Scroll to latest"]'; - -/** - * jsdom has no layout, so scroll geometry is faked per element: scrollHeight / - * clientHeight are pinned and scrollTop is backed by a plain variable. - */ -function fakeGeometry(el: HTMLElement, { scrollHeight = 1000, clientHeight = 400, clamp = false } = {}) { - let scrollTop = 0; - Object.defineProperty(el, "scrollHeight", { value: scrollHeight, configurable: true }); - Object.defineProperty(el, "clientHeight", { value: clientHeight, configurable: true }); - Object.defineProperty(el, "scrollTop", { - get: () => scrollTop, - set: (v: number) => { - scrollTop = clamp ? Math.max(0, Math.min(v, el.scrollHeight - el.clientHeight)) : v; - }, - configurable: true, - }); -} - -function fakeResizableGeometry( - el: HTMLElement, - { scrollHeight = 1000, clientHeight = 400 } = {}, -) { - let currentClientHeight = clientHeight; - let scrollTop = 0; - Object.defineProperty(el, "scrollHeight", { - value: scrollHeight, - configurable: true, - }); - Object.defineProperty(el, "clientHeight", { - get: () => currentClientHeight, - configurable: true, - }); - Object.defineProperty(el, "scrollTop", { - get: () => scrollTop, - set: (value: number) => { - scrollTop = value; - }, - configurable: true, - }); - return { - setClientHeight(value: number) { - currentClientHeight = value; - }, - }; -} - -/** - * Scroll/wheel are continuous-priority events, so React flushes the resulting - * state updates asynchronously — wait a macrotask after dispatching. - */ -function flushEvents() { - return new Promise((resolve) => { - setTimeout(resolve); - }); -} - -describe("TaskMessageScroller", () => { - let container: HTMLDivElement; - let root: Root; - - function render(contentKey: unknown = 0) { - flushSync(() => { - root.render( - -
messages
-
, - ); - }); - } - - function scroller(): HTMLDivElement { - return container.querySelector('[data-testid="task-chat-scroller"]')!; - } - - function pill(): HTMLButtonElement | null { - return container.querySelector(PILL_SELECTOR); - } - - /** - * Wait for the pill to reach a state, rather than for a fixed number of turns. - * `flushEvents` yields exactly one macrotask, which is enough on an idle - * machine and not when the suite runs many workers in parallel — React - * flushes continuous-priority updates asynchronously, so the DOM read can - * land before the state does. Sites that dereference `pill()!` turn that into - * a hard failure rather than a retry. - */ - async function waitForPill(present: boolean): Promise { - await vi.waitFor(() => - present ? expect(pill()).not.toBeNull() : expect(pill()).toBeNull(), - ); - } - - /** Set scrollTop and fire a scroll event, like a user or the browser would. */ - async function scrollTo(el: HTMLElement, top: number) { - el.scrollTop = top; - el.dispatchEvent(new Event("scroll", { bubbles: true })); - await flushEvents(); - } - - async function dispatch(el: HTMLElement, event: Event) { - el.dispatchEvent(event); - await flushEvents(); - } - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - }); - - afterEach(() => { - flushSync(() => root.unmount()); - container.remove(); - document.documentElement.style.removeProperty("--motion-scrollbar-idle-delay"); - vi.useRealTimers(); - vi.unstubAllGlobals(); - }); - - it("loads one older page on upward scroll, keeps the status slot, and pauses after failure", async () => { - let release!: () => void; - const load = vi.fn(() => new Promise(resolve => { release = resolve; })); - const history = { hasMore: true, loading: false, error: false, load }; - const update = (tick: number) => flushSync(() => root.render( -
saved messages
, - )); - update(0); - fakeGeometry(scroller()); - update(1); - expect(load).not.toHaveBeenCalled(); - await scrollTo(scroller(), 400); - expect(load).not.toHaveBeenCalled(); - await scrollTo(scroller(), 150); - expect(load).toHaveBeenCalledTimes(1); - await scrollTo(scroller(), 100); - scroller().dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -100 })); - await flushEvents(); - expect(load).toHaveBeenCalledTimes(1); - const status = container.querySelector('[data-testid="chat-history-status"]'); - history.loading = true; - update(2); - expect(container.querySelector('[data-testid="chat-history-status"]')).toBe(status); - expect(status?.textContent).toBe("Loading earlier messages…"); - release(); - await flushEvents(); - history.loading = false; - history.error = true; - update(3); - await scrollTo(scroller(), 50); - expect(load).toHaveBeenCalledTimes(1); - expect(status?.textContent).toContain("Earlier messages couldn’t load."); - (status?.querySelector('button') as HTMLButtonElement).click(); - expect(load).toHaveBeenCalledTimes(2); - release(); - await flushEvents(); - history.error = false; - history.hasMore = false; - update(4); - await scrollTo(scroller(), 0); - expect(load).toHaveBeenCalledTimes(2); - }); - - it("follows a late image resize in the message body after the history status", () => { - const observers: { targets: Set; resize: () => void }[] = []; - vi.stubGlobal("ResizeObserver", class { - targets = new Set(); - constructor(callback: ResizeObserverCallback) { observers.push({ targets: this.targets, resize: () => callback([], this as unknown as ResizeObserver) }); } - observe(target: Element) { this.targets.add(target); } - disconnect() {} - }); - const update = (tick: number) => flushSync(() => root.render( -
image content
, - )); - update(0); fakeGeometry(scroller(), { clamp: true }); update(1); - const body = container.querySelector('[data-testid="image-body"]')!; - Object.defineProperty(scroller(), "scrollHeight", { value: 1400, configurable: true }); - for (const observer of observers) if (observer.targets.has(body)) observer.resize(); - expect(scroller().scrollTop).toBe(1000); - }); - - it("keeps following when content grows before the previous scroll event is delivered", async () => { - render(0); - fakeGeometry(scroller(), { clamp: true }); - render(1); - expect(scroller().scrollTop).toBe(600); - Object.defineProperty(scroller(), "scrollHeight", { value: 1400, configurable: true }); - await dispatch(scroller(), new Event("scroll", { bubbles: true })); - expect(scroller().scrollTop).toBe(1000); - expect(pill()).toBeNull(); - scroller().dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -100 })); - Object.defineProperty(scroller(), "scrollHeight", { value: 1600, configurable: true }); - await scrollTo(scroller(), 900); - render(2); - expect(scroller().scrollTop).toBe(900); - await waitForPill(true); - }); - - it("retains the reading anchor when a resize scroll event precedes the next width reflow", async () => { - const resize: (() => void)[] = []; - vi.stubGlobal("ResizeObserver", class { - constructor(callback: ResizeObserverCallback) { resize.push(() => callback([], this as unknown as ResizeObserver)); } - observe() {} - disconnect() {} - }); - let width = 400, rowTop = 100; - flushSync(() => root.render( -
{ - if (!node) return; - const viewport = node.parentElement!; - fakeGeometry(viewport, { clamp: true }); - Object.defineProperty(viewport, "clientWidth", { get: () => width, configurable: true }); - viewport.getBoundingClientRect = () => ({ top: 0, bottom: 400 } as DOMRect); - }}> -
{ - if (node) node.getBoundingClientRect = () => ({ top: rowTop - scroller().scrollTop, bottom: rowTop + 100 - scroller().scrollTop, height: 100 } as DOMRect); - }}>Saved reply
-
-
)); - await scrollTo(scroller(), 150); - width = 500; rowTop = 80; - for (const callback of resize) callback(); - expect(scroller().scrollTop).toBe(130); - rowTop = 70; - await dispatch(scroller(), new Event("scroll", { bubbles: true })); - for (const callback of resize) callback(); - expect(scroller().scrollTop).toBe(120); - width = 600; rowTop = 60; - await dispatch(scroller(), new Event("scroll", { bubbles: true })); - for (const callback of resize) callback(); - expect(rowTop - scroller().scrollTop).toBe(-50); - expect(pill()).not.toBeNull(); - }); - - it("retains upward intent when content reconciles before the scroll event", async () => { - const load = vi.fn(); - const update = (tick: number) => flushSync(() => root.render( -
saved messages
, - )); - update(0); fakeGeometry(scroller()); update(1); - await scrollTo(scroller(), 400); - scroller().dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -1000 })); - scroller().scrollTop = 0; - update(2); - await dispatch(scroller(), new Event("scroll", { bubbles: true })); - expect(load).toHaveBeenCalledTimes(1); - }); - - it("holds a short conversation when an upward wheel gesture loads history", async () => { - const load = vi.fn().mockResolvedValue(undefined); - const update = (tick: number) => flushSync(() => root.render( -
short conversation
, - )); - update(0); - fakeGeometry(scroller(), { scrollHeight: 200, clientHeight: 400, clamp: true }); - update(1); - await scrollTo(scroller(), 0); - scroller().dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -100 })); - await flushEvents(); - expect(load).toHaveBeenCalledTimes(1); - Object.defineProperty(scroller(), "scrollHeight", { value: 1200, configurable: true }); - update(2); - expect(scroller().scrollTop).toBe(0); - }); - - it("pages short conversations with touch and keyboard gestures", async () => { - const load = vi.fn().mockResolvedValue(undefined); - const update = (tick: number) => flushSync(() => root.render( -
short conversation
, - )); - update(0); fakeGeometry(scroller(), { scrollHeight: 200, clientHeight: 400, clamp: true }); update(1); - await scrollTo(scroller(), 0); - const touch = (type: string, y: number) => { - const event = new Event(type, { bubbles: true }); - Object.defineProperty(event, "touches", { value: [{ clientY: y }] }); - scroller().dispatchEvent(event); - }; - touch("touchstart", 100); touch("touchmove", 200); touch("touchmove", 250); - await flushEvents(); - expect(load).toHaveBeenCalledTimes(1); - scroller().dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key: "Home" })); - await flushEvents(); - expect(load).toHaveBeenCalledTimes(2); - }); - - it("does not measure historical rows on each streaming update while following the bottom", () => { - let initialized = false; - let rowMeasurements = 0; - const update = (tick: number) => flushSync(() => root.render( - -
{ - if (node && !initialized) { - fakeGeometry(node.parentElement!, { scrollHeight: 20000, clientHeight: 400 }); - initialized = true; - } - }}> - {Array.from({ length: 200 }, (_, index) =>
{ - if (node) node.getBoundingClientRect = () => { - rowMeasurements++; - const top = index * 100 - scroller().scrollTop; - return { top, bottom: top + 100, height: 100 } as DOMRect; - }; - }}>History {index}
)} -

Live response {tick}

-
-
, - )); - update(0); - rowMeasurements = 0; - for (let tick = 1; tick <= 30; tick++) update(tick); - expect(container.textContent).toContain("Live response 30"); - expect(scroller().scrollTop).toBe(20000); - expect(rowMeasurements).toBe(0); - }); - - it("applies same-task hash changes and restores each history entry without remounting", async () => { - let initialized = false; - function navigate(key: string, hash: string, restore = false) { - flushSync(() => root.render( - - -
{ - if (node && !initialized) { - fakeGeometry(node.parentElement!); - initialized = true; - } - }}> - {[100, 500].map((top, index) =>
{ - if (node) node.getBoundingClientRect = () => ({ top: top - scroller().scrollTop, bottom: top + 100 - scroller().scrollTop, height: 100 } as DOMRect); - }}>Comment {index}
)} -
-
-
, - )); - } - navigate("desktop-entry-one", "#nav-comment-0"); - const viewport = scroller(); - expect(viewport.scrollTop).toBe(100); - await scrollTo(viewport, 150); - navigate("desktop-entry-two", "#nav-comment-1"); - expect(scroller()).toBe(viewport); - expect(viewport.scrollTop).toBe(500); - navigate("desktop-entry-one", "#nav-comment-0", true); - expect(viewport.scrollTop).toBe(150); - navigate("desktop-entry-one", "#nav-comment-1", true); - expect(viewport.scrollTop).toBe(500); - }); - - it.each([[false, "none"], [false, "wheel"], [false, "pointer"], [true, "none"], [true, "wheel"], [true, "pointer"]] as const)("positions a late hash target unless the reader moved on (restore=%s, readerMoved=%s)", async (restore, readerMoved) => { - let initialized = false; - const show = (targetReady: boolean) => flushSync(() => root.render( - - -
{ - if (node && !initialized) { fakeGeometry(node.parentElement!, { clamp: true }); initialized = true; } - }}> - Saved conversation - {targetReady ?
{ - if (node) node.getBoundingClientRect = () => ({ top: 100 - scroller().scrollTop, bottom: 200 - scroller().scrollTop, height: 100 } as DOMRect); - }}>Linked comment
: null} -
-
-
, - )); - show(false); - if (readerMoved !== "none") { - await scrollTo(scroller(), 300); - await dispatch(scroller(), readerMoved === "wheel" ? new WheelEvent("wheel", { bubbles: true, deltaY: -100 }) : new Event("pointerdown", { bubbles: true })); - } - show(true); - expect(scroller().scrollTop).toBe(readerMoved === "none" ? 100 : 300); - }); - - it("does not replace a saved reading position with a hidden route's geometry", async () => { - function mount(restore: boolean) { - flushSync(() => root.render( - - -
{ if (node) fakeGeometry(node.parentElement!); }}>Saved messages
-
-
, - )); - } - mount(false); - const viewport = scroller(); - await scrollTo(viewport, 150); - Object.defineProperty(viewport, "clientHeight", { value: 0, configurable: true }); - await scrollTo(viewport, 0); - flushSync(() => root.render(null)); - mount(true); - expect(scroller().scrollTop).toBe(150); - }); - - it("restores bottom-follow on Back after the viewport and message heights change", () => { - const configured = new WeakSet(); - function mount(restore: boolean, scrollHeight: number, clientHeight: number) { - flushSync(() => root.render( - - -
{ - const viewport = node?.parentElement; - if (viewport && !configured.has(viewport)) { - fakeGeometry(viewport, { scrollHeight, clientHeight }); - let top = 0; - Object.defineProperty(viewport, "scrollTop", { - configurable: true, - get: () => top, - set: (value: number) => { - top = Math.max(0, Math.min(value, viewport.scrollHeight - viewport.clientHeight)); - }, - }); - configured.add(viewport); - } - }}>Latest response
-
-
, - )); - } - mount(false, 1000, 400); - flushSync(() => root.render(null)); - // Rotation changed wrapping and the available message viewport while away. - mount(true, 2000, 500); - expect(scroller().scrollTop).toBe(1500); - expect(pill()).toBeNull(); - Object.defineProperty(scroller(), "scrollHeight", { value: 2400, configurable: true }); - mount(true, 2400, 500); - expect(scroller().scrollTop).toBe(1900); - }); - - it("renders children inside the scroll container, pill hidden, scrolled to bottom on mount", () => { - render(); - const el = scroller(); - expect(el.textContent).toContain("messages"); - expect(pill()).toBeNull(); - // Mount effect pins to the bottom. - expect(el.scrollTop).toBe(el.scrollHeight); - }); - - it("extends only the streamlined scroll box through the page gutter", () => { - render(); - const el = scroller(); - const frame = el.parentElement; - - expect(frame?.className).toBe("relative min-h-0 flex-1"); - expect(el.classList).toContain("-right-4"); - expect(el.classList).toContain("pr-4"); - expect(el.classList).toContain("md:-right-6"); - expect(el.classList).toContain("md:pr-6"); - expect(el.classList).not.toContain("right-0"); - }); - - it("shows the scrollbar only while scroll activity is recent", () => { - vi.useFakeTimers(); - document.documentElement.style.setProperty("--motion-scrollbar-idle-delay", "600ms"); - render(); - const el = scroller(); - fakeGeometry(el); - - expect(el.className).toContain("scrollbar-while-scrolling"); - expect(el.getAttribute("data-scroll-active")).toBeNull(); - - el.scrollTop = 100; - el.dispatchEvent(new Event("scroll", { bubbles: true })); - expect(el.getAttribute("data-scroll-active")).toBe("true"); - - vi.advanceTimersByTime(599); - expect(el.getAttribute("data-scroll-active")).toBe("true"); - vi.advanceTimersByTime(1); - expect(el.getAttribute("data-scroll-active")).toBeNull(); - }); - - it("contains horizontal overflow so no scrollbar appears above the composer", () => { - render(); - - expect(scroller().classList).toContain("overflow-x-hidden"); - expect(scroller().classList).toContain("overflow-y-auto"); - }); - - it("auto-follows content instantly while pinned", async () => { - render(1); - const el = scroller(); - fakeGeometry(el); - await scrollTo(el, 600); // bottom: 1000 - 600 - 400 = 0 → pinned - await waitForPill(false); // pinned state settled before content grows - render(2); - expect(el.scrollTop).toBe(1000); - expect(pill()).toBeNull(); - }); - - it("holds position and shows the icon-only pill when scrolled up", async () => { - render(1); - const el = scroller(); - fakeGeometry(el); - await scrollTo(el, 100); // 500px from bottom → unpinned - await waitForPill(true); - const btn = pill(); - expect(btn).not.toBeNull(); - expect(btn!.className).toContain("tc-scroll-pill-in"); - expect(btn!.className).toContain("size-8"); - expect(btn!.className).toContain("bottom-7"); - expect(btn!.className).not.toContain("bottom-3"); - expect(btn!.className).not.toContain("-translate-x-1/2"); - // Icon-only: no visible text. - expect(btn!.textContent).toBe(""); - // New content must not yank the held position. - render(2); - expect(el.scrollTop).toBe(100); - }); - - it("follows a shrinking viewport while pinned so a growing composer cannot cover the latest text", async () => { - let triggerResize = () => {}; - vi.stubGlobal( - "ResizeObserver", - class { - constructor(callback: ResizeObserverCallback) { - triggerResize = () => - callback([], this as unknown as ResizeObserver); - } - observe() {} - disconnect() {} - }, - ); - render(); - const el = scroller(); - const geometry = fakeResizableGeometry(el); - triggerResize(); - await scrollTo(el, 600); - - geometry.setClientHeight(200); - triggerResize(); - - expect(el.scrollTop).toBe(el.scrollHeight); - expect(pill()).toBeNull(); - }); - - it("holds a reader's position when the composer grows while they are scrolled up", async () => { - let triggerResize = () => {}; - vi.stubGlobal( - "ResizeObserver", - class { - constructor(callback: ResizeObserverCallback) { - triggerResize = () => - callback([], this as unknown as ResizeObserver); - } - observe() {} - disconnect() {} - }, - ); - render(); - const el = scroller(); - const geometry = fakeResizableGeometry(el); - triggerResize(); - await scrollTo(el, 100); - await waitForPill(true); - - geometry.setClientHeight(200); - triggerResize(); - - expect(el.scrollTop).toBe(100); - expect(pill()).not.toBeNull(); - }); - - it("small drifts within the pin threshold do not show the pill", async () => { - render(); - const el = scroller(); - fakeGeometry(el); - await scrollTo(el, 560); // 40px from bottom, threshold is 48 - expect(pill()).toBeNull(); - }); - - it("clicking the pill smooth-scrolls, ignores intermediate scroll events, re-pins on arrival", async () => { - vi.stubGlobal("matchMedia", vi.fn().mockReturnValue({ matches: false })); - render(1); - const el = scroller(); - fakeGeometry(el); - const scrollToSpy = vi.fn(); - el.scrollTo = scrollToSpy as unknown as typeof el.scrollTo; - - await scrollTo(el, 100); - await waitForPill(true); - const btn = pill()!; - btn.click(); - await flushEvents(); - expect(scrollToSpy).toHaveBeenCalledWith({ top: 1000, behavior: "smooth" }); - - // Intermediate glide positions fire scroll events; they must not unpin - // (i.e. the easing flag swallows them and the pill state stays put). - await scrollTo(el, 250); - await scrollTo(el, 400); - expect(pill()).not.toBeNull(); - - // Arrival within the threshold re-pins and hides the pill (immediately - // here: no matchMedia in jsdom → reduced-motion/unmount-now path). - vi.stubGlobal("matchMedia", vi.fn().mockReturnValue({ matches: true })); - await scrollTo(el, 600); - expect(pill()).toBeNull(); - - // Re-pinned: content growth follows instantly again. - render(2); - expect(el.scrollTop).toBe(1000); - }); - - it("finishes following at the new bottom when content changes during the latest glide", async () => { - vi.stubGlobal("matchMedia", vi.fn().mockReturnValue({ matches: false })); - render(1); - const el = scroller(); - fakeGeometry(el); - el.scrollTo = vi.fn() as unknown as typeof el.scrollTo; - await scrollTo(el, 100); - await waitForPill(true); - pill()!.click(); - await flushEvents(); - await scrollTo(el, 250); - render(2); - expect(el.scrollTop).toBe(1000); - }); - - it("a wheel gesture during the glide cancels easing and stays unpinned", async () => { - vi.stubGlobal("matchMedia", vi.fn().mockReturnValue({ matches: false })); - render(1); - const el = scroller(); - fakeGeometry(el); - el.scrollTo = vi.fn() as unknown as typeof el.scrollTo; - - await scrollTo(el, 100); - await waitForPill(true); - pill()!.click(); - await flushEvents(); - await dispatch(el, new Event("wheel", { bubbles: true })); - - // Easing cancelled → user is unpinned, pill visible, content holds. - expect(pill()).not.toBeNull(); - render(2); - expect(el.scrollTop).toBe(100); - - // Scroll events far from the bottom now behave normally (still unpinned). - await scrollTo(el, 200); - expect(pill()).not.toBeNull(); - }); - - it("plays the exit animation before unmounting when motion is enabled", async () => { - vi.stubGlobal( - "matchMedia", - vi.fn().mockReturnValue({ matches: false }), // motion allowed - ); - render(); - const el = scroller(); - fakeGeometry(el); - await scrollTo(el, 100); - await vi.waitFor(() => expect(pill()?.className).toContain("tc-scroll-pill-in")); - - // Scrolling back to the bottom starts the exit animation but keeps the - // pill mounted until animationend. - await scrollTo(el, 600); - await vi.waitFor(() => expect(pill()?.className).toContain("tc-scroll-pill-out")); - const exiting = pill(); - expect(exiting).not.toBeNull(); - - // jsdom has no window.AnimationEvent, so React's vendor-prefix detection - // maps onAnimationEnd to "webkitAnimationEnd" here (real browsers get the - // unprefixed event). - await dispatch(exiting!, new Event("webkitAnimationEnd", { bubbles: true })); - await waitForPill(false); - }); - - it("unmounts immediately on hide under prefers-reduced-motion", async () => { - vi.stubGlobal( - "matchMedia", - vi.fn().mockReturnValue({ matches: true }), // reduce - ); - render(); - const el = scroller(); - fakeGeometry(el); - await scrollTo(el, 100); - await waitForPill(true); - await scrollTo(el, 600); - await waitForPill(false); // no animationend needed - }); -}); diff --git a/ui/src/context/CompanyContext.test.tsx b/ui/src/context/CompanyContext.test.tsx index 2a269243317..5a92cbd0dd9 100644 --- a/ui/src/context/CompanyContext.test.tsx +++ b/ui/src/context/CompanyContext.test.tsx @@ -223,7 +223,7 @@ describe("CompanyProvider", () => { root = createRoot(container); queryClient = new QueryClient({ defaultOptions: { - queries: { retry: false }, + queries: { retry: false, retryDelay: 0 }, }, }); mockAuthApi.getSession.mockResolvedValue(null); @@ -508,8 +508,8 @@ describe("CompanyProvider", () => { }); await flushReact(); // Past the bounded retries, so the failure has actually settled. - await act(async () => { - await new Promise((resolve) => window.setTimeout(resolve, 1200)); + await vi.waitFor(() => { + expect(captured?.companyListUnavailable).toBe(true); }); await flushReact(); @@ -549,13 +549,12 @@ describe("CompanyProvider", () => { queryClient.setQueryData(queryKeys.auth.session, sessionFor("user-2")); }); await flushReact(); - await act(async () => { - await new Promise((resolve) => window.setTimeout(resolve, 1200)); + await vi.waitFor(() => { + expect(seen).toEqual([null, "company-1", null, "company-2"]); }); await flushReact(); expect(captured?.companyListUnavailable).toBe(false); - expect(seen).toEqual([null, "company-1", null, "company-2"]); }); // The failure flag must not outlive the failure. A later success — a focus @@ -571,13 +570,11 @@ describe("CompanyProvider", () => { queryClient.setQueryData(queryKeys.auth.session, sessionFor("user-2")); }); await flushReact(); - await act(async () => { - await new Promise((resolve) => window.setTimeout(resolve, 1200)); + await vi.waitFor(() => { + expect(captured?.companyListUnavailable).toBe(true); }); await flushReact(); - expect(captured?.companyListUnavailable).toBe(true); - // This account genuinely owns no companies, and the request says so. mockCompaniesApi.list.mockResolvedValue([]); await act(async () => { diff --git a/ui/src/features/connections/AwsRoleSetup.test.tsx b/ui/src/features/connections/AwsRoleSetup.test.tsx deleted file mode 100644 index da18b886ae7..00000000000 --- a/ui/src/features/connections/AwsRoleSetup.test.tsx +++ /dev/null @@ -1,233 +0,0 @@ -// @vitest-environment jsdom -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { AgentSetupProgress, AgentSetupProgressHandoff, AwsConnectionSetup } from "@paperclipai/shared"; -import type { AgentSetupProgressClient } from "@/components/AgentSetupProgress"; -import { AwsRoleSetup, awsAgentSetupPrompt, awsCliCommands, awsSetupErrorMessage, type AwsRoleSetupClient } from "./AwsRoleSetup"; -import { ApiError } from "@/api/client"; - -vi.mock("@/api/tools", () => ({ toolsApi: {} })); -vi.mock("@/api/companies-query", () => ({ useAccountIdentity: () => ({ userId: "user-1", settled: true, current: true }) })); - -const READY: AwsConnectionSetup = { - available: true, - issuer: "https://acme.paperclip.app/oidc/companies/company-1", - audience: "sts.amazonaws.com", - subject: "connection:conn-1", - providerHost: "acme.paperclip.app/oidc/companies/company-1", - roleName: "paperclip-conn-1", - savedRoleArn: null, - accessLevel: "read_only", - trustPolicy: { Version: "2012-10-17", Statement: [{ Effect: "Allow", Principal: { Federated: "arn:aws:iam::ACCOUNT_ID:oidc-provider/acme.paperclip.app/oidc/companies/company-1" } }] }, - cloudFormationTemplate: "{\"Resources\":{}}\n", - cloudFormationConsoleUrl: "https://console.aws.amazon.com/cloudformation/home#/stacks/create", - issuerPublished: true, -}; -const ROLE_ARN = "arn:aws:iam::123456789012:role/paperclip-conn-1"; -type Ready = Extract; - -function setInput(input: HTMLInputElement, value: string) { - Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value); - input.dispatchEvent(new Event("input", { bubbles: true })); -} - -describe("AwsRoleSetup", () => { - let container: HTMLDivElement; - let root: Root; - beforeEach(() => { - (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - window.sessionStorage.clear(); - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - }); - afterEach(async () => { - await act(async () => root.unmount()); - container.remove(); - vi.restoreAllMocks(); - }); - - async function render(setup: AwsConnectionSetup, props: Partial[0]> = {}) { - const client: AwsRoleSetupClient = { setup: vi.fn(async () => setup) }; - const onTest = vi.fn(); - await act(async () => { - root.render( - - - , - ); - }); - await act(async () => { await Promise.resolve(); }); - return { client, onTest }; - } - const button = (text: string) => [...container.querySelectorAll("button")].find((b) => b.textContent?.trim() === text); - - it("shows only the agent setup by default, then tests with the pasted role ARN", async () => { - const { client, onTest } = await render(READY); - expect(client.setup).toHaveBeenCalledWith("conn-1", undefined); - expect(container.querySelector('button[aria-label="Set it up with your agent"]')).not.toBeNull(); - expect(container.textContent).toContain("Or do it by hand"); - expect(container.textContent).not.toContain("Download template"); - const test = () => button("Test connection")!; - expect(test().disabled).toBe(true); - const input = container.querySelector("#aws-role-arn")!; - await act(async () => { setInput(input, "not-an-arn"); }); - expect(container.textContent).toContain("Use the full role ARN"); - expect(test().disabled).toBe(true); - await act(async () => { setInput(input, ` ${ROLE_ARN} `); }); - expect(test().disabled).toBe(false); - await act(async () => { test().click(); }); - expect(onTest).toHaveBeenCalledWith(ROLE_ARN); - }); - - it("fills in a role ARN saved earlier", async () => { - await render({ ...READY, savedRoleArn: ROLE_ARN } as AwsConnectionSetup); - expect(container.querySelector("#aws-role-arn")!.value).toBe(ROLE_ARN); - expect(button("Test connection")?.disabled).toBe(false); - }); - - it("shows CloudFormation and IAM steps by hand, with CLI commands that read the account", async () => { - await render(READY); - await act(async () => { button("Or do it by hand")?.click(); }); - expect(container.textContent).toContain("With CloudFormation"); - expect(container.textContent).toContain("copy RoleArn from its Outputs tab"); - expect(container.textContent).toContain("replacing ACCOUNT_ID with your AWS account ID"); - const cli = container.querySelector('textarea[aria-label="AWS CLI commands"]')!.value; - expect(cli).toContain("ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)"); - expect(cli).toContain("arn:aws:iam::${ACCOUNT_ID}:oidc-provider/"); - expect(cli).toContain("--role-name paperclip-conn-1"); - expect(cli).toContain("arn:aws:iam::aws:policy/ReadOnlyAccess"); - expect(cli).toContain("aws iam get-role --role-name paperclip-conn-1 --query Role.Arn --output text"); - }); - - it("gives the user's agent a prompt that deploys this connection's template and reports the role ARN", () => { - const prompt = awsAgentSetupPrompt(READY as Ready); - expect(prompt).toContain("aws sts get-caller-identity"); - expect(prompt).toContain("--stack-name paperclip-conn-1 "); - expect(prompt).toContain("CAPABILITY_NAMED_IAM"); - expect(prompt).toContain("RoleArn output"); - expect(prompt).toContain("connection:conn-1"); - expect(prompt).toContain((READY as Ready).cloudFormationTemplate.trimEnd()); - expect(prompt).not.toContain("AccessPolicyArn="); - const full = awsAgentSetupPrompt({ ...READY, accessLevel: "full" } as Ready); - expect(full).toContain("ask me which managed policy"); - expect(full).toContain("AccessPolicyArn="); - }); - - it("updates the connection's role on reconnect, checks its account, with CLI commands that paste as is", async () => { - const setup = { ...READY, savedRoleArn: ROLE_ARN, accessLevel: "full" } as Ready; - await render(setup); - expect(container.textContent).toContain("It updates the existing role"); - await act(async () => { button("Or do it by hand")?.click(); }); - expect(container.textContent).toContain("Update the role"); - const roleRow = [...container.querySelectorAll("div")].find((d) => d.firstElementChild?.textContent === "Role name"); - expect(roleRow?.querySelector("code")?.textContent).toBe("paperclip-conn-1"); - const cli = awsCliCommands(setup); - expect(cli).toContain("if aws iam get-role --role-name paperclip-conn-1"); - expect(cli).toContain("aws iam update-assume-role-policy --role-name paperclip-conn-1"); - expect(cli).toContain("|| aws iam create-open-id-connect-provider"); - expect(cli).toContain("REPLACE_WITH_POLICY_ARN"); - expect(cli).not.toMatch(/<[^<>\n]*>/); - const prompt = awsAgentSetupPrompt(setup); - expect(prompt).toContain(`Update the AWS IAM role ${ROLE_ARN}`); - // The agent stops when the CLI is signed in to another account than the role's. - expect(prompt).toContain("The role is in account 123456789012: if the CLI uses a different account"); - expect(prompt).toContain("creates the stack, or updates it if it already exists"); - expect(prompt).toContain("If the stack paperclip-conn-1 already exists and its value is true"); - expect(prompt).toContain("keep true so the stack keeps owning its provider. Otherwise run `aws iam list-open-id-connect-providers`"); - }); - - it("asks for the access policy when the connection has full access", async () => { - await render({ ...READY, accessLevel: "full" } as AwsConnectionSetup); - await act(async () => { button("Or do it by hand")?.click(); }); - expect(container.textContent).toContain("Set AccessPolicyArn to the managed policy agents should have"); - expect(container.textContent).not.toContain("so it needs no edits"); - }); - - it("downloads the template generated for this connection", async () => { - await render(READY); - await act(async () => { button("Or do it by hand")?.click(); }); - const createObjectURL = vi.fn(() => "blob:template"); - const revokeObjectURL = vi.fn(); - Object.assign(URL, { createObjectURL, revokeObjectURL }); - let downloaded = ""; - vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(function (this: HTMLAnchorElement) { downloaded = this.download; }); - await act(async () => { [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Download template"))?.click(); }); - expect(downloaded).toBe("paperclip-aws-paperclip-conn-1.json"); - expect(createObjectURL).toHaveBeenCalledOnce(); - expect(revokeObjectURL).toHaveBeenCalledWith("blob:template"); - }); - - it("adds live progress reporting to the prompt and shows the agent's checklist", async () => { - const progress: AgentSetupProgress = { - id: "11111111-1111-4111-8111-111111111111", companyId: "company-1", purpose: "aws_connection", subjectId: "conn-1", - status: "waiting", items: [], summary: null, expiresAt: new Date(Date.now() + 6 * 3600_000).toISOString(), createdAt: "2026-11-23T14:00:00.000Z", updatedAt: "2026-11-23T14:00:00.000Z", - }; - const base = `https://acme.paperclip.app/api/agent-setup-progress/${progress.id}`; - const handoff: AgentSetupProgressHandoff = { progress, token: "pcsp_test", urls: { checklist: `${base}/checklist`, item: `${base}/items/{key}`, finish: `${base}/finish` } }; - // Live updates are covered in AgentSetupProgress.test.tsx; here the agent has not reported yet. - const progressClient: AgentSetupProgressClient = { create: vi.fn(async () => handoff), get: vi.fn(async () => progress) }; - await render(READY, { companyId: "company-1", progressClient }); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - // Creating the checklist is asynchronous: wait for it rather than assume one tick is enough. - await vi.waitFor(() => expect(container.textContent).toContain("Paste the prompt into your agent. Its steps appear here as it works.")); - expect(progressClient.create).toHaveBeenCalledWith("company-1", { purpose: "aws_connection", subjectId: "conn-1" }); - const prompt = awsAgentSetupPrompt(READY as Ready, "PROGRESS"); - expect(prompt).toContain("Also put it in your finish summary"); - // Progress reporting comes first, so the agent sets its checklist before it starts. - expect(prompt.indexOf("PROGRESS")).toBeLessThan(prompt.indexOf("Steps:")); - }); - - it("says when live progress is unavailable, keeps the prompt, and tries again", async () => { - const create = vi.fn().mockRejectedValueOnce(new Error("offline")).mockResolvedValueOnce({ - progress: { id: "11111111-1111-4111-8111-111111111111", companyId: "company-1", purpose: "aws_connection", subjectId: "conn-1", - status: "waiting", items: [], summary: null, expiresAt: new Date(Date.now() + 3600_000).toISOString(), - createdAt: "2026-11-23T14:00:00.000Z", updatedAt: "2026-11-23T14:00:00.000Z" }, - token: "pcsp_test", urls: { checklist: "https://x/checklist", item: "https://x/items/{key}", finish: "https://x/finish" }, - }); - const progressClient: AgentSetupProgressClient = { create, get: vi.fn(async () => { throw new Error("unused"); }) }; - await render(READY, { companyId: "company-1", progressClient }); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - await vi.waitFor(() => expect(container.textContent).toContain("Live progress isn’t available")); - expect(container.querySelector('button[aria-label="Set it up with your agent"]')).not.toBeNull(); - await act(async () => { button("Try again")?.click(); }); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - expect(create).toHaveBeenCalledTimes(2); - expect(container.textContent).not.toContain("Live progress isn’t available"); - await vi.waitFor(() => expect(container.textContent).toContain("Paste the prompt into your agent.")); - }); - - it("points to the access-key method when AWS cannot reach this instance, without starting a checklist", async () => { - const progressClient: AgentSetupProgressClient = { create: vi.fn(), get: vi.fn() }; - await render({ available: false, reason: "loopback" }, { companyId: "company-1", progressClient }); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); - // No prompt can carry a checklist here, so none is created. - expect(progressClient.create).not.toHaveBeenCalled(); - expect(container.textContent).toContain("Use an access key instead"); - expect(container.textContent).toContain("runs on this computer only"); - expect(button("Test connection")?.disabled).toBe(true); - }); - - it("shows the server's AWS message even when setup reports it with a gateway status", () => { - const message = "AWS refused this connection's role. Check that the role exists and trusts this connection."; - const awsError = new ApiError(message, 502, { error: message, code: "aws_role_access_denied", details: { code: "aws_role_access_denied" } }); - expect(awsSetupErrorMessage(awsError)).toBe(message); - const other = new ApiError("Bad Gateway", 502, { error: "upstream", details: { code: "mcp_remote_fetch_failed" } }); - expect(awsSetupErrorMessage(other)).not.toContain("upstream"); - }); - - it("explains a failed test in place", async () => { - await render(READY, { error: "AWS refused this connection's role. Check that the role exists and trusts this connection." }); - expect(container.textContent).toContain("AWS didn’t accept the connection yet"); - expect(container.textContent).toContain("AWS refused this connection's role"); - }); - - it("asks to save the connection again instead of showing steps for an old address", async () => { - await render({ available: false, reason: "address_changed" }); - expect(container.textContent).toContain("Save the connection again"); - expect(container.textContent).not.toContain("Create it with CloudFormation"); - expect(button("Test connection")?.disabled).toBe(true); - }); -}); diff --git a/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsx b/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsx deleted file mode 100644 index 598c6fcb012..00000000000 --- a/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsx +++ /dev/null @@ -1,929 +0,0 @@ -// @vitest-environment jsdom - -import { act as reactAct, useState, type ReactNode } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import type { - ConnectionIntentInteraction, - ToolConnection, -} from "@paperclipai/shared"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { ApiError } from "@/api/client"; -import { - connectedConnectionIntentInteraction, - issueThreadInteractionFixtureMeta, - pendingConnectionIntentInteraction, - retryConnectionIntentInteraction, -} from "@/fixtures/issueThreadInteractionFixtures"; -import { ConnectionIntentInteractionBody } from "./ConnectionIntentInteractionBody"; - -const emailConnectMock = vi.hoisted(() => vi.fn()); -const emailSetupMock = vi.hoisted(() => vi.fn()); -const emailListMock = vi.hoisted(() => vi.fn()); -const emailControlMock = vi.hoisted(() => vi.fn()); -const emailCredentialsMock = vi.hoisted(() => vi.fn()); -vi.mock("@/api/email", () => ({ emailApi: { - credentials: (...args: unknown[]) => emailCredentialsMock(...args), - list: (...args: unknown[]) => emailListMock(...args), - control: (...args: unknown[]) => emailControlMock(...args), - connect: (...args: unknown[]) => emailConnectMock(...args), - setup: (...args: unknown[]) => emailSetupMock(...args), -} })); - -const credentialRender = vi.hoisted(() => vi.fn()); -const routedCredentialRender = vi.hoisted(() => vi.fn()); -const setupOptionsMock = vi.hoisted(() => vi.fn()); -const completeMock = vi.hoisted(() => vi.fn()); -const declineMock = vi.hoisted(() => vi.fn()); -const setPhaseMock = vi.hoisted(() => vi.fn()); -const getAgentMock = vi.hoisted(() => vi.fn()); -const updateAgentMock = vi.hoisted(() => vi.fn()); -const setDefaultMock = vi.hoisted(() => vi.fn()); -vi.mock("@/api/ai-connections", () => ({ aiConnectionsApi: { setDefault: (...args: unknown[]) => setDefaultMock(...args) } })); -const adoptMock = vi.hoisted(() => vi.fn()); -const installMock = vi.hoisted(() => vi.fn()); -vi.mock("@/api/tools", () => ({ toolsApi: { - getConnectionInstalls: async () => ({ installs: [] }), - putConnectionInstalls: (...args: unknown[]) => installMock(...args), -} })); - -vi.mock("@/api/agents", () => ({ agentsApi: { - adoptAiConnection: (...args: unknown[]) => adoptMock(...args), - get: (...args: unknown[]) => getAgentMock(...args), - update: (...args: unknown[]) => updateAgentMock(...args), -} })); - -vi.mock("@/api/connection-intents", () => ({ - connectionIntentsApi: { - setupOptions: (...args: unknown[]) => setupOptionsMock(...args), - complete: (...args: unknown[]) => completeMock(...args), - decline: (...args: unknown[]) => declineMock(...args), - setPhase: (...args: unknown[]) => setPhaseMock(...args), - }, -})); - -vi.mock("@/components/ai-connections/AiConnectionCredentialStep", () => ({ - AiConnectionCredentialStep: (props: { connectionId?: string; name: string; hideName?: boolean; fixedMethod?: boolean; onComplete: (result: {connectionId: string; grantId: string; method: "api_key"}) => void; onCancel: () => void }) => { credentialRender(props); return
- {!props.hideName && {props.name}}{String(props.fixedMethod)} - - -
; }, -})); - -vi.mock("@/components/ai-connections/AiProviderSetup", () => ({ - AiProviderSetup: (props: { reconnect: { id: string }; onComplete: (binding: { connectionId: string; grantId: string; method: "api_key" }) => void; onCancel: () => void }) => { - routedCredentialRender(props); - return
- - -
; - }, -})); - -vi.mock("./ConnectionSetupFlow", () => ({ - ConnectionSetupFlow: (props: { - requestedAgentId?: string; - requiredAgentId?: string; - existingConnections?: ToolConnection[]; - onUseExisting?: (id: string) => Promise; - onComplete?: (completion: { connectionId: string } | { resolvedByCallback: true }) => void; - onPhaseChange?: (phase: "needs_retry") => void; - onCancel?: () => void; - }) => ( -
- {props.requestedAgentId} - {props.requiredAgentId} - - {props.existingConnections?.length ?? 0} - - {props.existingConnections?.map((connection) => ( - - ))} - - - - -
- ), -})); - -( - globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } -).IS_REACT_ACT_ENVIRONMENT = true; - -let root: Root | null = null; -let host: HTMLDivElement | null = null; -let queryClient: QueryClient; - -async function act(callback: () => void | Promise) { - await reactAct(callback); -} - -async function flush() { - await act(async () => { - await Promise.resolve(); - await new Promise((resolve) => window.setTimeout(resolve, 0)); - }); -} - -async function waitForAssertion(assertion: () => void, attempts = 20) { - let lastError: unknown; - for (let attempt = 0; attempt < attempts; attempt += 1) { - await flush(); - try { - assertion(); - return; - } catch (error) { - lastError = error; - } - } - throw lastError; -} - -function terminal( - status: ConnectionIntentInteraction["status"], - outcome: "declined" | "superseded" | "expired", -): ConnectionIntentInteraction { - return { - ...pendingConnectionIntentInteraction, - id: `interaction-${outcome}`, - status, - resolvedAt: new Date("2026-08-26T12:00:00.000Z"), - result: { version: 1, outcome }, - } as ConnectionIntentInteraction; -} - -function renderNode(node: ReactNode) { - host = document.createElement("div"); - document.body.appendChild(host); - root = createRoot(host); - queryClient = new QueryClient({ - defaultOptions: { queries: { retry: false }, mutations: { retry: false } }, - }); - void act(() => { - root?.render( - - {node} - , - ); - }); - return host; -} - -function renderBody( - interaction: ConnectionIntentInteraction = pendingConnectionIntentInteraction, - currentUserId: - string | null = issueThreadInteractionFixtureMeta.currentUserId, -) { - return renderNode( - , - ); -} - -function button(label: string) { - return Array.from(document.body.querySelectorAll("button")).find( - (candidate) => candidate.textContent?.trim() === label || (label === "Connect / Use existing" && candidate.textContent?.trim() === "Connect"), - ) as HTMLButtonElement | undefined; -} - -it("explains all-agent defaults consistently on compact connector cards", () => { - renderNode(); - expect(document.body.textContent).toContain("New connections default to all agents"); - expect(document.body.textContent).not.toContain("Access is added only for this agent"); -}); - -beforeEach(() => { - sessionStorage.clear(); - emailCredentialsMock.mockReset().mockResolvedValue([]); - emailListMock.mockReset().mockResolvedValue([]); - emailControlMock.mockReset().mockResolvedValue({}); - emailConnectMock.mockReset().mockResolvedValue({ id: "email-account" }); - emailSetupMock.mockReset().mockResolvedValue({ connectionId: "email-inbox" }); - setDefaultMock.mockReset(); - getAgentMock.mockReset(); - updateAgentMock.mockReset(); - installMock.mockReset(); - adoptMock.mockReset(); - setupOptionsMock.mockReset(); - completeMock.mockReset(); - declineMock.mockReset(); - setPhaseMock.mockReset(); - setupOptionsMock.mockResolvedValue({ - requestedAgentId: - pendingConnectionIntentInteraction.payload.requestingAgentId, - existingConnections: [], - }); - completeMock.mockResolvedValue({}); - declineMock.mockResolvedValue({}); - setPhaseMock.mockResolvedValue({}); -}); - -afterEach(async () => { - if (root) await act(() => root?.unmount()); - await queryClient.cancelQueries(); - queryClient.clear(); - host?.remove(); - document.body - .querySelectorAll("[data-radix-focus-guard]") - .forEach((node) => node.remove()); - root = null; - host = null; -}); - -describe("ConnectionIntentInteractionBody states and audience", () => { - it("opens the saved chat authentication step without another setup form", async () => { - const interaction = { ...pendingConnectionIntentInteraction, payload: { ...pendingConnectionIntentInteraction.payload, - purpose: "channel" as const, serviceSlug: "slack", serviceName: "Slack", phase: "authorizing" as const, - savedSetup: { endpointId: "endpoint", connectionId: "connection" } } }; - setupOptionsMock.mockResolvedValue({ version: 1, interaction, requestedAgentId: interaction.payload.requestingAgentId, - existingConnections: [], service: { service: "slack", name: "Slack", methods: [], state: "needs_user_action" }, - chatSetup: { endpointId: "endpoint", connectionId: "connection", path: "/ACME/apps/chat/connect?provider=slack&resume=endpoint" } }); - renderBody(interaction); - await waitForAssertion(() => - expect(document.querySelector('a')?.getAttribute("href")).toBe("/ACME/apps/chat/connect?provider=slack&resume=endpoint"), - ); - expect(document.querySelector('[data-testid="shared-connection-setup"]')).toBeNull(); - expect(completeMock).not.toHaveBeenCalled(); - }); - - it.each([ - [pendingConnectionIntentInteraction, "Connect"], - [ - { - ...pendingConnectionIntentInteraction, - payload: { - ...pendingConnectionIntentInteraction.payload, - phase: "authorizing", - }, - }, - "Continue setup", - ], - [retryConnectionIntentInteraction, "Try again"], - [connectedConnectionIntentInteraction, "Notion connected"], - [terminal("rejected", "declined"), "Connection declined"], - [terminal("expired", "superseded"), "Request superseded"], - [terminal("expired", "expired"), "Connection request expired"], - ] as const)("renders the %s state", (interaction, expected) => { - renderBody(interaction as ConnectionIntentInteraction); - expect(document.body.textContent).toContain(expected); - }); - - it("shows the stored reason on an expired request", () => { - // The server writes what actually expired the request and what to do next. - // A generic "no longer active" line left the reader with no next step. - const reason = "The task was reassigned before the connection request was answered, so the Notion connection is still not connected. Reconnect it or choose an available connection."; - renderBody({ - ...terminal("expired", "expired"), - result: { version: 1, outcome: "expired", reason }, - } as ConnectionIntentInteraction); - expect(document.body.textContent).toContain(reason); - expect(document.body.textContent).not.toContain("This request is no longer active."); - }); - - it("shows non-addressees only the waiting state and never loads setup", () => { - renderBody(pendingConnectionIntentInteraction, "other-user"); - expect(document.body.textContent).toContain("Waiting for Carol"); - expect(button("Connect / Use existing")).toBeUndefined(); - expect(button("Not now")).toBeUndefined(); - expect(setupOptionsMock).not.toHaveBeenCalled(); - expect(document.body.innerHTML).not.toMatch( - /authorizationUrl|bearer|credential/i, - ); - }); -}); - -describe("ConnectionIntentInteractionBody dialog behavior", () => { - it("verifies inline OAuth callback hints against durable server acceptance", async () => { - const options = { requestedAgentId: pendingConnectionIntentInteraction.payload.requestingAgentId, existingConnections: [], interaction: pendingConnectionIntentInteraction }; - setupOptionsMock.mockResolvedValue(options); - renderBody(); - await act(() => button("Connect / Use existing")?.click()); - await flush(); - const readsBeforeMessage = setupOptionsMock.mock.calls.length; - await act(() => button("Simulate OAuth callback")?.click()); - await flush(); - expect(setupOptionsMock.mock.calls.length).toBeGreaterThan(readsBeforeMessage); - expect(document.querySelector('[role="dialog"]')).not.toBeNull(); - expect(completeMock).not.toHaveBeenCalled(); - setupOptionsMock.mockResolvedValue({ ...options, interaction: connectedConnectionIntentInteraction }); - await act(() => button("Simulate OAuth callback")?.click()); - await waitForAssertion(() => expect(document.querySelector('[role="dialog"]')).toBeNull()); - expect(completeMock).not.toHaveBeenCalled(); - }); - - it("passes existing choices and requires the requester without locking tool setup to that agent", async () => { - let resolveSetup!: (value: unknown) => void; - setupOptionsMock.mockReturnValue( - new Promise((resolve) => { - resolveSetup = resolve; - }), - ); - renderBody(); - - await act(() => button("Connect / Use existing")?.click()); - expect(document.body.textContent).toContain("Loading connection options…"); - - await act(async () => { - resolveSetup({ - requestedAgentId: "agent-requesting", - existingConnections: [ - { id: "connection-one", name: "Carol's Notion" }, - { id: "connection-two", name: "Team Notion" }, - ], - }); - }); - await flush(); - - expect( - document.querySelector('[data-testid="requested-agent"]')?.textContent, - ).toBe(""); - expect(document.querySelector('[data-testid="required-agent"]')?.textContent).toBe("agent-requesting"); - expect(document.body.textContent).toContain("New connections default to all agents"); - expect(document.body.textContent).not.toContain("Access is added only for this agent"); - expect( - document.querySelector('[data-testid="existing-count"]')?.textContent, - ).toBe("2"); - expect(button("Use Carol's Notion")).toBeDefined(); - expect(button("Use Team Notion")).toBeDefined(); - expect(button("Connect new")).toBeDefined(); - }); - - it("keeps a load failure open with readable copy and recovers through the query retry", async () => { - setupOptionsMock.mockRejectedValueOnce(new ApiError("Request failed: 500", 500, { error: "internal_error" })); - renderBody(); - await act(() => button("Connect / Use existing")?.click()); - await flush(); - - expect(document.querySelector('[data-query-view="error"]')).not.toBeNull(); - expect(document.body.textContent).toContain("Couldn't load connection setup"); - expect(document.body.textContent).not.toContain("internal_error"); - expect(document.body.textContent).not.toContain("Request failed: 500"); - setupOptionsMock.mockResolvedValueOnce({ - requestedAgentId: "agent-requesting", - existingConnections: [], - }); - await act(() => button("Retry")?.click()); - await flush(); - expect( - document.querySelector('[data-testid="shared-connection-setup"]'), - ).not.toBeNull(); - expect(document.querySelector('[data-query-view="error"]')).toBeNull(); - }); - - it("keeps loaded setup options usable when a refetch fails during an outage", async () => { - renderBody(); - await act(() => button("Connect / Use existing")?.click()); - await flush(); - expect( - document.querySelector('[data-testid="shared-connection-setup"]'), - ).not.toBeNull(); - - setupOptionsMock.mockRejectedValue( - new ApiError("Paperclip is restarting.", 503, { error: "tenant_app_unavailable" }), - ); - await act(async () => { - await queryClient.invalidateQueries(); - }); - await flush(); - - expect( - document.querySelector('[data-testid="shared-connection-setup"]'), - ).not.toBeNull(); - expect(document.querySelector('[data-query-view="error"]')).toBeNull(); - expect(document.body.textContent).not.toContain("Paperclip is restarting."); - expect(document.body.textContent).not.toContain("Couldn't load connection setup"); - }); - - it("completes an existing connection, closes, restores focus, and invalidates each task query once", async () => { - setupOptionsMock.mockResolvedValue({ - requestedAgentId: "agent-requesting", - existingConnections: [{ id: "connection-one", name: "Carol's Notion" }], - }); - renderBody(); - const trigger = button("Connect / Use existing")!; - const invalidation = vi.spyOn(queryClient, "invalidateQueries"); - - await act(() => trigger.click()); - await flush(); - await act(() => button("Use Carol's Notion")?.click()); - await flush(); - - expect(completeMock).toHaveBeenCalledWith( - pendingConnectionIntentInteraction.id, - "connection-one", - ); - expect( - document.querySelector('[data-testid="shared-connection-setup"]'), - ).toBeNull(); - await waitForAssertion(() => - expect(document.activeElement).toBe( - document.querySelector( - '[data-testid="connection-intent-focus-target"]', - ), - ), - ); - expect(invalidation).toHaveBeenCalledTimes(2); - expect(invalidation).toHaveBeenCalledWith({ - queryKey: ["issues", "interactions"], - }); - expect(invalidation).toHaveBeenCalledWith({ - queryKey: ["issues", "detail"], - }); - }); - - it("restores focus when completion remounts the intent in a different task host", async () => { - setupOptionsMock.mockResolvedValue({ - requestedAgentId: "agent-requesting", - existingConnections: [{ id: "connection-one", name: "Carol's Notion" }], - }); - const acceptedInteraction = { - ...pendingConnectionIntentInteraction, - status: "accepted", - resolvedAt: new Date("2026-08-26T12:00:00.000Z"), - result: { - version: 1, - outcome: "connected", - connectionId: "connection-one", - }, - } as ConnectionIntentInteraction; - let showAcceptedInteraction!: () => void; - - function RemountingTaskHost() { - const [interaction, setInteraction] = useState( - pendingConnectionIntentInteraction, - ); - showAcceptedInteraction = () => setInteraction(acceptedInteraction); - return ( - - ); - } - - completeMock.mockImplementation(async () => { - showAcceptedInteraction(); - return acceptedInteraction; - }); - renderNode(); - - await act(() => button("Connect / Use existing")?.click()); - await flush(); - await act(() => button("Use Carol's Notion")?.click()); - - await waitForAssertion(() => { - const target = document.getElementById( - `connection-intent-focus-target-${acceptedInteraction.id}`, - ); - expect(document.body.textContent).toContain("Notion connected"); - expect(document.activeElement).toBe(target); - }); - }); - - it("keeps the dialog open and surfaces completion failures", async () => { - completeMock.mockRejectedValue(new Error("install commit failed")); - renderBody(); - await act(() => button("Connect / Use existing")?.click()); - await flush(); - await act(() => button("Connect new")?.click()); - await flush(); - - expect( - document.querySelector('[data-testid="shared-connection-setup"]'), - ).not.toBeNull(); - expect( - document.body.querySelector('[role="alert"]')?.textContent, - ).toContain("install commit failed"); - }); - - it("declines once with pending controls disabled and invalidates each task query once", async () => { - let finishDecline!: () => void; - declineMock.mockReturnValue( - new Promise((resolve) => { - finishDecline = resolve; - }), - ); - renderBody(); - const invalidation = vi.spyOn(queryClient, "invalidateQueries"); - const decline = button("Not now")!; - - await act(() => decline.click()); - await flush(); - expect(decline.disabled).toBe(true); - decline.click(); - expect(declineMock).toHaveBeenCalledTimes(1); - await act(async () => finishDecline()); - await flush(); - - expect(invalidation).toHaveBeenCalledTimes(2); - }); - - it("turns shared-flow retry signals into the server-authored retry phase", async () => { - renderBody(); - await act(() => button("Connect / Use existing")?.click()); - await flush(); - await act(() => button("Simulate retry")?.click()); - await flush(); - expect(setPhaseMock).toHaveBeenCalledWith( - pendingConnectionIntentInteraction.id, - "needs_retry", - ); - }); -}); - - -describe("AI repair inside the card", () => { - const interaction: ConnectionIntentInteraction = { ...pendingConnectionIntentInteraction, payload: { ...pendingConnectionIntentInteraction.payload, purpose: "ai" } }; - const connection = { id: "selected-account", name: "My Codex account", provider: "openai", method: "api_key", ownership: "personal", ownerName: "Dotta", status: "revoked" }; - it.each(["openrouter", "bedrock", "gateway"] as const)("retains the selected %s route through task-card account repair", async kind => { - const routing = kind === "bedrock" - ? { kind, protocol: "bedrock", region: "us-east-1", auth: "bearer", models: [] } - : { kind, protocol: "responses", auth: "bearer", models: [], ...(kind === "gateway" ? { baseUrl: "https://gateway.example/v1" } : {}) }; - const routedConnection = { ...connection, provider: kind === "bedrock" ? "anthropic" : kind === "openrouter" ? "openrouter" : "openai", routing }; - setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiRepair: { connection: routedConnection, canReconnect: true } }); - completeMock.mockResolvedValue({ ...interaction, status: "accepted" }); - renderBody(interaction); await flush(); - await act(() => button("Fix connection")!.click()); - expect(document.querySelector('[data-testid="shared-ai-credentials"]')).toBeNull(); - expect(routedCredentialRender.mock.lastCall![0]).toMatchObject({ companyId: interaction.companyId, agentId: interaction.payload.requestingAgentId, reconnect: routedConnection }); - await act(() => button("Reconnect routed account")!.click()); - expect(completeMock).toHaveBeenCalledWith(interaction.id, connection.id); - }); - - it.each([false, true])("requires atomic validated legacy adoption (validation fails: %s)", async (fails) => { - const binding = { provider: "openai", method: "subscription", mode: "responsible_user" }; - setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiConnection: binding, aiConnectionRequiresAdoption: true }); - if (fails) adoptMock.mockRejectedValue(new Error("Connection test failed")); - else adoptMock.mockResolvedValue({ ...interaction, status: "accepted" }); - renderBody(interaction); - await waitForAssertion(() => expect(button("Connect OpenAI")).toBeDefined()); - await act(() => button("Connect OpenAI")!.click()); - await act(() => button("Reconnect selected account")!.click()); - expect(adoptMock).not.toHaveBeenCalled(); - expect(document.body.textContent).toContain("Use your OpenAI account"); - expect(document.body.textContent).toContain("Your account is connected."); - expect(document.body.textContent).toContain("This replaces the agent’s existing authentication"); - await act(() => button("Use connection and continue")!.click()); - await flush(); - expect(adoptMock).toHaveBeenCalledWith(interaction.payload.requestingAgentId, interaction.id, "new-ai-account", interaction.companyId); - expect(updateAgentMock).not.toHaveBeenCalled(); - expect(installMock).not.toHaveBeenCalled(); - expect(completeMock).not.toHaveBeenCalled(); - if (fails) expect(document.querySelector('[role="alert"]')?.textContent).toContain("Connection test failed"); - }); - it.each(["anthropic", "openai"])("connects a missing %s default directly in the task", async (provider) => { - setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiConnection: { provider, method: "api_key", mode: "responsible_user" } }); - completeMock.mockResolvedValue({ ...interaction, status: "accepted" }); - renderBody(interaction); await flush(); - const providerName = provider === "anthropic" ? "Claude" : "OpenAI"; - await waitForAssertion(() => expect(document.body.textContent).toContain(`Connect your ${providerName} account`)); - expect(document.body.textContent).toContain("needs your own AI connection"); - await act(() => button(`Connect ${providerName}`)!.click()); - expect(document.querySelector('[role="dialog"]')).toBeNull(); - expect(document.querySelector('[data-testid="shared-connection-setup"]')).toBeNull(); - expect(document.querySelector('[data-testid="shared-ai-credentials"]')).not.toBeNull(); - expect(credentialRender.mock.lastCall![0]).toMatchObject({ provider, hideName: true, ownership: "personal", agentIds: [interaction.payload.requestingAgentId], allAgents: false }); - expect(credentialRender.mock.lastCall![0].connectionId).toBeUndefined(); - expect(credentialRender.mock.lastCall![0].fixedMethod).toBeUndefined(); - expect(document.body.textContent).toContain("the task will resume automatically"); - await act(() => button("Reconnect selected account")!.click()); - expect(completeMock).toHaveBeenCalledWith(interaction.id, "new-ai-account"); - }); - it("reuses authentication inline, preserves the selected account, cancels with focus, and completes", async () => { - setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiRepair: { connection, canReconnect: true } }); - completeMock.mockResolvedValue({ ...interaction, status: "accepted" }); - renderBody(interaction); - await flush(); - await act(() => button("Fix connection")!.click()); - expect(document.querySelector('[role="dialog"]')).toBeNull(); - expect(document.querySelector('[data-testid="ai-connection-inline-repair"]')?.textContent).not.toContain("My Codex account"); - expect(credentialRender.mock.lastCall![0]).toMatchObject({ name: "My Codex account", hideName: true, fixedMethod: false, connectionId: "selected-account" }); - await act(() => button("Cancel repair")!.click()); - await waitForAssertion(() => expect(document.activeElement?.getAttribute("data-testid")).toBe("connection-intent-focus-target")); - expect(completeMock).not.toHaveBeenCalled(); - await act(() => button("Fix connection")!.click()); - await act(() => button("Reconnect selected account")!.click()); - expect(completeMock).toHaveBeenCalledWith(interaction.id, "selected-account"); - }); - it.each(["responsible_user", "delegated", "shared"] as const)("selects a different authentication method for a %s binding before resuming", async (mode) => { - const binding = { provider: "openai", method: "api_key", mode, ...(mode !== "responsible_user" ? { connectionId: connection.id, grantId: "old-grant" } : {}) }; - setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiConnection: binding, aiRepair: { connection: { ...connection, grantId: "old-grant" }, canReconnect: true } }); - getAgentMock.mockResolvedValue({ id: interaction.payload.requestingAgentId, runtimeConfig: { aiConnection: binding, heartbeat: { enabled: true } } }); - completeMock.mockResolvedValue({ ...interaction, status: "accepted" }); - renderBody(interaction); await flush(); - await act(() => button("Fix connection")!.click()); - await act(() => credentialRender.mock.lastCall![0].onComplete({ connectionId: "new-subscription", grantId: "new-grant", method: "subscription" })); - await flush(); - if (mode === "responsible_user") { - expect(setDefaultMock).toHaveBeenCalledWith(interaction.companyId, "new-grant"); - expect(updateAgentMock).not.toHaveBeenCalled(); - } else { - expect(updateAgentMock).toHaveBeenCalledWith(interaction.payload.requestingAgentId, { runtimeConfig: { heartbeat: { enabled: true }, aiConnection: { ...binding, method: "subscription", connectionId: "new-subscription", grantId: "new-grant" } } }, interaction.companyId); - expect(setDefaultMock).not.toHaveBeenCalled(); - } - expect(completeMock).toHaveBeenCalledWith(interaction.id, "new-subscription"); - }); - it("keeps a failed account switch pending and retries the saved account", async () => { - setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiConnection: { provider: "openai", method: "api_key", mode: "responsible_user" }, aiRepair: { connection, canReconnect: true } }); - setDefaultMock.mockRejectedValueOnce(new Error("Could not select this account")); - renderBody(interaction); await flush(); - await act(() => button("Fix connection")!.click()); - await act(() => credentialRender.mock.lastCall![0].onComplete({ connectionId: "new-subscription", grantId: "new-grant", method: "subscription" })); - await flush(); - expect(completeMock).not.toHaveBeenCalled(); - expect(document.querySelector('[role="alert"]')?.textContent).toContain("Could not select this account"); - await act(() => button("Retry using this connection")!.click()); - await flush(); - expect(completeMock).toHaveBeenCalledWith(interaction.id, "new-subscription"); - }); - it("clears an account-selection retry when its setup is abandoned", async () => { - setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiConnection: { provider: "openai", method: "api_key", mode: "responsible_user" }, aiRepair: { connection, canReconnect: true } }); - setDefaultMock.mockRejectedValueOnce(new Error("Could not select this account")); - renderBody(interaction); await flush(); - await act(() => button("Fix connection")!.click()); - await act(() => credentialRender.mock.lastCall![0].onComplete({ connectionId: "new-subscription", grantId: "new-grant", method: "subscription" })); - await flush(); - expect(button("Retry using this connection")).toBeDefined(); - await act(() => button("Cancel repair")!.click()); - await act(() => button("Fix connection")!.click()); - expect(button("Retry using this connection")).toBeUndefined(); - expect(document.querySelector('[role="alert"]')).toBeNull(); - expect(completeMock).not.toHaveBeenCalled(); - }); - it("keeps a late credential save after cancellation from accepting the request", async () => { - setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiRepair: { connection, canReconnect: true } }); - renderBody(interaction); await flush(); - await act(() => button("Fix connection")!.click()); - const abandoned = credentialRender.mock.lastCall![0]; - await act(() => button("Cancel repair")!.click()); - await act(() => button("Fix connection")!.click()); - await act(() => abandoned.onComplete({ connectionId: connection.id, grantId: "grant", method: "api_key" })); - expect(completeMock).not.toHaveBeenCalled(); - }); - it("offers continuation for the restored account without another login", async () => { - setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [connection], aiRepair: { connection, canReconnect: true } }); - renderBody(interaction); await flush(); - await act(() => button("Fix connection")!.click()); - expect(document.querySelector('[data-testid="shared-ai-credentials"]')).toBeNull(); - await act(() => button("Continue task")!.click()); - expect(completeMock).toHaveBeenCalledWith(interaction.id, connection.id); - }); - it("does not let another user reconnect the owner's account", async () => { - setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiRepair: { connection, canReconnect: false } }); - renderBody(interaction); await flush(); - await act(() => button("Fix connection")!.click()); - expect(document.body.textContent).toContain("Dotta must reconnect My Codex account"); - expect(document.querySelector('[data-testid="shared-ai-credentials"]')).toBeNull(); - }); - it("shows a withdrawn AI request as terminal without another setup action", () => { - renderBody({ ...interaction, status: "cancelled", resolvedAt: new Date() }); - expect(document.body.textContent).toContain("Connection request withdrawn"); - expect(document.body.textContent).not.toContain("This task can’t run"); - expect(button("Fix connection")).toBeUndefined(); - expect(document.querySelector('[data-testid="connection-intent-terminal"]')).not.toBeNull(); - expect(setupOptionsMock).not.toHaveBeenCalled(); - expect(credentialRender).not.toHaveBeenCalled(); - }); - it("does not promise to run without credentials when declined", () => { - renderBody({ ...interaction, status: "rejected" }); - expect(document.body.textContent).toContain("The task still needs a working AI connection"); - expect(document.body.textContent).not.toContain("can continue without it"); - }); -}); - -describe("AgentMail inline setup", () => { - const interaction: ConnectionIntentInteraction = { - ...pendingConnectionIntentInteraction, - payload: { ...pendingConnectionIntentInteraction.payload, purpose: "channel", serviceSlug: "agentmail", serviceName: "AgentMail" }, - }; - async function clickReadyButton(label: string) { - await waitForAssertion(() => expect(button(label)?.disabled).toBe(false)); - await act(() => button(label)!.click()); - await flush(); - } - async function enterKey() { - await waitForAssertion(() => expect(document.querySelector('input[type="password"]')).not.toBeNull()); - const input = document.querySelector('input[type="password"]') as HTMLInputElement; - await act(() => { - Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "fixture-api-key"); - input.dispatchEvent(new Event("input", { bubbles: true })); - }); - } - it("shows only the key inline, saves company access for this agent and completes after inbox setup", async () => { - renderBody(interaction); - await flush(); - expect(document.querySelector('[role="dialog"]')).toBeNull(); - await waitForAssertion(() => expect(document.querySelectorAll("input")).toHaveLength(1)); - expect(document.querySelector('a[href="https://console.agentmail.to/dashboard/api-keys"]')).not.toBeNull(); - expect(document.querySelector('[role="radiogroup"], select')).toBeNull(); - expect(button("Connect AgentMail")?.disabled).toBe(true); - await enterKey(); - await clickReadyButton("Connect AgentMail"); - expect(emailConnectMock).toHaveBeenCalledWith(interaction.companyId, { - apiKey: "fixture-api-key", grantKind: "organization", allAgents: false, - agentIds: [interaction.payload.requestingAgentId], idempotencyKey: interaction.id, - }); - expect(emailSetupMock).toHaveBeenCalledWith(interaction.companyId, { - assignedAgentId: interaction.payload.requestingAgentId, credentialConnectionId: "email-account", - receiveMode: "websocket", idempotencyKey: interaction.id, - }); - expect(completeMock).toHaveBeenCalledWith(interaction.id, "email-inbox"); - }); - it("keeps invalid credentials retryable and does not create an inbox or accept the request", async () => { - emailConnectMock.mockRejectedValueOnce(new Error("AgentMail request failed (401)")); - renderBody(interaction); await flush(); await enterKey(); - await clickReadyButton("Connect AgentMail"); - expect(document.querySelector('[role="alert"]')?.textContent).toContain("401"); - expect(emailSetupMock).not.toHaveBeenCalled(); - expect(completeMock).not.toHaveBeenCalled(); - await clickReadyButton("Connect AgentMail"); - expect(completeMock).toHaveBeenCalledTimes(1); - }); - it("retries inbox setup without asking for or saving the key again", async () => { - emailSetupMock.mockRejectedValueOnce(new Error("Inbox setup unavailable")); - renderBody(interaction); await flush(); await enterKey(); - await clickReadyButton("Connect AgentMail"); - expect(completeMock).not.toHaveBeenCalled(); - expect(document.querySelector('input[type="password"]')).toBeNull(); - await clickReadyButton("Finish setup"); - expect(emailConnectMock).toHaveBeenCalledTimes(1); - expect(emailSetupMock).toHaveBeenCalledTimes(2); - expect(completeMock).toHaveBeenCalledWith(interaction.id, "email-inbox"); - }); - it("can choose another key after a saved key fails, retiring an empty draft and preserving the retry identity", async () => { - emailCredentialsMock.mockResolvedValue([{ id: "saved-account", label: "Saved key", scope: "organization", createdAt: "2026-10-01T14:00:00Z" }]); - emailSetupMock.mockRejectedValueOnce(new Error("Inbox already assigned")) - .mockRejectedValueOnce(new Error("Temporary provider failure")); - emailListMock.mockResolvedValue([{ id: interaction.id, address: null, status: "draft" }]); - renderBody(interaction); await flush(); - await waitForAssertion(() => expect(button("Connect AgentMail")?.disabled).toBe(false)); - expect((document.querySelector("select") as HTMLSelectElement)?.value).toBe("saved-account"); - expect(emailConnectMock).not.toHaveBeenCalled(); - await clickReadyButton("Connect AgentMail"); - expect(emailConnectMock).not.toHaveBeenCalled(); - await clickReadyButton("Change API key"); - expect(emailControlMock).toHaveBeenCalledWith(interaction.id, "remove"); - await enterKey(); - await clickReadyButton("Connect AgentMail"); - const next = emailSetupMock.mock.calls[1][1].idempotencyKey; - expect(next).not.toBe(interaction.id); - expect(emailConnectMock).toHaveBeenCalledWith(interaction.companyId, expect.objectContaining({ idempotencyKey: next })); - expect(sessionStorage.getItem(`paperclip.agentmail-inline:${interaction.companyId}:${interaction.id}`)).not.toContain("fixture-api-key"); - await act(() => root!.unmount()); host!.remove(); queryClient.clear(); - renderBody(interaction); await flush(); - await clickReadyButton("Finish setup"); - expect(emailSetupMock.mock.calls[2][1].idempotencyKey).toBe(next); - expect(emailConnectMock).toHaveBeenCalledTimes(1); - expect(completeMock).toHaveBeenCalledWith(interaction.id, "email-inbox"); - }); - it("does not switch keys after an inbox address is allocated", async () => { - setupOptionsMock.mockResolvedValue({ existingConnections: [], emailSetup: { credentialConnectionId: "saved-account", readyConnectionId: null } }); - emailListMock.mockResolvedValue([{ id: interaction.id, address: "reserved@example.test", status: "draft" }]); - renderBody(interaction); await flush(); - await clickReadyButton("Change API key"); - expect(document.body.textContent).toContain("reserved@example.test is already reserved"); - expect(emailControlMock).not.toHaveBeenCalled(); - expect(document.querySelector('input[type="password"]')).toBeNull(); - }); - it("recovers the server-saved account when refresh interrupted its response", async () => { - const resumedInteraction = { ...interaction, id: "a381e91e-7127-427d-9d2d-519d4deba89f" }; - sessionStorage.setItem(`paperclip.agentmail-inline:${interaction.companyId}:${resumedInteraction.id}`, JSON.stringify({ - setupRequestId: resumedInteraction.id, credentialId: null, inboxConnectionId: null, selectedCredentialId: "", - })); - setupOptionsMock.mockResolvedValue({ existingConnections: [], emailSetup: { credentialConnectionId: "server-saved-account", readyConnectionId: null } }); - renderBody(resumedInteraction); await flush(); - expect(document.querySelector('input[type="password"]')).toBeNull(); - await clickReadyButton("Finish setup"); - expect(emailConnectMock).not.toHaveBeenCalled(); - expect(emailSetupMock).toHaveBeenCalledWith(interaction.companyId, expect.objectContaining({ - credentialConnectionId: "server-saved-account", idempotencyKey: resumedInteraction.id, - })); - }); - it("keeps a different saved-key selection when recovering an interrupted save", async () => { - const resumedInteraction = { ...interaction, id: "a381e91e-7127-427d-9d2d-519d4deba89f" }; - sessionStorage.setItem(`paperclip.agentmail-inline:${interaction.companyId}:${resumedInteraction.id}`, JSON.stringify({ - setupRequestId: resumedInteraction.id, credentialId: null, inboxConnectionId: null, selectedCredentialId: "selected-account", - })); - emailCredentialsMock.mockResolvedValue([{ id: "selected-account", label: "My selected key", scope: "organization", createdAt: "2026-10-01T14:00:00Z" }]); - setupOptionsMock.mockResolvedValue({ existingConnections: [], emailSetup: { credentialConnectionId: "earlier-account", readyConnectionId: null } }); - renderBody(resumedInteraction); await flush(); - await waitForAssertion(() => expect((document.querySelector('select') as HTMLSelectElement)?.value).toBe("selected-account")); - await clickReadyButton("Connect AgentMail"); - expect(emailConnectMock).not.toHaveBeenCalled(); - expect(emailSetupMock).toHaveBeenCalledWith(interaction.companyId, expect.objectContaining({ - credentialConnectionId: "selected-account", idempotencyKey: resumedInteraction.id, - })); - }); - it("does not restore an abandoned server account after the user changes keys", async () => { - const replacementRequestId = "a381e91e-7127-427d-9d2d-519d4deba89f"; - sessionStorage.setItem(`paperclip.agentmail-inline:${interaction.companyId}:${interaction.id}`, JSON.stringify({ - setupRequestId: replacementRequestId, credentialId: null, inboxConnectionId: null, selectedCredentialId: "", - })); - setupOptionsMock.mockResolvedValue({ existingConnections: [], emailSetup: { credentialConnectionId: "abandoned-account", readyConnectionId: null } }); - renderBody(interaction); await flush(); await enterKey(); - await clickReadyButton("Connect AgentMail"); - expect(emailConnectMock).toHaveBeenCalledWith(interaction.companyId, expect.objectContaining({ idempotencyKey: replacementRequestId })); - expect(emailSetupMock).toHaveBeenCalledWith(interaction.companyId, expect.objectContaining({ - credentialConnectionId: "email-account", idempotencyKey: replacementRequestId, - })); - }); - it("resumes a saved account after reload and retries acceptance without recreating the inbox", async () => { - setupOptionsMock.mockResolvedValue({ existingConnections: [], emailSetup: { credentialConnectionId: "email-account", readyConnectionId: "email-inbox" } }); - completeMock.mockRejectedValueOnce(new Error("Retry completion")); - renderBody(interaction); await flush(); - await clickReadyButton("Continue"); - await clickReadyButton("Continue"); - expect(emailConnectMock).not.toHaveBeenCalled(); - expect(emailSetupMock).not.toHaveBeenCalled(); - expect(completeMock).toHaveBeenCalledTimes(2); - }); - it("declines without provider requests and hides credentials from other viewers", async () => { - renderBody(interaction); await flush(); - await clickReadyButton("Not now"); - expect(declineMock).toHaveBeenCalledWith(interaction.id); - expect(emailConnectMock).not.toHaveBeenCalled(); - expect(emailSetupMock).not.toHaveBeenCalled(); - await act(() => root!.render()); - expect(document.querySelector('input')).toBeNull(); - }); - it("can decline even when inbox setup options fail to load", async () => { - setupOptionsMock.mockRejectedValue(new Error("Email setup is unavailable")); - renderBody(interaction); - await waitForAssertion(() => expect(document.body.textContent).toContain("Email setup is unavailable")); - await clickReadyButton("Not now"); - expect(declineMock).toHaveBeenCalledWith(interaction.id); - expect(emailConnectMock).not.toHaveBeenCalled(); - }); -}); - -describe("embedded agent access request", () => { - const accessRequest = { - connectionId: "22222222-2222-4222-8222-222222222222", - connectionName: "Saved Composio", - tools: [ - { catalogEntryId: "33333333-3333-4333-8333-333333333333", toolName: "COMPOSIO_SEARCH_TOOLS", versionHash: "v1", permission: "allowed" as const }, - { catalogEntryId: "44444444-4444-4444-8444-444444444444", toolName: "COMPOSIO_MANAGE_CONNECTIONS", versionHash: "v1", permission: "ask_first" as const }, - ], - }; - const interaction: ConnectionIntentInteraction = { ...pendingConnectionIntentInteraction, payload: { ...pendingConnectionIntentInteraction.payload, serviceName: "Composio", accessRequest } }; - - it("shows the exact tool permissions before granting inline without a setup modal", async () => { - setupOptionsMock.mockResolvedValue({ canGrantAccess: true }); - getAgentMock.mockResolvedValue({ id: interaction.payload.requestingAgentId, name: "Researcher" }); - completeMock.mockResolvedValue({ ...interaction, status: "accepted", result: { version: 1, outcome: "connected", connectionId: accessRequest.connectionId } }); - renderBody(interaction); - await waitForAssertion(() => expect(button("Grant access")?.disabled).toBe(false)); - expect(document.body.textContent).toContain("Grant Researcher access to “Saved Composio”?"); - expect(document.body.querySelector('[data-slot="agent-avatar"]')?.getAttribute("aria-label")).toBe("Researcher"); - expect(Array.from(document.body.querySelectorAll('ul[aria-label="Tool permissions"] li'), row => row.textContent)).toEqual([ - "COMPOSIO_SEARCH_TOOLSAllowed", - "COMPOSIO_MANAGE_CONNECTIONSAsk first", - ]); - expect(completeMock).not.toHaveBeenCalled(); - await act(() => button("Grant access")?.click()); - await waitForAssertion(() => expect(completeMock).toHaveBeenCalledWith(interaction.id, accessRequest.connectionId)); - expect(document.body.querySelector('[role="dialog"]')).toBeNull(); - }); - - it("keeps errors visible and does not allow a non-manager to grant", async () => { - setupOptionsMock.mockResolvedValue({ canGrantAccess: false }); - renderBody(interaction); - await waitForAssertion(() => expect(document.body.textContent).toContain("Connection manager required")); - expect(button("Grant access")?.disabled).toBe(true); - expect(completeMock).not.toHaveBeenCalled(); - }); - - it("supports declining and displays permission errors on the card", async () => { - setupOptionsMock.mockResolvedValue({ canGrantAccess: true }); - completeMock.mockRejectedValue(new Error("Tools changed. Request access again.")); - renderBody(interaction); - await waitForAssertion(() => expect(button("Grant access")?.disabled).toBe(false)); - await act(() => button("Grant access")?.click()); - await waitForAssertion(() => expect(document.body.querySelector('[role="alert"]')?.textContent).toContain("Tools changed")); - await act(() => button("Not now")?.click()); - await waitForAssertion(() => expect(declineMock).toHaveBeenCalledWith(interaction.id)); - }); - - it("shows resolved access and does not expose controls to other users", () => { - renderBody({ ...interaction, status: "accepted", result: { version: 1, outcome: "connected", connectionId: accessRequest.connectionId } }); - expect(document.body.textContent).toContain("Composio access granted"); - expect(button("Grant access")).toBeUndefined(); - }); -}); diff --git a/ui/src/features/connections/GoogleWorkspaceServices.test.tsx b/ui/src/features/connections/GoogleWorkspaceServices.test.tsx deleted file mode 100644 index 3ff82f854ae..00000000000 --- a/ui/src/features/connections/GoogleWorkspaceServices.test.tsx +++ /dev/null @@ -1,245 +0,0 @@ -// @vitest-environment jsdom -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { googleWorkspaceSelectedScopes, type ToolConnection } from "@paperclipai/shared"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { GoogleWorkspaceServicesDialog } from "./GoogleWorkspaceServices"; -import { GOOGLE_WORKSPACE_PRIVACY_POLICY_URL, googleWorkspaceDataUseDisclosure } from "./googleWorkspaceDisclosure"; - -const listGrants = vi.hoisted(() => vi.fn()); -vi.mock("@/api/tools", () => ({ toolsApi: { listConnectionGrants: listGrants } })); -vi.mock("@/pages/apps/AppLogo", () => ({ AppLogo: () => null })); - -describe("Workspace service consent", () => { - let root: Root; - let container: HTMLDivElement; - let client: QueryClient; - const onContinue = vi.fn(); - const onCancel = vi.fn(); - const existing = { id: "workspace-account", status: "active", credentialPolicy: "per_user", config: {} } as ToolConnection; - const flush = async () => { await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); }; - const click = async (name: string) => { - const button = [...document.querySelectorAll("button")].find(item => item.textContent === name)!; - await act(async () => { button.click(); }); - await flush(); - }; - async function render(connection?: ToolConnection) { - await act(async () => { root.render( - - ); }); - await flush(); - await flush(); - } - beforeEach(() => { - vi.clearAllMocks(); - listGrants.mockResolvedValue({ currentUserId: "me", grants: [] }); - container = document.createElement("div"); - document.body.append(container); - root = createRoot(container); - client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); - }); - afterEach(async () => { - await act(async () => { root.unmount(); }); - client.clear(); - container.remove(); - }); - - it("defaults all three groups to write and submits only their selections", async () => { - await render(); - expect([...document.querySelectorAll('[role="switch"]')].map(item => item.getAttribute("aria-checked"))).toEqual(["true", "true", "true"]); - expect([...document.querySelectorAll("select")].map(item => item.value)).toEqual(["write", "write", "write"]); - expect(listGrants).not.toHaveBeenCalled(); - await click("Continue"); - expect(onContinue).toHaveBeenCalledWith({ gmail: "write", drive: "write", calendar: "write" }); - }); - - it("restores the current user's saved request, not an organization or another user's broader grant", async () => { - listGrants.mockResolvedValue({ currentUserId: "me", grants: [ - { kind: "organization", providerTenant: { oauth: { requestedScopes: ["https://www.googleapis.com/auth/documents"] } } }, - { kind: "user", subjectUserId: "other", providerTenant: { oauth: { requestedScopes: ["https://www.googleapis.com/auth/calendar.events"] } } }, - { kind: "user", subjectUserId: "me", providerTenant: { oauth: { - requestedScopes: ["https://www.googleapis.com/auth/gmail.readonly"], - scopes: ["https://www.googleapis.com/auth/gmail.readonly", "https://www.googleapis.com/auth/documents"], - } } }, - ] }); - await render(existing); - expect([...document.querySelectorAll('[role="switch"]')].map(item => item.getAttribute("aria-checked"))).toEqual(["true", "false", "false"]); - expect(document.querySelector("select")?.value).toBe("read"); - await click("Continue"); - expect(onContinue).toHaveBeenCalledWith({ gmail: "read" }); - }); - - it("restores a cold draft's selected services after declined OAuth", async () => { - await render({ ...existing, companyId: "company-1", status: "draft", config: { - workspaceSetup: { - version: 1, companyId: "company-1", connectionId: existing.id, - actorType: "user", actorId: "me", grantKind: "user", subjectId: "me", - requestedScopes: ["https://www.googleapis.com/auth/gmail.readonly"], - }, - oauth: { scopes: ["https://www.googleapis.com/auth/documents"] }, - } }); - expect([...document.querySelectorAll('[role="switch"]')].map(item => item.getAttribute("aria-checked"))).toEqual(["true", "false", "false"]); - expect(document.querySelector("select")?.value).toBe("read"); - await click("Continue"); - expect(onContinue).toHaveBeenCalledWith({ gmail: "read" }); - }); - - it.each([undefined, "another-user"])("requires a deliberate choice for an unbound draft (%s)", async (actorId) => { - await render({ ...existing, companyId: "company-1", status: "draft", config: { - ...(actorId ? { workspaceSetup: { - version: 1, companyId: "company-1", connectionId: existing.id, - actorType: "user", actorId, grantKind: "user", subjectId: "me", - requestedScopes: ["https://www.googleapis.com/auth/gmail.readonly"], - } } : {}), - oauth: { scopes: ["https://www.googleapis.com/auth/documents"] }, - } }); - expect([...document.querySelectorAll('[role="switch"]')].map(item => item.getAttribute("aria-checked"))).toEqual(["false", "false", "false"]); - const proceed = [...document.querySelectorAll("button")].find(item => item.textContent === "Continue")!; - expect(proceed.disabled).toBe(true); - expect(onContinue).not.toHaveBeenCalled(); - }); - - it("blocks on grant-load failure and retries without broadening the saved request", async () => { - listGrants.mockRejectedValueOnce(new Error("unavailable")); - await render(existing); - expect(document.body.textContent).toContain("Could not load your saved service access"); - expect(document.querySelector('[role="switch"]')).toBeNull(); - expect(onContinue).not.toHaveBeenCalled(); - listGrants.mockResolvedValue({ currentUserId: "me", grants: [] }); - await click("Try again"); - await flush(); - const continueButton = [...document.querySelectorAll("button")].find(item => item.textContent === "Continue")!; - expect(continueButton.disabled).toBe(true); - await click("Cancel"); - expect(onCancel).toHaveBeenCalledWith({}); - expect(onContinue).not.toHaveBeenCalled(); - }); - - it("restores only the addressed user's pending services on a saved draft", async () => { - listGrants.mockResolvedValue({ currentUserId: "me", grants: [] }); - await render({ ...existing, status: "draft", config: { oauth: { pendingWorkspaceServiceRequests: { - me: { requestedScopes: ["https://www.googleapis.com/auth/gmail.readonly"], requestedAt: "2026-10-26T10:00:00Z" }, - other: { requestedScopes: ["https://www.googleapis.com/auth/documents"], requestedAt: "2026-10-26T10:00:00Z" }, - } } } }); - await click("Continue"); - expect(listGrants).toHaveBeenCalledWith(existing.id); - expect(onContinue).toHaveBeenCalledWith({ gmail: "read" }); - }); - - it.each([true, false])("uses pending consent only when newer than the saved grant (newer: %s)", async newer => { - listGrants.mockResolvedValue({ currentUserId: "me", grants: [{ - kind: "user", subjectUserId: "me", updatedAt: "2026-10-26T10:00:00Z", - providerTenant: { oauth: { requestedScopes: googleWorkspaceSelectedScopes({ drive: "write" }), consentedAt: "2026-10-26T10:00:00Z" } }, - }] }); - await render({ ...existing, config: { oauth: { pendingWorkspaceServiceRequests: { - me: { requestedScopes: ["https://www.googleapis.com/auth/gmail.readonly"], requestedAt: newer ? "2026-10-26T11:00:00Z" : "2026-10-26T09:00:00Z" }, - } } } }); - await click("Continue"); - expect(onContinue).toHaveBeenCalledWith(newer ? { gmail: "read" } : { drive: "write" }); - }); - it.each([false, true])("preserves pending service choices through token refresh (legacy grant: %s)", async legacy => { - listGrants.mockResolvedValue({ currentUserId: "me", grants: [{ - kind: "user", subjectUserId: "me", createdAt: "2026-10-26T10:00:00Z", updatedAt: "2026-10-26T12:00:00Z", - providerTenant: { oauth: { requestedScopes: googleWorkspaceSelectedScopes({ drive: "write" }), - ...(legacy ? {} : { consentedAt: "2026-10-26T10:00:00Z" }), refreshedAt: "2026-10-26T12:00:00Z" } }, - }] }); - await render({ ...existing, config: { oauth: { pendingWorkspaceServiceRequests: { - me: { requestedScopes: ["https://www.googleapis.com/auth/gmail.readonly"], requestedAt: "2026-10-26T11:00:00Z" }, - } } } }); - await click("Continue"); - expect(onContinue).toHaveBeenCalledWith({ gmail: "read" }); - }); - -}); - -const GMAIL_SEND_NOTE = "Google's permission screen also mentions sending email; Paperclip does not send email."; - -describe("Google Workspace data-use disclosure", () => { - const use = [ - "Agents read this content only to do the tasks you give them.", - "To do that, the content is sent to the AI model provider configured for your workspace.", - "It is not used to train general AI models.", - "Results are saved in the task and its run history. They stay there until you delete them, even after you disconnect.", - ]; - - it.each([ - [{ gmail: "read" }, ["Gmail: agents can read and search your email."]], - [{ gmail: "write" }, ["Gmail: agents can read and search your email, and create drafts. Google's permission screen also mentions sending email; Paperclip does not send email."]], - [{ drive: "read" }, ["Drive: agents can read and search your files, Docs, Sheets and Slides."]], - [{ drive: "write" }, ["Drive: agents can read and search your files, Docs, Sheets and Slides. They can also create files and edit Docs, Sheets and Slides."]], - [{ calendar: "read" }, ["Calendar: agents can see your calendars, events and free/busy times."]], - [{ calendar: "write" }, ["Calendar: agents can see your calendars, events and free/busy times. They can also create, change and delete events, and respond to invitations."]], - ] as const)("describes only the selected service (%o)", (selection, access) => { - expect(googleWorkspaceDataUseDisclosure(selection)).toEqual({ access, use }); - }); - - it("lists every selected service in picker order and always explains sharing", () => { - const disclosure = googleWorkspaceDataUseDisclosure({ calendar: "read", gmail: "write", drive: "read" }); - expect(disclosure.access.map(line => line.split(":")[0])).toEqual(["Gmail", "Drive", "Calendar"]); - expect(disclosure.use).toContain("To do that, the content is sent to the AI model provider configured for your workspace."); - }); - - it("never claims Gmail can send: read only never mentions sending, read & write only says Paperclip does not send", () => { - const text = (gmail: "read" | "write") => { - const { access, use } = googleWorkspaceDataUseDisclosure({ gmail }); - return [...access, ...use].join(" "); - }; - expect(text("read")).not.toMatch(/send/i); - expect(text("write")).toContain("Paperclip does not send email."); - expect(text("write").replace(GMAIL_SEND_NOTE, "")).not.toMatch(/send/i); - }); - - it("says nothing with no services selected", () => { - expect(googleWorkspaceDataUseDisclosure({})).toEqual({ access: [], use: [] }); - }); -}); - -describe("Workspace picker disclosure", () => { - let root: Root; - let container: HTMLDivElement; - const flush = async () => { await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); }; - beforeEach(() => { - container = document.createElement("div"); - document.body.append(container); - root = createRoot(container); - }); - afterEach(async () => { - await act(async () => { root.unmount(); }); - container.remove(); - }); - async function render(initial?: Record) { - await act(async () => { root.render( - - ); }); - await flush(); - } - const disclosure = () => document.querySelector('[aria-label="How Paperclip uses your Google data"]'); - - it("shows the selected services, sharing and privacy policy before Continue", async () => { - await render({ gmail: "write", calendar: "read" }); - const block = disclosure()!; - expect(block.textContent).toContain("Gmail: agents can read and search your email, and create drafts. Google's permission screen also mentions sending email; Paperclip does not send email."); - expect(block.textContent).toContain("Calendar: agents can see your calendars, events and free/busy times."); - expect(block.textContent).not.toContain("Drive"); - expect(block.textContent!.replace(GMAIL_SEND_NOTE, "")).not.toMatch(/\bsend/i); - expect(block.textContent).toContain("the content is sent to the AI model provider configured for your workspace"); - const link = block.querySelector("a")!; - expect(link.getAttribute("href")).toBe(GOOGLE_WORKSPACE_PRIVACY_POLICY_URL); - expect(GOOGLE_WORKSPACE_PRIVACY_POLICY_URL).toBe("https://paperclip.ing/privacy"); - expect(link.getAttribute("target")).toBe("_blank"); - expect(link.getAttribute("rel")).toContain("noopener"); - expect(link.textContent).toContain("Limited Use"); - const footer = document.querySelector("footer")!; - expect(block.compareDocumentPosition(footer) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); - }); - - it("follows the selection as services are turned off", async () => { - await render({ drive: "read" }); - expect(disclosure()!.textContent).toContain("Drive: agents can read and search your files"); - const toggle = document.querySelector("#workspace-service-drive")!; - await act(async () => { toggle.click(); }); - expect(disclosure()).toBeNull(); - expect(document.body.textContent).toContain("Select at least one service to continue."); - }); -}); diff --git a/ui/src/features/connections/MachineSignInSetup.test.tsx b/ui/src/features/connections/MachineSignInSetup.test.tsx deleted file mode 100644 index 6dcb9b52ebb..00000000000 --- a/ui/src/features/connections/MachineSignInSetup.test.tsx +++ /dev/null @@ -1,161 +0,0 @@ -// @vitest-environment jsdom -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import type { ConnectToolAppResult, MachineSignInSetupResult } from "@paperclipai/shared"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { MachineSignInSetup, type MachineSignInClient } from "./MachineSignInSetup"; - -vi.mock("@/api/tools", () => ({ toolsApi: {} })); - -const draft = { - connectionId: "connection-1", - connection: {}, - machineSignIn: { - connectionId: "connection-1", method: "paperclip_key", clientId: null, issuer: "https://auth.example", tokenUrl: "https://auth.example/token", - scopes: [], hasClientSecret: false, lastTokenAt: null, pendingPublicKey: null, - publicKey: { keyId: "kid-1", algorithm: "RS256", pem: "-----BEGIN PUBLIC KEY-----\nabc\n-----END PUBLIC KEY-----\n", jwk: { kty: "RSA", kid: "kid-1" }, createdAt: "2026-11-13T00:00:00Z" }, - }, -} as unknown as MachineSignInSetupResult; - -describe("Machine sign-in setup", () => { - let root: Root; - let container: HTMLDivElement; - const flush = async () => { await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); }; - const button = (name: string) => [...container.querySelectorAll("button")].find((item) => item.textContent === name); - const click = async (name: string) => { await act(async () => { button(name)!.click(); }); await flush(); }; - const type = async (id: string, value: string) => { - const input = container.querySelector(`#${id}`)!; - await act(async () => { - Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value); - input.dispatchEvent(new Event("input", { bubbles: true })); - }); - }; - - beforeEach(() => { - container = document.createElement("div"); - document.body.append(container); - root = createRoot(container); - }); - afterEach(() => { - act(() => root.unmount()); - container.remove(); - }); - - it("creates a key, shows the public key to register, then tests with the client ID", async () => { - const client: MachineSignInClient = { - create: vi.fn(async () => draft), - test: vi.fn(async () => ({ connectionId: "connection-1" }) as ConnectToolAppResult), - status: vi.fn(), - }; - const onConnected = vi.fn(); - await act(async () => { - root.render( undefined} onConnected={onConnected} />); - }); - expect(container.textContent).toContain("Paperclip key (recommended)"); - await click("Create key"); - expect(client.create).toHaveBeenCalledWith("company-1", { link: "https://mcp.example/mcp", method: "paperclip_key" }); - expect(container.textContent).toContain("Register this public key"); - expect(container.querySelector("textarea")?.value).toContain("BEGIN PUBLIC KEY"); - expect(button("Test connection")?.disabled).toBe(true); - await type("machine-sign-in-client-id-confirm", "paperclip-automation"); - await click("Test connection"); - expect(client.test).toHaveBeenCalledWith("connection-1", { clientId: "paperclip-automation", scopes: "" }); - expect(onConnected).toHaveBeenCalled(); - }); - - it("keeps the draft and shows the provider's answer when the test fails", async () => { - const client: MachineSignInClient = { - create: vi.fn(async () => draft), - test: vi.fn(async () => { throw new Error("The provider didn't accept Paperclip's key."); }), - status: vi.fn(), - }; - await act(async () => { - root.render( undefined} onConnected={() => undefined} />); - }); - await type("machine-sign-in-client-id-confirm", "wrong"); - await click("Test connection"); - expect(container.textContent).toContain("Machine sign-in didn’t work"); - expect(container.textContent).toContain("The provider didn't accept Paperclip's key."); - expect(container.textContent).toContain("Register this public key"); - }); - - it("asks for the client ID and secret together for a client secret", async () => { - const client: MachineSignInClient = { - create: vi.fn(async () => ({ ...draft, machineSignIn: { ...draft.machineSignIn, method: "client_secret" as const, publicKey: null } })), - test: vi.fn(async () => ({}) as ConnectToolAppResult), - status: vi.fn(), - }; - await act(async () => { - root.render( undefined} onConnected={() => undefined} />); - }); - expect(button("Test connection")?.disabled).toBe(true); - await type("machine-sign-in-client-id", "id-1"); - await type("machine-sign-in-client-secret", "secret-1"); - await click("Test connection"); - expect(client.create).toHaveBeenCalledWith("company-1", expect.objectContaining({ method: "client_secret", clientId: "id-1", clientSecret: "secret-1", applicationId: "app-1" })); - expect(client.test).toHaveBeenCalledWith("connection-1", { clientId: "id-1", scopes: "" }); - }); - - it("lets a wrong secret be replaced after a failed test", async () => { - const secretDraft = { ...draft, machineSignIn: { ...draft.machineSignIn, method: "client_secret" as const, publicKey: null, clientId: "id-1", hasClientSecret: true, scopes: ["a.read"] } }; - const client: MachineSignInClient = { - create: vi.fn(), - test: vi.fn(async () => { throw new Error("The provider didn't accept the client ID and secret."); }), - status: vi.fn(), - }; - await act(async () => { - root.render( undefined} onConnected={() => undefined} />); - }); - await click("Test connection"); - expect(container.querySelector("#machine-sign-in-client-secret-replace")).not.toBeNull(); - await type("machine-sign-in-client-secret-replace", "fixed-secret"); - await type("machine-sign-in-scopes-confirm", ""); - await click("Test connection"); - expect(client.test).toHaveBeenLastCalledWith("connection-1", { clientId: "id-1", scopes: "", clientSecret: "fixed-secret" }); - }); - - it("resumes the key draft this tab started instead of creating another", async () => { - sessionStorage.setItem("paperclip.machine-sign-in-draft.v2:company-1:new:https://mcp.example/mcp", "connection-1"); - let finish!: (value: typeof draft.machineSignIn) => void; - const client: MachineSignInClient = { - create: vi.fn(), - test: vi.fn(), - status: vi.fn(() => new Promise((resolve) => { finish = resolve; })), - }; - await act(async () => { - root.render( undefined} onConnected={() => undefined} />); - }); - // No second draft can be started while the saved one loads. - expect(button("Create key")?.disabled).toBe(true); - await act(async () => { finish(draft.machineSignIn); }); - await flush(); - expect(client.status).toHaveBeenCalledWith("connection-1"); - expect(container.textContent).toContain("Register this public key"); - expect(client.create).not.toHaveBeenCalled(); - sessionStorage.clear(); - }); - - it("never resumes a draft started for a different app", async () => { - const client: MachineSignInClient = { - create: vi.fn(async () => draft), - test: vi.fn(), - status: vi.fn(async () => draft.machineSignIn), - }; - // App A's setup creates a key draft in this tab, then the admin leaves it. - await act(async () => { - root.render( undefined} onConnected={() => undefined} />); - }); - await click("Create key"); - await act(async () => root.unmount()); - root = createRoot(container); - // Setup for app B at the same address starts fresh instead of adopting A's draft. - await act(async () => { - root.render( undefined} onConnected={() => undefined} />); - }); - await flush(); - expect(client.status).not.toHaveBeenCalled(); - await click("Create key"); - expect(client.create).toHaveBeenLastCalledWith("company-1", expect.objectContaining({ applicationId: "app-b" })); - sessionStorage.clear(); - }); -}); diff --git a/ui/src/features/connections/remote-mcp/RemoteMcpProductionSetup.test.tsx b/ui/src/features/connections/remote-mcp/RemoteMcpProductionSetup.test.tsx deleted file mode 100644 index 24e053f8fb5..00000000000 --- a/ui/src/features/connections/remote-mcp/RemoteMcpProductionSetup.test.tsx +++ /dev/null @@ -1,100 +0,0 @@ -// @vitest-environment jsdom - -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { afterEach, beforeEach, expect, it, vi } from "vitest"; -import type { ToolConnection } from "@paperclipai/shared"; -import type { ConnectionSetupFlowProps } from "../ConnectionSetupFlow"; -import { ApiError } from "@/api/client"; -import { toolsApi } from "@/api/tools"; -import { RemoteMcpProductionSetup } from "./RemoteMcpProductionSetup"; -import type { RemoteMcpSetupState } from "./types"; - -vi.mock("@/api/tools", () => ({ toolsApi: { getConnectionInstalls: vi.fn() } })); -vi.mock("@/api/agents", () => ({ agentsApi: { list: vi.fn(async () => []) } })); -vi.mock("@/api/companies-query", () => ({ resolveAccountUserId: async () => null })); -vi.mock("@/context/CompanyContext", () => ({ useCompany: () => ({ selectedCompanyId: "company" }) })); -vi.mock("@/lib/router", () => ({ useNavigate: () => vi.fn(), useSearchParams: () => [new URLSearchParams(), vi.fn()] })); -vi.mock("../ConnectionSetupFlow", () => ({ readConnectionIntentOAuthOutcome: () => null })); -vi.mock("../ConnectionInstructions", () => ({ ConnectionInstructionsEditor: () => null })); -vi.mock("./RemoteMcpConnectionSetup", () => ({ - RemoteMcpConnectionSetup: ({ state }: { state: RemoteMcpSetupState }) => ( -
{state.allAgents ? "all agents" : state.agentIds.join(",")}
- ), -})); - -(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - -const connection = { - id: "connection-1", companyId: "company", name: "Composio", status: "active", - credentialPolicy: "organization", authKind: "oauth", config: { url: "https://connect.composio.dev/mcp" }, -} as unknown as ToolConnection; -let root: Root; -let container: HTMLDivElement; -let client: QueryClient; - -function render(props: Partial & { connection?: ToolConnection } = {}) { - act(() => root.render( - - - , - )); -} - -beforeEach(() => { - vi.mocked(toolsApi.getConnectionInstalls).mockReset(); - container = document.createElement("div"); - document.body.append(container); - root = createRoot(container); - client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); -}); - -it("restores a task's saved draft audience before installations exist", async () => { - vi.mocked(toolsApi.getConnectionInstalls).mockResolvedValue({ installs: [] } as never); - render({ connection: { ...connection, status: "draft" }, interactionId: "intent", requiredAgentId: "agent-1", - setupAccess: { connectionId: connection.id, access: { agentIds: ["agent-1"] } } }); - await vi.waitFor(() => expect(container.querySelector('[data-testid="remote-mcp-setup"]')?.textContent).toBe("agent-1")); - await act(async () => { await client.invalidateQueries(); }); - expect(container.querySelector('[data-testid="remote-mcp-setup"]')?.textContent).toBe("agent-1"); -}); -afterEach(() => { - act(() => root.unmount()); - client.clear(); - container.remove(); -}); - -it("keeps saved access on screen when a refetch fails during an outage", async () => { - vi.mocked(toolsApi.getConnectionInstalls).mockResolvedValue({ installs: [{ targetType: "agent", targetId: "agent-1" }] } as never); - render(); - await vi.waitFor(() => expect(container.querySelector('[data-testid="remote-mcp-setup"]')?.textContent).toBe("agent-1")); - - vi.mocked(toolsApi.getConnectionInstalls).mockRejectedValue( - new ApiError("Paperclip is restarting.", 503, { error: "tenant_app_unavailable" }), - ); - await act(async () => { - await client.invalidateQueries(); - }); - - expect(container.querySelector('[data-testid="remote-mcp-setup"]')?.textContent).toBe("agent-1"); - expect(container.querySelector('[data-query-view="error"]')).toBeNull(); - expect(container.textContent).not.toContain("Paperclip is restarting."); - expect(container.textContent).not.toContain("Loading saved access"); -}); - -it("shows readable copy with a retry when saved access cannot be loaded", async () => { - vi.mocked(toolsApi.getConnectionInstalls) - .mockRejectedValueOnce(new ApiError("Request failed: 500", 500, { error: "internal_error" })) - .mockResolvedValue({ installs: [] } as never); - render(); - await vi.waitFor(() => expect(container.querySelector('[data-query-view="error"]')).not.toBeNull()); - expect(container.textContent).toContain("Couldn't load saved access"); - expect(container.textContent).not.toContain("internal_error"); - expect(container.textContent).not.toContain("Request failed: 500"); - expect(container.querySelector('[data-testid="remote-mcp-setup"]')).toBeNull(); - - act(() => (container.querySelector('[data-query-view="error"] button') as HTMLButtonElement).click()); - await vi.waitFor(() => expect(container.querySelector('[data-testid="remote-mcp-setup"]')).not.toBeNull()); - expect(toolsApi.getConnectionInstalls).toHaveBeenCalledTimes(2); - expect(container.querySelector('[data-query-view="error"]')).toBeNull(); -}); diff --git a/ui/src/hooks/useRecentTaskOpenWarmup.test.tsx b/ui/src/hooks/useRecentTaskOpenWarmup.test.tsx index 7a95e90ff96..411f8771220 100644 --- a/ui/src/hooks/useRecentTaskOpenWarmup.test.tsx +++ b/ui/src/hooks/useRecentTaskOpenWarmup.test.tsx @@ -34,7 +34,7 @@ function bootstrapItem(index: number, companyId = "company-1"): IssueChatBootstr } /** Long enough for two frames and the idle fallback timer. */ -const settle = () => act(async () => { await new Promise((resolve) => setTimeout(resolve, 400)); }); +const settle = () => act(async () => { await vi.advanceTimersByTimeAsync(400); }); let container: HTMLDivElement; let root: Root; @@ -57,6 +57,7 @@ function render(props: { companyId?: string | null; userId?: string | null; task } beforeEach(() => { + vi.useFakeTimers(); resetIssueChatBootstrapsForTest(); chatBootstrap.mockReset(); chatBootstrap.mockImplementation(async (_companyId: string, ids: string[]) => ({ @@ -208,7 +209,6 @@ describe("useRecentTaskOpenWarmup", () => { it("warms Recents again on a navigation once the earlier warm may have been dropped", async () => { // The sidebar stays mounted for hours; unread cache entries are dropped after five minutes. - vi.useFakeTimers({ toFake: ["Date"] }); render({ tasks: tasks(2), navigationKey: "/PAP/inbox" }); await settle(); expect(chatBootstrap).toHaveBeenCalledTimes(1); diff --git a/ui/src/lib/recent-selections.test.ts b/ui/src/lib/recent-selections.test.ts index 197698cbc41..5e9ddd6c4fa 100644 --- a/ui/src/lib/recent-selections.test.ts +++ b/ui/src/lib/recent-selections.test.ts @@ -1,5 +1,3 @@ -// @vitest-environment jsdom - import { beforeEach, describe, expect, it } from "vitest"; import { getRecentAssigneeIds, diff --git a/ui/src/lib/responsibility-outline-v2.test.ts b/ui/src/lib/responsibility-outline-v2.test.ts index 121347ff608..fd89b83699d 100644 --- a/ui/src/lib/responsibility-outline-v2.test.ts +++ b/ui/src/lib/responsibility-outline-v2.test.ts @@ -1,4 +1,3 @@ -// @vitest-environment jsdom import { afterEach, describe, expect, it, vi } from "vitest"; import { areaDealFlow, @@ -135,10 +134,10 @@ describe("collapsed areas in storage", () => { }); it("never throws when storage is blocked", () => { - vi.spyOn(Storage.prototype, "getItem").mockImplementation(() => { + vi.spyOn(localStorage, "getItem").mockImplementation(() => { throw new Error("blocked"); }); - vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { + vi.spyOn(localStorage, "setItem").mockImplementation(() => { throw new Error("blocked"); }); expect(readCollapsedAreas("owner").size).toBe(0); diff --git a/ui/src/lib/task-browsers-refresh.test.ts b/ui/src/lib/task-browsers-refresh.test.ts index ae5c931cc40..bfc9b979388 100644 --- a/ui/src/lib/task-browsers-refresh.test.ts +++ b/ui/src/lib/task-browsers-refresh.test.ts @@ -1,4 +1,3 @@ -// @vitest-environment jsdom import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { QueryClient, QueryObserver } from "@tanstack/react-query"; import type { TaskBrowser } from "@paperclipai/shared"; diff --git a/ui/src/pages/apps/TailscaleConnector.test.tsx b/ui/src/pages/apps/TailscaleConnector.test.tsx index 4350429d9c5..8fa3a028d77 100644 --- a/ui/src/pages/apps/TailscaleConnector.test.tsx +++ b/ui/src/pages/apps/TailscaleConnector.test.tsx @@ -165,12 +165,21 @@ describe("Tailscale network connector", () => { it("stops polling and gives a recovery action when the sign-in deadline passes", async () => { fixture.list.mockResolvedValue([{ ...connected, status: "authorizing" }]); fixture.deviceLogin.mockResolvedValue({ connection: { ...connected, status: "authorizing" }, authorizationUrl: "https://login.tailscale.com/a/fixture", expiresAt: new Date(Date.now() - 1).toISOString() }); - render();await settle(); - expect(container.textContent).toContain("Sign-in expired"); - expect(container.querySelector('a[href="https://login.tailscale.com/a/fixture"]')).toBeNull(); - await new Promise(resolve => setTimeout(resolve, 2100)); - expect(fixture.deviceLogin).toHaveBeenCalledOnce(); - expect(button("Cancel sign-in")).toBeDefined(); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "setInterval", "clearInterval"] }); + try { + render(); + for (let i = 0; i < 6; i++) { + await Promise.resolve(); + await vi.advanceTimersByTimeAsync(1); + } + expect(container.textContent).toContain("Sign-in expired"); + expect(container.querySelector('a[href="https://login.tailscale.com/a/fixture"]')).toBeNull(); + await vi.advanceTimersByTimeAsync(2100); + expect(fixture.deviceLogin).toHaveBeenCalledOnce(); + expect(button("Cancel sign-in")).toBeDefined(); + } finally { + vi.useRealTimers(); + } }); it.each(["cancelled", "failed"])("explains %s consent and retries the same saved connection", async outcome => { diff --git a/ui/src/pages/apps/app-detail/ActionTestDialog.test.tsx b/ui/src/pages/apps/app-detail/ActionTestDialog.test.tsx index 63f270db535..658cdd215b8 100644 --- a/ui/src/pages/apps/app-detail/ActionTestDialog.test.tsx +++ b/ui/src/pages/apps/app-detail/ActionTestDialog.test.tsx @@ -105,8 +105,13 @@ async function openAndRun(testEntry = entry) { await renderDialog(testEntry); const button = [...document.body.querySelectorAll("button")].find((candidate) => candidate.textContent?.trim() === "Run"); expect(button).toBeTruthy(); - await act(() => button!.click()); - await act(async () => { await new Promise((resolve) => window.setTimeout(resolve, 260)); }); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] }); + try { + await act(() => button!.click()); + await act(async () => { await vi.advanceTimersByTimeAsync(260); }); + } finally { + vi.useRealTimers(); + } await flushReact(); }