mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 14:35:17 +01:00
c8ca682bf28e43d03e836de53b466809cbafb806
8956
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
c8ca682bf2 |
fix(ui): remount the composer takeover card per pending input (#15121)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents ask people for decisions through cards in the task chat > - The composer shows one pending card at a time in a takeover slot > - The checkbox card and the suggested-tasks card keep the selection, the reason and the page in local React state > - The takeover slot renders each pending card in the same position without a React `key`, so React reuses one card instance for the next pending card > - The next card then starts with the state of the card before it > - This pull request adds a `key` for each pending input, so each card mounts with its own state > - The benefit is that each card shows and sends only its own options ## Linked Issues or Issue Description No public issue exists for this bug. The description follows the bug report template. **What happened?** A task had two pending cards of the same kind. I answered the first card. The takeover slot then showed the second card, but the second card kept the selection state of the first card. The default ticks of the second card did not show. The card also wrote the selection of the first card into the saved draft of the second card. When I confirmed the second checkbox card, it sent option ids that belong to the first card. The server refused the request with `Unknown checkbox confirmation optionId`. **Expected behavior** Each pending card starts with its own default selection. Each card sends only its own option ids. Each card saves only its own draft. **Steps to reproduce** 1. Create two pending `request_checkbox_confirmation` interactions on one task. Give them different option ids and different `defaultSelectedOptionIds`. 2. Open the task. The composer takeover shows one of the cards. 3. Change the ticks on that card, then confirm it. 4. Look at the next card in the takeover slot. Its default ticks do not show. 5. Confirm the next card. The request fails with `Unknown checkbox confirmation optionId`. The same fault occurs with two pending `suggest_tasks` cards. **Paperclip version or commit** `master` at `1c07b5903b1b11139b1e1ce052a3cd4885865d90`. **Deployment mode** Self-hosted server. The bug is in the UI and does not depend on the deployment mode. Related work: a search of issues and pull requests found no report and no fix for this bug. #14613 and #9290 change the same cards, but they do not change how the takeover slot mounts a card. ## What Changed - `ui/src/components/TaskChatThread.tsx`: the takeover `TaskChatProtocolCard` and `TaskChatInteractionCard` now have `key={selectedPendingInput.key}`. React mounts a new card when the pending input changes. - `ui/src/components/TaskChatThread.test.tsx`: two new tests. One test covers two pending checkbox cards. One test covers two pending suggested-tasks cards. Each test answers the first card and then checks the ticks, the submitted ids and the saved draft of the second card. - The branch has two commits. The first commit adds only the tests. The second commit adds the fix. ## Verification Run these commands from the repository root: - `pnpm exec vitest run --project @paperclipai/ui ui/src/components/TaskChatThread.test.tsx` - On the tests-only commit: 2 failed, 195 passed. The two failures are the new tests. - On the head commit: 197 passed. - `pnpm exec vitest run --project @paperclipai/ui`: 679 test files passed, 7316 tests passed. - `pnpm --filter @paperclipai/ui typecheck`: no errors. - `pnpm check:token-gates`: all gates clean. - `pnpm check:tokens`: no forbidden tokens. Manual check: on a self-hosted build that has the same two-line change, two pending checkbox cards on one task were accepted one after the other. Each request sent the option ids of its own card. This build was not the head commit of this branch. I did not run `pnpm -r typecheck`, the full `pnpm test:run`, `pnpm build` or the browser suites. The change touches only the two UI files above. ## Risks Low risk. A card in the takeover slot now mounts again when the selected pending input changes. Unsaved local state of the card that leaves the slot is not kept in memory. Selections and reasons stay in the saved draft for each card, as before. The card does not mount again while the same pending input stays selected, because the key is stable for one pending input. ## Model Used Claude Opus 5.5 (`claude-opus-5-5`) from Anthropic, run as a coding agent with tool use (shell, file edit, test runs). The context window size of the run was not recorded. A person reviews the change before the pull request opens. ## 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 (not applicable: no documentation describes this behavior) - [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 |
||
|
|
dbfcbb532b |
fix: key dashboard task cards by the native issue id (#15032)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The dashboard draws one task card per issue
> - `selectDashboardRunIds` reads only `contextSnapshot.issueId`
> - A native run stores the task on `nativeIssueId`
> - Older runs store it on `contextSnapshot.taskId`
> - The same task is then drawn as two cards
> - This pull request coalesces the bound issue id, then native issue
id, then context issue id, then task id
> - The benefit is that one task has one dashboard card
## Linked Issues or Issue Description
No open issue covers this. I searched open and closed issues and pull
requests.
**What happened?**
Dashboard task cards ignore the bound and native issue ids.
`selectDashboardRunIds` uses only `contextSnapshot.issueId`. Recovery
already reads `nativeIssueId`, then the context issue id, then `taskId`.
A native or bound run and a context run for the same task both take a
card slot.
**Expected behavior**
Use `coalesce(issueId, nativeIssueId, contextSnapshot.issueId,
contextSnapshot.taskId)` for the card key. Two runs for the same task
collapse to one card.
**Steps to reproduce**
1. Insert two runs for one company with the same `nativeIssueId`.
2. Give them different `contextSnapshot.issueId` values, or omit
`issueId` and set `taskId`.
3. Call `selectDashboardRunIds` with a small limit.
4. Observe that both runs are selected.
**Paperclip version or commit**
master at
|
||
|
|
51b398194a |
fix: inspect backup health without blocking the event loop (#14674)
## Thinking Path > - The health endpoint reports database backup status. > - Backup directories and marker files may live on slow storage. > - Synchronous filesystem reads hold Node's event loop during each check. > - Other requests wait behind that filesystem work. > - Await filesystem operations and preserve the existing health response. ## Linked Issues or Issue Description **What happened?** A backup-health check scans and reads files synchronously on the HTTP event loop. **Expected behavior:** Filesystem work yields so unrelated timers and requests can proceed. **Steps to reproduce:** Enable database backup health with a slow backup directory, request `/api/health`, and observe unrelated event-loop work waiting for synchronous filesystem calls. The regression deterministically holds an asynchronous directory read and verifies another timer can run before it completes. **Paperclip version or commit:** `master` at `a027f76a7`. **Deployment mode:** Built from source; tested using temporary backup files and controlled filesystem responses. Related PRs #13308 (empty archive health) and #10736 (backup retention) address different backup behavior. This change leaves archive validation and retention policy alone; those branches may need small textual reconciliations if merged first. ## What Changed - Use `node:fs/promises` for directory enumeration, file metadata and failure markers. - Scan archive metadata in batches of at most four reads to bound filesystem work while allowing parallel I/O. - Await the result in the health route. - Treat only missing files as absent, including files removed by retention during enumeration. - Preserve warnings for actual filesystem failures and existing newest-file/marker behavior. - Add coverage for freshness, missing directories, marker text, read errors, retention races, bounded scan concurrency and event-loop progress. ## Verification - Backup-health and health route suites (4 files): 35 passed. - The event-loop regression fails with the original synchronous service. - The archive-only concurrency regression also fails against the sequential scan; optional marker reads cannot mask that failure. - `pnpm --filter @paperclipai/server typecheck`: passed. - `git diff --check`: passed. - Refreshed with upstream `master` at `7d59de6113caf5219d34d65e1fb5f0c1a7fbdc2a`, which includes the Runner qualified-command fixture fix. The fresh branch diff remains limited to this fix and its tests. - Re-ran all four focused suites on `8e96930537774ac4623cd493ba065b8a6f5d3269`: 35 passed. The first [refreshed CI run](https://github.com/paperclipai/paperclip/actions/runs/37038481259) passed every test gate except the touch-picker browser shard. The failure screenshot shows the last option already visible at the scroll boundary. The source-identical retry at `eeaeb752a36e0acd5129b6c6bce40e24fdefe1bd` [passed all CI](https://github.com/paperclipai/paperclip/actions/runs/37040261790), including the touch-picker shard, both Runner shards, build, typecheck, server suites, canary dry run and the final aggregate. - Greptile is 5/5 and all review threads are resolved. ## Risks The internal inspection helper now returns a Promise; its route caller awaits it. The response schema and freshness threshold are unchanged. No database migration or cache is introduced. ## Model Used OpenAI GPT-6 through Codex, with reasoning, Git and code execution tools. The exact deployment identifier and context-window size 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, including the available 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 - [x] I have described the issue using the bug report fields - [x] I have not referenced internal/instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal ticket ID - [x] I have run tests locally and they pass - [x] I have added a regression test - [x] I have documented the affected request behavior and risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open findings - [x] I will address reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
6c6e978725 |
fix(build): preserve UI errors before service worker output exists (#14444)
## Thinking Path > - Paperclip serves a web UI with a service worker. > - The UI build stamps the worker with the entry bundle ID. > - Vite also calls `closeBundle` after a failed build. > - A failed build can leave the worker file absent. > - Reading that file replaces the useful build error with an `ENOENT` error. > - This change stamps the worker in `writeBundle`, after the output exists. ## Linked Issues or Issue Description **What happened?** An unresolved UI import reports a missing `dist/sw.js` file instead of the missing module. The stamping plugin reads the worker from `closeBundle`, including after a failed bundle. **Expected behavior** The build should report the original module error. A successful build should still stamp the copied worker with its entry bundle ID. **Steps to reproduce** 1. Create a minimal Vite project with an HTML entry and `public/sw.js` containing the build-ID placeholder. 2. Enable `serviceWorkerBuildIdPlugin()`. 3. Make the entry import `./missing.js`. 4. Run the build. The current plugin reports `ENOENT` for `dist/sw.js`. **Paperclip version or commit** Reproduced on `3447609d2247e75e55d91493dda91a608364f672`. **Deployment mode** Other: production UI build. **Installation method** Built from source. **Database mode** Not database-related. **Operating system** NixOS, x86_64 Linux. Node 24.19.0. **Additional context** Searches of open and closed issues and PRs for `closeBundle` and `writeBundle` found no matching contribution. ## What Changed - Move file stamping to `writeBundle`. - Add real Vite build tests for a failed import and a successful stamped output. - Compare the complete stamped worker content against the entry-derived build ID. ## Verification ### Current exact-source hosted qualification — 2026-10-09 Published head: `d0b95c377e43a06a2b5ba740dd6df9cb23fd3335`. The externally published reconciliation preserves the prior proposal and exactly matches its recorded tree merged with target `9b624a110e281badc54cbdf37ddb792cdc1690ff`; no proposal behavior was changed. Required **`ci / verify` and `ci / e2e` succeed** in [run 37864533960/1](https://github.com/paperclipai/paperclip/actions/runs/37864533960). Actual checkout logs bind this exact candidate to this exact current target. All original regression repairs and historical findings remain retained. GitHub verifies the reconciliation signature. Local signature verification cannot check it because the signer public key is absent; no key, signing setting or commit identity was changed. Local worktrees were fast-forwarded to the existing public heads without creating or rewriting commits. Successful complete native Codex code review and applicable maintainer approvals remain outstanding; [the source-bound review request](https://github.com/paperclipai/paperclip/pull/14444#issuecomment-6072822720) is not acceptance. After qualification, mark the draft ready and use the protected exact-head merge. The authenticated operator currently has READ-only upstream access. <!-- preserving-source-refresh-20261009:start --> ### Preserving upstream refresh — 2026-10-09 Published signed head: `d0b95c377e43a06a2b5ba740dd6df9cb23fd3335`. This head contains observed upstream `9b624a110e281badc54cbdf37ddb792cdc1690ff`, previous published head `eda06f1c0a8eaf0a8c9c3a352ba02dea88bb0b95`, and preserved prepared head `cde0ef5321f48d75593738afd3310d901986a16e`. The publication used one atomic, non-force push. Remote branch and PR readback match the signed head. The lockfile and database migrations have no delta from this upstream. Exact-head hosted CI: https://github.com/paperclipai/paperclip/actions/runs/37864533960. Qualification is pending. Earlier results remain historical evidence and do not qualify this refreshed head. Acceptance requires mandatory attempt-1 GREEN results, zero mandatory failures, errors, skips or retries, SHA-256-bound receipts, and provider retention of at least 2592000 seconds. Refresh assistance: OpenAI `openai/gpt-6.1-sol`, with repository inspection, Git tooling and evidence verification. The harness does not expose a context-window size. <!-- preserving-source-refresh-20261009:end --> ### Published reconciliation — 2026-10-08 Published candidate `eda06f1c0a8eaf0a8c9c3a352ba02dea88bb0b95` includes the target `71cd0a2621615182274a977d6cc969b9ab920b92`. Frozen dependency installation and all **9** stamping unit/integration tests passed on that exact candidate, with zero skipped. Changing only `writeBundle` back to `closeBundle` reproduced the masked missing-import diagnostic. Restoring the candidate passed the full focused file again. ```sh corepack pnpm --filter @paperclipai/ui exec vitest run src/lib/vite-sw-build-id.test.ts src/lib/vite-sw-build-id.integration.test.ts ``` The source comparison merges without conflict against the live `master` observed at `9f4acc8f14f5baf77b54b040d156a1b094d8d366`. The exact candidate was normal-pushed to this PR branch. The focused results are not full qualification of the newer target/composite tree. New hosted CI and full native code review are pending. Queued, running, skipped or failed checks do not establish a pass. Applicable maintainer approvals and protected merge gates remain required. ### Historical qualification — not acceptance of the new comparison - Before the fix, the failed-import regression reports the unrelated worker `ENOENT`; the successful-build case passes. - After the fix, all nine stamping unit/integration tests pass. - At `375f1cbd9`, all 6,756 UI tests passed across 639 files: `pnpm exec vitest run --project @paperclipai/ui --exclude '**/dist/**'`. - `pnpm --filter @paperclipai/ui typecheck` passes. - `pnpm --filter @paperclipai/ui build` passes, with existing chunk-size and mixed static/dynamic import warnings. - `git diff --check` passes. - `pnpm check:token-gates` passes on the exact published head. - The assertion-only follow-up `415c30fe034f7e99b25f12a940776766e9325966` passed all nine focused stamping tests and UI typecheck. Greptile reviewed that head at 5/5 with no remaining findings. Full-monorepo qualification and CI remain pending. This is a draft. - Added code comment removed per CONTRIBUTING.md; `pnpm exec vitest run ui/src/lib/vite-sw-build-id` (11 passed) and `pnpm --filter @paperclipai/ui typecheck` pass on this head and on upstream `820c458`. - `ci / General tests (server (8/12))` failed once in `server/src/__tests__/decision-expiry-work.test.ts` (expected timestamps off by exactly 90000 ms). This PR does not touch server code, and that file passes locally (20 tests). Treated as unrelated timing flake: https://github.com/paperclipai/paperclip/actions/runs/40728729442 ## Risks The hook timing changes. Real build tests verify that the copied worker exists at `writeBundle` and receives the emitted entry ID. Missing or invalid worker content during a successful build still fails stamping. ## Model Used OpenAI GPT-6 Astra, exact model ID `gpt-6-astra`, through OpenCode. Assistance included code, real-build regression tests, and command execution. The harness did not expose a verified 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 - [ ] 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 |
||
|
|
3ecc2dffff |
test(native-runtime): cite a saved request in the human-owned blocker corpus case (#23853)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
153b48dea9 |
fix(db): honor PostgreSQL URI host parameters for Unix sockets (#14442)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip stores control-plane state in PostgreSQL through
`packages/db`
> - A self-hosted instance can reach a local PostgreSQL service through
a Unix socket
> - libpq URIs select the socket with the `host` query parameter, but
postgres.js sends that parameter as a server setting and uses TCP
> - This pull request maps the URI `host` parameter to the driver host
option in one shared helper
> - The benefit is that app connections, migrations, backups, and
restores use the socket that the URI selects
## Linked Issues or Issue Description
**What happened?**
With
`DATABASE_URL=postgresql://paperclip@localhost:5432/paperclip?host=/run/postgresql`,
Paperclip connected over TCP to `localhost` instead of the socket.
**Expected behavior**
All JavaScript connections use the socket directory in `host`.
Percent-encoded paths also work. TCP URIs do not change.
**Steps to reproduce**
1. Run PostgreSQL with a Unix socket directory.
2. Set `DATABASE_URL` to a URI with `?host=<socket-directory>`.
3. Start Paperclip or run a JavaScript backup.
4. See that the connection uses TCP, not the socket.
**Paperclip version or commit**
upstream master
|
||
|
|
f4fc0ca0bc |
build(deps): bump @cloudflare/sandbox from 0.7.21 to 0.12.14 in /scripts/typecheck-sandbox-providers (#23827)
Bumps [@cloudflare/sandbox](https://github.com/cloudflare/sandbox-sdk) from 0.7.21 to 0.12.14. <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/cloudflare/sandbox-sdk/releases">@cloudflare/sandbox's releases</a>.</em></p> <blockquote> <h2><code>@cloudflare/sandbox</code><a href="https://github.com/0"><code>@0</code></a>.12.14</h2> <h3>Patch Changes</h3> <ul> <li><a href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/1028">#1028</a> <a href="https://github.com/cloudflare/sandbox-sdk/commit/2e4e1eb304e2cbbf5569e095e3ead296a5efbc87"><code>2e4e1eb</code></a> Thanks <a href="https://github.com/ghostwriternr"><code>@ghostwriternr</code></a>! - Update the container runtime to Bun 1.4.4. Bun checks certificates against its own built-in CA list, and in 1.4.4 that list no longer trusts the compromised eMudhra intermediates, so the <code>bun</code> command and <code>createBackup()</code> uploads of 10 MiB or more now reject their certificates. Bun 1.4.4 also updates Brotli to 1.2.1, which fixes CVE-2026-111497. The <code>-opencode</code> image ships OpenCode 1.19.4 or later, which also runs on Bun 1.4.4.</li> </ul> <h2><code>@cloudflare/sandbox</code><a href="https://github.com/0"><code>@0</code></a>.12.13</h2> <h3>Patch Changes</h3> <ul> <li><a href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/1023">#1023</a> <a href="https://github.com/cloudflare/sandbox-sdk/commit/a4eaa89aada863cda9ea8a7373404029a1a32761"><code>a4eaa89</code></a> Thanks <a href="https://github.com/ghostwriternr"><code>@ghostwriternr</code></a>! - Stop trusting certificates from the compromised eMudhra intermediate CAs in the container images. The images now ship the updated Ubuntu and Alpine CA bundles, Node.js 22.23.4, cloudflared 2026.10.2, and pip 26.2.2 in the <code>-python</code> image. Bun keeps trusting these certificates until it releases a fix, which affects <code>bun</code>, opencode, and multipart uploads in <code>createBackup()</code> for archives of 10 MiB or more. Update the container image to get this fix. See <a href="https://blog.cloudflare.com/emudhra-certificate-compromise/">the eMudhra certificate compromise</a> for details.</li> </ul> <h2><code>@cloudflare/sandbox</code><a href="https://github.com/0"><code>@0</code></a>.12.12</h2> <h3>Patch Changes</h3> <ul> <li> <p><a href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/1002">#1002</a> <a href="https://github.com/cloudflare/sandbox-sdk/commit/8dc216c5c16563d0e3f2044ad14c0657682f3fd9"><code>8dc216c</code></a> Thanks <a href="https://github.com/ghostwriternr"><code>@ghostwriternr</code></a>! - Fix <code>mountBucket()</code> breaking an existing mount when a second call for the same mount path fails with "already in use". The existing mount now stays mounted and usable.</p> </li> <li> <p><a href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/1013">#1013</a> <a href="https://github.com/cloudflare/sandbox-sdk/commit/98b787b81b5526851af95e6be9ca98da13ae450d"><code>98b787b</code></a> Thanks <a href="https://github.com/ghostwriternr"><code>@ghostwriternr</code></a>! - Keep streaming <code>exec()</code> alive while a command is quiet, and enforce its <code>timeout</code>. Quiet commands were cut off after about four minutes on the HTTP transport and five on WebSocket. The timeout was ignored on those transports, and on every transport for commands that run in a session. Requires the matching container image.</p> </li> <li> <p><a href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/1008">#1008</a> <a href="https://github.com/cloudflare/sandbox-sdk/commit/b2a862cffce187f56bcfae321756c0a9c91b712b"><code>b2a862c</code></a> Thanks <a href="https://github.com/ghostwriternr"><code>@ghostwriternr</code></a>! - Keep R2 binding and credential-proxy bucket mounts working when the Sandbox Durable Object restarts while its container keeps running. The mounts used to stay listed but fail every read and write with <code>EIO</code> until <code>mountBucket()</code> was called again.</p> </li> <li> <p><a href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/1003">#1003</a> <a href="https://github.com/cloudflare/sandbox-sdk/commit/e8332cd3c6b0a6f958062304f922d93678f6dfed"><code>e8332cd</code></a> Thanks <a href="https://github.com/ghostwriternr"><code>@ghostwriternr</code></a>! - Fix <code>createOpencodeServer()</code> and <code>createOpencode()</code> waiting for the full three-minute startup timeout when <code>OPENCODE_SERVER_PASSWORD</code> is set. When the password is passed in <code>env</code>, the client returned by <code>createOpencode()</code> now authenticates with it.</p> </li> <li> <p><a href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/1016">#1016</a> <a href="https://github.com/cloudflare/sandbox-sdk/commit/d62f020d6b1cae787fc676c11b29b7718c40f575"><code>d62f020</code></a> Thanks <a href="https://github.com/ghostwriternr"><code>@ghostwriternr</code></a>! - Create the s3fs password file for <code>mountBucket()</code> with mode 0600 from the start. The file used to be readable by other users in the container until a chmod a moment later, long enough for a non-root process to open it and read the bucket credentials. Upgrade the container image together with the SDK to close the gap; with an older image, mounts work as before.</p> </li> <li> <p><a href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/996">#996</a> <a href="https://github.com/cloudflare/sandbox-sdk/commit/da3d7b6c4edde53b071c42180bca22493e864c9a"><code>da3d7b6</code></a> Thanks <a href="https://github.com/ghostwriternr"><code>@ghostwriternr</code></a>! - Answer a preview request with <code>502</code> when the app's port in the container fails, for example because nothing listens on it or it closes the connection, and log the original error. Previously the error escaped the Sandbox, <code>proxyToSandbox()</code> answered <code>500 Proxy routing error</code>, and the log blamed a platform runtime update.</p> </li> <li> <p><a href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/997">#997</a> <a href="https://github.com/cloudflare/sandbox-sdk/commit/c79bf1de83e9be4d5c423b0b60fc7d48792418e7"><code>c79bf1d</code></a> Thanks <a href="https://github.com/ghostwriternr"><code>@ghostwriternr</code></a>! - Forward WebSocket upgrades on preview URLs with <code>Host: localhost:<port></code>, like every other preview request. Dev servers that check the <code>Host</code> header, such as Vite, no longer reject HMR connections. The public hostname is still in <code>X-Forwarded-Host</code>.</p> </li> <li> <p><a href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/1000">#1000</a> <a href="https://github.com/cloudflare/sandbox-sdk/commit/c6760770b291531ae9a782e6ddfc2aa32ad8674c"><code>c676077</code></a> Thanks <a href="https://github.com/ghostwriternr"><code>@ghostwriternr</code></a>! - Keep preview URLs and tunnels working on the RPC transport after the control connection reconnects. The connection closes after 1 second without calls, and the next call used to rerun the sandbox's start handling even though the container was still running. Preview URLs then returned <code>410 STALE_PREVIEW_URL</code>, <code>getExposedPorts()</code> returned an empty list, quick tunnels disappeared from <code>tunnels.list()</code>, and <code>tunnels.get()</code> could fail with "Tunnel recovery attempts were exhausted".</p> </li> <li> <p><a href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/1010">#1010</a> <a href="https://github.com/cloudflare/sandbox-sdk/commit/7866d45fb7c1b83e45d1fac4f5c084d712603bb0"><code>7866d45</code></a> Thanks <a href="https://github.com/ghostwriternr"><code>@ghostwriternr</code></a>! - Stop the first call on the RPC transport from failing when Cloudflare can't provide a container right away. The call now keeps waiting for the container within its retry window.</p> </li> <li> <p><a href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/995">#995</a> <a href="https://github.com/cloudflare/sandbox-sdk/commit/becade1ff2b472d50340c64b12cf1c9208d945f7"><code>becade1</code></a> Thanks <a href="https://github.com/ghostwriternr"><code>@ghostwriternr</code></a>! - Stop the container server from crashing with <code>ENOENT: no such file or directory, watch '…/<id>.log.stderr'</code> while commands run. The crash killed every process in the container. Update the container image to pick up this fix.</p> </li> <li> <p><a href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/1007">#1007</a> <a href="https://github.com/cloudflare/sandbox-sdk/commit/fa571496cd1276d41c8d23672c3e6da541c4d1d1"><code>fa57149</code></a> Thanks <a href="https://github.com/ghostwriternr"><code>@ghostwriternr</code></a>! - <code>tunnels.get()</code> on the RPC transport now reports the real tunnel error, such as <code>cloudflared</code> failing to start or missing from the image, instead of "Tunnel recovery attempts were exhausted". It also no longer leaves a port stuck after giving up: a <code>cloudflared</code> left running from an earlier attempt is stopped and replaced. Replacing it needs the matching container image.</p> </li> </ul> <h2><code>@cloudflare/sandbox</code><a href="https://github.com/0"><code>@0</code></a>.12.11</h2> <h3>Patch Changes</h3> <ul> <li> <p><a href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/889">#889</a> <a href="https://github.com/cloudflare/sandbox-sdk/commit/119336ef67819feda18cf0f716f10db4e1eece73"><code>119336e</code></a> Thanks <a href="https://github.com/scuffi"><code>@scuffi</code></a>! - Stop backups from dropping whole directories when <code>excludes</code> or <code>gitignore: true</code> match a nested path. For example, <code>excludes: ['.cache/foo/*/node_modules']</code> no longer removes all of <code>.cache</code> from the archive. A multi-component pattern such as <code>build/output</code> now matches only relative to the backup directory, while a single-component pattern such as <code>node_modules</code> still matches at any depth. Because mksquashfs does not support <code>**</code>, a pattern like <code>**/node_modules/.cache</code> now excludes only <code>node_modules/.cache</code> at the root of the backup directory; add a pattern for each nested location that must stay out of the backup.</p> </li> <li> <p><a href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/914">#914</a> <a href="https://github.com/cloudflare/sandbox-sdk/commit/66862ff45736e416422736b225da90b5f1dd9cd3"><code>66862ff</code></a> Thanks <a href="https://github.com/ghostwriternr"><code>@ghostwriternr</code></a>! - Return 404 with <code>workspace_read_not_found</code> from the bridge's <code>GET /v1/sandbox/:id/file/*</code> when the file doesn't exist. The route used to return 200 with an empty body, the same response as an empty file.</p> </li> <li> <p><a href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/894">#894</a> <a href="https://github.com/cloudflare/sandbox-sdk/commit/20d72db671876a3e50ab0881758cae7576ae2b6e"><code>20d72db</code></a> Thanks <a href="https://github.com/scuffi"><code>@scuffi</code></a>! - Fix local bucket mounts for large files and write bursts. On the RPC transport, objects over 4 MiB now stream into the container instead of failing with an interrupted runtime connection. Container files stream back to R2 byte for byte, without loading the whole file into Worker memory. A file being written uploads once its changes settle, instead of on every write.</p> </li> <li> <p><a href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/926">#926</a> <a href="https://github.com/cloudflare/sandbox-sdk/commit/6678b1378f4ba61586d26f84ee9616a171e6303c"><code>6678b13</code></a> Thanks <a href="https://github.com/ghostwriternr"><code>@ghostwriternr</code></a>! - Stop writing command text and output to Sandbox logs. Exec and process log events now record IDs, exit codes, durations, and output lengths, and the OpenAI Agents <code>Shell</code> and <code>Editor</code> adapters no longer log commands, stderr, or patch text, so secrets in commands, output, or patches no longer reach Workers Logs or container logs. Command failure messages no longer repeat the command; it remains available on the error's <code>context.command</code>.</p> </li> <li> <p><a href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/888">#888</a> <a href="https://github.com/cloudflare/sandbox-sdk/commit/6c9edcc4e466390f52540e48dbd3809ca80fcc89"><code>6c9edcc</code></a> Thanks <a href="https://github.com/scuffi"><code>@scuffi</code></a>! - Fix <code>restoreBackup()</code> error reporting for archives of 10 MB or more. A failed download part now throws a <code>BackupRestoreError</code> that includes curl's error output and each part's exit code, instead of a <code>Shell terminated unexpectedly</code> session error.</p> </li> <li> <p><a href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/887">#887</a> <a href="https://github.com/cloudflare/sandbox-sdk/commit/13f477d6fc1b4a73b61d333de6a222e8876de860"><code>13f477d</code></a> Thanks <a href="https://github.com/scuffi"><code>@scuffi</code></a>! - Sync local bucket mounts outside <code>/workspace</code>, such as <code>/data</code>, from the container back to R2. <code>watch()</code> and <code>checkChanges()</code> now accept any absolute path on every transport, as documented. A local mount whose container rejects the watch now logs one error instead of retrying forever.</p> </li> </ul> <!-- raw HTML omitted --> </blockquote> <p>... (truncated)</p> </details> <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/cloudflare/sandbox-sdk/commit/b96de6ea1ca248e11a56a78f1efabc2717d6c7b9"><code>b96de6e</code></a> Version Packages (<a href="https://redirect.github.com/cloudflare/sandbox-sdk/issues/1034">#1034</a>)</li> <li><a href="https://github.com/cloudflare/sandbox-sdk/commit/2e4e1eb304e2cbbf5569e095e3ead296a5efbc87"><code>2e4e1eb</code></a> Update the container runtime to Bun 1.4.4 (<a href="https://redirect.github.com/cloudflare/sandbox-sdk/issues/1028">#1028</a>)</li> <li><a href="https://github.com/cloudflare/sandbox-sdk/commit/b3a8566c61c15bdc24d216fadb322fd673bb0aca"><code>b3a8566</code></a> Promote public refs to 0.12.13 (<a href="https://redirect.github.com/cloudflare/sandbox-sdk/issues/1027">#1027</a>)</li> <li><a href="https://github.com/cloudflare/sandbox-sdk/commit/2538b5540b2f79b56af2a81fa0fa2b353948d667"><code>2538b55</code></a> Version Packages (<a href="https://redirect.github.com/cloudflare/sandbox-sdk/issues/1026">#1026</a>)</li> <li><a href="https://github.com/cloudflare/sandbox-sdk/commit/a4eaa89aada863cda9ea8a7373404029a1a32761"><code>a4eaa89</code></a> Stop trusting compromised eMudhra intermediates (<a href="https://redirect.github.com/cloudflare/sandbox-sdk/issues/1023">#1023</a>)</li> <li><a href="https://github.com/cloudflare/sandbox-sdk/commit/7fbb9e5dd3a419570fee79bb98365668b5188984"><code>7fbb9e5</code></a> Keep polling when a rollout wrangler call fails (<a href="https://redirect.github.com/cloudflare/sandbox-sdk/issues/1018">#1018</a>)</li> <li><a href="https://github.com/cloudflare/sandbox-sdk/commit/e3ebd96707fdb86ac68ce1641963864f5e5e4a81"><code>e3ebd96</code></a> Promote public references to 0.12.12 (<a href="https://redirect.github.com/cloudflare/sandbox-sdk/issues/1019">#1019</a>)</li> <li><a href="https://github.com/cloudflare/sandbox-sdk/commit/0d96b78f58c9e808688352d621249b673767cedf"><code>0d96b78</code></a> Version Packages (<a href="https://redirect.github.com/cloudflare/sandbox-sdk/issues/1004">#1004</a>)</li> <li><a href="https://github.com/cloudflare/sandbox-sdk/commit/d62f020d6b1cae787fc676c11b29b7718c40f575"><code>d62f020</code></a> Create s3fs support files owner-only from the start (<a href="https://redirect.github.com/cloudflare/sandbox-sdk/issues/1016">#1016</a>)</li> <li><a href="https://github.com/cloudflare/sandbox-sdk/commit/98b787b81b5526851af95e6be9ca98da13ae450d"><code>98b787b</code></a> Stop cutting off quiet exec streams (<a href="https://redirect.github.com/cloudflare/sandbox-sdk/issues/1013">#1013</a>)</li> <li>Additional commits viewable in <a href="https://github.com/cloudflare/sandbox-sdk/compare/@cloudflare/sandbox@0.7.21...@cloudflare/sandbox@0.12.14">compare view</a></li> </ul> </details> <br /> Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> |
||
|
|
3befcd245b |
feat(connections): add LinkedIn REST connector (v1 personal posting) (#23388)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - App connectors let agents call external APIs under company/user
grants, risk classification, and audit governance
> - LinkedIn does not publish an official remote MCP server, and its
public API separates self-serve personal posting (`Share on LinkedIn`)
from vetted commercial Company Page management (`Community Management
API`)
> - Users want a governed native LinkedIn connector without waiting
weeks for commercial review or relying on ToS-violating scrapers
> - This pull request adds a reviewed native LinkedIn REST adapter
(`server/src/services/connectors/linkedin/`) registered in
`rest-registry.ts`, extracts a shared governed REST transport
(`server/src/services/connectors/rest-transport.ts`) used by LinkedIn,
Vercel, and Supabase, and wires managed Paperclip Cloud OAuth
(`linkedin.share`) plus customer-owned OAuth fallback
> - The benefit is governed personal LinkedIn publishing
(`linkedin_get_profile`, `linkedin_create_post`, `linkedin_delete_post`)
with S4 destructive classification, shared transport security
guarantees, and clean expansion room for v2 Company Page support
## Linked Issues or Issue Description
**Subsystem affected**
Cross-cutting (multiple of the above)
**Problem or motivation**
Paperclip has no native LinkedIn connector. LinkedIn does not publish an
official remote MCP server, and standard self-serve OAuth requires a
pre-registered LinkedIn Developer App with exact callback URIs and
explicit governance for public broadcasts.
**Proposed solution**
Add a reviewed native LinkedIn REST adapter
(`server/src/services/connectors/linkedin/`) in `rest-registry.ts`
supporting v1 self-serve OIDC Sign In + Share on LinkedIn (`openid`,
`profile`, `email`, `w_member_social`), backed by a shared governed REST
transport (`server/src/services/connectors/rest-transport.ts`) shared
across LinkedIn, Vercel, and Supabase, paired with the `linkedin.share`
managed OAuth profile in `paperclip-cloud` and a customer-owned OAuth
fallback.
**Alternatives considered**
- Remote MCP: ruled out because LinkedIn has no official MCP server.
- Waiting for Community Management API review before v1: deferred to v2
so personal posting ships now without blocking on commercial app review.
## What Changed
- Extracted shared governed REST transport
(`server/src/services/connectors/rest-transport.ts` and
`rest-transport.test.ts`) owning pre-`Headers` Bearer validation, token
redaction in strings and object keys, origin/prefix pinning, `redirect:
"error"`, deadline racing with forged-504 rejection, input/output byte
caps with reader cancellation, and unified write uncertain-outcome
(`408`/`5xx`/unparseable 2xx) handling; converged LinkedIn, Vercel, and
Supabase adapters onto it.
- Added reviewed LinkedIn REST adapter
(`server/src/services/connectors/linkedin/catalog.ts`, `index.ts`,
`index.test.ts`) using `LinkedIn-Version: 202611` and registered it in
`server/src/services/connectors/rest-registry.ts`:
- `linkedin_get_profile` (`read`, also powers `probe()` via `GET
/v2/userinfo`)
- `linkedin_create_post` (`destructive`, S4; derives `author` URN from
authenticated grant via `POST /rest/posts`)
- `linkedin_delete_post` (`destructive`, S4; validates post URN via
`DELETE /rest/posts/{encoded_urn}`)
- Added `packages/shared/src/linkedin-connectors.ts` (`linkedin.share`
profile & scopes) and exported from `packages/shared/src/index.ts`.
- Wired `linkedin` / `linkedin.share` into
`server/src/services/paperclip-cloud-connector.ts`,
`server/src/services/tool-access/oauth/client-settings.ts` (with
exhaustive `managedConnectorIssuer` mapping), and
`server/src/services/tool-access/oauth/authorization-start.ts`.
- Added official sanitized LinkedIn SVG
(`ui/public/brands/apps/linkedin.svg`) and registered it in
`ui/public/brands/apps/manifest.json`.
- Added reviewed catalog override
(`scripts/app-definition-overrides/linkedin.json`), regenerated
`packages/shared/src/app-definitions/linkedin.json` and
`app-definitions.generated.ts`, added `"linkedin"` to
`CONNECTABLE_APP_SLUGS`, and added permission reviews in
`doc/connections/tool-method-permission-reviews.json`.
- Added `doc/connections/LINKEDIN.md` and indexed it in
`doc/connections/README.md`.
- Merged `master` and resynced
`tests/runner-e2e/source-sdk-public-inputs.json`.
## Verification
- `node scripts/check-app-brand-assets.mjs` — passed (115 brand
identities validated)
- `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse
HEAD) --check` — passed (`changed: false`)
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/server typecheck && pnpm --filter @paperclipai/ui
typecheck` — passed
- `pnpm exec vitest run
server/src/services/connectors/rest-transport.test.ts
server/src/services/connectors/linkedin/index.test.ts
server/src/services/connectors/vercel/index.test.ts
server/src/services/connectors/supabase/index.test.ts
server/src/services/tool-access/oauth/client-settings.test.ts
server/src/services/paperclip-cloud-connector.test.ts
server/src/__tests__/connector-tool-policy.test.ts
packages/shared/src/app-definitions.test.ts` — passed (8 files, 248/248
tests)
- `pnpm exec vitest run ui/src/lib/app-brand-assets.test.ts --project
@paperclipai/ui` — passed (7/7)
- `pnpm verify --explain` — exit 2 (global CI input
`doc/connections/tool-method-permission-reviews.json` changed; full CI
`ci / verify` and `ci / e2e` running on current head `cc7e3a8184`)
- **Live-provider proof (human-gated — pending):** Registering
Paperclip's LinkedIn Developer App + AWS Secrets Manager credentials on
`paperclip-cloud` (companion PR) and completing an interactive OAuth
sign-in on a real LinkedIn account are required before live-account
acceptance.
## Risks
- LinkedIn posts are public external broadcasts (S4); both
`linkedin_create_post` and `linkedin_delete_post` are classified
`destructive`, and `author` is always derived from the authenticated
grant rather than caller input.
- Standard self-serve LinkedIn tokens expire every 60 days without a
refresh token; UI copy and docs state this explicitly.
- Extracting `rest-transport.ts` touches Vercel and Supabase adapters
alongside LinkedIn; all three adapters' unit suites (80 tests combined)
plus dedicated `rest-transport.test.ts` pass and preserve existing
status/error codes while extending unified write
`408`/`5xx`/unparseable-2xx uncertain-outcome protection.
- Deploy the companion `paperclip-cloud` PR (`feat/linkedin-connector`)
and configure LinkedIn client credentials before enabling `managed`
sign-in on Cloud stacks.
## Model Used
- Google Gemini (Antigravity agentic coding assistant, tool use and code
execution enabled)
## 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
|
||
|
|
042cb67370 |
fix(ui): keep Composio connect navigation from closing back to /apps (#23845)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The Plugins page lets users connect third-party apps directly or through aggregators like Composio and Arcade. > - When an app offers multiple aggregators, clicking Connect opens AggregatorConnectDialog so the user can choose a provider. > - Selecting Composio with no saved Composio gateway, or clicking Connect new account, called onNavigate and then immediately called onClose. > - In Browse, closeAggregatorSetup checked window.location.search for source=composio, matched the URL that onNavigate had just pushed, and replaced the route with /apps. > - This pull request stops in-app dialog navigation from calling onClose, clears dialog state in Browse's navigation handler, and reads React Router's location.search instead of window.location.search. > - The benefit is that choosing Composio or adding a new Composio account from the connect modal navigates cleanly to /apps/connect while dismissing the modal still strips ?source=composio. ## Linked Issues or Issue Description No public GitHub issue exists for this report (searched open and closed issues and PRs for duplicates). **What happened?** When going to Plugins -> Slack -> Connect and clicking Composio without a saved Composio gateway, the connect modal closed and redirected back to /apps instead of opening /apps/connect?source=composio&targetToolkit=slack. The same redirect happened when opening the modal via /apps?source=composio&targetToolkit=slack and clicking Connect new account. **Expected behavior** Clicking Composio with no saved Composio gateway navigates to /apps/connect?source=composio&targetToolkit=slack. Clicking Connect new account navigates to /apps/connect?source=composio&targetToolkit=slack&new=1. Dismissing the modal without navigating still closes it and strips ?source=composio back to /apps. **Steps to reproduce** 1. Open Plugins on a Cloud instance where Slack yields to aggregators and no Composio gateway is saved. 2. Open Slack and click Connect. 3. Click Composio in the Connect Slack dialog. 4. Observe that the dialog closes and the page stays on /apps instead of navigating to /apps/connect?source=composio&targetToolkit=slack. **Access context** Board (human operator) ## What Changed - Updated `ui/src/pages/apps/AggregatorConnectDialog.tsx` so in-app navigation handlers (`choose`, `onConnectNew`, and the non-Composio "Connect a new account" button) call only `onNavigate` without also invoking `onClose`. - Updated `ui/src/pages/apps/Browse.tsx` to pass `navigateFromAggregatorSetup` as `AggregatorConnectDialog`'s `onNavigate` prop so navigation clears dialog state without triggering `closeAggregatorSetup`'s `?source=composio` redirect cleanup. - Switched `Browse.tsx` from `window.location.search` to React Router's `useLocation().search` for the `?source=...` effect and dismissal cleanup. - Added `ui/src/pages/apps/Browse.aggregatorConnect.test.tsx` with real `BrowserRouter` regression tests covering Plugins -> Slack -> Connect -> Composio, new-account navigation from `?source=composio`, dismissal cleanup, and staying on the plugin page when cancelling. ## Verification - Verified TDD red-before / green-after on `ui/src/pages/apps/Browse.aggregatorConnect.test.tsx`: before the fix, both Composio navigation tests failed with `Received: "/PAP/apps"` instead of `/PAP/apps/connect?source=composio&targetToolkit=slack` and `...&new=1`. - Ran `pnpm vitest run ui/src/pages/apps/Browse.aggregatorConnect.test.tsx ui/src/pages/apps/Browse.pluginTileState.test.ts ui/src/pages/apps/AppsConnect.test.tsx ui/src/lib/analytics/replay-masking.test.tsx` on rebased HEAD `c605d6358c`: 4 test files, 243 tests passed. - Ran `pnpm --filter @paperclipai/ui typecheck`: passed with 0 errors. - CI covers repo-wide typecheck, build, and test suites on the pushed PR revision. ## Risks - Low risk. Changes are scoped to `AggregatorConnectDialog` and `Browse`'s aggregator connect dialog wiring. Dismissal actions (Cancel, Escape, dialog close, completion, and external management links) still invoke `closeAggregatorSetup` to invalidate aggregator queries and strip `?source=composio`. ## Model Used - Google Gemini 4 (Antigravity agent with extended reasoning and local tool/test 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 - [ ] 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> |
||
|
|
2d7bb6392d |
build(deps): bump actions/checkout from 4.2.2 to 7.0.1 (#19561)
Bumps [actions/checkout](https://github.com/actions/checkout) from 4.2.2 to 7.0.1. <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/actions/checkout/releases">actions/checkout's releases</a>.</em></p> <blockquote> <h2>v7.0.1</h2> <h2>What's Changed</h2> <ul> <li>skip running unsafe pr check if input is default by <a href="https://github.com/aiqiaoy"><code>@aiqiaoy</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2518">actions/checkout#2518</a></li> <li>trim only ascii whitespace for branch by <a href="https://github.com/aiqiaoy"><code>@aiqiaoy</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2521">actions/checkout#2521</a></li> <li>escape values passed to --unset by <a href="https://github.com/aiqiaoy"><code>@aiqiaoy</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2530">actions/checkout#2530</a></li> <li>Various dependency updates</li> </ul> <p><strong>Full Changelog</strong>: <a href="https://github.com/actions/checkout/compare/v7...v7.0.1">https://github.com/actions/checkout/compare/v7...v7.0.1</a></p> <h2>v7.0.0</h2> <h2>What's Changed</h2> <ul> <li>block checking out fork pr for pull_request_target and workflow_run by <a href="https://github.com/aiqiaoy"><code>@aiqiaoy</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2454">actions/checkout#2454</a></li> <li>Bump actions/publish-immutable-action from 0.0.3 to 0.0.4 in the minor-actions-dependencies group across 1 directory by <a href="https://github.com/dependabot"><code>@dependabot</code></a>[bot] in <a href="https://redirect.github.com/actions/checkout/pull/2458">actions/checkout#2458</a></li> <li>Bump flatted from 3.3.1 to 3.4.2 by <a href="https://github.com/dependabot"><code>@dependabot</code></a>[bot] in <a href="https://redirect.github.com/actions/checkout/pull/2460">actions/checkout#2460</a></li> <li>Bump js-yaml from 4.1.0 to 4.2.0 by <a href="https://github.com/dependabot"><code>@dependabot</code></a>[bot] in <a href="https://redirect.github.com/actions/checkout/pull/2461">actions/checkout#2461</a></li> <li>Bump <code>@actions/core</code> and <code>@actions/tool-cache</code> and Remove uuid by <a href="https://github.com/dependabot"><code>@dependabot</code></a>[bot] in <a href="https://redirect.github.com/actions/checkout/pull/2459">actions/checkout#2459</a></li> <li>upgrade module to esm and update dependencies by <a href="https://github.com/aiqiaoy"><code>@aiqiaoy</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2463">actions/checkout#2463</a></li> <li>Bump the minor-npm-dependencies group across 1 directory with 3 updates by <a href="https://github.com/dependabot"><code>@dependabot</code></a>[bot] in <a href="https://redirect.github.com/actions/checkout/pull/2462">actions/checkout#2462</a></li> <li>getting ready for checkout v7 release by <a href="https://github.com/aiqiaoy"><code>@aiqiaoy</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2464">actions/checkout#2464</a></li> <li>update error wording by <a href="https://github.com/aiqiaoy"><code>@aiqiaoy</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2467">actions/checkout#2467</a></li> </ul> <h2>New Contributors</h2> <ul> <li><a href="https://github.com/aiqiaoy"><code>@aiqiaoy</code></a> made their first contribution in <a href="https://redirect.github.com/actions/checkout/pull/2454">actions/checkout#2454</a></li> </ul> <p><strong>Full Changelog</strong>: <a href="https://github.com/actions/checkout/compare/v6.0.3...v7.0.0">https://github.com/actions/checkout/compare/v6.0.3...v7.0.0</a></p> <h2>v6.1.0</h2> <h2>What's Changed</h2> <ul> <li><strong>[BREAKING]</strong> backport <code>allow-unsafe-pr-checkout</code> to v6 by <a href="https://github.com/aiqiaoy"><code>@aiqiaoy</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2500">actions/checkout#2500</a></li> <li>backport fixes to releases-v6 by <a href="https://github.com/aiqiaoy"><code>@aiqiaoy</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2527">actions/checkout#2527</a></li> </ul> <p><a href="https://github.blog/changelog/2026-06-18-safer-pull_request_target-defaults-for-github-actions-checkout/">https://github.blog/changelog/2026-06-18-safer-pull_request_target-defaults-for-github-actions-checkout/</a> for more details about this breaking change</p> <p><strong>Full Changelog</strong>: <a href="https://github.com/actions/checkout/compare/v6.0.3...v6.1.0">https://github.com/actions/checkout/compare/v6.0.3...v6.1.0</a></p> <h2>v6.0.3</h2> <h2>What's Changed</h2> <ul> <li>Update changelog by <a href="https://github.com/ericsciple"><code>@ericsciple</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2357">actions/checkout#2357</a></li> <li>fix: expand merge commit SHA regex and add SHA-256 test cases by <a href="https://github.com/yaananth"><code>@yaananth</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2414">actions/checkout#2414</a></li> <li>Fix checkout init for SHA-256 repositories by <a href="https://github.com/yaananth"><code>@yaananth</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2439">actions/checkout#2439</a></li> <li>Update changelog for v6.0.3 by <a href="https://github.com/yaananth"><code>@yaananth</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2446">actions/checkout#2446</a></li> </ul> <h2>New Contributors</h2> <ul> <li><a href="https://github.com/yaananth"><code>@yaananth</code></a> made their first contribution in <a href="https://redirect.github.com/actions/checkout/pull/2414">actions/checkout#2414</a></li> </ul> <p><strong>Full Changelog</strong>: <a href="https://github.com/actions/checkout/compare/v6...v6.0.3">https://github.com/actions/checkout/compare/v6...v6.0.3</a></p> <h2>v6.0.2</h2> <h2>What's Changed</h2> <ul> <li>Add orchestration_id to git user-agent when ACTIONS_ORCHESTRATION_ID is set by <a href="https://github.com/TingluoHuang"><code>@TingluoHuang</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/2355">actions/checkout#2355</a></li> </ul> <!-- raw HTML omitted --> </blockquote> <p>... (truncated)</p> </details> <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/actions/checkout/commit/3d3c42e5aac5ba805825da76410c181273ba90b1"><code>3d3c42e</code></a> prep v7.0.1 release (<a href="https://redirect.github.com/actions/checkout/issues/2531">#2531</a>)</li> <li><a href="https://github.com/actions/checkout/commit/28802689a136bfcdb721715abd713740beecbe07"><code>2880268</code></a> escape values passed to --unset (<a href="https://redirect.github.com/actions/checkout/issues/2530">#2530</a>)</li> <li><a href="https://github.com/actions/checkout/commit/12cd2235efa0937479335606d7c3ac9f6c0973b1"><code>12cd223</code></a> trim only ascii whitespace for branch (<a href="https://redirect.github.com/actions/checkout/issues/2521">#2521</a>)</li> <li><a href="https://github.com/actions/checkout/commit/62661c4e71a304b2823ed026347b8d34c3eac541"><code>62661c4</code></a> skip running unsafe pr check if input is default (<a href="https://redirect.github.com/actions/checkout/issues/2518">#2518</a>)</li> <li><a href="https://github.com/actions/checkout/commit/e8d4307400f9427dba7cb98e488d6ab85f1cec5f"><code>e8d4307</code></a> Bump the minor-actions-dependencies group with 2 updates (<a href="https://redirect.github.com/actions/checkout/issues/2499">#2499</a>)</li> <li><a href="https://github.com/actions/checkout/commit/631c942040754b6e095e929c1677c07e10ed4f87"><code>631c942</code></a> eslint 9 (<a href="https://redirect.github.com/actions/checkout/issues/2474">#2474</a>)</li> <li><a href="https://github.com/actions/checkout/commit/4f1f4aec02e41874fa0262ea8ff5172d7978ad1e"><code>4f1f4ae</code></a> Bump actions/upload-artifact from 4 to 7 (<a href="https://redirect.github.com/actions/checkout/issues/2476">#2476</a>)</li> <li><a href="https://github.com/actions/checkout/commit/ba097532fb203f7e88c9c3c0b899b49469908a92"><code>ba09753</code></a> Bump actions/checkout from 6 to 7 (<a href="https://redirect.github.com/actions/checkout/issues/2488">#2488</a>)</li> <li><a href="https://github.com/actions/checkout/commit/b9e0990d219a03df7633c93f6f005a8fecbcab22"><code>b9e0990</code></a> Bump docker/login-action from 3.3.0 to 4.2.0 (<a href="https://redirect.github.com/actions/checkout/issues/2479">#2479</a>)</li> <li><a href="https://github.com/actions/checkout/commit/e8cb398be4a550817e382abf69e4c12c76fce1f2"><code>e8cb398</code></a> Bump docker/build-push-action from 6.5.0 to 7.2.0 (<a href="https://redirect.github.com/actions/checkout/issues/2478">#2478</a>)</li> <li>Additional commits viewable in <a href="https://github.com/actions/checkout/compare/v4.2.2...v7.0.1">compare view</a></li> </ul> </details> <br /> Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> |
||
|
|
fd8ad7d5b8 |
fix(ui): remove environment selector from AI connection setup (#23836)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Users connect AI provider accounts (Claude, OpenAI, Antigravity, xAI, and GitHub Copilot) through `AiConnectionCredentialStep` > - AI connections store credentials in Paperclip's secret store and do not bind the saved connection to an execution environment > - When a company had more than one active login-capable environment, the setup form showed a raw environment dropdown (exposing internal sandbox names and appearing even for API key or hosted OAuth flows) > - The component already resolves the default login or probe environment automatically > - This pull request removes the environment selector dropdowns from `AiConnectionCredentialStep` while preserving automatic environment resolution > - The benefit is a simpler AI connection flow that does not leak internal execution infrastructure into provider account setup ## Linked Issues or Issue Description **What existing behavior does this improve?** The AI provider connection setup screen (`AiConnectionCredentialStep`) for Anthropic (Claude), OpenAI, Google (Antigravity), xAI (Grok), and GitHub Copilot. **Subsystem affected** `ui/` — React + Vite board UI **Current behavior** When a company has more than one active login-capable environment, `SubscriptionConnectionStep` renders a `Sign-in environment` dropdown and `ApiKeyConnectionStep` renders a `Copilot execution environment` dropdown. The dropdown appears even for hosted Google OAuth or when the user switches to an API key, and it exposes internal sandbox labels such as `Paperclip Sandbox (Legacy)`. **Proposed behavior** Remove both environment dropdowns from `AiConnectionCredentialStep` and update the GitHub Copilot help text to say verification discovers models automatically. Continue resolving `environmentId` automatically from the forced Kubernetes environment, instance default, plugin login target preferences, or local default environment. **Reason and benefit** Saved AI connections are not bound to an execution environment; the environment is only an internal detail for running a temporary subscription login PTY or Copilot model probe. Removing the dropdown eliminates user confusion and keeps internal infrastructure out of the Apps connect flow. **Breaking changes** Users can no longer manually override the temporary login/probe environment from the standalone AI connection setup form; Paperclip uses the automatically resolved default environment instead. Agent-scoped flows that pass `environmentId` explicitly continue to use the supplied environment. ## What Changed - Removed the `Sign-in environment` `<Select>` and unused `chosenEnvironment` state from `SubscriptionConnectionStep` in `ui/src/components/ai-connections/AiConnectionCredentialStep.tsx`. - Removed the `Copilot execution environment` `<Select>` and unused `chosenEnvironment` state from `ApiKeyConnectionStep` in `ui/src/components/ai-connections/AiConnectionCredentialStep.tsx`, and updated the Copilot help text to match. - Added `ui/src/components/ai-connections/AiConnectionCredentialStep.test.tsx` to verify that no environment selector renders for Anthropic, OpenAI, Google, xAI, or GitHub Copilot when multiple environments exist, while automatic `environmentId` resolution is preserved. ## Verification - `pnpm --filter @paperclipai/ui exec vitest run src/components/ai-connections/AiConnectionCredentialStep.test.tsx` — 5/5 tests passed. - `pnpm --filter @paperclipai/ui typecheck` — passed. - `pnpm verify` — 270/271 UI test files passed in the combined run (1 unrelated `requestAnimationFrame` timing failure in `src/components/TaskChatThread.test.tsx`); re-running `pnpm --filter @paperclipai/ui exec vitest run src/components/TaskChatThread.test.tsx src/components/ai-connections/AiConnectionCredentialStep.test.tsx` passed all 444 tests (1 skipped). ## Risks - Low risk. Self-hosted instances with multiple login-capable environments now always use the automatically resolved default environment during standalone AI account sign-in rather than exposing a per-login override dropdown. > 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 - Google Gemini (Antigravity agent, medium reasoning effort, with repository read/edit, terminal, and browser inspection 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 - [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 |
||
|
|
83d80b431b |
perf(db): add partial indexes for chat_actions run publications and pending work (#23811)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - External chat connectors (GitHub, Slack, Telegram, voice) store
webhook ingress, publication receipts, and scheduled background work in
`chat_actions`
> - On large instances (~325k rows in `chat_actions`, mostly processed
`github_webhook_ingress`), two hot query families fall back to full
sequential scans because existing partial indexes do not cover their
predicates
> - `githubRunReplyState` queries `kind = 'github_review_publication'`
across all statuses (including unsettled
`received`/`processing`/`failed` rows), so PostgreSQL cannot use
`chat_actions_github_task_publications_idx` (`WHERE kind =
'github_review_publication' AND status = 'processed'`)
> - Scheduled work polling (`nextChatActionAt`, `dueChatAction`, and
pending GitHub publication/response sweeps) filters active non-terminal
statuses (`received`, `processing`, `queued`, etc.) and retryable
failures across kinds that have no matching partial work index
> - This pull request adds two concurrent, idempotent, online-compatible
partial indexes on `chat_actions`
(`chat_actions_github_run_publications_idx` and
`chat_actions_pending_work_idx`) and adds PostgreSQL `EXPLAIN (ANALYZE,
BUFFERS)` regression coverage
> - The benefit is eliminating repeated full-table sequential scans on
`chat_actions` without locking writes during migration or altering query
semantics
## Linked Issues or Issue Description
**What happened?**
On a PostgreSQL instance with ~325k `chat_actions` rows (mostly
processed `github_webhook_ingress`), `chat_actions` incurred ~103 full
sequential scans per 5 seconds (20.6 scans/s):
- `githubRunReplyState` (`server/src/services/chat-run-publications.ts`)
ran a `Parallel Seq Scan on chat_actions` (218.6 ms, 100,595 shared
buffer hits for 1 row) because
`chat_actions_github_task_publications_idx` restricts `status =
'processed'` while `githubRunReplyState` must also inspect unsettled
rows.
- Scheduled action polling (`nextChatActionAt` and `dueChatAction` in
`server/src/services/chat-action-work.ts`, plus
`nextPendingAt`/`processPending` in
`server/src/services/chat-github-reviews.ts` and
`server/src/services/chat-github-response-comments.ts`) ran full
sequential scans (62.4 ms, 25,212 shared buffer hits) because no partial
work index covered `status IN ('received', 'processing', ...) OR (status
= 'failed' AND result->>'retryable' = 'true')` by `kind`. (Existing
`review-check-work.ts` and `acknowledgement-work.ts` do not include
`'processing'` and already use `chat_actions_github_check_work_idx` and
`chat_actions_github_ack_work_idx`.)
**Expected behavior**
PostgreSQL should resolve `githubRunReplyState` and scheduled
`chat_actions` work polling through small partial indexes in
sub-millisecond time with minimal shared buffer hits and zero full
sequential scans over completed webhook history.
**Steps to reproduce**
1. Populate `chat_actions` with ~10k+ processed `github_webhook_ingress`
and `github_review_publication` rows plus active target rows, then run
`VACUUM ANALYZE chat_actions`.
2. Run `EXPLAIN (ANALYZE, BUFFERS)` on `githubRunReplyState(...)` and on
`nextChatActionAt(db, "github_webhook_ingress")` /
`dueChatAction("github_webhook_ingress")`.
3. Observe full `Seq Scan on chat_actions` scanning all table pages
before this migration.
**Paperclip version or commit**
`master` (`6a5dfc0288`)
**Deployment mode**
Self-hosted server
## What Changed
- Added `chat_actions_github_run_publications_idx` in
`packages/db/src/schema/chat_channels.ts` on `(company_id, endpoint_id,
(payload->'session'->>'issueId'), (payload->'session'->>'runId')) WHERE
kind = 'github_review_publication'`.
- Added `chat_actions_pending_work_idx` in
`packages/db/src/schema/chat_channels.ts` on `(kind, created_at, id)
WHERE status IN ('received', 'processing', 'queued',
'provider_confirmed', 'admitting', 'resolving', 'validating',
'dispatching') OR (kind = 'failed_run_retry' AND status IN ('issued',
'processing')) OR (status = 'failed' AND result->>'retryable' =
'true')`. (Excludes permanently `'issued'` kinds such as
`task_control_authorization` and completed/cancelled/non-retryable
history so the index stays minimal at rest.)
- Generated migration
`packages/db/src/migrations/0516_exotic_spectrum.sql` with idempotent
`CREATE INDEX CONCURRENTLY IF NOT EXISTS`, registered it in
`MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS` in `packages/db/src/client.ts`,
and pruned schema snapshots to the 5 newest (`0512`–`0516`).
- Extended `server/src/__tests__/chat-admission-condition.test.ts` with
embedded PostgreSQL regression coverage verifying result behavior and
`EXPLAIN (ANALYZE, BUFFERS)` partial index usage (zero `Seq Scan` on
`chat_actions`) for `githubRunReplyState`, every `ScheduledChatAction`
in `CHAT_ACTION_QUEUES` (`nextChatActionAt`), `dueChatAction`
(`github_webhook_ingress`, `failed_run_retry`),
`githubChatReviewService.nextPendingAt`/`processPending`,
`githubResponseCommentService.processPending`, and
`speko_voice_reply_push` (`dispatching`).
## Verification
- Local red/green `EXPLAIN (ANALYZE, BUFFERS)` against embedded
PostgreSQL 18 with 10,003 `chat_actions` rows (8,000 processed
`github_webhook_ingress`, 1,000 processed `github_review_publication`,
500 processed `inbound_wakeup`, 500 issued `task_control_authorization`,
3 target rows) with strict result equality verified before and after
applying the concurrent partial-index migration SQL (and verified 2x
idempotent replay + `indisvalid = true`, `indisready = true`, index
sizes 152 kB and 16 kB):
| Query | Before | After (`0516`) |
| --- | --- | --- |
| `githubRunReplyState` | `Seq Scan` (0.900 ms, 2,204 buffer hits) |
`Index Scan(chat_actions_github_run_publications_idx)` (0.018 ms, 7
buffer hits) |
| `nextChatActionAt(github_webhook_ingress)` | `Seq Scan` (1.169 ms,
2,200 buffer hits) | `Bitmap Index Scan(chat_actions_pending_work_idx)`
(0.011 ms, 2 buffer hits) |
| `nextChatActionAt(provider_effect)` | `Seq Scan` (0.891 ms, 2,200
buffer hits) | `Index Scan(chat_actions_pending_work_idx)` (0.005 ms, 1
buffer hit) |
| `nextChatActionAt(failed_run_retry)` | `Index
Scan(chat_actions_company_issue_kind_idx)` (0.028 ms, 11 buffer hits) |
`Index Scan(chat_actions_pending_work_idx)` (0.006 ms, 2 buffer hits) |
| `nextChatActionAt(slash_task_start)` | `Seq Scan` (0.839 ms, 2,200
buffer hits) | `Index Scan(chat_actions_pending_work_idx)` (0.007 ms, 1
buffer hit) |
| `dueChatAction(github_webhook_ingress)` | `Seq Scan` (1.148 ms, 2,200
buffer hits) | `Bitmap Index Scan(chat_actions_pending_work_idx)` (0.010
ms, 2 buffer hits) |
| `chat-github-reviews.nextPendingAt()` | `Seq Scan` (0.807 ms, 2,200
buffer hits) | `Index Scan(chat_actions_pending_work_idx)` (0.004 ms, 2
buffer hits) |
- Verified prepared-statement execution (`PREPARE` + 10 `EXECUTE` runs)
keeps custom partial-index plans on the 10th execution (`0.004–0.010
ms`) and does not regress `githubLatestTaskResponseUrl`
(`chat_actions_github_task_publications_idx`) or `review-check-work`
(`chat_actions_github_check_work_idx`).
- Ran local checks on commit `97f0f7294262aa129dd283072108ce6932f3a447`:
- `pnpm --filter @paperclipai/db build` — PASS
- `pnpm --filter @paperclipai/db check:migrations` — PASS (1 new
migration, `online_compatible`, none blocked)
- `pnpm check:module-boundaries` — PASS
- `node scripts/check-test-budget.mjs --base origin/master` — PASS (113
nightly suites validated, 1 test file checked)
- `pnpm --filter @paperclipai/db typecheck` & `pnpm --filter
@paperclipai/server typecheck` — PASS
- `pnpm exec vitest run packages/db/src/check-migration-safety.test.ts
packages/db/src/migration-compatibility.test.ts
packages/db/src/migration-snapshot-drift.test.ts
server/src/__tests__/chat-admission-condition.test.ts` — 4 files, 149
tests passed
## Risks
- Low risk: purely additive migration creating two partial indexes with
`CREATE INDEX CONCURRENTLY IF NOT EXISTS` in
`MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`. Writes are not blocked during
index build, existing indexes
(`chat_actions_github_task_publications_idx`,
`chat_actions_github_check_work_idx`,
`chat_actions_github_ack_work_idx`) remain untouched, and previous
releases continue serving safely during rolling deploy.
- Small write-amplification trade-off: active `chat_actions` rows enter
`chat_actions_pending_work_idx` while non-terminal and leave once
settled; `chat_actions_github_run_publications_idx` tracks
`github_review_publication` rows only (excluding high-volume
`github_webhook_ingress` history).
## Model Used
- Gemini 4 Neon (Google DeepMind, XHigh reasoning, 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
- [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>
|
||
|
|
84ca111c78 |
fix(slack): align form publication wait backoff with enrollment deadlines (#23819)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Slack chat channels deliver interactive question forms that depend on Cloud events and form-owner enrollment before Paperclip posts the prompt. > - When enrollment is pending and backed off for 60s to 300s, `createSlackFormPublicationStage` returns a hardcoded `retryAfterMs: 2_000` wait instead of reading the enrollment `nextAttemptAt` deadline. > - That hardcoded 2-second wait makes the publication worker claim leases, run 20 to 30 SQL queries, emit `chat publication failed` warnings every few seconds, and keep `chat_endpoint_leases` hot while blocking idle sleep. > - This pull request derives the publication wait delay from the pending `slackCloudIntent` or `slack_form_owner` deadline (bounded to `[2_000 ms, 300_000 ms]`), clears waiting publication deadlines and notifies `chatPublications` whenever enrollment commits, retires, or enters `attention`, rechecks wait state via a shared predicate inside a savepoint (`FOR SHARE NOWAIT`) in the deferral transaction, and logs pre-send waits at debug level. > - The benefit is cutting a 5-minute enrollment wait from ~100–150 publication/lease cycles to 1 while preserving immediate wake on early enrollment completion or attention settlement. ## Linked Issues or Issue Description **What happened?** A Slack form publication waiting on `form_publication_enrollment_pending` loops every ~2–3 seconds and logs `chat publication failed` warnings continuously while enrollment is backed off for up to 300 seconds. Each tick claims and deletes `chat_endpoint_leases`, writes `chat_publications`, and prevents the worker from going quiet. **Expected behavior** A Slack form publication waiting on pending enrollment schedules its `nextAttemptAt` to match the pending `slackCloudIntent.nextAttemptAt` or `slack_form_owner.result.nextAttemptAt` deadline (with a 2-second floor for past/due deadlines and a 300-second cap), emits a debug log rather than a failure warning, and wakes immediately when enrollment commits early, retires, or transitions to `attention`. **Steps to reproduce** 1. Configure a Slack endpoint with managed Cloud forms and a pending `slackCloudIntent` or staged `slack_form_owner` backed off 60s–300s in the future. 2. Create an `ask_user_questions` interaction with a Slack form prompt (`question_form_open`) on an active Slack conversation. 3. Run the `chatPublications` delivery worker and observe `chat_publications.next_attempt_at` and server logs. **Paperclip version or commit** Reproduced on `master` prior to `0c0cd68c711da5ebdb0cbaf5a2d54bc96faca7c4`. **Deployment mode** Self-hosted server ## What Changed - **`server/src/services/chat-channels/slack/form-publication.ts`**: Extract single-source-of-truth `pendingIntentDeadline` and `pendingOwnerDeadline` helpers used by both the main readiness gate and the `stillWaiting(tx)` recheck. Compute `retryAfterMs` from the actual pending deadline clamped to `[2_000 ms, 300_000 ms]`. Use `FOR SHARE NOWAIT` in `stillWaiting(tx)` so the recheck never blocks on concurrent enrollment updates. - **`server/src/services/chat-channels/publications/preparation.ts` & `publications/failures.ts`**: Extend `ChatPublicationPreparationWait` with an optional platform-agnostic `stillWaiting?: (tx: DbTransaction) => Promise<boolean>` callback. Execute `stillWaiting` inside a PostgreSQL savepoint (`tx.transaction(...)`): if `stillWaiting` returns `false`, commit `nextAttemptAt = null` so an enrollment commit racing deferral wakes immediately; if `stillWaiting` hits lock contention (`NOWAIT`) or a transient error, roll back only the savepoint and commit `state = "retry"` with a `<= 2_000 ms` fallback so a benign pre-send wait can never stay `streaming` and become `delivery_unknown`. Log `waitingBeforeSend` deferrals at `logger.debug(..., "chat publication waiting before send")` instead of `logger.warn(..., "chat publication failed")`. - **`server/src/services/chat-channels/slack/form-owner.ts` & `cloud-enrollment.ts`**: Add `clearWaitingSlackFormPublicationDeadlines(tx, endpoint)` and register `notifyChatPublicationWork(tx)` before writes across every enrollment resolution/retirement/attention transition (`reconcileSlackFormEnrollment`, `stageSlackFormEnrollment` for an already-enrolled owner, `stageSlackFormOwnerConfiguration` deactivation, `reconcilePendingSlackFormWork` permanent `attention`, `stageSlackCloudEnrollmentIntent` inactive/attention staging, and `createSlackCloudEnrollment` `intent_authority_changed` / `attention` / retirement commits). - **Tests & CI timing manifests**: Extended `server/src/__tests__/slack-cloud-forms.test.ts` and `server/src/services/chat-channels/slack/cloud-enrollment.test.ts`, added a focused real embedded-PostgreSQL suite in `server/src/__tests__/chat-channels/slack-form-enrollment-wait.integration.test.ts` (641 lines; keeping `slack-protocol.integration.test.ts` untouched at 726 lines), and registered its measured 8-core CI timing (`12547 ms`) in `scripts/chat-shard-durations.json` and `scripts/general-server-shard-durations.json`. ### Sleep-Aware Background Work Contract - **Trigger**: Shared `DELIVERY_QUEUES.chatPublications` transaction-aware work signals (`notifyChatPublicationWork`) and saved per-row `chat_publications.next_attempt_at` deadlines read by `nextPublicationAt()`. - **Durable source of truth**: `chat_publications` (`state`, `next_attempt_at`, `attempts`, `redacted_error`), `chat_endpoints.setup` (`slackCloudIntent`, `slackCloudForms`), and `chat_actions` (`slack_form_owner`). - **Pending-work predicate**: `publicationEligibility()` selects `chat_publications` in `pending`/`retry` whose `next_attempt_at` is `null` or due (`<= now`) on active/verifying endpoints. - **Next deadline/retry**: `nextAttemptAt` tracks `clamp(2_000, 300_000, enrollmentDeadline - now)` while enrollment is scheduled, is cleared to `null` when enrollment completes, retires, or enters `attention` (or when `stillWaiting(tx)` sees enrollment already settled), and falls back to `<= 2_000 ms` if `stillWaiting` encounters lock contention. - **Quiet condition**: Once waiting publications defer to the enrollment deadline (up to 300s), no publication sweep or lease write runs until either that deadline arrives or an enrollment producer commits a state change; once enrollment resolves, publications publish or settle to `failed`/`cancelled` and `nextPublicationAt()` returns `null`. ## Verification Verified on commit `a75b654d3d75f9b36f860b0793baa94f5811fdac`: - Reproduced pre-fix RED failures before applying the fix: unit tests confirmed hardcoded `2000 ms` waits for 60s/300s deadlines and missing publication wake on `slackCloudIntent` attention; real PostgreSQL tests confirmed 2s `nextAttemptAt` scheduling, `chat publication failed` warn logs, and 5-minute stranding on the concurrent commit race. - `pnpm check:module-boundaries` — PASS. - `node scripts/check-test-budget.mjs --base origin/master` — PASS (113 nightly suites validated, 3 test files checked). - `node --test ./scripts/__tests__/run-vitest-stable-shard.test.mjs ./scripts/__tests__/run-vitest-stable-pr-mode.test.mjs ./scripts/ci/test-selection-pr-timings.test.mjs ./scripts/check-test-budget.test.mjs .github/scripts/tests/ci-dependency-cache.test.mjs` — PASS (79/79 tests). - `pnpm --filter @paperclipai/server typecheck` — PASS (all 7 typecheck layers green; unchanged server sources since `459443a36a`). - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/slack-cloud-forms.test.ts src/services/chat-channels/slack/cloud-enrollment.test.ts src/services/chat-publication-errors.test.ts src/__tests__/chat-channels/slack-form-enrollment-wait.integration.test.ts` — PASS (4 test files, 106/106 tests passed; unchanged server sources since `459443a36a`). - Scope note: Local tests verify worker quiet, durable deadlines, and PostgreSQL reactivation; they do not by themselves prove deployed host suspension or fleet cost reduction. ## Risks - Low risk; no database schema or migration changes are introduced. - Lock ordering stays acyclic (`chat_endpoint_leases` -> `chat_endpoints` -> `chat_actions` -> `chat_publications`), and `stillWaiting(tx)` uses `FOR SHARE NOWAIT` inside a PostgreSQL savepoint so lock contention can neither block nor abort publication finalization. - `clearWaitingSlackFormPublicationDeadlines` only clears `next_attempt_at` on `state = 'retry'` rows with `redacted_error = 'form_publication_enrollment_pending'` for the affected `(company_id, endpoint_id)`, verified by test to leave unrelated provider rate-limit backoffs untouched. - Process-local transaction notifications cover supported application writers; startup reconstruction and the bounded 300s ceiling still recover any external or out-of-band state change. ## Model Used Gemini 4 Neon (Google DeepMind, XHigh reasoning, 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 - [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 |
||
|
|
1f817b495c |
fix(ui): hide monitor waiting notices during active runs (#23822)
## Thinking Path > - Paperclip manages work performed by AI agents. > - Task monitors schedule later checks. > - A saved schedule can remain present during a new run. > - The UI calls that state a wait even while the agent works. > - This change gives the current run priority over monitor notices. > - Users see the monitor again after the run ends. ## Linked Issues or Issue Description Refs #19519, which added the active-run wait message. This change removes that message during execution. Searches found no open duplicate, and the roadmap has no overlapping item. The small SSH fixture repair below addresses a CI regression introduced on master by #14309. **What happened?** A task showed a running agent and a monitor waiting notice at the same time. The notice said the agent was waiting or saving work, based only on the presence of a run. **Expected behavior** Show the current run without monitor waiting notices. Keep the saved schedule. Restore both monitor surfaces after execution ends, if the monitor remains scheduled. **Steps to reproduce** 1. Schedule a task monitor. 2. Start a run on the same task before its next check. 3. Inspect the task banner and composer while the run works. 4. End the run and confirm the retained monitor appears again. **Paperclip version or commit** Reproduced against master at |
||
|
|
238e4779af | Keep answered chat turns settled across later status changes (#23815) | ||
|
|
bc548a736a |
test: fix CLI bind races and SSH fixture input (#23830)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - CI runs fixtures for real CLI servers and SSH commands. > - The CLI fixture can lose its fallback port before the server binds it. > - The SSH login-profile fixture must supply the command payload on stdin. > - These fixture failures stop CI before it can verify the application behavior. > - This pull request adds bounded CLI bind retries and supplies the SSH stdin payload. > - The fixtures retain their startup deadlines, child identity checks, and behavior assertions. ## Linked Issues or Issue Description **What happened?** [Source verification 47462717613, attempt 2](https://github.com/paperclipai/paperclip/actions/runs/47462717613/job/145492578739) failed in `cli/src/__tests__/company-import-export-e2e.test.ts`. The fixture occupied port 41511. The server selected 41512, then exited with `listen EADDRINUSE: address already in use 127.0.0.1:41512`. The suite failed before health readiness. The other 354 files passed, with 3,971 tests passed and one skipped. This cancelled [image run 47462717565](https://github.com/paperclipai/paperclip/actions/runs/47462717565). The SSH login-profile fixture also ran the command bootstrap without its stdin payload. It exited with code 125 before it could check profile behavior. [CI run 47464397195 on `ef3250d`](https://github.com/paperclipai/paperclip/actions/runs/47464397195/job/145497678930) failed on that test. The CLI shard passed in the same run. **Expected behavior** A fixture can start a fresh attempt after it loses a listener bind race to another local process. A configuration error, signal exit, health timeout, or test assertion must still fail. Runtime discovery must use the child PID and actual fallback port. The SSH fixture must supply `stdinPrefix` to execute the generated remote command. **Steps to reproduce** The failed source was master `dfe392dada69838da3d7c33a0ef00d7e4cfc60f3`, in local trusted mode. Reserve a loopback port, then make a child process bind that port. The new socket regression test does this without timing assumptions. Without the retry policy, the first collision aborts startup. For the SSH failure, run `PAPERCLIP_VITEST_RETRY=0 pnpm exec vitest run packages/adapter-utils/src/ssh-fixture.test.ts -t 'survives a bash-only login profile' --maxWorkers=1` on a host with `dash`. Before the stdin fix, it exits 125 with empty output. Refs #23813: that separate database teardown fix is already in this master revision. This failure is a listener bind collision. ## What Changed - Retry only a child exit with code 1 and the listener `EADDRINUSE` diagnostic on stderr. Limit startup to three attempts. - Release the old port reservation and start a fresh child with a fresh requested-port reservation on each attempt. - Share the original 90-second startup deadline across attempts. Keep the PID-matched runtime health check and the assertion that the server used a fallback port. - Recognize a child that has already exited by signal, so cleanup does not wait for a past exit event. - Add real-socket regression tests for recovery, failure limits, and other startup errors. - Pass `target.stdinPrefix` to the SSH login-profile fixture process, as required by the existing transport contract. ## Verification - CLI red: with the policy set to one attempt, the socket recovery test failed with the same `EADDRINUSE` diagnostic as CI. The bounded-attempt test also failed. - CLI green: `PAPERCLIP_VITEST_RETRY=0 pnpm exec vitest run cli/src/__tests__/server-startup.test.ts cli/src/__tests__/company-import-export-e2e.test.ts --maxWorkers=1` passed both suites and all five tests after rebase. CLI typecheck passed. These files have not changed since that verification. - SSH red: the targeted login-profile test failed locally with exit 125 and retries disabled, matching the CI failure on `ef3250d`. - SSH green: `PAPERCLIP_VITEST_RETRY=0 pnpm exec vitest run packages/adapter-utils/src/ssh-fixture.test.ts --maxWorkers=1` passed 26 tests, with two skipped. `pnpm exec tsc --noEmit -p packages/adapter-utils/tsconfig.json` passed. - The test budget check passed for all three changed test files. `git diff --check` passed. Final head: `4b0a5e4b96702829454b101b57be313b8908a63e`. - The CLI dependency-selection plan retained 2,347 of 3,084 test files on the previous head. Required CI will verify the final head with the SSH correction. No full local suite was run. - [Greptile rated final head `4b0a5e4b96702829454b101b57be313b8908a63e` 5/5](https://github.com/paperclipai/paperclip/pull/23830#issuecomment-7429780977), with no actionable findings or review threads. Final check results: 76 passed, six skipped, none pending or failed. The [final CI workflow](https://github.com/paperclipai/paperclip/actions/runs/47465088910) passed, and GitHub reports no merge conflicts. - Operational recovery: [image run 47463279495](https://github.com/paperclipai/paperclip/actions/runs/47463279495/job/145501215693) passed exact-source verification and published the AMD64/ARM64 manifest for master `6a5dfc028831831756bea006df4e399e31cdf281`. Tag: `ghcr.io/paperclipai/paperclip:sha-6a5dfc0`. Digest: `sha256:44576ab5bc386903dd592ed1f3e7277f60e0cd6c696590996d02330be2fbdbff`. All publication gates remained in place. This establishes publication recovery; these fixture changes address recurrence and still need to merge. ## Risks - Low risk. This changes test fixture startup only. - A persistent collision still fails after three attempts. Other failures retain their diagnostics and do not retry. Each recovered collision emits a warning in the test log. - Production listener selection is unchanged. This PR does not add a production server restart policy. - No documentation change is needed because the application contract does not change. ## Model Used - OpenAI `gpt-6.1-sol`, through the Codex harness in T3 Code, with xhigh reasoning effort and shell tools. The context window size is 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 - [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> |
||
|
|
65f429305e |
build(deps-dev): bump @types/node from 24.13.3 to 24.19.2 in /packages/plugins/sandbox-providers/daytona (#19564)
Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 24.13.3 to 24.19.2. <details> <summary>Commits</summary> <ul> <li>See full diff in <a href="https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node">compare view</a></li> </ul> </details> <br /> Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> |
||
|
|
205482b2c2 |
fix(telemetry): emit missing server telemetry across native, onboarding, and routine paths (#23297)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Paperclip emits first-party product telemetry from server lifecycle transitions so operators and Cloud analytics can measure real agent runs, completions, onboarding, and routines > - A full audit of every `track*` helper in `packages/shared/src/telemetry/events.ts` found several server code paths that perform real product transitions directly in the database without emitting their existing telemetry events: native/reconciliation terminal run failure writers (`agent.task_run`), agent-accepted `native_completion_review` closures (`agent.task_completed`), `active-run-watchdog` overwriting a null `lastHeartbeatAt` (suppressing `agent.first_heartbeat`), `onboarding-seed` creating the first agent and mission goal (`agent.created`, `goal.created`), routine suggestions creating a routine (`routine.created`), and standing check reports recording a routine run (`routine.run`) > - Because those paths bypass the REST routes or `emitTerminalAgentTaskRun` (which skips rows already written to `"failed"`), deployments under-report failed native runs, agent-reviewed completions, onboarding hires, and routine activity > - This pull request wires up the existing telemetry helpers at each missing server-side transition after transaction commit using a shared terminal-failure emitter, passes an explicit root database handle for post-commit operator-containment telemetry, skips non-terminal `retryable_failure` writes while emitting non-blocking telemetry on `retryable_failure -> terminal_failure` / `committed` transitions (including superseded retry retirement), keeps `agent-task-run-telemetry.ts` free of circular imports from `run-failure-report.ts`, updates `packages/shared/src/telemetry/README.md`, and adds embedded-Postgres regression tests covering every restored path > - The benefit is complete, deduplicated, non-blocking server-side telemetry across native runtime, onboarding, and routine flows without changing any telemetry contract schema ## Linked Issues or Issue Description Refs #22963 **What happened?** Several server-side lifecycle paths transitioned database rows directly without emitting their existing first-party telemetry events: 1. `native-session-executor.ts`, `native-restart-recovery.ts`, `native-superseded-retry.ts`, `execution-control-reconciliation.ts`, and `native-failed-run-owner-release.ts` wrote `heartbeat_runs.status = 'failed'` or transitioned `retryable_failure -> terminal_failure` directly (so `heartbeat.ts`'s `emitTerminalAgentTaskRun` later saw `previousStatus === updated.status` and skipped `agent.task_run`). 2. `issue-thread-interactions.ts` allowed an agent reviewer to accept a `native_completion_review` confirmation card and move an `in_review` task to `done` without emitting `agent.task_completed`. 3. `active-run-watchdog/adapters/postgres.ts` set `agents.lastHeartbeatAt = new Date()` unconditionally when folding a silent run instead of using `settledHeartbeat(now)`, suppressing `agent.first_heartbeat` for never-heartbeated agents. 4. `onboarding-seed.ts` created a company's first agent and mission goal without emitting `agent.created` or `goal.created`. 5. `routine-suggestions.ts` created routines from task suggestions without emitting `routine.created`, and `routine-standing-checks.ts` inserted completed `routine_runs` without emitting `routine.run`. **Expected behavior** Each of those committed transitions emits its existing first-party telemetry event once after commit, non-blocking, with accurate company and person scope (`withTelemetryActor` / `withTelemetryCompany`), using an explicit live root DB handle after outer transaction commit, skipping pending native retries (`retryable_failure`), and emitting no duplicates on replay or rollback. **Steps to reproduce** 1. Trigger any of the paths above in embedded Postgres (as exercised in `server/src/__tests__/missing-server-telemetry-emissions.test.ts`). 2. Observe that the database state transitions as expected, while the corresponding telemetry event is missing, dropped on a finished transaction, prematurely emitted on a retryable native failure, or blocking finalization while pending. **Paperclip version or commit** Merged cleanly with `master` at `054b4e1395b7f246e2c18d222b701595daf5522b` (PR head `b4e70c295b78de4bdcec1788e342c421cce1e138`). ## What Changed - `server/src/services/agent-task-run-telemetry.ts` & `server/src/services/run-failure-report.ts`: keep `isRunFailureStatus`, `isPendingNativeRetry`, and `isNewTerminalRunFailure` as pure leaf helpers in `agent-task-run-telemetry.ts` (re-exported by `run-failure-report.ts`) and colocate `emitTerminalRunFailure(db, run, options)` in `run-failure-report.ts` so `agent-task-run-telemetry.ts` never imports `run-failure-report.ts` (avoiding a circular dependency into `status-decision-committer.ts` that broke `vi.mock("../agent-task-run-telemetry.js")` in `native-task-completed-telemetry.test.ts`). Tighten `isNewTerminalRunFailure` so writes into `failed/retryable_failure` return `false` while writes leaving `retryable_failure` into a terminal failure return `true`, guard `emitAgentTaskRun` against `isPendingNativeRetry`, and select `nativePhase` in `emitAgentTaskRunById`. - `server/src/routes/issues.ts`, `server/src/services/execution-recovery-resolution.ts`, and `server/src/services/native-runtime/native-failed-run-owner-release.ts`: require an explicit root `telemetryDb: Db` whenever `controllerContainment` is set (discriminated union type plus runtime guard, removing the `input.telemetryDb ?? input.db` and `release.telemetryDb ?? db` fallbacks) so `afterTransactionCommit` always runs `emitTerminalRunFailure` against the root pool instead of a finished outer transaction, gated on `isNewTerminalRunFailure(run, settledRun)`. - `server/src/services/native-runtime/native-run-finalizer.ts` and `server/src/services/native-runtime/native-run-projection.ts`: emit non-blocking `void emitAgentTaskRun(...)` + `void reportRunFailure(...)` on the `isNewTerminalRunFailure` branch when a native run transitions from `failed/retryable_failure` to `failed/committed`, ensuring telemetry DB lookups never block finalization, projection, review responses, or chat settlement. - `server/src/services/native-runtime/native-superseded-retry.ts`, `server/src/services/native-runtime/native-finalization-reconciler.ts`, and `server/src/services/native-runtime/native-restart-recovery.ts`: return the retired `heartbeatRuns` row from `retireSupersededNativeRetry` so both `claimNativeSessionResumptions` and `claimNativeRestartRecoveries` emit `agent.task_run` and `reportRunFailure` once after commit when retiring a superseded `retryable_failure` run to `terminal_failure`. - `server/src/services/native-runtime/native-session-executor.ts`: select `runtimeMode` and `nativePhase` before the failure write, gate on `isNewTerminalRunFailure(runBeforeWrite, updatedRun)`, and emit via `emitTerminalRunFailure(input.db, terminalRunToReport, { failureReport: { nativeCloseFailure: error } })`. - `server/src/services/native-runtime/native-restart-recovery.ts`: return `updatedRun` from `endNamespaceUnverifiedRun` and call `emitTerminalRunFailure` after commit in both `claimNativeRestartRecoveries` and `boundAwaitingEvidence` (making `boundAwaitingEvidence` consistent with inline unverified-run termination for both telemetry and Sentry failure reporting). - `server/src/services/execution-control-reconciliation.ts`: gate terminal failure detection on `isNewTerminalRunFailure(run, updatedRun)` and emit via `emitTerminalRunFailure(db, terminalRunToReport)`. - `server/src/modules/active-run-watchdog/adapters/postgres.ts`: use `settledHeartbeat(now)` instead of `new Date()` when folding a silent run so a never-heartbeated agent keeps `lastHeartbeatAt = null` until its first real heartbeat. - `server/src/services/issue-thread-interactions.ts`: call `void emitAgentTaskCompleted(committedDb, completedTask)` in the post-commit `publish` hook when an agent reviewer accepts a `native_completion_review` confirmation card and closes the task to `done`. - `server/src/services/onboarding-seed.ts`: emit `trackAgentCreated` (after hire commit) and `trackGoalCreated` (via `afterTransactionCommit`) with `withTelemetryActor` when onboarding seed creates a new first agent or mission goal. - `server/src/services/routine-suggestions.ts`: emit `trackRoutineCreated` with `withTelemetryActor` after both the routine and its trigger are created. - `server/src/services/routine-standing-checks.ts`: emit `trackRoutineRun` (`source: STANDING_CHECK_TRIGGER_KIND` = `"heartbeat"`, `status: "completed"`) with `withTelemetryCompany` after committing a standing-check report. Emitting the raw value follows `packages/shared/src/telemetry/README.md`; the receiving layer and `posthog-direct/enum-fallbacks.generated.ts` normalize unknown `routine.run.source` values to `"other"` until `"heartbeat"` is promoted in the telemetry schema. - `packages/shared/src/telemetry/README.md` & `tests/runner-e2e/source-sdk-public-inputs.json`: document the restored `agent.task_run` and `agent.task_completed` emission paths per `rules/data-paths.mdc`. - `server/src/__tests__/missing-server-telemetry-emissions.test.ts`: add embedded-Postgres TDD regression tests covering every restored path, including `isNewTerminalRunFailure`, the real board containment route (`POST /api/issues/:id/recovery-actions/resolve`) for both `running` and `retryable_failure` runs, `native-session-executor` retryable vs terminal settlement, `native-restart-recovery` inline and `boundAwaitingEvidence` termination, non-blocking `finalizeNativeRun` / `projectCommittedRun` while `emitAgentTaskRun` is pending, superseded-retry retirement telemetry in both `claimNativeRestartRecoveries` and `claimNativeSessionResumptions`, and strict `telemetryDb` enforcement on `validateExecutionReconciliation`. ## Telemetry Contract Exception (`rules/data-paths.mdc`) - **Unchanged generated contract exception:** `packages/shared/src/telemetry/generated/paperclip-telemetry.ts` has no diff in this PR because all six emitted events (`agent.task_run`, `agent.task_completed`, `agent.created`, `goal.created`, `routine.created`, `routine.run`) and all of their dimensions, types, and optionality already exist unchanged in the generated contract. No new event names, dimensions, or enum values were added to the telemetry contract. - **Documentation & privacy review preserved:** `packages/shared/src/telemetry/README.md` is updated in this PR to document the restored emission paths, and privacy review remains requested per `rules/data-paths.mdc` because this PR adds callers to existing helpers in `packages/shared/src/telemetry/events.ts`. ## Verification - **RED (initial review-finding regression proof before fix on `9f10d34af2`):** `pnpm --filter @paperclipai/server exec vitest run src/__tests__/missing-server-telemetry-emissions.test.ts -t "classifies pending native retries|board containment route|retryable native session failures"` — **3/3 failed**. - **RED (targeted P1/CI/review fix pass before `b4e70c295b`):** - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-task-completed-telemetry.test.ts` — **3/3 failed** (reproducing CI shard 16 failure caused by the `agent-task-run-telemetry.ts -> run-failure-report.ts` circular import into `status-decision-committer.ts`). - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/missing-server-telemetry-emissions.test.ts -t "without awaiting emitAgentTaskRun|retiring a superseded native retry|requires an explicit root telemetryDb"` — **3/3 failed** (reproducing blocking `await emitAgentTaskRun`, missing `agent.task_run` on superseded retry retirement, and silent `telemetryDb` fallback to `input.db`). - **GREEN (on final head `b4e70c295b78de4bdcec1788e342c421cce1e138`):** - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/missing-server-telemetry-emissions.test.ts` — **1/1 file, 12/12 tests passed**. - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-task-completed-telemetry.test.ts src/__tests__/heartbeat-status-preserving-telemetry.test.ts src/__tests__/agent-task-run-telemetry.test.ts` — **3/3 files, 59/59 tests passed** (3 + 1 + 55). - **Test budget:** `node scripts/check-test-budget.mjs --files server/src/__tests__/missing-server-telemetry-emissions.test.ts` — **PASS** (113 nightly suites validated, 1 test file checked). - **Verify scope & local gap:** Local `tsc --noEmit` was skipped to avoid exceeding the container's shared 9.7 GiB cgroup memory limit; GitHub PR CI supplied full typecheck, build, serialized server suites (`ci / verify`), and E2E (`ci / e2e`) verification for head `b4e70c295b78de4bdcec1788e342c421cce1e138`. - **GitHub CI on `b4e70c295b78de4bdcec1788e342c421cce1e138`:** - `ci / verify` — **PASS** (https://github.com/paperclipai/paperclip/actions/runs/47455114528/job/145468380453; includes Typecheck + Release Registry, Build, policy, Runner support/package/native server suites, and all 20 server test shards). - `ci / e2e` — **PASS** (https://github.com/paperclipai/paperclip/actions/runs/47455114528/job/145468199932; all 16 E2E shards). - All 87 status checks completed with zero failures and zero pending checks. - **Automated reviews on `b4e70c295b78de4bdcec1788e342c421cce1e138`:** Greptile **5/5** (`SUCCESS`, unchanged-contract exception recorded), Ponytail **5/5** (`Verdict: ship`), Feynman **4/5** (zero functional defects; structural rationale recorded below and in threads, 17/17 review threads resolved). - **Structural decisions (`rules/pull-request-review.mdc` & `rules/test-budget.mdc`):** - `server/src/services/native-runtime/native-finalization-reconciler.ts` grew from 1,000 lines on `master` to 1,006 lines (+6 net lines) to keep the `retiredSupersededRun` capture, error-clear, and post-commit `void emitTerminalRunFailure` call locally visible inside `claimNativeSessionResumptions` rather than bundling an unrelated reconciler refactor into this telemetry fix. - `server/src/__tests__/missing-server-telemetry-emissions.test.ts` (1,447 lines) keeps all 12 embedded-Postgres telemetry regressions in one shared `beforeAll` suite (grouped by domain `describe` blocks) to avoid multiplying disposable Postgres startup cost across CI shards per `rules/test-budget.mdc`. ## Risks - Low risk. No telemetry schemas, event names, or dimension contracts changed; all new emissions run after transaction commit as best-effort/fire-and-forget and catch errors so telemetry can never block or fail product flows. - `native-restart-recovery.ts`'s `boundAwaitingEvidence` and `retireSupersededNativeRetry` callers now invoke terminal failure telemetry/reporting after commit, matching inline unverified-run termination. - Deployments will see more accurate counts for failed `agent.task_run`, agent-reviewed `agent.task_completed`, `agent.created` / `goal.created` during onboarding, and `routine.created` / `routine.run`, which is the intended fix. - Requesting privacy review per `rules/data-paths.mdc` because this PR adds callers to existing helpers in `packages/shared/src/telemetry/events.ts`. ## Model Used - Google Antigravity (Gemini 4 Neon, High reasoning, 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups (explicit unchanged-contract exception recorded per `rules/data-paths.mdc`) - [x] I will address all Greptile and reviewer comments before requesting merge |
||
|
|
1a20fb1953 |
fix(server): avoid ServerResponse MaxListenersExceededWarning in stream pipelines (#23810)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The Express server streams HTTP responses through Node's
`stream.pipeline(..., res)` on proxy, avatar, file download, MCP
transfer, and retained UI asset routes
> - Node's `stream.pipeline` attaches 7 internal `close` listeners (and
4 `finish` listeners) to `ServerResponse`
> - Global request middleware (`idleAdmissionMiddleware`, `pino-http`,
`postHogRequestContextMiddleware`, `authorizationReadScope`) and route
cleanup handlers already attach 3 to 5 `close` listeners to `res` before
streaming begins, pushing every request over the default `MaxListeners`
cap of 10
> - Each excess listener emits `MaxListenersExceededWarning`, which
captures a synchronous V8 stack trace and writes to stderr on every
streamed request
> - This pull request collapses the 3 redundant `close` listeners in
`posthog-proxy` into one cleanup listener and routes all
`ServerResponse` stream pipelines through a narrow `pipelineToResponse`
helper that reserves only pipeline's internal listener headroom once per
response
> - The benefit is zero false `MaxListenersExceededWarning` stack traces
on streamed HTTP responses while preserving real listener-leak detection
## Linked Issues or Issue Description
**What happened?**
Streamed HTTP routes that call `stream.pipeline(source, res)` emit
`MaxListenersExceededWarning: Possible EventEmitter memory leak
detected. 11 close listeners added to [ServerResponse]. MaxListeners is
10.` on every request. Each warning runs a synchronous
`Error.captureStackTrace` and writes to stderr. On a hosted server this
occurred 14 to 17 times per minute.
Root cause:
- `stream.pipeline(readable, res)` attaches 7 internal `close` listeners
(`destroyer`, two `eos` pairs of `onlegacyfinish` + `onclose`, `pipe`,
and `Readable.pipe`) and 4 internal `finish` listeners to
`ServerResponse`.
- Any route with 4 or more `close` listeners already registered on `res`
exceeds the default limit of 10:
- `server/src/routes/posthog-proxy.ts`: `idleAdmissionMiddleware` (1) +
3 separate route `close` listeners + `pipeline` (7) = 11.
- `server/src/services/cloud-trial-proxy.ts`: 3 global middleware +
`onClientClose` (1) + `pipeline` (7) = 11.
- `server/src/routes/agent-avatars.ts`: 4 global middleware + `pipeline`
(7) = 11.
- `server/src/routes/agents.ts`: 4 global middleware + `pipeline` (7) =
11.
- `server/src/routes/file-resources.ts`: 4 global middleware +
`abortIfResponseIncomplete` (1) + `pipeline` (7) = 12.
- `server/src/retained-ui-assets.ts`: 4 global middleware + `cancel` (1)
+ `pipeline` (7) = 12.
- `server/src/services/public-mcp/file-transfers.ts`: 3 global
middleware + `pipeline` (7) = 10 (at the limit).
**Expected behavior**
Streamed HTTP responses complete with 0 `MaxListenersExceededWarning`
events under the real middleware chain, while genuine listener leaks
(such as adding listeners in a loop) still trigger
`MaxListenersExceededWarning`.
**Steps to reproduce**
1. Mount `idleAdmissionMiddleware`, `posthogProxyRoutes`,
`createHttpLogger`, `postHogRequestContextMiddleware`,
`authorizationReadScope`, `agentAvatarRoutes`, and `retainedUiAssets` on
an Express app in `app.ts` order.
2. Attach a `process.on("warning", ...)` listener.
3. Send one request each to `POST /_ph/e/`, `GET
/api/agent-avatars/cap-v1/arctic-blue/rest.png`, and `GET
/assets/chunk-test.js`.
4. Observe 3 `MaxListenersExceededWarning` warnings (one per streamed
response).
**Paperclip version or commit**
Reproduced at `306437a2a5` on `master`; fixed on top of `83f10b968d`.
**Deployment mode**
Self-hosted server and hosted server deployments.
**Node.js version**
Reproduced on Node v24 and v26.4.0.
**Relevant logs or output**
```text
(node:2376) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 close listeners added to [ServerResponse]. MaxListeners is 10. Use emitter.setMaxListeners() to increase limit
```
## What Changed
- Added `pipelineToResponse` in `server/src/http/response-pipeline.ts`:
- Shared HTTP-layer primitive owned by `server/src/http/` so routes,
services, and `retained-ui-assets.ts` do not duplicate `EventEmitter`
listener-budget logic or cross module boundaries.
- Reserves at most `stream.pipeline`'s internal `close` (8) and `finish`
(5) headroom once per `ServerResponse` (tracked via
`WeakSet<ServerResponse>`), capped at `currentMax + 8` and never setting
`0` (unlimited) or overwriting an explicit `0`.
- Delegates directly to `node:stream/promises` `pipeline`, preserving
backpressure, error propagation, `AbortSignal` cancellation, and
response headers/status codes.
- Collapsed the 3 separate `res.once("close")` / `res.on("close")`
listeners in `server/src/routes/posthog-proxy.ts` (in-flight slot
decrement, deadline `clearTimeout`, and upstream abort) into one
`res.once("close")` cleanup listener and routed response streaming
through `pipelineToResponse`.
- Updated all 6 remaining `pipeline(..., res)` call sites to use
`pipelineToResponse`:
- `server/src/services/cloud-trial-proxy.ts`
- `server/src/routes/agent-avatars.ts`
- `server/src/routes/agents.ts`
- `server/src/routes/file-resources.ts`
- `server/src/retained-ui-assets.ts`
- `server/src/services/public-mcp/file-transfers.ts`
- Added unit and middleware-chain regression tests in
`server/src/http/response-pipeline.test.ts`,
`server/src/__tests__/cloud-posthog-browser.test.ts`,
`server/src/__tests__/agent-avatars.test.ts`, and
`server/src/__tests__/retained-ui-assets.test.ts`.
## Verification
Before fix (Node v26.4.0, real Express middleware chain for
`posthog-proxy`, `agent-avatars`, `retained-ui-assets`):
```text
Statuses: 200 200 200
Warnings count: 3
{"route":"posthog-proxy","name":"MaxListenersExceededWarning","message":"Possible EventEmitter memory leak detected. 11 close listeners added to [ServerResponse]. MaxListeners is 10. Use emitter.setMaxListeners() to increase limit"}
{"route":"agent-avatars","name":"MaxListenersExceededWarning","message":"Possible EventEmitter memory leak detected. 11 close listeners added to [ServerResponse]. MaxListeners is 10. Use emitter.setMaxListeners() to increase limit"}
{"route":"retained-ui-assets","name":"MaxListenersExceededWarning","message":"Possible EventEmitter memory leak detected. 11 close listeners added to [ServerResponse]. MaxListeners is 10. Use emitter.setMaxListeners() to increase limit"}
```
After fix (same 3 routes + a 15-listener leak probe):
```text
Statuses: 200 200 200 200
Warnings count: 1
{"route":"genuine-leak","name":"MaxListenersExceededWarning","message":"Possible EventEmitter memory leak detected. 13 close listeners added to [ServerResponse]. MaxListeners is 12. Use emitter.setMaxListeners() to increase limit"}
```
Local checks run on rebased revision
`e265a0a2207244f79eeddadf7a5b2958a8c59888`:
- `pnpm check:module-boundaries` — PASS
- `node scripts/check-test-budget.mjs --base origin/master` — PASS (113
nightly suites validated, 4 test files checked)
- `pnpm --filter @paperclipai/server exec vitest run
src/http/response-pipeline.test.ts
src/__tests__/cloud-posthog-browser.test.ts
src/__tests__/agent-avatars.test.ts
src/__tests__/retained-ui-assets.test.ts` — 4 files, 116 tests passed
- `pnpm --filter @paperclipai/server typecheck` — PASS
- Pre-rebase also ran the 5 additional DB-backed affected route suites
(`cloud-trial-inference.test.ts`,
`cloud-trial-proxy-middleware-order.test.ts`, `file-resources.test.ts`,
`agent-instructions-routes.test.ts`, `public-mcp.test.ts`) — 5 files,
172 tests passed; CI will run the full required matrix on this revision.
## Risks
- Low risk. `pipelineToResponse` only adjusts `maxListeners` narrowly
once per `ServerResponse` by the internal headroom `stream.pipeline`
requires (at most `currentMax + 8`), never disables the cap (`0`), and
forwards directly to `node:stream/promises` `pipeline`.
- In `posthog-proxy.ts`, replacing callback `pipeline(upstreamRes, res,
cb)` with `void pipelineToResponse(upstreamRes, res).catch(...)`
preserves identical error destruction and debug logging; the
consolidated `res.once("close")` listener executes the same deadline
cleanup, in-flight accounting, and upstream abort logic.
> 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
- Gemini 4 Neon (Google DeepMind, XHigh reasoning, 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
- [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
|
||
|
|
b85e189408 |
perf(runner,native-runtime): silence AJV format warnings, cache validators, and retain released catalogs (#23812)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The server and Runner validate assigned MCP tool input schemas with AJV and project shared frozen tool catalogs into native sessions > - Today, AJV runs with `validateFormats: true` and no registered formats, so every tool schema with `format` keywords (such as `uuid` or `date-time`) emits two synchronous `console.warn` lines per property while still ignoring those formats > - Each call to `admitToolInputSchema` also recompiles identical schemas from scratch, `resolveAssignedCatalog` evicts a shared catalog as soon as its last active session closes (so back-to-back runs rebuild the catalog every time), and `createAssignedMcpTools` logs the over-budget and uncompilable schema warnings on every run even on a cache hit > - Together these issues produce heavy synchronous stderr/log churn and repeat CPU and allocation work on sequential runs > - This pull request disables AJV format lookup in `tool-input-schema.ts`, adds a bounded compiled-validator LRU cache with isolated error state, retains explicitly closed assigned catalogs in a bounded short-TTL warm LRU, and deduplicates catalog schema warnings per `(gatewayPublicId, catalogKey)` > - The benefit is zero `unknown format` stderr warnings, up to ~27x faster repeat schema admission, sequential catalog cache reuse across back-to-back runs, and one warning per distinct gateway and catalog instead of per-run log floods ## Linked Issues or Issue Description Refs #21274, #21482. No separate public GitHub issue exists; the bug is described below using the bug report template. **What happened?** During native agent runs that use assigned MCP tools with JSON Schema `format` annotations (such as `"format": "uuid"` and `"format": "date-time"`) or tool catalogs over the 768 KiB compile budget: 1. `admitToolInputSchema` in `packages/paperclip-runner/src/drivers/tool-input-schema.ts` creates `Ajv`, `Ajv2019`, and `Ajv2020` with `{ allErrors: true, strict: false, addUsedSchema: false }`, leaving `validateFormats` at its default (`true`) without registering any formats. AJV still ignores unknown formats because `strict: false`, but writes two synchronous `unknown format "..." ignored in schema at path "..."` `console.warn` lines per property on every compilation. 2. Repeated calls to `admitToolInputSchema` for identical schemas re-run AJV compilation (`new Function`) each time. 3. `resolveAssignedCatalog` in `server/src/services/native-runtime/assigned-mcp-tools.ts` evicts the shared catalog immediately when `holder.holders === 0`, so sequential runs for the same company and unchanged tool listing never reuse the frozen catalog. 4. `createAssignedMcpTools` logs `assigned MCP tools whose input schema is over the compile budget are offered only through assigned-tool search` and `assigned MCP tools whose input schema the Runner cannot validate are not offered` unconditionally on every call, including cache hits. **Expected behavior** 1. `admitToolInputSchema` preserves exact validation behavior (ignoring unregistered format annotations while still rejecting invalid non-string `format` values via meta-schema validation) with zero `unknown format` warnings. 2. Identical schemas reuse cached compiled validators in a bounded LRU without sharing mutable `.errors` state or allowing mutation of the cached schema. 3. Explicitly closed assigned tool catalogs stay warm in a bounded short-TTL LRU so sequential runs reuse the frozen catalog when the fresh gateway listing is unchanged, while expired or changed catalogs rebuild cleanly and idle processes hold no background polling timers. 4. Catalog schema warnings log once per distinct `(gatewayPublicId, catalogKey)` within a bounded deduplication window instead of flooding logs on every run. **Steps to reproduce** 1. Call `admitToolInputSchema` on 50 schemas containing `format: "uuid"`, `format: "date-time"`, and `format: "email"` across 20 iterations (1,000 admissions) and count `console.warn` lines matching `unknown format`. 2. Call `createAssignedMcpTools` 20 times sequentially (`close()` after each call) for the same `companyId` and `gatewayPublicId` with an unchanged listing over the 768 KiB compile budget and with an under-budget listing, counting `logger.warn` lines and schema object reuse across runs. **Paperclip version or commit** Reproduced on `master` at `306437a2a5`. **Deployment mode** Self-hosted server / Local dev (`pnpm dev`). ## What Changed - `packages/paperclip-runner/src/drivers/tool-input-schema.ts`: - Pass `validateFormats: false` to `Ajv`, `Ajv2019`, and `Ajv2020` compilers. - Add a bounded compiled-validator LRU cache (`TOOL_INPUT_SCHEMA_CACHE_MAX_ENTRIES = 512`, `TOOL_INPUT_SCHEMA_CACHE_MAX_BYTES = 16 MiB` serialized schema bytes) keyed by canonical dialect and SHA-256 of the normalized schema JSON, including caching `uncompilable` outcomes and skipping `$async` schemas. - Deep-freeze cached compiled schemas after `forgetCompiledSchema` and wrap cached `ValidateFunction` instances in `isolatedValidator` so each caller has independent `.errors` state and cached validators retain no prior error arrays. - Export `toolInputSchemaCacheStats`, `TOOL_INPUT_SCHEMA_CACHE_MAX_ENTRIES`, and `TOOL_INPUT_SCHEMA_CACHE_MAX_BYTES` for verification. - `packages/paperclip-runner/src/drivers/tool-input-schema.test.ts`: - Add tests covering zero `unknown format` warnings across all three dialects while preserving validation and rejecting invalid non-string `format` values. - Add tests covering validator cache reuse (including `$schema` fragment normalization, `uncompilable` caching, and uncached `$async` schemas), isolated `.errors` state, frozen `validate.schema`, independent `admission.schema`, and cache bounds. - Give each `reserved $id` iteration a unique `title` so every iteration still compiles fresh on the compiler. - `server/src/services/native-runtime/assigned-mcp-tools.ts`: - Retain explicitly closed shared catalogs in a bounded warm LRU (`ASSIGNED_CATALOG_RETAIN_ENTRIES = 64`, `ASSIGNED_CATALOG_RETAIN_BYTES = 32 MiB`, `ASSIGNED_CATALOG_RETAIN_TTL_MS = 60_000`) promoted back to active `sharedCatalogs` on sequential hits and invalidated automatically whenever the fresh gateway listing changes `identity`. - Unregister the `collectedCatalogs` `FinalizationRegistry` token (`catalog`) in `forgetSharedCatalog` and before re-registering in `shareAssignedCatalog` so repeated sequential warm reuses never accumulate live registrations. - Keep `FinalizationRegistry` GC drop callbacks (`drop` from `createSessionRelease`) in a separate lexical scope with no reference to `assigned` or `catalog`, releasing holds without retaining abandoned sessions. - Manage warm TTL expiry with lazy pruning on lookup/insert plus one per-entry `.unref()` `setTimeout` cleared in `forgetRetainedCatalog` on hit, eviction, or expiry. Keep `assignedRetainedCatalogCacheStats()` read-only. - Deduplicate `unavailable` and `unchecked` `logger.warn` emissions per `(gatewayPublicId, catalogKey)` in a bounded LRU (`ASSIGNED_CATALOG_WARNING_CACHE_ENTRIES = 512`, `ASSIGNED_CATALOG_WARNING_DEDUP_MS = 10 * 60_000`). - `server/src/services/native-runtime/assigned-mcp-tools.test.ts` and `server/src/services/native-runtime/assigned-mcp-tools-cache.test.ts`: - Split `describe("shared assigned tool catalogs")` into `assigned-mcp-tools-cache.test.ts` (353 lines), reducing `assigned-mcp-tools.test.ts` from 980 to 808 lines. - Add fake-timer tests verifying timer-driven and lazy warm catalog TTL expiration, invalidation on listing changes, bounded `FinalizationRegistry` registrations across 50 sequential warm reuses, and per-`(gatewayPublicId, catalogKey)` warning deduplication and window expiry. ## Verification ### Local Before vs After Benchmark Measured in the worktree against `306437a2a5` (before) and `2b3757ad58` (after): | Workload | Metric | Before | After | | --- | --- | ---: | ---: | | `admitToolInputSchema` (50 schemas w/ 4 format fields × 20 calls) | `unknown format` warnings (cold 50 / total 1,000) | 400 / 8,000 | **0 / 0** | | `admitToolInputSchema` (950 repeat admissions) | Total wall time | 144.44 ms | **5.28 ms** (27.4× faster) | | `createAssignedMcpTools` over-budget (120 tools × ~6.7 KiB, 20 sequential runs) | `unknown format` warnings | 672 | **0** | | `createAssignedMcpTools` over-budget (20 sequential runs) | Compile-budget `logger.warn` count | 20 | **1** | | `createAssignedMcpTools` over-budget (runs 2–20) | Median / total time | 1.35 ms / 29.07 ms | **1.18 ms / 23.52 ms** | | `createAssignedMcpTools` under-budget (50 tools × ~1 KiB, 20 sequential runs) | Sequential catalog cache hits | 0 / 19 | **19 / 19** | | `createAssignedMcpTools` under-budget (runs 2–20) | Median / total time | 0.34 ms / 6.81 ms | **0.29 ms / 5.66 ms** | Memory benchmark (`NODE_OPTIONS="--expose-gc" npx tsx scripts/benchmark-assigned-mcp-tools-memory.ts --tools 80 --schema-bytes 2048 --sessions 50 --turns 10`): - `sharedAcrossTurns: true`, `retainedBytesPerSession: 10052`, `bytesStillHeldAfterRelease: 321248` (unclosed sessions released on GC without entering warm retention). ### Automated Tests & Checks (on head `687fe283be`) - `pnpm --filter @paperclipai/paperclip-runner exec vitest run src/drivers/tool-input-schema.test.ts src/drivers/runner-tool-bridge.schemas.test.ts`: 2 files, 26 passed. - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/assigned-mcp-tools.test.ts src/services/native-runtime/assigned-mcp-tools-cache.test.ts`: 2 files, 80 passed. - `pnpm --filter @paperclipai/paperclip-runner run typecheck:typescript`: passed. - `pnpm --filter @paperclipai/server exec tsc --noEmit`: passed. - `pnpm check:module-boundaries`: passed. - `node scripts/check-test-budget.mjs --base origin/master`: passed (`2 test file(s) checked`). - `node tests/runner-e2e/source-sdk-public-inputs.mjs "$(git rev-parse HEAD)" --check`: passed (`changed: false`). ### Operational Assumptions & Sleep Safety - **Format validation parity:** `tool-input-schema.ts` never registered `ajv-formats` and ran with `strict: false`, so format keywords were never enforced before this change. Verified with real `Ajv`, `Ajv2019`, and `Ajv2020` instances across all shared fixtures plus explicit format tests. - **Warm retention lifecycle (`sleep-aware-background-work`):** Trigger is explicit `assigned.close()` releasing the last active holder (`holders === 0`). Source of truth for tool grants remains the fresh gateway listing on every `createAssignedMcpTools` call. Pending-work predicate is `retainedCatalogs.size > 0`, with one `.unref()` `setTimeout` per retained entry (at most 64 entries, 60s TTL), cleared immediately in `forgetRetainedCatalog` on hit, eviction, or expiry. When all retained entries expire or are promoted back to active, zero timers, SQL queries, or network requests remain. - **Remaining coverage:** Full repository test suites and build gates run in CI on this revision. ## Risks - **Frozen `validate.schema` in `tool-input-schema.ts`:** Cached compiled schemas are deep-frozen before reuse so callers cannot corrupt shared cache entries. All in-repo consumers (`admitToolInput`, `toolInputError`, `RepeatedToolInputRejectionGuard`) only read `validate.schema`, and `admission.schema` remains a fresh unfrozen clone. Any future consumer attempting to mutate `validate.schema` will get a `TypeError` instead of silent cross-caller corruption. - **Validator cache byte accounting:** `TOOL_INPUT_SCHEMA_CACHE_MAX_BYTES` (16 MiB) accounts for serialized schema JSON bytes rather than V8 compiled closure heap, and is paired with a 512-entry cap so total validator memory stays bounded. - **Warm catalog memory bound:** Released catalogs are held strongly for up to 60 seconds, capped strictly at 64 entries and 32 MiB accounted bytes, and cleared by per-entry `.unref()` expiry timers. Abandoned sessions dropped without `close()` are never retained, and `collectedCatalogs` unregisters tokens on release and re-share. - **Warning deduplication window:** Repeated warnings for an unchanged `(gatewayPublicId, catalogKey)` are suppressed for 10 minutes (bounded at 512 entries). Changes to the tool listing or gateway ID log immediately, and unchanged warnings re-log after the 10-minute window. - **No database schema changes or migrations.** > 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 - Gemini 4 Neon (Google DeepMind, XHigh reasoning, 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 - [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 |
||
|
|
858f021658 |
fix(server): add exponential backoff to MCP cloud sync workers (#23821)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Public MCP cloud sync runs two delivery workers: `mcp-client-mirror` and `mcp-revocation-index` > - Both workers retry every 5 seconds indefinitely when the Cloud connector broker returns HTTP 404/501 or fails repeatedly, and `delivery-work-coordinator` caps error retries at fixed `task.retryMs` > - Each failed tick executes PostgreSQL locks and queries, local secret derivation, Ed25519 request signing, and an HTTPS request while logging full error stacks roughly 20 times per minute > - In `client-mirror-sync`, a failed `begin` also sets `reserveFullRevision = true`, causing extra revision bumps and self-notifications that immediately re-trigger failed runs > - This pull request adds an opt-in `retryAtOnError` hook to `delivery-work-coordinator`, adds bounded exponential backoff to both MCP cloud sync workers, prevents self-wakes from bypassing backoff, and avoids unnecessary `reserveFullRevision` churn on unsupported HTTP 404/501 `begin` rejections > - The benefit is a >94% reduction in repeated failure load during broker outages or unsupported endpoint responses while preserving immediate recovery on broker return and all sleep-safety and revocation invariants ## Linked Issues or Issue Description No matching public GitHub issue or duplicate pull request exists. **What happened?** When the Cloud connector broker returns HTTP 404 (`UNKNOWN_BROKER_ERROR`), HTTP 501, or repeated transient errors, `mcp-client-mirror` (`server/src/services/public-mcp/client-mirror-sync.ts`) and `mcp-revocation-index` (`server/src/services/public-mcp/revocation-index-sync.ts`) retry every 5 seconds without backoff. Both workers log `Delivery reconciliation failed` continuously and repeat PostgreSQL advisory locks, queries, local key derivation, and signed HTTP requests. In `client-mirror-sync`, a failed tick also triggers `prepareMcpClientMutation`, which bumps `mcp_oauth_client_mirror_state.revision` and self-notifies `mcpClientMirror`, immediately re-running the worker and bypassing retry delays. **Expected behavior** Both MCP cloud sync workers must apply bounded exponential backoff on consecutive failures, ramp faster on HTTP 404/501 unsupported broker endpoints, avoid unnecessary revision bumps on unsupported `begin` rejections, ignore self-wakes while backed off, recover cleanly and reset backoff when the broker succeeds, and stay quiet once synchronized. **Steps to reproduce** 1. Configure a managed Paperclip instance with `startMcpClientMirrorSync` and `startMcpRevocationIndexSync` registered on `createDeliveryWorkCoordinator`. 2. Make the Cloud connector broker return HTTP 404 (`PaperclipCloudConnectorError` with status `404` and reason `UNKNOWN_BROKER_ERROR`) or HTTP 503 for 10 minutes. 3. Observe ~121-122 failed ticks per worker in 10 minutes (every 5 seconds, plus immediate self-wake ticks in `client-mirror-sync`) and repeated `Delivery reconciliation failed` errors. **Paperclip version or commit** Reproduced on `master` (`306437a2a5` / rebased on latest `origin/master`). **Deployment mode** Other (managed Cloud connector runtime; reproduced deterministically with unit tests and fake timers). ## What Changed - **`server/src/services/delivery-work-coordinator.ts`** (shared contract update): - Keep `scheduledAt` unmodified if `scheduler.schedule` throws on a non-finite deadline. - Add an opt-in `retryAtOnError?: () => number | null` callback on registered tasks. When `task.run` fails (`runFailed === true`), `input.canRun()` is true, and `task.retryAtOnError()` returns a finite deadline, schedule `Math.max(Date.now(), backoffAt)` directly instead of capping the retry at `task.retryMs`. - Keep `nextRunAtOnError` and all existing consumers (`scoped-deadline-work.ts`, `receiver-work.ts`, `createScheduledBoardPostsWorker`, `createClaimLeaseExpiryWorker`, and all workers without `retryAtOnError`) unchanged on the `task.retryMs` fallback. - Fall back to `task.retryMs` whenever `retryAtOnError` is absent, returns `null`, throws, returns a non-finite value, `!input.canRun()`, `!runFailed`, or `databaseWorkPending(input.owner, queue)` is true. - **`server/src/services/public-mcp/client-mirror-sync.ts`**: - Add bounded exponential backoff on consecutive failures: - Transient errors: `5s -> 10s -> 20s -> 40s -> 80s -> 160s -> 300s` (5-minute cap). - HTTP 404/501 unsupported broker endpoints: `5s -> 20s -> 80s -> 320s -> 900s` (15-minute cap). - Respect finite broker `Retry-After` (`PaperclipCloudConnectorError.retryAt`) up to the active cap. - Register `retryAtOnError: () => retryAt` so the coordinator schedules the computed backoff deadline directly. - Guard `run()` at entry against active `retryAt` so self-notifications from `prepareMcpClientMutation` and mutation bursts during a broker outage do not bypass backoff or execute database/network work early; preserve explicit `worker.wake()` to clear `retryAt` for immediate manual/recovery wake. - Avoid setting `fullRecovery = true; reserveFullRevision = true` when `begin` itself fails with HTTP 404/501 before acceptance; for failures after `begin` or non-404/501 failures, reserve at most one full-recovery revision per failure episode until recovery succeeds. - Reset `consecutiveFailures = 0` and `retryAt = null` immediately upon successful synchronization, disable ACK, or unmanaged/unconfigured state. - **`server/src/services/public-mcp/revocation-index-sync.ts`**: - Add the same bounded exponential backoff (`5s` doubling to `5m` on transient errors, `5s` quadrupling to `15m` on HTTP 404/501, respecting broker `Retry-After`), `retryAtOnError: () => retryAt`, early backoff guard in `run()`, explicit `worker.wake()` bypass, and immediate backoff reset upon grant sync progress or empty/synchronized state. - **Background work lifecycle contract (`rules/sleep-aware-background-work.mdc`)**: - **Trigger**: Startup check plus transaction-aware `notifyDeliveryWork` settlements (`mcp-client-mirror`, `mcp-revocation-index`) and explicit `worker.wake()`. - **Durable source of truth**: `mcp_oauth_client_mirror_state` / `mcp_oauth_clients` / `mcp_oauth_client_changes` / `mcp_oauth_device_requests` for client mirror; `mcp_oauth_grants` and `mcp_oauth_tokens` for revocation index. - **Pending-work predicate**: Unacknowledged revision/deviceStatus/issuer mismatch in `mcp_oauth_client_mirror_state` (`idle-client-mirror.ts` continues to report `blocked: true` until acknowledged); unrevoked grants whose `revocation_index_receipt` revision or `keyId` differs from current `revocation_revision` / `keyId`. - **Next deadline/retry**: `null` when synchronized, disabled, or unmanaged; `Date.now() + 5_000` when a follow-up batch/revision is queued without error; bounded exponential `retryAt` on failure. - **Quiet condition**: Zero scheduled timers, zero SQL queries, and zero network requests once synchronized, unconfigured, or unmanaged; bounded retries only while an unacknowledged obligation remains failed. - **Tests**: - Added `server/src/services/public-mcp/client-mirror-sync.test.ts` (fake timers, real `createDeliveryWorkCoordinator` + `installDatabaseWorkSignals`, covering HTTP 404, HTTP 501, HTTP 503, HTTP 429 `Retry-After`, `reserveFullRevision` churn, self-wake suppression, `readIdleMcpClientMirror` sleep-safety invariants, drain pause/resume, explicit `worker.wake()`, and quiet post-recovery state). - Extended `server/src/services/public-mcp/revocation-index-sync.test.ts` with fake-timer backoff, 404/503/429 coverage, mutation-during-backoff quietness, explicit `worker.wake()`, and post-recovery reset/quietness. - Extended `server/src/__tests__/work-scheduler.test.ts` for coordinator `retryAtOnError` backoff deadlines, `retryMs` fallbacks (`null`, `NaN`, and pending database work), and regression coverage confirming `nextRunAtOnError` remains capped at `retryMs`. ## Verification Tested on commit `c53a4a0bdf2ca3723f6a446e85f54bf2255a3223`: - **Red/green before-vs-after (fake timers over 10 minutes / `600_000 ms`)**: - `mcp-client-mirror` under HTTP 404: **122 failed ticks** before fix (`0, 0, 1, 5001, ...`, with immediate self-wakes and extra revision bump) -> **5 failed ticks** after fix (`0, 5s, 25s, 105s, 425s`, next wake `1_325s`; **95.9% reduction**, zero extra `reserveFullRevision` bumps). - `mcp-revocation-index` under HTTP 404: **121 failed ticks** before fix (`0, 5s, 10s, ..., 600s`) -> **5 failed ticks** after fix (`0, 5s, 25s, 105s, 425s`, next wake `1_325s`; **95.9% reduction**). - Both workers under transient HTTP 503: **121 failed ticks** -> **7 failed ticks** (`0, 5s, 15s, 35s, 75s, 155s, 315s`, next wake `615s`; **94.2% reduction**). - After broker returns HTTP 200: both workers save receipts, reset backoff (`nextWakeAt() === null`), and execute 0 queries and 0 publishes across a subsequent 10-minute idle window. - Commands run (all passed): - `pnpm --filter @paperclipai/server exec vitest run src/services/public-mcp/revocation-index-sync.test.ts src/services/public-mcp/client-mirror-sync.test.ts src/services/public-mcp/client-mirror-ack.test.ts src/__tests__/work-scheduler.test.ts` (4 files, 16 tests passed; full 7-file public-mcp + work-scheduler suite: 33/33 passed) - `pnpm check:module-boundaries` (passed) - `node scripts/check-test-budget.mjs --files server/src/services/public-mcp/client-mirror-sync.test.ts server/src/services/public-mcp/revocation-index-sync.test.ts server/src/__tests__/work-scheduler.test.ts` (passed: 113 nightly suites validated, 3 test files checked) - `pnpm --filter @paperclipai/server typecheck` (all 7 layers passed) - Scope note: Verification uses deterministic fake-timer unit suites and local typecheck/boundary checks; this does not claim live deployed Cloud host suspension or external wake behavior. ## Risks - Low risk. During an active broker outage, new local client or grant mutations wait until the active backoff deadline (capped at 5 minutes for transient errors and 15 minutes for HTTP 404/501) rather than immediately retrying the failing broker, while preserving durable pending state and `idle-client-mirror` sleep blocks until acknowledged. - Existing `delivery-work-coordinator` consumers (including `nextRunAtOnError` callers) keep their exact `retryMs`-capped fallback behavior. Only workers opting into `retryAtOnError` schedule error retries beyond `retryMs`, with `null`, thrown errors, non-finite values, drain/standby states, and pending database transactions still falling back safely to `task.retryMs`. > 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 - Gemini 4 Neon (Google DeepMind, XHigh reasoning, 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 - [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> |
||
|
|
74e67231bd |
perf(github): fix inherited review wait join and batch lookup plan (#23817)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - When an agent publishes a GitHub pull request review, the Paperclip task waits in review for the next GitHub reply. Later runs on that task inherit this wait. > - Issue lists and inbox attention call `readInheritedGitHubReviewWaits` to check all waiting runs of a company in one batch (`readInheritedReviewsForKeys`). > - In `readInheritedReviewsForKeys`, the join between `chat_message_links` and `chat_conversations` matched only `conversation_id` and omitted `endpoint_id`, while filtering `comment_id`, `issue_id`, and `agent_id` through three separate `= ANY(...)` arrays and joining every historical `chat_github_reviews` row before `DISTINCT ON`. > - On PostgreSQL with many endpoints and message links, the missing leading `endpoint_id` column caused PostgreSQL to skip-scan `chat_message_links_provider_message_uq (endpoint_id, conversation_id, provider_message_id)` across all endpoints for every matched conversation, reading hundreds of buffers per conversation. Separate `= ANY(...)` arrays also allowed cross-key cartesian matching in SQL, and joining all historical reviews forced extra `heartbeat_runs` lookups and `assessment` JSONB detoasting before `DISTINCT ON` discarded older rows. > - This pull request binds `chat_message_links.endpoint_id = chat_conversations.endpoint_id` in both the single-key and batch queries, replaces the three `= ANY(...)` arrays with deduplicated `(comment_id, issue_id, agent_id)` tuples via `unnest(...)`, and selects only the latest `chat_github_reviews` row per `(endpoint_id, issue_id)` in a lateral subquery before joining `heartbeat_runs` and projecting `assessment->'reviewedCommit'`. > - The benefit is 25x-35x lower query execution time and 34x-50x fewer shared buffer hits on realistic multi-endpoint batches, with exact result equivalence and zero schema changes. ## Linked Issues or Issue Description Refs #20673 Refs #20851 **What happened?** `readInheritedReviewsForKeys` in `server/src/services/chat-channels/github/review-wait.ts` ran slow multi-second queries on hosted multi-tenant PostgreSQL instances when listing in-review issues. `EXPLAIN (ANALYZE, BUFFERS)` showed PostgreSQL skip-scanning `chat_message_links_provider_message_uq` on `conversation_id = chat_conversations.id` without the leading `endpoint_id` column, producing over 200 buffer hits per conversation. The query also used three independent `= ANY(...)` array predicates (allowing cross-key combinations in SQL) and joined all historical `chat_github_reviews` rows to `heartbeat_runs` before `DISTINCT ON` discarded older reviews. **Expected behavior** `readInheritedReviewsForKeys` should look up exact `(comment_id, issue_id, agent_id)` keys using leading-prefix index scans (`chat_message_links_company_comment_idx` or `(endpoint_id, conversation_id)` on `chat_message_links_provider_message_uq`), avoid cross-key matches in SQL, and join `heartbeat_runs` and project `assessment->'reviewedCommit'` only for the latest review per key. **Steps to reproduce** 1. Seed a PostgreSQL database with multiple chat endpoints (across GitHub and other channels), tens of thousands of `chat_message_links`, and 100-250 waiting GitHub PR tasks with 5-20 historical `chat_github_reviews` rows each. 2. Run `VACUUM ANALYZE`. 3. Call `readInheritedGitHubReviewWaits` for 100 or 250 waiting runs and run `EXPLAIN (ANALYZE, BUFFERS)` on the `chat_github_reviews` query. 4. Observe PostgreSQL skip-scanning `chat_message_links_provider_message_uq` across all endpoints (over 100,000 shared buffer hits for 100 keys) and probing `heartbeat_runs` once for every historical review. **Paperclip version or commit** `83f10b968d` (`master`) **Deployment mode** Self-hosted server **Database mode** External Postgres ## What Changed - `server/src/services/chat-channels/github/review-wait.ts`: - Added `eq(chatConversations.endpointId, chatMessageLinks.endpointId)` to both `prepareInheritedReviewQuery` and `readInheritedReviewsForKeys`. - Replaced the three independent `= ANY(...)` array predicates in `readInheritedReviewsForKeys` with deduplicated `(comment_id, issue_id, agent_id)` tuples via `unnest(...)`, matching `chat_message_links.comment_id` with strict equality so `chat_message_links_company_comment_idx` (`WHERE comment_id IS NOT NULL`) is directly eligible and cross-key cartesian matches cannot occur in SQL. - Added `latestGitHubReviewSubquery` (`CROSS JOIN LATERAL ... ORDER BY created_at DESC, id DESC LIMIT 1`) in `readInheritedReviewsForKeys` so `heartbeat_runs` joins and `assessment->'reviewedCommit'` extraction run only on the newest review per `(endpoint_id, issue_id)`, while retaining outer `DISTINCT ON` ordering and shared `inheritedReviewFields` projection with `prepareInheritedReviewQuery`. - `server/src/__tests__/github-review-wait.test.ts`: - Verified batch parity on malformed, null, and valid JSON `assessment` values. - Added regression coverage proving cross-key `(comment_id, issue_id, agent_id)` combinations return zero rows from SQL and mismatched `chat_message_links.endpoint_id` values return `null` in both single and batch reads. - Added an `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)` regression test over multi-endpoint data confirming `chat_message_links` never skip-scans without `endpoint_id`, `heartbeat_runs` joins only one row per key across multiple historical reviews, and raw wire rows stay under 1,000 bytes. ## Verification - Audited `packages/db/src/schema/chat_channels.ts` and all production write sites of `chat_message_links` (`chat-channels.ts`, `email-channels.ts`, `chat-teams-file-publication.ts`, `interactions/callbacks.ts`, `publications/transport.ts`, `publications/worker.ts`) and `chat_conversations` updates: every insert writes matching `endpointId` for the conversation and no production path mutates `endpointId` on either table. - Ran checks on commit `e76ca43f1714b31fd47fd9149661090dd3a98483`: - `pnpm check:module-boundaries` — passed. - `node scripts/check-test-budget.mjs --base origin/master` — passed (`113 nightly suites validated, 1 test file(s) checked`). - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/github-review-wait.test.ts src/__tests__/github-review-check-state.test.ts src/__tests__/issue-list-review-wait-authorization.integration.test.ts src/services/native-runtime/external-review-wait.test.ts` — 4 test files, 26/26 tests passed. - `pnpm --filter @paperclipai/server typecheck` — passed across all 7 typecheck layers. - Captured apples-to-apples before (`origin/master`) vs. after (`8a7b1939db4d3ee66c6fdfebcac38032c2a2895b`) `EXPLAIN (ANALYZE, BUFFERS)` on embedded PostgreSQL 18.1 with `VACUUM ANALYZE` (253 `chat_endpoints` including 3 GitHub + 20 Slack in the target company and 230 in other companies, 2,980 `chat_conversations`, 89,400 `chat_message_links`, 4,200 `chat_github_reviews` with ~8 KB TOASTed `assessment` JSONB, 4,680 `heartbeat_runs`, 7 warm samples per query, exact result equivalence asserted with `assert.deepEqual`): | Batch | Before (`origin/master`) | After (this PR) | Improvement | | --- | --- | --- | --- | | 100 keys (5 reviews/PR) | 21.85 ms median (21.75-22.03 ms), 109,761 shared buffer hits (`chat_message_links_provider_message_uq` skip-scan: 29,237 searches, 105,656 hits; `heartbeat_runs`: 500 loops, 1,500 hits) | 0.68 ms median (0.63-0.75 ms), 2,208 shared buffer hits (`chat_message_links_company_comment_idx`: 100 searches, 400 hits; `heartbeat_runs`: 100 loops, 300 hits) | 32.1x faster, 49.7x fewer buffers | | 100 keys (20 reviews/PR) | 28.49 ms median (28.02-28.78 ms), 124,939 shared buffer hits (`chat_message_links_provider_message_uq` skip-scan: 30,229 searches, 108,902 hits; `heartbeat_runs`: 2,000 loops, 6,000 hits) | 1.11 ms median (1.09-1.36 ms), 3,619 shared buffer hits (`chat_message_links_company_comment_idx`: 100 searches, 400 hits; `heartbeat_runs`: 100 loops, 300 hits) | 25.7x faster, 34.5x fewer buffers | | 250 keys (5 reviews/PR) | 58.24 ms median (57.77-58.62 ms), 278,373 shared buffer hits (`chat_message_links_provider_message_uq` skip-scan: 73,820 searches, 268,080 hits; `heartbeat_runs`: 1,250 loops, 3,750 hits) | 1.68 ms median (1.59-1.76 ms), 5,525 shared buffer hits (`chat_message_links_company_comment_idx`: 250 searches, 1,000 hits; `heartbeat_runs`: 250 loops, 750 hits) | 34.7x faster, 50.4x fewer buffers | ## Risks - Low risk. No database schema or migration changes. - Adding `chat_conversations.endpoint_id = chat_message_links.endpoint_id` relies on the invariant that every `chat_message_links` row belongs to the same endpoint as its `chat_conversations` row. All production write paths enforce this invariant, and rejecting a mismatched cross-endpoint link is stricter and safer than matching it. - The `CROSS JOIN LATERAL (... ORDER BY created_at DESC, id DESC LIMIT 1)` subquery is mathematically equivalent to the previous `DISTINCT ON` because `heartbeat_runs` is a primary-key `LEFT JOIN` that neither filters nor multiplies rows, and the outer query still applies `DISTINCT ON (comment_id, issue_id, agent_id) ORDER BY ..., created_at DESC, id DESC` across any multiple conversations or endpoints. ## Model Used - Gemini 4 Neon (Google DeepMind, XHigh reasoning, 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 - [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 |
||
|
|
69144bcf22 |
Require saved requests for human-owned blockers (#23820)
## Thinking Path > - Paperclip coordinates AI agents and human decisions. > - Native runs report blockers through the completion feedback service. > - A run could name a human owner and stop without saving a question. > - The task then had only a generic blocker card and no answerable choice. > - This change requires a saved request receipt before accepting that blocker. > - The human can answer the request, and the existing continuation flow can resume the work. ## Linked Issues or Issue Description **What happened?** A native run could report a human-owned product decision blocker with no saved question, approval, or decision. The task stopped after publishing the choices only as text. **Expected behavior** The agent must save an answerable request that requires a human response and resumes the task after that response. **Steps to reproduce** 1. Start a native task. 2. Call `paperclip_block` with a human owner, a concrete choice in `unblockAction`, and no request receipt. 3. Before this change, the report was accepted and no answerable request existed. After this change, the agent receives a correction and must save the request first. **Paperclip version or commit** Reproduced against `845ca8506a2a` with an isolated source checkout and embedded PostgreSQL. **Deployment mode** Source tests on macOS arm64 with Node 25.6.1 and pnpm 9.15.4. No hosted deployment was made. Related: #22674 improves the text on generic blocker cards. #20807 changes blocker routing. This change enforces the saved request contract before a native worker can stop. ## What Changed - Require a cited, current human-only interaction with `wake_assignee`, a linked pending approval, or an open decision with `wake_origin_agent`. - Check company, task, creator, recipient, request state, and continuation policy. Reuse active requests from prior runs. Reject historical, dismissed, resolved, expired, and unrelated records. - Give the agent a correction in the same turn when it reports a text-only handoff. Add the request and receipt rules to native task instructions. - Expose `request_human_input` in the closed Muse first-party catalog. It uses the existing task, run, and authorizer checks. Generic API and repository operations stay outside that catalog. - Cover the original failure, request reuse, saved answers and queued response delivery, invalid request states, and approval and decision compatibility. ## Verification - Reproduced the original bug with a failing regression, then confirmed the same test passes after the fix. - Passed 114 tests across `native-human-blocker-feedback`, `native-completion-feedback`, `native-completion-format-feedback`, and `native-execution-input`. The review-fix run passed all 161 tests across these suites and `historical-task-questions`. - Passed the updated 16-test request suite after adding the saved-answer delivery check. - Passed `pnpm --filter @paperclipai/server typecheck` across all server layers. - Passed test-budget validation, `git diff --check`, and the secret/PII scan. - `pnpm verify --explain` selected 2,013 of 2,373 Vitest files. Focused local checks cover this change; required CI must supply broad typecheck, test, build, and runner coverage on the final revision. - Initial verification exposed two TypeScript errors and three tests that expected the old permissive behavior. The type errors and expectations were corrected before the passing runs above. - [The first CI run](https://github.com/paperclipai/paperclip/actions/runs/47462198570/job/145490417452) found two more historical-question tests that expected a human blocker with no saved request to be accepted. Their expectations now match the enforced contract; they still check that historical questions stay answerable and do not gate completion. - Reproduced the Muse review finding with a failing native-profile test. After the catalog fix, all 10 selected Muse tests pass, including the new request test and existing actor, grant, and lock-wait authority checks. - Final revision `7d4928cebe5`: [CI passed](https://github.com/paperclipai/paperclip/actions/runs/47463165222) with 68 successful checks and 6 expected skips. [Greptile scored 5/5](https://github.com/paperclipai/paperclip/pull/23820#issuecomment-7429462031) on this revision. No unresolved review threads remain. GitHub reports a clean, mergeable branch. ## Risks - This tightens native human-owned blocker reports. An older in-flight prompt may receive a correction and must save or cite a request before stopping. - Persisted shapes and identities do not change. Existing questions, approvals, decisions, sessions, and saved results carry forward. No migration is required. - Already committed text-only blockers are not backfilled. They need a new agent turn to create the missing request. - Response delivery is tested through its durable queue. No live provider run or hosted deployment was tested. ## Model Used OpenAI Codex, `gpt-6.1-sol`, with xhigh reasoning effort 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> |
||
|
|
c6a8c3ac06 |
fix(queue): let the person who declined a connection discard its queued notice (#23699)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The task composer shows a queue of messages that wait for the agent's current turn to end > - A saved card response, such as a declined connection, also waits in this queue as a read-only row > - The person cannot remove a "Declined: <service> connection" row. The trash stays disabled, and a forced discard returns 409 > - When the person's own queued messages are in front of it, the row is hidden. When the person trashes the last message, the declined row appears. To the person, the deleted row comes back > - This pull request lets the person who declined the connection discard that notice > - The benefit is that the composer queue no longer keeps a row that the person cannot remove ## Linked Issues or Issue Description **What happened?** A person declined a connection request while the agent's turn was running. A "Declined: Google Sheets connection" row then stayed in the composer queue. The trash button did not remove it. After the person deleted their own queued messages, the declined row showed again. **Expected behavior** The person who declined the connection can remove the declined notice from the queue. After removal, the row does not come back. **Steps to reproduce** 1. Start an agent turn on a task. 2. While the turn runs, queue one or more messages, and decline a connection request from the agent. 3. Trash the queued messages one at a time. 4. The "Declined: <service> connection" row appears. Its trash is disabled, and `DELETE /api/issues/:id/queued-comments/:interactionId` returns 409. ## What Changed - `queued-interaction-response.ts`: a declined `connection_intent` receipt now reports the user who declined it as the one person who can discard it. - Board read path (`queued-comment-board-postgres.ts`): the receipt row sets `canDiscard: true` only for that person. - Mutation lock (`queued-comment-postgres.ts`): a receipt wake now counts as a pending queue, and its snapshot uses the same receipt row and revision as the read path. - Discard use-case: for a saved response, discard cancels the receipt wake and does not delete a comment. The card keeps its Declined outcome. - Discard also marks an unfinished connection delivery as done in the same transaction. A delivery retry after a crash does not send the notice again. - `queuedInteractionEntry` builds the receipt row and its `canDiscard` rule for the read path and the mutation path. - The connection delivery worker counts a wake that a person discarded as delivered. A retry that is already running does not create a new wake. - The read path and the mutation path drop a tool-action outcome the same way, so both compute one queue revision. Edit and reorder refuse every saved-response queue with `queued_comment_not_pending`. - Edit and reorder still return 409 for every saved response. Approvals, answers, accepted connections and tool-action outcomes stay non-discardable. ## Verification - New route tests in `server/src/__tests__/issue-queued-comments-routes.test.ts`: - The person who declined the connection discards the notice. The next read is empty, the wake is `cancelled`, `hasQueuedInteractionResponse` is false, and the card stays `rejected`. Another member gets `canDiscard: false` and cannot discard it. - The notice waits behind two queued messages. Trashing each visible row empties the queue: messages, then the declined notice, then nothing. - The tests failed before the fix (409 on discard) and pass after it. - `npx vitest run src/__tests__/issue-queued-comments-routes.test.ts src/__tests__/issue-queued-comments-dispatch-routes.test.ts src/modules/wake-queue` passes, together with `src/__tests__/connection-intents-service.test.ts`: 19 files, 540 tests. - New tests: a delivery retry that is already running does not send a discarded notice again, and reordering a hidden tool-action outcome returns 409. Both fail without the change. - A route test with an unfinished delivery row checks that discard sets `deliveredAt`. The test fails without the change. - I did not complete a local full `tsc` run. The process ran out of memory on the test machine. CI runs the typecheck. ## Risks - Low risk. The change applies only to declined connection notices. - When the person discards the notice, the agent does not get the decline as a steering message. The agent still sees the Declined card on its next turn. Continuation recovery only redelivers accepted or answered cards, so it does not queue the notice again. - Discard sets `deliveredAt` on an unfinished connection delivery. The delivery worker also treats a discarded wake as delivered, so a retry that is already running does not create a new wake. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in a Paperclip agent workspace. ## 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 - [ ] 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> |
||
|
|
0c456fcca1 |
fix(adapters): find Windows ACP commands through PATHEXT (#14441)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Local adapters (Claude, Codex, Gemini, Kimi) start an ACP server command for each agent > - Each adapter finds a bare ACP command, such as `codex-acp`, on `PATH` > - On Windows, that lookup only tries the exact name and ignores `PATHEXT` > - So a real install such as `codex-acp.exe` is never found, and the environment check says the ACP command is not available > - This pull request makes the lookup try each `PATHEXT` form on Windows, with the same rule that `adapter-utils` already uses > - The benefit is that ACP works on Windows with a normal `PATH` install, and all four adapters use one rule ## Linked Issues or Issue Description Fixes #14372 Related PRs: #14129 and #13053 fix the `PATHEXT` lookup in the GitHub launchers (`github-launcher.ts`). #9996 changes how the ACP engine probes `gemini --version` on Windows. They change different code, so this PR does not duplicate them. ## What Changed - `adapter-utils`: add `commandPathCandidates(dir, command, { env, includeBareName })`. It returns the files to check for a command in one `PATH` folder. On Windows it returns one file for each `PATHEXT` entry. With `includeBareName`, it also returns the bare name last. It returns the name unchanged if the command has an extension or if the platform is not Windows. - `adapter-utils`: `resolveCommandPath` now uses `commandPathCandidates`. Its behavior does not change. - `claude-local`, `codex-local`, `gemini-local`, `kimi-local`: `findCommandOnPath` in `acp.ts` now checks the `PATHEXT` forms first, then the bare name. Before this change, the four copies checked only the bare name. They still find an extensionless file, so their old results do not change. - `gemini-local`, `kimi-local`: these adapters already read `PATH` from the agent `env` config. They now also read `PATHEXT` from it, and use the host value when the config does not set it. ## Verification - `pnpm vitest run packages/adapter-utils/src/server-utils.test.ts -t commandPathCandidates`: 4 new tests, for Windows `PATHEXT` forms, the bare-name fallback, a name with an extension, and other platforms. - `pnpm vitest run packages/adapters/codex-local/src/server/acp.test.ts -t "finds a Windows codex-acp.exe"`: a new test puts `codex-acp.exe` on `PATH` and sets the platform to `win32`. It expects the ACP engine to be available for the bare command `codex-acp`. Without the fix, the test fails with the error from #14372: `Codex ACP server command is not available: codex-acp`. - `gemini-local` and `kimi-local` `acp.test.ts`: a new test in each puts `gemini.ACP` or `kimi.ACP` on a configured `PATH` and sets `PATHEXT: ".ACP"` in the agent `env` config. It expects the ACP engine to be available. Without the configured `PATHEXT` support, both tests fail. - The tests set `process.platform` to `win32`, so they also run on Linux CI. The fixture file names match the `PATHEXT` case exactly, so the tests do not depend on a case-insensitive file system. - I ran the test suites of `adapter-utils` and the four adapters on Windows, with and without this change. No test fails only with this change. - `pnpm --filter <package> typecheck` passes for `adapter-utils` and the four adapters after each commit. `scripts/check-forbidden-tokens.mjs` and `scripts/check-module-boundaries.mjs` pass. ## Risks - Low risk. On macOS and Linux, the lookup does not change: it checks the same single path. - On Windows, the lookup now prefers a `PATHEXT` file (for example `codex-acp.exe` or `codex-acp.cmd`) over an extensionless file in the same folder. In an npm `.bin` folder, it can now return `codex-acp.cmd` where it returned the extensionless shell script before. Windows cannot run that shell script directly, so the old result did not work either. An extensionless file alone is still found. > 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 - Provider: Anthropic - Model: Claude Opus 5.5 (`claude-opus-5-5`) - Tool: Claude Code, with tool use (shell commands, file edits, and test runs) - The model found the issue, wrote the change and the tests, and ran the checks. I reviewed the change and the test results. ## 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 - [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: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com> |
||
|
|
9f61016d37 |
chore(deps): keep @cloudflare/sandbox on 0.x in Dependabot (#23818)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Sandbox providers include a Cloudflare bridge template that operators deploy as a Worker > - Dependabot opened #19565 to bump `@cloudflare/sandbox` from 0.7.21 to 1.0.3 > - Version 1.0 removes the `Sandbox` Durable Object class and `getSandbox()`. The bridge template uses both, so typecheck fails with TS2305 > - A port to 1.0 also needs a new `wrangler.jsonc` (public-beta scheduling policy, new container name), a new container image, and a deploy that operators cannot roll back > - This pull request tells Dependabot to skip major `@cloudflare/sandbox` updates. We will do the 1.0 migration later as a planned change with operator docs > - The benefit is that Dependabot stops opening a pull request that cannot pass CI, and minor/patch 0.x updates continue ## Linked Issues or Issue Description Refs #19565 **What happened?** Dependabot pull request #19565 bumps `@cloudflare/sandbox` to 1.0.3. The `Typecheck + Release Registry` job fails because 1.0 does not export `Sandbox` or `getSandbox`. **Expected behavior** Dependabot does not propose a major `@cloudflare/sandbox` update that needs a manual, one-way migration. **Steps to reproduce** Check out #19565 and typecheck `packages/plugins/sandbox-providers/cloudflare/bridge-template/tsconfig.test.json`. ## What Changed - Add an `ignore` rule for `@cloudflare/sandbox` `version-update:semver-major` to the `/scripts/typecheck-sandbox-providers` entry in `.github/dependabot.yml`, with a comment that gives the reason. ## Verification - Parsed `.github/dependabot.yml` with the `yaml` package. The `/scripts/typecheck-sandbox-providers` entry now has two ignore rules: `@types/node` and `@cloudflare/sandbox`, both semver-major. - No source, test, or lockfile changes. ## Risks - Low risk. This is a config-only change. Dependabot continues to propose 0.x updates for `@cloudflare/sandbox`. Someone must remove the rule when the team plans the 1.0 migration. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with 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 - [x] 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: devinfoley <139239+devinfoley@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
3346a95af8 |
fix(adapters): mount skill sources in the local workspace sandbox (#14340)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - `claude_local` and `codex_local` can confine a run with the local
bwrap sandbox (`filesystemScope: "workspace"`)
> - The adapters give the agent its skills as symlinks (in the prompt
bundle, or in `CODEX_HOME/skills`) to the skill source under the
Paperclip instance skills directory
> - The sandbox mounts the bundle and `CODEX_HOME`, but not the link
targets, so every link dangles
> - The agent sees no skill, not even the built-in `paperclip` skill,
and the run gives no warning
> - This pull request mounts each linked skill source read-only in the
sandbox
> - The benefit is that confined agents get the skills that the board
assigned to them
## Linked Issues or Issue Description
No issue exists. Description:
**What happened?**
A `claude_local` agent with `filesystemScope: "workspace"` and assigned
skills ran without skills. Inside the sandbox, `.claude/skills/<skill>`
in the `--add-dir` bundle was a dangling symlink to
`~/.paperclip/instances/default/skills/<company>/__runtime_cache_v1__/…`
(company skills) and to `…/@paperclipai/server/skills` (built-in
skills). `codex_local` had the same problem with `CODEX_HOME/skills`.
**Expected behavior**
The agent reads every desired skill inside the sandbox.
**Steps to reproduce**
1. Create a `claude_local` or `codex_local` agent with `filesystemScope:
"workspace"` and one company skill.
2. Run it and ask it to list its skills, or run `ls -L` on the skills
directory inside the run.
3. The links do not resolve. The workaround is to add both directories
to `filesystemExtraPaths` by hand.
**Paperclip version or commit**
Seen on 2026.916.1, reproduced on `master` at
|
||
|
|
9ccb5455a1 |
fix(adapter-utils): keep SSH profile sourcing alive under dash (#14309)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - SSH environments run the environment probe and every agent execution on an operator-configured host > - Before each remote command, the wrapper sources the login profiles so that `node` and the agent CLI are on `PATH` > - On Debian and Ubuntu, `/bin/sh` is `dash`. A bash-only line in a profile, such as `export -a`, is a special builtin error, and `dash` exits the whole shell on it > - The `|| true` guard never runs, so the probe and every run fail with exit 2 and empty stdout and stderr > - This pull request sources each profile with `command .`, in both `runSshCommand` and `buildSshSpawnTarget` > - The benefit is that a host with a bash-only `~/.bashrc` works, and exports made before the failing line stay in effect ## Linked Issues or Issue Description Refs #14226 This PR fixes items 1 and 2 of the issue. Item 3 (keep the profile diagnostics when the exit code is non-zero and both streams are empty) is not in this PR, so the issue stays open for it. ## What Changed - `packages/adapter-utils/src/ssh.ts`: in `runSshCommand` and `buildSshSpawnTarget`, source each login profile with `command .` instead of `.`. POSIX `command` removes the special builtin behavior of `.`. Under `dash`, a special builtin error or a syntax error in a profile now stops that profile at the failing line, and the wrapper shell continues. An `exit` in a profile still ends the wrapper, as before. Under `bash`, the behavior does not change. - `packages/adapter-utils/src/ssh.ts`: move the four sourcing lines into one constant, `LOGIN_PROFILE_SOURCE_LINES`, that both functions use. The dash test on `buildSshSpawnTarget` now also covers the lines that `runSshCommand` sends, and the two call sites cannot drift apart. - `packages/adapter-utils/src/ssh-fixture.test.ts`: add a test that runs the generated remote command line with `dash` as `sh`. The fake `HOME` has a `.bash_profile` that sources a `.bashrc` with `export PATH=...`, `[[ ... ]]`, and `export -a`. The test expects the command to run and `PATH` to start with the directory that `.bashrc` exported. The test is skipped when `dash` is not installed. I chose `command .` over the two fixes in the issue. The subshell plus `export -p` form re-imports the whole environment with `eval`. The `bash -lc` form changes the shell for every host. `command .` is one word per call site and keeps the current sourcing order. ## Verification - `npx vitest run packages/adapter-utils/src/ssh-fixture.test.ts -t dash` on macOS with `/bin/dash`: the new test passes 2 times in a row. - Red before the fix: with the `ssh.ts` change reverted, 1 failed. `dash` exits with status 2 before the command runs, the same symptom as the issue. - Manual check with `dash` and the profiles from the issue: the old script exits 2 with no output. The new script exits 0, and `PATH` has the entry that `.bashrc` exported before `export -a`. Under `bash`, the old and new scripts give the same output. - Mutation check: with `command . ` changed back to `. ` in the shared constant, the dash test fails. - `npx vitest run packages/adapter-utils/src/ssh-fixture.test.ts`: 21 of 21 pass, 2 runs. - `npx vitest run packages/adapter-utils` is flaky under parallel load in my checkout, on `master` and on this branch. Across runs I saw failures in `sandbox-managed-runtime`, `sandbox-callback-bridge`, `acpx-engine/execute`, `acpx-engine/startup-characterization`, `execution-target-stdin-race`, and `github-launcher-environment`. Each of the last four passes when run alone. `sandbox-managed-runtime` (2 tests) and `sandbox-callback-bridge` also fail on `master`. - `cd packages/adapter-utils && npx tsc --noEmit`: exit 0. - I did not run the SSH env-lab fixture against a real Debian or Ubuntu host. ## Risks - Low risk. POSIX specifies `command .`. I tested it in `dash` and `bash`. - Lines in a profile after the failing line still do not run under `dash`. Before this change, nothing ran at all. - This PR does not do item 3 of the issue. A profile that calls `exit` still gives a non-zero exit with empty streams. I can open a follow-up PR for it. - Six sandbox provider sites use the same sourcing lines: `cloudflare/bridge-template/src/exec.ts`, `daytona/src/login-pty.ts`, `daytona/src/plugin.ts`, `e2b/src/plugin.ts`, `exe-dev/src/plugin.ts`, and `modal/src/plugin.ts`. The default images come from Paperclip, but operators can set their own image or template, so the same bug can apply. This PR keeps the scope to SSH, as in #14226. I can open a follow-up PR for these sites. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`, Anthropic), in Claude Code with tool use (shell, file edit). It reproduced the bug with a failing test, wrote the fix, and drafted this description. A human reviewed the change. ## 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 (no documentation describes the profile sourcing) - [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: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
6a5dfc0288 |
feat(recents): store sidebar Recents on the server so every client shares one list (#23706)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The sidebar Recents list shows the tasks from a person's own recent activity > - Each browser kept Recents in `localStorage`. A laptop, a phone, and a second browser each showed a different list > - People expect one list for their account, the same on every client > - This pull request moves Recents to the server. The server keeps one list for each person in each company. The UI shows that list and gets live updates when another client changes it > - The benefit is that every client shows the same Recents in the same order, and a change on one client shows on the others at once ## Linked Issues or Issue Description **Is your feature request related to a problem? Please describe.** Recents is kept in the browser. When I open a task on my laptop, the task does not show in Recents on my phone or in another browser. **Describe the solution you'd like** Keep Recents on the server, so that every client that I sign in to shows the same list. **Additional context** Eligibility (which rows show) does not change. The navigation summaries still decide it (see #23675). ## What Changed - `packages/db`: new `user_recent_tasks` table (company, user, issue, `recorded_at`), unique on company + user + issue. Migration `0515` creates only a new table, so it is `online_compatible`. - `packages/shared`: `RecentTaskRecord`, `RecentTaskList`, `RECENT_TASKS_MAX_ENTRIES` (200), and the `recordRecentTaskSchema` and `importRecentTasksSchema` validators. - `server`: new `recentTaskService` and routes: - `GET /api/companies/:companyId/recent-tasks/me`: the list, newest first. - `POST /api/companies/:companyId/recent-tasks/me` `{ issueId, touch }`: `touch: true` moves the task to the top (server time). `touch: false` adds a missing task below the history and does not move an existing task. - `POST /api/companies/:companyId/recent-tasks/me/import`: imports the list that a browser kept. The later time wins. - `DELETE /api/companies/:companyId/recent-tasks/me/:issueId`. - The server keeps the newest 200 rows for each person. Each change is in the activity log as `recent_tasks.*` with `entityType: "company"` and `details.userId`. The entry does not name the task. Viewers can change their own Recents, like workspace preferences. - Record, import, and list use the normal task read decision. A private or unreadable task gets the same 404 as a missing task. The import skips it, and the list does not return it. - `server/src/realtime/live-events-ws.ts`: sends `recent_tasks.*` events only to the owner's connections, without details. - OpenAPI entries for the four routes. - `ui/src/lib/recent-tasks.ts`: the module is now a client mirror of the server list, not `localStorage`. Optimistic records and removals stay applied until a server list that was requested after the server saved them arrives. This prevents a stale list from hiding a new visit. - `ui/src/hooks/useRecentTasks.ts`: fetches the server list (`queryKeys.recentTasks`). On the first load it imports the old browser list one time and then deletes the browser copy. It does not delete ineligible rows anymore. It hides them, and it requests a new summary batch when new activity occurs on a hidden task. The `awaitingRead` flow is removed because nothing deletes the row while the read is in flight. - `LiveUpdatesProvider`: a `recent_tasks.*` event refreshes Recents. Other company views do not refresh. - A failed save is tried again one time. If it fails again, the client loads the server list again, so an unsaved change does not look saved. - The import reads only the newest browser storage version. - `SidebarRecentTasks`: the "Archive" action removes the task from the server list. - `doc/PRODUCT.md`: describes the shared list. ## Verification - `cd server && npx vitest run src/__tests__/recent-tasks-routes.test.ts` (embedded Postgres): 5 passed. The tests cover: two clients of the same person see the same order; touch and passive seed; personal and company scope (teammate, other company, agent, viewer, suspended member); removal plus activity log plus live events; import, and the 200-row limit. - `cd server && npx vitest run src/__tests__/openapi-routes.test.ts`: 59 passed. - `cd server && npx vitest run src/__tests__/recent-tasks-routes.test.ts src/__tests__/live-events-toast.test.ts`: 21 passed. This includes private-task checks and owner-only socket delivery. - `cd ui && npx vitest run src/lib/recent-tasks.test.ts src/hooks/useRecentTasks.test.tsx src/context/LiveUpdatesProvider.test.ts`: all passed. New tests cover: the same list on a second client, legacy import (success and failure), the record-and-list race, server-time adoption, and live-event scoping. - `packages/db`: `migration-compatibility.ts` classifies `0515` as `online_compatible`. - `packages/shared` typecheck: no errors. `ui` typecheck: no errors in changed files (errors exist only in the ungenerated Storybook feature-map indexes). - `server`: a typecheck of the route, service, and test graph passes. The full `server` typecheck was killed by the local memory limit (exit 137). CI covers it. - `pnpm verify` returned exit 2 (the migration needs broad CI coverage). Required CI supplies that coverage. ## Risks - Medium. This adds a table and changes where Recents is kept. - Each task open now sends one more request and writes one activity row (the same as `issue.read_marked`). The live socket sends the event only to the owner's connections. - Rows that are not eligible stay in the server list (hidden) until they fall out of the newest 200. Before, the client deleted them. - The import reads `paperclip.recentTasks.v3`, `v2`, and the oldest key one time for each browser. If the import fails, the browser copy stays and the next load tries again. - An old tab from the previous release still writes to `localStorage`. The next load of a new tab imports those entries. The later time wins, so this does not reorder newer server entries. > 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`), via Claude Code with tool use (shell, file edit, 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 - [ ] 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 - [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: devinfoley <139239+devinfoley@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>canary/v2026.1205.0-canary.892800 |
||
|
|
dfe392dada |
fix(ui): include task identifier in browser tab title (#14212)
## Thinking Path Paperclip's task breadcrumbs already carry identifiers, while browser tab titles omit them. Showing a valid identifier before the task name makes tabs easier to distinguish. Preserve existing titles for missing, blank, or duplicate identifiers. ## Linked Issues or Issue Description - Fixes #13615. - Refs #10933, which added identifiers to visible task breadcrumbs. - Refs #14583. This branch reuses the existing test-only CI repair by itsjeremyjohnson and Codex, preserving its authored commit and attribution. ## What Changed - Show task titles as `IDENTIFIER — Name` when the breadcrumb has a nonblank identifier. - Preserve the existing title when the identifier is missing, blank, or equals the label. - Cover task/identifier/company changes, empty breadcrumbs, and duplicate identifiers. - Merge current master and keep its expanded clipboard-feedback test unchanged. The earlier #14583 repair remains credited in history. The net change against master is limited to the two title files. ## Verification Integration base: `b110271c9b2fd6dd5a1beb119e7f0663385df8b9`. Current head: `5fd1105c78d16418876b70921cca97a836359da6`. Its merge parents are the previous PR head and the integration base above. - macOS arm64, official Node 24.21.0, Vitest 5.0.3, original current Vitest config/setup, one worker, 512 MiB heap: **16/16 passed** in BreadcrumbContext and ProjectWorkspaceSummaryCard. - The same tests against master's original title implementation produced **14 passed / 2 failed**. Both failures concern the missing identifier in the helper and live document title. The candidate passes both. This comparison keeps the same dependencies and test bytes. - Master's clipboard regression remains byte-for-byte unchanged. Its four text/icon controls and 1499ms-visible/1500ms-expired checks pass. - All four current token gates passed across 1,416 files. `git diff --check` passed. The exact committed tree matches the tested candidate. The net diff from the integration base contains only the two BreadcrumbContext files. - The diagnostic dependency environment uses 170 exact packages from the unchanged current lockfile. It reuses 156 packages from the prior integrity-checked cache and verifies registry and archive integrity for 14 added versions. No lifecycle scripts or dependency overrides ran. This is a minimal test environment, not a full workspace installation. - Checks for this new head are pending. The prior [workflow 39381608779](https://github.com/paperclipai/paperclip/actions/runs/39381608779) passed all 48 jobs at `574f0c9`, with 54 successful and two skipped checks. That result and the old Greptile 5/5 are historical; they do not validate this integration. - Full-workspace typecheck, build, backend and browser acceptance were not repeated locally on this integration. The current local environment covers the affected regressions. Full repository checks remain for upstream CI. The original failed clipboard CI attempt is retained in history. Its exact Ubuntu timing cause was not independently reproduced locally. No assertion, workflow or gate was disabled. The upstream-expanded test now replaces our imported test diff while preserving its authored history. ## Risks The application change affects tab text for task breadcrumbs with a valid identifier. Master now contains a broader workspace clipboard-feedback regression. This merge keeps that file exactly as master. The imported #14583 commits and original attribution remain in branch history. No clipboard production code changes. Historical real-backend browser acceptance at `4040c564` remains historical only. Authentication, multi-user permissions, agent execution and other browser engines were outside that acceptance. Maintainer review and checks for the new head remain pending. ## Model Used OpenAI Codex, GPT-6 family, assisted with implementation, tests, repository inspection and GitHub checks. The exact served model ID, context window and reasoning settings were not exposed. The reused test repair retains the AI disclosure and authorship recorded in #14583. ## 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 - [ ] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Codex <codex@openai.com> |
||
|
|
d939c64a6b |
fix(opencode): keep the text-first answer when only the completion call is written as text (#23806)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The Paperclip runner drives OpenCode models and asks again when a
turn ends without a final answer
> - The second request asks for a plain-text answer first, then the
`paperclip_finish` call
> - DeepSeek v4.1 flash sometimes sends that answer and then writes
`paperclip_finish` as DSML text, not as a real tool call
> - The runner discards the full reply when it finds tool-call text, so
it also discards the answer it asked for, and the turn fails with
`opencode_empty_response`
> - This pull request keeps that answer when the only text call after it
is the completion call
> - The benefit is that a turn that already did its work ends with an
answer, not a failed run and a full retry
## Linked Issues or Issue Description
Refs #21361
Refs #21761
**What happened?**
After real tool work, a reviewer agent on DeepSeek v4.1 flash
(OpenRouter) ended its turn with a tool call written as text. The runner
sent two corrections. For the second correction, the model wrote a
correct plain-text answer, a blank line, and then `paperclip_finish` as
DSML text. The runner discarded the full reply and failed the turn with
`opencode_empty_response` ("after two corrections"). The work was
already done. In one run, the model had published a PR review. In a
different run, it had posted a GitHub reply. The automatic retry then
ran the full session again. This occurred three times on staging in
three weeks, and two of the three were on the same day.
**Expected behavior**
The second correction asks for exactly this shape: an answer, then the
completion call. When the completion call is the only text call, the
runner should keep the answer. A completion call starts no work, so the
answer cannot describe an action that did not occur.
**Steps to reproduce**
1. Start an OpenCode turn that does tool work and then sends an empty
reply two times.
2. For the text-first correction, send `Here is the actual final
answer.` followed by a DSML `paperclip_paperclip_finish` call as text.
3. Before this change, the turn fails with `opencode_empty_response`.
The new `tool-work-text-finish-markup` case in `empty-response.test.ts`
does these steps.
**Paperclip version or commit**
`master` at
|
||
|
|
df371acc77 |
fix(recovery): give fresh runs a grace period before the issue-terminal sweep (#13883)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The control plane keeps issue ownership and run liveness in separate rows, and a recovery sweep reconciles them. > - That sweep can terminalize a `running` heartbeat row on two authorities: a dead process, or a terminal issue above a live row. > - The issue-terminal authority infers orphanhood from the issue status alone. It does not observe the run. > - A reassignment hand-off satisfies that inference while it is healthy: one request sets the issue to `done` and reassigns it, so the receiving agent's run starts while the issue is momentarily terminal and still holds the lock columns. > - The sweep then kills a run that is seconds old and releases the checkout it just acquired. > - This pull request requires the row to have stayed `running` for 60 seconds before the issue-terminal authority applies. > - The benefit is that a reassignment hand-off completes instead of failing with an ownership conflict on a checkout that returned 200. ## Linked Issues or Issue Description No public GitHub issue exists for this bug. Related pull requests: - Refs #13271. That pull request makes a live in-memory executor authoritative over both authorities. It fixes the case where one run sets its own issue terminal and keeps writing. It does not close the window this pull request closes. See "Relationship to #13271" below. **What happened?** An agent set an issue to `done` and reassigned it in the same `PATCH`. The server started the receiving agent's run. The issue was still terminal and still held `checkout_run_id` and `execution_run_id`. The stale-lock sweep read the terminal issue as proof that the new run was orphaned. The sweep marked the run terminal after about 700 ms and cleared the lock columns. The receiving agent had already received `200` from its checkout. Every later status write from that agent failed with an ownership conflict. **Expected behavior** The sweep must not terminalize a run that is seconds old on the strength of the issue status alone. A run that just acquired a checkout must keep it. **Steps to reproduce** 1. Assign an issue to agent A and let its run check the issue out. 2. Send one `PATCH` that sets the issue to `done` and reassigns it to agent B. 3. Let the server start agent B's run. The issue still holds both lock columns. 4. Run the stale issue-lock sweep inside the first seconds of that run. 5. See the sweep mark agent B's run `succeeded` with error code `orphaned_running_run_issue_terminal`. 6. Send a status write from agent B. See the ownership conflict. **Paperclip version or commit** `master` at `60c7c9cd1`. **Deployment mode** Self-hosted server with PostgreSQL. The defect is in the shared run lifecycle. It is not specific to an adapter. ## What Changed - Added `ISSUE_TERMINAL_MIN_RUN_AGE_MS` (60 seconds) to `server/src/services/recovery/service.ts`. - Suppressed the issue-terminal authority in `terminalizeOrphanedRunningRun` while the run row is younger than that age, and logged a warning when the suppression fires. - Left the process-death authority unchanged, so a dead process is still swept immediately at any run age. - Made the two reuse-lease tests seed an aged run row, because an orphan is by definition a row that stayed `running`. - Added a test for the reassignment hand-off. It asserts that the fresh run survives and that both lock columns survive. - Added a test for a fresh run with a dead recorded pid. It asserts that the sweep still terminalizes the run as `interrupted` and still clears the locks. ## Relationship to #13271 #13271 moves the `liveRunExecutions` check to an early return, so it covers both authorities. That is a good change and this pull request composes with it. It does not cover this window, for two reasons. 1. The run row reaches `running` before the execution registers itself. `activeRunExecutions.add(run.id)` runs inside the execution body, after awaited database work. A sweep that fires in that gap sees no live execution. The run also has no recorded pid yet, so the process-death authority stays silent by design. The issue-terminal authority is the only one left, and it fires. 2. `activeRunExecutions` is a module-scope `Set`. It is per server process. A sweep on one process cannot see an execution owned by another. The grace period covers both, because run age is in the row itself. ## Verification - `node scripts/run-vitest-stable.mjs server/src/__tests__/recovery-stale-issue-lock-sweep.test.ts` is the target suite. I could not run it in my environment: the suite needs embedded PostgreSQL, and my sandbox has no host for it. I ask CI to be the check here. Please do not merge on a red run. - I did verify the guard logic directly. I extracted the compiled guard and drove it against seven cases: a 700 ms run under a `done` issue, a 59 s run, a 61 s run, a one-hour run under a `cancelled` issue, a row with no usable timestamp, an ISO string timestamp, and a null issue status. All seven matched the intended outcome, and the warning fired only on the three suppressed cases. - I traced the single call site. `sweepStaleIssueLocks` builds `runRows` with `db.select()` and no projection, so `run.createdAt` is always present at run time. There is no other caller. - Reviewers can reproduce the bug with the six steps above. The new hand-off test fails on `master` and passes with this change. ## Risks Low, and the direction of the failure is the safe one. - A genuinely orphaned run now keeps its lock for up to one extra sweep tick. The sweep is periodic, so the next tick clears it. Nothing is stranded. - The guard fails open. If the row carries no usable timestamp, the sweep behaves as it does today. - The process-death authority is untouched. A hard crash is still reaped at once. - Two existing tests changed their fixture, not their assertions. They still assert that the sweep terminalizes the run and clears the lock. - The 60 second value is a constant, so an operator who needs a different window changes one line. ## Model Used Claude Opus 4.7 (`claude-opus-4-7`) by Anthropic, through Claude Code with tool use and extended thinking. ## 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 — the suite needs embedded PostgreSQL, which my environment cannot start. See Verification. - [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 the first CI run - [ ] 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 --------- Co-authored-by: Builder <builder@nublo.net> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
67e6a6aa2a |
fix(plugins): bridge issue.child_created activity to issue.created plugin event (#13728)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Plugins subscribe to core domain events such as `issue.created` through the `events.subscribe` capability > - Issues created through `POST /issues/:id/children` or accepted-plan decompositions only log the `issue.child_created` activity action, and that action was not in the plugin event bridge in `activity-log.ts` > - Subscribers to `issue.created` therefore never observe child issues, so plugin workflows that track every new issue silently miss decompositions > - This pull request maps `issue.child_created` to the `issue.created` plugin event type > - The benefit is that plugin subscribers observe every new issue through one event type, and the bridged payload matches a top-level creation because the activity row already carries `entityType: "issue"` and the new child issue id ## Linked Issues or Issue Description Fixes: #13466 ## What Changed - Added `issue_child_created: "issue.created"` to `ACTIVITY_ACTION_TO_PLUGIN_EVENT` in `server/src/services/activity-log.ts`, with a comment explaining why the bridge is safe (same entity shape as top-level creation) - Added `server/src/__tests__/activity-plugin-event-bridge.test.ts` covering: - `issue.child_created` is bridged to `issue.created` with the child issue id as the event entity - a native `issue.created` action still passes through unchanged - unmapped actions still emit no plugin event ## Verification ```sh ./node_modules/.bin/vitest run server/src/__tests__/activity-plugin-event-bridge.test.ts ``` All 3 tests pass against an embedded Postgres instance. Also ran `git diff --check`. ## Risks Low risk. The change only adds a mapping entry; no existing activity action is remapped or removed. Plugins that already handle `issue.created` will now also receive child creations. The activity details payload carries an extra `parentId` field for child creations, which additive subscribers should tolerate. No migration or schema change. > 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 OpenAI Codex (GPT-5, coding-agent mode, repository tool use) — assisted with root-cause analysis, the mapping change, and the new test file. ## 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: 馨冉 <xinxincui239@gmail.com> |
||
|
|
f530a7b167 |
Keep pause status inline and ease the agent character into sleep (#23662)
## Thinking Path
> - Paperclip helps people manage AI agents at work.
> - The agent overview shows the agent name and runtime status.
> - A pause or resume adds a status row and moves the name.
> - The name should stay in place while the agent changes state.
> - This change places the status beside the name and crown.
## Linked Issues or Issue Description
**Subsystem affected**
Agent detail header.
**Current behavior**
Pause and resume add a line of detail below the harness. The title moves
when that line appears.
**Proposed behavior**
Keep the title steady. Show progress beside the crown and keep the
paused state visible until the user resumes the agent.
## What Changed
- Resize and fade the pill with a fixed left edge. Respect reduced
motion.
- Blend the header character into its sleeping pose over 160 ms when the
agent reaches **Paused**. Keep its assigned colors and show the
onboarding sleep marks. Wake the character when resuming begins.
- Show the new pose immediately when the user requests reduced motion.
- Preserve lifecycle error details and retry controls.
- Add a development preview that lets reviewers try both transitions
without changing an agent.
## Verification
- Open an agent overview in development with `?preview=pause`. Select
**Preview pause**, wait for **Paused**, then select **Preview resume**.
- Chromium confirmed the full cycle and the 240 ms resize duration.
- Chromium confirmed that the character uses the same palette when
sleeping and awake.
- All 36 focused tests passed in four Vitest files on commit
|
||
|
|
845ca8506a |
test(server): drain structured issue route work before teardown (#23813)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Issue routes can wake an assigned agent in the background. > - The structured issue parity suite uses those real routes and a temporary database. > - It could stop that database while route-triggered work was still active. > - The resulting unhandled database error failed source verification after test assertions passed. > - This pull request drains that work after each test and checks quiescence. > - Database teardown now starts only after the suite's background work settles. ## Linked Issues or Issue Description **What happened?** [Cloud readiness run 47456696780, attempt 2](https://github.com/paperclipai/paperclip/actions/runs/47456696780/job/145473729239) reported 1,562 tests passed and three skipped in server shard 13/20, then failed on an unhandled PostgreSQL `read ECONNRESET`. The error came from type discovery and was reported while `canonical-issue-structured-parity.test.ts` was running. This cancelled [image run 47456696824](https://github.com/paperclipai/paperclip/actions/runs/47456696824). **Expected behavior** The fixture must settle route-triggered wakeups and executions before it resets data or stops PostgreSQL. **Steps to reproduce** On master `83f10b968dba1cb0300f216cabce3a5924f5d3c8`, add the quiescence assertion from this diff without the drain. Run `PAPERCLIP_VITEST_RETRY=0 pnpm exec vitest run server/src/__tests__/canonical-issue-structured-parity.test.ts --maxWorkers=1`. The assertion failed locally with three active executions and one pending wake. The old teardown also logged queries against a closed connection. ## What Changed - Await the existing heartbeat drain after each test. - Assert zero active executions and pending wakes before the fixture can continue or stop its database. - Keep the route, channel isolation, schema validation, and authorization checks in place. ## Verification - Red: the cleanup assertion failed with `activeRuns: 3`, `pendingWakes: 1`, and `quiescent: false`. - Green: both tests passed after the drain, with retries disabled and no unhandled errors. - Test budget and `git diff --check` passed. - Final PR head `f4679f12c299ff7718112f5d368fce907d1d0f3a`: 64 checks passed, seven skipped, no pending or failed checks; GitHub reports no merge conflicts. [Greptile rated it 5/5](https://github.com/paperclipai/paperclip/pull/23813#issuecomment-7429108337), with no review threads or follow-ups. - The first server typecheck found stale local Plugin SDK declarations that omitted `runtime_updating`. The value already exists in SDK source. Rebuilt the Plugin SDK and shared package; the final server typecheck passed, and both focused tests passed again with retries disabled. - `pnpm verify --explain` conservatively retained 2,009 of 2,372 test files. Required CI will provide that broad coverage. - Recovery: [exact-source verification attempt 3](https://github.com/paperclipai/paperclip/actions/runs/47456696780/job/145482927885) passed for master `83f10b968dba1cb0300f216cabce3a5924f5d3c8`. [Image attempt 2](https://github.com/paperclipai/paperclip/actions/runs/47456696824/job/145483491486) then published the AMD64/ARM64 manifest as `ghcr.io/paperclipai/paperclip:sha-83f10b9`, digest `sha256:9c23177cbe9744eded163c56bc88904aa0901442fe9932b6ea5cf329f143c66e`. All publication gates remained in place. This establishes operational recovery; resolving the cleanup race requires this change. ## Risks - Low risk. Only test fixture cleanup changes. Production code and database behavior stay as they are. - The drain can settle work that the route started before the HTTP response. A future unfinished execution fails the quiescence assertion instead of leaking into database teardown. - No documentation change is needed because the application contract does not change. ## Model Used - OpenAI `gpt-6.1-sol`, through the Codex harness in T3 Code, with xhigh reasoning effort and shell tools. The context window size is 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 - [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>nightly/v2026.1205.0-nightly.0 canary/v2026.1205.0-canary.892200 |
||
|
|
83f10b968d |
build(deps): bump actions/dependency-review-action from 5.0.0 to 5.0.1 (#22594)
Bumps [actions/dependency-review-action](https://github.com/actions/dependency-review-action) from 5.0.0 to 5.0.1. <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/actions/dependency-review-action/releases">actions/dependency-review-action's releases</a>.</em></p> <blockquote> <h2>v5.0.1</h2> <p>Minor update:</p> <ul> <li>Better error information from the compare endpoint (<a href="https://github.com/ahpook"><code>@ahpook</code></a>)</li> <li>Many dependency updates</li> </ul> </blockquote> </details> <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/actions/dependency-review-action/commit/bbc44d14a204704ccc493733616cd1e93a0321ec"><code>bbc44d1</code></a> Merge pull request <a href="https://redirect.github.com/actions/dependency-review-action/issues/1188">#1188</a> from actions/v501</li> <li><a href="https://github.com/actions/dependency-review-action/commit/295c48fd7d5199433e846423e06c02691a162f77"><code>295c48f</code></a> Set up files for 5.0.1 release</li> <li><a href="https://github.com/actions/dependency-review-action/commit/977bcd13d3eb1fbb591c288db1115cffba6b06c9"><code>977bcd1</code></a> Merge pull request <a href="https://redirect.github.com/actions/dependency-review-action/issues/1185">#1185</a> from actions/dependabot/npm_and_yarn/fast-xml-parser...</li> <li><a href="https://github.com/actions/dependency-review-action/commit/61842ba809cdbb8c0307f3388a74db8ffff254d1"><code>61842ba</code></a> Merge pull request <a href="https://redirect.github.com/actions/dependency-review-action/issues/1182">#1182</a> from actions/ahpook/555-api-error-handling</li> <li><a href="https://github.com/actions/dependency-review-action/commit/4a8ea4ac762bd60977046709e47e32f7efe958f2"><code>4a8ea4a</code></a> Merge pull request <a href="https://redirect.github.com/actions/dependency-review-action/issues/1186">#1186</a> from actions/dependabot/npm_and_yarn/minor-updates-a...</li> <li><a href="https://github.com/actions/dependency-review-action/commit/c33d34643dda810d719146b811c53e546128b71c"><code>c33d346</code></a> Bump the minor-updates group across 1 directory with 3 updates</li> <li><a href="https://github.com/actions/dependency-review-action/commit/bc6b60f898530d498df031176316afa44ddf0762"><code>bc6b60f</code></a> Merge pull request <a href="https://redirect.github.com/actions/dependency-review-action/issues/1183">#1183</a> from actions/dependabot/github_actions/github/codeql...</li> <li><a href="https://github.com/actions/dependency-review-action/commit/a0e662b13d69052d77249d8b201248fd4b90e054"><code>a0e662b</code></a> Merge pull request <a href="https://redirect.github.com/actions/dependency-review-action/issues/1184">#1184</a> from actions/dependabot/npm_and_yarn/minor-updates-1...</li> <li><a href="https://github.com/actions/dependency-review-action/commit/dea7fcdcea402571207cc0b9994b228434c76745"><code>dea7fcd</code></a> Merge pull request <a href="https://redirect.github.com/actions/dependency-review-action/issues/1151">#1151</a> from actions/dependabot/npm_and_yarn/babel/core-7.29.7</li> <li><a href="https://github.com/actions/dependency-review-action/commit/f0c4183490714aa3aac7f3c90b8429dac8fa25f0"><code>f0c4183</code></a> Bump fast-xml-parser from 5.10.1 to 5.12.0</li> <li>Additional commits viewable in <a href="https://github.com/actions/dependency-review-action/compare/a1d282b36b6f3519aa1f3fc636f609c47dddb294...bbc44d14a204704ccc493733616cd1e93a0321ec">compare view</a></li> </ul> </details> <br /> [](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) --- <details> <summary>Dependabot commands and options</summary> <br /> You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) </details> Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> |
||
|
|
bc526683c2 |
fix(github-chat): fix initial repository import and verify UX states (#23760)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - The GitHub Code Review Bot setup wizard registers a GitHub App,
discovers its installation repositories, imports initial repository
selections, and verifies access before activation.
> - When a user or agent saves review configuration on a draft before
installing the GitHub App, the wizard skipped initial repository import
because it required `saved.revision === 0`, leaving enabled GitHub
repositories disabled in Paperclip and showing a misleading "Enable at
least one repository from the App installation." error.
> - The wizard also closed initial repository import prematurely when
GitHub returned zero repositories, failed to refresh repositories on
retry, treated removed installations (HTTP 404) as generic 422 failures
and transient repository-sync errors as empty installations, omitted the
direct GitHub App installation link on verification errors, and kept
showing "Checking GitHub access…" while idle on a failed check.
> - This pull request decouples initial repository import from review
configuration revision, recovers verifying endpoints stuck with a
pending initial import, maps removed installations and transient
repository sync errors to structured verification check codes with
validated GitHub URLs, and updates the setup verify screen to show clear
error states, accurate paired links/labels, and active retry feedback.
> - The benefit is that pre-configured GitHub review bots connect
cleanly when the App is installed, and operators get accurate error
diagnostics, direct GitHub installation and Access settings links, and
clear retry feedback when setup checks fail.
## Linked Issues or Issue Description
**What happened?**
During GitHub Code Review Bot setup
(`/apps/chat/connect?provider=github&purpose=chat&resume=...`), the
verify step failed with "Enable at least one repository from the App
installation." even when one repository was already enabled on the
GitHub App installation. The verify screen also kept displaying
"Checking GitHub access…" when idle, did not link to the GitHub App
installation URL, and did not clearly explain whether the problem was on
GitHub or in Paperclip Access settings.
**Expected behavior**
Installing the GitHub App with one or more repositories enabled should
import and enable those repositories during initial setup even if custom
review configuration was saved earlier, while preserving that saved
configuration. When verification genuinely fails for missing
repositories, missing permissions, removed/suspended installations, or
transient GitHub repository sync errors, the screen should stop polling,
replace the checking indicator with a clear error card, pair each GitHub
link with an accurate label, link to Paperclip Access settings, and show
active checking feedback only while a retry or refetch is running.
**Steps to reproduce**
1. Create a GitHub Code Review Bot draft and save custom review
configuration (`PUT /api/chat-endpoints/:id/github/configuration`),
incrementing configuration revision to `1`.
2. Register and install the GitHub App on GitHub with one repository
selected, verify webhook delivery, and link a GitHub identity.
3. Resume
`/apps/chat/connect?provider=github&purpose=chat&resume=<endpointId>`.
4. Observe that `POST /api/chat-endpoints/:id/github/setup` leaves the
repository disabled, marks `initialRepositoriesImported: true` while
leaving `initialRepositoryImportPending: true`, and returns `state:
"verify"` with "Enable at least one repository from the App
installation." and no GitHub installation link.
**Paperclip version or commit**
Reproduced on `master` at commit `e2e2265085`.
**Deployment mode**
Self-hosted server
**Agent adapter(s) involved**
Not adapter-specific (core bug)
## What Changed
- Extract initial GitHub repository import eligibility/transition logic
into `server/src/services/chat-github-initial-import.ts` and decouple
initial repository import in `server/src/services/chat-github-wizard.ts`
from `saved.revision === 0` so pre-saved review configuration no longer
blocks enabling repositories granted during initial App installation,
while keeping `saved.revision === 0` strictly for default review
configuration writes.
- Recover verifying endpoints left in the prior half-state
(`initialRepositoriesImported: true` with
`initialRepositoryImportPending: true` and `repositorySelectionSaved`
unset) without re-enabling repositories after an explicit user save
(`repositorySelectionSaved: true`).
- Keep `initialRepositoryImportPending` open when GitHub returns zero
repositories during initial import
(`server/src/services/chat-github-wizard.ts` and
`server/src/services/chat-channels/resource-reconciliation.ts`), refresh
repository inventory on wizard retry when no enabled available
repository exists, and track transient repository-sync errors so failed
`/installation/repositories` refreshes skip initial import and emit
`repositories_sync_failed` instead of misreporting
`no_installation_repositories`.
- Map HTTP 404 on `/app/installations/:id` in
`server/src/services/chat-github-management.ts` to
`installation_missing` + `managementUrl` (keeping 401/403/5xx and
transient failures separate), and enforce `!permissionsOk` precedence
(`permissions_required`) over cached repository state.
- Preserve `setup.github.managementUrl` and sibling setup fields via
atomic `jsonb_set` in
`server/src/services/chat-channels/github/app-setup.ts`.
- Centralize strict GitHub URL validation
(`safeGitHubInstallationManagementUrl`, `safeGitHubAppInstallUrl`,
`safeGitHubAppUrl`) and structured `GitHubVerificationCheckCode` values
(including `repositories_sync_failed`) in
`packages/shared/src/types/github-app-setup.ts` and
`packages/shared/src/index.ts`, with OpenAPI schema updates in
`server/src/routes/openapi.ts` and UI API types in
`ui/src/api/githubChat.ts`.
- Extract `deriveGitHubVerifyView`, `shouldPollGitHubVerify`, and
`<GitHubVerifyStatus />` into
`ui/src/pages/apps/chat/GitHubVerifyStatus.tsx` and simplify
`ui/src/pages/apps/chat/GitHubChatSetup.tsx` so verification failures
stop 5-second background polling, pair every external GitHub link with
an accurate label (including `installation_missing` fallback to
`managementUrl`), show active checking feedback only while
retrying/refetching, and link to Paperclip Access and Connection
settings.
- Add unit, integration, and UI tests in
`server/src/services/chat-github-initial-import.test.ts`,
`server/src/services/chat-github-management.test.ts`,
`server/src/__tests__/chat-channels/github-setup-and-access.integration.test.ts`,
`ui/src/pages/apps/chat/GitHubVerifyStatus.test.ts`, and
`ui/src/pages/apps/chat/GitHubChatSetup.test.tsx`.
- Update `tests/runner-e2e/source-sdk-public-inputs.json` for the shared
type and helper exports.
## Verification
Tested on Linux through revision `9a5a949098`:
- Red-green TDD proofs:
- Pre-saved review configuration and stuck verifying endpoint recovery
(`server/src/__tests__/chat-channels/github-setup-and-access.integration.test.ts`):
confirmed both failed before the wizard fix (`Received: "verify"`,
`Expected: "connected"`) and passed after.
- Removed installation HTTP 404 (`installation_missing` +
`managementUrl`) and `!permissionsOk` precedence
(`server/src/services/chat-github-management.test.ts` + integration
test): confirmed red before fix, green after.
- Transient `/installation/repositories` 503 failure with empty cache
and valid permissions (`repositories_sync_failed`, followed by
successful retry -> `connected`) and UI `installation_missing` fallback
label (`ui/src/pages/apps/chat/GitHubVerifyStatus.test.ts`,
`GitHubChatSetup.test.tsx`,
`github-setup-and-access.integration.test.ts`): confirmed red before
fix, green after.
- Server unit & OpenAPI tests on `9a5a949098`:
- `pnpm --filter @paperclipai/server exec vitest run
src/services/chat-github-management.test.ts
src/services/chat-github-initial-import.test.ts` (47/47 passed: 39
management + 8 initial-import).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/openapi-routes.test.ts` (59/59 passed).
- Server integration tests (`c1f234335f`; full suite running in CI on
merged head `9a5a949098`):
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/chat-channels/github-setup-and-access.integration.test.ts
-t "recovers from an empty initial GitHub repository inventory|keeps
explicitly disabled repositories disabled|imports GitHub App
installation repositories even when review configuration was
pre-saved|recovers a verifying endpoint whose
initialRepositoriesImported|returns installation_missing with
managementUrl when the GitHub installation is removed|surfaces a
retryable repositories_sync_failed check"` (6/6 passed).
- UI tests & typecheck on `9a5a949098`:
- `pnpm --filter @paperclipai/ui exec vitest run
src/pages/apps/chat/GitHubChatSetup.test.tsx
src/pages/apps/chat/GitHubVerifyStatus.test.ts
src/pages/apps/chat/chat-ui-contract.test.ts` (27/27 passed) and
`ui/src/lib/analytics/replay-masking.test.tsx` (236/236 passed).
- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck && pnpm --filter @paperclipai/ui
typecheck` (passed).
- `node scripts/check-token-gates.mjs` — zero violations in touched
files.
- Release registry check on `9a5a949098`:
- `node tests/runner-e2e/source-sdk-public-inputs.mjs
|
||
|
|
ff591b7d28 |
docs: add ERR_PNPM_LOCKFILE_CONFIG_MISMATCH troubleshooting note (#13690)
<!-- Write all pull request text in Simplified Technical English (ASD-STE100): short sentences, one instruction per sentence, simple approved vocabulary, and the active voice. --> ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Its `pnpm-lock.yaml` can drift out of sync with `package.json` for short windows after a merge, tracked in the recurring issue #10393. > - A contributor who clones `master` during that window gets `ERR_PNPM_LOCKFILE_CONFIG_MISMATCH` on a fresh, unmodified checkout, with no signal that this is a known platform issue and not their own mistake. > - Two examples happened within the same day (#13683, #13645) where contributors reacted to this error by hand-fixing and committing a `pnpm-lock.yaml` diff in a normal PR, which `pr.yml` then hard-fails, wasting their time twice. > - This pull request adds a short troubleshooting entry to `CONTRIBUTING.md` that names the known issue, tells the contributor how to unblock themselves safely, and tells them explicitly not to commit the lockfile diff themselves. > - The benefit is fewer confused first-time contributors and fewer accidental lockfile-diff PRs that `pr.yml` rejects. ## Linked Issues or Issue Description Refs #13689 Refs #10393 #13689 documents a fresh occurrence of the drift this note is about (`postgres@3.4.9` / `patchedDependencies` mismatch after #13643 merged), with two ready fixes (#13645, #12115) still needing a maintainer merge. #10393 is the long-running parent issue for the underlying lockfile-drift pattern. This PR does not fix the drift itself — it only makes the failure mode legible to the next contributor who hits it while a fix is in flight. ## What Changed - `CONTRIBUTING.md`: added a "Troubleshooting: `ERR_PNPM_LOCKFILE_CONFIG_MISMATCH` on a fresh clone" entry under "Tests Must Pass", explaining that a frozen-install failure on an untouched `master` checkout is usually #10393-class drift, not a local problem, with three concrete next steps (check for an existing report/refresh PR, safely unblock locally without committing the lockfile, or file a new bug report with the exact manifest field and merge SHA). ## Verification - Docs-only change; no build or test surface affected. - Rendered the added Markdown locally to confirm the list and links format correctly. - Cross-checked the guidance against `pr.yml`'s actual behavior and against `commitperclip`'s feedback on #13683 (`"You have changes to pnpm-lock.yaml — pr.yml will hard-fail this PR ... The lockfile is regenerated automatically by the refresh bot on a schedule"`), so the "do not commit the lockfile yourself" instruction matches what the bot already enforces. ## Risks Low risk. Documentation-only change, one file, no code or workflow behavior affected. Worst case is a wording nit in review. ## Model Used Claude Sonnet 5 (Anthropic), model id `claude-sonnet-5`, standard reasoning mode, with tool use (repo research via `gh`, local diff/patch construction). ## 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 (docs-only; no tests apply) - [ ] 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: Claude Sonnet 5 <noreply@anthropic.com> |
||
|
|
8abbf84fc7 |
fix(ui): stop coalescing native runner turns across consecutive agent replies (#23799)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agent chats and task threads assemble settled runs and reply bubbles through `TaskChatThread` and `ui/src/components/task-chat/transcript-adapter.ts`. > - Native Paperclip Runner turns set `standaloneHeader: true` and render an open chronological timeline (`beforeTurn`) above their reply bubble, including provider progress commentary such as "I'll check...". > - `coalesceSettledTurns` was designed for legacy collapsed "Worked" footers and merged back-to-back same-agent turns across intermediate agent bubbles, including native `standaloneHeader` turns and cross-task `send_chat_message` updates. > - When an agent completed several consecutive automated runs without an intervening user message, every earlier run's progress commentary moved off its original reply and piled up above the newest reply, making the commentary list stick to the bottom of the chat. > - `attachSettledTurns` also attached settled turns to any preceding same-agent bubble without checking anchor ownership, allowing unanchored native turns or turns with their own `finalResponse` to attach above an earlier reply or cross-task message. > - This pull request stops `coalesceSettledTurns` from merging `standaloneHeader` turns (and stops legacy coalescing across `fast_response` and `chatMessage` bubbles) and enforces explicit `anchorCommentId` ownership checks in `attachSettledTurns`. > - The benefit is that each native runner turn keeps its own commentary and timeline on its own reply bubble, while legacy collapsed footer coalescing keeps its existing behavior. ## Linked Issues or Issue Description **What happened?** In Agent Chat (and any task thread with consecutive native Paperclip Runner runs from the same agent), when an agent runs several times in a row without an intervening user message (for example, consecutive automated follow-up wakes and cross-task `send_chat_message` updates), every prior run's provider progress commentary (such as "I'll check the latest result...") is removed from its original reply and stacked together above the newest reply bubble. Whenever a new run finishes, the accumulated commentary block moves down again to the newest reply, making earlier "I'll check..." messages appear sticky at the bottom of the chat. **Expected behavior** Each native Paperclip Runner turn keeps its own chronological timeline and progress commentary attached only to its own reply bubble (or stays standalone in chronological order when unanchored). Earlier runs' commentary never accumulates or moves onto later replies. **Steps to reproduce** 1. Open a persistent Agent Chat or task thread for an agent running on the native Paperclip Runner with a provider that emits progress commentary (`channel: "progress"`). 2. Let the agent complete two or more consecutive runs without an intervening user message (for example, automated task-completion wakes with optional cross-task `send_chat_message` updates in between), with their settled transcripts loaded. 3. Observe that the earlier reply loses its own commentary and the newest reply renders every prior run's commentary stacked above its body. **Paperclip version or commit** Reproduced on `master` (commit `306437a2a5`). **Deployment mode** Self-hosted server ## What Changed - Require `anchorCommentId: string | null` on `SettledTurnMergeMeta` in `ui/src/components/task-chat/transcript-adapter.ts`, and populate it from `TaskChatThread` (`ui/src/components/TaskChatThread.tsx`) and `ui/src/components/design-sandbox/settled-preview-reply.ts`. - Update `coalesceSettledTurns` in `ui/src/components/task-chat/transcript-adapter.ts` so `standaloneHeader` (native Paperclip Runner) turns never coalesce across runs or replies, and so legacy turn coalescing stops at `origin: "fast_response"` and cross-task `chatMessage` bubbles. - Update `attachSettledTurns` in `ui/src/components/task-chat/transcript-adapter.ts` so turns carrying `finalResponse` never attach to a preceding bubble, cross-task `chatMessage` bubbles never accept an attached turn, and `standaloneHeader` turns attach only when `meta.anchorCommentId === prev.id`. - Add red-then-green regression tests in `ui/src/components/task-chat/transcript-adapter.test.ts` and `ui/src/components/TaskChatThread.test.tsx` covering consecutive native runner turns, interleaved cross-task `chatMessage` bubbles, `fast_response` boundaries, unanchored/mismatched `standaloneHeader` turns, and `finalResponse` turns. ## Verification - Confirmed red before the fix and green after the fix: - `pnpm vitest run ui/src/components/task-chat/transcript-adapter.test.ts ui/src/components/TaskChatThread.test.tsx` (failed 3 unit tests + 1 component test before the fix; passed after the fix). - `pnpm vitest run ui/src/components/task-chat/ ui/src/components/TaskChatThread.test.tsx ui/src/pages/IssueDetail.agentChatPanel.test.tsx` (30 test files passed, 962 passed, 1 skipped on latest head `13e71a2e58`). - `pnpm --filter @paperclipai/ui typecheck` (passed with 0 errors on latest head `13e71a2e58`). ## Risks Low risk. Legacy collapsed-footer turns (`standaloneHeader` falsy) keep their existing back-to-back coalescing behavior across consecutive replies from the same agent. Native `standaloneHeader` turns now remain scoped to their own reply bubble or chronological slot instead of merging across turns. ## Model Used - Google Gemini (Antigravity, high reasoning effort, with code inspection, file editing, test execution, and API diagnostics). ## 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 - [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> |
||
|
|
f23af2e079 |
Fix user attribution for agent lifecycle verification (#23800)
## Thinking Path > - Paperclip manages work for AI agents. > - An agent must pass execution checks before it can run work. > - Personal AI accounts require the identity of the responsible user. > - An environment change could start those checks without a user identity. > - The manual connection test still passed because it used the signed-in user. > - This pull request records the configuring user and repairs missing identity on an authorized retry. ## Linked Issues or Issue Description **What happened?** An agent could pass its manual connection test and stay paused after an environment change. Background verification had no responsible user and rejected access to the selected personal AI account. Retry now repeated the same failure. **Expected behavior** Verification started by a configuration change uses the configuring user. An authorized retry can repair an older operation that has no responsible user. Existing account sharing and task access checks still apply. **Steps to reproduce** 1. Use an agent with a personal AI connection and no saved lifecycle user or company default responsible user. 2. Move the agent to an environment that requires setup. 3. Run its manual connection test. The test passes under the signed-in user. 4. Observe failed background verification. Retry now does not repair the missing identity. **Paperclip version or commit** Reproduced on base commit `f0d4f6c3eb2e931f2f7a3e8b426f964aeb54aeee`. **Deployment mode** Authenticated hosted server. The local regression uses disposable PostgreSQL databases on macOS arm64, Node 25.6.1, and pnpm 9.15.4. ## What Changed - Record the authenticated responsible user when a configuration change starts a new lifecycle operation. Include the verified human context for an agent acting on behalf of a user. Keep the prior identity for changes without that context. - Pass the authenticated board identity to the existing retry command. Fill only missing responsibility; preserve an operation's recorded owner. - Start a new operation when repairing a missing identity. Repeat the host check under that identity. A prior attempt cannot complete the replacement operation. - Extend the lifecycle owner suites to cover human and delegated configuration attribution, retry repair, existing owners, active leases, readiness, and request-body spoofing. The existing board, agent, and company access checks remain covered. The lifecycle module owns the repair. Its internal store contract now accepts the authenticated retry identity. The routes supply those values after their existing authorization checks. No new API field, migration, provider policy, or credential permission is added. ## Verification - Before the fix, focused regressions failed in four cases: configuration attribution, board retry attribution, and retry identity repair with and without a lease. - The three owner suites passed all 141 tests after the fix. The final retry suite passed all 27 tests, including rejection of a stale host completion after identity repair. - Server typechecking passed with `node scripts/typecheck-layers.mjs` after the Runner and SDK build prerequisites. An initial test-only type error was corrected with the lifecycle operation type. - `pnpm verify --explain` returned exit 2 because the internal port type lies outside the resolved runtime test graph. Required CI will supply the listed broad typecheck, test, build, and end-to-end coverage. No full local suite pass is claimed. - Test budget, module boundaries, runtime push guard, whitespace, and local secret/PII checks passed. - CI found one stale mocked retry expectation in `agent-cross-tenant-authz-routes.test.ts`. It now checks the authenticated board user as well as the agent ID. All 18 tests in that suite pass locally. The interrupted native-runner CI job was stopped by a runner shutdown; the new revision will rerun CI. - Greptile reviewed the final `e5701b3584a57bbdde269b60439c561acca1f9b1` revision at 5/5. There are no unresolved review threads. - GitHub CI passed on `e5701b3584a57bbdde269b60439c561acca1f9b1`: all 68 reported checks are green, including typecheck, build, native Runner, serialized server, general tests, and end-to-end shards. [CI run](https://github.com/paperclipai/paperclip/actions/runs/47452634326). The initial canceled Runner attempt and stale mock failure are superseded by this successful run. - Hosted acceptance remains pending deployment of the reviewed revision. No live provider call is made by the regression tests. ## Risks - Identity repair does not change credential sharing. Verification still fails if the responsible user lacks access to the selected account. - An identity repair starts a replacement operation and fences any old lease. Existing plugin and host work must pass under that operation before readiness. - No schema or migration changes. Background retry behavior without an explicit user keeps the saved identity. ## Model Used - OpenAI `gpt-6.1-sol`, through the Codex harness in T3 Code, with xhigh reasoning and terminal tool access. The harness does not expose the 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> |
||
|
|
bf49fce70f |
chore(lockfile): refresh pnpm lockfiles (#23802)
## Thinking Path > - Paperclip uses a dependency lock for reproducible builds. > - Dependency changes on master need matching lock entries. > - Paid eval reports also pin a reviewed offline correction. > - Reports must install before paid model work starts. > - This automated PR keeps the lock and report proof together. ## Linked Issues or Issue Description **What happened?** Dependency manifests on master changed after the last committed lock refresh. **Expected behavior** Frozen installs must match those manifests. Eval reports must retain matching offline lock proof. **Steps to reproduce** Run a frozen install before and after this lock refresh. ## What Changed - Refresh the dependency lock from the manifests on master. - Refresh the sandbox provider lockfiles from their manifests on master. - Include the matching offline report correction and hashes. - Resync the SDK public source proof's lock pins from the refreshed lock. ## Verification - Pinned pnpm resolution completed with lifecycle scripts disabled. - The report proof refresh accepted the reviewed committed baseline. - The workflow rejected changes outside the lock and report proof files. ## Risks The lockfile bot merges this PR without CI or review when it verifies every added version on npm and all versions outside the harness allowlist are at least 3 days old. Otherwise the PR waits for a maintainer, and the daily refresh tries again. The bot merges only the exact commit this workflow generated from manifests already reviewed on master. Unknown report lock baselines remain blocked. This update changes no permissions or paid enable gates. ## Model Used None — generated by pnpm and the deterministic report-lock updater. ## Checklist - [x] Thinking path and problem description included - [x] Generated lock and matching report proof included - [x] Release-age gate decides between bot merge and maintainer review Co-authored-by: lockfile-bot <lockfile-bot@users.noreply.github.com>canary/v2026.1205.0-canary.891600 |
||
|
|
627e1be76d |
fix(db): give each database address time for a retransmitted SYN (#23784)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - The server reads and writes all state through one postgres.js pool
in `packages/db`.
> - Sentry recorded a production query failure. Every address of the
database host failed to connect: `connect ETIMEDOUT` on three IPv4
addresses and `ENETUNREACH` on three IPv6 addresses.
> - Node tries the addresses of a host name in turn ("happy eyeballs").
It gives each address except the last only 250 ms. The last address was
IPv6 and this host has no IPv6 route, so it failed at once.
> - Thus the connection failed after about 750 ms. One dropped SYN was
sufficient, because Linux sends the first SYN again only after 1 s. The
30 s `connect_timeout` of postgres.js did not apply.
> - This pull request gives each address 2 s by default, so a
retransmitted SYN can get an answer.
> - The benefit is that a short network stall to the database no longer
fails queries.
## Linked Issues or Issue Description
No public GitHub issue exists. This is a bug report.
**What happened?**
A server query failed with `Failed query: select ... from "companies"
...`. The cause was an `AggregateError` with code `ETIMEDOUT`. Its
errors were `ETIMEDOUT`, `ENETUNREACH`, `ETIMEDOUT`, `ENETUNREACH`,
`ETIMEDOUT`, `ENETUNREACH`. Each `ETIMEDOUT` came from Node's
per-address attempt timer (`internalConnectMultipleTimeout`), not from
postgres.js.
**Steps to reproduce**
1. Use a database host name that resolves to IPv4 addresses and IPv6
addresses, on a machine without an IPv6 route.
2. Make the IPv4 addresses drop SYN packets for less than one second.
3. Run a query that opens a new pooled connection.
**Expected behavior**
The connection waits for a retransmitted SYN. It fails only after
`connect_timeout`.
**Actual behavior**
The connection fails after about 750 ms with `AggregateError`
`ETIMEDOUT`.
## What Changed
- `patches/postgres@3.4.9.patch`: postgres.js now calls
`socket.connect({ port, host, autoSelectFamilyAttemptTimeout })` when
the new `auto_select_family_attempt_timeout` option is set. Without the
option, the call is the same as before. The change is in both the ESM
and CJS builds.
- `packages/db/src/client.ts`: new `connectAttemptTimeoutMs` client
option and `DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS` variable.
`resolveDatabaseClientOptions` sets a default of 2000 ms, so all pools
from `createDb` use it. `client.ts` was already longer than 1,000 lines.
This change adds the option next to the other driver options in that
file, because they share one parser and one mapping.
- `packages/db/src/postgres-connect-attempt-timeout.test.ts`: new
regression test. It examines the arguments that the patched driver gives
to `net.Socket.prototype.connect`.
- `packages/db/src/client-options.test.ts`: tests for the new variable,
its validation, the mapping and the default.
- `docs/deploy/database.md` and `doc/DATABASE.md`: document the new
variable.
- I did not commit `pnpm-lock.yaml`. The patch hash changes, and the
lockfile policy in `doc/ci-workflows.md` lets CI and the refresh
workflow update it.
## Verification
- Red, then green: `cd packages/db && npx vitest run
src/postgres-connect-attempt-timeout.test.ts`. Before the fix, both
tests failed. The driver called `connect(1, "127.0.0.1")` with no
options. After the fix, both tests pass.
- Focused: `npx vitest run src/postgres-connect-attempt-timeout.test.ts
src/client-options.test.ts src/postgres-connection-recovery.test.ts
src/client-disconnect-replay.test.ts src/client.test.ts
src/postgres-receive-buffer.test.ts`. Result: 6 files, 48 tests pass.
Some of these tests open real connections through the patched driver.
- `pnpm exec tsc --noEmit -p packages/db` passes.
- `pnpm verify` exits 2, because the postgres patch is a global CI
input. Required CI supplies the broad coverage.
- Manual reproduction on Node v24.23.0. A script overrides `dns.lookup`
to give the production address shape: three loopback IPv4 listeners with
full accept queues, which drop SYNs, and three unroutable IPv6
addresses. The listeners start to accept after 600 ms.
- Before: `AggregateError code=ETIMEDOUT after 764ms
inner=ETIMEDOUT,ENETUNREACH,ETIMEDOUT,ENETUNREACH,ETIMEDOUT,ENETUNREACH`.
This is the same as the production error.
- After, with the 2000 ms default: the listener accepted the client's
retransmitted SYN at 1.035 s, and the TCP connection opened. The stub
was not a Postgres server, so the query then stopped at the test's 3 s
`connect_timeout`.
## Risks
- Low risk. The option changes only how long Node waits for one address
before it tries the next one. `connect_timeout` still bounds the whole
attempt.
- If an IPv6 address comes first and drops packets without an error,
each new connection can wait up to 2 s before it tries IPv4, not 250 ms.
Operators can set `DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS` lower.
- Unix-socket connections (`path`) and custom `socket` factories do not
change.
- The patch hash of `postgres@3.4.9` changes. CI resolves the lockfile
for this run, and the refresh workflow commits the new lockfile after
merge.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edit and test 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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
bbb226dcbe |
fix(ui): hide mobile task composer and bottom nav while reading back (#23693)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The task page shows a chat thread with a pinned composer and a bottom navigation bar on mobile > - On a phone, these two bars use a large part of the screen when you read earlier messages > - The old task page hid the bottom navigation when you scrolled. The new chat thread scrolls inside its own container, so that behavior stopped > - This pull request makes the thread scroller drive the auto-hide mobile chrome again, and it also hides the composer > - The benefit is more reading space when you read back through a task, with the standard mobile scroll-to-dismiss behavior ## Linked Issues or Issue Description **Is your feature request related to a problem?** On mobile, the task chat page keeps the composer and the bottom navigation on screen at all times. When you scroll up to read earlier messages, these bars cover a large part of the screen. **Describe the solution you'd like** When you scroll the thread away from the latest message, the composer and the bottom navigation slide out of view. When you scroll back toward the latest message, or reach it, they slide back. When the keyboard is open, the composer stays on screen. **Describe alternatives you've considered** Hide only the bottom navigation. This gives less reading space and does not match common mobile chat apps. ## What Changed - `useMobileNavVisibility` also tracks nested scroll containers that have `data-mobile-chrome-scroll="bottom"`. It measures distance from the bottom of the thread, so the resting zone is the latest message. It ignores the viewport growth that occurs when the composer collapses, so the bars do not flicker. An open keyboard keeps the chrome visible. - `TaskMessageScroller` sets the marker attribute on the thread scroller. - `Layout` and `Layout.production` publish `data-mobile-nav` on `#main-content`. - `index.css` slides the composer dock out with a negative bottom margin and removes the bottom padding while the chrome is hidden. The motion uses the existing mobile nav motion tokens. Reduced motion makes the change instant. - `TaskChatComposerDock` measures its height on mobile as well as in the coordinator layout. The wheel forwarding stays coordinator-only. - New unit tests: `ui/src/hooks/useMobileNavVisibility.test.tsx`. - New Storybook stories: `Tasks and conversations/Task creation and lifecycle/Task chat/Mobile chrome auto-hide` (interactive, reading back, heading back), with play assertions. ## Verification - `npx vitest run ui/src/hooks/useMobileNavVisibility.test.tsx ui/src/lib/mobile-nav-scroll` passes (11 tests). - `npx vitest run ui/src/components/Layout.mobile.test.tsx ui/src/components/TaskChatThread.test.tsx ui/src/hooks/useMobileVisualViewport.test.tsx` passes (446 tests). - I ran the three stories in Storybook at 390×844. Reading back gives `data-mobile-nav="hidden"`, the nav has `data-visible="false"`, and the dock is hidden. Heading back restores all three. - Manual: open a long task on a phone, scroll up, and confirm both bars slide away. Then scroll down and confirm they return. ## Risks - Low risk. The change applies only on mobile when a task chat shell is present. Desktop and the coordinator layout keep their current behavior. - Physical iPhone touch acceptance is still needed. Momentum scroll and rubber-band behavior can differ from the browser test. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), 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> |
||
|
|
a484eb7bf8 |
build(deps): bump novita-sandbox from 1.0.3-b2 to 2.1.5 in /scripts/typecheck-sandbox-providers (#22599)
Bumps [novita-sandbox](https://novita.ai/sandbox) from 1.0.3-b2 to 2.1.5. Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> |
||
|
|
f0d4f6c3eb |
Remember model and effort in the task composer (#23698)
## Thinking Path > - Paperclip manages work for AI agents. > - People use the new-task composer to select an agent and its run settings. > - The composer remembers the last agent. A new draft opens with the agent's default model. > - People who use a different model must select it again. > - This change remembers the selected model and effort for the agent in that company. > - The next draft can use those settings as soon as the agent is selected. ## Linked Issues or Issue Description **What happened?** The new-task composer forgot the selected model when the next draft opened. It could restore an effort without restoring the model that went with it. **Expected behavior** The next new-task draft for the same agent starts with the last selected model and effort. Reset to agent default clears both choices. **Steps to reproduce** 1. Open the new-task composer and select an agent. 2. Select a different model and change the effort. 3. Close the composer and open a fresh task for the same agent. Check the model and effort. **Paperclip version or commit** Base commit: `3f882fc5895072e9a63e46df0eb0e1dad75f092b`. **Deployment mode** The regression runs in the UI component test environment. The browser preference is available in all deployment modes. ## What Changed - Save the model and effort when a person changes either value in the new-task picker. Store them in the current browser for the company, agent, and harness. - Restore the model and effort together. Keep explicit draft and task settings when present. - Share explicit effort choices and resets with conversation composers. A new-task composer uses the company-wide effort when the selected agent has no saved choices and its model supports that effort. - Keep the saved effort while model discovery is pending. When discovery confirms support, record the validated model for the next draft. A late result applies only to the draft settings that were waiting for it and preserves newer saved choices. - Cover fresh drafts, agent changes, explicit draft settings and inherited overrides, incomplete model catalogs, and reset. ## Verification - The regressions failed when a fresh composer forgot the model, when conversation composers lost the shared effort preference, and when selecting a model during discovery cleared that preference. - A reload before discovery reproduced effort loss after the initial draft had restored the effort. The regression now passes. - All 190 tests passed across the task composer, composer run settings, and recent selections suites on `d155e3e5489f8635b97e746b2d86b208ae30ed49`. - UI typecheck passed after the plugin SDK build supplied its generated declarations. - `pnpm verify` stopped before test selection because the workspace Git storage guard could not run Git. The three focused Vitest files ran directly. - GitHub CI passed on the same revision, including typecheck, build, verification, and end-to-end tests. [CI run](https://github.com/paperclipai/paperclip/actions/runs/47260521316) - The merge with master keeps recent-assignee ordering and composer preferences. All 193 focused tests and UI typecheck passed on `d8dca2d2ca6535dcab1bc2ebf2cf4c9926b37664`. GitHub CI and review are pending for this revision. ## Risks - The preference is local to the browser. If browser storage is unavailable, the composer uses the agent and draft settings. - Model access and support remain subject to validation when a run starts. ## Model Used - OpenAI GPT-6 Codex coding agent with terminal and GitHub tool access. ## 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 task ID - [x] I have run focused tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have documented the behavior in this PR - [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>canary/v2026.1205.0-canary.891200 |
||
|
|
1bbf734ce6 |
fix(connections): avoid timeouts when saving agent access (#23790)
## Thinking Path > - Paperclip manages agents and the connections they can use. > - A connection's Permissions page saves its actions and agent audience together. > - The save checks the saved profile, its agent targets, and related accounts. > - Those checks repeat database reads for each target and action. They also expand the same profile for each related account. > - On a large company, the request can time out before it reaches the save transaction. > - This change bounds that work and keeps the existing permission decisions and reauthorization boundaries. ## Linked Issues or Issue Description **What happened?** Adding an agent to an existing connection leaves the page at “Saving…” until the request fails. Refreshing shows the old audience. The browser reproduction ended with HTTP 502 at the five-minute request deadline. **Expected behavior** Save an authorized agent-audience change and return the saved permissions without repeated checks across the full company and catalog. **Steps to reproduce** Use a company with many agents, several accounts under one application, and an existing connection profile with many catalog entries. Add an agent on the connection's Permissions page. The new regression covers 40 additional agents, three accounts, and 50 actions through the assembled server and real PostgreSQL. GitHub searches found no duplicate fix. ## What Changed - Share membership and grant reads inside one authorization check. Retain the existing two-second age limit. Close the scope before the handler runs and start a fresh scope for each reauthorization. - Resolve catalog references and canonical agent target IDs in batches. Keep the ordinary target lookup outside the check scope and for other UUID spellings. Continue to decide permissions for every target. - Keep the already checked profile in each related account's permission scope without expanding that profile again. Continue to check changed profiles, gateway bindings, and the referenced accounts. - Add a save regression with SQL-count bounds and a subsequent grant-revocation refusal. Cover nested, completed, and failed authorization-check scopes. ## Verification - `cd server && pnpm run typecheck` — passed, including the test-tree layers. Repeated successfully after rebasing onto current `master`. - `cd server && pnpm exec vitest run src/__tests__/connection-management.integration.test.ts src/__tests__/connection-management-delegated-policy.integration.test.ts src/__tests__/connection-management-gateway-rules.integration.test.ts src/__tests__/connection-management-delegated-tests.integration.test.ts src/__tests__/connection-management-providers.integration.test.ts src/__tests__/connection-management-gateways.integration.test.ts src/__tests__/authorization-request-reads.test.ts` — 7 files and 110 tests passed. - After rebase, repeated both `connection-management.integration.test.ts` and `authorization-request-reads.test.ts` on head `fc8b3ecf16cc`: 2 files and 31 tests passed. The 110-test run above preceded the rebase. - Red/green: the new HTTP regression first failed on 2,218 membership reads. It now saves the requested audience, retains all 50 actions, meets the query bounds, and refuses the next request after its grant scope is restricted. - Read-only replay of the affected authorization path completed with the fix. No tenant database rows were changed by the replay. - `node scripts/check-test-budget.mjs --files server/src/__tests__/connection-management.integration.test.ts server/src/__tests__/authorization-request-reads.test.ts` — passed. - `git diff --check` and Gitleaks scan of the diff — passed. The diff was also checked for private identifiers and personal data. - `pnpm verify` selected 2,008 test files through the shared authorization dependencies. That broad local run was stopped; it is not a pass. The focused suites and server typecheck above passed. Required CI must supply the broad checks on this revision. - Final head `fc8b3ecf16cc`: [CI run](https://github.com/paperclipai/paperclip/actions/runs/47445309988) passed, including typecheck, build, all general and serialized server shards, native Runner checks, and all end-to-end shards. [Greptile review](https://github.com/paperclipai/paperclip/pull/23790#issuecomment-7426956976) scored 5/5 with no actionable issues or unresolved threads. GitHub reports the branch mergeable with a clean merge state. - The fix has not been deployed. A live browser save and refresh on the new release remain to be verified after deployment. ## Risks No schema, API, or deployment-policy change. Shared authorization code is affected. Reuse is limited to one check with the existing age limit; each pre-write reauthorization reads fresh facts. The related-account checks still include profile IDs in their permission scopes. Existing delegated, scoped-grant, company-isolation, and gateway tests pass. Revert this commit to roll back. ## Model Used OpenAI GPT-6.1 Sol (`gpt-6.1-sol`) through Codex in T3 Code, with xhigh reasoning and 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 - [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 (the public contract is unchanged; the internal boundaries and validation are recorded above) - [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> |
||
|
|
ab79cb9cdd |
fix(heartbeat): wait for an updating runtime before workspace setup fails (#23779)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Before a run starts its agent, Paperclip prepares the task workspace through a workspace provider plugin > - A hosted agent computer can apply an update. While it updates, it finishes its running tasks and refuses new workspaces > - The provider can only report this refusal as a generic `remote_incomplete` failure. Setup retries that failure two times in about 90 seconds (#23764), but an update can wait for running tasks for an hour > - So each new task on that computer fails setup, reports an error, and stops, although it only had to wait > - This pull request adds the closed provider reason `runtime_updating` and a separate wait lane for it. Setup holds the run and retries the same workspace every 2 minutes for up to 1 hour. The wait does not use the failure retry budget, and Paperclip does not report the run as a failure while the wait continues > - The benefit is that new tasks wait for an updating agent computer and then start, instead of failing ## Linked Issues or Issue Description Refs #23764, #23362 **What happened?** A hosted agent computer refused every new workspace preparation while it applied an update and finished its long running tasks. The provider reported each refusal as `remote_incomplete`. Setup failed each new run. Every retry of the same workspace failed the same way, and each failure was reported to error tracking. On one staging stack this happened 34 times in two hours, for two agents. **Expected behavior** A provider can say that the selected runtime is updating. Setup then holds the run and retries the same workspace after the update. The retry does not spend the failure budget. Paperclip reports the failure only if the wait ends without success. **Steps to reproduce** 1. Start a legacy run whose workspace preparation calls a workspace provider plugin. 2. Have the provider reject preparation because its runtime is updating. Before this change, the only fitting reason is `remote_incomplete`. 3. Setup records `workspace_storage_incomplete` and retries two times (30 s and 60 s). Then the task stops and the failure is reported, while the runtime is still updating. **Paperclip version or commit** `master` at `30334c1f03`. **Deployment mode** Hosted (Paperclip Cloud agent computers). A self-hosted workspace provider can use the same reason. ## What Changed - `packages/plugins/sdk/src/workspace-operation-error.ts`: add the closed reason `runtime_updating` ("the selected runtime is applying an update and refuses new workspaces until it finishes"). - `server/src/services/workspace-provider-failure.ts`: give `runtime_updating` a fixed, retryable message. Map it to the new setup code `workspace_runtime_updating`. Add `WORKSPACE_RUNTIME_UPDATING_RETRY` (reason `runtime_update_wait`, 30 attempts, 2 minutes apart). Add the code to `WORKSPACE_STORAGE_RETRY_CODES`, so the existing deferred error report also covers it. - `server/src/services/heartbeat/run-completion.ts` and `heartbeat/retries.ts`: schedule a failed pre-dispatch `workspace_runtime_updating` run with the wait lane, and use the lane's budget in `failedRunRetryBudgetSpent`. This is the same pattern as `runner_revision_mismatch`. - `server/src/services/execution-recovery-attempt.ts`, `modules/run-dispatch/domain/wake-context.ts`, `task-interruption-presentation.ts`: `runtime_update_wait` is an uncharged preparation wait. An answered interaction keeps its continuation through the wait, and the task shows a wait, not a failure. - `failed-preparation-retry.ts`, `legacy-execution-recovery.ts`, `recovery/service.ts`, `agent-task-run-telemetry.ts`: treat `workspace_runtime_updating` like the other transient workspace preparation codes. - `recovery/stranded-notice.ts`: add a notice for a wait that ended without success ("Agent computer was still updating"). ## Verification - Red before the change (test files only, source reverted): 9 new tests fail in `workspace-provider-failure.test.ts`, `execution-recovery-attempt.test.ts`, `heartbeat/retries.test.ts`, `heartbeat/run-completion.test.ts` and `run-failure-report-sandbox-resume.test.ts`. - `pnpm verify` did not run: its workspace link repair failed for `plugin-orchestration-smoke-example`, before test selection. The SDK change also affects many packages, so CI supplies the broad coverage. - Green after the change: the same 5 files pass (267 tests). Related files also pass: `task-interruption-automatic-path`, `task-interruption-query`, `wake-context`, `stranded-notice-remote-workspace-environment`, `task-interruption-presentation` (181 tests); `agent-task-run-telemetry`, `legacy-continuation-authority`, `heartbeat-retry-scheduling` (179 tests); plugin SDK `workspace-operation-error`, `workspace-provider` (20 tests). - `pnpm --dir server typecheck` and `pnpm --filter @paperclipai/plugin-sdk typecheck`: pass (server typecheck run with `PAPERCLIP_TYPECHECK_LOW_MEMORY=1` because of a local memory limit). - CI supplies the full suite. - Review follow-up (`cf73701742`, `d7540263bd`): update waits keep their count in `executionRetryAccounting` (`runtimeUpdateWaits`) across other retry lanes. An answered interaction whose update wait runs out is escalated like an exhausted storage wait. The pinned SDK input registry is refreshed. The two new tests failed before the fix and pass after it. `execution-recovery-attempt`, `heartbeat/retries`, `workspace-provider-failure` and `run-failure-report-sandbox-resume` pass (83 tests). `heartbeat/run-completion` and `modules/wake-queue` pass (577 tests). `tests/runner-e2e/source-sdk-public-inputs` passes (13 tests). `pnpm --dir server typecheck` passes. ## Risks - Low risk. No schema, migration, API route or wire protocol shape change. The reason set is closed and validated on both sides. An older Core that receives `runtime_updating` treats it as an unknown provider failure, as before. - A provider must not send `runtime_updating` before the new SDK is available to it. The SDK constructor rejects an unknown reason, so a provider update has to follow this change. - The wait is a bounded scheduled retry after a real refusal, not idle polling: at most 30 retries in one hour per waiting run. Each retry is one workspace preparation call. When the wait ends without success, the run is reported and the task shows a named notice with a Retry action. - Only legacy runs that fail before provider dispatch use the lane. Started and native runs keep `setup_failed`. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with tool use (code search, file edits, shell, local test execution, GitHub CLI). ## 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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
14f23fef03 |
fix(plugins): offer direct Buffer setup when Composio has no sign-in link (#23782)
## Thinking Path > - Paperclip helps people manage AI agents for work. > - Plugins lets people connect tools to their agents. > - Some tool connections use the Composio gateway. > - Buffer requires a custom OAuth app in the Composio project that serves the session. > - When that gateway returns no sign-in link, Plugins can help the user open Buffer's own MCP setup. > - This pull request opens the existing connection form with the Buffer name and endpoint filled in. ## Linked Issues or Issue Description **What happened?** Plugins showed a generic error when Composio returned no Buffer sign-in link. **Expected behavior** The user can open the direct Buffer setup from the error. For other apps, the user can open Composio's app settings. **Steps to reproduce** In Plugins, select Buffer and choose a saved Composio gateway without a configured Buffer OAuth app. Select Continue. **Additional context** [Buffer's MCP setup](https://developers.buffer.com/guides/integrations/other-ai-tools.html) accepts a Buffer API key. [Composio's Buffer setup](https://composio.dev/toolkits/buffer) requires a custom OAuth app. [Composio auth configs belong to one project](https://docs.composio.dev/kb/guide/dashboard-auth-configs-navigation). Related prior work: Refs #19408. ## What Changed - Return a machine-readable code when Composio returns no sign-in link. - Offer the direct Buffer MCP form with its official address. Offer a link to Composio app settings for other toolkits. - Clear the old sign-in link when the user requests a new one. Keep the link if the completion check fails. - Document the setup options. Refresh the shared SDK test input pins. ## Verification - Reproduced the missing-link API response with an embedded database and a Composio response fixture. The new test failed on the old server. - Passed 13 focused tests across the Composio route, Plugins setup dialog, and the MCP URL prefill flow. The replacement-link test reproduced the stale link before the fix. A second test checks that the sign-in link stays available after a failed completion check. - Sent an unauthenticated MCP initialize request to Buffer's documented endpoint and confirmed that it requires authentication. A real Buffer consent or API-key test needs a Buffer account with access. ## Risks - Low risk. The new action opens the existing MCP setup page. The user chooses the credentials and access before Paperclip creates the connection. - A valid Composio sign-in link still takes the user through Composio. ## Model Used - OpenAI GPT-6 (Codex), with repository, test, 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 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 - [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 - [ ] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
4ba596d268 |
fix(slack): recognize pre-pool Cloud stacks in managed Slack setup (#23783)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - The Slack chat connector supports managed one-click setup on
Paperclip Cloud instances when
`PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED=true` is set.
> - `createSlackManagerGrants` checked only `getCloudRuntimeIdentity()`
to detect a Cloud instance.
> - Pre-pool Cloud stacks have `isCloudManagedInstance() === true` (the
canonical Cloud predicate used by `/api/health`) but do not have a
persisted warm-pool runtime identity, so `getCloudRuntimeIdentity()`
returns `null`.
> - As a result, `/api/companies/:companyId/chat-slack/setup-options`
returned `defaultMethod: "automatic"` and `managedAvailable: false` on
those stacks, hiding managed Slack setup.
> - This pull request checks `Boolean(getCloudRuntimeIdentity()) ||
isCloudManagedInstance()` in `manager-grants.ts` and adds unit tests for
pre-pool Cloud stacks, self-hosted instances, and disabled flags.
> - The benefit is that managed Slack setup works consistently across
all Paperclip Cloud stacks while self-hosted instances remain completely
excluded.
## Linked Issues or Issue Description
**What happened?**
On a Paperclip Cloud stack without a warm-pool runtime identity record,
`GET /api/companies/:companyId/chat-slack/setup-options` returns
`{"defaultMethod":"automatic","managedAvailable":false,"workspaces":[]}`
even when `enableChatConnectors` is enabled,
`PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED=true` is set, and the Cloud
Connector Broker advertises `slack.manager`.
**Expected behavior**
Any Paperclip Cloud stack where `isCloudManagedInstance()` is `true`,
`PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED=true`, and Cloud Connector Broker
credentials are present should select `defaultMethod: "managed"` and
query the broker for `slack.manager` availability. Self-hosted instances
must continue to stay on `defaultMethod: "automatic"`.
**Steps to reproduce**
1. Run a Paperclip Cloud stack that sets
`PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN` (or `PAPERCLIP_MANAGED_CONFIG`)
without a persisted warm-pool `cloud-runtime-identity/v1` row.
2. Enable `enableChatConnectors` and set
`PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED=true` with valid
`PAPERCLIP_CLOUD_CONNECTOR_*` credentials.
3. Call `GET /api/companies/:companyId/chat-slack/setup-options`.
Observe `defaultMethod: "automatic"` and `managedAvailable: false`.
**Paperclip version or commit**
`306437a2a5` (and `7e025ae65f`)
## What Changed
- Updated `server/src/services/connectors/slack/setup/manager-grants.ts`
to compute `const isCloud = Boolean(getCloudRuntimeIdentity()) ||
isCloudManagedInstance();` instead of relying only on
`getCloudRuntimeIdentity()`.
- Added
`server/src/services/connectors/slack/setup/manager-grants.test.ts`
verifying that:
- Pre-pool Cloud stacks (`isCloudManagedInstance()` true, no runtime
identity) select `defaultMethod() === "managed"` when
`PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED=true`.
- Self-hosted instances stay on `"automatic"` even if
`PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED=true` is set.
- Cloud stacks stay on `"automatic"` when
`PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED` is not `"true"`.
## Verification
- `pnpm --filter @paperclipai/server exec vitest run
src/services/connectors/slack/setup/manager-grants.test.ts
src/__tests__/slack-development-manager.test.ts` — 11/11 passed.
- `pnpm --filter @paperclipai/server typecheck` — passed with 0 errors.
## Risks
- Low risk: `isCloudManagedInstance()` is already the canonical Cloud
predicate across the server (including `/api/health`). Self-hosted
instances never set `PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN` or
`PAPERCLIP_MANAGED_CONFIG`, and managed Slack setup still requires
`PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED=true` plus valid
`PAPERCLIP_CLOUD_CONNECTOR_*` credentials and an active broker
`slack.manager` profile.
## Model Used
- Google Gemini (Antigravity agent 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
|
||
|
|
054b4e1395 |
fix(ui): remove the Needs you description from the Inbox header (#23781)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The Inbox shows the decisions that need a person, in the "Needs you" folder > - The Inbox header shows a line under the folder tabs: "Review open requests and decide what happens next." > - This line does not give new information. It adds noise to the header. > - This pull request removes that line from the "Needs you" folder only > - The benefit is a cleaner Inbox header. Waiting and History keep their helpful descriptions. ## Linked Issues or Issue Description **Is your feature request related to a problem? Please describe.** The Inbox header shows the text "Review open requests and decide what happens next." under the folder tabs. The text repeats what the "Needs you" tab already says. **Describe the solution you'd like** Remove the text from the "Needs you" folder. Do not show an empty paragraph. **Describe alternatives you've considered** Remove the descriptions of all folders. We did not do this, because the Waiting and History descriptions explain what those folders contain. ## What Changed - `CoordinatorNeedsYou.tsx`: the "Needs you" folder has no description. The description field is now optional, and the header shows the paragraph only when the folder has a description. - `CoordinatorNeedsYou.toolbar.test.tsx`: the test checks that "Needs you" shows no description and that "Waiting" still shows its description. ## Verification - `cd ui && npx vitest run src/components/coordinator/CoordinatorNeedsYou.toolbar.test.tsx` — 13/13 pass. - Red-green: with the old component, the new assertion fails (`expected 'Review open requests and decide what …' to be null`). With the fix, it passes. - `cd ui && npx tsc --noEmit -p .` reports no errors in the changed files. ## Risks - Low risk. This is a text-only UI change in one component. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), 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: devinfoley <139239+devinfoley@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>canary/v2026.1204.0-canary.890700 |