Merge origin/master into feat/antigravity-swarm-command

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* origin/master:
  refactor(plugin-sdk): remove archivedState from the resume result (#22443)
  refactor(runner): let the provider decide whether a released Runner relaunches (#22442)
  fix(connections): drop MCP wording and the MCP guide link from Google Workspace setup (#22793)
  fix(ui): defer the Connectors announcement until a return visit (#22790)
  fix(connections): show only the privacy policy link in the Google Workspace picker (#22795)
  Add count, newest-first and lean run reads to customer-success inspection (#22781)
  fix(connections): keep a finished setup checklist on screen when the app refreshes queries (#22715)
  perf(ci): Phase 2 PR CI under 4 minutes (dynamic workers, fast E2E boot, typecheck overlap, test-budget gate) (#22729)
  fix(plan-mode): open the plan review card when a Plan-mode run settles without one (#22732)
This commit is contained in:
DottaandClaude Opus 5.5 committed 2026-11-24 13:21:12 -06:00
commit 3cbfa500f4
142 files changed
+5552 -11636

No files matched your search

@@ -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
+10 -1
View File
@@ -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"
},
{
+3 -3
View File
@@ -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"]);
}
+16 -2
View File
@@ -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:
+2 -2
View File
@@ -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
+11
View File
@@ -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"
]
}
]
}
+7
View File
@@ -257,6 +257,13 @@ period. A hidden tab clears the card; becoming visible fetches fresh dismissal
state before showing anything, even if that lookup takes longer than three
seconds.
The Connectors promotion (`2026-09-14-connectors`) also waits for
the user's second visit. In this browser, returning to Paperclip or interacting
with it after 30 minutes of inactivity starts that visit. The board records
first-visit activity per account across tabs and companies, including time in
the onboarding wizard and the agent chat. Once eligible, the browser remembers
that the account has returned. Clearing site data starts the visit history over.
The instance caches the feed for an hour, deduplicates concurrent fetches, and
uses conditional requests. Failed requests have a fifteen-minute cooldown; no
card appears for unavailable/invalid/incompatible content. Each request has a
+19 -2
View File
@@ -1,7 +1,7 @@
# Cloud customer-success inspection support
Paperclip exposes `/api/customer-success/v1/run-authority`, `/run-liveness` and
`/read` for the coordinated Cloud inspection broker. This foundation supports one registered
Paperclip exposes `/api/customer-success/v1/run-authority`, `/run-liveness`,
`/read` and `/read-v2` for the coordinated Cloud inspection broker. This foundation supports one registered
Paperclip agent; bot creation, scheduling, scoring and reporting are separate.
The authority endpoint is disabled unless
@@ -67,6 +67,23 @@ pass through Cloud; ranges cap at 1 MiB, JSON at 2 MiB, and lists at 100 rows.
Remote or unsnapshotted resources report unavailable; large content requires
pagination or download ranges. No storage credentials or bypass URLs are issued.
Summary reads keep a fleet-wide refresh cheap:
- `count` takes a catalogued `resource`, `companyId` and optional `parentId`,
and returns `{total, byStatus}`: counts grouped by the reader's `status`
column, or `byStatus: null` when it has none. No row content is read out.
- `order` (`list` only) is `newest` or `oldest` by creation time, with the table's
primary key as tie-breaker so offset pages never repeat or skip rows. Without it, lists keep their original id order.
- `view: "summary"` (`list`/`get` on `runs` only) returns an allowlist of ids,
status, error code, retry counters and timestamps plus a computed
`durationMs`, and leaves out the large JSON columns (result, usage, context
snapshot, runner profile). `RUN_SUMMARY_COLUMNS` is the allowlist.
Queries that use `count`, `order` or `view` are served only on `/read-v2`
(`inspectionReadPath` picks the path); `/read` refuses them. A tenant that
predates them answers 404 on `/read-v2`, so Cloud fails closed with
`tenant_inspection_version_unsupported` instead of misreading the query.
Existing config/event/run redactions and path/symlink/secret-file/size restrictions
remain in use. Authentication account/session, secret, private-key/encrypted-key
and raw provider-trace tables/readers are excluded. Identity-enabled trace
+2 -1
View File
@@ -482,7 +482,8 @@ profiles.
5. Choose the services and sign in with Google.
Google's guide:
[Configure Google Workspace MCP servers](https://developers.google.com/workspace/guides/configure-mcp-servers).
[Create an OAuth client ID](https://developers.google.com/workspace/guides/create-credentials#oauth-client-id).
The setup screen links to the same guide.
An unverified Google app shows a warning screen and has a user cap; only you
can decide whether to submit your own app for Google's verification.
+2 -1
View File
@@ -49,13 +49,14 @@ Last updated: November 23, 2026 (evening).
| Nov 23 | **Security lab: TAC Security (recommended, not yet engaged)** | Google's discounted Tier 2 partner. Plan about $2,000 for year one including a retest. Confirm with a quote; Google assigns the tier. |
| Nov 23 | **A tool refuses an argument it does not know** | All 36 tools fail before any request to Google and name the accepted arguments. Found live: `list_threads` ignored a filter and returned unfiltered mail. |
| Nov 23 | **A cancelled or abandoned first sign-in leaves no connection** | Cancel removes the draft; a closed tab leaves a hidden draft that the next attempt reuses. Applies to every sign-in connector. |
| Nov 24 | **The service picker shows no explanatory text, only the privacy policy link** | Owner decision. This removes the in-product data-use disclosure added on Nov 17 ([#21998](https://github.com/paperclipai/paperclip/pull/21998)). Risk noted by the coordinator: Google's user data policy may expect an in-product disclosure before consent; if a reviewer asks, restore a short statement above the link. |
## What has shipped
| PR | What it does | Merged commit |
| --- | --- | --- |
| [#21996](https://github.com/paperclipai/paperclip/pull/21996) | Plan docs: this file, the production checklist and the code-fix plan. | `12cb18e17d` |
| [#21998](https://github.com/paperclipai/paperclip/pull/21998) | Data-use disclosure in the service picker, shown just before Google consent. Every Google Workspace sign-in start goes through the picker, including four sign-in paths on the app page (Reconnect, Connect as me, Connect organization identity, dedicated-agent connect). The Gmail read & write line says Google's screen also mentions sending and that Paperclip does not send. | `b124ad0674` |
| [#21998](https://github.com/paperclipai/paperclip/pull/21998) | Data-use disclosure in the service picker, shown just before Google consent. Every Google Workspace sign-in start goes through the picker, including four sign-in paths on the app page (Reconnect, Connect as me, Connect organization identity, dedicated-agent connect). The Gmail read & write line says Google's screen also mentions sending and that Paperclip does not send. Removed on Nov 24 by owner decision (see "Decisions"); the picker keeps the privacy policy link. | `b124ad0674` |
| [#21999](https://github.com/paperclipai/paperclip/pull/21999) | Prompt-injection screening now also covers resource reads through a named gateway, the one path that was not screened. Applies to every connector, not only Google. | `65eac24876` |
| [#22001](https://github.com/paperclipai/paperclip/pull/22001) | Scope lock. `GOOGLE_WORKSPACE_SUBMITTED_SCOPES` is the hand-written list of 14, and `workspace.all` uses it. Paperclip-managed Google methods outside the 14 (Gmail archive, Chat, People, Workspace Search) are no longer offered for new setup or reconnect through Paperclip's Google app; saved ones keep refreshing and running. | `66ac5d7aa0` |
| [#22000](https://github.com/paperclipai/paperclip/pull/22000) | REST tool set part 1: the folder `server/src/google-workspace-rest-tools/` with Gmail `get_message`, `search_threads` and `create_draft`. Nothing calls it yet; the switch comes in a later PR. | `a29658b5b7` |
@@ -17,7 +17,7 @@ change in fix 2, the deploy order is app first, then broker (see fix 10).
| # | Fix | Size | Blocks submission | Status |
| --- | --- | --- | --- | --- |
| 1 | Data-use disclosure in the picker | Small | Yes | Done, [#21998](https://github.com/paperclipai/paperclip/pull/21998) |
| 1 | Data-use disclosure in the picker | Small | Yes | Done, [#21998](https://github.com/paperclipai/paperclip/pull/21998); removed Nov 24 by owner decision |
| 2 | Lock the managed scope set to 14 | Small to medium | Yes | Done in the app, [#22001](https://github.com/paperclipai/paperclip/pull/22001) |
| 3 | Take `gmail.modify` off the Paperclip-managed client | Small | Yes | Done, [#22001](https://github.com/paperclipai/paperclip/pull/22001) |
| 4 | Confirm injection screening on Google results | Check, then small | Yes | Done, [#21999](https://github.com/paperclipai/paperclip/pull/21999) |
@@ -36,6 +36,9 @@ four sign-in paths on the app page. The Gmail read & write line says Google's
screen also mentions sending and that Paperclip does not send. The plan below
is kept for reference.
**Removed** (Nov 24) by owner decision. The picker keeps only the privacy
policy link, which names Google's Limited Use requirements.
**Confirmed gap.** `ServicePicker` in
`ui/src/features/connections/GoogleWorkspaceServices.tsx` shows three service
rows and Cancel / Continue. Its only description is screen-reader text. Google
@@ -59,8 +59,12 @@ Decisions and the details behind them are kept in the
## 2. Product and code (see the code-fix plan)
- [x] Data-use disclosure shown in the picker immediately before Google consent
(Nov 17, [#21998](https://github.com/paperclipai/paperclip/pull/21998)).
- [ ] Data-use disclosure in the picker immediately before Google consent.
Added Nov 17 ([#21998](https://github.com/paperclipai/paperclip/pull/21998)),
then removed on Nov 24 by owner decision. The picker now shows only the
service rows and a link to the privacy policy and its Limited Use
statement. If a Google reviewer asks for an in-product disclosure,
restore a short statement above the link.
- [ ] Limited Use statement published and linked from the picker.
- [x] Help page: how to disconnect and how to delete stored Google data
(Nov 17, [#22010](https://github.com/paperclipai/paperclip/pull/22010):
+17 -18
View File
@@ -201,13 +201,16 @@ this field, the provider must:
- Move the source Runner state (`runner-state.json`) out of the Runner state
directory into an archive, so that the Runner creates new state.
- Start the Runner as the claimant identity with the fresh `bootstrapTicket`.
- Return `runner: { version, digest }` and `archivedState` (the archived Runner
state) on the `resumed` result.
- Return `runner: { version, digest }` on the `resumed` result.
Core accepts the archived state only when it is the source's settled cut: the
`suspended` lifecycle, or the `ready` lifecycle with an empty outbox, every
event acknowledged and no command in progress. Core then sends one ordinary
`run.attach` with no authority hand-off. A retry with the same source, ticket
The provider is the authority on whether a park exists. It relaunches only from
the source's settled cut, and Core does not check that cut again. That cut is the
`suspended` lifecycle, or the `ready` lifecycle with an empty outbox, every event
acknowledged and no command in progress. Core resumes on the assumption that the
source parked. When the task has no park of that source, return `unavailable`
once nothing runs for the task, and Core starts a fresh task from the saved
session. Otherwise Core sends one ordinary `run.attach` with no authority
hand-off. A retry with the same source, ticket
and `runner` must return the original result and must not start a second
Runner. Without `runner` on `resume`, keep the claimant handover above.
@@ -274,18 +277,14 @@ turn replay. A known `unavailable` result still requires ordinary physical
cleanup. Transparent cold fallback remains a separate qualification requirement.
A normal Core cache timeout detaches only Core's quiet local owner. The host
keeps its retained resources under its own retention policy. Core's existing
completed-session record stores only the confirmed source, physical task and a
digest of the selected account, credential revision and workspace scope. The
transport returns the exact source after the host's release receipt; Core does
not infer it from a local checkpoint marker, which may still name an older run.
An invalid source receipt or failed proof write keeps cleanup under the same
owner until physical retirement finishes. Later
cache adoption validates that Core-authored proof before claiming or
reconnecting. A stale or missing proof never licenses a claim. A changed
selection remains blocked until guarded retirement/recovery; it does not imply
that a cold launch is safe. Confirmed claim or physical cleanup clears only the
matching proof. Raw tickets are never stored in this record.
keeps its retained resources under its own retention policy. Core keeps no
record of a release beyond that owner. The transport returns the exact source
after the host's release receipt. Core checks it against the attached run,
session, Runner and lease, and only then marks its owner released. An invalid
source receipt keeps cleanup under the same owner until physical retirement
finishes. A later run resumes the source Core restores from its controller
checkpoint, on the lease's current task only, and the provider answers from its
own park record. Raw tickets are never stored.
When graceful host eviction has saved a suspended session and Core has recorded
physical stop, a later allocation can use ordinary `resumeFrom` recovery. Core
+1 -1
View File
@@ -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.
+1 -1
View File
@@ -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,
+4 -4
View File
@@ -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
+4 -5
View File
@@ -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)
+4 -4
View File
@@ -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",
+28 -4
View File
@@ -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<EmbeddedPostgres
// fresh path so the cache can only make a suite faster, never fail it.
async function startEmbeddedPostgresClusterForSuite(
tempDirPrefix: string,
options?: EmbeddedPostgresTestDatabaseOptions,
): Promise<{ port: number; dataDir: string; instance: EmbeddedPostgresInstance; mode: EmbeddedPostgresStartMode }> {
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<EmbeddedPostgresTestDatabase> {
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 {
+4 -1
View File
@@ -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();
@@ -11,7 +11,7 @@ import type { DurableRecoveryIdentity } from "../contracts/durable-recovery.js";
export type RunnerReleaseResumeOutcome =
| "resumed"
| "unavailable"
| { outcome: "resumed"; runner: { version: string; digest: string }; settled?: () => Promise<void> };
| { outcome: "resumed"; runner: { version: string; digest: string } };
export interface RunnerExecutionDriver {
/** The driver verifies a stopped, idle Codex App Server source before launch. */
-1
View File
@@ -101,7 +101,6 @@ export { resolveGrokEffort } from "./drivers/acpx/grok-effort.js";
export * from "./drivers/runner-tool-bridge.js";
export {
createRunnerdCodexTransport,
isSettledReleasedRunnerCut,
revertUnattachedRelaunchRotation,
probeNativeRunnerEnvironment,
NativeEnvironmentProbeCleanupError,
@@ -122,7 +122,6 @@ it.skipIf(process.platform === "win32").each(["cached", "lost claim reply", "cac
const measuredTurn = new Promise<void>(resolve => { enterMeasuredTurn = resolve; });
const heldMeasuredTurn = new Promise<void>(resolve => { finishMeasuredTurn = resolve; });
const sockets = new Set<PrpWireConnection>();
const relaunchSettled = vi.fn(async () => { expect(authority!.store.state.identity.runId).toBe(identity.runId); });
const registration = async (core: DurablePrpControlPlane, source = core.store.state.identity) => {
if ((mode === "late claim reply" || mode === "held past deadline" || mode === "early claim expired") && claimAccepted) throw new Error("Fixture source authentication started after expiry");
authority = core;
@@ -184,7 +183,7 @@ it.skipIf(process.platform === "win32").each(["cached", "lost claim reply", "cac
if (mode === "relaunched flush retry" && pair.resume.mock.calls.length === 1) {
vi.spyOn(authority!, "flushCheckpoint").mockRejectedValueOnce(new Error("Fixture checkpoint write failed"));
}
return { outcome: "resumed", runner: { version, digest: runnerDigest }, settled: relaunchSettled };
return { outcome: "resumed", runner: { version, digest: runnerDigest } };
}
return "resumed";
}),
@@ -438,9 +437,7 @@ it.skipIf(process.platform === "win32").each(["cached", "lost claim reply", "cac
await bundle.transport.close();
} else await attaching;
expect(new Set(claimTicketDigests).size).toBe(1);
if (mode === "relaunched same build" || mode === "relaunched flush retry") expect(relaunchSettled).toHaveBeenCalledOnce();
if (mode === "relaunched incompatible build") {
expect(relaunchSettled).not.toHaveBeenCalled();
expect(pair.resume).toHaveBeenCalledOnce();
expect(authority!.store.state.identity.runId).toBe(identity.runId);
return;
@@ -4,7 +4,7 @@ import {
runnerLaunchRequirementsDigest,
type RunnerProviderLaunchRequirements,
} from "./runner-provider-launch.js";
import { coldAdmissionTimeoutMs, describeRunnerCommandStall, isSettledReleasedRunnerCut, revertUnattachedRelaunchRotation, RUNNER_MAX_STOPPED_CREDIT_MS, RUNNER_POST_STOP_GRACE_MS, RunnerStallLedger, waitForRunnerCommand } from "./runnerd-codex-transport.js";
import { coldAdmissionTimeoutMs, describeRunnerCommandStall, revertUnattachedRelaunchRotation, RUNNER_MAX_STOPPED_CREDIT_MS, RUNNER_POST_STOP_GRACE_MS, RunnerStallLedger, waitForRunnerCommand } from "./runnerd-codex-transport.js";
import { configuredEnvironmentProjection } from "../configured-environment.js";
import { chmod, cp, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, stat, truncate, writeFile } from "node:fs/promises";
import { createHash } from "node:crypto";
@@ -2211,26 +2211,6 @@ describe("a rotation for a released Runner that the host starts again", () => {
}
}
});
it("accepts a stopped Runner's ready cut only when nothing is left in flight", () => {
expect(isSettledReleasedRunnerCut(settled, priorIdentity)).toBe(true);
expect(isSettledReleasedRunnerCut({ schema: settled.schema, ...priorIdentity, lifecycle: "suspended" }, priorIdentity)).toBe(true);
for (const changed of [
{ outbox: [{ sourceSeq: 8 }] },
{ ackedSourceSeq: 6 },
{ nextSourceSeq: undefined },
{ processedCommands: { "command-a": { status: "pending" } } },
{ processedCommands: { "command-a": { status: "indeterminate" } } },
{ warmTransition: { transitionId: "transition" } },
{ pendingTerminalDelivery: { turnId: "turn" } },
{ pendingProviderCleanup: { turnId: "turn" } },
{ lifecycle: "connecting" },
{ schema: "paperclip.runner.durable.state.v0" },
{ runId: desiredIdentity.runId },
]) {
expect(isSettledReleasedRunnerCut({ ...settled, ...changed }, priorIdentity)).toBe(false);
}
});
});
describe("authority rotation after the prior controller state is restored", () => {
@@ -237,22 +237,6 @@ function assertSuspendedRunnerState(
}
}
export function isSettledReleasedRunnerCut(
state: Record<string, unknown>,
expected: DurableRecoveryIdentity,
): boolean {
if (state.schema !== "paperclip.runner.durable.state.v1" || !recoveryIdentityMatches(state, expected)) return false;
if (state.lifecycle === "suspended") return true;
return state.lifecycle === "ready"
&& Array.isArray(state.outbox) && state.outbox.length === 0
&& Number.isSafeInteger(state.nextSourceSeq) && state.ackedSourceSeq === Math.max(0, Number(state.nextSourceSeq) - 1)
&& state.warmTransition === undefined
&& (state.pendingTerminalDelivery ?? null) === null
&& (state.pendingProviderCleanup ?? null) === null
&& Object.values(record(state.processedCommands)).every(command =>
!["pending", "indeterminate"].includes(String(record(command).status)));
}
function assertRealDirectory(path: string): void {
const metadata = lstatSync(path);
if (metadata.isSymbolicLink() || !metadata.isDirectory()) {
@@ -5067,7 +5051,6 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
assertPending();
let outcome: "resumed" | "unavailable" | undefined;
let relaunched: { version: string; digest: string } | undefined;
let settled: (() => Promise<void>) | undefined;
try {
if (!episode.ticket) {
episode.ticket = core.issueBootstrapTicket(RUNNER_BOOTSTRAP_TICKET_TTL_MS);
@@ -5081,7 +5064,6 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
const result = await Promise.race([pair.resume(episode.source, episode.ticket), deadline, closed]);
outcome = typeof result === "string" ? result : result.outcome;
relaunched = typeof result === "string" ? undefined : result.runner;
settled = typeof result === "string" ? undefined : result.settled;
} catch (error) {
// A generic RPC error cannot prove refusal. Keep this exact pending claim quiet.
assertPending();
@@ -5096,7 +5078,6 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
core.acceptRelaunchedRunner(episode.ticket!, relaunched, episode.parked);
this.#relaunchedRunnerArtifact = structuredClone(relaunched);
await Promise.race([core.flushCheckpoint(), deadline, closed]);
await Promise.race([settled?.(), deadline, closed]);
} catch (error) {
if (error instanceof Error && error.message === "native_runner_relaunched_build_unaccepted") {
throw new Error("native_runner_reuse_unavailable");
@@ -194,8 +194,7 @@ export const environmentTaskResultSchema = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("admission_rejected"), taskId: providerId,
reason: z.enum(["session_state_unavailable", "account_binding_mismatch"]) }).strict(),
z.object({ kind: z.literal("released"), taskId: providerId }).strict(),
z.object({ kind: z.literal("resume"), taskId: providerId, outcome: z.enum(["resumed", "unavailable"]), runner: runnerArtifact.optional(),
archivedState: z.record(z.string(), z.unknown()).optional() }).strict(),
z.object({ kind: z.literal("resume"), taskId: providerId, outcome: z.enum(["resumed", "unavailable"]), runner: runnerArtifact.optional() }).strict(),
z.object({
kind: z.literal("ownership"),
taskId: providerId,
@@ -307,8 +306,7 @@ export function parseEnvironmentTaskResult(operation: PluginEnvironmentTaskOpera
const expected = operation.kind === "release" ? "released" : operation.kind === "resume" ? "resume" : operation.kind === "read_file" ? "file" : operation.kind === "describe" ? "description" : operation.kind === "prepare" ? "prepared" : operation.kind === "check_project_auth" ? "project_auth" : ["read_state", "archive_state"].includes(operation.kind) ? "state" : ["status", "connection", "credentials", "copilot_metadata"].includes(operation.kind) ? operation.kind : "accepted";
const rejectedSubmit = operation.kind === "submit" && result.kind === "admission_rejected";
if (result.taskId !== taskId || (result.kind !== expected && !rejectedSubmit)) throw new Error("Invalid plugin-provided Runner execution response");
if (operation.kind === "resume" && result.kind === "resume" && (operation.runner
? result.outcome === "resumed" && (!result.runner || !result.archivedState) : result.archivedState !== undefined)) {
if (operation.kind === "resume" && result.kind === "resume" && operation.runner && result.outcome === "resumed" && !result.runner) {
throw new Error("Invalid plugin-provided Runner execution response");
}
return result;
@@ -94,7 +94,7 @@ describe("release and resume task contract", () => {
expect(environmentTaskResultSchema.safeParse({ ...result, runner: { ...runner, extra: true } }).success).toBe(false);
});
it("relaunches as the claimant's identity only when asked, and reports the archived state", () => {
it("relaunches as the claimant's identity only when asked, and reports the build", () => {
expect(environmentTaskResultSchema.parse({ ...description, resumeIdentityVersion: 1 })).toEqual({ ...description, resumeIdentityVersion: 1 });
expect(environmentTaskResultSchema.safeParse({ ...description, resumeIdentityVersion: 2 }).success).toBe(false);
const runner = { runId: "claimant-run", turnId: "turn-claimant-run", itemId: "item-claimant-run" };
@@ -104,12 +104,11 @@ describe("release and resume task contract", () => {
expect(environmentTaskOperationSchema.safeParse({ ...resume, runner: changed }).success).toBe(false);
}
const build = { version: "0.4.1", digest: `sha256:${"b".repeat(64)}` };
const archivedState = { schema: "paperclip.runner.durable.state.v1", ...identity, lifecycle: "ready" };
const resumed = { kind: "resume", taskId: "task", outcome: "resumed", runner: build, archivedState };
const resumed = { kind: "resume", taskId: "task", outcome: "resumed", runner: build };
expect(parseEnvironmentTaskResult(relaunch, "task", resumed)).toEqual(resumed);
expect(() => parseEnvironmentTaskResult(relaunch, "task", { ...resumed, archivedState: undefined })).toThrow();
const archivedState = { schema: "paperclip.runner.durable.state.v1", ...identity, lifecycle: "ready" };
expect(() => parseEnvironmentTaskResult(relaunch, "task", { ...resumed, archivedState })).toThrow();
expect(() => parseEnvironmentTaskResult(relaunch, "task", { ...resumed, runner: undefined })).toThrow();
expect(() => parseEnvironmentTaskResult(resume, "task", resumed)).toThrow();
expect(parseEnvironmentTaskResult(relaunch, "task", { kind: "resume", taskId: "task", outcome: "unavailable" }))
.toEqual({ kind: "resume", taskId: "task", outcome: "unavailable" });
});
@@ -16,7 +16,6 @@
"urlPatterns": [
"https://workspace.google.com/*"
],
"docsUrl": "https://developers.google.com/workspace/guides/configure-mcp-servers",
"setupPrerequisite": {
"title": "Google Developer Preview access required",
"description": "Google must register the Workspace email and the Cloud project that owns the OAuth client before these services can be used.",
@@ -111,10 +110,10 @@
"prompt": "consent"
}
},
"guidanceMd": "Enable the Google Workspace MCP APIs and register Paperclip's callback URI. Choose which permissions to grant on Google's consent screen; declined permissions disable only the corresponding actions.",
"guidanceMd": "Enable the Gmail, Drive, Docs, Sheets, Slides, and Calendar APIs in your Google Cloud project and register Paperclip's callback URI. Choose which permissions to grant on Google's consent screen; declined permissions disable only the corresponding actions.",
"consoleLinks": {
"register": "https://console.cloud.google.com/auth/clients",
"docs": "https://developers.google.com/workspace/guides/configure-mcp-servers"
"docs": "https://developers.google.com/workspace/guides/create-credentials#oauth-client-id"
},
"riskTier": "S4"
}
+42 -2
View File
@@ -65,10 +65,28 @@ export const INSPECTION_RESOURCES = [
"threads",
] as const;
export type InspectionResource = (typeof INSPECTION_RESOURCES)[number];
export const INSPECTION_ORDERS = ["newest", "oldest"] as const;
export type InspectionOrder = (typeof INSPECTION_ORDERS)[number];
export const INSPECTION_VIEWS = ["summary"] as const;
export type InspectionView = (typeof INSPECTION_VIEWS)[number];
/** The tenant path for queries that use only the original (version 1) features. */
export const INSPECTION_READ_PATH = "/read";
/**
* The tenant path for queries that use `count`, `order` or `view`. A tenant
* that predates them answers 404 here, so Cloud fails closed with
* `tenant_inspection_version_unsupported` instead of misreading the query.
*/
export const INSPECTION_EXTENDED_READ_PATH = "/read-v2";
export interface InspectionCount {
total: number;
/** Counts grouped by the resource's `status` column, or null when it has none. */
byStatus: Record<string, number> | null;
}
export interface InspectionQuery {
operation:
| "list"
| "get"
| "count"
| "instructions.file"
| "skills.file"
| "runs.log"
@@ -85,6 +103,10 @@ export interface InspectionQuery {
limit?: number;
offset?: number;
range?: { start: number; end: number };
/** `list` only: order by creation time instead of by id. */
order?: InspectionOrder;
/** `list`/`get` on `runs` only: leave out the large JSON columns. */
view?: InspectionView;
context?: {
projectId?: string;
workspaceId?: string;
@@ -129,6 +151,11 @@ export function canonicalJson(value: unknown): string {
}
throw new Error("Invalid JSON value");
}
export function inspectionReadPath(query: InspectionQuery): string {
return query.operation === "count" || query.order !== undefined || query.view !== undefined
? INSPECTION_EXTENDED_READ_PATH
: INSPECTION_READ_PATH;
}
export function parseInspectionQuery(value: unknown): InspectionQuery {
if (!value || typeof value !== "object" || Array.isArray(value))
throw new Error("Invalid inspection query");
@@ -144,6 +171,8 @@ export function parseInspectionQuery(value: unknown): InspectionQuery {
"limit",
"offset",
"range",
"order",
"view",
"context",
]);
if (Object.keys(q).some((k) => !allowed.has(k)))
@@ -152,6 +181,7 @@ export function parseInspectionQuery(value: unknown): InspectionQuery {
![
"list",
"get",
"count",
"instructions.file",
"skills.file",
"runs.log",
@@ -169,11 +199,21 @@ export function parseInspectionQuery(value: unknown): InspectionQuery {
if (q.resource !== undefined && !INSPECTION_RESOURCES.includes(q.resource))
throw new Error("Unsupported inspection resource");
if (q.operation === "get" && !q.resourceId) throw new Error("resourceId required");
if (["get", "list"].includes(q.operation) && !q.resource) throw new Error("resource required");
if (["get", "list", "count"].includes(q.operation) && !q.resource)
throw new Error("resource required");
if (!(q.operation === "list" && q.resource === "companies") && !q.companyId)
throw new Error("companyId required");
if (!["get", "list"].includes(q.operation) && !q.resourceId)
if (!["get", "list", "count"].includes(q.operation) && !q.resourceId)
throw new Error("resourceId required");
if (q.operation === "count" && q.resourceId !== undefined)
throw new Error("count does not take resourceId");
if (q.order !== undefined && (q.operation !== "list" || !INSPECTION_ORDERS.includes(q.order)))
throw new Error("Invalid order");
if (
q.view !== undefined &&
(!["list", "get"].includes(q.operation) || q.resource !== "runs" || !INSPECTION_VIEWS.includes(q.view))
)
throw new Error("Invalid view");
if (
q.path !== undefined &&
(typeof q.path !== "string" || q.path.length > 1024 || q.path.includes("\0"))
@@ -0,0 +1,31 @@
import { describe, expect, it } from "vitest";
import { getConnectableAppDefinition } from "./app-definitions.js";
const MCP_SERVERS_GUIDE = "configure-mcp-servers";
const OAUTH_CLIENT_GUIDE = "https://developers.google.com/workspace/guides/create-credentials#oauth-client-id";
describe("Google Workspace setup links and copy", () => {
const app = getConnectableAppDefinition("google-workspace")!;
const method = (key: string) => app.methods.find((candidate) => candidate.key === key)!;
it("never sends a user to Google's MCP servers guide", () => {
expect(JSON.stringify(app)).not.toContain(MCP_SERVERS_GUIDE);
});
it("gives the Paperclip-managed sign-in no requirements link", () => {
expect(app.docsUrl).toBeUndefined();
expect(method("paperclip-workspace").consoleLinks?.docs).toBeUndefined();
});
it("links the customer-owned client method to Google's OAuth client guide", () => {
expect(method("customer-workspace-oauth").consoleLinks?.docs).toBe(OAUTH_CLIENT_GUIDE);
});
it("does not mention MCP in user-facing method text", () => {
for (const entry of app.methods) {
for (const text of [entry.label, entry.whenToUse, entry.guidanceMd, ...(entry.warnings ?? [])]) {
expect(text ?? "").not.toMatch(/\bMCP\b/);
}
}
});
});
+42
View File
@@ -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: <reason>`.
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: <reason>`.
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 <ref>` / `--files <paths...>`) 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.
+90 -14
View File
@@ -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"],
+6 -3
View File
@@ -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);
@@ -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 });
}
});
@@ -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");
+469
View File
@@ -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: <reason>.`,
});
}
}
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: <reason>.`,
});
}
}
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).`,
);
}
+212
View File
@@ -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"/);
});
+15 -5
View File
@@ -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 = [
+138 -36
View File
@@ -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 });
File diff suppressed because it is too large. Load diff
+59
View File
@@ -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));
}
+91
View File
@@ -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;
}
+37 -37
View File
@@ -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
}
}
+10 -3
View File
@@ -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));
+135
View File
@@ -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();
}
+2 -115
View File
@@ -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<string, unknown> {
return JSON.parse(readFileSync(filePath, "utf8")) as Record<string, unknown>;
}
function discoverWorkspacePackagePaths(rootDir: string): Map<string, string> {
const packagePaths = new Map<string, string>();
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<string, unknown> | undefined),
...(packageJson.devDependencies as Record<string, unknown> | 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();
+31 -20
View File
@@ -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);
}
+16 -4
View File
@@ -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 = [];
+13
View File
@@ -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);
});
@@ -154,6 +154,18 @@ describe.skipIf(!cloudDist)("customer-success managed agent / Cloud / tenant qua
transactionReads++;
return registry.getCustomerSuccessAccount(id);
},
getStacks: async (ids: readonly string[]) => {
await client.query("SELECT 1");
transactionReads++;
return (await Promise.all(ids.map((id) => registry.getStack(id)))).filter(Boolean);
},
getAccounts: async (ids: readonly string[]) => {
await client.query("SELECT 1");
transactionReads++;
return (
await Promise.all(ids.map((id) => registry.getCustomerSuccessAccount(id)))
).filter(Boolean);
},
listStackIds: async () => registry.listCustomerSuccessStackIds(),
});
const store = new PostgresInspectionStore(pool, registryForClient);
@@ -272,7 +284,9 @@ describe.skipIf(!cloudDist)("customer-success managed agent / Cloud / tenant qua
const grant=await call('grant',{stackId:'qualification-stack'});
const tasks=await call('read',{stackId:'qualification-stack',grantToken:grant.token,query:{operation:'list',resource:'tasks',companyId:${JSON.stringify(customer.id)}}});
const file=await call('read',{stackId:'qualification-stack',grantToken:grant.token,query:{operation:'files.download',companyId:${JSON.stringify(customer.id)},resourceId:${JSON.stringify(task.id)},context:{projectId:${JSON.stringify(project.id)},workspaceId:${JSON.stringify(workspace.id)}},path:'result.bin',range:{start:2,end:5}}});
console.log(JSON.stringify({stackCount:discovery.items.length,titles:tasks.items.map(t=>t.title),fileBytes:[...Buffer.from(file.content,'base64')]}));
const taskCount=await call('read',{stackId:'qualification-stack',grantToken:grant.token,query:{operation:'count',resource:'tasks',companyId:${JSON.stringify(customer.id)}}});
const latestRuns=await call('read',{stackId:'qualification-stack',grantToken:grant.token,query:{operation:'list',resource:'runs',companyId:${JSON.stringify(customer.id)},order:'newest',view:'summary',limit:1}});
console.log(JSON.stringify({stackCount:discovery.items.length,titles:tasks.items.map(t=>t.title),fileBytes:[...Buffer.from(file.content,'base64')],taskCount,latestRuns}));
`;
const programFile = join(directory, "qualify.mjs");
await writeFile(programFile, program);
@@ -298,6 +312,9 @@ describe.skipIf(!cloudDist)("customer-success managed agent / Cloud / tenant qua
expect(result.exitCode, [...output, ...serverErrors].join("\n")).toBe(0);
expect(output.join("")).toContain("First successful task");
expect(output.join("")).toContain('"fileBytes":[2,3,4,5]');
// Count and newest-first summary reads travel the extended tenant path.
expect(output.join("")).toContain('"taskCount":{"total":1,"byStatus":{');
expect(output.join("")).toContain('"latestRuns":{"items":[],"nextOffset":null}');
expect((await stat(filePath)).mtimeMs).toBe(fileBefore.mtimeMs);
expect(await readFile(filePath)).toEqual(Buffer.from([0, 1, 2, 3, 4, 5]));
const audit = await pool.query(
@@ -13,6 +13,7 @@ import {
INSPECTION_HEADER,
INSPECTION_PERMIT_TYPE,
INSPECTION_RESOURCES,
inspectionReadPath,
parseInspectionQuery,
type InspectionQuery,
type InspectionPermit,
@@ -21,6 +22,8 @@ import { customerSuccessRunAuthority } from "../services/customer-success-author
import {
readCustomerSuccessResource,
inspectionReaders,
RUN_SUMMARY_COLUMNS,
primaryKeyColumns,
} from "../services/customer-success-inspection.js";
import {
customerSuccessRoutes,
@@ -438,6 +441,29 @@ describe("customer-success read authority", () => {
expect((await request(app).post("/api/customer-success/v1/unknown").send({})).status).toEqual(
404,
);
// Count, order and view live only on the extended path, so a tenant that
// predates them answers 404 there and Cloud fails closed.
const countQuery: InspectionQuery = { operation: "count", resource: "tasks", companyId };
const countToken = () => token({ ...claims, jti: randomUUID(), query: countQuery });
expect(
(
await request(app)
.post("/api/customer-success/v1/read")
.set(INSPECTION_HEADER, countToken())
.send(countQuery)
).status,
).toEqual(403);
const counted = await request(app)
.post("/api/customer-success/v1/read-v2")
.set(INSPECTION_HEADER, countToken())
.send(countQuery);
expect(counted.status).toEqual(200);
expect(counted.body).toEqual({ total: expect.any(Number), byStatus: expect.any(Object) });
const original = await request(app)
.post("/api/customer-success/v1/read-v2")
.set(INSPECTION_HEADER, token())
.send(query);
expect(original.status).toEqual(200);
fetcher.mockResolvedValue(new Response("", { status: 503 }));
expect(
(
@@ -692,6 +718,153 @@ describe("customer-success read authority", () => {
})) as { items: unknown[] };
expect(versions.items).toHaveLength(1);
});
it("counts by status, orders newest first, and returns lean run summaries, company scoped", async () => {
const [company, other] = await db
.insert(schema.companies)
.values([
{ name: "Counted", issuePrefix: "CNT" },
{ name: "Elsewhere", issuePrefix: "ELS" },
])
.returning();
const [countedAgent] = await db
.insert(schema.agents)
.values({ companyId: company.id, name: "Counted agent", adapterType: "process" })
.returning();
const [otherAgent] = await db
.insert(schema.agents)
.values({ companyId: other.id, name: "Other agent", adapterType: "process" })
.returning();
const heavy = { transcript: "x".repeat(200_000) };
const at = (minutes: number) => new Date(Date.UTC(2026, 0, 1, 0, minutes));
const runs = await db
.insert(schema.heartbeatRuns)
.values([
{ companyId: company.id, agentId: countedAgent.id, status: "succeeded", createdAt: at(1), startedAt: at(1), finishedAt: at(3), resultJson: heavy, contextSnapshot: heavy },
{ companyId: company.id, agentId: countedAgent.id, status: "failed", createdAt: at(5), startedAt: at(5), finishedAt: at(6), errorCode: "adapter_failed", resultJson: heavy },
{ companyId: company.id, agentId: countedAgent.id, status: "failed", createdAt: at(9), startedAt: at(9), resultJson: heavy },
{ companyId: other.id, agentId: otherAgent.id, status: "failed", createdAt: at(20) },
])
.returning();
await db.insert(schema.issues).values([
{ companyId: company.id, title: "Open", status: "todo" },
{ companyId: company.id, title: "Shipped", status: "done" },
{ companyId: other.id, title: "Not ours", status: "done" },
]);
expect(
await readCustomerSuccessResource(db, storage, { operation: "count", resource: "runs", companyId: company.id }),
).toEqual({ total: 3, byStatus: { succeeded: 1, failed: 2 } });
expect(
await readCustomerSuccessResource(db, storage, { operation: "count", resource: "tasks", companyId: company.id }),
).toEqual({ total: 2, byStatus: { todo: 1, done: 1 } });
expect(
await readCustomerSuccessResource(db, storage, {
operation: "count",
resource: "comments",
companyId: company.id,
}),
).toEqual({ total: 0, byStatus: null });
const latest = (await readCustomerSuccessResource(db, storage, {
operation: "list",
resource: "runs",
companyId: company.id,
order: "newest",
view: "summary",
limit: 1,
})) as { items: Array<Record<string, unknown>>; nextOffset: number | null };
expect(latest.items.map((r) => r.id)).toEqual([runs[2].id]);
expect(latest.nextOffset).toEqual(1);
expect(Object.keys(latest.items[0]).sort()).toEqual([...RUN_SUMMARY_COLUMNS, "durationMs"].sort());
expect(latest.items[0].durationMs).toBeNull();
expect(JSON.stringify(latest).length).toBeLessThan(2_000);
const page = (await readCustomerSuccessResource(db, storage, {
operation: "list",
resource: "runs",
companyId: company.id,
order: "newest",
view: "summary",
limit: 2,
offset: 1,
})) as { items: Array<Record<string, unknown>> };
expect(page.items.map((r) => [r.id, r.durationMs])).toEqual([
[runs[1].id, 60_000],
[runs[0].id, 120_000],
]);
const oldest = (await readCustomerSuccessResource(db, storage, {
operation: "list",
resource: "runs",
companyId: company.id,
order: "oldest",
limit: 1,
})) as { items: Array<Record<string, unknown>> };
expect(oldest.items[0].id).toEqual(runs[0].id);
expect(oldest.items[0]).toHaveProperty("resultJson");
const one = (await readCustomerSuccessResource(db, storage, {
operation: "get",
resource: "runs",
companyId: company.id,
resourceId: runs[1].id,
view: "summary",
})) as Record<string, unknown>;
expect(one).toMatchObject({ id: runs[1].id, status: "failed", errorCode: "adapter_failed", durationMs: 60_000 });
expect(one).not.toHaveProperty("resultJson");
expect(one).not.toHaveProperty("contextSnapshot");
});
it("ordered pages cover rows that share a creation time exactly once", async () => {
for (const resource of INSPECTION_RESOURCES)
expect(primaryKeyColumns(inspectionReaders[resource].table).length, resource).toBeGreaterThan(0);
const [company] = await db
.insert(schema.companies)
.values({ name: "Labelled", issuePrefix: "LBL" })
.returning();
const [issue] = await db.insert(schema.issues).values({ companyId: company.id, title: "Tagged" }).returning();
const labels = await db
.insert(schema.labels)
.values(Array.from({ length: 5 }, (_, i) => ({ companyId: company.id, name: `label-${i}`, color: "#000000" })))
.returning();
const createdAt = new Date(Date.UTC(2026, 0, 2));
await db
.insert(schema.issueLabels)
.values(labels.map((label) => ({ companyId: company.id, issueId: issue.id, labelId: label.id, createdAt })));
for (const order of ["newest", "oldest"] as const) {
const seen: string[] = [];
for (let offset = 0; offset < labels.length; offset += 2) {
const page = (await readCustomerSuccessResource(db, storage, {
operation: "list",
resource: "taskLabels",
companyId: company.id,
order,
limit: 2,
offset,
})) as { items: Array<{ labelId: string }> };
seen.push(...page.items.map((row) => row.labelId));
}
expect(seen.sort()).toEqual(labels.map((label) => label.id).sort());
}
});
it("count, order and view are bounded and take the extended read path", () => {
expect(inspectionReadPath(parseInspectionQuery({ operation: "list", resource: "runs", companyId }))).toEqual("/read");
for (const value of [
{ operation: "count", resource: "runs", companyId },
{ operation: "list", resource: "runs", companyId, order: "newest" },
{ operation: "get", resource: "runs", companyId, resourceId: agentId, view: "summary" },
])
expect(inspectionReadPath(parseInspectionQuery(value))).toEqual("/read-v2");
for (const value of [
{ operation: "count", companyId },
{ operation: "count", resource: "runs" },
{ operation: "count", resource: "runs", companyId, resourceId: agentId },
{ operation: "get", resource: "runs", companyId, resourceId: agentId, order: "newest" },
{ operation: "list", resource: "runs", companyId, order: "random" },
{ operation: "list", resource: "tasks", companyId, view: "summary" },
{ operation: "list", resource: "runs", companyId, view: "full" },
{ operation: "runs.log", companyId, resourceId: agentId, view: "summary" },
])
expect(() => parseInspectionQuery(value)).toThrow();
});
it("the operation contract has no writes, credentials or unknown parameters", () => {
for (const value of [
{ operation: "write", companyId },
@@ -280,6 +280,7 @@ const support = await getEmbeddedPostgresTestSupport();
const audit = await db.select().from(toolAccessAuditEvents).where(and(eq(toolAccessAuditEvents.companyId, f.company.id), eq(toolAccessAuditEvents.action, "call_completed")));
expect(audit).toHaveLength(1);
expect(JSON.stringify(audit[0])).toContain("Google Workspace REST");
expect(JSON.stringify(audit[0])).not.toContain("mcpMethod");
expect(JSON.stringify([invocation, audit])).not.toContain("workspace-access-1");
});
@@ -0,0 +1,206 @@
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { and, eq } from "drizzle-orm";
import {
agents,
agentWakeupRequests,
companies,
completionContracts,
createDb,
heartbeatRuns,
issueThreadInteractions,
issues,
statusDecisions,
workspaceOperations,
} from "@paperclipai/db";
import { CONTROL_PLANE_CONFORMANCE_OPEN } from "../vendor/paperclip-runner/testing.js";
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { finalizeNativeRun } from "../services/native-runtime/native-run-finalizer.js";
import { PaperclipControlPlanePort } from "../services/native-runtime/paperclip-control-plane-port.js";
import { documentService } from "../services/documents.js";
import { recoveryService } from "../services/recovery/service.js";
const cardFailure = vi.hoisted(() => ({ next: false }));
vi.mock("../services/native-runtime/native-plan-review-card.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../services/native-runtime/native-plan-review-card.js")>();
return {
...actual,
ensureNativePlanReviewCard: async (...args: Parameters<typeof actual.ensureNativePlanReviewCard>) => {
if (cardFailure.next) {
cardFailure.next = false;
throw new Error("connection reset while opening the card");
}
return actual.ensureNativePlanReviewCard(...args);
},
};
});
const committedPlanWait = vi.hoisted(() => ({ runIds: new Set<string>() }));
vi.mock("../services/native-runtime/native-plan-wait.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../services/native-runtime/native-plan-wait.js")>();
return {
...actual,
hasCommittedNativePlanWait: async (...args: Parameters<typeof actual.hasCommittedNativePlanWait>) =>
committedPlanWait.runIds.has(args[1].runId) || actual.hasCommittedNativePlanWait(...args),
};
});
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_PLAN_REVIEW_FINALIZER_TEST_DATABASE_URL");
// The live failure: the Antigravity process was killed mid Plan-mode run; the
// automatic continuation wrote a new plan revision and yielded "waiting for
// plan review" without opening the Approve / Request changes card. The task
// sat in progress with nothing for the user to act on.
describe("Plan-mode run settle opens the plan review", () => {
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
const companyId = "72300000-0000-4000-8000-000000000001";
const agentId = "72300000-0000-4000-8000-000000000002";
let seq = 0;
beforeAll(async () => {
if (!external) temporary = await startEmbeddedPostgresTestDatabase("paperclip-plan-review-finalizer-");
db = createDb(external ?? temporary.connectionString);
await db.insert(companies).values({ id: companyId, name: "Plan review", issuePrefix: "PRF" });
await db.insert(agents).values({ id: agentId, companyId, name: "Gemma Antigravity", adapterType: "antigravity_local", status: "running" });
}, 30_000);
afterAll(async () => {
await db?.$client.end({ timeout: 1 });
await temporary?.cleanup();
});
const yielded = {
schema: "paperclip.run_result.v1" as const,
reportedWorkDisposition: "yielded" as const,
summary: "Saved the plan. Waiting for plan review before executing.",
completionClaim: {
contractRevision: "plan-v1", objectiveSatisfied: false,
criteria: [{ criterionId: "objective", status: "unknown" as const, evidenceRefs: [] }],
remainingWork: [],
},
evidence: [], verification: [], attentionRequests: [], artifacts: [],
continuation: { kind: "response_wake" as const, summary: "Waiting for plan review", idempotencyKey: "plan-review-wake-v1" },
};
async function settleRun(options: { workMode: "planning" | "standard"; writePlan: boolean }) {
seq += 1;
const id = (n: number) => `72300000-0000-4000-8${String(seq).padStart(3, "0")}-${String(n).padStart(12, "0")}`;
const issueId = id(1), contractId = id(2), runId = id(3);
await db.insert(issues).values({ id: issueId, companyId, title: `Plan ${seq}`, status: "in_progress",
assigneeAgentId: agentId, workMode: options.workMode });
await db.insert(completionContracts).values({
id: contractId, companyId, issueId, revision: 1,
schemaVersion: "paperclip.completion-contract.v1", policyVersion: "phase6-v1", risk: "standard",
completionAuthority: "server_arbiter", incompleteCriteriaPolicy: "preserve_non_terminal",
contractJson: { revision: "plan-v1", objective: "Plan the file",
criteria: [{ id: "objective", requirement: "The plan is approved" }] },
canonicalSha256: `plan-contract-${seq}`, createdByActorType: "system", createdByActorId: "test",
});
await db.insert(heartbeatRuns).values({
id: runId, companyId, agentId, status: "running", runtimeMode: "native",
runtimeModeReason: "persisted_before_kill_switch", nativeIssueId: issueId, nativeSessionId: runId,
runnerInstanceId: contractId, completionContractId: contractId,
completionContractSha256: `plan-contract-${seq}`, contextSnapshot: { issueId },
});
if (options.writePlan) {
await documentService(db).upsertIssueDocument({ issueId, key: "plan", title: "Plan", format: "markdown",
body: "# Create crash-proof.txt\n\n1. Write CRASH.", createdByAgentId: agentId, createdByRunId: runId });
}
const port = new PaperclipControlPlanePort(db, {
companyId, issueId, runId, agentId, sessionId: runId, completionContractId: contractId,
completionContractSha256: `plan-contract-${seq}`, sourceInstanceId: contractId,
controlPlaneSourceInstanceId: `plan-control-${seq}`,
});
await port.openRun({ ...CONTROL_PLANE_CONFORMANCE_OPEN,
identity: { companyId, issueId, runId, agentId, sessionId: runId }, sourceInstanceId: contractId });
await port.completeRun({ result: yielded, terminal: { schema: "paperclip.prp.terminal.v1",
turnTerminalState: "completed", runTerminalState: "succeeded", reportedWorkDisposition: "yielded" },
callerResultId: `plan-result-${seq}` });
await db.insert(workspaceOperations).values({ companyId, heartbeatRunId: runId, issueId,
phase: "workspace_finalize", status: "succeeded" });
await finalizeNativeRun({ db, runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.id, issue!.lastStatusDecisionId!));
const cards = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, issueId));
const wakes = await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, companyId),
eq(agentWakeupRequests.agentId, agentId)));
return { issueId, runId, issue: issue!, decision: decision!, cards,
wakes: wakes.filter(wake => JSON.stringify(wake.payload ?? {}).includes(issueId)) };
}
it("opens one review card for the new plan revision and waits on it", async () => {
const settled = await settleRun({ workMode: "planning", writePlan: true });
expect(settled.cards).toHaveLength(1);
expect(settled.cards[0]).toMatchObject({ kind: "request_confirmation", status: "pending", sourceRunId: settled.runId });
expect(settled.cards[0]!.payload).toMatchObject({ target: { type: "issue_document", key: "plan", revisionNumber: 1 } });
expect(settled.issue.status).toBe("in_review");
expect(settled.decision.reasonCode).toBe("governed_response_waiting");
});
it("asks the agent for its plan when a Plan-mode run yields with none", async () => {
const settled = await settleRun({ workMode: "planning", writePlan: false });
expect(settled.cards).toHaveLength(0);
expect(settled.decision.reasonCode).toBe("plan_mode_plan_not_produced");
expect(settled.wakes.some(wake => JSON.stringify(wake.payload).includes("Plan mode"))).toBe(true);
});
it("gives a task left without its card by an older release one on the next recovery pass", async () => {
const settled = await settleRun({ workMode: "planning", writePlan: true });
// The state an older release left: settled, waiting, no card.
await db.delete(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId));
await db.update(issues).set({ status: "in_progress" }).where(eq(issues.id, settled.issueId));
const enqueueWakeup = vi.fn(async () => null);
const recovery = recoveryService(db, { enqueueWakeup });
await recovery.reconcileStrandedAssignedIssues({ companyId, issueId: settled.issueId });
await recovery.reconcileStrandedAssignedIssues({ companyId, issueId: settled.issueId });
const cards = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId));
expect(cards).toHaveLength(1);
expect(cards[0]).toMatchObject({ kind: "request_confirmation", status: "pending" });
expect(enqueueWakeup).not.toHaveBeenCalled();
});
it("settles the run when opening the card fails, and the next recovery pass opens it", async () => {
cardFailure.next = true;
const settled = await settleRun({ workMode: "planning", writePlan: true });
expect(settled.cards).toHaveLength(0);
expect(settled.issue.status).toBe("in_progress");
expect(settled.decision.reasonCode).toBe("response_wake_waiting_for_input");
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, settled.runId));
expect(run).toMatchObject({ status: "succeeded" });
await recoveryService(db, { enqueueWakeup: vi.fn(async () => null) })
.reconcileStrandedAssignedIssues({ companyId, issueId: settled.issueId });
const cards = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId));
expect(cards).toEqual([expect.objectContaining({ kind: "request_confirmation", status: "pending" })]);
});
it.each(["finalization reason", "committed plan wait"])("never opens a second card for a plan the user already accepted (%s)", async (proof) => {
const settled = await settleRun({ workMode: "planning", writePlan: true });
await db.delete(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId));
await db.update(issues).set({ status: "in_progress" }).where(eq(issues.id, settled.issueId));
if (proof === "finalization reason") {
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, settled.runId));
await db.update(heartbeatRuns).set({ resultJson: { ...(run!.resultJson as Record<string, unknown>),
finalizationReasonCode: "native_plan_accepted_waiting_for_continuation" } }).where(eq(heartbeatRuns.id, settled.runId));
} else committedPlanWait.runIds.add(settled.runId);
await recoveryService(db, { enqueueWakeup: vi.fn(async () => null) })
.reconcileStrandedAssignedIssues({ companyId, issueId: settled.issueId });
expect(await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId))).toHaveLength(0);
});
it("leaves a Standard-mode response wait unchanged", async () => {
const settled = await settleRun({ workMode: "standard", writePlan: true });
expect(settled.cards).toHaveLength(0);
expect(settled.issue.status).toBe("in_progress");
expect(settled.decision.reasonCode).toBe("response_wake_waiting_for_input");
});
});
@@ -0,0 +1,543 @@
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
import { randomUUID } from "node:crypto";
import { and, eq } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
activityLog,
agents,
companies,
createDb,
documentRevisions,
documents,
goals,
heartbeatRuns,
issueComments,
issueDocuments,
issueThreadInteractions,
issues,
} from "@paperclipai/db";
import { ensureNativePlanReviewCard, planReviewCardIdempotencyKey } from "../services/native-runtime/native-plan-review-card.js";
import { synchronizeCompletedProviderPlan } from "../services/native-runtime/native-session-executor.js";
import { documentService } from "../services/documents.js";
import { issueThreadInteractionService } from "../services/issue-thread-interactions.js";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
// Lets a test hand the card function the document as it was read before a
// newer revision landed: the window a delayed settle runs in.
const staleRead = vi.hoisted(() => ({ next: null as unknown }));
vi.mock("../services/documents.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../services/documents.js")>();
return {
...actual,
documentService: (db: Parameters<typeof actual.documentService>[0]) => {
const service = actual.documentService(db);
return {
...service,
getIssueDocumentByKey: async (...args: Parameters<typeof service.getIssueDocumentByKey>) => {
if (staleRead.next) {
const snapshot = staleRead.next;
staleRead.next = null;
return snapshot as Awaited<ReturnType<typeof service.getIssueDocumentByKey>>;
}
return service.getIssueDocumentByKey(...args);
},
};
},
};
});
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_PLAN_REVIEW_CARD_TEST_DATABASE_URL");
const embeddedPostgresSupport = external ? { supported: true } : await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
const PLAN = "# Create crash-proof.txt\n\n1. Write the file.\n2. Verify it.";
// Harnesses without a provider plan event (Antigravity and other ACPX agents)
// write the Plan document with a tool. A Plan-mode run that settles without
// opening the review card — for example a run recovered after its process was
// killed — must not leave the task waiting on a review nobody can give.
describeEmbeddedPostgres("Plan-mode review card on settle", () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
beforeAll(async () => {
if (!external) tempDb = await startEmbeddedPostgresTestDatabase("paperclip-plan-review-card-");
db = createDb(external ?? tempDb!.connectionString, { maxConnections: 6 });
}, 20_000);
afterEach(async () => {
await db.delete(activityLog);
await db.delete(issueComments);
await db.delete(issueThreadInteractions);
await db.delete(issueDocuments);
await db.delete(documentRevisions);
await db.delete(documents);
await db.delete(heartbeatRuns);
await db.delete(issues);
await db.delete(goals);
await db.delete(agents);
await db.delete(companies);
});
afterAll(async () => {
await db?.$client.end({ timeout: 1 });
await tempDb?.cleanup();
});
let prefix = 0;
async function seed(workMode: "standard" | "planning" = "planning", options: { conversation?: boolean } = {}) {
const companyId = randomUUID();
const goalId = randomUUID();
const issueId = randomUUID();
const agentId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Paperclip", issuePrefix: `PRC${++prefix}`, requireBoardApprovalForNewAgents: false });
await db.insert(goals).values({ id: goalId, companyId, title: "Ship", level: "task", status: "active" });
await db.insert(agents).values({
id: agentId, companyId, name: "Gemma", role: "engineer", status: "active",
adapterType: "antigravity_local", adapterConfig: {}, runtimeConfig: {}, permissions: {},
});
await db.insert(issues).values({
id: issueId, companyId, goalId, title: "Create crash-proof.txt", status: "in_progress",
priority: "medium", assigneeAgentId: agentId, workMode,
...(options.conversation ? { conversationAgentId: agentId, conversationUserId: "local-board", conversationState: "active" } : {}),
});
const newRun = async () => {
const runId = randomUUID();
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "succeeded", contextSnapshot: { issueId } });
return runId;
};
const binding = (runId: string) => ({ companyId, issueId, agentId, runId });
const writePlan = async (runId: string, body = PLAN) => documentService(db).upsertIssueDocument({
issueId, key: "plan", title: "Plan", format: "markdown", body,
baseRevisionId: (await documentService(db).getIssueDocumentByKey(issueId, "plan"))?.latestRevisionId ?? undefined,
createdByAgentId: agentId, createdByRunId: runId,
} as never);
const cards = () => db.select().from(issueThreadInteractions)
.where(and(eq(issueThreadInteractions.issueId, issueId), eq(issueThreadInteractions.kind, "request_confirmation")));
return { companyId, issueId, agentId, newRun, binding, writePlan, cards };
}
it("opens exactly one review card for a recovered run's new plan revision", async () => {
const t = await seed();
await t.newRun(); // the killed run
const recovered = await t.newRun();
await t.writePlan(recovered);
const outcome = await ensureNativePlanReviewCard(db, t.binding(recovered));
expect(outcome.kind).toBe("created");
const cards = await t.cards();
expect(cards).toHaveLength(1);
const plan = await documentService(db).getIssueDocumentByKey(t.issueId, "plan");
expect(cards[0]).toMatchObject({ status: "pending", sourceRunId: recovered, createdByAgentId: t.agentId });
expect(cards[0]!.payload).toMatchObject({
acceptLabel: "Approve plan", rejectLabel: "Request changes",
target: { type: "issue_document", key: "plan", revisionId: plan!.latestRevisionId, revisionNumber: 1 },
});
const activity = await db.select().from(activityLog).where(eq(activityLog.entityId, t.issueId));
expect(activity).toEqual([expect.objectContaining({ action: "issue.thread_interaction_created", actorType: "system" })]);
});
// The agent's plan card opened as instructed: bound to the saved plan revision.
async function agentPlanCard(t: Awaited<ReturnType<typeof seed>>, runId: string, key: string) {
const plan = await documentService(db).getIssueDocumentByKey(t.issueId, "plan");
return issueThreadInteractionService(db).create({ id: t.issueId, companyId: t.companyId }, {
kind: "request_confirmation", idempotencyKey: key, sourceRunId: runId, continuationPolicy: "wake_assignee",
payload: { version: 1, prompt: "Approve the plan?", acceptLabel: "Approve plan", rejectLabel: "Request changes",
target: { type: "issue_document", issueId: t.issueId, documentId: plan!.id, key: "plan",
revisionId: plan!.latestRevisionId, revisionNumber: plan!.latestRevisionNumber } },
} as never, { agentId: t.agentId, runId });
}
const plainCard = (t: Awaited<ReturnType<typeof seed>>, runId: string, key: string, prompt: string) =>
issueThreadInteractionService(db).create({ id: t.issueId, companyId: t.companyId }, {
kind: "request_confirmation", idempotencyKey: key, sourceRunId: runId, continuationPolicy: "wake_assignee_on_accept",
payload: { version: 1, prompt, acceptLabel: "Confirm", rejectLabel: "Request changes" },
} as never, { agentId: t.agentId, runId });
it("does nothing when the agent already opened its plan card for the revision", async () => {
const t = await seed();
const runId = await t.newRun();
await t.writePlan(runId);
await agentPlanCard(t, runId, "confirm-plan-v1");
await expect(ensureNativePlanReviewCard(db, t.binding(runId))).resolves.toMatchObject({ kind: "pending" });
expect(await t.cards()).toHaveLength(1);
});
it("keeps one card across repeated and concurrent settles of the same and later runs", async () => {
const t = await seed();
const runId = await t.newRun();
await t.writePlan(runId);
const reconcileRun = await t.newRun();
const outcomes = await Promise.all([
ensureNativePlanReviewCard(db, t.binding(runId)),
ensureNativePlanReviewCard(db, t.binding(runId)),
ensureNativePlanReviewCard(db, t.binding(reconcileRun)),
]);
await ensureNativePlanReviewCard(db, t.binding(runId));
await ensureNativePlanReviewCard(db, t.binding(reconcileRun));
expect(outcomes.filter(outcome => outcome.kind === "created")).toHaveLength(1);
expect(await db.select().from(activityLog).where(eq(activityLog.entityId, t.issueId))).toHaveLength(1);
const cards = await t.cards();
expect(cards.filter(card => card.status === "pending")).toHaveLength(1);
expect(cards).toHaveLength(1);
});
it("opens a new card for the revision written after Request changes and leaves the old one unanswerable", async () => {
const t = await seed();
const first = await t.newRun();
await t.writePlan(first);
const created = await ensureNativePlanReviewCard(db, t.binding(first));
if (created.kind !== "created") throw new Error("expected a card");
const interactions = issueThreadInteractionService(db);
const [oldCard] = await t.cards();
await interactions.rejectInteraction(
{ id: t.issueId, companyId: t.companyId }, oldCard!.id,
{ reason: "Name the file crash-proof-2.txt" } as never, { userId: "local-board" } as never,
);
// Request changes answered this revision: nothing new until the agent revises.
await expect(ensureNativePlanReviewCard(db, t.binding(first))).resolves.toMatchObject({ kind: "reviewed" });
const second = await t.newRun();
await t.writePlan(second, `${PLAN}\n3. Use crash-proof-2.txt.`);
await expect(ensureNativePlanReviewCard(db, t.binding(second))).resolves.toMatchObject({ kind: "created" });
const cards = await t.cards();
expect(cards).toHaveLength(2);
const pending = cards.filter(card => card.status === "pending");
expect(pending).toHaveLength(1);
expect(pending[0]!.payload).toMatchObject({ target: { revisionNumber: 2 } });
expect(cards.find(card => card.id === oldCard!.id)?.status).toBe("rejected");
});
it("replaces a still-pending card for an older revision", async () => {
const t = await seed();
const first = await t.newRun();
await t.writePlan(first);
await ensureNativePlanReviewCard(db, t.binding(first));
const [oldCard] = await t.cards();
const second = await t.newRun();
await t.writePlan(second, `${PLAN}\n3. Revised.`);
await expect(ensureNativePlanReviewCard(db, t.binding(second))).resolves.toMatchObject({ kind: "created" });
const cards = await t.cards();
expect(cards.find(card => card.id === oldCard!.id)?.status).toBe("expired");
expect(cards.filter(card => card.status === "pending")).toHaveLength(1);
await expect(interactionsAccept(t, oldCard!.id)).rejects.toThrow();
});
it("never withdraws a newer revision's card from a delayed settle of an older one", async () => {
const t = await seed();
const first = await t.newRun();
await t.writePlan(first);
const revisionOne = await documentService(db).getIssueDocumentByKey(t.issueId, "plan");
const second = await t.newRun();
await t.writePlan(second, `${PLAN}\n3. Revised.`);
await expect(ensureNativePlanReviewCard(db, t.binding(second))).resolves.toMatchObject({ kind: "created" });
// The first run's settle read revision 1 before revision 2 landed.
staleRead.next = revisionOne;
await expect(ensureNativePlanReviewCard(db, t.binding(first))).resolves.toMatchObject({ kind: "not_applicable" });
const cards = await t.cards();
expect(cards).toHaveLength(1);
expect(cards[0]).toMatchObject({ status: "pending" });
expect(cards[0]!.payload).toMatchObject({ target: { revisionNumber: 2 } });
});
it("withdraws the agent's plan card for v1 when a recovered run writes v2, leaving one answerable card", async () => {
const t = await seed();
const crashed = await t.newRun();
await t.writePlan(crashed);
const v1 = await agentPlanCard(t, crashed, "own-v1");
const recovered = await t.newRun();
await t.writePlan(recovered, `${PLAN}\n3. Revised after recovery.`);
await expect(ensureNativePlanReviewCard(db, t.binding(recovered))).resolves.toMatchObject({ kind: "created" });
const pending = (await t.cards()).filter(card => card.status === "pending");
expect(pending).toHaveLength(1);
expect(pending[0]!.payload).toMatchObject({ target: { revisionNumber: 2 } });
await expect(interactionsAccept(t, v1.id)).rejects.toThrow();
});
it("keeps an unrelated confirmation opened after the plan ordinary: answering it never approves the plan", async () => {
const t = await seed();
const runId = await t.newRun();
await t.writePlan(runId);
const unrelated = await plainCard(t, runId, "rename-repo", "May I rename the repository?");
expect((unrelated.payload as { target?: unknown }).target).toBeUndefined();
await expect(ensureNativePlanReviewCard(db, t.binding(runId))).resolves.toMatchObject({ kind: "created" });
await interactionsAccept(t, unrelated.id);
const [issue] = await db.select().from(issues).where(eq(issues.id, t.issueId));
expect(issue!.workMode).toBe("planning");
const planCards = (await t.cards()).filter(card => (card.payload as { target?: { key?: string } }).target?.key === "plan");
expect(planCards).toEqual([expect.objectContaining({ status: "pending" })]);
});
it("leaves a card opened before plan binding existed answerable, and still opens the current plan's card", async () => {
const t = await seed();
const first = await t.newRun();
await t.writePlan(first);
// A row an older release saved: the agent's plan card with no target.
const [legacy] = await db.insert(issueThreadInteractions).values({
companyId: t.companyId, issueId: t.issueId, kind: "request_confirmation", status: "pending",
continuationPolicy: "wake_assignee_on_accept", sourceRunId: first, createdByAgentId: t.agentId,
payload: { version: 1, prompt: "Proceed with plan v1?", acceptLabel: "Confirm", rejectLabel: "Request changes" },
}).returning();
const second = await t.newRun();
await new Promise(resolve => setTimeout(resolve, 5));
await t.writePlan(second, `${PLAN}\n3. Revised.`);
await expect(ensureNativePlanReviewCard(db, t.binding(second))).resolves.toMatchObject({ kind: "created" });
const cards = await t.cards();
// Not withdrawn by guess; its answer reaches the agent as an ordinary confirmation.
expect(cards.find(card => card.id === legacy!.id)?.status).toBe("pending");
expect(cards.filter(card => card.status === "pending" &&
(card.payload as { target?: { revisionNumber?: number } }).target?.revisionNumber === 2)).toHaveLength(1);
// Accepting the old card does not approve the newer revision.
await interactionsAccept(t, legacy!.id);
const [issue] = await db.select().from(issues).where(eq(issues.id, t.issueId));
expect(issue!.workMode).toBe("planning");
expect((await t.cards()).filter(card => card.status === "pending")).toHaveLength(1);
});
it.each(["server", "agent"])("keeps run A's pending %s plan card as the gate when run B settles a Plan-mode conversation", async (opener) => {
const t = await seed("planning", { conversation: true });
const first = await t.newRun();
await t.writePlan(first);
if (opener === "server") await expect(ensureNativePlanReviewCard(db, t.binding(first))).resolves.toMatchObject({ kind: "created" });
else await agentPlanCard(t, first, "conversation-plan");
const second = await t.newRun();
await expect(ensureNativePlanReviewCard(db, t.binding(second))).resolves.toMatchObject({ kind: "pending" });
expect((await t.cards()).filter(card => card.status === "pending")).toHaveLength(1);
});
async function interactionsAccept(t: Awaited<ReturnType<typeof seed>>, id: string) {
return issueThreadInteractionService(db).acceptInteraction(
{ id: t.issueId, companyId: t.companyId, projectId: null, goalId: null }, id, {} as never, { userId: "local-board" } as never,
);
}
it("returns the original card for an identical retry after a plan revision landed", async () => {
const t = await seed();
const runId = await t.newRun();
const first = await plainCard(t, runId, "retry-key", "May I proceed?");
// The response was lost; meanwhile the agent saved its plan.
await t.writePlan(runId);
const retried = await plainCard(t, runId, "retry-key", "May I proceed?");
expect(retried.id).toBe(first.id);
});
it("reports a Plan-mode run with no plan, and leaves Standard tasks untouched", async () => {
const planning = await seed();
const runId = await planning.newRun();
await expect(ensureNativePlanReviewCard(db, planning.binding(runId))).resolves.toEqual({ kind: "no_plan" });
expect(await planning.cards()).toHaveLength(0);
const standard = await seed("standard");
const standardRun = await standard.newRun();
await standard.writePlan(standardRun);
await expect(ensureNativePlanReviewCard(db, standard.binding(standardRun))).resolves.toEqual({ kind: "not_applicable" });
expect(await standard.cards()).toHaveLength(0);
});
it("leaves the card Codex and Claude open from their plan event as the only card", async () => {
const t = await seed();
const runId = randomUUID();
await db.insert(heartbeatRuns).values({ id: runId, companyId: t.companyId, agentId: t.agentId, status: "running", contextSnapshot: { issueId: t.issueId } });
const synced = await synchronizeCompletedProviderPlan({
db,
execution: {
binding: t.binding(runId), provider: { kind: "codex" }, task: { workMode: "planning" }, executionMode: "plan",
planningContext: { documentId: null, baseRevisionId: null, baseRevisionNumber: 0, markdown: "", sha256: "none", reviewContext: {} },
} as never,
event: { sourceEventId: "event-1", turnId: "turn-1", eventType: "plan.proposed",
payload: { schema: "paperclip.plan.proposed.v1", proposalId: "plan-1", status: "completed", markdown: PLAN, source: "codex" } },
});
expect(synced).toMatchObject({ status: "synchronized" });
await expect(ensureNativePlanReviewCard(db, t.binding(runId))).resolves.toMatchObject({ kind: "pending", interactionId: synced!.confirmationId });
expect(await t.cards()).toHaveLength(1);
});
it("does not put a person's own plan edit up for review", async () => {
const t = await seed();
const runId = await t.newRun();
await documentService(db).upsertIssueDocument({
issueId: t.issueId, key: "plan", title: "Plan", format: "markdown", body: "# My plan", createdByUserId: "local-board",
});
await expect(ensureNativePlanReviewCard(db, t.binding(runId))).resolves.toEqual({ kind: "not_applicable" });
expect(await t.cards()).toHaveLength(0);
});
// Each way a Plan-mode run can leave the task, and the one current action
// the user gets: a review card for the revision, or (no plan / already
// answered) the arbiter's "save your plan" continuation.
type Scenario = { name: string; setup: (t: Awaited<ReturnType<typeof seed>>, runId: string) => Promise<void>;
kind: "created" | "pending" | "reviewed" | "no_plan" };
const question = async (t: Awaited<ReturnType<typeof seed>>, runId: string) => {
const [row] = await db.insert(issueThreadInteractions).values({
companyId: t.companyId, issueId: t.issueId, kind: "ask_user_questions", status: "pending",
continuationPolicy: "wake_assignee", sourceRunId: runId, createdByAgentId: t.agentId,
payload: { version: 1, questions: [{ id: "q1", prompt: "Which name?", selectionMode: "single",
options: [{ id: "a", label: "A" }] }] },
}).returning();
return row!;
};
const scenarios: Scenario[] = [
{ name: "no plan saved", setup: async () => {}, kind: "no_plan" },
{ name: "plan saved, agent opened no card (first run or recovered run)", setup: async (t, runId) => { await t.writePlan(runId); }, kind: "created" },
{ name: "plan saved, agent opened its plan card bound to the revision", setup: async (t, runId) => {
await t.writePlan(runId); await agentPlanCard(t, runId, `own-${runId}`);
}, kind: "pending" },
{ name: "plan saved, agent opened an unbound confirmation (ordinary, not a plan review)", setup: async (t, runId) => {
await t.writePlan(runId); await plainCard(t, runId, `plain-${runId}`, "Proceed?");
}, kind: "created" },
{ name: "plan saved, agent asked a current question", setup: async (t, runId) => {
await t.writePlan(runId); await question(t, runId);
}, kind: "pending" },
{ name: "plan saved, an older question a later comment made historical", setup: async (t, runId) => {
await question(t, runId);
await db.insert(issueComments).values({ companyId: t.companyId, issueId: t.issueId, authorType: "user",
authorUserId: "local-board", body: "Use A.", createdAt: new Date(Date.now() + 1_000) });
await t.writePlan(runId);
}, kind: "created" },
{ name: "plan saved, an older question the user dismissed", setup: async (t, runId) => {
const row = await question(t, runId);
await db.update(issueThreadInteractions).set({ dismissedAt: new Date(), dismissedByUserId: "local-board" })
.where(eq(issueThreadInteractions.id, row.id));
await t.writePlan(runId);
}, kind: "created" },
...(["toolAction", "secretProposal", "connectionAuthorization", "qualityReview"] as const).flatMap(key =>
(["pending", "accepted", "rejected"] as const).map((status): Scenario => ({
name: `plan saved, an unrelated ${key} card (${status}) opened after it`,
setup: async (t, runId) => {
await t.writePlan(runId);
await db.insert(issueThreadInteractions).values({
companyId: t.companyId, issueId: t.issueId, kind: "request_confirmation", status,
continuationPolicy: "wake_assignee", sourceRunId: runId, createdByAgentId: t.agentId,
payload: { version: 1, prompt: "Allow this?", [key]: { id: "governed" } },
});
},
kind: "created",
}))),
{ name: "plan saved, a confirmation someone else opened after it", setup: async (t, runId) => {
await t.writePlan(runId);
await db.insert(issueThreadInteractions).values({
companyId: t.companyId, issueId: t.issueId, kind: "request_confirmation", status: "rejected",
continuationPolicy: "none", createdByUserId: "local-board",
payload: { version: 1, prompt: "Unrelated?" },
});
}, kind: "created" },
{ name: "revision already answered with Request changes, no new revision", setup: async (t, runId) => {
await t.writePlan(runId);
await ensureNativePlanReviewCard(db, t.binding(runId));
const [card] = await t.cards();
await issueThreadInteractionService(db).rejectInteraction({ id: t.issueId, companyId: t.companyId }, card!.id,
{ reason: "Rename it" } as never, { userId: "local-board" } as never);
}, kind: "reviewed" },
{ name: "new revision after Request changes", setup: async (t, runId) => {
await t.writePlan(runId);
await ensureNativePlanReviewCard(db, t.binding(runId));
const [card] = await t.cards();
await issueThreadInteractionService(db).rejectInteraction({ id: t.issueId, companyId: t.companyId }, card!.id,
{ reason: "Rename it" } as never, { userId: "local-board" } as never);
await t.writePlan(runId, `${PLAN}\n3. Renamed.`);
}, kind: "created" },
];
it.each(scenarios)("$name", async ({ setup, kind }) => {
const t = await seed();
const runId = await t.newRun();
await setup(t, runId);
const outcome = await ensureNativePlanReviewCard(db, t.binding(runId));
expect(outcome.kind).toBe(kind);
// A repeat settle changes nothing, and at most one review card is pending.
await expect(ensureNativePlanReviewCard(db, t.binding(runId))).resolves.toMatchObject({
kind: kind === "created" ? "pending" : kind });
const planReviews = (await t.cards()).filter(card => card.status === "pending" &&
(card.payload as { target?: { key?: string } }).target?.key === "plan");
expect(planReviews.length).toBeLessThanOrEqual(1);
if (kind === "created") expect(planReviews).toHaveLength(1);
});
// Every state the current revision's own plan card can reach, and what the
// user is left with: a current card, or (they decided) the agent's bounded
// "revise your plan" continuation. Never a silent wait, never a second card
// for a plan the user already accepted.
type CardState = { status: string; by?: "user" | "agent" | "system"; dismissed?: boolean; laterComment?: boolean;
outcome: "pending" | "reviewed" | "created" };
const cardStates: CardState[] = [
{ status: "pending", outcome: "pending" },
{ status: "pending", dismissed: true, outcome: "pending" },
{ status: "pending", laterComment: true, outcome: "pending" },
{ status: "accepted", by: "user", outcome: "reviewed" },
{ status: "rejected", by: "user", outcome: "reviewed" },
{ status: "cancelled", by: "user", outcome: "reviewed" },
{ status: "cancelled", by: "agent", outcome: "created" },
{ status: "expired", by: "system", outcome: "created" },
{ status: "expired", by: "agent", outcome: "created" },
{ status: "failed", by: "system", outcome: "created" },
];
it.each(cardStates)("current revision's card $status (by $by, dismissed $dismissed, later comment $laterComment) -> $outcome",
async ({ status, by, dismissed, laterComment, outcome }) => {
const t = await seed();
const runId = await t.newRun();
await t.writePlan(runId);
const plan = await documentService(db).getIssueDocumentByKey(t.issueId, "plan");
const resolved = status !== "pending";
const [card] = await db.insert(issueThreadInteractions).values(<typeof issueThreadInteractions.$inferInsert>{
companyId: t.companyId, issueId: t.issueId, kind: "request_confirmation", status: status as never,
continuationPolicy: "wake_assignee", sourceRunId: runId, createdByAgentId: t.agentId,
idempotencyKey: planReviewCardIdempotencyKey(plan!.latestRevisionId!),
payload: { version: 1, prompt: "Approve plan revision 1?", acceptLabel: "Approve plan", rejectLabel: "Request changes",
target: { type: "issue_document", issueId: t.issueId, documentId: plan!.id, key: "plan",
revisionId: plan!.latestRevisionId, revisionNumber: 1 } },
...(resolved ? { resolvedAt: new Date(),
resolvedByUserId: by === "user" ? "local-board" : null,
resolvedByAgentId: by === "agent" ? t.agentId : null } : {}),
...(dismissed ? { dismissedAt: new Date(), dismissedByUserId: "local-board" } : {}),
}).returning();
if (laterComment) await db.insert(issueComments).values({ companyId: t.companyId, issueId: t.issueId, authorType: "user",
authorUserId: "local-board", body: "Looking now.", createdAt: new Date(Date.now() + 1_000) });
const first = await ensureNativePlanReviewCard(db, t.binding(runId));
expect(first.kind).toBe(outcome);
const again = await ensureNativePlanReviewCard(db, t.binding(await t.newRun()));
expect(again.kind).toBe(outcome === "created" ? "pending" : outcome);
const pending = (await t.cards()).filter(row => row.status === "pending");
if (outcome === "reviewed") expect(pending).toHaveLength(0);
else expect(pending).toHaveLength(1);
if (outcome === "created") expect(pending[0]!.id).not.toBe(card!.id);
});
it("opens exactly one card for the current revision when settles race across a revision change", async () => {
for (let round = 0; round < 15; round += 1) {
const t = await seed();
const first = await t.newRun();
await t.writePlan(first);
await ensureNativePlanReviewCard(db, t.binding(first));
const second = await t.newRun();
await t.writePlan(second, `${PLAN}\n3. Round ${round}.`);
const runs = await Promise.all([t.newRun(), t.newRun(), t.newRun()]);
await Promise.all([second, ...runs].map(runId => ensureNativePlanReviewCard(db, t.binding(runId))));
const plan = await documentService(db).getIssueDocumentByKey(t.issueId, "plan");
const pending = (await t.cards()).filter(card => card.status === "pending");
expect(pending).toHaveLength(1);
expect(pending[0]!.payload).toMatchObject({ target: { revisionId: plan!.latestRevisionId } });
}
});
});
@@ -153,6 +153,7 @@ const explicitOpenApiOperationCoverageExclusions = new Set([
// Ordinary board sessions and agent API keys cannot invoke these endpoints.
"GET /api/customer-success/v1/run-authority",
"POST /api/customer-success/v1/read",
"POST /api/customer-success/v1/read-v2",
"POST /api/customer-success/v1/run-liveness",
// OAuth discovery and protocol endpoints have their own metadata contract;
// browser connection-management operations remain documented in the board API.
+12 -3
View File
@@ -1,9 +1,11 @@
import { createPublicKey, verify } from "node:crypto";
import { Router } from "express";
import { Router, type Request as ExpressRequest, type Response as ExpressResponse } from "express";
import type { Db } from "@paperclipai/db";
import {
canonicalJson,
inspectionReadPath,
parseInspectionQuery,
INSPECTION_READ_PATH,
INSPECTION_AUDIENCE,
INSPECTION_PERMIT_TYPE,
INSPECTION_HEADER,
@@ -180,7 +182,10 @@ export function customerSuccessRoutes(db: Db, storage: StorageService, options:
if (!match) throw forbidden("Managed run bearer required");
res.json(await customerSuccessRunAuthority(db, match[1]));
});
router.post("/read", async (req, res) => {
// `/read` serves the original query features; `/read-v2` also serves
// count, order and view. Cloud picks the path from the query, so a tenant
// without `/read-v2` answers 404 and Cloud fails closed.
const read = async (req: ExpressRequest, res: ExpressResponse) => {
if (process.env.PAPERCLIP_CUSTOMER_SUCCESS_INSPECTION_ENABLED !== "true")
throw forbidden("Inspection is disabled");
if (req.headers.authorization || req.headers.cookie)
@@ -209,6 +214,8 @@ export function customerSuccessRoutes(db: Db, storage: StorageService, options:
}
if (canonicalJson(query) !== canonicalJson(permit.query))
throw forbidden("Inspection parameters do not match permit");
if (req.path === INSPECTION_READ_PATH && inspectionReadPath(query) !== INSPECTION_READ_PATH)
throw forbidden("This inspection query needs the extended read path");
// Replay fencing and all inspection state live in Cloud. No tenant receipt.
const consumed = await fetch(`${origin}/v1/customer-success/permits/consume`, {
method: "POST",
@@ -223,7 +230,9 @@ export function customerSuccessRoutes(db: Db, storage: StorageService, options:
if (body === null)
throw unprocessable("Inspection response is too large; use pagination or a byte range");
res.type("application/json").send(body);
});
};
router.post("/read", read);
router.post("/read-v2", read);
// Cloud run liveness check for inspection authority. Cloud asks with its
// own signed, stack-addressed, 60-second question; no agent credential,
// identity key, actor, session or activity is involved.
@@ -1,7 +1,7 @@
import fs from "node:fs/promises";
import { constants } from "node:fs";
import { and, eq, getTableColumns, type SQL } from "drizzle-orm";
import type { AnyPgTable, AnyPgColumn } from "drizzle-orm/pg-core";
import { and, asc, count, desc, eq, getTableColumns, type SQL } from "drizzle-orm";
import { getTableConfig, type AnyPgTable, type AnyPgColumn } from "drizzle-orm/pg-core";
import * as schema from "@paperclipai/db";
import type { Db } from "@paperclipai/db";
import {
@@ -31,6 +31,42 @@ export interface CustomerSuccessInspectionOptions {
pluginWorkerManager?: PluginWorkerManager;
}
/**
* The `summary` view of a run: status, timestamps, ids and error codes, never
* the large JSON columns (result, usage, context snapshot, runner profile...),
* which make a full run row 170-540 KB. An allowlist, so a new column stays out
* until someone adds it here.
*/
export const RUN_SUMMARY_COLUMNS = [
"id",
"companyId",
"agentId",
"issueId",
"scopeKind",
"invocationSource",
"triggerDetail",
"status",
"errorCode",
"exitCode",
"runtimeMode",
"driverKind",
"retryOfRunId",
"processLossRetryCount",
"scheduledRetryAttempt",
"continuationAttempt",
"livenessState",
"startedAt",
"finishedAt",
"createdAt",
"updatedAt",
] as const;
function durationMs(row: Record<string, unknown>): number | null {
const started = row.startedAt instanceof Date ? row.startedAt.getTime() : null;
const finished = row.finishedAt instanceof Date ? row.finishedAt.getTime() : null;
return started !== null && finished !== null ? Math.max(0, finished - started) : null;
}
// This is a reviewed catalog of readers, not a proxy for existing GET routes.
// Select credentials out of queries; never load encrypted identity records.
interface Reader {
@@ -109,6 +145,13 @@ export const inspectionReaders: Record<InspectionResource, Reader> = {
threads: { table: schema.chatConversations, parent: "endpointId" },
};
/** The table's primary key columns: a stable tie-breaker for ordered pages. */
export function primaryKeyColumns(table: AnyPgTable): AnyPgColumn[] {
const config = getTableConfig(table);
const single = config.columns.filter((column) => column.primary);
return single.length ? single : (config.primaryKeys[0]?.columns ?? []);
}
async function ownRow(tx: Db, table: AnyPgTable, companyId: string, id: string) {
const columns = getTableColumns(table) as Record<string, AnyPgColumn>;
const [row] = await tx
@@ -157,7 +200,7 @@ export async function readCustomerSuccessResource(
.where(eq(schema.companies.id, q.companyId));
if (!company) throw notFound("Inspection company not found");
}
if (q.operation === "list" || q.operation === "get") {
if (q.operation === "list" || q.operation === "get" || q.operation === "count") {
const reader = inspectionReaders[q.resource!];
const all = getTableColumns(reader.table) as Record<string, AnyPgColumn>;
const columns = Object.fromEntries(
@@ -180,6 +223,7 @@ export async function readCustomerSuccessResource(
const { inArray } = await import("drizzle-orm");
if (!memberships.length) {
if (q.operation === "get") throw notFound("Inspection resource not found");
if (q.operation === "count") return { total: 0, byStatus: all.status ? {} : null };
return { items: [], nextOffset: null };
}
predicates.push(
@@ -200,13 +244,51 @@ export async function readCustomerSuccessResource(
throw unprocessable("This reader does not accept parentId");
predicates.push(eq(all[reader.parent], q.parentId));
}
if (q.operation === "count") {
// Totals only: no row content leaves the database.
if (!all.status) {
const [{ total }] = await tx
.select({ total: count() })
.from(reader.table)
.where(and(...predicates));
return { total: Number(total), byStatus: null };
}
const groups = await tx
.select({ status: all.status, total: count() })
.from(reader.table)
.where(and(...predicates))
.groupBy(all.status);
const byStatus: Record<string, number> = {};
let total = 0;
for (const group of groups) {
byStatus[String(group.status)] = Number(group.total);
total += Number(group.total);
}
return { total, byStatus };
}
const limit = q.operation === "get" ? 1 : Math.max(1, q.limit ?? 25);
const order = all[reader.id ?? "id"] ?? all.createdAt ?? all.companyId;
const idColumn = all[reader.id ?? "id"];
let orderBy: SQL[] | AnyPgColumn[];
if (q.order) {
if (!all.createdAt) throw unprocessable("This resource has no creation time to order by");
const direction = q.order === "newest" ? desc : asc;
// Rows written together share createdAt; the full primary key keeps
// offset pages from repeating or skipping them.
orderBy = [all.createdAt, ...primaryKeyColumns(reader.table)].map((column) => direction(column));
} else {
orderBy = [idColumn ?? all.createdAt ?? all.companyId];
}
const selected =
q.view === "summary"
? Object.fromEntries(
RUN_SUMMARY_COLUMNS.filter((key) => columns[key]).map((key) => [key, columns[key]]),
)
: columns;
let rows = await tx
.select(columns)
.select(selected)
.from(reader.table)
.where(and(...predicates))
.orderBy(order)
.orderBy(...orderBy)
.limit(limit + (q.operation === "get" ? 0 : 1))
.offset(q.offset ?? 0);
if (q.resource === "agents")
@@ -245,6 +327,7 @@ export async function readCustomerSuccessResource(
q.companyId!,
rows as Array<{ id: string }>,
);
if (q.view === "summary") rows = rows.map((r) => ({ ...r, durationMs: durationMs(r) }));
// Match the existing structured event/config redaction, without scanning
// prose, documents, instructions, skill contents, or workspace files.
if (
@@ -1,6 +1,6 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { buildPaperclipTaskMarkdown } from "./task-markdown.js";
import { NATIVE_PLAN_REVIEW_DIRECTIVE, buildPaperclipTaskMarkdown } from "./task-markdown.js";
const issue = {
id: "task-1",
@@ -66,6 +66,15 @@ describe("heartbeat task markdown rendering", () => {
expect(markdown).toContain("Do not invent material user intent or success criteria");
});
it("tells a native Plan-mode run that Paperclip opens the one plan review card", () => {
const planning = { issue: { ...issue, workMode: "planning" } };
expect(buildPaperclipTaskMarkdown({ ...planning, nativeRunner: true })).toContain(NATIVE_PLAN_REVIEW_DIRECTIVE);
// Adapters keep their own approval flow, and an accepted plan is executed.
expect(buildPaperclipTaskMarkdown({ ...planning, nativeRunner: false })).not.toContain(NATIVE_PLAN_REVIEW_DIRECTIVE);
expect(buildPaperclipTaskMarkdown({ ...planning, nativeRunner: true, acceptedPlanContinuation: true,
taskPlan: { documentId: "plan", revisionId: "revision", revisionNumber: 1, body: "Do it." } })).not.toContain(NATIVE_PLAN_REVIEW_DIRECTIVE);
});
it("preserves execution of a clear accepted plan without imposing clarification", () => {
const markdown = buildPaperclipTaskMarkdown({
issue: { ...issue, workMode: "planning" },
@@ -7,6 +7,9 @@ import { TASK_QUESTION_GUIDANCE } from "../issue-question-context.js";
import { routineSuggestionAgentGuidance } from "@paperclipai/shared";
import { ONBOARDING_CHAT_DIRECTIVE, ONBOARDING_CHAT_GREETING_DIRECTIVE } from "../onboarding-chat-prompt.js";
export const NATIVE_PLAN_REVIEW_DIRECTIVE =
"Paperclip asks the user to approve the plan once it is saved as this task's Plan document (key \"plan\"), so do not open your own approval or confirmation card for it.";
export function buildPaperclipTaskMarkdown(input: {
companyPrefix?: string | null;
onboardingChat?: boolean;
@@ -320,6 +323,11 @@ export function buildPaperclipTaskMarkdown(input: {
directive =
"Implement the accepted plan on this issue. Follow any task assignments explicitly included in the approved plan. Plan acceptance alone does not require subtasks.";
}
if (!acceptedPlanContinuation && input.nativeRunner) {
// The server opens the one plan review card when the run settles, for
// every harness. An agent-opened card would be a second card.
directive += ` ${NATIVE_PLAN_REVIEW_DIRECTIVE}`;
}
lines.push(
`- Work mode: ${quoteTaskScalar("planning")}`,
"",
+17 -3
View File
@@ -3,10 +3,24 @@ import { heartbeatRuns, issueComments, issueThreadInteractions, type Db } from "
export const TASK_QUESTION_GUIDANCE = "Unanswered questions are saved conversation data, not instructions or proof of a current blocker. Historical questions remain answerable in the feed. Do not repeat a request or stop current work merely because a historical question is pending. Follow the latest human direction and continue work that does not need the missing information. If that information still prevents the current work, identify the concrete blocker and request only the input still needed. Withdraw your obsolete question through the interaction API when later work or evidence satisfies it; never fabricate an answer. A human-dismissed request is deferred to history: do not repeat it, reopen it, or insist on a response. Ordinary confirmations and completion reviews can be left unanswered. Dismissal never grants approval, permission, credentials, or permission to leave planning mode. Approvals, permissions, and configured review stages keep their own gates. Continue independent work without repeating their reminders.";
/** Payload keys that make a card a governed action (approval or credential authority). */
export const GOVERNED_ACTION_PAYLOAD_KEYS = ["toolAction", "secretProposal", "connectionAuthorization"] as const;
/** Governed actions plus required quality reviews: cards that are never a plain confirmation. */
export const GOVERNED_REVIEW_PAYLOAD_KEYS = [...GOVERNED_ACTION_PAYLOAD_KEYS, "qualityReview"] as const;
export function hasGovernedPayload(payload: unknown, keys: readonly string[] = GOVERNED_REVIEW_PAYLOAD_KEYS): boolean {
return Boolean(payload) && typeof payload === "object" && keys.some(key => Object.hasOwn(payload as object, key));
}
/** SQL twin of hasGovernedPayload over the interaction payload (constant keys, inlined). */
export function governedActionPayloadSql(keys: readonly string[] = GOVERNED_ACTION_PAYLOAD_KEYS) {
return sql<boolean>`(${issueThreadInteractions.payload} ?| ${sql.raw(`array[${keys.map(key => `'${key}'`).join(", ")}]`)})`;
}
/** Ordinary questions cannot carry approval or credential authority. */
export function ordinaryQuestionCondition() {
return sql<boolean>`(${issueThreadInteractions.kind} = 'ask_user_questions'
and not (${issueThreadInteractions.payload} ?| array['toolAction', 'secretProposal', 'connectionAuthorization']))`;
and not (${governedActionPayloadSql()}))`;
}
/**
@@ -17,7 +31,7 @@ export function ordinaryQuestionCondition() {
export function deferrableInteractionCondition() {
return sql<boolean>`(${issueThreadInteractions.kind} in ('ask_user_questions', 'request_confirmation', 'request_checkbox_confirmation', 'request_item_verdicts', 'suggest_tasks')
and ${issueThreadInteractions.effectiveResolverPolicySource} = 'requested'
and not (${issueThreadInteractions.payload} ?| array['toolAction', 'secretProposal', 'connectionAuthorization'])
and not (${governedActionPayloadSql()})
and coalesce(${issueThreadInteractions.payload}->'target'->>'type', '') <> 'issue_document')`;
}
@@ -89,7 +103,7 @@ export function activeIssueInteractionCondition(input: {
${ordinaryQuestionCondition()}
or (${issueThreadInteractions.kind} in ('request_confirmation', 'request_checkbox_confirmation')
and ${issueThreadInteractions.effectiveResolverPolicy} = 'anyone'
and not (${issueThreadInteractions.payload} ?| array['toolAction', 'secretProposal', 'connectionAuthorization']))
and not (${governedActionPayloadSql()}))
)
)` : undefined,
)!;
@@ -14,7 +14,7 @@ import { notifyToolReviewChange } from "./tool-review-work-notifications.js";
import { projectGitHubInteractionErrors } from "./tool-access/github-action-error-projection.js";
import { normalizeEscapedLineBreaks } from "@paperclipai/shared/validators/text";
import { notifyDeliveryWork, DELIVERY_QUEUES } from "./delivery-work-notifications.js";
import { historicalQuestionCondition } from "./issue-question-context.js";
import { hasGovernedPayload, historicalQuestionCondition } from "./issue-question-context.js";
import {
currentContinuationOrigins,
deliveredContinuationCommentIds,
@@ -228,6 +228,8 @@ type CreateInteractionOptions = {
supersedePendingSiblingInteractions?: boolean;
replayAcceptedInteractionIds?: readonly string[];
requireAcceptedReplay?: boolean;
/** Runs once, in the insert transaction, only when this call created the card (never on an idempotent replay). */
afterInsertInTransaction?: (tx: Db, row: IssueThreadInteractionRow) => Promise<void>;
};
type InteractionWakeup = (
@@ -693,7 +695,7 @@ async function isEquivalentAcceptedReplay(
if (
!replayAcceptedInteractionIds.includes(row.id)
|| !isRequestConfirmationLikeKind(row.kind)
|| ["toolAction", "secretProposal", "connectionAuthorization", "qualityReview"].some(key => Object.hasOwn(row.payload, key))
|| hasGovernedPayload(row.payload)
|| row.status !== "accepted"
|| row.result?.outcome !== "accepted"
|| !row.resolvedAt
@@ -5324,6 +5326,7 @@ export function issueThreadInteractionService(
})
.returning();
await options.afterInsertInTransaction?.(tx as unknown as Db, row);
if (row.addresseeAgentId || row.addresseeUserId) {
const [privacyIssue] = await tx.select().from(issues).where(and(eq(issues.id, issue.id), eq(issues.companyId, issue.companyId)));
await ensureAssignmentIssueAccessGrant(tx, { ...privacyIssue!,
@@ -0,0 +1,252 @@
import { and, eq, inArray } from "drizzle-orm";
import { documentRevisions, documents, issueThreadInteractions, issues, type Db } from "@paperclipai/db";
import { logActivity, publishActivity } from "../activity-log.js";
import { documentService } from "../documents.js";
import { HttpError } from "../../errors.js";
import { logger } from "../../middleware/logger.js";
import { issueThreadInteractionService } from "../issue-thread-interactions.js";
import { activeIssueInteractionCondition, hasGovernedPayload } from "../issue-question-context.js";
import { isConversation } from "../../lib/conversation-wake-policy.js";
/**
* The Plan-mode review card for the current plan revision.
*
* Codex and Claude report their plan as a provider event, and the session
* opens the Approve / Request changes card for it. Harnesses without such an
* event (Antigravity and other ACPX agents) write the Plan document with a
* tool and must open the card themselves. A run that forgets, or a recovered
* run that resumes after the original process died, would otherwise leave a
* Plan-mode task waiting on a review nobody can give. When a Plan-mode run
* settles, the server opens the card for the current revision unless one
* already covers it.
*/
export type NativePlanReviewCardOutcome =
/** The server opened the card for this revision. */
| { kind: "created"; interactionId: string; revisionId: string }
/** A pending card (or question) already gives the user the next action. */
| { kind: "pending"; interactionId: string }
/** The current revision was already answered; the agent owes a new revision. */
| { kind: "reviewed"; revisionId: string }
/** Plan mode produced no plan to review. */
| { kind: "no_plan" }
/** Not a Plan-mode task this agent owns, or the revision is not the agent's. */
| { kind: "not_applicable" };
type Binding = { companyId: string; issueId: string; runId: string; agentId: string };
const record = (value: unknown): Record<string, unknown> =>
value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
export function planReviewCardIdempotencyKey(revisionId: string): string {
return `plan-review:v1:${revisionId}`;
}
/**
* The one Plan-review card shape, for the card Paperclip opens from a
* provider's plan event (Codex, Claude) and the one it opens on settle.
*/
export function planReviewConfirmationInput(input: {
issueId: string;
documentId: string;
revisionId: string;
revisionNumber: number;
sourceRunId: string;
idempotencyKey: string;
source: "provider_plan" | "plan_document";
}) {
return {
kind: "request_confirmation" as const,
idempotencyKey: input.idempotencyKey,
sourceRunId: input.sourceRunId,
title: `Review plan revision ${input.revisionNumber}`,
summary: input.source === "provider_plan"
? "Review the synchronized Paperclip plan."
: "Review the plan before the agent starts the work.",
continuationPolicy: "wake_assignee" as const,
payload: {
version: 1 as const,
prompt: `Approve plan revision ${input.revisionNumber}?`,
...(input.source === "provider_plan"
? { detailsMarkdown: "The completed provider plan has been synchronized to the canonical Plan document." }
: {}),
acceptLabel: "Approve plan",
rejectLabel: "Request changes",
rejectRequiresReason: true,
supersedeOnUserComment: false,
target: {
type: "issue_document" as const,
issueId: input.issueId,
documentId: input.documentId,
key: "plan",
revisionId: input.revisionId,
revisionNumber: input.revisionNumber,
label: `Plan v${input.revisionNumber}`,
},
},
};
}
async function coveringCard(db: Db, binding: Binding, revision: { id: string }, conversationMode: boolean) {
// A historical or deferred card cannot give the user the next action; the
// same rule decides the run's governance gate.
const active = new Set((await db.select({ id: issueThreadInteractions.id }).from(issueThreadInteractions).where(and(
eq(issueThreadInteractions.companyId, binding.companyId),
eq(issueThreadInteractions.issueId, binding.issueId),
eq(issueThreadInteractions.status, "pending"),
activeIssueInteractionCondition({ runId: binding.runId, conversationMode }),
))).map(row => row.id));
const cards = await db.select({
id: issueThreadInteractions.id,
kind: issueThreadInteractions.kind,
status: issueThreadInteractions.status,
payload: issueThreadInteractions.payload,
createdAt: issueThreadInteractions.createdAt,
resolvedByUserId: issueThreadInteractions.resolvedByUserId,
resolvedByAgentId: issueThreadInteractions.resolvedByAgentId,
result: issueThreadInteractions.result,
}).from(issueThreadInteractions).where(and(
eq(issueThreadInteractions.companyId, binding.companyId),
eq(issueThreadInteractions.issueId, binding.issueId),
inArray(issueThreadInteractions.kind, ["request_confirmation", "ask_user_questions"]),
));
const targetRevision = (payload: unknown) => {
const target = record(record(payload).target);
return target.type === "issue_document" && typeof target.revisionId === "string" ? target.revisionId : null;
};
// Only an explicit plan review covers a revision: a card bound to this
// revision (the server's, Codex/Claude's, or an agent's card opened with the
// plan target). An unbound confirmation is an ordinary request: it never
// covers a plan, never starts execution and is never withdrawn here. A
// pending question also gives the user the next action. A card bound to an
// older revision does not cover this one.
const covers = (card: (typeof cards)[number]) => {
if (card.kind === "ask_user_questions") return card.status === "pending";
if (hasGovernedPayload(card.payload)) return false;
return targetRevision(card.payload) === revision.id;
};
// A pending card bound to this revision always gates it, also when the
// conversation prior-turn rule would leave it out of the active set.
const pending = cards.find(card => card.status === "pending" && covers(card) &&
(active.has(card.id) || targetRevision(card.payload) === revision.id));
if (pending) return { kind: "pending" as const, interactionId: pending.id };
// How each terminal state of a card bound to this revision counts:
// - accepted or rejected: the user decided this revision;
// - cancelled by the user (withdrawn from the thread): the user declined to
// review this revision. Do not reopen it; the agent is asked to revise.
// - cancelled by an agent or the system, expired (superseded, stale, task
// closed) or failed: no one reviewed it. The revision gets a fresh card.
// A card withdrawn as a stale target was for an older revision, even though
// the withdrawal records the current revision on it.
const bound = cards.filter(card => card.kind === "request_confirmation" && covers(card) &&
record(card.result).outcome !== "stale_target");
const decided = bound.find(card => ["accepted", "rejected"].includes(card.status) ||
(card.status === "cancelled" && card.resolvedByUserId && !card.resolvedByAgentId));
if (decided) return { kind: "reviewed" as const, revisionId: revision.id };
const unreviewed = bound.filter(card => card.status !== "pending")
.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())[0];
return unreviewed ? { kind: "reopen" as const, afterInteractionId: unreviewed.id } : null;
}
export async function ensureNativePlanReviewCard(db: Db, binding: Binding): Promise<NativePlanReviewCardOutcome> {
const publications: Parameters<typeof publishActivity>[0][] = [];
// One decision per task at a time: reading the current revision and its
// cards, withdrawing older cards, choosing the key and inserting all happen
// under the task row lock, so two settles can never both open a card for
// one plan. Card creation takes the same lock first, so the order matches.
const outcome = await db.transaction(async (transaction) => {
const tx = transaction as unknown as Db;
const [issue] = await tx.select({
workMode: issues.workMode, status: issues.status, assigneeAgentId: issues.assigneeAgentId,
assigneeUserId: issues.assigneeUserId, hiddenAt: issues.hiddenAt,
conversationAgentId: issues.conversationAgentId, conversationUserId: issues.conversationUserId,
}).from(issues).where(and(eq(issues.id, binding.issueId), eq(issues.companyId, binding.companyId))).limit(1).for("update");
if (!issue || issue.workMode !== "planning" || issue.hiddenAt || issue.assigneeUserId ||
issue.assigneeAgentId !== binding.agentId || ["done", "cancelled"].includes(issue.status)) {
return { kind: "not_applicable" } as const;
}
const plan = await documentService(tx).getIssueDocumentByKey(binding.issueId, "plan");
if (!plan?.latestRevisionId) return { kind: "no_plan" } as const;
const [revision] = await tx.select({
id: documentRevisions.id, revisionNumber: documentRevisions.revisionNumber,
createdByAgentId: documentRevisions.createdByAgentId,
}).from(documentRevisions).where(and(
eq(documentRevisions.id, plan.latestRevisionId), eq(documentRevisions.companyId, binding.companyId),
)).limit(1);
if (!revision) return { kind: "no_plan" } as const;
// A delayed settle that read an older revision must not act on it.
const [current] = await tx.select({ latestRevisionId: documents.latestRevisionId, latestRevisionNumber: documents.latestRevisionNumber })
.from(documents).where(and(eq(documents.id, plan.id), eq(documents.companyId, binding.companyId))).for("update");
if (current?.latestRevisionId !== revision.id) return { kind: "not_applicable" } as const;
const conversationMode = isConversation(issue);
const existing = await coveringCard(tx, binding, revision, conversationMode);
if (existing && existing.kind !== "reopen") return existing;
// Only the assigned agent's own proposal is put up for review. A revision
// a person wrote is theirs already.
if (revision.createdByAgentId !== binding.agentId) return { kind: "not_applicable" } as const;
// A card for this revision that no one reviewed keeps its key; the fresh
// card's key names the one it follows.
const idempotencyKey = existing?.kind === "reopen"
? `${planReviewCardIdempotencyKey(revision.id)}:after:${existing.afterInteractionId}`
: planReviewCardIdempotencyKey(revision.id);
// Withdraw cards bound to an older revision. Answering one is already
// refused as a stale target, so this only tidies the thread: a row it
// cannot read must not stop the current card from opening.
await tx.transaction(async (savepoint) => {
await issueThreadInteractionService(savepoint as unknown as Db).expireStaleRequestConfirmationsForIssueDocument(
{ id: binding.issueId, companyId: binding.companyId },
{ id: plan.id, key: "plan", latestRevisionId: current.latestRevisionId, latestRevisionNumber: current.latestRevisionNumber },
{ agentId: binding.agentId, runId: binding.runId });
}).catch((error: unknown) => logger.warn({ issueId: binding.issueId, error }, "Could not withdraw stale plan review cards"));
let inserted = false;
try {
const interaction = await issueThreadInteractionService(tx).create(
{ id: binding.issueId, companyId: binding.companyId },
planReviewConfirmationInput({
issueId: binding.issueId, documentId: plan.id, revisionId: revision.id, revisionNumber: revision.revisionNumber,
sourceRunId: binding.runId, source: "plan_document", idempotencyKey,
}) as never,
{ agentId: binding.agentId, runId: binding.runId },
{
// Leave the agent's other pending cards answerable. Only cards bound
// to an older plan revision were withdrawn above; an unbound card is
// never withdrawn by guess.
supersedePendingSiblingInteractions: false,
// Only the call that inserted the card records it.
afterInsertInTransaction: async (insertTx, row) => {
inserted = true;
await logActivity(insertTx, {
companyId: binding.companyId,
actorType: "system",
actorId: "native-plan-review",
agentId: binding.agentId,
runId: binding.runId,
issueId: binding.issueId,
action: "issue.thread_interaction_created",
entityType: "issue",
entityId: binding.issueId,
details: {
interactionId: row.id,
interactionKind: "request_confirmation",
source: "plan_mode_settle",
planRevisionId: revision.id,
planRevisionNumber: revision.revisionNumber,
},
}, publications);
},
},
);
return inserted
? { kind: "created", interactionId: interaction.id, revisionId: revision.id } as const
: { kind: "pending", interactionId: interaction.id } as const;
} catch (error) {
// The task closed or the agent may no longer write here. A refused card
// must not fail the run's settlement; database errors still surface so
// finalization (or the recovery pass) retries.
if (!(error instanceof HttpError) || error.status >= 500) throw error;
const covered = await coveringCard(tx, binding, revision, conversationMode);
return covered && covered.kind !== "reopen" ? covered : { kind: "not_applicable" } as const;
}
});
for (const publication of publications) publishActivity(publication);
return outcome;
}
@@ -114,6 +114,7 @@ import {
} from "../heartbeat-run-summary.js";
import { resolveChatRunPresentationAuthorizationReason } from "../chat-run-publications.js";
import { settledResponsePublicationSql } from "./native-response-publication-receipt.js";
import { ensureNativePlanReviewCard } from "./native-plan-review-card.js";
import { hasChatRunOwnedProviderInteraction } from "../chat-interaction-arbitration.js";
import {
authorizeCommittedChatResponse,
@@ -1677,6 +1678,23 @@ export async function finalizeNativeRun(input: {
? await findSupersededExternalReviewRequests(input.db, {
companyId: run.companyId, issueId: authoritativeIssue.id, runId: run.id, agentId: run.agentId,
}) : [];
// A Plan-mode run that settles with a plan revision nobody was asked to
// review gets its review card here, whichever harness ran it and whether
// or not the agent remembered to open it. The card is the review gate below.
const planReview = terminalState === "succeeded" && input.workspaceFinalizeStatus === "succeeded" &&
authoritativeIssue.workMode === "planning" && result.reportedWorkDisposition !== "done" &&
!isNativePlanWaitResult(result) &&
!readNativeReviewAssignmentContext(run.contextSnapshot)
? await ensureNativePlanReviewCard(input.db, {
companyId: run.companyId, issueId: authoritativeIssue.id, runId: run.id, agentId: run.agentId,
}).catch((error: unknown) => {
// The run already succeeded; a card that could not be opened must
// not fail its settlement. The task settles in its response wait and
// the stranded-task pass opens the card (idempotently) later.
logger.warn({ runId: run.id, issueId: authoritativeIssue.id, error }, "Plan review card could not be opened at settle; recovery will retry");
return null;
})
: null;
const governanceGate = await pendingNativeGovernance({
db: input.db,
companyId: run.companyId,
@@ -1778,6 +1796,7 @@ export async function finalizeNativeRun(input: {
monitorWaitSuperseded: supersededMonitorWait !== null,
monitorWaitAuthorized: authoritativeIssue.workMode === "standard" && authoritativeIssue.executionRunId === run.id && monitorWaitAt !== null,
planWaitAuthorized: planWait !== null,
planNotProduced: planReview?.kind === "no_plan" || planReview?.kind === "reviewed",
hasPendingChildCompletion,
providerModelRejected: providerFailure?.errorCode === "native_provider_model_rejected" && ownsProviderFailureDecision,
providerOverloaded: providerFailure?.errorCode === "native_provider_overloaded" && ownsProviderFailureDecision,
@@ -15147,10 +15147,12 @@ describe("native warm session supervision", () => {
async ({ name, firstEnvironment = {}, secondEnvironment = {}, refreshTools, unsupportedRefresh = false,
managedGitHub = false, reuse, adoptionReuse = reuse }) => {
const decisions: Record<string, boolean> = {};
for (const path of ["warm", "adoption", ...(refreshTools ? ["portable", "portable-bootstrap", "legacy-plugin"] as const : [])] as const) {
for (const path of ["warm", "adoption", ...(refreshTools ? ["portable", "portable-bootstrap", "legacy-plugin"] as const : []),
...(refreshTools && !unsupportedRefresh ? ["released-unavailable"] as const : [])] as const) {
const portable = path === "portable" || path === "portable-bootstrap";
const bootstrap = path === "portable-bootstrap";
const pluginRecovery = portable || path === "legacy-plugin";
const releasedUnavailable = path === "released-unavailable";
const pluginRecovery = portable || path === "legacy-plugin" || releasedUnavailable;
githubAccess.create.mockReset().mockImplementation(async () => ({ env: {}, ready: true, duplexRequested: false,
activate: githubAccess.activate.mockReset().mockImplementation(() => vi.fn()), stop: githubAccess.stop.mockReset().mockResolvedValue(undefined) }));
const stateBase = await mkdtemp(join(tmpdir(), "paperclip-runnerd-reuse-key-"));
@@ -15228,7 +15230,7 @@ describe("native warm session supervision", () => {
const projection = vi.spyOn(controllerRecovery, "resolveNativeControllerRecovery").mockResolvedValue({ kind: "no_prior_execution" });
const restore = path === "legacy-plugin" ? vi.spyOn(runnerCheckpoint, "restoreNativeRunnerCheckpoint")
.mockImplementation(async (_db, binding) => binding.runId === first.binding.runId && recoveredSession.close.mock.calls.length ? {} as never : null) : undefined;
const issueProjection = path === "legacy-plugin" ? vi.spyOn(issueServiceModule, "issueService")
const issueProjection = path === "legacy-plugin" || releasedUnavailable ? vi.spyOn(issueServiceModule, "issueService")
.mockReturnValue({ update: vi.fn(async () => null) } as never) : undefined;
try {
await executePaperclipNativeSession({ db: leaseDb(first), execution: first, runnerInstanceId: "runner-reuse-key",
@@ -15261,14 +15263,26 @@ describe("native warm session supervision", () => {
});
}
if (pluginRecovery) state.createBackend.mockReturnValueOnce({
kind: "test", recoverSession: async () => ({ recovered: true, session: recoveredSession }),
kind: "test", recoverSession: async () => {
if (releasedUnavailable) throw new Error("native_runner_reuse_unavailable");
return { recovered: true, session: recoveredSession };
},
} as never);
const createOwner = pluginTaskRuntime.createPluginRunnerTaskOwner;
const owners = releasedUnavailable ? vi.spyOn(pluginTaskRuntime, "createPluginRunnerTaskOwner")
.mockImplementation(ownerInput => Object.assign(createOwner(ownerInput), { retiredBeforeClaim: () => true })) : undefined;
const resumeFrom = releasedUnavailable ? vi.spyOn(environmentTaskRuntime, "resolvePluginTaskResume").mockResolvedValue("target-task") : undefined;
const pluginTaskDescription = { kind: "description", taskId: "target-task", warmTaskVersion: 1,
launchPreparationVersion: 1, projectAuthCheckVersion: 1, releaseResumeVersion: 1,
...(releasedUnavailable ? { executionContextVersion: 1 as const } : {}),
runner: { version: "fixture", digest: `sha256:${"a".repeat(64)}` } } as const;
const portableTarget = { ...target, runner: undefined, leaseId: "target-lease",
sandboxLeaseAcquisition: { outcome: path === "legacy-plugin" ? "resumed" : "created", providerLeaseId: "target-task" },
runnerTask: vi.fn(async (operation: { kind: string }) => {
sandboxLeaseAcquisition: { outcome: path === "legacy-plugin" || releasedUnavailable ? "resumed" : "created", providerLeaseId: "target-task" },
runnerTask: vi.fn(async (operation: { kind: string }, options?: { executionContext?: unknown }) => {
if (releasedUnavailable && operation.kind === "describe") {
if (options?.executionContext) throw new Error("fixture replacement bound to the old task context");
return { ...pluginTaskDescription, taskId: "fresh-task" };
}
if (path === "legacy-plugin") {
expect(recoveredSession.close).toHaveBeenCalledOnce();
expect(operation.kind).toBe("describe");
@@ -15313,6 +15327,16 @@ describe("native warm session supervision", () => {
expect(portableTarget.runnerTask).toHaveBeenCalledOnce();
continue;
}
if (releasedUnavailable) {
try {
await continuation;
delete decisions[path];
expect(portableTarget.runnerTask.mock.calls.map(([operation]) => operation.kind)).toContain("describe");
expect(state.execute).toHaveBeenCalledTimes(2);
expect(recoveredSession.close).not.toHaveBeenCalled();
} finally { owners?.mockRestore(); resumeFrom?.mockRestore(); }
continue;
}
if (path === "adoption") await expect(continuation).rejects.toThrow("fixture adoption decision recorded");
else await continuation;
expect(decisions[path]).toBe(portable ? true : path === "adoption" ? adoptionReuse : reuse);
@@ -19613,12 +19637,12 @@ describe("runnerd provider runtime wiring", () => {
});
it.each((["codex", "claude"] as const).flatMap(provider => [
...[[false, false, false, false], [true, false, false, false], [false, true, false, false], [false, false, true, false], ...(provider === "codex" ? [[false, false, false, true]] : [])]
.map(([unknown, shutdown, journalFailure, deadline]) => [provider, unknown, shutdown, journalFailure, deadline, "idle timeout"] as const),
...[[false, false, false], [true, false, false], [false, true, false], ...(provider === "codex" ? [[false, false, true]] : [])]
.map(([unknown, shutdown, deadline]) => [provider, unknown, shutdown, deadline, "idle timeout"] as const),
...(["controller restart", "detach failure", "environment deletion", "replacement hand-off"] as const)
.map(retirement => [provider, false, false, false, false, retirement] as const),
.map(retirement => [provider, false, false, false, retirement] as const),
]))(
"releases settled %s only under its current owner and retires its cache (unknown=%s, shutdown=%s, journalFailure=%s, deadline=%s, retirement=%s)", async (provider, unknown, shutdown, journalFailure, deadline, retirement) => {
"releases settled %s only under its current owner and retires its cache (unknown=%s, shutdown=%s, deadline=%s, retirement=%s)", async (provider, unknown, shutdown, deadline, retirement) => {
await closeIdleWarmNativeSessionsForRestart();
expect(readNativeSessionIdleWork()).toBe("none");
const previousHome = process.env.PAPERCLIP_HOME;
@@ -19654,7 +19678,7 @@ describe("runnerd provider runtime wiring", () => {
});
let allowPhysicalStop!: () => void;
const physicalStop = new Promise<void>(resolve => { allowPhysicalStop = resolve; });
const close = vi.fn(async () => { if (shutdown || deadline || journalFailure) await physicalStop; }), detachControllerForRestart = vi.fn(async () => {});
const close = vi.fn(async () => { if (shutdown || deadline) await physicalStop; }), detachControllerForRestart = vi.fn(async () => {});
const session = { release, close, detachControllerForRestart };
const validated = validatePrpStructuredRunResult({ schema: "paperclip.run_result.v1", reportedWorkDisposition: "done",
summary: "Completed", completionClaim: { contractRevision: current.completionContract.contract.revision,
@@ -19683,7 +19707,7 @@ describe("runnerd provider runtime wiring", () => {
runnerInstanceId: source.runnerInstanceId, useRunnerd: true, runnerIngressAuthorized: true,
runnerExecutionTarget: { ...target, runnerTask: nextTask } })).rejects.toThrow("native_session_supervisor_busy");
expect(nextTask).not.toHaveBeenCalled();
if (provider === "codex" && !unknown && !shutdown && !journalFailure && !deadline) {
if (provider === "codex" && !unknown && !shutdown && !deadline) {
await expect(executePaperclipNativeSession({ db: leaseDb(next), execution: next,
runnerInstanceId: source.runnerInstanceId, useRunnerd: true, runnerIngressAuthorized: true,
runnerExecutionTarget: { ...target, environmentId: "competing-environment", runnerTask: nextTask,
@@ -19714,33 +19738,6 @@ describe("runnerd provider runtime wiring", () => {
expect(JSON.parse(await readFile(join(directory, (await readdir(directory))[0]!), "utf8")).releasedRunner).toBeUndefined();
return;
}
if (journalFailure) {
const directory = join(resolvePaperclipInstanceRoot(), "runtime/paperclip-runner/sessions");
const path = join(directory, (await readdir(directory))[0]!);
await rename(path, `${path}.saved`);
await mkdir(path);
let finished = false;
void execute.finally(() => { finished = true; }).catch(() => undefined);
allowRelease();
await new Promise(resolve => setImmediate(resolve));
expect(finished).toBe(false);
await expect(executePaperclipNativeSession({ db: leaseDb(next), execution: next,
runnerInstanceId: source.runnerInstanceId, useRunnerd: true, runnerIngressAuthorized: true,
managedAiCredentialHome: home, managedAiCredentialIdentity: "selected-revision", managedAiAccountIdentity: "selected-account",
runnerExecutionTarget: { ...target, remoteCwd: "different-workspace", runnerTask: nextTask } })).rejects.toThrow("native_session_supervisor_busy");
expect(nextTask).not.toHaveBeenCalled();
await vi.waitFor(() => expect(close).toHaveBeenCalledOnce());
expect(readNativeSessionIdleWork()).toBe("present");
expect(finished).toBe(false);
await rm(path, { recursive: true });
await rename(`${path}.saved`, path);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined();
allowPhysicalStop();
await expect(execute).resolves.toMatchObject({ sessionId: source.normalizedSessionId });
expect(readNativeSessionIdleWork()).toBe("none");
expect(detachControllerForRestart).not.toHaveBeenCalled();
return;
}
allowRelease();
await expect(execute).resolves.toMatchObject({ sessionId: source.normalizedSessionId });
expect(readNativeSessionIdleWork()).toBe("none");
@@ -19748,21 +19745,20 @@ describe("runnerd provider runtime wiring", () => {
const files = await readdir(directory);
const path = join(directory, files[0]!);
const envelope = JSON.parse(await readFile(path, "utf8"));
expect(envelope.releasedRunner).toMatchObject({ source, taskId: "retained-task", scopeDigest: expect.any(String) });
expect(envelope.releasedRunner).toBeUndefined();
expect(JSON.stringify(envelope)).not.toContain("synthetic-fixture");
if (!unknown) {
const calls = owners.mock.calls.length;
for (const changed of [{ remoteCwd: "different-workspace" }, { runnerTaskProjectIds: ["different-project"] }]) {
await expect(executePaperclipNativeSession({ db: leaseDb(next), execution: next,
runnerInstanceId: source.runnerInstanceId, useRunnerd: true, runnerIngressAuthorized: true,
managedAiCredentialHome: home, managedAiCredentialIdentity: "selected-revision", managedAiAccountIdentity: "selected-account",
runnerExecutionTarget: { ...target, ...changed, runnerTask: nextTask },
runnerEnvironment: provider === "claude" ? { ANTHROPIC_API_KEY: "synthetic-fixture" } : {} })).rejects.toThrow("released_owner_scope_mismatch");
}
await expect(executePaperclipNativeSession({ db: leaseDb(next), execution: next,
runnerInstanceId: source.runnerInstanceId, useRunnerd: true, runnerIngressAuthorized: true,
managedAiCredentialHome: home, managedAiCredentialIdentity: "selected-revision", managedAiAccountIdentity: "selected-account",
runnerExecutionTarget: { ...target, runnerTask: nextTask,
sandboxLeaseAcquisition: { ...target.sandboxLeaseAcquisition, providerLeaseId: "different-task" } },
runnerEnvironment: provider === "claude" ? { ANTHROPIC_API_KEY: "synthetic-fixture" } : {} })).rejects.toThrow("released_owner_scope_mismatch");
expect(owners).toHaveBeenCalledTimes(calls);
expect(nextTask).not.toHaveBeenCalled();
expect(state.execute).toHaveBeenCalledTimes(1);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toEqual(envelope.releasedRunner);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined();
}
if (retirement === "environment deletion") {
expect(await closeWarmNativeSessionsForEnvironment({ environmentId: target.environmentId, reason: "environment deleted" }))
@@ -19777,7 +19773,7 @@ describe("runnerd provider runtime wiring", () => {
expect(await closeIdleWarmNativeSessionsForRestart()).toMatchObject({ closed: 0, busy: 0, failed: 1 });
expect(close).not.toHaveBeenCalled();
expect(readNativeSessionIdleWork()).toBe("present");
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toEqual(envelope.releasedRunner);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined();
}
detachControllerForRestart.mockResolvedValue(undefined);
}
@@ -19788,7 +19784,7 @@ describe("runnerd provider runtime wiring", () => {
expect(readNativeSessionIdleWork()).toBe("none");
expect(close).not.toHaveBeenCalled();
expect(task.mock.calls.map(([operation]) => (operation as { kind: string }).kind)).toEqual(["describe"]);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toEqual(envelope.releasedRunner);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined();
if (provider === "codex" && !unknown) {
const inspected = vi.spyOn(remoteWarmRecoveryRuntime, "inspectRemoteWarmSessionRecovery").mockImplementation(async request => {
request.loadCheckpoint(current);
@@ -19805,18 +19801,15 @@ describe("runnerd provider runtime wiring", () => {
{ runnerExecutionTarget: { ...target, runnerTaskProjectIds: ["different-project"] } },
{ runnerExecutionTarget: { ...target, remoteCwd: "different-workspace" } },
{ runnerExecutionTarget: { ...target, sandboxLeaseAcquisition: { ...target.sandboxLeaseAcquisition, providerLeaseId: "different-task" } } },
]) await expect(executePaperclipNativeSession({ ...base, ...changed })).rejects.toThrow("released_owner_scope_mismatch");
]) await expect(executePaperclipNativeSession({ ...base, ...changed })).rejects.toThrow("fixture completed-source proof checked");
await writeFile(path, JSON.stringify({ ...envelope,
releasedRunner: { source, taskId: "retained-task", scopeDigest: `sha256:${"0".repeat(64)}` } }));
await expect(executePaperclipNativeSession(base)).rejects.toThrow("fixture completed-source proof checked");
expect(inspected.mock.calls.at(-1)![0].loadCheckpoint(current)).toMatchObject({ identity: envelope.snapshot.identity });
expect(owners).toHaveBeenCalledTimes(calls);
expect(state.execute).toHaveBeenCalledTimes(1);
} finally { inspected.mockRestore(); }
}
await owners.mock.calls.at(-1)![0].onResumed!(source);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined();
const replacement = { ...envelope, snapshot: { ...envelope.snapshot, identity: { ...envelope.snapshot.identity, runId: "new-owner" } },
releasedRunner: { ...envelope.releasedRunner, source: { ...source, runId: "new-owner" } } };
await writeFile(path, JSON.stringify(replacement));
await expect(owners.mock.calls.at(-1)![0].onResumed!(source)).rejects.toThrow("released_source_mismatch");
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toEqual(replacement.releasedRunner);
} finally {
detachControllerForRestart.mockResolvedValue(undefined);
registerRunStartHandover(null);
@@ -19827,7 +19820,7 @@ describe("runnerd provider runtime wiring", () => {
it.each((["codex", "claude"] as const).flatMap(provider => (["current", "stale", ...(provider === "codex" ? ["foreign runner", "foreign lease"] : [])] as const)
.map(receipt => [provider, receipt] as const)))(
"records the confirmed %s source after external checkpoint registration and attachment (receipt=%s)", async (provider, receipt) => {
"accepts only the attached %s source's release receipt after external checkpoint registration (receipt=%s)", async (provider, receipt) => {
const invalidReceipt = receipt !== "current";
await closeIdleWarmNativeSessionsForRestart();
const previousHome = process.env.PAPERCLIP_HOME;
@@ -19899,7 +19892,6 @@ describe("runnerd provider runtime wiring", () => {
.toBe("paperclip.runner.external-control-plane-state.v1");
} else {
expect(options.existingSession).toBe(session);
await owners.mock.calls[0]![0].onResumed!(source);
authority.rotateRunIdentity(successor);
await register!(authority, successor);
await writeFile(join(root, "runner/runner-state.json"), JSON.stringify(durableRunnerState(successor, "ready")));
@@ -19931,7 +19923,7 @@ describe("runnerd provider runtime wiring", () => {
expect(release).toHaveBeenCalledOnce();
const directory = join(resolvePaperclipInstanceRoot(), "runtime/paperclip-runner/sessions");
const path = join(directory, (await readdir(directory))[0]!);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner.source).toEqual(source);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined();
following = run(next);
void following.catch(() => undefined);
if (invalidReceipt) {
@@ -19944,7 +19936,7 @@ describe("runnerd provider runtime wiring", () => {
} else {
await expect(following).resolves.toMatchObject({ sessionId: source.normalizedSessionId });
expect(release).toHaveBeenCalledTimes(2);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner.source).toEqual(successor);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined();
expect(close).not.toHaveBeenCalled();
}
} finally {
@@ -337,6 +337,7 @@ import {
type NativeStatusDecision,
} from "./status-arbiter.js";
import { conflict, HttpError } from "../../errors.js";
import { planReviewConfirmationInput } from "./native-plan-review-card.js";
import { redactSensitiveText } from "../../redaction.js";
import { classifyRemoteConnectionError } from "../remote-connection-failure.js";
import { resolvePaperclipRunnerBinary, resolvePaperclipRunnerBinaryAsync, resolveRemotePaperclipRunnerBinary, verifiedBundledRemoteRunnerBinary } from "./native-codex-runner.js";
@@ -2324,33 +2325,15 @@ export async function synchronizeCompletedProviderPlan(input: {
id: input.execution.binding.issueId,
companyId: input.execution.binding.companyId,
},
{
kind: "request_confirmation",
idempotencyKey: `runner-plan-approval:v1:${input.execution.binding.runId}:${planId}:${providerRevision}:${digest}`,
planReviewConfirmationInput({
issueId: input.execution.binding.issueId,
documentId: current.id,
revisionId: revision.id,
revisionNumber: revision.revisionNumber,
sourceRunId: input.execution.binding.runId,
title: `Review plan revision ${revision.revisionNumber}`,
summary: "Review the synchronized Paperclip plan.",
continuationPolicy: "wake_assignee",
payload: {
version: 1,
prompt: `Approve plan revision ${revision.revisionNumber}?`,
detailsMarkdown:
"The completed provider plan has been synchronized to the canonical Plan document.",
acceptLabel: "Approve plan",
rejectLabel: "Request changes",
rejectRequiresReason: true,
supersedeOnUserComment: false,
target: {
type: "issue_document",
issueId: input.execution.binding.issueId,
documentId: current.id,
key: "plan",
revisionId: revision.id,
revisionNumber: revision.revisionNumber,
label: `Plan v${revision.revisionNumber}`,
},
},
} as never,
source: "provider_plan",
idempotencyKey: `runner-plan-approval:v1:${input.execution.binding.runId}:${planId}:${providerRevision}:${digest}`,
}) as never,
{
agentId: input.execution.binding.agentId,
runId: input.execution.binding.runId,
@@ -8796,49 +8779,23 @@ function legacyNativeSessionCheckpointPath(
);
}
type ReleasedWarmRunner = { source: DurableRecoveryIdentity; taskId: string; scopeDigest: string };
const RELEASED_SOURCE_KEYS = ["runnerInstanceId", "environmentLeaseId", "runId", "normalizedSessionId", "turnId", "itemId"] as const;
function releasedWarmScope(input: Parameters<typeof executePaperclipNativeSession>[0]): string {
const target = input.runnerExecutionTarget;
return nativeSha256({ companyId: input.execution.binding.companyId, agentId: input.execution.binding.agentId,
environmentId: target?.kind === "remote" ? target.environmentId ?? null : null, workspace: nativeSessionWorkspaceScope(input.execution),
cwd: input.execution.workspace.cwd, remoteCwd: target?.kind === "remote" ? target.remoteCwd : null,
projectIds: target?.kind === "remote" && target.transport === "sandbox" ? target.runnerTaskProjectIds ?? [] : [],
accountIdentity: input.managedAiAccountIdentity ?? null, credentialIdentity: input.managedAiCredentialIdentity ?? null });
function releasedDurableIdentity(identity: Record<string, unknown> | null): DurableRecoveryIdentity | undefined {
if (!identity || RELEASED_SOURCE_KEYS.some(key => typeof identity[key] !== "string" || !identity[key])) return undefined;
const field = (key: typeof RELEASED_SOURCE_KEYS[number]) => identity[key] as string;
return { runnerInstanceId: field("runnerInstanceId"), environmentLeaseId: field("environmentLeaseId"), runId: field("runId"),
normalizedSessionId: field("normalizedSessionId"), turnId: field("turnId"), itemId: field("itemId") };
}
function requireReleasedWarmScope(input: Parameters<typeof executePaperclipNativeSession>[0],
proof: ReleasedWarmRunner | undefined, identity: unknown): DurableRecoveryIdentity {
function releasedWarmSource(input: Parameters<typeof executePaperclipNativeSession>[0], taskId: string | null): DurableRecoveryIdentity {
const target = input.runnerExecutionTarget;
if (!proof || target?.kind !== "remote" || target.transport !== "sandbox" || !target.runnerTask
|| proof.taskId !== target.sandboxLeaseAcquisition?.providerLeaseId
|| proof.scopeDigest !== releasedWarmScope(input) || canonicalJson(proof.source) !== canonicalJson(identity)) {
const source = releasedDurableIdentity(readRunnerdDurableIdentity(scopedRunnerdStateRoot(input.execution)));
if (!source || target?.kind !== "remote" || target.transport !== "sandbox" || !target.runnerTask
|| taskId !== target.sandboxLeaseAcquisition?.providerLeaseId) {
throw new Error("native_session_released_owner_scope_mismatch");
}
return proof.source;
}
function readWarmNativeEnvelope(execution: NativeExecutionInput): Record<string, unknown> | null {
const path = nativeSessionCheckpointPath(execution);
if (!existsSync(path)) return null;
const envelope = record(JSON.parse(readBoundedNativeFile(path, NATIVE_WARM_CHECKPOINT_MAX_BYTES,
"native_session_supervisor_checkpoint_too_large").toString("utf8")));
if (envelope.schema !== "paperclip.native-session-supervisor.v1") throw new Error("native_session_supervisor_checkpoint_mismatch");
return envelope;
}
function releasedWarmRunner(envelope: Record<string, unknown> | null): ReleasedWarmRunner | undefined {
if (!envelope || envelope.releasedRunner === undefined) return undefined;
const proof = record(envelope.releasedRunner), source = record(proof.source);
const snapshot = record(envelope.snapshot), identity = record(snapshot.identity);
for (const key of ["runnerInstanceId", "environmentLeaseId", "runId", "normalizedSessionId", "turnId", "itemId"]) {
if (typeof source[key] !== "string" || !source[key]) throw new Error("native_session_released_source_mismatch");
}
if (typeof proof.taskId !== "string" || !proof.taskId || typeof proof.scopeDigest !== "string"
|| identity.runId !== source.runId || identity.sessionId !== source.normalizedSessionId) {
throw new Error("native_session_released_source_mismatch");
}
return proof as ReleasedWarmRunner;
return source;
}
function writeWarmNativeEnvelope(execution: NativeExecutionInput, envelope: Record<string, unknown>): void {
@@ -8849,38 +8806,15 @@ function writeWarmNativeEnvelope(execution: NativeExecutionInput, envelope: Reco
chmodSync(path, 0o600);
}
function updateReleasedWarmRunner(execution: NativeExecutionInput, source: DurableRecoveryIdentity,
taskId: string, proof: ReleasedWarmRunner | null): void {
const envelope = readWarmNativeEnvelope(execution);
const previous = releasedWarmRunner(envelope);
if (!envelope) {
if (proof) throw new Error("native_session_supervisor_checkpoint_missing");
return;
}
if (!proof && !previous) return;
const identity = record(record(envelope.snapshot).identity);
if (identity.companyId !== execution.binding.companyId || identity.agentId !== execution.binding.agentId
|| identity.runId !== source.runId || identity.sessionId !== source.normalizedSessionId
|| (previous && (previous.taskId !== taskId || canonicalJson(previous.source) !== canonicalJson(source)))) {
throw new Error("native_session_released_source_mismatch");
}
if (proof) envelope.releasedRunner = proof;
else delete envelope.releasedRunner;
writeWarmNativeEnvelope(execution, envelope);
}
function persistWarmNativeCheckpoint(
execution: NativeExecutionInput,
configDigest: string,
snapshot: PersistedNativeSession,
processConfigDigest?: string,
): void {
const previous = releasedWarmRunner(readWarmNativeEnvelope(execution));
writeWarmNativeEnvelope(execution, {
schema: "paperclip.native-session-supervisor.v1", configDigest, processConfigDigest,
updatedAt: new Date().toISOString(), snapshot,
...(previous && previous.source.runId === snapshot.identity.runId
&& previous.source.normalizedSessionId === snapshot.identity.sessionId ? { releasedRunner: previous } : {}),
});
}
@@ -11252,10 +11186,11 @@ async function executePaperclipNativeSessionAttempt(
}
const cachedReleasedOwner = warmNativeSessions.get(nativeSessionScopeKey(input.execution));
if (cachedReleasedOwner?.released) {
const proof = portableSource ? undefined : releasedWarmRunner(readWarmNativeEnvelope(input.execution));
const identity = readRunnerdDurableIdentity(scopedRunnerdStateRoot(input.execution));
const durable = portableSource ? undefined : releasedDurableIdentity(identity);
const target = input.runnerExecutionTarget;
const source = portableSource ?? (proof && { taskId: proof.taskId, identity: proof.source });
const source = portableSource ?? (durable && cachedReleasedOwner.pluginTaskId
? { taskId: cachedReleasedOwner.pluginTaskId, identity: durable } : undefined);
if (source && target?.kind === "remote" && target.transport === "sandbox" && target.runnerTask && target.leaseId
&& (portableSource || target.sandboxLeaseAcquisition?.outcome === "created")
&& source.taskId !== target.sandboxLeaseAcquisition?.providerLeaseId) {
@@ -11265,8 +11200,7 @@ async function executePaperclipNativeSessionAttempt(
|| cachedReleasedOwner.preparingRunId && cachedReleasedOwner.preparingRunId !== input.execution.binding.runId
|| cachedReleasedOwner.instructionPreparationRunId && !ownInstructionPreparation
|| cachedReleasedOwner.closeOnReleaseReason) throw new Error("native_session_supervisor_busy");
if (source.taskId !== cachedReleasedOwner.pluginTaskId || cachedReleasedOwner.runId !== identity?.runId ||
(proof && (proof.scopeDigest !== releasedWarmScope(input) || canonicalJson(proof.source) !== canonicalJson(identity)))) {
if (source.taskId !== cachedReleasedOwner.pluginTaskId || cachedReleasedOwner.runId !== identity?.runId) {
throw new Error("native_session_released_owner_scope_mismatch");
}
const wasBusy = cachedReleasedOwner.busy;
@@ -11284,7 +11218,7 @@ async function executePaperclipNativeSessionAttempt(
}
forgetWarmNativeSession(nativeSessionScopeKey(input.execution), cachedReleasedOwner);
} finally { cachedReleasedOwner.busy = wasBusy; }
} else requireReleasedWarmScope(input, proof, identity);
} else releasedWarmSource(input, cachedReleasedOwner.pluginTaskId ?? null);
}
if (input.useRunnerd && canRecoverWarmOwner && !input.backend &&
input.runnerExecutionTarget?.kind === "remote" &&
@@ -11320,7 +11254,6 @@ async function executePaperclipNativeSessionAttempt(
}
if (durableIdentityMatchesSession(identity, input.execution) && identity.runId !== input.execution.binding.runId &&
runnerdAuthorityLifecycleWithVerifiedBackup({ root, identity, execution: input.execution, allowVerifiedBackup: true }) !== "suspended") {
let releasedSource = portableSource?.identity;
remoteWarmRecovery = await inspectRemoteWarmSessionRecovery({
db: input.db, execution: input.execution, target: input.runnerExecutionTarget, identity,
portableSourceTaskId: portableSource?.taskId,
@@ -11328,19 +11261,15 @@ async function executePaperclipNativeSessionAttempt(
resolve(root, "control-plane", "control-plane-state.json"), NATIVE_CONTROL_PLANE_STATE_MAX_BYTES,
"runner_durable_identity_too_large").toString("utf8"))),
matchesExecution: previous => matchesRemoteWarmExecution(previous, input.execution, input.toolRefreshOnResume),
loadCheckpoint: previous => {
if (!portableSource) {
const proof = releasedWarmRunner(readWarmNativeEnvelope(previous));
if (proof) releasedSource = requireReleasedWarmScope(input, proof, identity);
}
return loadWarmNativeCheckpoint(previous, nativeSessionConfigDigest(previous, "remote"), "remote");
},
loadCheckpoint: previous => loadWarmNativeCheckpoint(previous, nativeSessionConfigDigest(previous, "remote"), "remote"),
canReuseProcess: previous => !portableSource && !needsCoreGitHubAccess(input) &&
nativeSessionConfigDigest(previous, "remote") === nativeSessionConfigDigest(input.execution, "remote") && canReuseNativeProcess(input,
record(JSON.parse(readBoundedNativeFile(nativeSessionCheckpointPath(previous),
NATIVE_WARM_CHECKPOINT_MAX_BYTES, "native_session_supervisor_checkpoint_too_large").toString("utf8"))).processConfigDigest),
}) ?? undefined;
if (remoteWarmRecovery) {
const releasedSource = portableSource?.identity
?? (pluginTaskDescription?.releaseResumeVersion === 1 ? releasedDurableIdentity(identity) : undefined);
remoteWarmRecovery.releasedSource = releasedSource;
if (releasedSource) {
const header = await loadNativeRunnerCheckpointHeader(input.db, remoteWarmRecovery.previousExecution.binding).catch((error: unknown) => {
@@ -12318,6 +12247,7 @@ async function executePaperclipNativeSessionAttempt(
let reusingReleasedRunner = false;
let relaunchReleased: { owner?: ReturnType<typeof createPluginRunnerTaskOwner>; source: DurableRecoveryIdentity;
runner: { version: string; digest: string }; published?: true } | undefined;
let releasedRecoveryOwner: ReturnType<typeof createPluginRunnerTaskOwner> | undefined;
let managedCredentialSession: NativeSession | undefined;
let githubAccess: NativeGitHubAccess | undefined;
let releaseGitHubRun: (() => void) | undefined;
@@ -12340,8 +12270,7 @@ async function executePaperclipNativeSessionAttempt(
const registered = warmNativeSessions.get(warmSessionId);
const entry = registered && forgetUnretiredOwnerOnOtherSandbox(warmSessionId, registered, input.runnerExecutionTarget)
? undefined : registered;
const releasedSource = entry?.released ? requireReleasedWarmScope(input, releasedWarmRunner(readWarmNativeEnvelope(input.execution)),
readRunnerdDurableIdentity(scopedRunnerdStateRoot(input.execution))) : undefined;
const releasedSource = entry?.released ? releasedWarmSource(input, entry.pluginTaskId ?? null) : undefined;
if (entry || remoteWarmRecovery?.releasedSource) {
if (input.execution.provider.kind === "codex" ||
(input.execution.provider.kind === "acpx" && input.execution.provider.agent === "claude")) {
@@ -12644,7 +12573,10 @@ async function executePaperclipNativeSessionAttempt(
pluginTaskDescription,
retainedPluginTaskOwner: existingWarmSession ? pluginTaskSessionOwners.get(existingWarmSession) : relaunchReleased?.owner,
relaunchReleased: relaunchReleased ? { source: relaunchReleased.source, runner: relaunchReleased.runner } : undefined,
onPluginTaskOwner: owner => { if (relaunchReleased && !relaunchReleased.owner) relaunchReleased.owner = owner; },
onPluginTaskOwner: owner => {
if (relaunchReleased && !relaunchReleased.owner) relaunchReleased.owner = owner;
else if (remoteWarmRecovery?.releasedSource && !releasedRecoveryOwner) releasedRecoveryOwner = owner;
},
beginRetainedRunAttachment: existingWarmSession && reusingReleasedRunner ? beginRetainedRunAttachment(existingWarmSession) : undefined,
durableEnvironmentLeaseId: durableRunnerBinding?.environmentLeaseId,
remoteWarmRecovery: remoteWarmRecovery ? (recovery => ({
@@ -12678,13 +12610,22 @@ async function executePaperclipNativeSessionAttempt(
input.useRunnerd && input.backend === undefined
? await timeController("backend_setup", () => executionContext ? executionContext.wait(createExecutionBackend) : createExecutionBackend())
: null;
let releasedRecoveryUnavailable: Error | undefined;
let recovered: Awaited<ReturnType<NonNullable<NonNullable<typeof runnerdBackend>["recoverSession"]>>> | undefined;
if (remoteWarmRecovery) {
const recovery = remoteWarmRecovery;
if (executionContext) await executionContext.wait(() => recovery.revalidate(leaseOwner));
else await recovery.revalidate(leaseOwner);
const recovered = await runnerdBackend?.recoverSession?.(remoteWarmRecovery.checkpoint, {
signal: executionContext?.signal ?? new AbortController().signal,
});
try {
recovered = await runnerdBackend?.recoverSession?.(remoteWarmRecovery.checkpoint, {
signal: executionContext?.signal ?? new AbortController().signal,
});
} catch (error) {
if (!recovery.releasedSource || !(error instanceof Error) || error.message !== "native_runner_reuse_unavailable") throw error;
releasedRecoveryUnavailable = error;
}
}
if (remoteWarmRecovery && !releasedRecoveryUnavailable) {
if (!recovered?.recovered || !recovered.session) throw new Error("runner_state_identity_mismatch: remote_warm_session_unproven");
const movedSession = remoteWarmRecovery.portableSourceTaskId !== undefined;
// A portable resume already starts a new Runner. Its run attachment
@@ -12733,12 +12674,14 @@ async function executePaperclipNativeSessionAttempt(
)).then(rows => rows[0])
: null;
let remoteCleanupLease = await readRemoteCleanupLease();
const continueAfterUnavailableReuse = async (error: unknown) => {
const continueAfterUnavailableReuse = async (error: unknown, recovering = false) => {
const target = input.runnerExecutionTarget;
const retainedOwner = existingWarmSession ? pluginTaskSessionOwners.get(existingWarmSession) : relaunchReleased?.owner;
const releasedRecovery = recovering && remoteWarmRecovery?.releasedSource ? remoteWarmRecovery : undefined;
const retainedOwner = existingWarmSession ? pluginTaskSessionOwners.get(existingWarmSession)
: relaunchReleased?.owner ?? (releasedRecovery ? releasedRecoveryOwner : undefined);
if (!(error instanceof Error) || error.message !== "native_runner_reuse_unavailable" || !retainedOwner
|| retainedOwner.retiredBeforeClaim() !== true
|| remoteWarmRecovery || warmConfigDigest === null || target?.kind !== "remote" || target.transport !== "sandbox"
|| (remoteWarmRecovery && !releasedRecovery) || warmConfigDigest === null || target?.kind !== "remote" || target.transport !== "sandbox"
|| !target.runnerTask || runnerdBackend === null) return false;
const retainedTaskId = target.sandboxLeaseAcquisition?.providerLeaseId;
if (existingWarmSession) await existingWarmSession.close({ reason: "retained Runner was unavailable for reuse" });
@@ -12750,6 +12693,16 @@ async function executePaperclipNativeSessionAttempt(
}
}
relaunchReleased = undefined;
if (releasedRecovery) {
if (remoteWarmRecoveryPending) {
if (executionContext) await executionContext.wait(() => releasedRecovery.revalidate(leaseOwner));
else await releasedRecovery.revalidate(leaseOwner);
}
remoteWarmRecovery = undefined;
remoteWarmRecoveryPending = false;
releasedRecoveryOwner = undefined;
await finishStartupContextForFallback();
}
const inspect = () => target.runnerTask!({ kind: "describe" }, executionContext ? { executionContext } : undefined);
const description = environmentTaskResultSchema.parse(await (executionContext ? executionContext.wait(inspect) : inspect()));
if (description.kind !== "description" || description.taskId === retainedTaskId) return false;
@@ -12761,6 +12714,7 @@ async function executePaperclipNativeSessionAttempt(
remoteCleanupLease = await readRemoteCleanupLease();
return true;
};
if (releasedRecoveryUnavailable && !await continueAfterUnavailableReuse(releasedRecoveryUnavailable, true)) throw releasedRecoveryUnavailable;
const portTarget = input.runnerExecutionTarget;
if (input.useRunnerd && !input.backend && !existingWarmSession && portTarget?.kind === "remote" && portTarget.transport === "sandbox"
&& portTarget.runner && !portTarget.runnerTask && portTarget.sandboxLeaseAcquisition?.outcome === "resumed"
@@ -14183,11 +14137,8 @@ async function executePaperclipNativeSessionAttempt(
|| entry.pluginTaskId !== target.sandboxLeaseAcquisition?.providerLeaseId) {
throw new Error("native_session_released_source_mismatch");
}
const source = operation.identity;
updateReleasedWarmRunner(input.execution, source, entry.pluginTaskId,
{ source, taskId: entry.pluginTaskId, scopeDigest: releasedWarmScope(input) });
} catch {
entry.closeOnReleaseReason = "released Runner source proof could not be verified or saved";
entry.closeOnReleaseReason = "released Runner source could not be verified";
await closeWarmNativeSession(entry, entry.closeOnReleaseReason);
forgetWarmNativeSession(scope, entry);
return;
@@ -17060,8 +17011,6 @@ async function createRunnerdBackendWithinSessionClaim(
releasedSource: input.remoteWarmRecovery?.releasedSource,
releasedSourceRunner: input.remoteWarmRecovery?.releasedSourceRunner,
sessionHandoff: !!input.remoteWarmRecovery?.portableSourceTaskId,
onResumed: async source => updateReleasedWarmRunner(input.execution, source, input.remoteWarmRecovery?.portableSourceTaskId ?? description.taskId, null),
onRetired: async source => updateReleasedWarmRunner(input.execution, source, description.taskId, null),
adoptIdentity: adoptionIdentity ?? (adopting && prior ? {
runnerInstanceId: prior.runnerInstanceId, environmentLeaseId: prior.environmentLeaseId,
runId: prior.runId, normalizedSessionId: prior.normalizedSessionId,
@@ -0,0 +1,51 @@
import { describe, expect, it } from "vitest";
import type { NativeEvidenceAssessment } from "./evidence-classifier.js";
import { arbitrateNativeStatus } from "./status-arbiter.js";
import { PLAN_NOT_PRODUCED_REASON } from "./plan-mode-status.js";
const yieldedWait: NativeEvidenceAssessment = {
objectiveClaimSatisfied: false, objectiveSatisfied: false, allCriteriaSatisfied: false, verificationPassed: false,
hasFailedVerification: false, hasBlockingRemainingWork: false, reportedDisposition: "yielded",
summary: "Waiting for plan review", contractRevisionMatches: true, criterionAssessments: [],
verificationAssessments: [], verificationCaveats: [], acceptedEvidenceRefs: [], missingRequirements: [],
rejectedEvidence: [], unverifiableEvidence: [], blocker: null,
continuation: { kind: "response_wake", summary: "Waiting for plan review", idempotencyKey: "plan-review-wake-v1" },
attentionRequests: [], ignoredAttentionRequests: [],
} as NativeEvidenceAssessment;
const arbitrate = (overrides: Partial<Parameters<typeof arbitrateNativeStatus>[0]>) => arbitrateNativeStatus({
assessment: yieldedWait, terminalState: "succeeded", workspaceFinalizeStatus: "succeeded",
agentId: "agent", priorIssueStatus: "in_progress", ...overrides,
});
// Every way a Plan-mode response wait can settle leaves the user one current
// action (the review card is the gate) or schedules the agent to produce one.
describe("Plan-mode response wait settlement", () => {
it.each([
{ name: "assigned run, plan card open", input: { governanceGate: { kind: "interaction" as const, id: "card" } },
reasonCode: "governed_response_waiting", next: "card" },
{ name: "comment-started run, plan card open", input: { governanceGate: { kind: "interaction" as const, id: "card" }, boardResponseWaitAuthorized: true, boardResponseWaitOrigin: true },
reasonCode: "governed_response_waiting", next: "card" },
{ name: "assigned run, no plan", input: { planNotProduced: true },
reasonCode: PLAN_NOT_PRODUCED_REASON, next: "continuation" },
{ name: "comment-started run, no plan", input: { planNotProduced: true, boardResponseWaitAuthorized: true, boardResponseWaitOrigin: true },
reasonCode: PLAN_NOT_PRODUCED_REASON, next: "continuation" },
{ name: "comment-started run whose comment was superseded, no plan", input: { planNotProduced: true, boardResponseWaitOrigin: true },
reasonCode: PLAN_NOT_PRODUCED_REASON, next: "continuation" },
{ name: "second miss after the continuation", input: { planNotProduced: true, allowIncompleteContinuation: false },
reasonCode: PLAN_NOT_PRODUCED_REASON, next: "recovery" },
])("$name", ({ input, reasonCode, next }) => {
const decision = arbitrate(input);
expect(decision.reasonCode).toBe(reasonCode);
const kinds = decision.effects.map(effect => effect.kind);
if (next === "card") expect(kinds).toContain("create_interaction");
if (next === "continuation") expect(kinds).toContain("enqueue_continuation");
if (next === "recovery") expect(kinds).toContain("record_finalization_error");
});
it("leaves Standard-mode and conversation waits unchanged", () => {
expect(arbitrate({}).reasonCode).toBe("response_wake_waiting_for_input");
expect(arbitrate({ boardResponseWaitAuthorized: true }).reasonCode).toBe("board_response_waiting");
expect(arbitrate({ planNotProduced: true, isConversation: true }).reasonCode).not.toBe(PLAN_NOT_PRODUCED_REASON);
});
});
@@ -0,0 +1,36 @@
import type { NativeAuthoritativeIssueStatus, NativeStatusDecision } from "./status-arbiter.js";
export const PLAN_NOT_PRODUCED_REASON = "plan_mode_plan_not_produced";
/**
* Plan mode waits only on a plan review. A Plan-mode run that yields a
* response wait with no plan to review (none saved, or the current revision
* already answered) must not rest as a silent wait. The agent is asked once to
* save its plan (its review card then opens); after that, the task keeps its
* status and shows a recovery step.
*/
export function planNotProducedDecision(input: {
priorIssueStatus: NativeAuthoritativeIssueStatus;
agentId: string;
allowIncompleteContinuation?: boolean;
}): Omit<NativeStatusDecision, "policyVersion"> {
if (input.allowIncompleteContinuation === false) {
return {
statusAction: "preserve", toStatus: input.priorIssueStatus,
reasonCode: PLAN_NOT_PRODUCED_REASON, unblockDescriptor: null,
effects: [{ kind: "record_finalization_error", cause: PLAN_NOT_PRODUCED_REASON,
nextAction: "The agent finished in Plan mode without a new plan to review. Ask it to write the plan, or switch the task out of Plan mode.",
agentId: input.agentId }],
};
}
return {
statusAction: "in_progress", toStatus: "in_progress",
reasonCode: PLAN_NOT_PRODUCED_REASON, unblockDescriptor: null,
effects: [{
kind: "enqueue_continuation", continuationKind: "same_agent",
summary: "This task is in Plan mode and there is no new plan to review. Save your plan (or the revised plan) to this task's Plan document; Paperclip then asks the user to approve it. If you need an answer first, ask a question instead of waiting.",
// The bounded incomplete-report key: a second miss gets the recovery step.
idempotencyKey: "native-completion-incomplete", agentId: input.agentId,
}],
};
}
@@ -311,7 +311,7 @@ describeEmbeddedPostgres("plugin Runner eviction through the Core execution entr
const a = await execute(execution, leaseA); expect(a).toMatchObject({ exitCode: 0, timedOut: false });
await waitForCondition("automatic release A", () => releases.length === 1);
expect((await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, runId)))[0]).toMatchObject({ schemaStatus: "accepted", resultJson: { result: { reportedWorkDisposition: "done" } } });
expect(await proof()).toMatchObject({ source: releases[0], taskId: taskA });
expect(await proof()).toBeUndefined();
const providerSessionId = (await supervisor()).snapshot.providerSessionId;
expect(providerSessionId).toEqual(expect.any(String));
if (detached) await new Promise(done => setTimeout(done, detachedIdleTimeoutMs + 200));
@@ -401,7 +401,7 @@ describeEmbeddedPostgres("plugin Runner eviction through the Core execution entr
const runB = await admitNext();
if (denied || mode === "bare unavailable") return;
await waitForCondition("automatic release B", () => releases.length === 2);
expect(await proof()).toMatchObject({ source: releases[1], taskId: taskB });
expect(await proof()).toBeUndefined();
expect((await supervisor()).snapshot.providerSessionId).toBe(providerSessionId);
const methods = (await readFile(calls, "utf8")).trim().split(/\r?\n/);
expect(submissions).toBe(2);
@@ -248,7 +248,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio
await waitForCondition("parked Runner stopped", () => handle!.isExitConfirmed?.() === true);
const identity = { ...operation.identity, ...operation.runner };
const archived = join(runnerRoot, `archived-${operation.identity.runId}.json`);
const archivedState = await state();
const parkedState = await state();
await rename(join(runnerRoot, "runner-state.json"), archived);
const launch = submittedLaunch!.launch!;
listenPath = `/api/runner/v1/connect/${identity.runId}`;
@@ -260,8 +260,8 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio
...(harness === "claude" ? { acpxLaunchProfile: { authorityDigest: `sha256:${sha("fixture authority")}`, command: sidecar,
commandSha256: `sha256:${sha(await readFile(sidecar, "utf8"))}`, sidecarScript,
sidecarScriptSha256: `sha256:${sha(await readFile(sidecarScript, "utf8"))}` } } : {}) });
relaunches.push({ source: operation.identity, runId: identity.runId, archivedRunId: archivedState.runId });
return { kind: "resume", taskId, outcome: "resumed", runner: artifact, archivedState };
relaunches.push({ source: operation.identity, runId: identity.runId, archivedRunId: parkedState.runId });
return { kind: "resume", taskId, outcome: "resumed", runner: artifact };
}
if (operation.kind === "resume") {
expect(relaunch).toBe(false);
@@ -310,7 +310,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio
const a = await execute(execution, leaseA); expect(a).toMatchObject({ exitCode: 0, timedOut: false });
await waitForCondition("automatic release A", () => releases.length === 1);
expect((await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, runId)))[0]).toMatchObject({ schemaStatus: "accepted", resultJson: { result: { reportedWorkDisposition: "done" } } });
expect(await proof()).toMatchObject({ source: releases[0], taskId });
expect(await proof()).toBeUndefined();
const providerSessionId = (await supervisor()).snapshot.providerSessionId;
expect(providerSessionId).toEqual(expect.any(String));
const pid = handle!.child.pid;
@@ -324,7 +324,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio
expect(await closeIdleWarmNativeSessionsForRestart()).toEqual({ closed: 0, busy: 0, failed: 0, failures: [] });
} else await new Promise(done => setTimeout(done, adoptedIdleTimeoutMs + 200));
expect(stops).toBe(0); expect(handle!.isExitConfirmed?.()).toBe(false);
expect(await proof()).toMatchObject({ source: releases[0], taskId });
expect(await proof()).toBeUndefined();
}
expect(readNativeSessionIdleWork()).toBe("none");
await reconcileNativeFinalizations(db, [runId]);
@@ -358,7 +358,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio
expect(handle!.isExitConfirmed!()).toBe(true);
expect((await readFile(calls, "utf8")).split(/\r?\n/).filter(method => method === "turn/start")).toHaveLength(1);
expect((await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, runB)))).toHaveLength(0);
expect(releases).toHaveLength(1); expect((await proof())?.source.runId).not.toBe(runB);
expect(releases).toHaveLength(1); expect(await proof()).toBeUndefined();
return runB;
}
expect(await pendingFollowup).toMatchObject({ exitCode: 0, timedOut: false });
@@ -369,7 +369,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio
const runB = await admitNext();
if (cancellation) return;
await waitForCondition("automatic release B", () => releases.length === 2);
expect(await proof()).toMatchObject({ source: releases[1], taskId });
expect(await proof()).toBeUndefined();
expect((await supervisor()).snapshot.providerSessionId).toBe(providerSessionId);
expect(adoption).toHaveBeenCalledTimes(adopted ? 1 : 0);
if (adopted) expect(adoption.mock.calls[0]![0]).toMatchObject({ identity: releases[0], execution: { binding: { runId: runB } } });
@@ -377,7 +377,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio
if (adopted) {
runC = await admitNext();
await waitForCondition("automatic release C", () => releases.length === 3);
expect(releases[2]!.runId).toBe(runC); expect(await proof()).toMatchObject({ source: releases[2], taskId });
expect(releases[2]!.runId).toBe(runC); expect(await proof()).toBeUndefined();
expect((await supervisor()).snapshot.providerSessionId).toBe(providerSessionId);
expect(adoption).toHaveBeenCalledTimes(1);
}
@@ -615,17 +615,11 @@ describe("plugin Runner release/resume facade", () => {
it.each([
["the parked build", undefined],
["a relaunched build", { version: "0.4.1", digest: `sha256:${"b".repeat(64)}` }],
])("clears the released Runner proof after a resume on %s, once Core saved a relaunched build", async (_label, runner) => {
])("passes the provider's resume outcome through on %s", async (_label, runner) => {
const task = vi.fn(async (): Promise<unknown> => ({ kind: "resume", taskId: "task", outcome: "resumed", ...(runner ? { runner } : {}) }));
const onResumed = vi.fn(async () => {});
const owner = createPluginRunnerTaskOwner({ ...input("codex"), task, onResumed, resumeRelaunchedRunnerVersion: 1 });
const owner = createPluginRunnerTaskOwner({ ...input("codex"), task, resumeRelaunchedRunnerVersion: 1 });
const outcome = await owner.driver.releaseResume!.resume(requirements.identity, "transient-ticket");
if (runner) {
expect(outcome).toEqual({ outcome: "resumed", runner, settled: expect.any(Function) });
expect(onResumed).not.toHaveBeenCalled();
if (typeof outcome === "object") await outcome.settled?.();
} else expect(outcome).toBe("resumed");
expect(onResumed).toHaveBeenCalledExactlyOnceWith(requirements.identity);
expect(outcome).toEqual(runner ? { outcome: "resumed", runner } : "resumed");
});
it("resumes with the credential resolved for the rebound claimant run", async () => {
@@ -805,8 +799,6 @@ describe("plugin Runner relaunch as the claimant run", () => {
const next = { ...source, runId: "next-run", turnId: "turn-next-run", itemId: "item-next-run" };
const parked = { version: "0.4.0", digest: `sha256:${"c".repeat(64)}` };
const build = { version: "0.4.1", digest: `sha256:${"b".repeat(64)}` };
const settledCut = { schema: "paperclip.runner.durable.state.v1", ...source, lifecycle: "ready", nextSourceSeq: 4, ackedSourceSeq: 3,
outbox: [], pendingTerminalDelivery: null, processedCommands: {} };
const base = { taskId: "task", projectIds: ["00000000-0000-4000-8000-000000000001"], projectAuthCheckVersion: 1 as const, harness: "codex", warmTaskVersion: 1 as const, releaseResumeVersion: 1 as const,
accountIdentity: "selected-account", credentialIdentity: "selected-credential" };
const relaunchSpec = (): RunnerProcessLaunchSpec => {
@@ -814,14 +806,14 @@ describe("plugin Runner relaunch as the claimant run", () => {
return { ...spec, nativeRunner: { ...spec.nativeRunner!, identity: next, lifecyclePolicy: { mode: "warm", idleTimeoutMs: 60_000 } } };
};
async function relaunchOwner(resume: (operation: any) => unknown,
options: { resumeIdentityVersion?: 1; onResumed?: () => Promise<void>; fresh?: true } = { resumeIdentityVersion: 1 }) {
options: { resumeIdentityVersion?: 1; fresh?: true } = { resumeIdentityVersion: 1 }) {
const { task } = provider();
const perform = task.getMockImplementation()!;
task.mockImplementation(async operation => operation.kind === "resume" ? resume(operation) : perform(operation));
const close = vi.fn(async () => {});
ingress.connect.mockReset().mockReturnValue({ ready: Promise.resolve(), quiesce: vi.fn(), close });
const relaunchInput = { ...base, task, authorityRunId: next.runId, resumeRelaunchedRunnerVersion: 1 as const,
resumeIdentityVersion: options.resumeIdentityVersion, relaunch: { source, runner: parked }, onResumed: options.onResumed };
resumeIdentityVersion: options.resumeIdentityVersion, relaunch: { source, runner: parked } };
const owner = createPluginRunnerTaskOwner(options.fresh ? relaunchInput : { ...base, task, adoptIdentity: source, authorityRunId: source.runId });
if (!options.fresh) owner.rebind(relaunchInput);
await prepare(owner, { ...requirements, identity: next });
@@ -831,10 +823,8 @@ describe("plugin Runner relaunch as the claimant run", () => {
}
it("starts the stopped Runner again as the claimant run and accepts the reported build", async () => {
const onResumed = vi.fn(async () => {});
const { owner, task, authority, registration } = await relaunchOwner(
() => ({ kind: "resume", taskId: "task", outcome: "resumed", runner: build, archivedState: settledCut }),
{ resumeIdentityVersion: 1, onResumed });
() => ({ kind: "resume", taskId: "task", outcome: "resumed", runner: build }));
expect(owner.driver.relaunchReleasedRunner).toEqual(source);
expect(owner.driver.adoptExistingRunner).toBeUndefined();
expect(owner.relaunchMayHaveStarted()).toBe(false);
@@ -848,7 +838,6 @@ describe("plugin Runner relaunch as the claimant run", () => {
}]);
expect(task.mock.calls.some(([operation]) => operation.kind === "submit")).toBe(false);
expect(authority.acceptRelaunchedRunner).toHaveBeenCalledExactlyOnceWith("synthetic-ticket", build, parked);
expect(onResumed).toHaveBeenCalledExactlyOnceWith(source);
expect(ingress.connect).toHaveBeenCalledOnce();
expect(owner.relaunchMayHaveStarted()).toBe(true);
owner.rebind({ ...base, task, authorityRunId: "later-run", resumeRelaunchedRunnerVersion: 1, resumeIdentityVersion: 1,
@@ -859,7 +848,7 @@ describe("plugin Runner relaunch as the claimant run", () => {
it("relaunches through a new owner, as after a Core restart, without submitting or adopting", async () => {
const { owner, task, authority, registration } = await relaunchOwner(
() => ({ kind: "resume", taskId: "task", outcome: "resumed", runner: build, archivedState: settledCut }),
() => ({ kind: "resume", taskId: "task", outcome: "resumed", runner: build }),
{ resumeIdentityVersion: 1, fresh: true });
expect(task.mock.calls.find(([operation]) => operation.kind === "prepare")?.[0]).toMatchObject({ priorIdentity: source });
expect(owner.driver.relaunchReleasedRunner).toEqual(source);
@@ -885,7 +874,7 @@ describe("plugin Runner relaunch as the claimant run", () => {
let attempts = 0;
const { task, registration, owner } = await relaunchOwner(() => {
if (attempts++ === 0) throw new Error("fixture resume reply lost");
return { kind: "resume", taskId: "task", outcome: "resumed", runner: build, archivedState: settledCut };
return { kind: "resume", taskId: "task", outcome: "resumed", runner: build };
});
owner.launcher(relaunchSpec());
registration.activate();
@@ -897,21 +886,6 @@ describe("plugin Runner relaunch as the claimant run", () => {
} finally { await registration.release("detach"); }
});
it.each([
["an unsettled cut", { ...settledCut, outbox: [{ sourceSeq: 4 }] }],
["another source's cut", { ...settledCut, runId: "other-run" }],
])("refuses %s before the Runner can connect", async (_label, archivedState) => {
const { authority, registration, owner } = await relaunchOwner(
() => ({ kind: "resume", taskId: "task", outcome: "resumed", runner: build, archivedState }));
owner.launcher(relaunchSpec());
registration.activate();
try {
await expect(registration.ready()).rejects.toThrow("native_runner_released_state_unsettled");
expect(authority.acceptRelaunchedRunner).not.toHaveBeenCalled();
expect(owner.relaunchMayHaveStarted()).toBe(true);
expect(ingress.connect).not.toHaveBeenCalled();
} finally { await registration.release("detach"); }
});
it("reports an unavailable relaunch for ordinary recovery", async () => {
const { registration, owner } = await relaunchOwner(() => ({ kind: "resume", taskId: "task", outcome: "unavailable" }));
@@ -5,7 +5,7 @@ import { environmentTaskOperationSchema, environmentTaskResultSchema, parseEnvir
import type { RunnerIngressEndpoint } from "@paperclipai/adapter-utils/runner-connectivity";
import { RUNNER_PRP_PROTOCOL_MIN, RUNNER_PRP_PROTOCOL_MAX, runnerLaunchPreparationDigest, runnerLaunchRunDigest, type RunnerProcessHandle, type RunnerProcessLaunchSpec,
type DurablePrpControlPlane, type RunnerExecutionDriver, type RunnerReleaseResumeOutcome, type RunnerLaunchPreparer, type DurableRecoveryIdentity, type PrpEvent,
isSettledReleasedRunnerCut } from "../../vendor/paperclip-runner/index.js";
} from "../../vendor/paperclip-runner/index.js";
import { connectRunnerPrpIngress } from "../../realtime/runner-prp-outbound.js";
import type { NativeExecutionContext } from "./native-execution-context.js";
@@ -60,8 +60,6 @@ export function createPluginRunnerTaskOwner(input: {
launchDigestVersion?: 1;
releasedSource?: DurableRecoveryIdentity;
sessionHandoff?: boolean;
onResumed?: (identity: DurableRecoveryIdentity) => Promise<void>;
onRetired?: (identity: DurableRecoveryIdentity) => Promise<void>;
githubBroker?: { url: string; token: string };
githubCredentialBrokerVersion?: 1;
configuredEnvironmentVersion?: 1;
@@ -262,11 +260,8 @@ export function createPluginRunnerTaskOwner(input: {
retiredBeforeClaim = state?.kind === "status" && state.executionStopped === true && state.sessionStateAvailable === true;
throw new Error("native_runner_reuse_unavailable");
}
if (!result.archivedState || !result.runner || !isSettledReleasedRunnerCut(result.archivedState, source)) {
throw new Error("native_runner_released_state_unsettled");
}
if (!result.runner) throw new Error("native_runner_released_state_unsettled");
authority.acceptRelaunchedRunner(native.ticket, result.runner, relaunch.runner);
await input.onResumed?.(source);
markReady();
return;
}
@@ -429,8 +424,6 @@ export function createPluginRunnerTaskOwner(input: {
if (submitted) {
await call({ kind: "complete" });
completed = true;
const identity = preparedIdentity ?? launchIdentity ?? input.priorIdentity;
if (identity) await input.onRetired?.(identity);
}
},
// The Runner is about to exit (its close suspend completed), as on release.
@@ -469,10 +462,7 @@ export function createPluginRunnerTaskOwner(input: {
if (activeOutbound === outbound) activeOutbound = null;
},
resume: async (identity: DurableRecoveryIdentity, ticket: string) => {
const outcome = await resume(identity, ticket);
if (typeof outcome === "object") return { ...outcome, settled: async () => { await input.onResumed?.(identity); } };
if (outcome === "resumed") await input.onResumed?.(identity);
return outcome;
return await resume(identity, ticket);
},
};
},
@@ -555,8 +545,6 @@ export function createPluginRunnerTaskOwner(input: {
}
await call({ kind: "complete" });
completed = true;
const identity = preparedIdentity ?? launchIdentity ?? input.priorIdentity;
if (identity) await input.onRetired?.(identity);
}
return stoppedState?.executionStopped === true && completed && !detached;
};
@@ -5,6 +5,7 @@ import { NATIVE_MODEL_REJECTION_MESSAGE, NATIVE_PROVIDER_CAPACITY_MAX_RETRIES, N
import { NATIVE_TOOL_RECEIPT_LIMIT_CODE, NATIVE_TOOL_RECEIPT_LIMIT_MAX_CONTINUATIONS } from "./native-tool-receipt-limit.js";
import { NATIVE_ENVIRONMENT_BLOCKER_CODE, NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_ACTION, NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_CODE,
NATIVE_ENVIRONMENT_BLOCKER_MAX_RETRIES } from "./native-environment-blocker.js";
import { planNotProducedDecision } from "./plan-mode-status.js";
import { NATIVE_AGENT_BLOCKER_CONTINUATION_CODE, NATIVE_AGENT_BLOCKER_HANDOFF_CODE,
NATIVE_AGENT_BLOCKER_MAX_CONTINUATIONS } from "./native-agent-blocker.js";
@@ -236,6 +237,8 @@ export function arbitrateNativeStatus(input: {
publishedExternalReview?: boolean;
/** Server-verified accepted plan request and normal provider terminal. */
planWaitAuthorized?: boolean;
/** A Plan-mode run settled with no unanswered plan revision to review. */
planNotProduced?: boolean;
monitorWaitAuthorized?: boolean;
caseHandoffAuthorized?: boolean;
/** The saved timer already admitted another run and this run no longer owns checkout. */
@@ -854,6 +857,12 @@ export function arbitrateNativeStatus(input: {
effects: [],
};
}
// Before the passive board/response waits: a Plan-mode run, assigned or
// comment-started, with no plan to review must not rest as a silent wait.
if (input.planNotProduced === true && !input.isConversation && input.assessment.reportedDisposition === "yielded" &&
input.assessment.continuation?.kind === "response_wake") {
return { policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION, ...planNotProducedDecision(input) };
}
if (
input.assessment.reportedDisposition === "yielded" &&
input.assessment.continuation?.kind === "response_wake" &&
+23
View File
@@ -28,6 +28,7 @@ import { isAiAuthenticationBlocked } from "../ai-auth-failure.js";
import { RESTRICTED_WORKSPACE_SOURCE_REASON } from "../workspace-source-restriction.js";
import { PROJECT_STORAGE_ENVIRONMENT_INCOMPATIBLE } from "../project-storage-environment-reason.js";
import { hasCommittedNativePlanWait } from "../native-runtime/native-plan-wait.js";
import { ensureNativePlanReviewCard } from "../native-runtime/native-plan-review-card.js";
import { hasCommittedNativeConversationTurnWait, hasCommittedNativeResponseWakeWait } from "../native-runtime/native-response-wake-wait.js";
import { listExternalReviewWaits } from "../native-runtime/external-review-wait.js";
import { isNativeWorkspaceExportRepairCause } from "@paperclipai/shared";
@@ -5099,6 +5100,28 @@ export function recoveryService(
continue;
}
// A Plan-mode task whose run settled before the server opened plan
// review cards on settle (or whose card opening was interrupted) gets
// its card here; the card is then its next action.
if (
issue.workMode === "planning" &&
issue.status === "in_progress" &&
latestRun?.status === "succeeded" &&
latestRun.agentId === agentId &&
// An accepted native plan waits for the user's next message; its
// answered plan question is the review. Never ask for it again.
parseObject(latestRun.resultJson).finalizationReasonCode !== "native_plan_accepted_waiting_for_continuation" &&
!(await hasCommittedNativePlanWait(db, {
companyId: issue.companyId, issueId: issue.id, runId: latestRun.id, agentId,
})) &&
(await ensureNativePlanReviewCard(db, {
companyId: issue.companyId, issueId: issue.id, runId: latestRun.id, agentId,
})).kind === "created"
) {
result.skipped += 1;
result.issueIds.push(issue.id);
continue;
}
if (
await hasActiveExecutionPath(
issue.companyId,
+2 -1
View File
@@ -641,7 +641,7 @@ type RemoteHttpExecutionAudit = {
protocol: "MCP JSON-RPC 2.0" | "Railway GraphQL" | "Railway GraphQL + SSH" | "Google Workspace REST";
httpMethod: "POST";
endpoint: string;
mcpMethod: "tools/call";
mcpMethod?: "tools/call";
requestId: string;
upstreamToolName: string;
dispatched: true;
@@ -8419,6 +8419,7 @@ export function createToolGatewayService(
};
if (workspaceTarget?.transport === "paperclip_rest") {
execution.request.protocol = "Google Workspace REST";
delete execution.request.mcpMethod;
execution.request.endpoint = googleWorkspaceRestAuditEndpoint(workspaceTarget.service);
await assertWorkspaceGrantCurrent();
const signal = taskSignals.run ? AbortSignal.any([controller.signal, taskSignals.run]) : controller.signal;
-1
View File
@@ -101,7 +101,6 @@ export const decodeDurablePrpCheckpoint = runner.decodeDurablePrpCheckpoint;
export const captureLegacyDurablePrpCheckpoint = runner.captureLegacyDurablePrpCheckpoint;
export const inspectDurablePrpCheckpointHeader = runner.inspectDurablePrpCheckpointHeader;
export const inspectDurablePrpCheckpointRunner = runner.inspectDurablePrpCheckpointRunner;
export const isSettledReleasedRunnerCut = runner.isSettledReleasedRunnerCut;
export const revertUnattachedRelaunchRotation = runner.revertUnattachedRelaunchRotation;
export const inspectUnclaimedBootstrapCheckpoint = runner.inspectUnclaimedBootstrapCheckpoint;
export const inspectUnauthenticatedBootstrapCheckpoint = runner.inspectUnauthenticatedBootstrapCheckpoint;
+1 -1
View File
@@ -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 });
+22 -20
View File
@@ -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,
+5 -7
View File
@@ -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) =>
+77 -70
View File
@@ -16,7 +16,12 @@ export async function json(response: Awaited<ReturnType<APIRequestContext["get"]
);
return response.json();
}
export async function setup(request: APIRequestContext) {
const DEFAULT_AGENT_NAMES = ["Alpha", "Beta", "Gamma", "Delta", "Epsilon", "Zeta"] as const;
export async function setup(
request: APIRequestContext,
options: { agentCount?: number } = {},
) {
const company = await json(
await request.post("/api/companies", {
data: { name: `Agent Chat ${Date.now()}` },
@@ -35,26 +40,29 @@ export async function setup(request: APIRequestContext) {
}),
);
}
const agents = [];
for (const name of ["Alpha", "Beta", "Gamma", "Delta", "Epsilon", "Zeta"])
agents.push(
await json(
await 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 },
},
const agentNames = DEFAULT_AGENT_NAMES.slice(0, options.agentCount ?? 1);
const createAgent = (name: string) =>
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(
+24 -7
View File
@@ -1,4 +1,5 @@
import { test, expect, request as pwRequest, type APIRequestContext, type Page } from "@playwright/test";
import { seedReturningAnnouncementVisit } from "./helpers/announcement-visit";
/**
* E2E (N-13): the in-app announcement well ("Introducing Connectors" upsell)
@@ -14,7 +15,7 @@ import { test, expect, request as pwRequest, type APIRequestContext, type Page }
const PORT = Number(process.env.PAPERCLIP_E2E_PORT ?? 3199);
const BASE_URL = `http://127.0.0.1:${PORT}`;
const ANNOUNCEMENT_ID = "e2e-n13-connectors";
const ANNOUNCEMENT_ID = "2026-09-14-connectors";
const SETTLE_WAIT_MS = 4_500; // ANNOUNCEMENT_SETTLE_MS (3 s) plus slack.
const ONE_PIXEL_PNG = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",
@@ -30,7 +31,8 @@ async function createCompany(board: APIRequestContext, name: string) {
data: { name: "Chief of staff", role: "ceo", adapterType: "process", adapterConfig: { command: "true" } },
});
if (!agentRes.ok()) throw new Error(`POST agents → ${agentRes.status()}: ${await agentRes.text()}`);
return { id: company.id as string, prefix: (company.issuePrefix ?? company.prefix) as string };
const agent = await agentRes.json();
return { agentId: agent.id as string, id: company.id as string, prefix: (company.issuePrefix ?? company.prefix) as string };
}
async function createIssue(board: APIRequestContext, companyId: string, data: Record<string, unknown>) {
@@ -54,11 +56,6 @@ async function mockAnnouncementFeed(page: Page) {
await page.route("**/api/workspace-preferences/me", (route) => route.fulfill({ json: {
userId: "local-board", coordinatorWorkspaceEnabled: false, updatedAt: null,
} }));
await page.addInitScript(() => {
for (const key of Object.keys(window.localStorage)) {
if (key.includes("announcement")) window.localStorage.removeItem(key);
}
});
}
test.describe("Announcement well (N-13)", () => {
@@ -79,7 +76,27 @@ test.describe("Announcement well (N-13)", () => {
await mockAnnouncementFeed(page);
});
test("chat-first onboarding keeps Connectors hidden across a reload until an idle return", async ({ page }) => {
const company = await createCompany(board, "E2E-Chat-Onboarding");
companyIds.push(company.id);
const start = await board.post(`${BASE_URL}/api/companies/${company.id}/chats/${company.agentId}/onboarding`, { data: {} });
expect(start.ok(), await start.text()).toBe(true);
const path = `/${company.prefix}/chats/${company.agentId}`;
const well = page.getByRole("complementary", { name: "Paperclip announcements" });
await page.clock.install();
for (const navigate of [() => page.goto(path), () => page.reload()]) {
await Promise.all([page.waitForResponse("**/api/announcements/current"), navigate()]);
await page.clock.fastForward(SETTLE_WAIT_MS);
await expect(well).toHaveCount(0);
}
const now = await page.evaluate(() => Date.now());
await page.clock.setSystemTime(now + 30 * 60_000);
await page.keyboard.press("Shift");
await expect(well.getByRole("link", { name: "Explore connectors" })).toBeVisible();
});
test("a brand-new company with its onboarding task open does not show the upsell", async ({ page }) => {
await seedReturningAnnouncementVisit(page);
const company = await createCompany(board, "E2E-N13-Onboarding");
companyIds.push(company.id);
const firstTask = await createIssue(board, company.id, {
+2
View File
@@ -1,4 +1,5 @@
import { test, expect, type APIRequestContext, type APIResponse, type Locator, type Page } from "@playwright/test";
import { seedReturningAnnouncementVisit } from "./helpers/announcement-visit";
/**
* N-17: a new user's first task view must stay usable while the in-app
@@ -54,6 +55,7 @@ async function box(locator: Locator, name: string): Promise<Box> {
}
async function serveConnectorsAnnouncement(page: Page, announcement: object = CONNECTORS_ANNOUNCEMENT) {
await seedReturningAnnouncementVisit(page);
await page.route("**/api/announcements/current", (route) =>
route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify(announcement) }),
);
@@ -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,
+21 -10
View File
@@ -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);
});
}
}
});
+8
View File
@@ -0,0 +1,8 @@
import type { Page } from "@playwright/test";
export async function seedReturningAnnouncementVisit(page: Page) {
await page.addInitScript(() => {
const key = "paperclip.board-visit.v1:local-board";
if (!localStorage.getItem(key)) localStorage.setItem(key, String(Date.now() - 31 * 60_000));
});
}
+14 -8
View File
@@ -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
+133
View File
@@ -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<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
let shutdownServer: ((signal?: "SIGINT" | "SIGTERM") => Promise<void>) | 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;
}
@@ -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",
@@ -13,7 +13,7 @@
"packages/plugins/sdk/src/environment-stop-error.ts": "b0e03f8aa2b2170ba095da5c7138050fced3f3cb",
"packages/plugins/sdk/src/environment-sync-error.ts": "7d6a51a95da49a7da4525aebbab6382dc5c44ae8",
"packages/plugins/sdk/src/environment-task-error.ts": "98aae8a06743b38884b68cb9a3ec44c57b34c0e4",
"packages/plugins/sdk/src/environment-tasks.ts": "5557e21415c67aca5c2dff7e06e8ea590f6c582e",
"packages/plugins/sdk/src/environment-tasks.ts": "ff2beb2c3c6af2e6b84bad8701367d8aee3c755d",
"packages/plugins/sdk/src/host-client-factory.ts": "e0301c390ea13f2340b669383f07af2455e48c8a",
"packages/plugins/sdk/src/idle-drain.test.ts": "cc59f7881e7d46c89395a1d93d74f6c6b9b0a64a",
"packages/plugins/sdk/src/idle-drain.ts": "ae6e4c6be4657a3d541396922b3bc551b8db557f",
@@ -130,7 +130,7 @@
"packages/shared/src/app-definitions/google-sheets.json": "de87b58007fca0b719d242148a838e2b5c26ddca",
"packages/shared/src/app-definitions/google-slides.json": "289366009d46be6b770eee6cd0bc650eb59a240c",
"packages/shared/src/app-definitions/google-workspace-search.json": "f3ec9d00ed0116b7cb8b9b1b71353cb8d6dc8cf4",
"packages/shared/src/app-definitions/google-workspace.json": "c3b55dc3ec502f6b86008e1e5b421748bdd50e91",
"packages/shared/src/app-definitions/google-workspace.json": "7a4acb34fb2ab5106860e910de50573070cbed2b",
"packages/shared/src/app-definitions/google.json": "f0bab0467612f915c88137eddbac0b320ac1aa2a",
"packages/shared/src/app-definitions/gsc-wizard.json": "a4ba6f183d5f35a25d0a420ade18f00d3fb64534",
"packages/shared/src/app-definitions/honcho.json": "17185eaf5189fc8c443388997c90ebf833bc9327",
@@ -241,7 +241,7 @@
"packages/shared/src/crash-point-registry.ts": "3cbf2d290bc111061376b43020848623e493737c",
"packages/shared/src/crash-points.test.ts": "3564a1f62d22f54a3c2fb0a72b3a6cde17c957d2",
"packages/shared/src/crash-points.ts": "c15259f39610e352eac5423a491548ec1bae94fe",
"packages/shared/src/customer-success.ts": "a2d02aaa8223164c0eae4267b2a6da82242eaa6f",
"packages/shared/src/customer-success.ts": "cf22017ffdd45123c1879f13c71c17516b8479a5",
"packages/shared/src/decision-models.ts": "a07aefd87d2fae34283ce21a0334d57e2108aa7e",
"packages/shared/src/decision.test.ts": "d0783d18613c73102f662e8a5da795ff6e7faed5",
"packages/shared/src/document-anchors.test.ts": "6805d149ad66d91f2e3ba4841f82e9af05bf5d83",
@@ -272,6 +272,7 @@
"packages/shared/src/google-sign-in-deployment.ts": "2e4e4cc3c24347642e20c91186581e1dce81d740",
"packages/shared/src/google-workspace-connectors.test.ts": "26316900a50e5ab384e0dcf9c45a2bb4abc0830d",
"packages/shared/src/google-workspace-connectors.ts": "88d942d1e66d7facc68cf8645f665cdc80c8c005",
"packages/shared/src/google-workspace-setup-links.test.ts": "d86428b26e74e54ab2902d1a14c0f06f562de775",
"packages/shared/src/grok-bot.ts": "9de68f00e7926c397729ff62bf8e277f5a41c525",
"packages/shared/src/heartbeat-inbox.ts": "227dc89705c20460ca02194091cb162e11503186",
"packages/shared/src/home-paths.test.ts": "81235c17c376224e1be3abd3f034a8400f079c66",
+4 -3
View File
@@ -1,3 +1,4 @@
import { AnnouncementVisitProvider } from "./context/AnnouncementVisitContext";
import { useCoordinatorWorkspaceEnabled } from "./hooks/useCoordinatorWorkspaceEnabled";
import { AgentChats } from "./pages/AgentChats";
import { lazy, Suspense, useEffect, type ReactNode } from "react";
@@ -782,7 +783,7 @@ function NoCompaniesStartPage() {
export function App() {
const { pathname } = useLocation();
const { enabled: classicStreamlinedUiEnabled, loaded: classicStreamlinedUiLoaded } = useStreamlinedUiEnabled();
const { enabled: coordinatorWorkspaceEnabled, loaded: coordinatorWorkspaceLoaded } = useCoordinatorWorkspaceEnabled();
const { enabled: coordinatorWorkspaceEnabled, loaded: coordinatorWorkspaceLoaded, userId } = useCoordinatorWorkspaceEnabled();
const streamlinedUiEnabled = classicStreamlinedUiEnabled || coordinatorWorkspaceEnabled;
const streamlinedUiLoaded = classicStreamlinedUiLoaded && coordinatorWorkspaceLoaded;
const { enabled: combinedInboxTasksEnabled } = useCombinedInboxTasksEnabled();
@@ -899,11 +900,11 @@ export function App() {
);
return (
<>
<AnnouncementVisitProvider userId={userId}>
<ConnectionStatusBanner />
<PageLoadTracker routes={routeTree} />
<Suspense fallback={<PaperclipLoading />}><Routes>{routeTree}</Routes></Suspense>
<OnboardingWizardVariant />
</>
</AnnouncementVisitProvider>
);
}
-167
View File
@@ -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<AgentChatPickerProps> = {}) {
props = { ...props, ...overrides };
await act(async () => { root.render(<AgentChatPicker {...props} />); });
}
async function search(value: string) {
const input = document.querySelector<HTMLInputElement>("[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<HTMLElement>("[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 => <span>{agent.title} marker</span> });
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<void>(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<HTMLInputElement>("[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<HTMLInputElement>("[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");
});
});
-187
View File
@@ -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<void>) {
let result: void | Promise<void> | 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(
<AgentMultiSelect agents={agents} selectedAgentIds={new Set()} onChange={onChange} />,
);
});
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<HTMLInputElement>('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(<AgentSelect agents={agents} value="" onChange={onChange} />);
});
act(() => {
container.querySelector("button")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
await flush();
const filter = document.body.querySelector<HTMLInputElement>('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(<AgentSelect agents={agents} value="agent-1" onChange={vi.fn()} />));
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(
<AgentMultiSelect
agents={agents}
selectedAgentIds={new Set(["agent-0", "agent-1", "agent-2", "agent-3", "agent-4"])}
onSave={onSave}
triggerLabel="Add to agent"
/>,
);
});
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)));
});
});
@@ -169,6 +169,44 @@ describe("agent setup progress", () => {
const flush = () => act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
const token = () => container.querySelector('[data-testid="token"]')?.textContent;
it("keeps a finished checklist on screen when the app refreshes every query", async () => {
const done: AgentSetupProgress = { ...WAITING, status: "done", summary: "Role ARN: arn:aws:iam::123456789012:role/paperclip-conn-1",
items: [{ key: "create-role", title: "Create the role", status: "done", detail: null }] };
const create = vi.fn().mockResolvedValue(HANDOFF);
let status: "waiting" | "done" = "waiting";
const client: AgentSetupProgressClient = { create, get: vi.fn(async () => status === "done" ? done : WAITING) };
await act(async () => { root.render(<QueryClientProvider client={queryClient}><Full client={client} /></QueryClientProvider>); });
await flush();
status = "done";
await act(async () => { await queryClient.invalidateQueries({ queryKey: queryKeys.agentSetupProgress(ID) }); });
await vi.waitFor(() => expect(container.textContent).toContain("Your agent set up AWS"));
// The live connection reconnects or the tab returns: the app refreshes every query on screen.
await act(async () => { await queryClient.invalidateQueries({ type: "active" }); });
await flush();
expect(create).toHaveBeenCalledOnce();
expect(token()).toBe("pcsp_token");
expect(container.textContent).toContain("Your agent set up AWS");
expect(container.textContent).toContain("Role ARN: arn:aws:iam::123456789012:role/paperclip-conn-1");
});
it("still creates a fresh checklist when Start again's first create fails and its retry succeeds", async () => {
const failedAttempt: AgentSetupProgress = { ...WAITING, status: "failed", summary: "Stopped: no permission",
items: [{ key: "deploy", title: "Create the role", status: "failed", detail: "iam:CreateRole denied" }] };
const second: AgentSetupProgressHandoff = { ...HANDOFF, token: "pcsp_after_retry", progress: { ...WAITING, id: "88888888-8888-4888-8888-888888888888" } };
const create = vi.fn().mockResolvedValueOnce(HANDOFF).mockRejectedValueOnce(new Error("offline")).mockResolvedValueOnce(second);
const client: AgentSetupProgressClient = { create, get: vi.fn(async (id: string) => id === ID ? failedAttempt : second.progress) };
// The app's queries retry a failed request; this one retries once, at once.
const retrying = new QueryClient({ defaultOptions: { queries: { retry: 1, retryDelay: 0 } } });
await act(async () => { root.render(<QueryClientProvider client={retrying}><Full client={client} /></QueryClientProvider>); });
await flush();
await act(async () => { await retrying.invalidateQueries({ queryKey: queryKeys.agentSetupProgress(ID) }); });
await vi.waitFor(() => expect(container.textContent).toContain("Your agent couldn’t finish setting up AWS"));
const startAgain = [...container.querySelectorAll("button")].find((b) => b.textContent === "Start again")!;
await act(async () => { startAgain.click(); });
await vi.waitFor(() => expect(token()).toBe("pcsp_after_retry"));
expect(create).toHaveBeenCalledTimes(3);
});
it("offers a fresh checklist after a failed attempt, and opening the step again later starts fresh", async () => {
const failedAttempt: AgentSetupProgress = { ...WAITING, status: "failed", summary: "Stopped: no permission",
items: [{ key: "deploy", title: "Create the role", status: "failed", detail: "iam:CreateRole denied" }] };
+10
View File
@@ -73,12 +73,21 @@ export function useAgentSetupProgress({
const accountFailed = !accountOverride && account.failed;
const handoffKey = ["agent-setup-progress-handoff", accountId, companyId ?? null, purpose, subjectId ?? null] as const;
const storageKey = agentSetupHandoffStorageKey(accountId, companyId, purpose, subjectId);
// Set by renew and kept until a new checklist is created, so a retry of a failed create still
// creates rather than returning the checklist being replaced.
const replacing = useRef(false);
const handoffQuery = useQuery({
queryKey: handoffKey,
queryFn: async () => {
// Any other refetch (the app refreshes every query on screen when its live connection
// reconnects or the tab returns) keeps the checklist on screen. A finished one is no longer
// in storage, so falling through here would replace it with a blank checklist.
const current = queryClient.getQueryData<{ handoff: AgentSetupProgressHandoff; fromEarlierVisit: boolean }>(handoffKey);
if (current && !replacing.current) return current;
// A handoff found in this tab's storage came from an earlier visit; a created one is new.
const stored = storedAgentSetupHandoff(storageKey);
const handoff = stored ?? await client.create(companyId!, { purpose, ...(subjectId ? { subjectId } : {}) });
replacing.current = false;
storeAgentSetupHandoff(storageKey, handoff);
return { handoff, fromEarlierVisit: Boolean(stored) };
},
@@ -115,6 +124,7 @@ export function useAgentSetupProgress({
return;
}
storeAgentSetupHandoff(storageKey, null);
replacing.current = true;
void handoffQuery.refetch();
};
-5
View File
@@ -29,11 +29,6 @@ export function useModalOpen(enabled: boolean, selector = MODAL_SELECTOR) {
const FINISHED_ONBOARDING_STATUSES = new Set(["done", "cancelled"]);
/**
* A new user's first session is the onboarding first task. Announcements and
* other optional prompts wait until that task is finished so they cannot cover
* its questions. Unknown state (loading or a failed read) keeps them hidden.
*/
export function useOnboardingInProgress(companyId: string | null) {
const query = useQuery({
queryKey: queryKeys.issues.onboardingFirstTask(companyId ?? "__none__"),
-254
View File
@@ -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<ChatComposerProps> & { initial?: string }) {
const { initial = "", onChange, ...rest } = props;
const [value, setValue] = useState(initial);
return (
<ChatComposer
value={value}
onChange={(v) => {
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<HTMLTextAreaElement>('[data-testid="chat-composer-input"]')!;
}
function sendButton() {
return container.querySelector<HTMLButtonElement>('button[aria-label="Send message"]')!;
}
function attachButton() {
return container.querySelector<HTMLButtonElement>('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(<Harness placeholder="Ask anything…" />);
});
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(<Harness onAttachFiles={() => {}} />);
});
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(<Harness />);
});
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(<Harness onSubmit={onSubmit} initial="hi" />);
});
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(<Harness onSubmit={onSubmit} initial="hi" submitKey="enter" />);
});
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(<Harness onSubmit={onSubmit} initial="hi" submitKey="mod-enter" />);
});
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(<Harness singleLine onChange={onChange} />);
});
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(<Harness />);
});
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(<Harness singleLine />);
});
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(<Harness tone="planning" />);
});
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(<Harness tone="ask" />);
});
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(<Harness />);
});
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(<Harness surface="translucent" />);
});
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(<Harness surface="translucent" onAttachFiles={() => {}} />);
});
const box = container.querySelector<HTMLDivElement>('[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());
});
});
@@ -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<void>) {
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<typeof vi.spyOn>;
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(
<DocumentAnnotationLayer
containerRef={{ current: body }}
markdown="Annotated body text."
threads={[
{ id: "active", selectedText: "Annotated", status: "open", anchorState: "active" },
{ id: "focused", selectedText: "body", status: "open", anchorState: "active" },
{ id: "stale", selectedText: "text", status: "open", anchorState: "stale" },
{ id: "resolved", selectedText: "body text", status: "resolved", anchorState: "active" },
]}
focusedThreadId="focused"
onThreadFocus={vi.fn()}
pendingAnchor={null}
onPendingAnchorChange={vi.fn()}
onRequestComment={vi.fn()}
hideResolved={false}
/>,
);
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(
<DocumentAnnotationLayer
containerRef={{ current: body }}
markdown="Hidden folded text"
threads={[
{ id: "hidden", selectedText: "Hidden folded text", status: "open", anchorState: "active" },
]}
focusedThreadId={null}
onThreadFocus={vi.fn()}
pendingAnchor={null}
onPendingAnchorChange={vi.fn()}
onRequestComment={vi.fn()}
/>,
);
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(
<DocumentAnnotationLayer
containerRef={{ current: body }}
markdown="Editing routine instructions"
threads={[]}
focusedThreadId={null}
onThreadFocus={vi.fn()}
pendingAnchor={null}
onPendingAnchorChange={onPendingAnchorChange}
onRequestComment={vi.fn()}
/>,
);
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(
<DocumentAnnotationLayer
containerRef={{ current: body }}
markdown="Editing routine instructions"
threads={[]}
focusedThreadId={null}
onThreadFocus={vi.fn()}
pendingAnchor={null}
onPendingAnchorChange={onPendingAnchorChange}
onRequestComment={vi.fn()}
/>,
);
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(
<DocumentAnnotationLayer
containerRef={{ current: body }}
markdown="Annotated body text."
threads={[
{ id: "active", selectedText: "Annotated", status: "open", anchorState: "active" },
]}
focusedThreadId={null}
onThreadFocus={vi.fn()}
pendingAnchor={null}
onPendingAnchorChange={vi.fn()}
onRequestComment={vi.fn()}
/>,
);
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;
});
});
@@ -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 <><output>{location.pathname}{location.search}{location.hash}</output><button onClick={() => navigate(-1)}>Back</button></>;
}
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(<MemoryRouter initialEntries={[`/PAP/issues/example?keep=1${hash}`]}>
<QueryClientProvider client={client}><ThemeProvider>
<DocumentMarkdownBody documentKey="report" revisionId={revisionId} documentIssueId={documentIssueId} currentIssueId={currentIssueId}>{markdown}</DocumentMarkdownBody>
<LocationProbe />
</ThemeProvider></QueryClientProvider>
</MemoryRouter>);
});
}
async function click(selector: string) {
const element = document.querySelector<HTMLElement>(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);
});
});
-127
View File
@@ -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<void>) {
let result: void | Promise<void> = 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<React.ComponentProps<typeof EnvironmentVariablesEditor>>) {
root = createRoot(container);
return act(() => {
root.render(
<EnvironmentVariablesEditor
value={props.value ?? {}}
secrets={props.secrets ?? []}
userSecretDefinitions={props.userSecretDefinitions}
onCreateSecret={props.onCreateSecret ?? (vi.fn() as never)}
onChange={props.onChange ?? vi.fn()}
/>,
);
});
}
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<string, EnvBinding> = {
GH_TOKEN: { type: "user_secret_ref", key: "PERSONAL_GH_TOKEN", required: true },
};
await render({ value, userSecretDefinitions: [definition] });
const keyInput = container.querySelector<HTMLInputElement>('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<string, EnvBinding> = {
API_KEY: { type: "secret_ref", secretId: "sec-1", version: "latest" },
};
await render({ value, secrets: [secret] });
const keyInput = container.querySelector<HTMLInputElement>('input[placeholder="KEY"]');
expect(keyInput?.value).toBe("API_KEY");
expect(container.textContent).toContain("API key");
});
});
-231
View File
@@ -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(
<FileTree nodes={[]} selectedFile={null} expandedDirs={new Set()} onSelectFile={() => {}} 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(
<FileTree
nodes={nodes}
selectedFile="README.md"
expandedDirs={new Set(["docs"])}
onSelectFile={onSelectFile}
onToggleDir={onToggleDir}
/>,
);
});
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(
<FileTree
nodes={nodes}
selectedFile={null}
expandedDirs={new Set(["docs"])}
checkedFiles={new Set(["docs/a.md"])}
onSelectFile={() => {}}
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(
<FileTree
nodes={nodes}
selectedFile={null}
expandedDirs={new Set(["wiki"])}
onSelectFile={() => {}}
onToggleDir={() => {}}
fileBadges={{
"wiki/very-long-page-slug.md": {
label: "fresh",
status: "ok",
tooltip: "Synced",
},
}}
renderFileExtra={(node) => (
node.kind === "file" ? <span data-testid="file-extra">{node.name.length} chars</span> : 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(
<FileTree
nodes={nodes}
selectedFile={null}
expandedDirs={new Set(["wiki"])}
onSelectFile={() => {}}
onToggleDir={() => {}}
/>,
);
});
expect(row("wiki/extremely-long-page-slug-that-wraps-on-mobile.md")?.innerHTML).toContain("break-all");
act(() => {
root.render(
<FileTree
nodes={nodes}
selectedFile={null}
expandedDirs={new Set(["wiki"])}
onSelectFile={() => {}}
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(
<FileTree
nodes={nodes}
selectedFile={null}
expandedDirs={new Set()}
onSelectFile={() => {}}
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(<FileTree {...props} />));
act(() => row("docs/b.md")?.focus());
act(() => root.render(<FileTree {...props} visiblePaths={new Set(["docs", "docs/a.md"])} renderLabel={node => <span>{node.name} description</span>} />));
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(<FileTree nodes={buildFileTree({ "docs/a.md": "" })} selectedFile={null} expandedDirs={new Set(["docs"])} onToggleDir={onToggleDir} onToggleCheck={onToggleCheck} onSelectFile={onSelectFile} disabled />));
act(() => {
row("docs/a.md")?.click();
row("docs")?.dispatchEvent(new KeyboardEvent("keydown", { key: " ", bubbles: true }));
container.querySelector<HTMLButtonElement>('[aria-label="Collapse docs"]')?.click();
});
expect(onToggleCheck).not.toHaveBeenCalled();
expect(onSelectFile).not.toHaveBeenCalled();
expect(onToggleDir).not.toHaveBeenCalled();
expect(container.querySelector<HTMLInputElement>('input[type="checkbox"]')?.disabled).toBe(true);
});
});
@@ -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<void>) {
let result: void | Promise<void> = 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(
<Dialog defaultOpen>
<DialogContent aria-describedby={undefined}>
<DialogTitle>New task</DialogTitle>
<InlineEntitySelector
value=""
options={Array.from({ length: 20 }, (_, index) => ({ 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
/>
</DialogContent>
</Dialog>,
);
});
try {
await act(() => {
document.querySelector<HTMLButtonElement>("[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<HTMLElement>("[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(<>
<button type="button" data-testid="outside-picker">Outside</button>
<InlineEntitySelector
value=""
options={[{ id: "agent-1", label: "Agent One" }]}
placeholder="Assignee"
noneLabel="No assignee"
searchPlaceholder="Search assignees..."
emptyMessage="No assignees found."
onChange={vi.fn()}
triggerTestId="desktop-assignee-picker"
/>
</>);
});
try {
const trigger = container.querySelector<HTMLButtonElement>("[data-testid=desktop-assignee-picker]")!;
const outside = container.querySelector<HTMLButtonElement>("[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(
<Dialog defaultOpen>
<DialogContent aria-describedby={undefined}>
<DialogTitle>New task</DialogTitle>
<InlineEntitySelector
value="project-1"
options={[{ id: "project-1", label: "Board UI" }]}
placeholder="Project"
noneLabel="No project"
searchPlaceholder="Search projects..."
emptyMessage="No projects found."
onChange={onChange}
triggerTestId="project-picker"
openOnFocus={false}
/>
</DialogContent>
</Dialog>,
);
});
try {
const trigger = document.querySelector<HTMLButtonElement>('[data-testid="project-picker"]')!;
await act(() => trigger.click());
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
const backdrop = document.querySelector<HTMLElement>("[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(
<InlineEntitySelector
value=""
options={[
{ id: "agent:agent-1", label: "CodexCoder" },
{ id: "agent:agent-2", label: "DesignBot" },
]}
placeholder="Responsible"
noneLabel="No responsible"
searchPlaceholder="Search responsible..."
emptyMessage="No responsible found."
onChange={onChange}
/>,
);
});
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(
<InlineEntitySelector
value=""
options={[
{ id: "agent:agent-1", label: "CodexCoder" },
{ id: "agent:agent-2", label: "DesignBot" },
]}
placeholder="Responsible"
noneLabel="No responsible"
searchPlaceholder="Search responsible..."
emptyMessage="No responsible found."
onChange={vi.fn()}
disablePortal
/>,
);
});
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(
<InlineEntitySelector
value=""
options={[{ id: "project-1", label: "Project One" }]}
placeholder="Project"
noneLabel="No project"
searchPlaceholder="Search projects..."
emptyMessage="No projects found."
onChange={vi.fn()}
/>,
);
});
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(
<InlineEntitySelector
value="project-1"
options={[
{ id: "project-1", label: "Project One" },
{ id: "project-2", label: "Project Two" },
]}
recentOptionIds={["project-2"]}
placeholder="Project"
noneLabel="No project"
noneAtTop
searchPlaceholder="Search projects..."
emptyMessage="No projects found."
onChange={onChange}
/>,
);
});
const trigger = container.querySelector("button") as HTMLButtonElement;
await act(() => trigger.click());
const options = Array.from(
document.querySelectorAll<HTMLButtonElement>("[data-mobile-entity-picker-list] > button"),
);
expect(options.map((option) => option.textContent)).toEqual([
"No project",
"Project One",
"Project Two",
]);
const searchInput = document.querySelector<HTMLInputElement>('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<HTMLButtonElement>("[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(
<InlineEntitySelector
value=""
options={[{ id: "agent:agent-1", label: "CodexCoder" }]}
placeholder="Responsible"
noneLabel="No responsible"
searchPlaceholder="Search responsible..."
emptyMessage="No responsible found."
onChange={onChange}
disabled
/>,
);
});
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(
<InlineEntitySelector
value=""
options={[
{ id: "agent:agent-1", label: "CodexCoder" },
{ id: "agent:agent-2", label: "DesignBot" },
]}
placeholder="Responsible"
noneLabel="No responsible"
searchPlaceholder="Search responsible..."
emptyMessage="No responsible found."
onChange={onChange}
/>,
);
});
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();
});
});
});
@@ -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<void>) {
if (typeof reactAct === "function") {
await reactAct(callback);
return;
}
let result: void | Promise<void> = 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(
<TooltipProvider>
<InteractionGovernancePanel governance={governance} onChange={onChange} />
</TooltipProvider>,
);
});
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 `<SelectValue />` 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<HTMLElement>(
'[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(
<TooltipProvider>
<InteractionGovernancePanel
governance={{}}
onChange={vi.fn()}
errorMessage="Failed to save interaction governance"
/>
</TooltipProvider>,
);
});
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" },
});
});
});
Loaded 100 of 142 files, more files were not shown because too many files have changed in this diff. Show more