mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 11:59:26 +01:00
533d02ff1a9db82e647fa6bf7eaf194f3ab69bdb
7918
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
533d02ff1a |
perf(recovery): match scoped deadline entries only against scopes of their own company (#21467)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Live-run recovery uses the shared scoped deadline worker (`scoped-deadline-work.ts`). Each queue keeps its entries (one for each running run) and the scopes that writes marked dirty (for example one company and one run) > - To schedule and to pick due work, the worker tested every entry against every dirty scope. It also decoded each scope hint with `JSON.parse` again inside those loops, and each reconstructed scope walked all entries to drop vanished ones > - With many runs and many dirty run scopes, this work grows with entries × scopes on the event loop of the one server process that controls all runs > - This pull request lets an owner declare a partition key for its scopes. Live-run recovery uses the company. The worker then tests an entry only against the scopes of its own company, and decodes each hint once > - The benefit is that matching cost grows with entries + scopes, with the same results ## Linked Issues or Issue Description Refs #21444 (the lease renewal change from the same load model). **What existing behavior does this improve?** The scoped deadline worker in `server/src/services/scoped-deadline-work.ts`, which live-run recovery (`server/src/services/heartbeat/live-recovery-work.ts`) uses for its seven queues. **Subsystem affected** Server: background work scheduling for live-run and resource recovery. **Current behavior** For 400 entries in 40 companies and 40 dirty run scopes, one schedule computation and one pass call `matches` 27,830 times and decode each hint many times. **Proposed behavior** The same case calls `matches` fewer than 3,200 times and decodes each hint at most once. Owners that do not declare a key behave exactly as before. **Reason and benefit** The plan for 1,000 concurrent agents needs per-run background work that does not grow with the product of runs and changes. The work runs on the main thread of the controlling process. **Breaking changes** None. `scopeKey` is optional. ## What Changed - `scoped-deadline-work.ts`: new optional `scopeKey` option (`entry(entry)` and `scope(scope)`). The contract: a scope with a defined key matches only entries with the same key. A scope without a key (for example `*`) is tested against every entry, as before. - The worker indexes the dirty scopes by key, so `next()` and the due filter test each entry only against the scopes of its key and the unkeyed scopes. - When a reconstructed keyed scope drops vanished entries, it visits only the entries of its key (an index built once for each pass). - Scope hints are decoded once and the decoded value is reused while the hint is dirty or scanning. - `live-recovery-work.ts`: declares the company as the key. Its `matches` already requires the same company for every defined scope. ## Verification - New test in `scoped-deadline-work.test.ts`: 400 entries in 40 companies, then 40 run-scoped invalidations. It requires fewer than 3,200 `matches` calls and at most 40 decodes, and the next deadline is unchanged. - Red first: with `origin/master` `scoped-deadline-work.ts`, the test failed with 27,830 `matches` calls. - `pnpm exec vitest run src/__tests__/scoped-deadline-work.test.ts`: 22 passed. - The live-run recovery matrix (`live-recovery-work.test.ts`) is covered by CI. ## Risks - If an owner declares a key that its `matches` does not respect, the worker can miss a match. Only live-run recovery declares a key, and its `matches` returns false for any defined scope of another company. - Low risk otherwise: owners without a key keep the old code path. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
754b1f36d3 |
perf(native): renew all of a process's execution leases in one transaction, without a recovery wake (#21444)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - One server process controls every running native agent. Each run holds a native execution lease that the process must renew before it expires (60 seconds for a remote run, 20 minutes for a local run) > - Each run renewed its lease on its own timer, in its own transaction, on a private pool of two connections. At 1,000 remote runs that is about 50 transactions each second through two connections > - When renewals queue behind each other, a renewal can miss its 60 second deadline, and the run is lost although the server is healthy > - Each renewal also woke six live-run recovery queues for its run. The recovery owner then re-checked a healthy run about every 20 seconds, although a renewal only moves the deadline later > - This pull request renews all leases of one process with one shared timer. All leases that are due go into one transaction of fixed size, the same model that the legacy controller lease already uses. A renewal no longer wakes recovery, as #20924 did for the legacy lease > - The benefit is that the renewal cost no longer grows with the number of runs, and all safety properties of a single renewal stay the same ## Linked Issues or Issue Description Refs #20924 (the same change for the legacy controller lease), #21242. **What existing behavior does this improve?** Native execution lease renewal in `server/src/services/native-runtime/native-execution-lease.ts`. Each run had one `setInterval` and one transaction per renewal: statement timeout, row lock, recovery notification, update, commit. **Subsystem affected** Server: native runtime, controller lease renewal on the liveness connection pool. **Current behavior** The renewal cost grows with the number of runs. A local load model with 1,000 remote runs sends 35.7 lease transactions and 212.8 lease statements each second, and the event-loop utilization is 0.34. All of them use a pool of two connections. **Proposed behavior** One timer for each database client renews all due leases in one transaction for each 200 runs. With 1,000 remote runs the same model sends 0.29 lease transactions and 1.7 lease statements each second, and the event-loop utilization is 0.07. **Reason and benefit** The plan for 1,000 concurrent agents needs renewals that do not scale with the run count (item 1d). A renewal that misses its deadline loses the run. **Breaking changes** None. The `NativeExecutionLeaseRenewal` contract (`stop()`, `remainingMs()`) and `renewNativeSessionExecutionLease` do not change. ## What Changed - `native-execution-lease.ts`: a renewal (batched or single) no longer calls `notifyLiveRunRecovery`. A renewal only moves the lease deadline later. Recovery already holds a deadline at the earlier expiry. At that deadline it re-reads the row and moves to the new expiry. A lapsed lease is still found at its expiry. This change does not touch the signals of the writers that release, revoke or take over a lease, or that change the run status. This also removes six notifications for each renewal, which was 1,200 notifications for a batch of 200 runs during a deploy overlap. - `native-execution-lease.ts`: one shared schedule for each database client replaces the timer of each run. When the first lease is due, all leases that are due within a quarter of their own interval renew with it. Thus the leases of a process converge on one batch for each interval. - A batch is one transaction on the liveness pool for each 200 runs: `statement_timeout`, one `SELECT … FOR UPDATE SKIP LOCKED` of the coordinator rows, and one `UPDATE … FROM (VALUES …)`. - The batch keeps the guarantees of a single renewal: - It locks each coordinator row before it reads the expiry, as before. Thus an owner whose lease expired while another writer held the row is never revived. - It extends a row only for the exact owner: run, company, task, lease owner, attempt, controller boot id, pid, process start, and a live lease. - The confirmed deadline is sampled after the locks and before the update, as before. - A run whose row was locked and not extended fails with `native_session_lease_lost`. The other runs in the batch succeed. - These rows do not renew in the batch. They renew alone through the unchanged single-run path: - A row that another writer holds (`SKIP LOCKED`). Thus one busy row cannot hold the batch until the statement timeout. - A row that the lock did not find (another owner, or no row). The single path gives the same answer as before. - A local lease that lapsed (host sleep). Only the single path may take it back, under the run row lock. - A batch that is cancelled (statement timeout `57014` or deadlock `40P01`) extends nothing. Its runs retry after 1 second, and each run keeps its own deadline timer. Before this change, a statement timeout waited for the next 20 second tick. - Any other batch failure, also an error thrown while the statement is built, may come from one bad row. Each run of that batch then renews alone at once through the single path, so a bad row can cost only its own run. A run that fails alone while others in its batch renew keeps renewing alone (out of later batches) until a single renewal succeeds. During a database outage the single renewals also fail; those runs return to the batch at their next interval, not after a 1 second retry, so an outage causes at most one queued single transaction for each run and interval. - Runs that become due while a batch is in flight wait for that batch. A batch that runs for more than 15 seconds no longer holds back the next batch. - A tick that passed while a renewal was in flight is skipped, as a fixed interval skips it. Thus a slow database gets no extra load. - The shared timer replaces the interval timer of each run. It exists only while this process holds a lease, and it fires at the next renewal deadline. With no held lease there is no timer and no SQL. - New export `renewNativeExecutionLeasesNow(db)` renews all leases of the process at once. Tests use it. ## Verification - New PostgreSQL tests in `native-execution-lease-batch.test.ts`: - 3 runs and 60 runs each renew in 1 transaction with the same number of statements. - 450 runs renew in 3 transactions. - In one batch, the runs whose lease was taken over, whose controller boot changed, or whose lease expired fail with `native_session_lease_lost`. Their rows do not change. The healthy runs renew. A newer attempt under the same owner is not lost, as before. - Interleaving: another transaction holds a coordinator row from before its lease expires until after it expired. The healthy run in the same batch renews at once. After the lock is released, the expired owner is lost and its row stays expired. - A takeover that commits before the batch: the batch extends nothing and the run is lost. - A local and a remote lease renew in one transaction, each for its own lease length. - A poison binding (an attempt outside the integer range) makes the shared UPDATE fail with `22003`. The other 4 runs still renew in the same tick, only the poison run is lost, and the next tick renews the 4 runs in 1 transaction again. - An invalid date throws while the statement is built. The other runs renew, the broken run is lost alone, and no lease stays busy (the next call renews again in 1 transaction). - New PostgreSQL test in `live-recovery-work.test.ts` with the real registered recovery owners: another server's native run renews its lease. No recovery pass runs after the renewal. At the old expiry recovery re-reads the row, keeps the run running and moves its deadline to the new expiry. When renewals stop, recovery acts on the run within 10 seconds after the end of the last lease. - Red first: with a shim on `origin/master` that renews each lease alone, the transaction test failed (`expected 3 to be 1`) and the 450-run test failed. - The unit tests in `native-execution-lease.test.ts` now drive the batch. New tests show that a non-cancelled batch failure renews the run alone at once, and that an outage (batch and single renewal both fail) does not retry every second and loses no run. - `native-execution-lease-reacquire.test.ts`: the host-sleep tests now go through the batch, which hands the lapsed local lease to the single path. - Load model (`startNativeSessionExecutionLeaseRenewal` for N remote runs that start at random times over 20 seconds, 70 second window, local PostgreSQL, machine load average about 50): | Runs | Lease transactions/s before → after | Lease statements/s before → after | Event-loop utilization before → after | Smallest margin to the 60 s deadline | Lost | | --- | --- | --- | --- | --- | --- | | 50 | 1.81 → 0.11 | 10.9 → 0.69 | 0.015 → 0.095 (noise) | 40.0 s → 40.0 s | 0 → 0 | | 1,000 | 35.67 → 0.29 | 212.8 → 1.71 | 0.341 → 0.065 | 39.0 s → 40.0 s | 0 → 0 | The window includes the 20 second ramp, so the steady rate before is higher (one transaction each 20 seconds for each run, 50/s at 1,000 runs). After the change, one batch carries up to 200 runs. ## Risks - **Behavior change: batch-wide error handling.** One shared transaction now carries up to 200 runs, so one database error reaches all of them. A cancelled batch only skips the extension and retries after 1 second. Any other batch error sends each run to the single path at once, so one bad row (a bad value, a cast error, an error while the statement is built) costs only its own run. In a database outage, up to one single transaction for each run waits on the two-connection pool at each interval. Each run's own deadline is unchanged. - **Behavior change: no recovery signal on renewal.** See below. - During a deploy overlap the old server renews its runs one by one and the new server renews in batches. Both use the same row lock and the same conditions, so they do not conflict. Rows written by the old version have the same columns. - `SKIP LOCKED` sends a busy row to the single path, which waits for the lock as before. - **No recovery signal on renewal:** recovery of a healthy run of another server now runs once for each lease period at the old expiry, not after each renewal. A dead run is found at the same time as before: at the expiry of its last lease. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
969cf246ae |
perf(run-events): keep each native source's cursor on the run row (#21435)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - One server process stores every event of every running native agent in `heartbeat_run_events` > - Each native source event append counted all retained events of its source (`count(*)`, `max(source_seq)`) to compute the acknowledgement cursor > - So the cost of each append grew with the length of the run, and long runs made every text delta slower > - This pull request keeps the gap-free cursor of each source on the run row and moves it in the same UPDATE that reserves the event sequence > - The benefit is that an in-order append stops reading other events, so its cost does not grow with run length ## Linked Issues or Issue Description Refs #21131 (earlier reduction of statements per event). Item 1b of the agent scaling plan in #21418. **What existing behavior does this improve?** The append of a native source event (`appendNativeSourceEvent` in `server/src/services/heartbeat-run-events.ts`). It ran a `retained` CTE that counted every event of the source on every append. **Subsystem affected** Server run event ingest (`heartbeat_run_events`, `heartbeat_runs`). **Current behavior** On a run that already holds 50,000 events, one in-order append takes about 10–13 ms (p50) on a local PostgreSQL. On a run with 400 events it takes about 3.3 ms. **Proposed behavior** The append reads the stored cursor in the run lock statement that it already sends. An in-order event moves the cursor and does not count events. On the same 50,000-event run an append takes about 1.7–3.3 ms (p50). **Reason and benefit** Text deltas are about 85% of the server's statements in the load model. Their cost must not grow with run length. **Breaking changes** None. The new column is nullable. The previous release ignores it. ## What Changed - Add the nullable column `heartbeat_runs.native_source_cursors` (`jsonb`, `{"<source instance id>": <seq>}`). Migration `0479` is `ADD COLUMN` only and classifies as `online_compatible`. - The run lock read of a native append also reads the cursor of its source. - When the event sequence is at most cursor + 1, the append statement has no `retained` CTE. It moves the cursor in the UPDATE that reserves the sequence, and the receipt uses the cursor. - Every other case (no cursor, a gap, or a cursor behind the stored events) runs the earlier recount. In the same UPDATE it stores the cursor when the source has no gap, and removes it when the source has a gap. So the event that fills a gap recounts. - The cursor is a lower bound. A writer that does not keep it (the previous release during a deploy overlap, or `NativeRunCoordinatorStore`) can only make it lag. The next out-of-order event then recounts and corrects it. ## Verification - `cd server && npx vitest run src/__tests__/heartbeat-run-event-atomic-append.test.ts src/__tests__/heartbeat-run-event-sequencing.test.ts` passes (19 tests). - Red/green: before the change, 3 tests failed: the two new tests and the updated lock-read statement test. After the change, all pass. - New: "keeps the source cursor on the run so an in-order append does not count the run's events" checks that the append statement has no `count(` and that a replay returns the cursor. - New: "recounts a source whose run has no cursor or a cursor behind its stored events" covers rows saved before the change, rows from a writer that does not keep the cursor, a gap, and the event that fills the gap. - Focused related tests: `paperclip-control-plane-port.test.ts`, `native-observer-replay`, `native-event-boundary-golden`, `chat-native-progress-work`, `live-recovery-work`, `native-interaction-bridge`. - `pnpm check:module-boundaries` passes. `pnpm verify` returned exit 2 (broader CI coverage required) because of local benchmark scripts that are not in this pull request. Required CI supplies the broad coverage. - Append cost on a run with many events (local embedded PostgreSQL, 1,000 in-order appends, busy machine, load average about 20–40): | Events already in run | Before p50 / p90 | After p50 / p90 | | --- | --- | --- | | 50,000 (run 1) | 10.4 / 15.8 ms | 1.7 / 3.7 ms | | 50,000 (run 2) | 12.9 / 21.6 ms | 3.3 / 5.9 ms | | 400 | 3.3 / 6.2 ms | 3.7 / 7.7 ms (noise) | - Statements per event do not change: BEGIN, run lock read, one append statement, COMMIT (4). The append statement no longer scans the source's events. - Load model (`scripts/benchmark-agent-scaling-load.ts` from #21418, `AGENTS=50 SECONDS=20`): the machine was too busy for a stable result. Deltas only: before 20,000 of 20,000 done at 3,999 statements/s. After: 13,796 and 14,817 of 20,000 in two runs. All sources: before 6,346 of 20,000 deltas done. After: 20,000 and 2,083 in two runs. A 20-second window gives only 400 events per run, so it cannot show this change. The long-run figures above are the evidence. ## Risks - Low. The column is nullable and the previous release does not read it. Runs that are in flight during a deploy have no cursor. Their first append recounts once and stores the cursor. - A stale cursor can only make the acknowledgement lag, never pass the stored events. Event rows are deleted only with their company or agent. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
0d832a02d3 |
perf(ci): shorten the general server and chat test lanes (#21393)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Every pull request runs the `PR` CI workflow before it can merge > - The `General tests (server (N/12))` and `General tests (chat (N/3))` jobs finish last, so they set the wall-clock time of CI > - Before this change, server shards took 9.5 to 11.7 minutes and chat shards took 6.4 to 9.6 minutes; the target is 7 minutes or less > - Measurement shows that the chat lane was unbalanced and that the server lane is limited by CPU on the 4-vCPU runners > - This pull request balances the chat lane by recorded test time, runs three chat partitions per job, and takes general server weights from PR runs > - The benefit is a chat lane under 7 minutes and measured evidence for the shard count that the server lane needs ## Linked Issues or Issue Description **What existing behavior does this improve?** The PR CI general server and chat test jobs. They are the slowest jobs of every pull request. **Subsystem affected** CI test scheduling: `scripts/run-vitest-stable.mjs`, `scripts/test-line-shard.mjs` and `scripts/ci/refresh-test-durations.mjs`. **Current behavior** Baseline: green `PR` runs [43437558012](https://github.com/paperclipai/paperclip/actions/runs/43437558012) and [43441184316](https://github.com/paperclipai/paperclip/actions/runs/43441184316), all on m7i-flex.xlarge (4 vCPU, 16 GB). - Server shards: 9.5 to 11.7 job minutes, 502 to 654 s test step, effective file concurrency 2.5 to 2.9 of 3 workers. Vitest reports `tests 61-68%, import 25-31%, transform 6-7%, setup 1%`. Each shard sums 1,410 to 1,765 s of file time. The longest file is 303 s (`deferred-execution-receipt-work.test.ts`), so the floor is total work divided by workers, not one file. - Chat shards: 9.3 to 9.6, 7.6 to 7.8 and 6.4 to 6.5 job minutes. Each job ran two partitions of `chat-channels.integration.test.ts`. The partitions were balanced by collected-case count, but one `it.each` line can run many cases. One of six partitions recorded 532 s of test time against a 377 s mean. **Proposed behavior** - Chat partitions keep each source line whole and balance by recorded time per collected entry. - Each chat job runs three partitions in place of two. - General server weights come from the server jobs of merged PR runs, which run files with the same concurrency as the lane they place. **Reason and benefit** The slowest job sets the CI wall-clock time for every pull request. The chat lane goes from a 9.3-9.6 minute maximum to 6.5-6.8 minutes. ## What Changed - `scripts/test-line-shard.mjs`: `partitionTestLines` takes optional recorded durations. With durations, it balances source lines by recorded time; entries without a record take the median. Without durations, the behavior is unchanged. - `scripts/chat-shard-durations.json` (new): recorded time per collected chat entry, from the CI profile records of PR run [43444854171](https://github.com/paperclipai/paperclip/actions/runs/43444854171). 926 of 928 collected entries are measured; the other two are the bogus collection entries that the launcher already drops. - `scripts/ci/refresh-chat-shard-durations.mjs` (new): builds that manifest from downloaded `ci-profile-*` artifacts. Each executed case maps to the collected `it`/`it.each` entry that registers it. A case without an entry fails the refresh. - `scripts/run-vitest-stable.mjs`: a sharded chat job runs three partitions in place of two, and the chat launcher passes the recorded durations. A chat job collects the suite once with `vitest list` in place of once per partition, and the per-partition filter checks run at the same time. Before, each partition ran two blocking collections of the 86,000-line file one after another. The server worker count stays at three. - `scripts/ci/refresh-test-durations.mjs` and `scripts/ci/pr-run-durations.mjs`: the weekly refresh reads general server weights from the two newest merged-PR runs. Each run must have the full server shard count from `.github/ci-task-matrix.json` and cover at least 90% of the lane. Serialized weights still come from master Cloud readiness runs. - `scripts/general-server-shard-durations.json`: refreshed with the new source (PR runs 43439145752 and 43439279537). - Tests: `scripts/__tests__/run-vitest-stable-shard.test.mjs`, `scripts/ci/test-selection-pr-timings.test.mjs` and `server/src/__tests__/vitest-chat-shards.test.ts` cover the weighted partition, the entry mapping, the manifest format, the PR-run collection rules and the three-partition chat launcher. - `doc/DEVELOPING.md`: describes the three chat partitions, the chat weights and how to refresh them, and the new source of the server weights. ## Verification Experiments ran in this PR's own CI with a temporary resource sampler (removed before review). | Setting (run) | Server step vs. same shard's baseline | CPU busy | Max memory used | Result | |---|---|---|---|---| | 3 workers (43444854171, shards 1-4) | +8% (profiling overhead) | 62-73% | 6.8 GB | 1 flaky retry | | 4 workers (43444854171, shards 5-8) | -4% | 82-86% | 8.2 GB | clean | | 5 workers (43444854171, shards 9-12) | -10% | 70-93% | 9.5 GB | 1 hard failure: `decision-models.test.ts` timed out at 15 s twice | | 4 workers (43450469416) | mixed m5a/m5n/m6i runners | 78-89% | 7.7 GB | 1 hard failure: `workspace-recovery-warm-handoff.test.ts` timed out at 30 s on m5a | The server lane is CPU bound: at four workers the CPU is 82-89% busy and wall time improves by only about 10%. Five workers fail tests. Memory is not the limit (no swap, no memory pressure, at least 6 GB free). Node's compile cache and Postgres `fsync=off` showed no attributable gain (import share stayed 29-34%; `fsync=off` cut iowait from 2-4% to 0.2-0.7% of CPU time), so neither is in this PR. Final configuration (server: 3 workers with refreshed weights; chat: 3 weighted partitions per job), job minutes / test-step seconds / effective concurrency: | Shard | Baseline 43437558012 | Baseline 43441184316 | A: 43465156503 attempt 1 | B: attempt 2 | C: attempt 3 | |---|---|---|---|---|---| | server 1/12 | 11.0 / 609 / 2.81 | 10.2 / 562 / 2.82 | 10.1 / 535 / 2.88 | 11.6 / 615 / 2.86 | 11.3 / 600 / 2.86 | | server 2/12 | 10.2 / 567 / 2.71 | 10.9 / 607 / 2.79 | 9.7 / 510 / 2.85 | 8.9 / 466 / 2.86 | 11.9 / 635 / 2.83 | | server 3/12 | 10.9 / 609 / 2.88 | 10.9 / 601 / 2.86 | 9.4 / 498 / 2.81 | 11.7 / 623 / 2.80 | 20.3 / 1109 / 0.00 | | server 4/12 | 11.0 / 613 / 2.77 | 11.2 / 622 / 2.84 | 11.3 / 602 / 2.84 | 9.3 / 487 / 2.83 | 12.5 / 676 / 2.84 | | server 5/12 | 10.1 / 555 / 2.83 | 9.9 / 544 / 2.84 | 10.2 / 542 / 2.85 | 11.6 / 618 / 2.82 | 11.9 / 640 / 2.84 | | server 6/12 | 9.9 / 551 / 2.85 | 10.4 / 579 / 2.85 | 9.8 / 516 / 2.69 | 9.1 / 480 / 2.68 | 9.2 / 480 / 2.67 | | server 7/12 | 10.8 / 596 / 2.84 | 10.1 / 558 / 2.86 | 10.8 / 575 / 2.80 | 11.8 / 631 / 2.80 | 20.8 / 1129 / 2.69 | | server 8/12 | 11.7 / 654 / 2.62 | 11.2 / 624 / 2.56 | 9.8 / 513 / 2.83 | 11.2 / 589 / 2.82 | 19.4 / 1059 / 2.40 | | server 9/12 | 9.7 / 533 / 2.85 | 9.7 / 533 / 2.84 | 11.5 / 615 / 2.68 | 9.8 / 515 / 2.66 | 13.0 / 703 / 2.68 | | server 10/12 | 9.8 / 540 / 2.79 | 9.5 / 502 / 2.81 | 10.6 / 561 / 2.84 | 11.8 / 625 / 2.83 | 9.3 / 488 / 2.83 | | server 11/12 | 10.9 / 605 / 2.83 | 11.3 / 627 / 2.75 | 10.3 / 545 / 2.75 | 9.5 / 498 / 2.72 | 20.3 / 1107 / 0.00 | | server 12/12 | 10.6 / 592 / 2.50 | 11.7 / 645 / 2.53 | 9.6 / 503 / 2.81 | 8.9 / 468 / 2.82 | 19.7 / 1065 / 2.70 | | chat 1/3 | 9.6 / 528 / 1.56 | 9.3 / 511 / 1.58 | 6.6 / 310 / 2.69 | 5.7 / 272 / 2.65 | 6.8 / 331 / 2.69 | | chat 2/3 | 7.8 / 418 / 1.74 | 7.6 / 408 / 1.75 | 6.3 / 305 / 2.57 | 6.5 / 311 / 2.58 | 5.5 / 260 / 2.58 | | chat 3/3 | 6.5 / 337 / 1.74 | 6.4 / 333 / 1.73 | 6.0 / 285 / 2.65 | 5.4 / 258 / 2.68 | 5.8 / 262 / 2.69 | Summary: chat maximum 9.3-9.6 min before, 6.6 / 6.5 / 6.8 min in A / B / C. Server maximum 11.7 min before, 11.5 / 11.8 min in A / B; the server worker setting is unchanged, so its run-to-run spread is mostly runner type (m8i.xlarge shards took 8.9-9.8 min, m6a.xlarge 11.9-13.0 min). Runners: A all m7i.xlarge; B m8i/m6i; C m6a/m6in/m8i/m5a. In C, the five server shards on m5a.xlarge summed 2,545-3,037 s of file time against about 1,700 s elsewhere; three reached the 20-minute job limit and two failed tests on 15 s timeouts. The server lane settings in this PR are the same as master's, so this is a fleet finding: m5a.xlarge cannot run a server shard inside the job limit (follow-up for the fleet configuration, outside this PR). Flakiness of the final setting: the nine chat jobs in A, B and C had no failure and no retried test. Server shards in A and B had no failure and no retried test. Before the last commit (single chat collection), three runs of 43456289623 had chat at 6.7-7.5 min with no chat retries; server retries there (2 in one run, 1 in another) were on the unchanged three-worker server setting. Local checks (correctness only): - `node --test scripts/__tests__/run-vitest-stable-shard.test.mjs scripts/ci/test-selection-pr-timings.test.mjs scripts/ci/test-selection-timings.test.mjs`: 68 passed. - `pnpm exec vitest run --project @paperclipai/server server/src/__tests__/vitest-chat-shards.test.ts`: passed. - `pnpm verify` exits 2 (global CI input changed), so the required CI checks supply the broad coverage. ## Risks - Three chat partitions per job use more memory: the peak was 11.4 GB of 16 GB, with at least 4.2 GB free and no memory pressure. CPU was 55-63% busy. - Stale chat weights only change balance, never which tests run. Shard membership is still checked with `vitest list` before each run. - The weekly refresh now downloads general server logs from merged-PR runs. Runs that selected a subset of files are skipped before download because their shard count is smaller. - The server lane is still above 7 minutes. See the remaining floor below. **Remaining floor and shard-count recommendation (for a follow-up under `.github/`)** A server shard sums about 1,600 s of file time, and 3 workers on 4 vCPUs give at most about 2.8 effective concurrency, so the test step is about 560-640 s. Job overhead is about 50 s. A job of 7 minutes needs a test step of about 360 s, so about 1,000 s of file time per shard. The current 19,200 s of general server file time therefore needs about 19-20 shards of 4 vCPUs at 3 workers. More workers on the same runners do not help, because the CPU is already the limit. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use (shell, GitHub CLI) in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
0199c963e2 |
feat(apps): ship the redesigned sign-in step for a pasted MCP server (#21469)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Apps lets an operator connect a remote MCP server by pasting its
address ("Connect your own MCP server")
> - Step 2 of that flow put every sign-in choice in an "Advanced
authentication" box with wrapped pill buttons and a hint paragraph
> - The box hid the choice behind a vague label, and its shape did not
match the access line ("Connects for everyone… Change") right below it
> - The owner approved a redesign: a stated sign-in default with a
Change link, and five options with their fields directly below each
option
> - This pull request wires that redesign into the real screen, removes
the old step, and updates copy that named the removed box
> - The benefit is a screen that reads as two stated answers and one
action, with the same default path (paste the address, press Check link)
## Linked Issues or Issue Description
No public issue exists. Enhancement:
**What existing behavior does this improve?**
The sign-in section of the "Connect your own MCP server" step in Apps.
**Subsystem affected**
UI: Apps connection setup (`ui/src/features/connections`). Small copy
changes in the server OAuth client registration message and docs.
**Current behavior**
Step 2 shows an "Advanced authentication" collapsible with five wrapped
pill buttons and a hint paragraph below them. The fields for the chosen
mode appear further down. Guidance banners tell the operator to look
"under Advanced authentication". The page also shows the "Unverified
server" badge twice (header and body). The stepper reads "Pick app · Add
your key", even when the server needs no key.
**Proposed behavior**
Step 2 states the sign-in choice in one line ("Paperclip asks the server
how to sign in.") with a Change link. Change shows five radio cards: Let
Paperclip check, Key or token, Browser sign-in, Custom headers, No
sign-in needed. The fields for the selected option are directly below
it. Done collapses the list to a one-line summary (for example "Signs in
with 1 custom header."). The list stays open while the chosen option
still needs a value. Client ID and secret are behind "Use your own
client ID" unless they have values or the server asked for them. The
stepper reads "Pick app · Connect".
**Reason and benefit**
The choice is visible as a stated default in the same shape as the
access line. Each option keeps its fields next to it. No copy points at
a box that does not exist.
**Breaking changes**
None. The five auth modes and their request payloads do not change.
**Additional context**
Related open PRs change server behavior for the same flow. They are not
duplicates. Refs #15192, Refs #15450.
## What Changed
- `ui/src/features/connections/GenericMcpConnectStep.tsx`: new step
component (same props as the old `LinkConnectStep`). It uses stable
field ids `generic-mcp-key`, `generic-mcp-client-id`,
`generic-mcp-client-secret` and a `data-testid` on the sign-in
Change/Done link.
- `ui/src/features/connections/ConnectionSetupFlow.tsx`: render
`GenericMcpConnectStep`; delete `LinkConnectStep`,
`GENERIC_AUTH_MODE_OPTIONS`, `SegmentedOption` and unused imports;
change the pasted-link stepper label from "Add your key" to "Connect"
(`STEP_LABELS` is used only by the pasted-link flow; curated apps keep
their own `["Add your key"]`).
- `ui/src/pages/apps/generic-mcp-connect.ts`: `oauth_challenge` and
`oauth_manual_client_required` guidance now say "below" instead of
"under Advanced authentication".
- `server/src/services/tool-access/oauth/client-registration.ts`: the
manual-client message no longer names the removed box.
- `doc/connections/GENERIC-REMOTE-MCP.md`: describe the sign-in line,
Change, and the five options.
- Comments in `packages/shared` and `server/src/services/tool-access.ts`
reworded. `tests/runner-e2e/source-sdk-public-inputs.json` regenerated
for the two shared files (blob hashes only).
- `ui/storybook/stories/connection-setup/byo-mcp-sign-in.stories.tsx`:
14 stories for the shipped component; annotation is now `current` /
`production`.
- Tests: `AppsConnect.test.tsx` generic MCP block uses the sign-in
toggle and radio options; new tests for the collapsed summary, the
open-while-empty-key rule, and a single "Unverified server" label. New
`GenericMcpConnectStep.test.ts` unit-tests `genericMcpAuthSummary`.
Before: "Advanced authentication" box with pill buttons and a hint;
fields below the pills; two "Unverified server" badges; stepper "Pick
app · Add your key".
After: one sign-in line with Change; five radio cards with fields under
the selected card; one "Unverified server" badge in the header; stepper
"Pick app · Connect". Storybook: `byo-mcp-sign-in--choosing`,
`byo-mcp-sign-in--server-asked-for-key`.
## Verification
- `cd ui && pnpm exec vitest run src/pages/apps/AppsConnect.test.tsx
src/pages/apps/generic-mcp-connect.test.ts
src/features/connections/GenericMcpConnectStep.test.ts
src/features/connections/ConnectionSetupFlow.architecture.test.ts
src/features/connections/ConnectionSetupFlow.oauth.test.ts`: 5 files,
300 tests pass.
- `cd ui && node ../scripts/run-tsc.mjs -b`: pass.
- `pnpm -s typecheck` in `packages/shared` and `server`: pass.
- `pnpm check:token-gates`: all gates clean.
- `node scripts/storybook-catalog.mjs`: pass (generated indexes not
committed).
- `pnpm verify`: exit 2 (broader verification required, because
`doc/connections/GENERIC-REMOTE-MCP.md` is a global CI input). Required
CI supplies that coverage. The focused files above were rerun on the
final revision after the rebase.
- Headless Playwright against the Storybook dev server: the Default,
Choosing and Server-asked-for-key stories render the new step, the new
guidance copy, and the "Pick app · Connect" stepper.
## Risks
- Low risk. UI change on one screen; request payloads
(`genericConnectPayload`) do not change.
- Tests that click the first collapsed "Change" button now skip the
sign-in toggle, because the access line also has a "Change" button.
- The server message for `oauth_manual_client_required` changes text. No
code matches on the text; the client uses the error code.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, headless Playwright).
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
|
||
|
|
e9d7895648 |
fix(recovery): start an overdue saved-work recovery instead of looping on no pending path (#21478)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - When a run stops before its sandbox files are saved, Paperclip holds
the task and recovers the files first. A recovery queue does this work.
> - The queue runs two attempts at a time for the whole instance. A
remote attempt can take many minutes.
> - On staging, 29 recoveries waited with 0 attempts. The oldest waited
since 15:01Z. One task waited 3 h 33 min for its single attempt.
> - During that time the task said "Recovering saved work…", but the
assigned-work invariant saw no pending path. The sweep sent a
continuation wake every few minutes. The hold refused each wake, and the
activity log showed "could not start yet".
> - This pull request makes the queued recovery the task's pending path
for a bound. After the bound, the sweep starts the recovery itself
instead of sending a wake that the hold refuses.
> - The benefit: a held task gets its files recovered and continues
without a person, and the sweep stops its refused-wake loop.
## Linked Issues or Issue Description
**What happened?**
A scheduled task ran a legacy retry on a Daytona sandbox. Setup failed
with `setup_failed` ("remote_workspace_operation_timed_out: capture
(configured timeout 300000ms)"). Paperclip held the task for saved-work
recovery (`legacy_execution_requires_reconciliation`, resolved, replay
blocked, system recovery `scheduled`, 0 attempts). After 45 minutes the
recovery had not started. The task showed "Recovering saved work…" with
no Retry. The assigned-work sweep logged `issue.continued_automatically`
with outcome `not_started` and violation `no_pending_path` at 17:58,
18:02, 18:10 and 18:25 UTC.
**Expected behavior**
The recovery proceeds by itself and the task continues. If the recovery
cannot finish, the task shows a Retry that works. "Recovering…" never
shows with nothing behind it.
**Steps to reproduce**
1. A legacy run with a retained remote workspace fails during setup, and
its saved-work hold is adopted by system recovery.
2. The recovery queue does not reach the hold (it has two slots, and
they are busy).
3. The assigned-work sweep checks the task 10 or more minutes later. It
finds `no_pending_path` and sends a wake. The hold refuses the wake.
This repeats until the continuation cap.
The regression test
`server/src/services/saved-work-recovery-overdue.test.ts` reproduces
this state on real rows.
**Paperclip version or commit**
`master` at `c6301c92ff` (staging, 2026-11-13).
**Agent adapter(s) involved**
Not adapter-specific (core bug). Seen with a Daytona sandbox on the
legacy runtime.
## What Changed
- `assigned-work-invariant.ts`: new pending intent
`saved_work_recovery`. A saved-work recovery that the queue still owes
counts as the task's pending path while an attempt runs, while its next
attempt is scheduled, or for `SAVED_WORK_RECOVERY_START_BOUND_MS` (10
minutes) after it became due.
- `assigned-work-invariant.ts`: new violation
`saved_work_recovery_overdue`, used when that bound passes. It comes
before the `no_pending_path`, `retry_offered` and blocked checks, so the
sweep never sends a wake that the hold refuses.
- `assigned-work-sweep.ts`: the sweep loads the fact with the same
eligibility predicate the recovery worker uses. For the overdue
violation it calls `startSavedWorkRecovery` and records no continuation
activity.
- `workspace-recovery.ts`: `startOverdueWorkspaceRecovery` starts one
attempt outside the queue's two slots, with at most two such attempts
per process. It skips runs that are already in flight and uses the same
ownership lock and attempt bookkeeping as the queue. The queue skips
runs that this path started. `recoverRunAction` moved to module scope.
Its "Retained workspace remains pending" warning now logs the error.
- `heartbeat.ts` and `recovery/service.ts`: wire the dependency.
- The sweep returns the end of the bound as the task's re-check
deadline, so the overdue start does not depend on another notification.
## Verification
- New `server/src/services/saved-work-recovery-overdue.test.ts` (real
Postgres, recovery fixture with a mocked sandbox):
- Overdue hold: the sweep starts the recovery and does not call
`enqueueWakeup`. No continuation activity is written. The system
recovery reaches `complete`. The next sweep records a fresh
continuation, and `deliverReconciledExecutions` starts a successor run.
- Hold within the bound: verdict `ok / pending_intent /
saved_work_recovery`. No wake is sent and no attempt starts.
- A second start for the same run returns `in_flight`. Exactly one
attempt is recorded, and a completed hold returns `not_eligible`.
- Red on the old invariant and sweep, with `no_pending_path` and
`enqueue_refused`, the same as staging. Green with this change.
- `server/src/services/recovery/assigned-work-invariant.test.ts`: 54
pass, with new cases for the bound, a running or scheduled attempt, a
stale attempt, and a pending question.
- `server/src/__tests__/assigned-work-invariant.test.ts`: 31 pass.
- `server/src/services/workspace-recovery-passive-fairness.test.ts`:
passes.
- `tsc --noEmit -p server/tsconfig.json`: clean.
## Risks
- A sweep-started attempt can run beside the queue's two attempts. That
adds up to two more concurrent recovery attempts per process, each with
its own database connection while it holds the ownership lock. Each
attempt for a run still takes that run's advisory lock, so two servers
cannot run the same recovery at once.
- The 10-minute bound is new. A queue that is slow but working now gets
help after 10 minutes. It does not get the hours it took on staging.
- Out of scope, reported for follow-up: why the queue was so slow on
staging (two slots for the whole instance, attempts that take minutes),
and why the setup capture hit its 300 s timeout. Server logs were not
available from this session.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used in Claude Code
with tool use (shell, browser reads of the staging API, local test
runs).
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
f58bbefc4e |
fix(ui): group failed-query Sentry reports by status and query name (#21475)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The browser app can report errors to Sentry. A final query error goes to Sentry when it is not an outage, a denial, or a missing item. > - Every failed API request throws an `ApiError` from the same frames in `api/client.ts`. > - Sentry groups errors by stack. Thus all unrelated server failures go into one issue, titled "ApiError: Internal server error". > - The report has no route, no query name, and no status. Breadcrumbs and URLs are removed for privacy. A person cannot find which endpoint failed. > - This pull request tags each failed-query report with its HTTP status and the static name of its query key. It also sets the Sentry fingerprint from these two values. > - The benefit: each failing endpoint gets its own Sentry issue, and a person can connect it to the server error. ## Linked Issues or Issue Description **What happened?** One browser Sentry issue collected unrelated server 500 errors from different pages and environments. The events had no route or query name. A person could not connect an event to a server error. **Steps to reproduce** 1. Turn on browser error monitoring with a Sentry DSN. 2. Make two different queries fail with a 500 response, for example the issues list and the agents list. 3. Look at Sentry. Both events are in one issue with the title "ApiError: Internal server error". Neither event shows which query failed. **Expected behavior** Each failing query has its own Sentry issue. The event shows the HTTP status and the static query name. It shows no IDs, refs, or filters. **Environment** The hosted browser app, staging and production builds. I searched open pull requests for duplicates. I found no pull request that changes browser query-error grouping. ## What Changed - `ui/src/lib/browser-error-context.ts`: add `queryKindFor`. It keeps only the first query-key part, and only when it is a lowercase word list such as `issues` or `agent-commentary`. Other values become `other`, so an ID, a ref, an email, or a typed value is never sent. - `ui/src/lib/browser-error-context.ts`: add `buildQueryErrorContext`. For an error with an HTTP status, it sets the `query_kind` and `api_status` tags and the fingerprint `["api-error", status, queryKind]`. For an error without a status, it sets only the `query_kind` tag and keeps default stack grouping. - `ui/src/lib/sentry.ts`: add `captureQueryException`. It uses the same serialized queue as `captureBrowserException`. Both functions now share one private capture step. - `ui/src/lib/query-client.ts`: `reportError` now also receives the query key. - `ui/src/main.tsx`: the query client reports through `captureQueryException`. - Tests for key sanitizing, the fingerprint, the reporter argument, and the gate call. ## Verification - Red before the fix: the 6 new assertions fail on the old source (`queryKindFor`, `buildQueryErrorContext` and `captureQueryException` do not exist, and `reportError` gets no key). - Green after the fix: `cd ui && npx vitest run src/lib/sentry.test.ts src/lib/browser-error-context.test.ts src/lib/query-client.test.ts` passes 3 files and 78 tests. - The privacy test makes sure that `company-uuid` and `PAP-1` from later key parts do not go into the Sentry call. It also makes sure that UUID, ref, email, and long heads become `other`. - `ui` typecheck: no errors in the changed files. The local install was filtered to the UI package, so unrelated packages (`plugin-sdk` build output, runner dependencies) could not resolve. Required CI supplies the full typecheck. - I did not run browser e2e suites. This change does not touch them. ## Risks - Low risk. Only the grouping and tags of browser query-error reports change. The app does not change what it shows to users. - Sentry opens new issues for future query errors, one for each status and query name. The old catch-all issue gets no new events. - A query key with a dynamic first part becomes `other`. Those errors still group together, but they keep the status tag. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), in Claude Code with tool use, repository inspection, and shell code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
ef2a49b6df |
fix(daytona): bound the duplex channel close so a stalled kill cannot retire the worker (#21471)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Cloud agent runs use the Daytona sandbox provider plugin. One shared plugin worker process serves all Daytona calls on a server. > - The host closes a duplex channel through the worker. The host waits 10 seconds for the close acknowledgement. When the acknowledgement is late, the host retires the whole worker with SIGKILL. > - The worker close waits for the remote PTY kill before it releases the socket. The Daytona SDK sends that kill as a toolbox request with a 24-hour default timeout. A stalled sandbox can hold it open for longer than 10 seconds. > - Then the host kills the shared worker. Every other call in flight on that worker fails with `Worker process exited (code=null, signal=SIGKILL)`. This includes other runs' workspace preparation and restore. > - This pull request limits the wait for the remote kill to 5 seconds. Then the worker releases the socket and acknowledges the close. > - The benefit is that one slow sandbox no longer stops unrelated runs on the same server. ## Linked Issues or Issue Description **What happened?** On a hosted staging server, the host logged `duplex channel close not acknowledged; retiring worker` six times in about 90 minutes. Each time, the Daytona worker exited with SIGKILL. Each time, all in-flight calls on that worker failed. Runs in workspace preparation failed with `setup_failed` and `Worker process exited (code=null, signal=SIGKILL)`. Several runs failed together in each burst. **Expected behavior** A slow close of one duplex channel does not stop calls that belong to other channels or other runs. **Steps to reproduce** 1. Open a duplex channel on a Daytona lease. 2. Make the Daytona PTY kill request stall (the SDK default request timeout is 24 hours). 3. Close the channel from the host. The worker does not acknowledge within 10 seconds. 4. The host retires the worker with SIGKILL. All other pending calls fail. **Relevant logs or output** ``` info duplex channel close not acknowledged; retiring worker info retired worker process exited code=null signal=SIGKILL willRestart=true JsonRpcCallError: Worker process exited (code=null, signal=SIGKILL) ``` **Additional context** The login PTY close does not have this problem. It only does the local socket disconnect. A kill that rejects already gets a close acknowledgement, because the session close ignores kill errors. This change gives a slow kill the same result. No related public PR exists. I searched open and closed PRs for this failure. ## What Changed - `duplex-command-stream.ts`: `close()` waits for the remote `kill()` for at most `DUPLEX_CHANNEL_CLOSE_KILL_TIMEOUT_MS` (5 seconds). Then it always releases the socket with `disconnect()`. The kill continues in the background. A kill that answers in time keeps the old order: kill, then disconnect, then the acknowledgement. - `duplex-close-deadline.test.ts` (new): regression tests at the session close and at the worker `onDuplexChannelClose` boundary, and a check that the deadline stays well inside the host deadline. ## Verification - Red before the fix: with the old `duplex-command-stream.ts`, `acknowledges a bound close inside the host deadline when the remote kill never settles` fails (no acknowledgement after 9 seconds), and the session close test times out. - Green after the fix: `pnpm --dir packages/plugins/sandbox-providers/daytona exec vitest run --config vitest.config.ts src/duplex-close-deadline.test.ts src/duplex-command-stream.test.ts src/plugin.test.ts` passes 453 of 453. This includes the existing tests `joins pending teardown for concurrent closes while all channel authority stays revoked` and `does not turn a rejected retired close into an acknowledgement`. - The safety case `still waits for a kill that answers inside the deadline before it releases the socket` passes before and after the fix. - `tsc --noEmit` for the Daytona plugin passes. - In the full Daytona plugin suite, two GNU tar tests in `file-sync.test.ts` fail in my sandbox. They also fail on unchanged `master` in the same sandbox, so they are environment failures. CI covers them. - I did not run a live staging workflow. After the deploy, the staging logs must show no new `duplex channel close not acknowledged; retiring worker` lines from slow kills. ## Risks - Low risk. The change is in one Daytona plugin function. - After a kill timeout, the gateway process can stay alive in the sandbox until the background kill completes or the lease teardown stops the sandbox. The socket is closed, so no bytes can move on the channel. The route stays retired, so the host route cannot open again. This is the same state as when a kill rejects today. - The host contract does not change. A malformed or mismatched acknowledgement still retires the worker. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com> |
||
|
|
7773b52f05 |
fix(codex): preserve sandbox certificate trust in Codex shell commands (#20364)
<!-- Written in ASD-STE100 style: short sentences, active voice. --> ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The Paperclip Runner and the Codex adapters run agent shell commands inside a sandboxed Codex session with a strict environment allowlist > - The controller builds `shell_environment_policy.include_only` before the sandbox injects certificate-trust variables such as `SSL_CERT_FILE` and `GIT_SSL_CAINFO` > - The allowlist drops the injected variables, so managed `git` and `gh` commands cannot verify HTTPS against a runtime-provided CA > - This pull request allows the certificate-trust variable names through every environment policy stage, from the Rust process supervisor to the shell allowlist > - The benefit is that managed `git` and `gh` work again in sandboxes that require a runtime CA, while provider-credential isolation and the bounded allowlist stay in place ## Linked Issues or Issue Description - Fixes: #20019 - Refs #20038 — community pull request for the same defect. This change reviews the approach independently. The commit credits the community author as co-author. ## What Changed - Add `CERTIFICATE_ENVIRONMENT_KEYS` (`SSL_CERT_FILE`, `SSL_CERT_DIR`, `GIT_SSL_CAINFO`, `NODE_EXTRA_CA_CERTS`, `DENO_CERT`, `REQUESTS_CA_BUNDLE`, `CURL_CA_BUNDLE`) to `packages/paperclip-runner/src/configured-environment.ts` - Native Codex shell policy (`codex-security-config.ts`): always put the certificate names in `include_only`; set inheritance to `"all"` with `ignore_default_excludes=true`, bounded by the explicit allowlist - Pass the certificate names through the app-server environment filter, the ACPX spawn environment filter, the ACPX runtime sandbox `include_only`, the runner platform environment keys, and the Rust process supervisor base key list - Legacy and ACPX-engine Codex shell allowlists (`packages/adapter-utils/src/codex-shell-environment.ts`): always include the certificate names - Add a synthetic private-CA HTTPS journey test: a real `git ls-remote` fails TLS verification without the injected CA and succeeds with it, through the policy-filtered child environment - Document the contract in `doc/sandbox-shell-environment.md` and link it from `doc/DEVELOPING.md` ## Verification - `pnpm --filter @paperclipai/paperclip-runner exec vitest run src/drivers/codex/codex-security-config.test.ts src/configured-environment.test.ts src/drivers/codex/codex-shell-certificate-trust.test.ts src/drivers/codex/codex-app-server-driver.context-control.test.ts src/drivers/acpx/runtime-sandbox.test.ts` — 104 tests pass - `pnpm --filter @paperclipai/adapter-utils exec vitest run src/codex-shell-environment.test.ts src/acpx-engine/execute.test.ts` — 270 tests pass - `pnpm --filter @paperclipai/adapter-codex-local exec vitest run src/server/execute.test.ts` — 10 tests pass - Codex driver lifecycle, conformance, recovery, and boundaries suites pass (103 tests); environment-builder suites pass (307 tests) - Red proof: with only the source fix reverted, the new regressions fail. The journey test shows `GIT_SSL_CAINFO` is undefined in the shell environment, and `git` fails TLS verification against the private-CA fixture - `cargo check` passes for `paperclip-runner-core`; `rustfmt --check` passes for the edited Rust file - The journey test needs `git` and `openssl`; it skips when either tool is absent ## Risks - The native shell policy now always sets `shell_environment_policy.inherit="all"` with `ignore_default_excludes=true`. Before, it set `"none"` when no credentials or task keys were projected. The explicit `include_only` allowlist still bounds every inherited name, so no new secret names can cross - The allowlist grows by seven non-secret certificate-trust names. Their values point at CA files. The sandbox filesystem policy still controls access to those files; this change grants no filesystem access - No persisted run, session, or launch identity changes shape. Sessions saved by the previous release resume unchanged; the new policy applies when the next launch builds its arguments - Provider credentials keep their existing exclusions at every stage ## Model Used - Claude Fable 5 (Anthropic, model ID `claude-fable-5`), extended thinking, agentic tool use, run through Claude Code. The implementation was written and reviewed independently against the community design in #20038; the community author is credited as co-author in the commit. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green (pending: checks run after this PR opens) - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups (pending review) - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: everlastingcrown <everlastingcrown@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>canary/v2026.1113.0-canary.11 |
||
|
|
d018a9d1cd |
fix(queue): retain chat bindings on resolved card continuations (#20825)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - A task can receive a card response while its agent runs.
> - The queue saves this response for the next turn.
> - Chat authorization requires the saved inbound message binding.
> - Queue promotion removed this binding when a prior turn received the
message.
> - This pull request retains live bindings for resolved card responses.
> - The next turn can check current chat access and continue the
approved work.
## Linked Issues or Issue Description
**What happened?**
An accepted plan card queued behind a chat run could start with a chat
source and no message IDs. Reviewed chat authorization then failed with
context_mismatch before provider work started.
**Expected behavior**
A resolved card must retain its live chat binding through queue
promotion. The new run must check current access. A consumed
message-only wake must not start another turn.
**Steps to reproduce**
1. Start a chat run with an inbound message.
2. Queue a card response with that message binding.
3. Complete the first run and release its queue.
4. Inspect the promoted context and check chat authorization.
Related work: #20689 cancels consumed message-only wakes. #19156
protects a successor checkout. This change retains the binding for an
independent card response.
## What Changed
- Retain delivered message bindings for resolved chat card responses
during queue promotion.
- Keep deleted, foreign-task, and self-authored message filters and
current chat authorization.
- Add a persisted queue regression and Slack/Discord
promotion-to-authorization checks, including access revocation.
- Document the queue behavior.
## Verification
- Before the fix, the persisted queue test failed because the promoted
context had no wakeCommentIds. Three existing tests passed.
- The first focused run passed 108 tests. The added Slack and Discord
checks passed after promotion and refused revoked access.
- Final head
|
||
|
|
b4861d5e37 |
fix(diagnostics): report Daytona acquisition state for runs retried as provider outages (#21476)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Before an agent starts on a sandbox environment, the host gets an environment lease. On Daytona, this creates a sandbox. > - When the create does not finish in time, the Daytona plugin records the failed phase, the elapsed time, the budget, and the Daytona sandbox state. #15736 and #15946 added these fields to the run failure report, so that operators can see where the acquisition stopped. > - #20857 changed the error code of these failures from `setup_failed` to `environment_provider_unavailable`, so that the host retries them. > - The run failure diagnostics read the acquisition fields only when the error code is `setup_failed`. Thus every Daytona create timeout now reaches the error report without its phase or provider state. > - On staging, more than 270 Daytona lease timeouts occurred in three days, and none of them shows the provider state. > - This pull request also reads the acquisition fields when the error code is `environment_provider_unavailable`. > - The benefit is that the error report shows again whether the sandbox was stuck in `creating`, in a snapshot state, or absent. This evidence is necessary to find the cause of the timeouts. ## Linked Issues or Issue Description Refs #20857, Refs #20828, Refs #15946, Refs #15736 **What happened?** A Daytona lease acquisition timeout is now classified as `environment_provider_unavailable` (#20857). The run failure report for this failure does not contain `environmentAcquisitionPhase`, `environmentAcquisitionElapsedMs`, `environmentAcquisitionBudgetMs` or `environmentAcquisitionProviderState`. **What did you expect?** The report contains the acquisition phase and the provider state, as it did for `setup_failed` runs before #20857. **Steps to reproduce** 1. Let a Daytona sandbox create pass its acquisition deadline. 2. The plugin returns "Daytona lease acquisition timed out; allocation cleanup is pending" with an acquisition diagnostic. 3. The host fails the run with `environment_provider_unavailable`. 4. Look at the `run_execution` context of the error report. The acquisition fields are not there. ## What Changed - `collectRunFailureDiagnostics` reads the private acquisition diagnostic for a setup failure with the error code `setup_failed` or `environment_provider_unavailable`. The other conditions do not change: the phase must be `setup`, and the diagnostic must belong to the same run and company. - A new test builds the real wrapper chain (lease failure, then provider failure, then the RPC error that holds the diagnostic). It checks that the fields are reported for the failed run, and that they are not reported for another run or for the execute phase. ## Verification - `cd server && npx vitest run src/services/__tests__/run-failure-diagnostics-provider-unavailable.test.ts` fails on master (the report has only `failurePhase`). It passes with this change. - `cd server && npx vitest run src/services/__tests__/run-failure-diagnostics-provider-unavailable.test.ts src/services/__tests__/run-failure-diagnostics.test.ts src/__tests__/environment-acquisition-diagnostics.test.ts`: 3 files, 139 tests pass. ## Risks Low risk. The change adds four bounded scalar fields to an error report. These fields already exist for `setup_failed` runs. The change does not alter retries, the error grouping, or the run result. ## Model Used Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code execution in an agent harness. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) |
||
|
|
89ab7e51ff |
fix(recovery): retain a failed run's sandbox in one lease write (#21474)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Agent runs execute in remote sandboxes. Each run holds an
environment lease row that points to its environment, task, workspace
and company
> - When a run fails before it copies its files back, Paperclip keeps
the sandbox for a file repair. It writes a stop-and-retain intent and a
repair-hold policy on the lease
> - The recorder wrote the same lease row two times in one transaction.
Postgres runs the foreign-key checks again on a row that the current
transaction already wrote, and these checks take `FOR KEY SHARE` locks
on the referenced rows
> - Other runs lock the shared environment row `FOR UPDATE` when they
acquire a lease. Then the second write waits, meets the 1 second lock
timeout, and the run fails with "Database query failed (55P03)"
> - This pull request writes the stop intent and the repair hold in one
update
> - The benefit is that a busy shared environment no longer fails runs,
and the file repair hold is recorded
## Linked Issues or Issue Description
**What happened?**
On staging, native OpenCode runs failed with `adapter_failed` and the
error "Database query failed (55P03)". The failed statement was `update
"environment_leases" set "lease_policy" = 'retain_on_failure',
"metadata" = "metadata" || {workspaceRestoreRecovery...} where ...
"status" = 'pending_cleanup'` in
`preserveLegacyWorkspaceRestoreSources`. The cause was `canceling
statement due to lock timeout`. The statement does not wait on the lease
row, because the transaction already holds it `FOR UPDATE`. It waits on
the foreign-key check `SELECT 1 FROM ONLY "public"."environments" x
WHERE "id" = $1 FOR KEY SHARE OF x`. Postgres runs this check because
the transaction wrote the same row one statement before, in
`prepareSandboxStopAndRetain`.
**What did you expect?**
The run records its workspace restore failure and keeps its sandbox for
repair, also when another run holds the shared environment row.
**Steps to reproduce**
1. Start a run with an active, ephemeral sandbox lease.
2. In another session, lock the lease's `environments` row with `SELECT
... FOR UPDATE` and keep the transaction open.
3. Record a workspace restore failure for the run
(`terminalizeLegacyExecution`, legacy or native
`recordRestoreFailureOnly`).
4. Before this change, the second lease write fails after 1 second with
55P03. The new test
`server/src/__tests__/legacy-workspace-restore-lock-contention.test.ts`
shows this for legacy and native runs.
No public issue exists. I searched open and recent pull requests for
this lock timeout and found no duplicate. #21071 bounds a different lock
wait (workspace source locks in run preparation) and does not overlap.
## What Changed
- `server/src/services/sandbox-stop-and-retain.ts`:
`prepareSandboxStopAndRetain` accepts an optional `retention` argument
(`leasePolicy` and extra `metadata`). The stop-and-retain update sets
these values in the same statement. Other callers do not change.
- `server/src/services/legacy-workspace-restore-recovery.ts`: the
active-source path passes the repair hold (`retain_on_failure` and
`workspaceRestoreRecovery` with `originalLeasePolicy`) to that update.
It no longer does a second update on the same row.
-
`server/src/__tests__/legacy-workspace-restore-lock-contention.test.ts`:
a regression test for legacy and native runs. Another session holds the
environment row `FOR UPDATE` while the run records its restore failure.
The test checks the run's recovery evidence and the lease policy,
status, stop intent and repair metadata.
## Verification
- `cd server && npx vitest run
src/__tests__/legacy-workspace-restore-lock-contention.test.ts`: both
cases fail on `master` with `canceling statement due to lock timeout` on
the `environments` `FOR KEY SHARE` check. Both cases pass with this
change.
- `cd server && npx vitest run
src/__tests__/legacy-workspace-restore-recovery.test.ts`: 73 existing
tests pass.
- Related suites pass (10 files, 485 tests):
`heartbeat-observed-workspace-preservation`,
`heartbeat-native-remote-failure-retention`, `live-recovery-work`,
`workspace-recovery-stop-proof`, `native-failed-workspace-recovery`,
`native-cancelled-workspace-preservation`,
`workspace-recovery-admission`, `native-workspace-reconstruction`,
`environment-retained-orphan-sandbox`, `abandoned-workspace-files-hold`.
- I did not complete a local server typecheck. The process ran out of
memory in the 10 GB sandbox. CI runs the typecheck on this head.
## Risks
- Low risk. The lease ends with the same status, policy and metadata as
before. The values are written in one statement instead of two. The
update keeps its ownership guards (status, provider, provider lease ID
and exact metadata).
- Other code paths can still write a lease row two times in one
transaction (for example the shutdown settlement path, which sets a
lease back to `active` before it records the restore failure). That path
handles 55P03 as a lock timeout and retries. This pull request does not
change it.
> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used in Claude Code
with tool use (shell, code execution, embedded Postgres tests, and
GitHub tools).
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
7866e9ef05 |
fix(acpx): admit a Claude tool call only for a tool use its turn announced (#21278)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Paperclip Runner runs Claude Code through the ACPX sidecar. Claude calls Paperclip tools through a Runner-owned MCP endpoint, the tool bridge. > - The bridge identifies a call by its JSON-RPC request id. That id does not say which turn sent the call. The sidecar binds a call to the turn that is active when the call arrives. > - Because of this, the Runner stops and starts the Claude process at each turn boundary. A late call from an earlier turn then cannot run in a later turn. This restart also stops all background work that Claude started. > - Claude Code already sends the missing identity. Each MCP `tools/call` has `_meta["claudecode/toolUseId"]`. It is the id of the ACP `tool_call` that the provider announces first, inside one turn. > - This pull request uses that id. The sidecar admits a Claude tool call only if the active turn announced its tool use. > - The benefit is that a call from an earlier turn is refused by its identity. This is the first step to keep the Claude process alive between turns. This pull request does not change the restart. ## Linked Issues or Issue Description No public issue exists. The issue is described here. Refs #19912 (the design for turn-scoped ACPX MCP authority), #12419 (the restart at turn start) and #20190 (the restart at turn end). This pull request is the bottom of a stack. #21274 is merged, so the base branch is `master`. It uses no code from #21274. The stack order lets a later pull request remove the direct gateway path after both. **What existing behavior does this improve?** How the Runner decides which turn a Claude tool call belongs to. **Subsystem affected** Paperclip Runner: the tool bridge and the ACPX sidecar, for the Claude provider only. **Current behavior** - The bridge keys a call by the JSON-RPC request id (`runner-tool-bridge.ts`). - The sidecar gives the call to the active turn (`waitForTool` in `acpx-runtime-sidecar.ts`). - After `session/cancel`, Claude Code does not stop an MCP request that is in flight. A test run showed two calls from two turns live at the same time on one MCP session. Request ids cannot tell them apart. **Proposed behavior** - The bridge can read a provider tool-use id from `params._meta` and give it to the handler. It keys replays by that id. - For Claude, the sidecar admits a call only when the turn event stream of the active turn contains the ACP `tool_call` with the same id, and no earlier call used that id. - The announcement and the call use different channels. If the call arrives first, the sidecar waits for the announcement for a maximum of 5 seconds. The wait stops when the turn ends or the call is cancelled. - A call with no id, an id from an earlier turn, an id that was never announced, or an id that was used before gets a tool error. There is no fallback. - The call id that the sidecar sends to runnerd is `tool-use:<id>` for Claude. **Reason and benefit** - A late call from an earlier turn cannot run in a later turn. The identity of the call prevents this, not only the process restart. - A later change can stop the restart between turns. ## What Changed - `packages/paperclip-runner/src/drivers/runner-tool-bridge.ts` - New option `providerToolUseIdMetaKey`. Without it the bridge does not change. - With it, the bridge reads `params._meta[key]`. It refuses a value that is not a bounded string. It gives a valid value to the handler as `providerToolUseId`. - The replay key is the tool-use id. A retry with a new request id replays the first result. The same id with different arguments is refused. - `notifications/cancelled` still finds the call by its request id. - `packages/paperclip-runner/src/drivers/acpx/claude-tool-use-admission.ts` (new): `ClaudeToolUseAdmission`. - `observe` records an id only from an event with `type === "tool_call"` and `tag === "tool_call"`. A `tool_call_update` does not count, so a late update about an old tool use cannot admit it. - `admit` applies the rule above. An id is used when it is admitted. Limits: 4,096 announcements for each turn and 8,192 admitted ids. At a limit, new calls are refused. - `packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts` - The sidecar creates the admission object only for `agent === "claude"` and sets the bridge option only for Claude. - `pumpTurn` gives each turn event to `observe`. `waitForTool` calls `admit` and then checks the turn and run again. - The internal `get_task_context` call for a completion continuation does not go through admission. - The Claude call id does not use the per-process namespace, because a tool-use id is unique. - No change to Rust, the sidecar contract, the `claude-agent-acp` patch, the server, or restart, park and turn lifecycle code. Other ACPX agents and Cursor Cloud use the same code path as before. Why 5 seconds: the measured time between the announcement and the call is 1.1 ms to 14.7 ms. The limit must also include queue and event-loop delay. 5 seconds is far above that, and a call that cannot be attributed still gets a fast answer. ## Verification Commands, from `packages/paperclip-runner`: - `npx vitest run src/drivers/acpx/acpx-runtime-adapter.claude-tool-use.test.ts src/drivers/acpx/claude-tool-use-admission.test.ts src/drivers/runner-tool-bridge.test.ts src/drivers/runner-tool-bridge.claude-tool-use.test.ts src/drivers/runner-tool-bridge.claude-schema.test.ts src/cli/acpx-runtime-sidecar.test.ts src/drivers/acpx/acpx-runtime-adapter.test.ts src/drivers/cursor-cloud/cursor-cloud-driver.test.ts`: `8 passed (8)` files, `384 passed` tests. - `npx tsc --noEmit -p tsconfig.json`: no errors. New tests: - **Real ACP runtime** (`acpx-runtime-adapter.claude-tool-use.test.ts`). It uses the real `openCodexAcpxRuntime`, ACPX 0.22, the pinned and patched `claude-agent-acp`, the pinned Claude Code client and a real tool bridge, against a local fake Anthropic API. - Turn 1: two parallel tool uses are admitted as `tool-use:<id>`. The model receives both results. The turn completes. - Turn 2 in the same session: a replay of a turn 1 id returns the cached result and does not dispatch again. The same id with different arguments is refused. `admit` refuses the old id. - In five runs each call arrived 6.9 ms to 13.2 ms after its announcement. No call waited. - **Qualification** (`runner-tool-bridge.claude-tool-use.test.ts`). The pinned Claude Code client sends `_meta["claudecode/toolUseId"]` on each `tools/call`, with the id that the API issued. This test must pass before a Claude Code version change. - **Admission unit tests** (19): announced then called, called then announced, never announced, turn end during the wait, cancel, an id from the previous turn, reuse, two concurrent calls with one id, two turns with live calls, a subagent call, a bad id. - **Sidecar process tests** (2), with a fake host, for Claude and for Codex. The Codex run shows no change. - **Bridge unit tests** (5). Mutation checks: - Change the announcement predicate so that it matches nothing: the real ACP test and one unit test fail. - Remove the bridge option in the real ACP test: the test fails. - Count only `tool_call_update`: the unit test "counts only an opening ACP tool_call event as an announcement" fails. Live run with a real Claude account, not in CI: the real ACP runtime (ACPX 0.22, the patched `claude-agent-acp`, the pinned Claude Code client), a real tool bridge, and the real Anthropic API with model `claude-sonnet-5-5`, on the code at the top of this stack. In three sessions, 8 Paperclip tool calls were admitted and none was refused. This includes calls in a prompt turn, in a cycle that Claude started itself, and in a later turn of the same process. Each call arrived 0.8 s to 1.7 s after its announcement, so no call waited for a late announcement. Not run: a turn through the real sidecar process with the real host. That needs a qualified provider installation, the runtime sandbox and the provider lifetime lease. Not run: the Linux builds of the pinned client and a test under load. Not run: `pnpm verify` and the full suite. CI supplies that coverage. ## Risks - **This changes each Paperclip tool call that Claude makes.** If the announcement does not reach the turn event stream in production, the sidecar refuses the call after 5 seconds. The real ACP test covers the stream of ACPX 0.22 with the pinned provider. It does not cover the real sidecar host. - **The 5 second limit is not tested under load.** A slow host can delay the announcement. The call is then refused, and Claude sees a tool error. - **A Claude Code version that stops sending the id breaks all Claude tool calls.** The qualification test finds this before the version changes. - **The admitted-id ledger is in sidecar memory.** Today the sidecar restarts at each turn boundary, so the ledger is small. The limit of 8,192 ids refuses new calls when it is full. - **Subagent calls and calls from a cycle that Claude starts itself** are covered by unit tests and fake-host tests, not by the real ACP stream. - **An admitted call that is in flight when its turn ends** is refused by the existing turn cleanup. Claude Code can leave the HTTP request open. The bridge stops it only on its own cancel or close, as before. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Fable 5.2 (`claude-fable-5-2`) in Claude Code planned the change, reviewed the diff, asked for the real ACP runtime test, and ran the verification and a mutation check again. - Claude Opus 5.5 (`claude-opus-5-5`), as a Claude Code subagent with tool use (shell, file edits, local test runs), wrote the change and the tests. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> |
||
|
|
89f486cdab |
fix(heartbeat): run one dispatch pass per agent, back off refused claims, and enforce the run limit in the claim (#21433)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The heartbeat queue starts an agent's queued runs. Each trigger (a run finishes, a wake arrives, a sweep runs) asks for one dispatch pass of that agent > - An agent could run more runs than its `maxConcurrentRuns`, dispatch passes could stack up without a limit, and every pass offered the same unclaimable runs again > - On hosted staging ( |
||
|
|
bc4bc61f9c |
fix(ui): restore chat submission on plain HTTP origins (#20308)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Operators send task replies and chat messages from the board UI. > - Browsers can omit `crypto.randomUUID` on a plain HTTP origin. > - The send handler calls that API before it sends the request. Its error handler restores the draft. > - The UI already has a UUID helper with a fallback for this case. > - This pull request uses that helper in the task and chat send paths and image upload state. > - Operators can send messages and retain the existing request receipt behavior on these origins. ## Linked Issues or Issue Description Fixes: #15846 Refs #15495, #16090, #15135, #17081. Related open proposals: #15937, #16522, #16947. They remain unmerged. This change adds independent regression and browser verification. It does not establish a cause for every intermittent send failure in those reports. ## What Changed - Use `createUuid` for both composer attempt IDs, both request ID fallbacks, and image upload state. - Test five successive sends in task and chat modes without `randomUUID`. - Test upload receipts, retry request identity, the next draft, and first-message creation without that API. ## Verification - Base: `d10c6e0e8b3005cb49d0732a670ab1a851833b01`. - Six focused regression cases fail with the original calls. The same cases pass with this change. - The three affected test files pass: 506 tests. - `pnpm --filter @paperclipai/ui typecheck`, `pnpm --filter @paperclipai/ui build`, and `pnpm check:token-gates` pass. - `pnpm verify` ran 460 UI files: 7,895 tests pass and one is skipped. One CLI startup suite failed because this environment supplied empty AI endpoint variables. That suite passes when those variables are unset. The aggregate run also reported changed inputs, so it is not a reusable verification pass. - Chromium, real local UI and API, empty synthetic instance: the original Send action sends no request and retains the draft when `randomUUID` is absent. With the fix, five task replies, a scheduled-task reply, a Classic reply, and five standing-chat messages save. Request IDs are distinct and drafts clear. An image uploads and its receipt is attached to the saved comment. - Browser scope: loopback HTTP with `randomUUID` removed before page code runs. This models the missing browser API. Service workers are blocked for the fixed request-count checks. Telemetry is disabled. No agent runs start. This does not test a remote LAN browser, provider execution, or intermittent failures after real agent exchanges. - Required CI and Greptile review are pending at PR creation. ## Risks - Low risk. The change uses the existing UUID helper and keeps the send and receipt contracts. - Other causes of intermittent send failures may remain. This change only addresses the reproduced missing-UUID failure. ## Model Used - OpenAI GPT-6 (`gpt-6`), with reasoning, tool use, and code execution. The harness does not disclose a more specific revision or context window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
d738ed5ee4 |
fix(ui): show each related task once in the Tasks tab (#20315)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The Tasks tab shows related tasks in separate sections. > - A task can be both a subtask and a task created from the current task. > - The tab showed that task in Subtasks and again in its project group. > - This pull request removes tasks from project groups when another section already shows them. > - Users can scan each task once and keep the subtask progress view. ## Linked Issues or Issue Description **What happened?** The Tasks tab shows the same task in Next action or Other subtasks and again in a project group. **Expected behavior** Show each task once. Hide a project group when all its tasks appear in other sections. **Steps to reproduce** 1. Open a task that created subtasks in the same project. 2. Open the Tasks tab. 3. Compare Next action and Other subtasks with the project section. **Paperclip version or commit** Reproduced in component tests on source commit `189fefb99183`. **Deployment mode** Built from source. The fault is in the shared UI component. No related open pull request was found in searches for duplicate tasks and TaskDetailTasksPanel. ## What Changed - Exclude task IDs already shown as subtasks, ancestors, the creation source, or a root blocker from project groups. - Show a creation source that is also an ancestor only in Created from. - Hide empty project groups, including No project. - Use an index for project lookup. - Update the product contract and regression tests. ## Verification - Before the fix, four regression cases failed because task rows or links appeared twice. - After the fix, both relation-panel test files pass: 19 tests. Run from `ui`: `node ../node_modules/vitest/vitest.mjs run --config vitest.config.ts src/components/task-detail/TaskDetailTasksPanel.test.tsx src/components/task-detail/TaskDetailRelationsPanel.test.tsx`. - Tests cover active and completed subtasks, progress, independent collapse, duplicate input rows, empty project groups, ancestors, the creation source, and a root blocker. - A test with 800 tasks and 120 projects checks unique rows and bounds task and project lookups. - `pnpm check:token-gates` and `git diff --check` pass. - The first CI typecheck found an incomplete blocker-attention test fixture. The fixture now supplies all required fields. The 19 focused tests pass again. - `pnpm --filter @paperclipai/ui typecheck` passes after `pnpm --filter @paperclipai/plugin-sdk ensure-build-deps`. The first local attempt lacked the built SDK; the retry built that dependency. - `pnpm verify` returns exit 2 because the product document requires broad CI coverage. CI typecheck, build, general tests, browser shards, and serialized server suites pass on the current head. - Full local preflight could not finish: the OpenCode CLI install hook failed, and Cargo is absent. The UI tests ran after installing dependencies with install hooks disabled. - No full-stack browser acceptance was run. This change has component DOM evidence. - Greptile gives the current head `f3bfd8fb47154810b85578ee6731246238caf67a` 5/5 with no review threads. - All 58 current-head checks pass. [CI attempt 2](https://github.com/paperclipai/paperclip/actions/runs/42657701260/attempts/2) succeeded on `f3bfd8fb47154810b85578ee6731246238caf67a`. - The first Rust CI job failed in `reaping_stops_a_dead_runners_provider_and_its_escaped_tool_job`. Its report listed one unattributed orphan after cleanup. The same Rust code passed in the previous run. [One job retry](https://github.com/paperclipai/paperclip/actions/runs/42657701260/job/129311740923) passed without code changes. The original failure is retained here; its exact cause was not established. This PR does not change Rust code. ## Risks - Low risk. This changes UI grouping only. Stored task relationships and API data stay the same. - A project section can disappear when every task in it already appears above. This is the expected result. ## Model Used - OpenAI GPT-6, through Codex, with reasoning, repository tools, and code execution. The runtime does not expose a more specific model build or context window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
c6301c92ff |
fix(ci): keep the typecheck job working on stacked PRs and stop its CLI guidance test timing out (#21451)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Every pull request runs the required `Typecheck + Release Registry` job from the trusted workflow on `master` > - #21404 replaced that job's six sequential steps with one script, `scripts/ci-typecheck-lane.mjs`, that runs independent checks in parallel > - PR runs take the workflow from `master` but check out the PR's merge commit. A stacked PR's merge commit is built on its base branch, so it can lack a script that only `master` has > - The lane also ran the CLI guidance test beside the typechecks at a lower CPU priority, and one of its cases is slow enough to cross its 15 second timeout there > - This pull request makes the job fall back to the earlier commands when the script is absent, and runs the CLI guidance test before the parallel checks > - The benefit is that stacked PRs typecheck again and the job stops failing on a timeout that has nothing to do with the PR ## Linked Issues or Issue Description Refs #21404 **What happened?** In the first eight PR runs after #21404 merged (2026-11-13 18:06Z), the typecheck job failed three times for reasons unrelated to the PRs: - Twice on #20617, a PR stacked on `feat/ssh-agent-ai-accounts`: `Error: Cannot find module '/home/runner/_work/paperclip/paperclip/scripts/ci-typecheck-lane.mjs'` (jobs 132076887259 and 132079570039). The job failed 0 seconds into the step. - Once on run 43480469363 (job 132075678943): `CLI guidance safety failed with exit code 1`, from `Error: Test timed out in 15000ms.` in `allows only exact-allowlist pnpm paperclipai commands on every guidance surface`, which took 17059 ms. The same case passes in about 5 seconds when the test runs alone. **Expected behavior** The typecheck job passes or fails on the PR's own code, including for stacked PRs. **Actual behavior** Stacked PRs always fail the job. Other PRs fail it intermittently (1 of 6 runs that reached the lane). **Steps to reproduce** Open a PR whose base branch does not contain `scripts/ci-typecheck-lane.mjs`, or run the lane on a loaded 4 vCPU runner. ## What Changed - `.github/workflows/pr-trusted.yml`: the lane step runs only when `scripts/ci-typecheck-lane.mjs` exists in the checkout. A new step runs the six earlier commands, in their earlier order, when it does not. Only the `typecheck_release_registry` job changed. - `scripts/ci-typecheck-lane.mjs`: the CLI guidance test moved from the parallel checks to the end of the sequential preparation steps, at normal priority. - Tests: `scripts/__tests__/ci-typecheck-lane.test.mjs` and `.github/scripts/tests/ci-plan.test.mjs` assert the two conditions, that the earlier commands appear only in the fallback step, and that the CLI guidance test is a preparation step. - `doc/DEVELOPING.md`: the "Typecheck lane in CI" section describes both. ## Verification - `node --test scripts/__tests__/ci-typecheck-lane.test.mjs`: 8 pass. - `node --test '.github/scripts/tests/*.test.mjs'` (the `policy` job's command): 807 pass. - `node --test scripts/__tests__/runner-release-crate-cache.test.mjs`: 11 pass. - Not exercised by this PR's own CI: PR runs use the workflow from `master`, so the new conditions first run after merge. The script change does run here, because the script is read from the PR's checkout. - Not measured: the lane's wall time with the CLI guidance test moved. The test takes 2 to 5 seconds alone, so the expected cost is that much. ## Risks - The fallback step repeats six commands in the workflow. It is needed only until open stacked PRs are based on a branch that has the script, and can be removed later. - `hashFiles` returns an empty string when no file matches, which is what the two conditions rely on. - If a future PR deletes or renames the script, the job silently uses the slower commands instead of failing. The wiring tests would fail in that PR. ## Model Used Claude Fable 5.2 (`claude-fable-5-2`), via Claude Code, with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> |
||
|
|
aa4a06653c |
fix(native): name the recorded turn failure when a native run fails (#21235)
Failed native runs now report the runner's recorded turn-failure code instead of the generic unclassified fallback, and the Sentry run-failure fingerprint includes runner:<code>. Co-Authored-By: Paperclip <Paperclip-Paperclip@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
38821e061f |
perf(runner): serialise only changed journal records for a checkpoint (#21437)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - One server process controls every running agent, and its main thread limits how many agents can run at the same time > - Each agent has a controller journal. The controller saves a checkpoint of this journal after each control event and before each frame it sends > - Each checkpoint converted every command and every event of the journal to JSON again, also when only one record changed. The cost grew with the journal length (up to 500 commands and 4,096 events) > - This pull request keeps the JSON of each record and uses it again while the record does not change > - The benefit is that a checkpoint converts only the records that changed, so the main thread does less work for each agent ## Linked Issues or Issue Description Refs #21411 (this change sits on top of its checkpoint queue). **What existing behavior does this improve?** The controller journal checkpoint in `packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts`. Each flush calls `captureCheckpoint`, which runs `JSON.stringify` on every command and every recovery event of the journal. **Current behavior** A flush after one new event converts the full journal to JSON. With 4,096 events, one flush made about 5 MB of new JSON strings and used about 14 ms of CPU on the event loop. A hosted CPU profile with about 50 agents showed about 3% of the main thread in this path. **Proposed behavior** A flush converts only the records that changed since the last flush. The other records use the JSON that the controller made before. The saved records are byte-identical to the records of the full conversion. **Reason and benefit** The target is 1,000 agents in one controller process. Checkpoint CPU must not grow with journal length. After this change, one flush with 4,096 events makes about 2.5 KB of new JSON and uses about 2 ms of CPU. ## What Changed - Add `CheckpointRecordCache` to `durable-prp-control-plane.ts`. It keeps the JSON and the part name of each command and event record, keyed by the record object. It uses the JSON again only when the record has the same keys, in the same order, with the same values (`===`). Commands change some fields in place (`status`, `result`, `controllerSeq`), and this comparison finds these changes. - `captureCheckpoint` accepts the cache as an optional fourth argument. Only `setCheckpointPersistence` and `flushCheckpoint` pass it. All other callers (decode, legacy import, bootstrap inspection) do the full conversion as before. - `checkpointChanges` uses loops instead of array copies. Records that did not change keep the same string, so the comparison is by reference. - `queueCommand` stores a copy of the command payload (`structuredClone`). The journal must own its nested objects, because the cache compares nested objects by reference. - `durableRecoveryInternals` exposes `captureCheckpoint` and `createCheckpointRecordCache` for tests. - Regions changed: `checkpointChanges` and the new cache above `captureCheckpoint`; `captureCheckpoint`; `durableRecoveryInternals`; one field of `DurablePrpControlPlane`; the `captureCheckpoint` calls in `setCheckpointPersistence` and `flushCheckpoint`; the `payload` field in `queueCommand`. The `#event` path is not changed. - No change to what a checkpoint saves, when a flush is awaited, or the order of event commit, acknowledgement and checkpoint. The "at most one waiting checkpoint" behavior from #21411 is not changed. ## Verification - New `durable-prp-checkpoint-records.test.ts`: - A journal with 499 commands and 4,000 events gets one new command. The test counts `JSON.stringify` calls on journal records during the flush. Before: 4,499. After: 0 calls on existing records, at most 2 in total (the size check of the new command and its checkpoint record). The delta contains only `command:500`. The test then restores a new controller from the checkpoint and compares its records with a full conversion without the cache. I saw this test fail on `origin/master`. - A property-style test with 5 seeds and 600 random steps each: add, settle and remove commands (with `controllerSeq` renumbering), add, replay and evict events, streaming and usage events, `structuredClone` and spread copies of the state, header counters, the same value written again, and a key-order change. After each step, the records with the cache must be byte-identical to the records without the cache, in the same order. I checked that this test fails when the field comparison is removed (cache by object only). - Existing `durable-prp-control-plane.test.ts` passes. On this loaded machine, some 5-second timing tests time out with and without this change (they also time out on `origin/master`), and pass when I run them alone. - Benchmark: `PAPERCLIP_CHECKPOINT_FLUSH_BENCHMARK=1 pnpm exec vitest run src/control-plane/durable-prp-checkpoint.benchmark.test.ts` (from `packages/paperclip-runner`). Each case commits one new event and flushes with a no-op save, 200 times. CPU time is noisy (load average about 40), the byte and record counts are exact. | Journal | CPU per flush, before | CPU per flush, after | JSON bytes per flush, before | after | Records converted per flush, before | after | | --- | --- | --- | --- | --- | --- | --- | | 10 commands, 10 events | 207 µs | 64–80 µs | 20,975 | 2,465 | 20 | 1 | | 500 commands, 10 events | 1,874 µs | 505–511 µs | 375,068 | 2,466 | 510 | 1 | | 10 commands, 4,096 events | 14,013 µs | 1,655–2,343 µs | 5,174,786 | 2,473 | 4,106 | 1 | - `pnpm check:module-boundaries` passes. `tsc -p packages/paperclip-runner/tsconfig.json --noEmit` passes. ## Risks - The cache assumes that nested `payload`, `result` and `envelope` objects of journal records are not edited in place after they enter the journal. I checked the module: results are stored with `structuredClone`, envelopes with `structuredClone`, and events are replaced, not edited. This change also copies the payload in `queueCommand`. If a later change edits a nested object in place, the checkpoint could keep old JSON. The property test shows top-level edits are found. - Some per-record work is still proportional to the journal (a Map of part names and a field comparison for each record). It is about 0.4 µs for each record. Removing it needs dirty tracking in every state mutator, which this change does not do. - No change to the saved format, so old and new servers read the same checkpoints during a deploy overlap. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use (shell, file edits) in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
37393f5dc5 |
fix(browser-tracing): send API spans only for measured page loads, without timing events (#21441)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Hosted instances can send browser page-load traces to Honeycomb (#21156, #21392) > - On staging, one hour in one workspace sent about 64,000 Honeycomb events, and only about 15 were `page.load` > - Two sources make the volume: nine network timing span events on each API request span, and request spans for background polling in idle tabs > - The page-load metrics use neither of them > - This pull request drops the timing events and records API request spans only while a page load is measured > - The benefit is about 30x fewer events in a browser test, with the same page-load data and the same server trace joins ## Linked Issues or Issue Description Refs #21156, Refs #21392 **What existing behavior does this improve?** Browser tracing exports a span for every same-origin `/api/` fetch and nine network timing events on each of those spans. **Subsystem affected** UI browser tracing (`ui/src/lib/browser-tracing/`), on hosted instances with browser tracing turned on. **Current behavior** Honeycomb stores each span event as its own event. Each request span becomes about 10 events. Idle tabs poll (for example live runs every 3 s on a task page), so most spans are requests that no page load made. On staging: about 6,600 `GET` spans plus about 6,400 of each timing event per hour, against about 15 `page.load` spans. **Proposed behavior** Request spans carry no timing events. A request is recorded only when it starts while a `page.load` measurement is open. Other requests send no span and no `traceparent`. **Reason and benefit** Event volume drops by about 30x for an idle tab. `page.load`, Web Vitals, and the Resource Timing backfill do not change. No exported request span lacks its `page.load` parent, and no server span points at a browser span that was never sent. ## What Changed - `sdk.ts`: the fetch instrumentation runs with `ignoreNetworkEvents: true` (an option of the installed `@opentelemetry/instrumentation-fetch` 0.221.0). - `sdk.ts`: new `measuredRequestsOnly` wraps the tracer provider that only the fetch instrumentation uses. When no `page.load` is open, it returns a non-recording span with an invalid context. Nothing is exported. The W3C propagator sends no `traceparent` for an invalid context, so the server traces that request alone, as for an unsampled tab. The `page.load`, Web Vitals, and backfill spans use the normal tracer and do not change. - Failed idle requests are not kept. The server's own request span records server errors. To keep them, the browser must record every idle request and send its `traceparent` before it knows the status, and that brings back the dangling joins. - `span-sanitizer.ts`: comment update only. - `doc/browser-performance-tracing.md`: new "Live API spans" section with the rule, the note that timing events are not sent, and updated volume and trace-header text. ## Verification - Red then green (`ui/src/lib/browser-tracing/sdk.test.ts`): - `records no span and sends no traceparent for an API request made while no page load is measured`: failed on the old code (an idle request sent `traceparent`), passes now. - `sends request spans without per-request network timing events`: failed on the old code (9 timing events on the request span), passes now. - All 56 tests in `ui/src/lib/browser-tracing/` pass. `tsc --noEmit` for `ui` passes. - `pnpm verify` exits 2 because a doc is a global CI input. CI supplies the broad coverage. - Real browser: local dev server on an isolated empty instance with 8 tasks, a stand-in OTLP collector, headless Chromium, and the tracing config injected into the session response. Scenario: hard load of the all-tasks page, click a task, then 2 minutes idle. One Honeycomb event = one span or one span event. | Name | master | this branch | | --- | ---: | ---: | | `page.load` | 2 | 2 | | `web_vital.lcp` | 1 | 1 | | `HTTP` (backfill) | 33 | 32 | | `GET` | 165 | 18 | | `POST` | 1 | 1 | | each of `fetchStart`, `domainLookupStart`, `domainLookupEnd`, `connectStart`, `connectEnd`, `requestStart`, `responseStart`, `responseEnd` | 165 | 0 | | **Total events** | **1,522** | **54** | - `secureConnectionStart` does not appear locally because the dev server is plain HTTP. On staging it is the ninth event. - Branch: the hard `page.load` has 32 `HTTP` children and the client `page.load` of the task has 19 live children (`GET`, `POST`). 0 request spans without a `page.load` parent (master: 146). 19 requests sent `traceparent`, and all 19 point at an exported span (master: 172 sent, 6 point at spans never exported). - Idle traffic in this test (210 `/api/` requests in total): `GET /api/issues/:id/live-runs` 88 times in 2 minutes, and `GET /api/health` 44 times (a dev-server-only 2 s poll). Most of the rest are one-off refetches. - Bundle (`vite build`): entry 3,826,982 B raw both, gzip 1,156,148 → 1,156,173 B (+25 B, chunk hash). Lazy SDK chunk 85,423 → 85,825 B raw, 27,723 → 27,859 B gzip. ## Risks - Low risk. The change is limited to the operator-gated browser tracing path on hosted instances. - Behavior shift: Honeycomb no longer has browser spans for requests made outside a page load, such as polling and mutations in a loaded page. Their server spans are still recorded as their own traces. - A request that starts during a page load and finishes after it is still recorded, as a child of that load. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edits, headless Chromium). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
08341ea134 |
fix(queue): let board users discard agent-authored queued messages (#21458)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The task composer holds messages that an agent has not consumed yet. > - A board operator needs to remove an agent-authored pending message before it starts more work. > - The queue currently grants discard only to the human author, so these messages have a disabled trash button and the API rejects the board user. > - This change derives the board discard permission in the queue snapshot and uses that same permission under the existing issue lock. > - The route checks task access before it changes the queue. The benefit is a working discard action with the existing company, privacy, revision, and dispatch guards. ## Linked Issues or Issue Description Fixes #15464. Supersedes #15465 with an independent implementation and red/green regression evidence. Thanks to @MMTE for identifying the gap and proposing a fix. Related: #18958 addresses deletion of comments that have already been delivered; this change covers pending queue entries. ## What Changed - Queue responses grant board users discard permission for agent-authored messages. Editing and other human authors' messages retain their existing permissions. - The discard use case honors the actor-specific permission rebuilt under the queue lock. Author agents keep their existing cancellation path. - The board discard route checks private-task access before deletion. The denial for a non-author agent now points to the board action instead of saying that no board action exists. - Tests cover queue states, cancellation of an empty continuation, persistence, queue linkage, audit attribution, private-task denial, and cross-company denial. The API reference describes the supported action. ## Verification - Red before the fix: the two snapshot regressions returned `canDiscard: false`; the discard regression threw `QueuedCommentMutationForbiddenError`. The route regressions also caught the disabled permission, missing private-task guard, and stale agent denial text. - Green after the fix: 30 queue snapshot and use-case tests; all five focused route regressions with real disposable Postgres; six Postgres adapter tests; 42 existing queue UI tests. - Server typecheck: `cd server && node scripts/typecheck-layers.mjs` passes. `node scripts/check-module-boundaries.mjs` and `git diff --check` pass. - The [complete PR workflow](https://github.com/paperclipai/paperclip/actions/runs/43484735280) passes on head `164200602828e23f01a8b209ff954821c5e14e9a`. [Greptile reports 5/5](https://github.com/paperclipai/paperclip/pull/21458#issuecomment-6861824451) on that same head with no open review threads. - Local scope: the 83 focused snapshot, use-case, route, adapter, and UI checks pass. The existing queue UI suite has 42 tests. The new route cases use real disposable Postgres and verify the resulting database state after reload. - Additional local full-suite attempt: 174 tests passed and 13 approval-related tests failed with cleanup timeouts, Postgres deadlocks, and duplicate-prefix errors after cleanup failed. The first failure, `queues request_confirmation resolution while its legacy source run is still running`, also fails on unchanged base code with the same 30-second `afterEach` and `afterAll` timeouts. This broader local run is not counted as a pass. No test timeout or assertion was weakened. CI supplies the broad passing result for the committed head. - `node scripts/local-verify.mjs --explain` returned exit 2 because the API documentation is a global CI input; all of its required CI lanes passed. The initial adapter attempt could not initialize local Postgres under the sandbox; the same six checks passed with local-process access. The initial cross-company fixture was corrected to use a distinct company prefix. ## Risks - This grants board operators a new action on agent-authored pending messages. The route must pass company membership and private-task access checks; the mutation retains its transaction, revision, and dispatch protections. - No schema or migration is required. The UI uses its existing discard control and error handling. - The staging task was inspected to confirm the cause. No staging data was deleted, and a deployed UI retest is not claimed by these local and CI checks. ## Model Used - OpenAI Codex, GPT-6, with reasoning, repository inspection, tool use, and code execution. The exact runtime model ID and context limit are not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass — the focused regression, adapter, and UI checks listed above; the additional broad local cleanup failure is documented separately - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
8b7b2a0701 |
fix: Recognize Git mount-boundary absence diagnostics in workspace checks (#21048)
> [!NOTE] > Opened by Prospector's automated issue-fix pipeline. A maintainer reviews and decides; nothing here merges on its own. > [!WARNING] > This change crosses a trust boundary. See Risks. ## Thinking Path - Issue #20525 reports a defect in paperclipai/paperclip. - Root cause, as the fixing agent read it: Both callers recognized only the ordinary Git absence diagnostic. Preserve the earlier exact boundary matcher and all existing exit, signal, environment, and filesystem checks. - This pull request: Recognize Git mount-boundary absence diagnostics in workspace checks ## What Changed - `server/src/services/git-mount-boundary-message.ts`: Retain the shared complete-diagnostic matcher, which rejects partial and appended output. - `server/src/services/managed-repository-checkout.ts`: Retain boundary recognition without changing ordinary-diagnostic behavior or fallback guards. - `server/src/services/heartbeat/workspaces.ts`: Retain boundary recognition and ancestor metadata inspection. - `server/src/__tests__/git-mount-boundary.test.ts`: Add root mount, CRLF, and embedded-line-break cases through both callers. Confirmed six failures with boundary recognition disabled; restored implementation passes this suite, both neighboring suites, and typecheck. ## Verification - Reproducing test(s), added in this PR: `server/src/__tests__/git-mount-boundary.test.ts` - They fail on the base commit and pass with the fix, each twice in a fresh sandbox. - The repository's compile command passes with the fix applied. - 10 existing test file(s) near the change passed. - The full test suite passes except for the 16 file(s) that already fail on the base commit. ## Risks - Written by an automated pipeline, not a person: review it as you would an outside contribution. - Risk tier of the touched paths: 2. - It crosses a trust boundary. Check each crossing against what the issue asked for, and against who asked: - validation (server/src/services/heartbeat/workspaces.ts:860): Broadens the accepted Git absence diagnostics to include the mount-boundary message when classifying a checkout failure as an expected non-repository result. - validation (server/src/services/managed-repository-checkout.ts:265): Allows the mount-boundary diagnostic to bypass a previously thrown Git error when plainTaskDirectory and the existing exit, signal, and environment conditions hold. ## Model Used - opus (Anthropic Claude, via Claude Code), writing and checking the change in an isolated sandbox. - opus (Anthropic Claude, via Claude Code), reviewing it independently. ## Linked Issues Fixes #20525 #20525 also mentions, without asking this fix for it: - Non-Git directories in close readiness. (The report explicitly identifies merged #19553 as handling 'a different caller'; this patch does not modify close readiness.) - Initial managed-clone readiness. (The report says '#2977 concerns initial managed-clone readiness, rather than this diagnostic matcher.') - CI jobs 131047332629 and 131040975860 fail; fix the change only if it causes the failures. (This earlier-round conditional comment supplies no demonstrated matcher defect. .github/workflows/pr-trusted.yml:1801-1804 asserts aggregate shard status, while server/src/services/tool-access/catalog/health.ts:222 reports MCP health failures; neither changed here. Historical job causation cannot be) A search of paperclipai/paperclip's open and closed pull requests found no other pull request that names #20525. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [ ] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with 'Fixes: #' / 'Closes #' / 'Refs #' OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub '#NNN' / 'github.com/paperclipai/paperclip' URLs) - [ ] My branch name describes the change (e.g. 'docs/...', 'fix/...') and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge <!-- prospector:issue-fix v1 issue=20525 base=156453fe7c67 report=513d758246cb2ac5 --> Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com>canary/v2026.1113.0-canary.10 |
||
|
|
80f7989f4b |
fix: Wait for the SSH export pipeline to drain before importing the bundle (#20708)
> [!NOTE] > Opened by Prospector's automated issue-fix pipeline. A maintainer reviews and decides; nothing here merges on its own. ## Thinking Path - Issue #16567 reports a defect in paperclipai/paperclip. - Root cause, as the fixing agent read it: SSH process closure ended the destination stream while the progress Transform still held buffered bytes. Transfer success now requires both pipeline completion and SSH completion. - This pull request: Wait for the SSH export pipeline to drain before importing the bundle ## What Changed - `packages/adapter-utils/src/ssh.ts`: Use Node's pipeline to drain the stream chain, propagate stream errors, and release streams on failure while preserving SSH stderr errors. - `packages/adapter-utils/src/ssh-export-stream.test.ts`: Reproduced truncation and confirmed the fix passes with and without progress. Added failure cleanup cases; their final run and typecheck have not returned, and live SSH fixtures skipped because ssh is unavailable. ## Verification - Reproducing test(s), added in this PR: `packages/adapter-utils/src/ssh-export-stream.test.ts`, `packages/adapter-utils/src/ssh-export.test.ts` - They fail on the base commit and pass with the fix, each twice in a fresh sandbox. - 3 independent attempts wrote 3 reproductions; this fix passes every one of them. - The repository's compile command passes with the fix applied. - 10 existing test file(s) near the change failed, and fail on the base too, so they cannot show whether the change breaks them. - The full test suite passes except for the 17 file(s) that already fail on the base commit. ## Risks - Written by an automated pipeline, not a person: review it as you would an outside contribution. - Risk tier of the touched paths: 2. ## Model Used - codex:gpt-6.1-sol, opus, sonnet (Anthropic Claude, via Claude Code; OpenAI, via the Codex CLI), writing and checking the change in an isolated sandbox. - opus (Anthropic Claude, via Claude Code), reviewing it independently. ## Linked Issues Fixes #16567 #16567 also mentions, without asking this fix for it: - Add git bundle verify or a remote size check to provide a clearer diagnostic for short files. (The report calls this 'A cheap extra guard would be git bundle verify (or a size check sent by the remote script) before git fetch'; it is an optional additional safeguard. Empty or malformed output that ends normally still reaches the existing git fetch validation at packages/adapter-utils/src/ssh.) Other pull requests that name #16567: - #16613 (open): fix: prevent truncated SSH Git exports ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [ ] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with 'Fixes: #' / 'Closes #' / 'Refs #' OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub '#NNN' / 'github.com/paperclipai/paperclip' URLs) - [ ] My branch name describes the change (e.g. 'docs/...', 'fix/...') and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge <!-- prospector:issue-fix v1 issue=16567 base=5ab98b006359 report=6118c07135df7c3a --> Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com> |
||
|
|
ed671f57bf |
fix: Display Ollama billers with their product names in cost views (#20420)
> [!NOTE] > Opened by Prospector's automated issue-fix pipeline. A maintainer reviews and decides; nothing here merges on its own. ## Thinking Path - Issue #16573 reports a defect in paperclipai/paperclip. - Root cause, as the fixing agent read it: The shared providerDisplayName map omitted ollama and ollama-cloud, causing all cost views using it to display the raw slugs. - This pull request: Display Ollama billers with their product names in cost views ## What Changed - `ui/src/lib/utils.ts`: Add Ollama and Ollama Cloud names in the shared formatter used by cost views. - `ui/src/lib/utils.provider-display-name.test.ts`: Reproduce the missing names and cover case-insensitive lookup and unchanged fallback behavior. Confirmed failure before the fix; all 20 selected tests and the workspace typecheck passed afterward. ## Verification - Reproducing test(s), added in this PR: `ui/src/lib/utils.provider-display-name.test.ts` - They fail on the base commit and pass with the fix, each twice in a fresh sandbox. - 3 independent attempts wrote 3 reproductions; this fix passes every one of them. - The repository's compile command passes with the fix applied. - 10 existing test file(s) near the change passed. - The full test suite passes except for the 16 file(s) that already fail on the base commit. ## Risks - Written by an automated pipeline, not a person: review it as you would an outside contribution. - Risk tier of the touched paths: 3. ## Model Used - codex:gpt-6.1-sol, opus, sonnet (Anthropic Claude, via Claude Code; OpenAI, via the Codex CLI), writing and checking the change in an isolated sandbox. - opus (Anthropic Claude, via Claude Code), reviewing it independently. ## Linked Issues Fixes #16573 Other pull requests that name #16573: - #16609 (open): fix(ui): map Ollama and Ollama Cloud biller slugs to human-readable names - #16590 (open): fix(ui): format ollama and ollama-cloud provider names in cost views - #16574 (open): fix(ui): show Ollama and Ollama Cloud by name in cost views ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [ ] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with 'Fixes: #' / 'Closes #' / 'Refs #' OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub '#NNN' / 'github.com/paperclipai/paperclip' URLs) - [ ] My branch name describes the change (e.g. 'docs/...', 'fix/...') and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge <!-- prospector:issue-fix v1 issue=16573 base=8e5959c759bb report=f738d3d291d2282c --> Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com> |
||
|
|
6f2ea3b4d5 |
fix: Complete run cancellation when lifecycle event append fails (#20215)
> [!NOTE] > Opened by Prospector's automated issue-fix pipeline. A maintainer reviews and decides; nothing here merges on its own. > [!WARNING] > This change crosses a trust boundary. See Risks. ## Thinking Path - Issue #20116 reports a defect in paperclipai/paperclip. - Root cause, as the fixing agent read it: Cancellation awaited the lifecycle event append after cancelling the run and wakeup. An append failure rejected the stop before issue release, agent finalization, and queue advancement. - This pull request: Complete run cancellation when lifecycle event append fails ## What Changed - `server/src/services/heartbeat/run-control.ts`: Log cancellation event append failures and continue essential cleanup, matching lease-release terminalization. - `server/src/services/heartbeat/run-control-event-failure.test.ts`: Cover queued and running cancellation with an injected append failure and the real issue-release adapter. Confirmed regression failures before the fix; regression tests, neighboring tests, and final typecheck pass. ## Verification - Reproducing test(s), added in this PR: `server/src/services/heartbeat/run-control-event-failure.test.ts`, `server/src/__tests__/heartbeat-lock-release-on-reassignment.test.ts`, `server/src/services/heartbeat/run-control.test.ts` - They fail on the base commit and pass with the fix, each twice in a fresh sandbox. - 3 independent attempts wrote 3 reproductions; this fix passes every one of them. - The repository's compile command passes with the fix applied. - 9 existing test file(s) near the change passed. - The full test suite passes except for the 16 file(s) that already fail on the base commit. ## Risks - Written by an automated pipeline, not a person: review it as you would an outside contribution. - Risk tier of the touched paths: 2. - It crosses a trust boundary. Check each crossing against what the issue asked for, and against who asked: - logging (server/src/services/heartbeat/run-control.ts:1665): Logs the event-append error and run ID to the server log when cancellation event recording fails. ## Model Used - codex:gpt-6.1-sol, opus, sonnet (Anthropic Claude, via Claude Code; OpenAI, via the Codex CLI), writing and checking the change in an isolated sandbox. - opus (Anthropic Claude, via Claude Code), reviewing it independently. ## Linked Issues Fixes #20116 The reviewer found the base already handles: - A closed request socket produces a misleading PATCH 200 log that hides the failure. (server/src/middleware/logger.ts:89–91 detects aborted or unfinished responses and formats 'request aborted'; lines 150 and 157–158 log these at warn level with that message instead of the default status-based success message.) A search of paperclipai/paperclip's open and closed pull requests found no other pull request that names #20116. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [ ] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with 'Fixes: #' / 'Closes #' / 'Refs #' OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub '#NNN' / 'github.com/paperclipai/paperclip' URLs) - [ ] My branch name describes the change (e.g. 'docs/...', 'fix/...') and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge <!-- prospector:issue-fix v1 issue=20116 base=ca34bed25797 report=e2609f9803f7cc0c --> Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com> |
||
|
|
a6608bd735 |
fix: Preserve plugin UI UUID validation and test trailing line terminators (#20058)
> [!NOTE] > Opened by Prospector's automated issue-fix pipeline. A maintainer reviews and decides; nothing here merges on its own. ## Thinking Path - Issue #17332 reports a defect in paperclipai/paperclip. - Root cause, as the fixing agent read it: Plugin keys reached a UUID-column query, and Drizzle's nested PostgreSQL error bypassed the original error handler. The existing UUID guard fixes this; its non-multiline JavaScript regex also rejects trailing newlines. - This pull request: Preserve plugin UI UUID validation and test trailing line terminators ## What Changed - `server/src/routes/plugin-ui-static.ts`: Retain the existing guard, PostgreSQL UUID forms, and key fallback. - `server/src/__tests__/plugin-ui-static.test.ts`: Add route tests for four trailing line terminators and accepted PostgreSQL UUID forms. Confirmed the original lookup fails; all 58 focused tests and typecheck pass with the guard. ## Verification - Reproducing test(s), added in this PR: `server/src/__tests__/plugin-ui-static.test.ts` - They fail on the base commit and pass with the fix, each twice in a fresh sandbox. - 3 independent attempts wrote 3 reproductions; this fix passes every one of them. - The repository's compile command passes with the fix applied. - 2 existing test file(s) near the change passed. - The full test suite passes except for the 16 file(s) that already fail on the base commit. - Revised in 1 round(s) of automated code review. ## Risks - Written by an automated pipeline, not a person: review it as you would an outside contribution. - Risk tier of the touched paths: 2. ## Model Used - codex:gpt-6.1-sol, opus, sonnet (Anthropic Claude, via Claude Code; OpenAI, via the Codex CLI), writing and checking the change in an isolated sandbox. - opus (Anthropic Claude, via Claude Code), reviewing it independently. ## Linked Issues Fixes #17332 Other pull requests that name #17332: - #17433 (open): fix(plugins): serve a plugin UI bundle addressed by plugin key - #17335 (open): fix(server): serve plugin UI assets requested by plugin key ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [ ] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with 'Fixes: #' / 'Closes #' / 'Refs #' OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub '#NNN' / 'github.com/paperclipai/paperclip' URLs) - [ ] My branch name describes the change (e.g. 'docs/...', 'fix/...') and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge <!-- prospector:issue-fix v1 issue=17332 base=ca34bed25797 report=b2e95a170c3be729 --> Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com> |
||
|
|
f4159e25e4 |
fix: Remove the unused OpenCode remote config guard and document host staging (#20045)
> [!NOTE] > Opened by Prospector's automated issue-fix pipeline. A maintainer reviews and decides; nothing here merges on its own. > [!WARNING] > This change crosses a trust boundary. See Risks. ## Thinking Path - Issue #17372 reports a defect in paperclipai/paperclip. - Root cause, as the fixing agent read it: The helper's unused targetIsRemote guard contradicted both callers, which intentionally stage configuration on the host and transfer it to remote targets as xdgConfig. - This pull request: Remove the unused OpenCode remote config guard and document host staging ## What Changed - `packages/adapters/opencode-local/src/server/runtime-config.ts`: Remove the unused option and contradictory guard while preserving both callers' staging behavior. - `packages/adapters/opencode-local/src/server/runtime-config.test.ts`: Add a regression for isolated staging, generated configuration, cleanup, and operator config preservation. Confirmed failure before the fix; all 50 focused tests pass afterward. Typecheck was started but has not returned a result. - `packages/adapters/opencode-local/README.md`: Document host staging for local and remote execution, remote asset transfer, path replacement, and host cleanup. ## Verification - Reproducing test(s), added in this PR: `packages/adapters/opencode-local/src/server/runtime-config.test.ts` - They fail on the base commit and pass with the fix, each twice in a fresh sandbox. - 3 independent attempts wrote 3 reproductions; this fix passes every one of them. - The repository's compile command passes with the fix applied. - 9 existing test file(s) near the change passed. - The full test suite passes except for the 16 file(s) that already fail on the base commit. ## Risks - Written by an automated pipeline, not a person: review it as you would an outside contribution. - Risk tier of the touched paths: 2. - It crosses a trust boundary. Check each crossing against what the issue asked for, and against who asked: - validation (packages/adapters/opencode-local/src/server/runtime-config.ts:107): Removes the targetIsRemote early-return check that prevented host configuration staging when explicitly set, although neither production caller supplies it. ## Model Used - codex:gpt-6.1-sol, opus, sonnet (Anthropic Claude, via Claude Code; OpenAI, via the Codex CLI), writing and checking the change in an isolated sandbox. - opus (Anthropic Claude, via Claude Code), reviewing it independently. ## Linked Issues Fixes #17372 #17372 also mentions, without asking this fix for it: - The remote per-run directory is never removed. (The report explicitly says: “Related but distinct: #14527 covers the remote per-run directory never being removed.”) A search of paperclipai/paperclip's open and closed pull requests found no other pull request that names #17372. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [ ] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with 'Fixes: #' / 'Closes #' / 'Refs #' OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub '#NNN' / 'github.com/paperclipai/paperclip' URLs) - [ ] My branch name describes the change (e.g. 'docs/...', 'fix/...') and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge <!-- prospector:issue-fix v1 issue=17372 base=ca34bed25797 report=0010c91463516eaf --> Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com> |
||
|
|
0eeee6ae96 |
fix: Defer chat milestone result reads and fix regression test transaction typing (#19875)
> [!NOTE] > Opened by Prospector's automated issue-fix pipeline. A maintainer reviews and decides; nothing here merges on its own. ## Thinking Path - Issue #16728 reports a defect in paperclipai/paperclip. - Root cause, as the fixing agent read it: PostgreSQL could evaluate both result_json predicates before publication filtering, detoasting already-published runs. The regression test also passed transaction handles to helpers typed for full database handles. - This pull request: Defer chat milestone result reads and fix regression test transaction typing ## What Changed - `server/src/services/chat-run-publications.ts`: Retain publication-dependent guards around both result JSON predicates in the shared milestone query. - `server/src/__tests__/chat-run-milestone-toast.test.ts`: Use the neighboring tests' transaction cast convention. Confirmed both cases fail without the guards and pass with them; all seven selected milestone test files and typecheck passed. ## Verification - Reproducing test(s), added in this PR: `server/src/__tests__/chat-run-milestone-candidates.test.ts`, `server/src/__tests__/chat-run-milestone-toast.test.ts` - They fail on the base commit and pass with the fix, each twice in a fresh sandbox. - The repository's compile command passes with the fix applied. - 8 existing test file(s) near the change failed, and fail on the base too, so they cannot show whether the change breaks them. - The full test suite passes except for the 15 file(s) that already fail on the base commit. ## Risks - Written by an automated pipeline, not a person: review it as you would an outside contribution. - Risk tier of the touched paths: 2. ## Model Used - opus (Anthropic Claude, via Claude Code), writing and checking the change in an isolated sandbox. - opus (Anthropic Claude, via Claude Code), reviewing it independently. ## Linked Issues Fixes #16728 The reviewer found the base already handles: - Milestone projection still runs on a one-second cadence. (server/src/services/chat-run-milestone-work.ts:12 describes and implements discovery on startup/committed changes with retries for failures or unfinished batches; server/src/app.ts:1269 registers this work owner. This code exists independently of the proposed predicate change.) Other pull requests that name #16728: - #18686 (open): perf(runs): read result_json once per run in run lists and index agent runs by created_at ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [ ] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with 'Fixes: #' / 'Closes #' / 'Refs #' OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub '#NNN' / 'github.com/paperclipai/paperclip' URLs) - [ ] My branch name describes the change (e.g. 'docs/...', 'fix/...') and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge <!-- prospector:issue-fix v1 issue=16728 base=d1ee25d0f722 report=5924b3e8dd6d2fe4 --> --------- Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com> |
||
|
|
633c8076c0 |
fix: Allow initial plugin configuration saves and scope completed saves to their original company and plugin (#19847)
> [!NOTE] > Opened by Prospector's automated issue-fix pipeline. A maintainer reviews and decides; nothing here merges on its own. > [!WARNING] > This change crosses a trust boundary. See Risks. ## Thinking Path - Issue #17637 reports a defect in paperclipai/paperclip. - Root cause, as the fixing agent read it: Dirty tracking did not distinguish missing configuration records from saved defaults. The earlier attempt also updated the cache using the current selection rather than the identifiers captured when saving. - This pull request: Allow initial plugin configuration saves and scope completed saves to their original company and plugin ## What Changed - `ui/src/pages/PluginSettings.tsx`: Preserve initial saves after successful loading, validation, and pending guards. Capture pluginId and companyId in mutation variables and use them for persistence, cache updates, and invalidation. - `ui/src/pages/PluginSettings.test.tsx`: Retain coverage for initial defaults, saved values, loading failures, and validation. - `ui/src/pages/PluginSettings.save-refetch.test.tsx`: Retain coverage preventing duplicate unchanged saves during refetch. - `ui/src/pages/PluginSettings.save-scope.test.tsx`: Add company and plugin selection coverage during pending saves. The company case failed before the revision; all 17 relevant tests and the sandbox typecheck now pass. ## Verification - Reproducing test(s), added in this PR: `ui/src/pages/PluginSettings.save-scope.test.tsx`, `ui/src/pages/PluginSettings.test.tsx`, `ui/src/pages/PluginSettings.save-refetch.test.tsx` - They fail on the base commit and pass with the fix, each twice in a fresh sandbox. - 3 independent attempts wrote 3 reproductions; this fix passes every one of them. - The repository's compile command passes with the fix applied. - The full test suite passes except for the 15 file(s) that already fail on the base commit. - Revised in 1 round(s) of automated code review; 1 reviewer claim(s) were first shown by a failing test. ## Risks - Written by an automated pipeline, not a person: review it as you would an outside contribution. - Risk tier of the touched paths: 3. - The scope reviewer found it also changes, beyond the report: Config query is loading, errored, or disabled (no company selected) - The scope reviewer found it also changes, beyond the report: saveMutation.mutate call signature (internal) - It crosses a trust boundary. Check each crossing against what the issue asked for, and against who asked: - validation (ui/src/pages/PluginSettings.tsx:1131): The Save button's disable check is loosened from '!isDirty' to '!isDirty && !needsInitialSave', so an unchanged form can now be submitted when the company has no saved plugin_config row. ## Model Used - codex:gpt-6.1-sol, opus, sonnet (Anthropic Claude, via Claude Code; OpenAI, via the Codex CLI), writing and checking the change in an isolated sandbox. - opus (Anthropic Claude, via Claude Code), reviewing it independently. ## Linked Issues Fixes #17637 #17637 also mentions, without asking this fix for it: - Proactive company set / job-scope hole (#12109, #12655) (Report: "This is not a request to change proactive scope. That discussion belongs on #12109 and #12655.") Other pull requests that name #17637: - #17654 (open): fix(ui): allow saving default plugin configuration ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [ ] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with 'Fixes: #' / 'Closes #' / 'Refs #' OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub '#NNN' / 'github.com/paperclipai/paperclip' URLs) - [ ] My branch name describes the change (e.g. 'docs/...', 'fix/...') and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge <!-- prospector:issue-fix v1 issue=17637 base=d1ee25d0f722 report=44fc7d94342a1efd --> Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com> |
||
|
|
47ce5459c9 |
fix: Keep tablet task composers above the keyboard and release sizing during pinch zoom (#19725)
> [!NOTE] > Opened by Prospector's automated issue-fix pipeline. A maintainer reviews and decides; nothing here merges on its own. > [!WARNING] > This change crosses a trust boundary. See Risks. ## Thinking Path - Issue #17866 reports a defect in paperclipai/paperclip. - Root cause, as the fixing agent read it: Viewport observation and conversation sizing were tied to the mobile navigation breakpoint. The earlier attempt also retained keyboard state during zoom and excluded classic task threads from keyboard sizing. - This pull request: Keep tablet task composers above the keyboard and release sizing during pinch zoom ## What Changed - `ui/src/components/Layout.tsx`: Retain viewport observation independent of navigation width. - `ui/src/components/Layout.production.tsx`: Apply the same viewport observation to the production layout. - `ui/src/hooks/useMobileVisualViewport.ts`: Clear keyboard state during pinch zoom and handle Safari document panning for classic conversation shells. - `ui/src/pages/IssueDetail.tsx`: Mark desktop-width classic chat pages for keyboard sizing while preserving phone layouts and other tabs. - `ui/src/index.css`: Constrain classic conversation shells during keyboard display, retain main-content scrolling, and keep their sticky composer inside the visible area. - `ui/src/hooks/useMobileVisualViewport.test.tsx`: Reproduce stale keyboard state after zoom and verify recovery. - `ui/src/components/Layout.viewport.test.tsx`: Cover both layouts, both conversation shells, zoom recovery, and document pan correction. - `ui/src/pages/IssueDetail.test.tsx`: Verify classic sizing eligibility at desktop and phone widths. Regression tests, existing thread tests, and typecheck passed. ## Verification - Reproducing test(s), added in this PR: `ui/src/hooks/useMobileVisualViewport.test.tsx`, `ui/src/pages/IssueDetail.test.tsx`, `ui/src/components/Layout.viewport.test.tsx`, `ui/src/components/Layout.test.tsx` - They fail on the base commit and pass with the fix, each twice in a fresh sandbox. - 3 independent attempts wrote 3 reproductions; this fix passes every one of them. - The repository's compile command passes with the fix applied. - 10 existing test file(s) near the change passed. - The full test suite passes except for the 15 file(s) that already fail on the base commit. - Revised in 1 round(s) of automated code review. ## Risks - Written by an automated pipeline, not a person: review it as you would an outside contribution. - Risk tier of the touched paths: 3. - The scope reviewer found it also changes, beyond the report: Enabled hook callers entering zoom after keyboard detection: both Layout variants, hook test hosts, and task-chat-mobile-follow Storybook - The scope reviewer found it also changes, beyond the report: Missing visualViewport or shell; disabled hook; zero, negative, non-finite, or missing viewport height; missing or malformed scale - It crosses a trust boundary. Check each crossing against what the issue asked for, and against who asked: - validation (ui/src/components/Layout.tsx:155): Passing true removes the mobile-width eligibility check for viewport keyboard handling. - validation (ui/src/components/Layout.production.tsx:182): Passing true removes the mobile-width eligibility check in the production layout. - validation (ui/src/hooks/useMobileVisualViewport.ts:12, not asked for by the report): The scroll-reset guard now accepts classic task shells as well as task-chat shells. ## Model Used - codex:gpt-6.1-sol, opus, sonnet (Anthropic Claude, via Claude Code; OpenAI, via the Codex CLI), writing and checking the change in an isolated sandbox. - opus (Anthropic Claude, via Claude Code), reviewing it independently. ## Linked Issues Fixes #17866 A search of paperclipai/paperclip's open and closed pull requests found no other pull request that names #17866. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [ ] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with 'Fixes: #' / 'Closes #' / 'Refs #' OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub '#NNN' / 'github.com/paperclipai/paperclip' URLs) - [ ] My branch name describes the change (e.g. 'docs/...', 'fix/...') and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge <!-- prospector:issue-fix v1 issue=17866 base=f8cb4957dcd9 report=8607f5fafe77c2be --> Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com> |
||
|
|
5859e7cfa6 |
perf(apps): avoid repeated writes during permission saves (#21033)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Apps give agents access to tools through saved profiles and approval rules. > - A save replaces the full set of action entries and access bindings. > - It also updates each Ask first rule and each retired rule in a separate query. > - Adding one agent can therefore cause hundreds of database round trips. > - This pull request keeps unchanged rows and batches the required changes. > - The benefit is faster saves with the same action permissions. ## Linked Issues or Issue Description **What happened?** An app permission save repeats database work for actions and agents that did not change. With 100 actions and 500 retired rules, one agent addition makes 636 queries. Of these, 599 update approval policies. Related boundary coverage: Refs #19973. This change keeps that issue's Off and agent-selection protections. **Expected behavior** Adding an agent applies the saved Allowed, Ask first, and Off choices. The save changes only the rows that need a change. Independent approval rules remain in force. **Steps to reproduce** 1. Create an app with 100 active actions and 99 Ask first rules. 2. Add 500 disabled app approval rules. 3. Save access for three agents. Then add a fourth agent. 4. Count database queries during the save. **Paperclip version or commit** Baseline: `51d77648bc62`. **Deployment mode** Built from source. The reproduction uses disposable local PostgreSQL. ## What Changed - Keep action entries and access bindings when their saved values match. - Insert new bindings in one query. Remove only bindings and entries that no longer apply. - Read managed approval rules for the selected app. Skip unchanged rules and rules that are already disabled. - Batch new or changed Ask first rules and disable stale enabled rules in one query. - Keep existing policy conditions, priority, author, and creation time when a rule changes. - Add real PostgreSQL regression tests and a repeatable benchmark. Document independent approval rules. ## Verification - Red: the original regression made 2,995 policy writes across five saves and failed the zero-write check. - Green: 636 focused service and runtime tests passed after the rebase. CI supplies the broad checks required by `pnpm verify` (exit 2). - Benchmark: `node --import ./server/node_modules/tsx/dist/loader.mjs scripts/benchmark-app-permission-save.ts --baseline-ref=51d77648bc62 --output=/tmp/app-permission-save.json`. - Local benchmark: two warmups and six samples in alternating order. Restore three agents outside each timed sample, then add the fourth agent. Median save time fell from 458.51 ms to 38.05 ms (12.0 times faster). Query count fell from 636 to 32. Unchanged policy writes fell from 599 to zero. - Compare all saved profile, entry, binding, and policy values after mapping fixture IDs and excluding generated row IDs and write times. Check Allowed and Ask first decisions for the added agent. Tests also cover Off, an unassigned agent, additive access, removal, independent policies, company boundaries, and re-enabled rules. - CI passes on `069e2c76252a19ec3c11a061de0506eccb0463d1`: [PR workflow](https://github.com/paperclipai/paperclip/actions/runs/43162600023). This includes typecheck, build, server tests, and all eight browser shards. - [Greptile](https://github.com/paperclipai/paperclip/pull/21033#issuecomment-6815608829) gives the final head 5/5. Its one finding is resolved. The separate Paperclip Review check is still queued. Its review task stopped after a Runner failure. - Hosted request timing and the specific reported approval prompt are not verified. No live permissions changed. ## Risks - The save now retains unchanged row IDs and timestamps. Consumers must use permission values to determine access. - Existing transaction locks and permission checks remain in place. The runtime concurrency tests exercise these paths. - The benchmark measures a local service with synthetic data. It does not establish hosted endpoint latency. - No migration or startup change is required. ## Model Used OpenAI Codex, GPT-6. Exact provider model ID is not exposed in this session. Used reasoning, tool calls, and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
6ad4529c5a |
fix(native): preserve pack proof across interrupted reattachment (#21246)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - The server can connect again to a live Runner after a restart.
> - Each new controller claim changes provider-pack admission to
pending.
> - The claim kept the previous verified proof only in local memory.
> - If recovery failed before its callback, the next claim lost that
proof.
> - This pull request saves a small reference to the verified proof with
the claim.
> - The next claim can check the same receipt without weakening
admission checks.
## Linked Issues or Issue Description
**What happened?**
A restart recovery attempt timed out before its admission callback. The
next attempt refused the saved pack with `source_state_pending`. It then
failed with `native_provider_artifacts_admission_unverified`.
**Expected behavior**
The next attempt can reuse the previous verified proof for the same
receipt, session, Runner, and lease. Current admission must remain
pending until its normal callback succeeds.
**Steps to reproduce**
1. Save verified provider-pack admission for a run.
2. Claim that run again. Commit the pending admission state.
3. Interrupt recovery before the session admission callback.
4. Claim the same run again and reconnect to the same Runner.
5. Observe that the old code refuses the saved receipt.
Related work: #20682 and #20850 address lock waits. #21085 adds refusal
logs. #21161 addresses command waits after restart. This change
addresses lost admission proof across interrupted claims. The original
transport timeout remains a separate investigation.
## What Changed
- The admission module prepares the claim patch and its recovery source.
- The claim saves a versioned reference with the source run, receipt
digest, and previous verified state. It adds no copy of provider files
or credentials.
- A later pending claim can use that reference only if the receipt is
unchanged. Normal company, agent, session, Runner, and lease checks
still apply.
- Missing proof, unknown state, a changed receipt, or a different Runner
stays refused. The callback clears the reference when it records its
decision.
- The executor uses this helper under its existing claim lock. Existing
artifact-retention and ownership checks stay in place.
- The execution guide states the previous-release behavior. Old verified
records seed the reference. Old pending records without a reference
remain refused. Older readers ignore the field and keep their existing
refusal behavior. No migration is needed.
## Verification
- The new interrupted-claim regression failed before the fix: admission
returned false instead of true.
- Focused admission, PostgreSQL fencing, and executor lease tests passed
after the rebase: 61 tests on commit
|
||
|
|
9d9ee92d15 |
refactor(evals): remove the orphaned chat TestOps dispatch guard (#21241)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The chat catalog eval harness sends selected cases to TestOps plans through GitHub workflows. > - PR #18322 added a dispatch guard script for the `chat-feature-testops` workflow. The guard checked each dispatch event before the workflow could use credentials. > - PR #18625 retired the duplicate chat TestOps plans. That PR deleted the `chat-feature-testops` workflow, the workflow step that ran the guard, and the only import of the guard function. > - The guard file stayed in the repository after that removal, but nothing calls it now. > - This pull request deletes the unused guard file. > - The benefit is less test support code to maintain. No protection is lost, because the workflow it guarded no longer exists. ## Linked Issues or Issue Description No public issue exists for this cleanup. The problem is described here, following the enhancement template. **What existing behavior does this improve?** The chat TestOps eval support under `tests/runner-e2e`. The guard script `testops-chat-dispatch.ts` verified workflow dispatch events for a retired workflow. **Current behavior** `tests/runner-e2e/testops-chat-dispatch.ts` holds a guard for the `chat-feature-testops` workflow. That workflow was deleted in #18625. A search of all tracked file content finds no import, no run command, and no test that uses the guard file today. **Proposed behavior** The repository does not keep the unused guard file. The runner-e2e typecheck program and the test tree load one support file less. **Reason and benefit** The guard protected a workflow dispatch path that no longer exists. Keeping the file suggests a live guard where none runs. Deleting it removes 31 lines of test support code. No regression coverage is lost: no test executes the file, and the contract it guarded is retired. **Breaking changes** None. The deleted file has no callers. No workflow, script, test, or documentation references it. ## What Changed - Deleted `tests/runner-e2e/testops-chat-dispatch.ts` (31 lines of test support code). No production code changed. ## Verification - Searched all tracked file content for `testops-chat-dispatch`, `validateChatTestOpsDispatch`, and `ChatTestOpsDispatch`. Only the deleted file matched. - Checked every selection path that could run the file: it is not a `*.test.ts` file; the runner-e2e harness selects test files through the catalog manifest, which does not name it; the root vitest projects do not include `tests/`; the `node --test` script lists do not name it; no workflow runs it. - Confirmed the history: #18322 added the file; #18625 deleted the workflow step `node tests/runner-e2e/testops-chat-dispatch.ts` and removed the only import and the assertions that referenced it; no commit touched the file after that. - Local limitation: this workspace has no installed dependencies, so the layered typecheck and the vitest suites could not run locally. The CI lanes on this pull request must confirm them. ## Risks - Low risk. The file had no callers. The remaining risk is a hidden reference that a text search cannot find. The typecheck lane and the CI test lanes on this pull request would find such a reference. ## Model Used - GLM by Z.ai, model id `z-ai/glm-5.3`, run through opencode by the Paperclip Runner. Extended reasoning enabled, with shell and file tool use. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes: #` / `Refs: #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [ ] I have run tests locally and they pass - [ ] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge |
||
|
|
b0447f3c76 |
fix: restrict chat task sponsors to self or admins (#21218)
## Thinking Path > - Paperclip manages AI agents and their authority to do work. > - External chat channels can create tasks for those agents. > - A task sponsor is the person responsible for that work. > - GitHub bot settings accepted another member as a sponsor from any connection manager. > - Connection management must not grant authority to act as another person. > - This change checks each sponsor on the server and limits the picker choices. > - The benefit is that ordinary members cannot assign work to another person's identity. ## Linked Issues or Issue Description **What happened?** A connection manager could save another member as a GitHub guest sponsor or automatic-task responsible member. The server checked membership but did not check authority to select that person. **Expected behavior** An ordinary manager can select only themselves. A company owner, company admin, or instance admin can select another active non-viewer member of the same company. The picker shows member avatars. **Steps to reproduce** 1. Sign in as an ordinary member with connection-management permission. 2. Open a GitHub bot's Access settings. 3. Set another member as a guest sponsor or responsible member. 4. Save. The old server accepts the request. This change returns 403. **Paperclip version or commit** Base: `9a9cd20d91edc93dba4e2295e42f0f1f9fcd4862`. **Deployment mode** Built from source. The checks use local PostgreSQL and an assembled authenticated API server. Related work: #17737 adds delegated connection configuration. #16163 separates author selection from guest access. This fix preserves both contracts. A search found no duplicate sponsor-permission fix. ## What Changed - Check every submitted sponsor in the configuration transaction. Lock the actor's membership and any required admin role through the save. - Require self-selection unless the actor has a current admin role. Check all target members in the same company. - Keep delegated connection checks, authority notifications, tool updates, and audit attribution. - Use avatar pickers for guest sponsorship and automatic-task responsibility. Default new guests to the signed-in member. - Test service and HTTP denials, admin selection, role removal, invalid targets, saved settings, and picker choices. - Test forged sponsor changes with real agent API keys and run credentials. Update the existing access-map policy. ## Verification - 67 sponsor, HTTP, picker, and settings tests pass. The picker test includes 600 members and bounds member lookups. - 93 existing GitHub management, event, policy, and tool tests pass. - The assembled connection-management fixture passes. Self-save succeeds. Both credential types receive 403 for forged guest and responsible-member sponsors. The saved revision stays unchanged. - UI typecheck and production build pass. Token gates, map checks, query-error policy, migration checks, and whitespace checks pass. - Two broad chat-test shards pass: 720 cases. The local full-suite run was then stopped; the complete local suite has no final verdict. Current-head CI remains the full verification path. - Full local typecheck and build reach Rust but cannot finish because Cargo is absent. - CI found the explicit retry override in the access query. Removed it; all 45 affected UI tests pass and the CI policy gate passed on the next commit. - Historical head `4146c89f9345efd38a69739d17e3194a7cf91980` received Greptile 5/5 and passed full CI: https://github.com/paperclipai/paperclip/actions/runs/43330028028 . Those results apply to that earlier head. - Current head `890df0322f382bb8ccc0fd3d59b25ba1e0299c58` merges master without conflicts. All eight changed files match the earlier reviewed fix. The 67 focused sponsor, HTTP, picker, and settings tests pass again. The production-bearer fixture also passes for both agent-key and run-token requests. UI typecheck, token gates, map checks, query-error policy, and whitespace checks pass. - Greptile gives current head `890df0322f382bb8ccc0fd3d59b25ba1e0299c58` 5/5 with no open review threads. All checks for this head are complete with no failures. The PR workflow passed: https://github.com/paperclipai/paperclip/actions/runs/43363400247 . This includes build, typecheck, general tests, serialized server suites, Runner checks, policy checks, and all eight E2E shards. The Snyk status also passed. - `pnpm verify --explain` returns exit 2 because the access-map change selects broad CI. The focused local checks pass. Broad checks are assigned to the CI run above. - The first broad checks inspected upstream migrations before the merge commit existed and stopped at migration classification. After the merge commit, the migration checks pass with zero new migrations. - Earlier saved-session broad checks stopped because Cargo was absent or memory was exhausted. These gaps are retained here. No live external-provider delivery or staging deployment is claimed. The configuration service owns sponsor authorization because both board and delegated API requests use it. No provider protocol or execution contract changes. ## Risks - An ordinary manager cannot save a configuration that names another sponsor, even when that sponsor is unchanged. They must select themselves or have an admin save it. - Membership and admin rows stay locked through the configuration write. A concurrent role change can delay the save. - Existing configurations are not rewritten. Each new save must pass the current checks. - Generic channel and AgentMail creation derive the sponsor from the authenticated user. Their strict input schemas do not accept sponsor overrides. ## Model Used OpenAI Codex, based on GPT-6. The exact runtime model ID and context-window size are not exposed in this session. Used reasoning, repository inspection, tool calls, code execution, and tests. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details available in this session) - [x] I have checked ROADMAP.md and confirmed this fix does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have described the issue with the bug-template field labels - [x] I have not referenced internal or instance-local Paperclip issues or links - [x] My published branch name describes the change and contains no internal task details - [x] I have run the focused tests locally and they pass - [x] I have added relevant tests - [x] I have updated the relevant access policy documentation - [x] I have considered and documented the risks - [x] All Paperclip CI gates are green for the current head - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
08be8be414 |
fix(recovery): report exact retained sandbox resumes as resumed (#21259)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - A controller restart must keep the same remote execution owner. > - A retained sandbox lease stores the result of its first acquisition. > - That result can say replacement after the same allocation resumes. > - The Runner then rejects a valid resume as a changed sandbox. > - This pull request reports the verified operation as resumed. > - The saved acquisition history and identity checks stay intact. ## Linked Issues or Issue Description Refs #18934. That change makes the retained sandbox ready before preparation. This change corrects the acquisition receipt after that resume. **What happened?** A remote native run resumed the exact retained sandbox after a controller restart. The lease still carried a historical replacement receipt. Runner verification rejected it with `native_remote_recovery_lease_mismatch`, stage `runner_verification`, field `replacement_sandbox`. **What did you expect to happen?** Report the verified exact-allocation operation as resumed. Preserve the original saved history. Reject a changed, absent or expired allocation. **Steps to reproduce** Save an active lease with historical replacement metadata. Resume that exact provider allocation through `acquireForRun`. Resolve its execution target. Before the fix, the target still reports replacement and Runner verification refuses it. **Deployment mode** Native Runner on a remote sandbox. The reported provider was Daytona. ## What Changed - Return a separate operation receipt after the exact retained allocation passes the existing resume checks. - Pass the receipt through heartbeat preparation and apply it only to the execution target. - Keep the saved lease metadata and workspace unchanged. - Test historical created, replacement and resumed receipts. Test ordinary and remote-authority realization through the real execution target resolver. Check every saved metadata write. - Document the difference between saved acquisition history and the current resume operation. ## Verification - Head: `74d03e8ddadd1274891bea99a10455795c500557`. - Red: three historical receipt cases fail without the resume receipt. - Review regression red: realization writes resumed over the historical replacement receipt. The saved metadata loses the previous allocation and cause. - Green: all 69 orchestrator tests pass. Ordinary and remote-authority realization preserve history in every metadata write and return resumed in the target. - Green: 135 focused orchestrator and remote controller adoption cases pass. Identity and changed-allocation refusals remain effective. - Server typecheck passes, including its TypeScript build dependencies and test layers. - `git diff --check` passes. - `pnpm verify` exits 2 because the execution-semantics document needs broad CI. Required CI supplies that coverage. - Linux x64, Node 25.9.0. Provider boundaries are simulated. - The first post-merge attempt could not collect tests because the compiled plugin SDK lacked the new taskLease schema. Shared and plugin SDK builds passed, then the unchanged selection passed. - Full preflight stopped because Cargo is absent. Dependency installation completed. The later server TypeScript build and typecheck passed. - Live retained Runner reattachment is not verified. This workspace has no provider credentials. No rollout or original-task recovery by this patch is claimed. - Required current-head CI and automated review remain pending. ## Risks A wrong receipt could hide an actual replacement. The projection occurs only after the existing company, task, run, agent, workspace, provider allocation, expiry and directory checks pass. The provider must resume the exact allocation. Runner process and identity verification still runs. No replacement is acquired and no saved acquisition history is changed. The heartbeat change only carries the typed receipt between the owning orchestrator stages. Callers without a receipt keep their existing behavior. ## Model Used OpenAI GPT-6 through Codex, with reasoning, repository inspection, code execution and tool use. The exact backend snapshot and context window are not exposed. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
2b1d0fc825 |
fix(connectors): keep result classification alive during run progress (#20763)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - App connectors screen returned content before they give it to an agent. > - The model screen checks run identity and reserves its budget in one transaction. > - That transaction took a repeatable-read snapshot before it locked the run. > - A run event could change the row first and cause all four attempts to fail. > - This pull request uses READ COMMITTED for this admission under the existing locks. > - The benefit is that connector results can pass screening while run progress continues. ## Linked Issues or Issue Description Refs #20385 and #20484. These changes fixed other run accounting paths. They did not change classifier admission. **What happened?** A connector read can return the accounting contention error before the model screen starts. A real gateway test reproduces SQLSTATE `40001` at `prompt-injection-prevention.ts` when it reads `heartbeat_runs FOR SHARE`. Each attempt commits a run event after the transaction starts its snapshot. **Expected behavior** Return screened connector content and save its classifier charge while run events continue. Refuse paid classification if the run stops, its identity changes, or access or budget checks fail. **Steps to reproduce** Run this test with the production source from `9574065a28`: `cd server && pnpm exec vitest run src/__tests__/prompt-injection-gateway.test.ts -t 'returns a screened connector result'` The test fails after four `40001` errors. It passes with this change. ## What Changed - Use READ COMMITTED only for prompt-injection admission. Keep company, project, configuration, agent, run and secret share locks. - Keep classifier settlement at repeatable read. Keep provider calls outside transaction retries. - Test screened results, stored charges and settled holds under run progress. Test four concurrent reads and refusal after a run stops or changes identity. - Document the transaction boundary. ### Hypothesis and thesis for a fix **Hypothesis:** the classifier admission snapshot becomes stale before its run share lock. The gateway regression confirms this cause in current source. The historical connector error alone does not identify its SQL statement. **Thesis for a fix:** read current run state under the existing locks at READ COMMITTED. This removes stale snapshots caused by run events. The change belongs to classifier admission because every screened connector result uses this service. Investigation source: [Braintrust pattern](https://www.braintrust.dev/app/Paperclip/p/Paperclip%20Staging/patterns/d5369c32-4c0f-43a1-af94-a01fef0a697b). Access is required to read the traces. **Proof:** baseline `9574065a28` failed with `40001` after four attempts. The same single-read regression passed after the change. The full focused suites then passed, including four concurrent reads, stored charges and refusal controls. ## Verification - Real PostgreSQL gateway regression: baseline red in 28.07 seconds; candidate green in 23.16 seconds. - `cd server && pnpm exec vitest run src/__tests__/prompt-injection-gateway.test.ts src/__tests__/prompt-injection-prevention.test.ts`: 54 tests passed. After sync with master `1ac8b6a711`, all 54 passed again in 34.46 seconds. - The tests use the real gateway, content guards, classifier service and database. The MCP server and paid model are simulated. This is not a live deployment test. - Existing controls cover company boundaries, budgets, credentials, configuration changes, interruption and receipt recovery. - Staging health reported `16024ffa2`. Its classifier and accounting source matches the reproduced baseline and includes #20385 and #20484. The revision at the earlier failure times remains unknown. - `pnpm verify` selected 2,512 of 3,303 test files because its dependency policy retained 2,510 files conservatively. The broad local run was stopped after the selection became clear. It is not a pass. The focused 54-test result above is the local proof; required CI supplies broad coverage. An earlier selection was also invalidated by a concurrent commit. - Full preflight could not finish because this host has no Cargo. Pinned dependencies and shared/plugin SDK builds completed. The focused tests passed without Rust. - [Greptile reviewed this head at 5/5](https://github.com/paperclipai/paperclip/pull/20763#issuecomment-6790238737). No inline thread is open. [Paperclip completed its assessment at 5/5 with no findings](https://github.com/paperclipai/paperclip/pull/20763#issuecomment-6790312753). [Required CI passed for head `643bbe51faa70dcb17f372b9e85e3cbbcb724b9d`](https://github.com/paperclipai/paperclip/actions/runs/42981473514), including typecheck, build, 12 server test shards, nine serialized suites, eight E2E shards and Runner checks. Snyk and Socket passed. The full inventory contains 58 completed check runs; the neutral Paperclip check is a completed 5/5 assessment, not an incomplete review. ## Risks - READ COMMITTED uses a new snapshot for each statement. Existing admission locks still protect the run status, identity, configuration and secret checks. Budget checks and reservation writes still commit together. - Concurrent independent admissions retain existing budget behavior. This change adds no retry of paid provider work. - No schema, API or saved receipt format changes. - Historical failing SQL is unavailable. The source regression proves this failure path; it does not prove that every historical example has the same cause. - The change is unmerged and not deployed. ## Model Used OpenAI GPT-6 through Codex, with reasoning, repository tools and code execution. The exact deployment model ID and context-window size are not exposed. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal Paperclip ticket id - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
1e33415f67 |
test(runner): run Kimi layout suites once in prep (#20487)
<!-- All text in Simplified Technical English. -->
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - The Runner package has node:test suites that verify the pinned Kimi
Code native runtime layout.
> - `test:typescript:prep` selects each Kimi layout suite directly. The
same command also selects the `build-verified-provider-entrypoints`
aggregator. The aggregator imported the same four Kimi suites.
> - One command therefore registered every Kimi layout test twice.
Commit
|
||
|
|
cfa959add7 |
refactor(slack): correct stale status comment and add production acceptance checklist (#20840)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The Slack chat connector lets people talk to their agents in Slack > - The connector is close to production, but its live evidence is out of date > - The September live results use old revisions, and the October setup run did not test follow-up, reauthorization, or removal > - Cloud managed setup has never run against real Slack, and its docs say not to enable it until it has > - This pull request adds one checklist for a fresh live pass on current master, and corrects one stale code comment > - The benefit is a clear finish line for Slack production readiness on self-hosted and Cloud ## Linked Issues or Issue Description **Issue type** Missing documentation. **Where is the issue?** `doc/connections/SLACK-AUTOMATIC-SETUP.md`, `doc/plans/chat-adapters/2026-09-05-slack-live-qualification-result.md`, `doc/testing/slack-cloud-qualification.md`, and `server/src/services/chat-channels.ts`. **What's wrong?** The Slack live qualification is spread over three documents. Their evidence uses older revisions. No document lists what a production pass must cover for Cloud managed setup. A code comment says the manifest does not request `assistant:write`, but the manifest does request it. **Suggested fix** Add one dated acceptance checklist with pass conditions per row. Correct the comment. ## What Changed - Added `doc/plans/2026-11-11-slack-production-acceptance.md`. It has sections for self-hosted automatic setup, manual and existing apps, conversation behavior, Cloud managed setup on staging, and distribution questions (Marketplace-only workspaces, non-Marketplace rate limits, scope justification, zero-copy). - Corrected the comment in `server/src/services/chat-channels.ts`. It now says that Slack shows the working state through `agents.sessions.setStatus` and the lifecycle reply. No code behavior changed. ## Verification - Documentation and a comment only. No runtime behavior changed. - I checked the doc links and the referenced files against current master. ## Risks - Low risk. The change is documentation and one comment. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and web search. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [ ] I have run tests locally and they pass - [ ] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
e5158293c5 |
perf(ui): keep the live socket when a cached session is verified (#20591)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The board UI keeps one live-updates WebSocket per company and saves
a copy of its query cache in `localStorage` so a returning visit can
paint from it
> - On a returning hard load of the Mine inbox, about eight shell and
inbox reads ran a second time 1.5–2.5 s after load (session, health,
company list, agents, inbox dismissals, user directory, approvals,
execution workspaces)
> - The cause is the socket's sign-in key. A session restored from the
saved cache has the user but no session id. The first session read adds
the id, the key changes, the socket closes and opens again, and that
second open refreshes every active query, session and health included
> - This pull request keeps the socket when the verified session belongs
to the same user as the restored one
> - The benefit is one read of each shell request per returning load and
one socket instead of two, with no change to the catch-up read that
covers the gap before the first subscription
## Linked Issues or Issue Description
**What happened?**
A returning hard load of `/:companyPrefix/issues?view=mine` sent
`auth/get-session`, `health`, `companies?scope=accessible`, agents,
inbox-dismissals, user-directory, approvals and execution-workspaces
twice. The second copy started about 1.5–2.5 s after load on the hosted
staging instance.
**Steps to reproduce**
1. Open Mine once so the app saves its query cache.
2. Reload the page.
3. Watch the network panel. The live-updates socket opens, closes, opens
again, and the reads above repeat.
**Expected behavior**
Each read runs once. The socket opens once.
Related: #20398 (socket reconcile skips settings and preferences),
#20407 and #20419 (Mine reveal and its perf guard).
## What Changed
- `ui/src/context/LiveUpdatesProvider.tsx`: the socket auth key comes
from `nextSocketAuthScope`. When the previous scope has the same user
and no session id, the first known session id is adopted without a new
key. A different user, or a different session id once one is known,
still produces a new key and a new connection.
- `ui/src/context/LiveUpdatesProvider.recovery.test.tsx`: two tests. A
restored session (no id) verified for the same user keeps the socket and
invalidates nothing; a later replacement session still reconnects. A
verified session for another user reconnects.
- `tests/perf/collections/shell-read-waves.spec.ts` and
`returning-visit-fixture.ts`: browser checks on a production build with
every API response delayed 300 ms. With a saved cache, each of the eight
reads runs at most once and the socket opens once. Without a saved
cache, session and health run once, no read runs more than twice, and
the socket opens once.
- `tests/perf/collections/README.md`: documents the new spec and
fixture.
## Verification
- `cd ui && pnpm exec vitest run src/context/`: 16 files, 286 tests
pass. The new same-user test fails on `master` (socket count 2) and
passes with this change.
- Browser check on a disposable local instance (production UI build,
`local_trusted`, embedded PostgreSQL, Chromium headless, 1440×900, API
+300 ms):
`PAPERCLIP_COLLECTION_PERF_BASE_URL=http://127.0.0.1:<port> pnpm exec
playwright test --config tests/perf/collections/playwright.config.ts
shell-read-waves.spec.ts`
- `master` build (`99edcd28a7`): returning visit fails with
`{"auth/get-session":2,"health":1,"companies?scope=accessible":2,"agents":2,"inbox-dismissals":1,"user-directory":1,"approvals":1,"execution-workspaces":0}`.
- This branch: both tests pass; every count is 1 and one socket opens.
- Timing evidence (same instance, 5 fresh contexts per arm, API +300 ms,
host load average about 20; `mine-returning-visit.spec.ts` timing case
from the companion Mine PR). Duplicate shell reads are summed over the 5
loads:
| Build | Saved cache: time to rows, median (range) | Saved cache:
duplicate shell reads | Cleared cache: median (range) | Cleared cache:
duplicate shell reads |
| --- | --- | --- | --- | --- |
| `master` | 1028 ms (906–3011) | 5 (session ×2 each load) | 1502 ms
(1423–1592) | 5 (company list ×2, the catch-up) |
| This PR | 895 ms (880–930) | 0 | 1364 ms (1328–1408) | 5 (company list
×2, the catch-up) |
The time difference is small and inside host noise; the claim here is
the removed reads and the single socket. On the busier hosted instance
the second wave was larger (about eight reads), because more reads have
answered before the session read returns.
- Review follow-up (
|
||
|
|
8aaf983151 |
perf(db): send a transaction's work notifications in one statement at commit (#21436)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The server signals queue work with database work signals, and it
sends a PostgreSQL notification for each signal so that another server
can wake during a deploy overlap
> - Each signal sends its own `select pg_notify($1, $2)`, inside the
open transaction, and waits for it
> - On staging this is the most-called statement in the database: 31.8
per second, 15.1 million calls in total against 7.5 million `begin`,
about 3.7 awaits per transaction
> - Every await inside an open transaction holds its locks and its
connection for one more turn of a saturated event loop
> - This pull request collects a transaction's notifications and sends
them in one statement just before commit
> - The benefit is at most one notification round trip per transaction,
with the same payloads delivered at the same commit
## Linked Issues or Issue Description
**What existing behavior does this improve?**
Database work signals send one `pg_notify` statement per signal, inside
the transaction.
**Subsystem affected**
`packages/db` work signals, used by every delivery queue in the server.
**Current behavior**
`signalDatabaseWork` and `notifyDatabaseWorkOnCommit` each run `select
pg_notify(channel, payload)` on the transaction and wait for it.
`notifyIssueRecovery` alone signals 7 queues per call, and a transaction
often calls it several times. A local legacy run (wake, start, 20 output
lines, finish) sends 424 notification statements. Staging measures 31.8
per second, 8.5 `begin` per second.
**Proposed behavior**
A signal inside a transaction records its payload on that transaction.
Before the outermost commit, the transaction sends every distinct
payload in one statement. Payloads and the channel are byte-identical to
today's, and PostgreSQL still delivers them only on commit.
**Reason and benefit**
At most one notification statement per transaction instead of one per
signal. Fewer awaits while a transaction holds its locks and its
connection.
**Breaking changes**
None. The listener protocol and the payload format do not change.
## What Changed
- `packages/db/src/work-signals.ts`: a signal records `(channel,
payload)` on the current transaction level. A released savepoint merges
its records into its parent; a rolled-back savepoint drops them. The
outermost transaction sends all distinct payloads in one statement
(`select pg_notify(channel, payload) from
jsonb_array_elements_text($2::jsonb)`) after its callback returns and
before commit. A transaction that signals nothing sends no extra
statement.
- The record lives on the transaction object only. A retried callback
gets a new transaction object and starts empty.
- `publishDatabaseWorkHint` (outside a transaction) is unchanged and
still sends at once.
- `packages/db/src/work-signals.test.ts`: tests on real PostgreSQL with
a LISTEN client.
## Verification
- `pnpm --filter @paperclipai/db exec vitest run
src/work-signals.test.ts`: 22 pass. 6 of the new tests fail on master.
- New tests (real PostgreSQL, LISTEN client, asserting what is delivered
as well as what is sent):
- Distinct topics in one transaction: one statement at commit. The
payloads delivered are identical to the format on master (`{version,
origin, topic}`), in first-signal order.
- A transaction that signals nothing: no notification statement.
- Savepoints: a released savepoint two levels deep keeps its topic. A
rolled-back savepoint drops its topic. A topic from a rolled-back
savepoint that the outer level signals again is still delivered.
- The callback throws: nothing is sent or delivered.
- The commit-time send fails: the transaction fails and rolls back its
write, and nothing is delivered.
- 500 distinct topics: one statement, all 500 delivered.
- Sequential, concurrent and retried transactions each start clean.
- Server suites that use notifications pass: `deployment-notifications`,
`run-start-handover`, `heartbeat-run-start-handover`,
`agent-runtime-hooks`, `legacy-controller-lease`,
`heartbeat-run-dispatch-lifecycle` (99 tests). Two of them hit statement
timeouts once on a loaded machine and then passed 41/41 when run alone.
- Before and after, one local legacy run (embedded PostgreSQL, process
adapter, 20 output lines 50 ms apart, uninstrumented pass, alternating
arms):
`TSX_DISABLE_CACHE=1 UNITS=legacy TASKS=50 AGENTS=3
NODE_OPTIONS=--expose-gc pnpm --filter @paperclipai/server exec tsx
scripts/query-cost/drive.ts` (harness from #21413)
| Per legacy run | Before (2 runs) | After (2 runs) |
| --- | --- | --- |
| Statements | 883, 883 | 474, 491 |
| `pg_notify` statements | 424 | 21 (one per signalling transaction) |
| Notification round trips per signalling transaction | about 20 | 1 |
| Transactions (BEGIN plus COMMIT) | 72 | 72 |
| Allocated | 81.1, 79.3 MB | 76.3, 74.3 MB |
| Wall time | 5.0, 5.2 s | 4.1, 7.7 s (noisy: loaded machine) |
Statement counts are exact and stable. Allocation fell by about 5 MB per
run (about 6%). Wall time varies too much on this machine to compare.
- Staging, measured by the coordinator (Neon statistics, 64 seconds):
31.8 `pg_notify` per second, 8.5 `begin` per second. At about 44 KB of
allocation per statement, notifications cost about 1.4 MB/s, about 2.4%
of the 57.6 MB/s. The allocation saving is part of that, about 2%, and
it is not the reason for this change. The reason is round trips inside
open transactions: at most one notification statement per transaction
instead of about 3.7. The per-second effect on staging is an estimate
until it is measured after deploy.
## Risks
- A failure of the notification send now surfaces at commit time, not at
the signal call. No caller catches errors around a signal call and
continues: the only `.catch` near a signal (`notifyBudgetStopsSettled`)
wraps a root-level call that is not in a transaction and already fails
before this change.
- Order within a transaction: notifications are sent in first-signal
order. A savepoint's records join its parent when the savepoint is
released, which matches the order of sequential code. Listeners do not
depend on order: each payload is an independent hint, and PostgreSQL
already removes duplicate payloads within a transaction.
- The notification is sent after the transaction's last statement
instead of in the middle. Delivery still happens only at commit, as
before.
Remaining work, not in this pull request: sending stops being useful
when no other server listens. The listener is open only during a startup
handoff, while this process owns a native execution, or during a
run-start handover, and a server drops its own notifications. A later
change could send only while an overlap is possible. It would have to
prove this interleaving: a new server announces itself, the old server
is still outside its own window, and the old server must start sending
before the new server relies on a hint. Otherwise the new server waits
for its next reconciliation pass.
## Model Used
- Claude Opus 5.5 (claude-opus-5-5), Anthropic, with tool use and code
execution in Claude Code.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes (no
documentation describes the send timing)
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
c6b497d831 |
perf(auth): authenticate a run's agent JWT in three statements (#21434)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Each running agent calls the Paperclip API with a signed run token (an agent JWT) > - The server authenticates each of these requests before the route handler starts > - This authentication sent 13 statements to the database for each request, and none of them were cached > - One server process starts to struggle at about 50 concurrent agents, and the target is 1,000 > - This pull request cuts the work before the route handler to 3 statements, with no transaction and no row locks in the usual case > - The benefit is less database work and less event-loop work for each agent request, with the same security checks on each request ## Linked Issues or Issue Description Refs #16577 (trimmed saved run JSON from agent authentication) Refs #17931 (scoped run identity reads to the needs of each operation) **What existing behavior does this improve?** The authentication of an API request that an agent makes with its run JWT. Before the route handler starts, `actorMiddleware` did 13 database statements in sequence: a board key lookup, an agent key lookup, a `select *` of the agent, the run read, a 7-statement locked identity capture (BEGIN, run task read, task row lock, run row lock and wide row read, pending steering read, context read, COMMIT), and two reads for the responsible user. **Subsystem affected** Server: `server/src/middleware/auth.ts`, `server/src/middleware/agent-run-authentication.ts` and `server/src/services/run-identity.ts`. **Current behavior** Each agent request costs 13 statements. The identity capture is a transaction that holds a pooled connection and takes `FOR NO KEY UPDATE` locks on the task row and the run row. These are the same rows that event appends and steering lock, so agent requests wait behind them. **Proposed behavior** Each agent request costs 3 statements and no transaction: the agent status columns, one run statement, and one membership statement. A run with a pending steering context still uses the locked capture, so steering acceptance does not change. **Reason and benefit** Item 1c of the thousand-concurrent-agents plan. The load model at 50 agents (API requests only) shows the database statements for this path go from 165.7/s to 30.1/s, transactions from 15.1/s to 0, and event-loop utilization from 0.74 to 0.25. **Breaking changes** None. The actor shape that routes get does not change. No route handler changes. No schema change. ## What Changed - **Skip key lookups for a verified run JWT.** The middleware verifies the JWT first (HMAC only, no database). Every stored board key and agent key is `pcp_` followed by letters, `_` and hex (`createBoardApiToken`, `createToken`). A verified JWT has three parts with dots. So its SHA-256 cannot equal a stored key hash, and both lookups always returned no row for it. A token that does not verify still tries the board key, then the agent key, in the same order as before. - **Read only the agent columns that authentication checks.** `companyId`, `status` and `lifecycleHolds` replace `select *`. The agent configuration JSON stays in the database. The agent-key path uses the same columns. - **Read revocation and identity in one statement.** `loadAgentRunAuthentication` now also returns the run task ids, a `pendingIdentityContext` flag (`exists` on a pending context of this run), and the active context `id` and `responsibleUserId` (only when that context belongs to this run). The new `resolveRequestRunIdentity` in `run-identity.ts` uses these columns: - The run is not running, or it has no active context: it keeps the run row values, as before. - A pending context exists: it calls `captureRunIdentity(..., "request_authentication")`, as before. This keeps the locked accept-or-refuse step and the 409 for an unacknowledged steer. - Otherwise: it checks the run task ids with the same rule as `lockIdentityTask` (now `assertRunTaskIdentity`), and returns the context from the statement. - **Reuse the run row for the legacy responsible user.** The legacy lookup had the same filter as the run read. The middleware now uses the `responsibleUserId` from that read, with the same non-UUID guard. - **One statement for memberships.** The user existence check is an `exists` condition in the membership statement, in place of a second parallel statement. - No in-process memo and no time-based cache. Every request reads the current run row. ### Why the request-authentication read does not need the locks or the transaction The capture locks are released at COMMIT, before the route handler starts. So they do not protect anything that the route does. Inside authentication, they have two effects: 1. **They protect the acceptance write when a pending context exists.** This PR keeps this case on the locked capture. 2. **They make the read wait for a steering transaction that is in progress.** In PostgreSQL READ COMMITTED, one statement reads one snapshot. So the run status, the cancellation fields, the active context, its responsible user and the pending flag are all from the same committed state. Each interleaving with a steering writer gives a result that a serial order also gives: | Writer state when the statement runs | What the statement sees | Result | Same as a serial order? | | --- | --- | --- | --- | | Reservation (`reserveSteeredIdentity`) not committed | Old active context, no pending | Old identity, 200 | Yes: request before the reservation. The old identity stays active until the steer is accepted. | | Reservation committed | Pending flag | Locked capture: 409, or accept if acknowledged | Same code path as before | | Acceptance in progress (pending committed) | Pending flag | Locked capture waits for the acceptance, then returns the new identity | Same code path as before | | Acceptance committed | New active context, no pending | New identity | Yes: request after the acceptance | | Cancel or supersede committed | `cancelled`, `executionCancellation.state = requested`, or `freshContinuationSupersededAt` | 403 on a write | Yes, on the very next request | `activate()` writes `activeIdentityContextId` and `responsibleUserId` in one update, and the statement joins the context by id and run id. So a mix of an old context with a new user is not possible. The tests show the first and third rows on real PostgreSQL. ### Notes for reviewers (moved from code comments) - The two correlated subqueries in `requestRunIdentityFields` name `"heartbeat_runs"` and an alias for `run_identity_contexts` in raw SQL. Drizzle writes the columns of a one-table select without the table name, so a `${heartbeatRuns.id}` inside the subquery would resolve to the inner table. The first test run showed this (the identity came back empty), and the statement-count test catches it. - The `exists` condition in `loadResponsibleUserMemberships` keeps the old rule: a membership counts only while its user exists. - The legacy responsible-user value comes from the run read, because that read has the same filter (`id`, `company_id`, `agent_id`) as the removed legacy lookup. ## Verification - New `server/src/__tests__/agent-jwt-request-authentication.test.ts` (embedded PostgreSQL, real `actorMiddleware`, `meterDatabaseStatements`): - Statement count: 3 statements, 0 transactions, 3 waits for a running agent with an active identity and a responsible user. Before: 13 statements. The test also checks that fewer than 8 KiB come back, with a 120 KB agent configuration. - Revocation: a write that passes is refused on the very next request after `status = cancelled`, after a Stop request (`executionCancellation.state = requested`), and after a fresh-continuation supersede (`agent_run_superseded`). - Identity change between two requests: the next request uses the new context and the new responsible user. - Uncommitted steering reservation: the request does not wait, and keeps the committed identity. After commit, the next request gets 409. After the acknowledgement, the next request gets the new identity. - Acceptance in progress: the request waits for it (locked capture), then returns the new identity. - Wrong claims: an agent token signed for another company gets 401. A token that names another agent's run gets no identity from that run. An active context id of another run is not used. - Pending steering without an acknowledgement still gets 409. - Red/green: on `origin/master` code, the statement-count test failed with 13 statements, and the uncommitted-reservation test failed because the request was blocked on the row lock. Both pass with this change. - `agent-auth-identity-transfer.test.ts`: the heartbeat_runs read count is now exactly 1 (it was a lower bound of 3). - These pass: `agent-auth-middleware.test.ts`, `agent-auth-identity-transfer.test.ts`, `agent-run-authentication.test.ts`, `run-identity.test.ts`. - `pnpm verify`: it selected 2,639 of 3,459 Vitest files, because `auth.ts` is imported by most route tests. That is close to the full suite, so I stopped it at 30 minutes on this busy machine (exit 124, no failures before the stop). CI supplies the broad coverage. The focused checks above pass on the final revision (41 tests). - `pnpm check:module-boundaries`: passed. Server `tsc --noEmit`: passed. - Load model (`scripts/benchmark-agent-scaling-load.ts` from the plan branch, not committed), `AGENTS=50 SECONDS=20`, one run at a time. The machine had a load average of 25 to 33 from other work, so the timings are noisy. The statement and transaction counts are not affected by the noise. | `SOURCES=api` | Before | After | | --- | --- | --- | | Statements/s (15 requests/s) | 165.7 | 30.1 | | Statements per request (this model has no responsible user) | 11 | 2 | | Transactions/s | 15.1 | 0 | | Event-loop utilization | 0.741 | 0.252 | | Event-loop delay p99 | 267.8 ms | 19.0 ms | | API lateness p50 / p99 | 1104 / 5631 ms | 6.7 / 79 ms | | All sources | Before | After | | --- | --- | --- | | API requests done | 300/300 | 300/300 | | API lateness p50 / p99 | 291 / 1130 ms | 230 / 2681 ms | | Delta appends done | 14977/20000 | 8260/20000 | The all-sources run is limited by delta appends, which this PR does not change. Its results move a lot between runs on this busy machine (the delta count is lower after, with no change to that path), so it does not show an effect of this PR in either direction. ## Risks - The usual path no longer waits for a steering reservation that is in progress. The request then uses the identity that is committed and active. This is the identity that the run acts under until the steer is accepted. The table above shows that each interleaving matches a serial order. - `loadAgentRunAuthentication` returns more columns (two small correlated subqueries on `run_identity_contexts`, by primary key and by the `(run_id, ...)` index). Other callers get extra fields and ignore them. - The JWT-first order depends on the stored key format. If a new key format can contain three dot-separated base64url parts that verify as a JWT, this order must be checked again. - Low risk for routes: the actor object is the same, and no route handler changes. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), by Anthropic, in Claude Code with tool use (shell, file edits, test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
16f00d62fb |
fix(connections): answer setup questions with a setup link in ranked results too (#21428)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - #21400 told the agent to answer a setup question ("What is the easiest way to connect Notion here?") with a setup-page link, because `connection_request` ends the turn before any answer text is shown > - That rule covered only a single search match > - In a paid eval run the agent searched "Notion integration connect workspace", got ranked matches, raised the card and ended with no answer > - This pull request adds the same rule to the ranked-matches instruction > - The benefit is that a setup question gets a written answer with a working setup link, whichever search the agent runs ## Linked Issues or Issue Description Refs #21400. This commit was pushed to #21400 after it merged, so it is a follow-up. **What happened?** Paid run 43455387724, case `connection-setup.choose-provider`: the agent called `connections_search` with a multi-word query, got the ranked-matches instruction ("Use connection_request when human setup or access is required"), called `connection_request`, and the turn ended as "Waiting for Connect Notion" with no text reply. **Expected behavior** For a setup question, the agent answers in plain words and links `/<prefix>/apps/connect?source=<app>`. For a data request, it raises the setup card. **Steps to reproduce** 1. Have no Notion connection. 2. Ask "What is the easiest way to connect Notion here?" and let the agent search with a multi-word query. ## What Changed - `server/src/services/connection-intents.ts`: the ranked-matches instruction says to use `connection_request` for data or actions the person asked for, and to answer a setup question with the app's setup-page link instead. It also says not to create a connection or draft unless the person asked for setup. - Test: the ranked instruction includes the setup-page rule. ## Verification - `cd server && npx vitest run src/__tests__/connection-intents-service.test.ts -t "own-server"`. - Paid run 43460401711 on a branch with this change: `connection-setup.choose-provider` passed (answer with `[Connect Notion](/COM/apps/connect?source=notion)`), `connection-setup.notion-declined` passed. ## Risks - About 60 more words in one tool result. No effect on agent boot or time to first token. ## Model Used - Claude, claude-opus-5-5, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
d9b977baf2 |
fix(runner): answer a live Runner's commands while it replays its backlog after a reconnect (#21442)
**DO NOT MERGE until the coordinator confirms the Daytona validation.**
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - A native run on a remote sandbox is driven by a Runner process. The
server talks to it over PRP and saves the controller state in a
checkpoint.
> - After a release swap, the incoming server reconnects to Runners that
kept working while no server was attached. Each Runner first replays the
events it built up.
> - The server answered commands one at a time and only after every
event queued ahead of them. It wrote one checkpoint and one
acknowledgement per event. A recovery read sent at reconnect therefore
timed out at 30 s behind the replay, although the Runner was alive and
had answered.
> - A tool call that the previous server started and never answered
blocked every later command, and a failed close was replayed forever.
> - This pull request lets read and barrier answers pass the replay,
extends a wait while the replay still commits, acknowledges a replayed
burst once per batch, delivers every pending command at attach, settles
an orphaned tool call at attach, and retries a close whose drain timed
out.
> - The benefit is that a live Runner is reached after a late reconnect
instead of being declared unanswered and then replaced, which lost its
turn.
## Linked Issues or Issue Description
**What happened?**
Hosted staging, release swaps on 2026-11-13 (06:05Z to 09:45Z). For each
run that crossed a swap we measured the gap from the last Runner output
to the moment the new server recorded the Runner's process identity:
- gap under 150 s: 0 of 9 runs failed
- gap over 420 s: 14 of 15 runs failed
- median gap: 180 s for runs that resumed, 470 s for runs that failed
Authentication took under 1 s. The identity was recorded 4 to 7 minutes
later, because it is written only after the Runner answers `run.attach`,
`runner.drain` and the thread read. Those answers waited behind the
replayed event backlog. The failure codes on the first attempt were:
- `PRP command session.snapshot timed out` and
`codex_history_read_failed: thread/turns/list read failed` (all 10
`ingress` runs in the sample)
- `PRP command runner.drain timed out (runner connected; pending ahead 2
[semantic_tool.result] oldest 1023s)` on the retry
A separate class, `cleanup_quarantined` (23 failures in 3 hours, no swap
involved), showed "prior session cleanup remains incomplete" on every
retry, because a close that failed once kept replaying the same
rejection.
A live Daytona capture showed the stale `semantic_tool.result`: Codex
waited for the result of an exec tool call that the stopped server
owned. It was not an unacknowledged frame.
**Expected behavior**
A live Runner answers recovery commands within its deadline after a late
reconnect. A tool call left by an earlier controller is settled once
(with its durable receipt, or as interrupted with an unknown outcome,
never executed again). A close that failed only because its journal
drain timed out reaches its real outcome on the next close.
**Steps to reproduce**
1. Start a control plane with a commit callback that takes 50 ms per
event.
2. Connect a Runner that replays 1,000 events, then send
`session.snapshot`.
3. On master the snapshot times out at its 30 s deadline. The new test
`answers a command issued during a 1,000-event replay within its
deadline` does this.
**Paperclip version or commit**
`master` at
|
||
|
|
89e6575418 |
test(native-runtime): cover released session tool authority and add a catalog memory benchmark (#21440)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Native agent runs get their tools from a session tool authority, which holds the run's assigned app (MCP) tool catalog > - #21415 releases a finished session's authority, so the server heap no longer grows with each finished session > - Two behaviors of that fix had no test: a released session fails closed, and the release when a follow-up run retires its warm predecessor and then fails before it admits its own authority > - The memory saving was measured once, by hand, with no script in the repository > - This pull request adds the two tests and a benchmark script. It changes no product code > - The benefit is that a later change cannot silently bring back the leak or let a released session reach its tools ## Linked Issues or Issue Description Refs #21415 (the fix these tests cover). Refs #21430 (closed duplicate; a reviewer comment there named the follow-up failure path). **What is missing?** #21415 tests that finished sessions return the authority map to its starting size. No test checks that a released session refuses late tool calls. No test checks the follow-up path, where a follow-up run retires the previous warm session (so the release at forget time is skipped while the follow-up owns the scope) and then fails before it admits its own authority. **Expected behavior** A late tool call or completion feedback for a released session fails with `native_session_tool_authority_unavailable`. The next run of the same scope gets a new authority with only its own assignments. When a follow-up fails after it retires its predecessor, the authority map is back at its starting size after that run settles. **Paperclip version or commit** master `edb6945ff3` (after #21415, `85f4a91e70`). ## What Changed - Test "refuses a released session's late tool call and completion feedback and admits the next run with only its own assignments". - Test "releases a retired warm predecessor's tool authority when the follow-up fails before admitting its own". A follow-up of the same warm scope with changed configuration retires the predecessor. Then its assigned tool listing fails. The test asserts that the predecessor was closed, that the follow-up failed with that error, and that `sessionToolAuthorityCount()` is back at its starting value. - `server/scripts/benchmark-assigned-mcp-tools-memory.ts`: retained bytes of one assigned tool catalog per session, and schema copies per `definitions()` call. ## Verification - `cd server && npx vitest run src/services/native-runtime/native-session-executor.test.ts -t "released native session tool authority|retired warm predecessor"`: 2 passed. - Red check: with the release at settle removed from `native-session-executor.ts`, both tests fail (`expected 1 to be +0`, and the late tool call is not refused). - Retained bytes per finished per-turn session were measured through `executePaperclipNativeSession` with the real `createAssignedMcpTools` (80 tools, 2 KB schemas, 100 sessions, forced GC, `heapUsed` delta). On `85f4a91e70^` (before #21415): 604,566 bytes. On `85f4a91e70`: 19,794 bytes (test-harness noise), and the authority map stayed at its starting size. - `cd server && node --expose-gc --import tsx scripts/benchmark-assigned-mcp-tools-memory.ts --tools 80 --schema-bytes 2048 --sessions 200 --turns 20` reports about 546 to 567 KB retained per assigned tool catalog. Each `definitions()` call makes 80 new schema copies (about 296 KB), and none are kept. - Full `native-session-executor.test.ts` locally, with a load average near 78 from other work on the machine: 1,483 passed and 5 failed. All 5 failures were timeouts in tests this change does not touch (the slowest took 163 s). CI gives the clean full-suite result. ## Risks - Low risk. Tests and one benchmark script only. No product code changes. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
df1b12ad8e |
fix(runner): advertise flat tool schemas and stop repeated runner-side input rejections (#21398)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents act through Paperclip tools. The runner shows each tool to
the model with an input schema and checks every call against that schema
before it runs
> - Some tool schemas had a root `oneOf`, `anyOf`, `allOf` or
`if`/`then`. `handoff_case` had no top-level `properties` at all
> - Some model hosts convert such a schema into an empty argument list.
The model then calls the tool with no arguments, and the runner rejects
the call as "Invalid tool input"
> - The repeated-failure guard from #21360 does not see these
rejections, because they happen in the runner before the call reaches
the control plane. The model sent the same rejected call again and again
> - This pull request gives every agent-facing tool a plain object
schema with named properties, checks the old cross-field rules with
named errors, and adds a runner-side guard for identical "Invalid tool
input" rejections
> - The benefit is that models on these hosts can see and send the
arguments, and a dropped argument ends in a clear correction or a stop,
not a long loop
## Linked Issues or Issue Description
**What happened?**
In a chat eval cohort with OpenCode and
`openrouter/deepseek/deepseek-v4.1-flash-1017`, the hosts Wafer and
DigitalOcean served most model calls. In the case handoff case,
`handoff_case` arrived with no arguments on all 10 calls across two
cases. The runner rejected each one with "must have required property
idempotencyKey, case, toAgentId, ...". The model's reasoning said that
the tool showed an empty property list. The model fell back to
`call_api`, but the reply waiter had already expired, so the case
failed. In the preserve-draft case, `request_human_input` was rejected 9
times in a row with the same root `then` error.
**Expected behavior**
Every tool that an agent sees has a plain object schema with named
properties, so every host can show its arguments. When the same call is
rejected twice with the same arguments, the model gets a correction that
lists the expected properties. On the third identical call, the model is
told to change the arguments or stop.
**Paperclip version or commit**
`master` at
|
||
|
|
64ec273845 |
perf(ci): run the typecheck lane's checks in parallel and drop its duplicate server type check (#21404)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Every pull request runs the trusted PR workflow, and the `Typecheck + Release Registry` job is one of its required checks > - That job takes about 9.2 minutes on the 4 vCPU / 16 GB fleet runner (run 43344818387), against a target of 7 minutes or less for every job > - The job runs six steps one after another, and the first step type-checks the whole server program a second time, at about 13.5 GiB, which makes the runner swap > - Typecheck results are the check that authors most want back quickly, so this job is on the critical path of most pull requests > - This pull request removes the duplicate server type check and runs the independent checks in parallel through one small script, inside the same memory budget > - The benefit is about 39% less wall time for the job's checks on the same machine, with peak memory down from about 14 GiB (plus swap) to about 8.5 GiB ## Linked Issues or Issue Description **What existing behavior does this improve?** The `Typecheck + Release Registry` job in `.github/workflows/pr-trusted.yml`. It takes about 9.2 minutes. The target for every job in the workflow is 7 minutes or less. **Subsystem affected** CI (`.github/workflows/pr-trusted.yml`) and the typecheck scripts under `scripts/` and `server/scripts/`. **Current behavior** After about 75 s of setup, the job runs six steps in sequence on a 4 vCPU runner, about 470 s in all (run 43344818387): `typecheck:build-gaps` 121 s, test programs 85 s, server layers 128 s, test projects 38 s, CLI guidance test 5 s, release registry tests 95 s. Most of these steps use one thread. The `typecheck:build-gaps` step builds the server with a full type check of the whole server program. The server layer step then checks the same files again, and the `Build` job checks them a third time. That full program peaks at about 13.5 GiB, so the job peaks at about 14 GiB of 16 GiB and uses swap. **Proposed behavior** The job runs `node scripts/ci-typecheck-lane.mjs`. The script builds the server without type checks (`PAPERCLIP_TSC_EMIT_ONLY=1`, as the Docker image does) and still checks the runtime assets. It runs the steps that write shared files first, one at a time. Then it runs the remaining checks in parallel, one per CPU, with the server declaration layers first, because the test layers and test projects read them. The checks that are not on that path run at a lower CPU priority. **Reason and benefit** On the same runner, the job's checks take 61% of the time and about 60% of the memory (see Verification). The job should take about 6 minutes on the fleet instead of 9.2. **Breaking changes** None. The same files are type-checked with the same options. Local commands do not change. `pnpm run typecheck:build-gaps` still works as before. ## What Changed - `scripts/ci-typecheck-lane.mjs` (new): runs the job's checks. It writes shared outputs first, in sequence: links, plugin SDK, server build without type checks, the runtime asset check, the sandbox provider installs, and the Runner typecheck (it rebuilds the eval kernel, which other checks read). Then it runs these checks in parallel: the server declaration layers, each server test layer, each test project, the test programs, the other build-gap workspaces, the CLI guidance test and the release registry tests. A passing check prints its output in a collapsed log group. A failing check prints its full output between `=== FAILED` and `=== end of` lines, with an error annotation. The script ends with a table of each check's start, duration and result, and exits non-zero if any check fails. - `server/scripts/typecheck-layers.mjs`: new `--layer <name>` option that checks one layer against the configs and declarations of an earlier `--declarations-only` run, and an exported `listLayers`. - `scripts/typecheck-test-programs.mjs`: new `--prepare-only` and `--skip-prepare` options, so the installs happen before the parallel checks start. - `scripts/run-typecheck-build-gaps.mjs`: new `--list-packages` option, so the script still finds the build-gap workspaces and still fails when one has no `typecheck` script. - `.github/workflows/pr-trusted.yml`: the `typecheck_release_registry` job runs the script instead of the six steps. No other job changes. - Tests: new `scripts/__tests__/ci-typecheck-lane.test.mjs` (added to `test:release-registry`), new cases in `server/scripts/typecheck-layers.test.mjs` and `scripts/typecheck-test-programs.test.mjs`, and the workflow wiring assertions in `.github/scripts/tests/ci-plan.test.mjs` and `scripts/__tests__/runner-release-crate-cache.test.mjs`. - `tests/runner-e2e/source-sdk-public-inputs.json`: repinned, because `package.json` changed. - `doc/DEVELOPING.md`: new "Typecheck lane in CI" section, and the new options. ## Verification This PR's own CI ran the old job definition, because PR runs use the workflow from master. So I measured the commands on a stand-in machine: a temporary workflow (`.github/workflows/typecheck-lane-bench-temp.yml`, now deleted) on GitHub-hosted `ubuntu-latest` (4 vCPU Intel Xeon 6975P-C, 15.7 GiB, no secrets, `contents: read`). It ran in runs [43444356017](https://github.com/paperclipai/paperclip/actions/runs/43444356017), [43445393958](https://github.com/paperclipai/paperclip/actions/runs/43445393958), [43446786105](https://github.com/paperclipai/paperclip/actions/runs/43446786105), [43448707837](https://github.com/paperclipai/paperclip/actions/runs/43448707837) and [43450786493](https://github.com/paperclipai/paperclip/actions/runs/43450786493). Each step ran under `/usr/bin/time -v`, and a sampler read `/proc/meminfo` every 0.25 s. **Old steps, one at a time (3 runs, run 43445393958):** | Step | Wall s | CPU s | Peak RSS of one process | System memory peak | | --- | --- | --- | --- | --- | | `typecheck:build-gaps` | 128–155 | 376–400 | 13.2–13.6 GiB | 14.2–14.7 GiB | | ...of which the full server `tsc` | 40–51 | 146–164 | 12.8–13.8 GiB | 13.7–14.7 GiB, swap up to 738 MiB | | ...replaced by the emit-only server build | 6–10 | 20–22 | 2.9 GiB | 3.9 GiB | | Test programs | 67–87 | 147–170 | 1.9 GiB | 2.9 GiB | | Server layers | 102–127 | 150–172 | 4.0–4.2 GiB | 5.4–5.6 GiB | | Test projects | 31–37 | 49–59 | 2.1–2.2 GiB | 3.1–3.2 GiB | | CLI guidance test | 2–4 | 2–3 | 0.2 GiB | 1.6 GiB | | Release registry tests | 82–95 | 159–183 | 1.7 GiB | 3.0 GiB | CPU seconds are about twice the wall seconds for the `tsc` steps even on one checker thread. So each step uses about two of the four vCPUs. **Old sequence and new lane on the same runner (4 runs, run 43450786493).** Each job copied one installed checkout, then ran both, in alternating order: | Run | Old steps, wall s | New lane, wall s | Ratio | Old memory peak | New memory peak | | --- | --- | --- | --- | --- | --- | | 1 | 503 | 314 | 0.62 | 13.98 GiB | 8.33 GiB | | 2 | 647 | 388 | 0.60 | 14.04 GiB, swap 637 MiB | 8.13 GiB | | 3 | 627 | 385 | 0.61 | 13.98 GiB | 8.63 GiB | | 4 | 382 | 237 | 0.62 | 14.10 GiB, swap 1.1 GiB | 7.99 GiB | Hosted runners differ in speed by up to 1.7 times, so only the same-runner ratio is meaningful. Both arms include a cold compile of the Runner release crate (45–80 s) that the fleet restores from cache. The fleet ran the old steps in 470 s; at the measured ratio, the new lane should take about 290 s, and the job about 6 minutes with setup. The new lane peaks at about 55% of memory, with no swap. Local checks (on a loaded Mac, for correctness only): - `node --test scripts/__tests__/ci-typecheck-lane.test.mjs` — 8 pass. - `node --test .github/scripts/tests/*.test.mjs` — 807 pass. - `node --test scripts/__tests__/e2e-shard.test.mjs scripts/__tests__/release-verify-workflow.test.mjs scripts/__tests__/runner-release-crate-cache.test.mjs scripts/__tests__/run-typecheck-build-gaps.test.mjs` — pass. - `pnpm exec vitest run scripts/typecheck-layers.test.mjs` in `server/` — the new cases pass. ## Risks - This changes a required job that every PR depends on, and its own CI cannot prove it. Please watch the first `Typecheck + Release Registry` runs on master after merge: the wall time (expect about 6 minutes), the summary table at the end of the step, and any `terminated by` message. - A type error now shows in that check's `=== FAILED` block, not in a step of its own. Passing checks are folded, so the failure is the only expanded block. - When the server declaration layers fail, the test layers and test projects are reported as skipped. Before, the test layers still ran after a source error. Fix the source errors first; the next run checks the tests. - The Honeycomb CI time board and any step-name queries see one step, `Typecheck, CLI guidance safety and release registry tests`, instead of six. The script prints the duration of each check. - The release registry tests run beside the type checks at normal priority. Their slowest test took 46–78 s here, against a 180 s timeout, and 114 s on the slowest stand-in runner. - Low risk for memory: the new lane peaked at 8.0–8.6 GiB of 15.7 GiB, far below the old 14 GiB. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), through Claude Code, with tool use (shell, GitHub CLI, file editing). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
0ece025749 |
perf(ci): cut repeated CPU work in the Runner support suite (#21390)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Every pull request runs the "Runner support suite" CI job (`pnpm test:e2e:runner:unit`) > - That job took 8.1–10.6 minutes, depending on the spot instance type, and was one of the last PR jobs to finish > - The target for every PR job is 7 minutes or less > - Measurement showed the suite is CPU-bound: each of the 693 Vitest files loads `@playwright/test`, the runner catalog and shared modules again in its own worker, and a few modules did quadratic or repeated work when they loaded > - This pull request removes that repeated work and reuses compiled code across workers > - The benefit is a job 75–86 s (13–16%) shorter on each instance type, with the same files, tests and assertions. It does not reach 7 minutes; the floor is explained below ## Linked Issues or Issue Description **What existing behavior does this improve?** The duration of the "Runner support suite" PR job. **Subsystem affected** CI, the Runner E2E support suite under `tests/runner-e2e/`, and one shared module (`packages/shared/src/connection-routing.ts`). **Current behavior** In 26 recent green PR runs the job took a median of 526 s on `m7i-flex.xlarge` (17 runs), 549 s on `m7i.xlarge` (3 runs) and 604 s on `m6a.xlarge` (6 runs). Vitest ran 693 files on 3 workers. The CPU was about 82% busy. 52% of the tracked time was module evaluation. **Proposed behavior** The job is shorter on every instance type. The same files and tests pass, and no assertion changes. **Reason and benefit** The PR workflow finishes sooner, so every pull request gets its result sooner. **Breaking changes** None. ## What Changed Measurements below are from the job's own runs on this PR. The spot fleet picks `m7i-flex`, `m7i`, `m6a` or `m5a` (all 4 vCPU); speed differs by up to 2x between them, so each comparison uses the same instance type. This suite has no Vitest retries, so a flaky test fails the job. ### Baseline (recent green PR runs on master, before this PR) | Run (job id) | Job | Test step | Vitest wall | Vitest split | | --- | --- | --- | --- | --- | | 131933126599 | 523 s | 474 s | 469.8 s | import 52%, tests 43%, transform 5% | | 131932775003 | 510 s | 461 s | 457.1 s | import 51%, tests 44%, transform 5% | | 131926764360 | 527 s | 479 s | 475.2 s | import 51%, tests 43%, transform 5% | | 131924082813 | 541 s | 496 s | – | – | | 131912527065 | 517 s | 468 s | – | – | - One Vitest invocation (693 files, 3 workers, the Vitest default of CPUs − 1), then 386 `node:test` tests in about 3 s. About 45–50 s of the job is checkout and dependency restore before the test step. - Summed tracked time was about 1,297 s for 470 s of wall time: effective concurrency 2.76 of 3 workers. Module evaluation was 674 s: 4,164 modules evaluated 77,699 times, because each file runs in a fresh isolated worker. - A CPU sampler (temporary, removed) showed 82% average CPU use with 3 workers and 95–99% with 4 workers. With 4 workers and no other change the wall time did not improve (455 s). The suite was CPU-bound, not idle. - Top modules by summed evaluation time (diagnostic run): `@playwright/test` 158 s over 390 files, `tests/runner-e2e/catalog.ts` 56 s over 141 files, `packages/shared/src/connection-routing.ts` 40 s over 317 files, `acpx/dist/runtime.js` 39 s. - Slowest files: `chat-rendered-links` 43 s, `results-root` 43 s, `chat-feature-flow` 43 s, `report` 40 s, `manual-private-transfer` 26 s, `private-framework-report` 24 s, `chat-catalog-fingerprint` 24 s, `hire-delegate-flow` 23 s, `source-sdk-evidence` 19 s, `unit-launcher` 16 s. No single file is near the 7-minute target, so there is no longest-file floor. - Slowest tests: the 256 MiB archive-cap test 23 s, the reload-once reply wait 20 s (plus two at 10 s), the documented pnpm validation 16 s, the retained name-only identity replay 14 s, the selected-case fingerprint replay 13 s. ### Changes, one at a time, with what each one bought 1. **Compile cache.** `run-unit.mjs` sets `NODE_COMPILE_CACHE` to `<tmpdir>/paperclip-runner-e2e-compile-cache` unless it is already set. Vitest workers and the Node processes that tests start reuse V8 compiled code. Node validates each entry against the source. `@playwright/test` evaluation went from 158 s to 107–124 s, `acpx` from 39 s to 26–27 s, and `zod` from 17 s to 9–10 s. Vitest went from 478 s to 441 s on a comparable run (this run also included change 2). 2. **Reuse import scans in the chat catalog fingerprint.** `fingerprintChatDependencyClosure` ran one esbuild parse for each of about 2,300 files on every call. The parse result is now cached by file path and content SHA-256 for the process. The fingerprint inputs and digest are unchanged. `chat-feature-flow` went from 43 s to 12–14 s, `chat-catalog-fingerprint` from 24 s to 11–13 s, and `chat-campaign-identity` from 13 s to 8 s. 3. **Hash each suite definition once.** `buildRunnerMatrix` computed `suiteDefinitionHash(suite)` for every execution, thousands of times, every time a test file loaded the catalog. It now computes it once per suite. The values are the same. `catalog.ts` evaluation went from 51 s to 9.6 s. Vitest went from 441 s to 389 s. 4. **Fake timers for the reload-once reply waits.** These three tests in `chat-rendered-links.test.ts` waited out the real 10 s render floor twice. They now advance fake time with `vi.runAllTimersAsync()`. The assertions on results, reload counts and attempt phases are unchanged. The file went from 43 s to 2.8 s. This freed a worker slot; on its own it did not shorten the CPU-bound run. 5. **Derive each aggregator identity once.** `connection-routing.ts` called `aggregatorAppIdentity` (two regex replaces) for every index entry for each of the 133 Arcade apps while it loaded, in 317 test files and in the server. The identity of each entry is now computed once. I compared the resulting `AGGREGATOR_SUPPORT_INDEX` (1,579 entries) and `searchAggregatorServices` results with master: they are identical. The SDK public input pins are refreshed for this change. 6. **Not shipped: four workers.** With the CPU work above removed, four workers cut Vitest from 379 s to 341 s (job 418 s). In the next run, `chat-installed-lane.test.ts` failed: the descendant of a timed-out preparation child was still visible to `process.kill(pid, 0)` right after cleanup. This is the process-tree-under-load risk, so the suite keeps the Vitest default of 3 workers. Docs: `tests/runner-e2e/README.md` describes the compile cache, how to turn it off, why the worker count stays at the default, and the cost of work at module load. ### Result | Run | Job | Test step | Vitest wall | Effective concurrency | | --- | --- | --- | --- | --- | | Baseline median, `m7i-flex` (17 runs) | 526 s | 465 s | 462 s | 2.76 | | Baseline median, `m7i` (3 runs) | 549 s | 476 s | 473 s | – | | Baseline median, `m6a` (6 runs) | 604 s | 535 s | 531 s | – | | This PR, `m7i-flex` (job 132007703795) | 440 s | 383 s | 379 s | 2.79 | | This PR, `m7i` (job 132027384596) | 474 s | 424 s | 420 s | 2.78 | | This PR, `m6a` (job 132033745288) | 526 s | 471 s | 466 s | 2.79 | | This PR, `m5a` (job 132040621237; dependency cache miss) | 880 s | 768 s | 761 s | – | The last three rows are the final configuration. The `m7i-flex` row is the same code before a README-only change. Module evaluation fell from 77,699 to 63,135 evaluations; part of that drop came from master changes merged into this branch, so I attribute time only to the per-change measurements above. ## Verification - CI on this PR is the experiment. Every push ran the real job on the real runner. The table above lists each run. - Local correctness checks, one process at a time: `chat-rendered-links.test.ts` (58 passed), the six chat fingerprint test files (37 passed), `catalog.test.ts` (92 passed), `packages/shared` `connection-routing.test.ts` and `connection-search.test.ts` (21 passed), and `node tests/runner-e2e/run-unit.mjs connection-auth.test.ts` (launcher path, 386 node:test passed). - Equivalence check for the connection routing change: the index and search results are byte-identical to master. - Flakiness: 10 runs of this branch with 3 workers (including the three final runs on `m7i`, `m6a` and the 2x slower `m5a`) passed with 0 failed tests and 0 timeouts. No port conflicts, OOM kills or `ps` timeouts appear in the logs. The suite has no retries. The 4-worker setting failed once in 3 runs, so it is not used. ## Risks - Low risk. No test is skipped or removed. No assertion is weakened. - The worker count is unchanged, so the load on process, port and temp-directory tests is lower than before (less CPU work per file). - The compile cache directory lives in the OS temp directory. Node rejects a stale or partial entry and compiles again. `NODE_DISABLE_COMPILE_CACHE=1` turns it off. - The connection routing change runs in the server too. It produces the same index, and it makes loading the module cheaper. ### What sets the remaining floor The job is about 45–55 s of checkout and dependency restore plus the Vitest run. The Vitest run is CPU-bound on 4 vCPU (2 physical cores). A fourth worker gives about 40 s more but fails a process-tree cleanup test under load (`chat-installed-lane.test.ts`, which checks the descendant immediately after cleanup). The largest remaining cost is per-file isolation: every file loads `@playwright/test` (about 0.3 s CPU each, 390 files), `zod` schemas from `packages/shared`, and `acpx` again. Vitest estimates that `isolate: false` would save about 140 s now. I did not use it: 116 files use `vi.mock`, and module state shared between files would make failures depend on which files share a worker. If more headroom is needed, the next step is a split across two machines (out of scope here because it changes `.github/`). Two duration-balanced halves (`vitest --shard=1/2` and `--shard=2/2`, about 190–235 s of Vitest each on `m7i-flex`/`m6a`) would put each job at about 4–5 minutes on every instance type except `m5a`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Claude Code agent with tool use (shell, GitHub CLI) and extended reasoning. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable (one test moved to fake timers; behavior changes are equivalence-checked) - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
a762b6bffd |
test(evals): keep the spend fixture's pointer to the tasks that record the charges (#21429)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - #21408 rewrote the spend-breakdown eval setup text in user words > - Its first wording ("Launch has recorded API charges on COM-3 (Morgan) and COM-4 (Riley)") dropped the old pointer that these tasks hold the charges > - In two paid runs the agent then gave correct totals but did not link the tasks that record them, which the case contract needs ("linked records support the totals") > - This pull request restores that pointer in plain words > - The benefit is that the setup gives the same information as before, without jargon ## Linked Issues or Issue Description Refs #21408. This commit was pushed to #21408 after it merged, so it is a follow-up. **What happened?** Paid runs 43451957487 and 43455387724: `budgets-costs.spend-breakdown` failed `actual-agent-breakdown-and-incomplete-total` because the reply did not link COM-3 and COM-4. **Expected behavior** The setup says where the charges are recorded, as the original text did. **Steps to reproduce** 1. Run `budgets-costs.spend-breakdown` with the #21408 wording. ## What Changed - The setup description now says "Launch's API charges this week are recorded on tasks COM-3 (Morgan) and COM-4 (Riley)." ## Verification - Paid run 43460401711 with this wording: `budgets-costs.spend-breakdown` passed. The reply links COM-3, COM-4, the project and the unpriced run, with no internal terms. ## Risks - Low. Eval setup text only. ## Model Used - Claude, claude-opus-5-5, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
b993702ae3 |
perf(ui): read the compact task index on the dashboard and refresh it once per window (#21413)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The board UI keeps company lists fresh from live task activity events > - The dashboard, the activity feed and board chat read the full company task list, and every burst of task activity refetches it > - One full list request costs the server 60 statements and 61-90 MB of allocation for 500 tasks, and the staging server is saturated by allocation and garbage collection > - This pull request moves those three views to the compact task index under its own key, and task activity refreshes that key at most once per 30 seconds > - The benefit is about one tenth of the server allocation per open dashboard tab while agents work, with the same rows on screen ## Linked Issues or Issue Description **What existing behavior does this improve?** The dashboard, the activity feed and board chat load the full company task list. Every burst of task activity refetches that list. **Subsystem affected** Board UI: live updates, the dashboard, the activity feed and board chat. **Current behavior** The three views read the full company task list (`GET /api/companies/:id/issues`, no view) with the key `["issues", companyId]`. `LiveUpdatesProvider` invalidates that key on every task activity event. Each open tab refetches the list at most every 5 seconds while agents work. One request costs the server 60 statements and 61-90 MB of allocation for 500 tasks (local measurement). The staging server allocates 57.6 MB per second and is saturated by garbage collection. **Proposed behavior** The views read only the fields they show, from the compact task index. Task activity from other people refreshes the index at most once per window. The viewer's own task changes refresh it at once. **Reason and benefit** Less server allocation and fewer statements per open tab, with the same rows on screen. **Breaking changes** None. No API, schema or server change. ## What Changed - The dashboard, the activity feed and board chat read `view=index` under a new key `issues.listIndex(companyId)`. - Task activity from other people refreshes that key at most once per 30 seconds (`TASK_INDEX_REFRESH_WINDOW_MS`). The viewer's own task activity refreshes it at once. The first event after a quiet window refetches at once. Later events in the window share one trailing refetch. Nothing from the event goes into the cache. An unwatched index is marked stale and refetches on the next mount. The user's own task changes still invalidate the whole `["issues", companyId]` prefix immediately. - The dashboard takes its ten recent tasks from the index, sorted by updatedAt as before. It reads the status glyph fields for those ten tasks from `issues/summaries`, because the index omits displayStatus and blockerAttention. - Toast and route lookups that read the full list cache also read the index cache. - `server/scripts/query-cost/` is the per-caller query cost harness used for the measurements below. It records the caller of each query at construction, the bytes allocated to build it, the rows it returns and the statements sent. ## Verification - `pnpm --filter @paperclipai/ui exec vitest run src/context/LiveUpdatesProvider src/pages/Dashboard.test.ts`: 261 pass. - Red/green: `LiveUpdatesProvider.task-index.test.ts` fails 6 of its first 10 cases against the provider on master and passes with this change. The tests cover a burst of events (4 index fetches in 90 seconds), the first event after a quiet window, a new task, a deleted task, a hidden task, a status/title/priority change, an event for a task outside the cache, an event for a task the viewer cannot read (nothing from the event goes into the cache), the viewer's own activity (refreshes at once), a task change made in this tab (refreshes at once through the company list invalidation), the trailing refresh (the last state shows when the window ends after activity stops), an unwatched index, and the live-event batcher path. - Other readers of `["issues", companyId]` (My Tasks, the task properties picker, the command palette, task detail cache writes, filtered and board-column lists) are not changed. The broad invalidation excludes only the new index key, so they refresh as before. A hidden tab keeps today's behavior: the live-event batcher still turns its refetches into stale marks. - Field parity (local, 1,500 tasks): the index returns the same 500 ids as the full list, with 0 differences in id, identifier, title, status, priority, createdAt, updatedAt and assigneeAgentId. It omits displayStatus and blockerAttention on all 500 rows, so the recent rows take those fields from summaries. - Real browser (headless Chromium, Playwright) against a local server from this branch, started with `test-drive --data-dir <scratch dir>`, which sets `PAPERCLIP_HOME` and `PAPERCLIP_CONFIG` to that directory: - Dashboard: the recent tasks and the "Tasks by Status" chart show the new tasks. The page sent 0 full-list requests, 2 index requests and 1 summaries request. - A task rename by this board user showed on the dashboard after 0.8 seconds, with 1 index refetch. - A second tab on the dashboard showed the same tasks. - Board chat loaded with 0 full-list requests and 3 index requests. Its activity feed showed the task names. - Not checked in the browser: activity from another actor. An agent key cannot edit a task without a heartbeat run context, so the window for other people's activity is covered by the unit tests only. - Nothing visual changed. The views keep their render code. Only their data source changed. - Cost per request (local, embedded PostgreSQL, Node 26, uninstrumented pass, 5 requests each), measured: `TSX_DISABLE_CACHE=1 UNITS=board ROUTES="issues list,issues list view=index,issues/summaries (10 ids)" REPEAT=5 NODE_OPTIONS=--expose-gc pnpm --filter @paperclipai/server exec tsx scripts/query-cost/drive.ts` | Request | Statements | Allocated | | --- | --- | --- | | full list | 60 | 61-90 MB | | view=index | 12 | 22-37 MB | | summaries, 10 ids | 23 | 2.8 MB | The ranges show the difference between runs. - Estimate, not measured: per open dashboard tab with continuous task activity, before about 13 MB/s (one full list per 5 seconds), after about 1.3 MB/s (one index per 30 seconds and one 10-id summaries request per 5 seconds). At the day-1 staging route rate (0.116 full lists per second) that is about 6.5 MB/s less. The real rate of task activity events on staging is not measured. ## Risks - Freshness: the dashboard's task charts and recent-task order, the activity feed's task names and board chat's task lookup can lag task activity from other people by up to 30 seconds. The status glyphs of the ten recent tasks stay on the 5-second lane. The viewer's own task changes refresh at once. The window is one constant, `TASK_INDEX_REFRESH_WINDOW_MS` in `LiveUpdatesProvider.tsx`, so a different value is a one-line change. - The index returns the same rows as the full list, so the charts count the same tasks. - The recent-task rows have no task description. The rows do not show it. - My Tasks, the task properties picker and the command palette still read the full list. They are not in this change. ## Model Used - Claude Opus 5.5 (claude-opus-5-5), Anthropic, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes (no documentation describes this behavior) - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
bb253c6a99 |
fix(ui): save new tasks in the background (#20831)
## Thinking Path > - Paperclip lets people manage AI agents and their tasks. > - The New task composer is the entry point for new work. > - The composer currently waits for the server to save a task before it closes. > - A slow request prevents the person from starting the next task. > - This change closes the composer as soon as it keeps the submitted request. > - Separate request records keep retries and files safe while another draft is open. > - The person can submit the next task without waiting for the first save. ## Linked Issues or Issue Description **What happened?** The New task composer stays open until task creation and file uploads finish. A slow save blocks the next task. **Expected behavior** Enter closes the composer at once. The save continues in the background. A failed save restores the request. A later draft stays intact. **Steps to reproduce** 1. Open New task and enter a request. 2. Delay the create response. 3. Submit the request. The current composer stays open until the response arrives. **Paperclip version or commit** Reproduced on source commit `a4e89288ec`. **Deployment mode** Board UI built from source. The save behavior does not depend on the server deployment mode. Related transport work: #13428. The open PR and issue searches did not find a duplicate for background New task saves. ## What Changed - Add an account-scoped queue around the existing durable submit hook. Keep each request and creation key before closing the composer. Send queued requests in order. - Keep submitted draft settings and files separate from the next draft. Resume keyed requests after a reload. Keep legacy recovery records readable. - Reopen a failed draft when the composer is free. If another draft is open, show a retry action beside it. An earlier receipt cannot clear the later draft or cause late navigation. - Add regression tests for slow saves, consecutive tasks, rejections, reloads, file ownership, and account lookup. Update the product and development docs. ## Verification - Red/green: the slow-response regression failed before the fix because the composer did not close. It passes after the fix. A second red/green case proves that missing files from an earlier task cannot change the next draft's parent or goal. - Final focused run: `pnpm exec vitest run ui/src/hooks/useBackgroundSubmitQueue.test.tsx ui/src/components/NewIssueDialog.test.tsx ui/src/hooks/useDurableSubmit.test.tsx ui/src/hooks/useStagedIssueFiles.test.tsx ui/src/lib/pending-send.test.ts ui/src/components/task-chat/TaskChatComposer.test.tsx` — 6 files and 316 tests passed on Linux with Node 25.9.0. - `pnpm --filter @paperclipai/ui typecheck` passed. `git diff --check` passed. - An earlier `pnpm verify` run selected 544 test files and overlapped the last edits. It reported the new account-lookup file-scoping assertion before the worker guard was complete. The stale run was stopped. The final focused run passes that case. Do not use the earlier run as proof for the final revision. - Store each queued request in its own browser entry. A submission or receipt in one tab cannot erase another tab's queued tasks. A red/green two-tab regression proves recovery after reload. Legacy queue migration also passes. - Follow-up recovery checks: a saved rejection cannot replace a newer saved draft or a fresh launch. Edits survive close, reopen, and reload. A retry keeps its original hidden workspace context and request key. The new regressions failed before the fixes and pass after them. - Updated the branch from `master`. This includes the SDK pin repair in #20834 and the span test repair in #21149, which address the two original CI failures. The SDK input drift check now reports no stale pins. - CI must provide broad checks for the final commit. Browser and release suites were not run; this change does not modify those suites. The dependency preflight installed packages and built the shared and plugin SDK outputs. Its later Runner step could not run because Cargo is absent in this UI workspace. ## Risks - Requests now close the composer before the server confirms a save. A failed request must stay visible and recoverable. The tests cover rejection, retry, reload, and a newer draft. - The queue and file snapshots use browser storage. If storage is unavailable, requests remain in memory and a reload can require the files again. - Server creation, authorization, and duplicate-request handling retain their existing APIs. No database migration is required. - The queue sends requests in order. An uncertain first save can delay later server saves while the person continues to compose. ## Model Used - OpenAI GPT-6 through Codex, with reasoning, shell tools, and code execution. The exact service model ID and context window are not exposed in this run. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |