diff --git a/doc/MCP-ACCESS-GOVERNANCE.md b/doc/MCP-ACCESS-GOVERNANCE.md index c29afa22094..c6d78bce32c 100644 --- a/doc/MCP-ACCESS-GOVERNANCE.md +++ b/doc/MCP-ACCESS-GOVERNANCE.md @@ -460,7 +460,7 @@ These are intentional gaps as of the MCP Access Governance v1 launch. Track or w | Effective profile | `GET /api/companies/:companyId/tools/profiles/effective/agents/:agentId` | Use for QA proofs and debugging selector misses. | | Policies | `GET\|POST /api/companies/:companyId/tools/policies`, `PATCH\|DELETE /api/companies/:companyId/tools/policies/:id` | Types: `allow`, `block`, `require_approval`, `rate_limit`, `trust_rule`. | | Policy dry-run | `POST /api/companies/:companyId/tools/policy/test` | Structured `{ companyId, actor, request, runContext? }` body; decision returned under `.decision`. | -| Gateway sessions | `POST /api/tool-gateway/sessions`, `POST /api/tool-gateway/sessions/:sessionId/revoke` | Board callers must supply `companyId`, `agentId`, `runId` to create and `companyId` to revoke; agent JWTs auto-fill from the token. Revocation invalidates the session immediately and emits `tool_gateway.session_revoked` without logging the raw session token. | +| Gateway sessions | `POST /api/tool-gateway/sessions`, `POST /api/tool-gateway/sessions/:sessionId/revoke` | Board callers must supply `companyId`, `agentId`, `runId` to create and `companyId` to revoke; agent JWTs auto-fill from the token. A board caller needs permission to wake the agent. A session that a person opens acts as that person: it uses that person's own personal (user-owned) grants, or asks that person to connect, and never another member's personal grant. An approval or long-running provider task started from that session runs as the same person. Approvals and tasks started before this rule shipped have no recorded opener and keep the previous behavior until they expire (15 to 60 minutes). Company-shared connections are unchanged. Revocation invalidates the session immediately and emits `tool_gateway.session_revoked` without logging the raw session token. | | Gateway calls | `POST /api/tool-gateway/tools/call` | `X-Paperclip-Tool-Gateway-Token` header; body uses `tool` + `parameters`. Approval-required calls respond `409` with `reasonCode: approval_required` and an `actionRequestId`; the agent retries with `approvedActionRequestId`. | | Action requests | `POST /api/tool-gateway/action-requests/:id/approve` | Requires `companyId` (body or query). Listing is via the audit log: filter for `tool_gateway.approval_requested`. | | Trust rules | `POST /api/companies/:companyId/tools/action-requests/:id/trust-rule`, `POST /api/companies/:companyId/tools/trust-rules/:id/revoke` | Approval-derived allow policies. | diff --git a/doc/connections/CONNECTOR-PLAYBOOK.md b/doc/connections/CONNECTOR-PLAYBOOK.md index e601ab361cd..0f13b7fb742 100644 --- a/doc/connections/CONNECTOR-PLAYBOOK.md +++ b/doc/connections/CONNECTOR-PLAYBOOK.md @@ -2177,7 +2177,17 @@ registers a client on the fly and stores it on the connection: client. - Env-registered clients always win: when `PAPERCLIP_TOOL_OAUTH__CLIENT_ID/_SECRET` are configured, the - broker uses them (`customer` ownership) and skips registration. List both + broker uses them (`customer` ownership) and skips registration. The broker + sends an env client only to the method's `defaults.tokenEndpoint`, or, when + the method has none, to a token endpoint on the exact host of its fixed + `serverUrl`, `discoveryUrl`, `metadataUrl` or `authorizationEndpoint`. Set + `defaults.tokenEndpoint` when the vendor's token endpoint is on another host. + The method must list `customer` ownership. Box, Notion, PostHog, Sentry and + Xero rely on the same-host rule today: if their discovery returns a token + endpoint on another host, a deployment-wide client is refused until the + endpoint is pinned, and a client added to the connection always works. + `client-settings.test.ts` fails when a new customer method neither pins its + token endpoint nor joins that named list. List both `customer` and `dcr` in the method's `ownershipModes` when the vendor supports both. diff --git a/doc/connections/GENERIC-REMOTE-MCP.md b/doc/connections/GENERIC-REMOTE-MCP.md index 92fd6e805a4..05b1e226768 100644 --- a/doc/connections/GENERIC-REMOTE-MCP.md +++ b/doc/connections/GENERIC-REMOTE-MCP.md @@ -158,8 +158,10 @@ You never choose this; Paperclip resolves it and the wizard shows none of it. Recorded here for security review and diagnostics. In preference order: 1. **Deployment-preconfigured client.** `PAPERCLIP_TOOL_OAUTH__CLIENT_ID` - / `_SECRET`, or the unsuffixed `PAPERCLIP_TOOL_OAUTH_CLIENT_ID` / `_SECRET`. - Always wins when set. + / `_SECRET` and the unsuffixed `PAPERCLIP_TOOL_OAUTH_CLIENT_ID` / `_SECRET` + apply only to gallery apps, at the token endpoint their app definition + fixes. A pasted server never gets a deployment client. Add a client of your + own to the connection, or use CIMD or dynamic registration. 2. **Client ID Metadata Document (CIMD).** When the authorization server advertises `client_id_metadata_document_supported`, Paperclip presents the URL of its own published metadata document as the `client_id`. Nothing is diff --git a/doc/connections/GOOGLE-WORKSPACE.md b/doc/connections/GOOGLE-WORKSPACE.md index ee64fd1b2fa..c6ceef68b63 100644 --- a/doc/connections/GOOGLE-WORKSPACE.md +++ b/doc/connections/GOOGLE-WORKSPACE.md @@ -68,9 +68,20 @@ Each service has a tool transport, set in `GOOGLE_WORKSPACE_TOOL_TRANSPORT` to Google's hosted MCP server for that service. `paperclip_rest` runs Paperclip's own tools over Google's REST APIs, in the server process (`server/src/google-workspace-rest-tools/`), with the same tool names, inputs -and results. Every service is on `google_mcp` today. A service can move to +and results. Gmail, Drive, Docs, Sheets, Slides and Calendar run on +`paperclip_rest` (since 2026-11-23), so the combined connection lists all 36 +allowlisted actions for a full read and write grant. Chat, People and Search, +which new setup does not offer, stay on `google_mcp`. A service can move to `paperclip_rest` only when Paperclip implements every tool on its allowlist; a -test enforces that. On either transport, the same grant scope checks, approvals, +test enforces that. Actions of a service on `paperclip_rest` are Paperclip's +own definitions. Agents receive them at once, also for a connection saved +before the switch, and the next catalog refresh saves them without holding +any for review. That refresh also clears the review hold of held actions, +without enabling them: actions turned Off stay Off and Ask first settings +stay, also for a held action. Only the two Gmail actions the connection never +had get the default for new actions. The setting applies only to the combined `google-workspace` +connection; saved individual product connections (for example the Gmail app) +still call Google's MCP servers directly. On either transport, the same grant scope checks, approvals, audit, token refresh and reconnection, prompt-injection screening, cancellation and experimental-feature gate apply. On `paperclip_rest`, discovery and health checks prove the token with one cheap REST read per service that the granted diff --git a/doc/memory/google-connector-memory.md b/doc/memory/google-connector-memory.md index 4cb85ab50d0..ccfc382edb0 100644 --- a/doc/memory/google-connector-memory.md +++ b/doc/memory/google-connector-memory.md @@ -12,7 +12,7 @@ Related: [production checklist](../plans/2026-11-17-google-workspace-production- [code-fix plan](../plans/2026-11-17-google-workspace-code-fixes.md), [connector doc](../connections/GOOGLE-WORKSPACE.md). -Last updated: November 18, 2026. +Last updated: November 23, 2026. ## Decisions @@ -40,6 +40,9 @@ Last updated: November 18, 2026. | Nov 17 | **Deleting a whole recurring series is refused** | Same rule as the `delete_event` decision above. | | Nov 17 | **A service is switched to REST only after a live test on the staging tester** | One service at a time. | | Nov 17 | **The gateway sets the REST result size limit** | The REST tools enforce the number the gateway passes: the gateway's MCP response limit less framing, 999,885 bytes. A result Google's MCP server could deliver is also delivered over REST. See the folder README's "Result size". | +| Nov 23 | **All six launch services switched to REST now** | Gmail, Drive, Docs, Sheets, Slides and Calendar are `paperclip_rest`. This replaces the Nov 17 "one service at a time after a live test" rule: live testing happens on the staging tester right after the switch deploys, and problems are fixed forward. Chat, People and Search stay on `google_mcp`. | +| Nov 23 | **Write actions default to "Allowed"** | No approval step by default, including actions labelled destructive. Operators can still set Ask first per action. | +| Nov 23 | **Images by public web address are allowed in Docs and Slides** | `insertInlineImage`, `replaceImage`, `createImage` and `replaceAllShapesWithImage` may use any public link. Links to Drive or Docs files stay refused (Nov 17 rule). Accepted risk: Google, not Paperclip, fetches the address, and Paperclip's own requests still go only to the allowed Google hosts. What remains is that an agent could put data in the address it chooses. Owner decision; do not restrict it. | ## What has shipped @@ -59,21 +62,21 @@ Last updated: November 18, 2026. | [#22029](https://github.com/paperclipai/paperclip/pull/22029) | Docs and Slides tools in the REST tool set (Docs 2 of 2, Slides 2 of 2). Also marks Calendar `update_event` destructive. | `f61b919701` | | [#22028](https://github.com/paperclipai/paperclip/pull/22028) | Eight Drive tools in the REST tool set (Drive 8 of 8). Also limits the Gmail host to its API path prefix (before, any path was accepted there) and requires a path prefix for every allowed host. | `ceaf574421` | -The REST tool set now covers all 36 actions. No service is switched to it. +The REST tool set covers all 36 actions, and all six services are switched to it. ### REST tools status | Service | Implemented | Switched on | | --- | --- | --- | -| Gmail | 9 of 9 | No | -| Calendar | 9 of 9 | No | -| Drive | 8 of 8 | No | -| Docs | 2 of 2 | No | -| Sheets | 6 of 6 | No | -| Slides | 2 of 2 | No | +| Gmail | 9 of 9 | Yes (Nov 23) | +| Calendar | 9 of 9 | Yes (Nov 23) | +| Drive | 8 of 8 | Yes (Nov 23) | +| Docs | 2 of 2 | Yes (Nov 23) | +| Sheets | 6 of 6 | Yes (Nov 23) | +| Slides | 2 of 2 | Yes (Nov 23) | "Switched on" means the service is `paperclip_rest` in -`GOOGLE_WORKSPACE_TOOL_TRANSPORT`. Today every service is `google_mcp`. +`GOOGLE_WORKSPACE_TOOL_TRANSPORT`. Chat, People and Search stay `google_mcp`. ### Known differences from Google's tools @@ -91,11 +94,6 @@ From the folder README (`server/src/google-workspace-rest-tools/README.md`). ## Still open -- **Images by public web address in Docs and Slides.** An edit may insert an - image from any public link, and Google then fetches that address. The - address is chosen by the agent, so it can carry data out (a leak path). - Allowed today. Recommendation: refuse it before Docs or Slides is switched - to REST. - **What we send to the reviewers.** Not decided: the new staging tester or something else. Whatever it is must use the separate Google app (below). - **Reviewer login on staging.** The broker now allows the scoped reviewer @@ -103,8 +101,9 @@ From the folder README (`server/src/google-workspace-rest-tools/README.md`). broker change is needed. - **AI-agent client and REST.** Whether an OAuth client marked for AI agents may call the REST APIs rather than MCP. The tester's client is marked for - AI agents and is wired, but it has only been used through MCP. Check on the - tester before any service is switched to REST. + AI agents and is wired, but it has only been used through MCP. The services + are switched (Nov 23); this is the first thing the live test on the tester + answers. - **Three Gmail tools are inferred.** Google's MCP reference does not list `get_draft`, `list_threads` and `search_messages`; their schemas copy the sibling tools (#22014). @@ -129,11 +128,11 @@ From the folder README (`server/src/google-workspace-rest-tools/README.md`). waits for Dotta. 2. Confirm the consent screen on the staging tester with a fresh Google account, and set the reviewer login secret. -3. Finish live acceptance on the staging tester. -4. Switch services to REST one at a time, each after its live test. -5. Revoke at Google when the last connection is removed. -6. Security scans. -7. Request revocation at Google when a company with Google connections is +3. Live-test all six services on REST on the staging tester and fix forward + (switched Nov 23). +4. Revoke at Google when the last connection is removed. +5. Security scans. +6. Request revocation at Google when a company with Google connections is deleted. ## Environments @@ -180,7 +179,8 @@ Found while testing: tester; `gmail__list_threads` and `gmail__search_messages` were missing. `gmail__get_draft` was offered live even though Google's published reference does not list it, so the reference and the live server differ. -- Write actions default to "Allowed" with no approval step. Dotta to decide. +- Write actions default to "Allowed" with no approval step. Decided Nov 23: + keep it (see "Decisions"). - The connection audit page shows internal tool names and raw ids. - The REST tools have not been run against real Google yet. @@ -306,8 +306,10 @@ Task and company deletion are hard deletes. A task deletion queues an `issue_connection_content_deletions` job that records the task's runs (including runs still working), calls and call events, including calls made without a run, before the task row goes, and runs the same steps as "Delete data". It -waits for runs and approvals that are still open, rechecking every one to -five minutes for up to a day, and then finishes on its own. It writes +waits for runs and approvals that are still open, and finishes on its own. While +it waits it only rechecks open work, every one to five minutes for up to a day; +it then runs the content steps once more. A task whose only trace is an audit +entry also gets a job. It writes `issue.connection_content_deleted` only when it deleted something, and `issue.connection_content_deletion_incomplete` when it stopped waiting with items still open. The ledger lives in `stored-object-deletion.ts` and the task diff --git a/packages/adapters/claude-local/src/server/setup-token-parse.test.ts b/packages/adapters/claude-local/src/server/setup-token-parse.test.ts index 2439e09d379..7837b192aa2 100644 --- a/packages/adapters/claude-local/src/server/setup-token-parse.test.ts +++ b/packages/adapters/claude-local/src/server/setup-token-parse.test.ts @@ -122,6 +122,36 @@ describe("parseSetupTokenPrompt", () => { expect(result?.prompt).toBe(SETUP_TOKEN_PROMPT); }); + it("keeps joining a hard-wrapped URL past a full-width row that already validates", () => { + const wrapped = hardWrap(CLAUDE_COM_URL, 64).split("\n"); + const lastRow = wrapped[wrapped.length - 1]; + expect(STATE.length - lastRow.length).toBeGreaterThanOrEqual(16); + const text = [ + PREAMBLE_LINE, + ...wrapped, + "Hold Shift while selecting to use your terminal's native copy", + PROMPT_LINE, + ].join("\n"); + const result = parseSetupTokenPrompt(text); + expect(result?.url).toBe(CLAUDE_COM_URL); + expect(result?.prompt).toBe(SETUP_TOKEN_PROMPT); + }); + + it("returns the full URL for every hard-wrap width from 40 to 200 columns", () => { + for (const url of [CLAUDE_AI_URL, CLAUDE_COM_URL]) { + for (let width = 40; width <= 200; width += 1) { + const text = [PREAMBLE_LINE, hardWrap(url, width), PROMPT_LINE].join("\n"); + expect(parseSetupTokenPrompt(text)?.url, `${url.slice(0, 20)} at ${width}`).toBe(url); + } + } + }); + + it("returns null, not a truncated URL, when a two-row wrap leaves the first row valid", () => { + const width = CLAUDE_COM_URL.length - 8; + const text = [PREAMBLE_LINE, hardWrap(CLAUDE_COM_URL, width), PROMPT_LINE].join("\n"); + expect(parseSetupTokenPrompt(text)).toBeNull(); + }); + it("returns the URL when the output arrives split across chunks", () => { // The streaming caller accumulates chunks and re-parses the whole buffer. The // chunk boundary falls inside the URL token with no line break, so the joined @@ -366,6 +396,38 @@ describe("parseSetupTokenPrompt", () => { expect(result?.prompt).toBe(SETUP_TOKEN_PROMPT); }); + it("skips the 2.1.306 login-method line after the copy hint", () => { + const rows = hardWrap(CLAUDE_COM_URL, 78) + .split("\n") + .map((row) => osc8Hyperlink(CLAUDE_COM_URL, row)); + const hint = chaSpaced("Hold Shift while selecting to use your terminal's native copy".split(" ")); + const method = chaSpaced("Login method pre-selected: Subscription Plan (Claude Pro/Max)".split(" ")); + const text = [PREAMBLE_LINE, ...rows, hint, method, PROMPT_LINE].join("\n"); + const result = parseSetupTokenPrompt(text); + expect(result?.url).toBe(CLAUDE_COM_URL); + expect(result?.prompt).toBe(SETUP_TOKEN_PROMPT); + }); + + it("skips the login-method line when no copy hint precedes it", () => { + const text = [ + PREAMBLE_LINE, + CLAUDE_COM_URL, + "Login method pre-selected: Claude account with subscription", + PROMPT_LINE, + ].join("\n"); + expect(parseSetupTokenPrompt(text)?.url).toBe(CLAUDE_COM_URL); + }); + + it.each([ + "Login method pre-selected: https://claude.com.example/x", + "Login method pre-selected: ABCD-EFGHJ:code", + "Login method pre-selected:", + "Login method selected: Subscription Plan", + ])("returns null for a malformed login-method line: %s", (line) => { + const text = [PREAMBLE_LINE, CLAUDE_COM_URL, line, PROMPT_LINE].join("\n"); + expect(parseSetupTokenPrompt(text)).toBeNull(); + }); + it("returns null when a copy hint names an unknown key", () => { const hint = "Hold Ctrl while selecting to use your terminal's native copy"; const text = [PREAMBLE_LINE, CLAUDE_COM_URL, hint, PROMPT_LINE].join("\n"); diff --git a/packages/adapters/claude-local/src/server/setup-token-parse.ts b/packages/adapters/claude-local/src/server/setup-token-parse.ts index bd538584522..b52a472c11f 100644 --- a/packages/adapters/claude-local/src/server/setup-token-parse.ts +++ b/packages/adapters/claude-local/src/server/setup-token-parse.ts @@ -188,6 +188,8 @@ const COPY_HINT_LINE_RE = /^Hold\s+(?:Shift|Option|Fn|Shift\s+\(Option\s+in\s+iT const MAX_COPY_HINT_LINES = 3; +const LOGIN_METHOD_LINE_RE = /^Login\s+method\s+pre-selected:\s+[A-Za-z][A-Za-z0-9 ()/+.,-]{0,79}$/; + // The maximum number of characters between the end of the URL preamble line and // the start of the URL. The Claude UI prints the URL right after the preamble. // The parser accepts a URL start only inside this window, so a URL far from the @@ -229,6 +231,12 @@ export function hasSetupTokenOAuthError(text: string): boolean { return /OAuth\s+error\s*:/.test(stripTerminalControls(text)); } +export function hasSetupTokenPromptLine(text: string): boolean { + return stripTerminalControls(text) + .split("\n") + .some((line) => PROMPT_LINE_RE.test(line.trim())); +} + /** * Returns true when `value` is a valid `scope` value: one to eight * space-separated tokens, a total length of at most {@link MAX_SCOPE_LENGTH}, @@ -352,22 +360,26 @@ function validateAuthUrl(candidate: string): string | null { * The parser starts at `startLine`, then joins at most {@link MAX_URL_LINES} * consecutive URL-character-only physical lines into at most {@link * MAX_URL_LENGTH} characters. It validates the joined string after each join and - * returns the first joined string that passes {@link validateAuthUrl}. A CLI that - * emits the whole URL on one line passes on the first join. A CLI that wraps the - * URL passes once the parser joins the last fragment. Returns null when no bounded - * join validates. + * returns the last joined string that passes {@link validateAuthUrl} before a + * row shorter than the first row ends the wrap. A CLI that emits the whole URL + * on one line passes on the first join. A CLI that wraps the URL passes once the + * parser joins the last fragment. Returns null when no bounded join validates. */ function reassembleUrl(lines: string[], startLine: number): SetupTokenUrlMatch | null { let joined = ""; + let firstWidth = 0; + let match: SetupTokenUrlMatch | null = null; for (let offset = 0; offset < MAX_URL_LINES && startLine + offset < lines.length; offset += 1) { const trimmed = lines[startLine + offset].trim(); if (trimmed.length === 0 || !URL_CHARS_ONLY_RE.test(trimmed)) break; + if (offset === 0) firstWidth = trimmed.length; joined += trimmed; if (joined.length > MAX_URL_LENGTH) break; const url = validateAuthUrl(joined); - if (url) return { url, endLine: startLine + offset }; + if (url) match = { url, endLine: startLine + offset }; + if (offset === 0 ? match !== null : trimmed.length < firstWidth) break; } - return null; + return match; } /** @@ -378,8 +390,10 @@ function reassembleUrl(lines: string[], startLine: number): SetupTokenUrlMatch | * parser skips a line that repeats `url`. The `claude` 2.1.291 UI also prints a * copy hint before the prompt, so the parser skips the up to {@link * MAX_COPY_HINT_LINES} non-blank lines that together match {@link - * COPY_HINT_LINE_RE}. The parser then binds the prompt on the first non-blank - * line that is not a repeat and not the copy hint. That line must match the + * COPY_HINT_LINE_RE}. The `claude` 2.1.306 UI also prints a login-method status + * line, so the parser skips a line that matches {@link LOGIN_METHOD_LINE_RE}. + * The parser then binds the prompt on the first non-blank line that is not a + * repeat, the copy hint, or the login-method line. That line must match the * exact prompt shape. Returns null when that line is not the prompt. */ function findBrowserCodePrompt(lines: string[], endLine: number, url: string): string | null { @@ -390,6 +404,7 @@ function findBrowserCodePrompt(lines: string[], endLine: number, url: string): s // punctuation first, the same way the repeated-URL comparison needs, so a // repeated URL with a trailing punctuation mark still matches. if (trimmed.replace(TRAILING_PUNCTUATION_RE, "") === url) continue; + if (LOGIN_METHOD_LINE_RE.test(trimmed)) continue; const hintEnd = copyHintEndLine(lines, i); if (hintEnd !== null) { i = hintEnd; diff --git a/packages/adapters/claude-local/src/server/setup-token-runner.test.ts b/packages/adapters/claude-local/src/server/setup-token-runner.test.ts index 8482efac1f6..4d2b953fe20 100644 --- a/packages/adapters/claude-local/src/server/setup-token-runner.test.ts +++ b/packages/adapters/claude-local/src/server/setup-token-runner.test.ts @@ -191,6 +191,41 @@ describe("runSetupTokenLogin", () => { expect(fake.disposes.count).toBe(1); }); + it("logs one fixed line when the prompt is on screen but the parser does not bind it", async () => { + const unrecognized = PROMPT_OUTPUT.replace(VALID_URL, `${VALID_URL}\nan unknown status line`); + const fake = createFakeDriver({ chunks: [unrecognized, unrecognized] }); + const logs: string[] = []; + const onPrompt = vi.fn(); + const result = await runSetupTokenLogin(fake.driver, { + onPrompt, + provideCode: async () => BROWSER_CODE, + timeoutMs: 20, + log: (line) => { + logs.push(line); + }, + }); + expect(result.outcome).toBe("timeout"); + expect(onPrompt).not.toHaveBeenCalled(); + const unrecognizedLogs = logs.filter((line) => line.includes("did not recognize the sign-in screen")); + expect(unrecognizedLogs).toHaveLength(1); + expect(logs.join("\n")).not.toContain(VALID_URL); + expect(logs.join("\n")).not.toContain("an unknown status line"); + }); + + it("does not log the unrecognized-screen line before the prompt appears", async () => { + const fake = createFakeDriver(); + const logs: string[] = []; + await runSetupTokenLogin(fake.driver, { + onPrompt: () => {}, + provideCode: async () => BROWSER_CODE, + timeoutMs: 20, + log: (line) => { + logs.push(line); + }, + }); + expect(logs.some((line) => line.includes("did not recognize the sign-in screen"))).toBe(false); + }); + it("stops the process on a cancellation", async () => { const fake = createFakeDriver(); const controller = new AbortController(); diff --git a/packages/adapters/claude-local/src/server/setup-token-runner.ts b/packages/adapters/claude-local/src/server/setup-token-runner.ts index f1d16644371..86d3c6cfccf 100644 --- a/packages/adapters/claude-local/src/server/setup-token-runner.ts +++ b/packages/adapters/claude-local/src/server/setup-token-runner.ts @@ -9,6 +9,7 @@ import { parseSetupTokenCredential, parseSetupTokenPrompt, hasSetupTokenOAuthError, + hasSetupTokenPromptLine, type SetupTokenPrompt, } from "./setup-token-parse.js"; @@ -218,6 +219,7 @@ export async function runSetupTokenLogin( } let promptSurfaced = false; + let unrecognizedPromptLogged = false; let codeSubmitted = false; let submitStarted = false; let oauthError = false; @@ -327,6 +329,10 @@ export async function runSetupTokenLogin( } return; } + if (!unrecognizedPromptLogged && hasSetupTokenPromptLine(buffer)) { + unrecognizedPromptLogged = true; + log("[paperclip] Setup-token login: the browser-code prompt is on screen, but the parser did not recognize the sign-in screen."); + } if (buffer.length > CLAUDE_SETUP_TOKEN_MAX_BUFFER_CHARS) { buffer = buffer.slice(buffer.length - CLAUDE_SETUP_TOKEN_MAX_BUFFER_CHARS); } diff --git a/packages/db/src/migrations/0502_dapper_hedge_knight.sql b/packages/db/src/migrations/0502_dapper_hedge_knight.sql new file mode 100644 index 00000000000..91d21c149f3 --- /dev/null +++ b/packages/db/src/migrations/0502_dapper_hedge_knight.sql @@ -0,0 +1,2 @@ +ALTER TABLE "tool_gateway_sessions" ADD COLUMN "created_by_user_id" text;--> statement-breakpoint +ALTER TABLE "tool_mcp_tasks" ADD COLUMN "created_by_user_id" text; \ No newline at end of file diff --git a/packages/db/src/migrations/meta/0497_snapshot.json b/packages/db/src/migrations/meta/0502_snapshot.json similarity index 99% rename from packages/db/src/migrations/meta/0497_snapshot.json rename to packages/db/src/migrations/meta/0502_snapshot.json index bc5d0bcb848..c15ccb739c1 100644 --- a/packages/db/src/migrations/meta/0497_snapshot.json +++ b/packages/db/src/migrations/meta/0502_snapshot.json @@ -1,6 +1,6 @@ { - "id": "3ea0a4c2-54f0-43fd-8c27-bcde98e3dd82", - "prevId": "82234354-6a19-4132-ae58-f545f798bbb7", + "id": "e7daf0b9-3e4a-42d7-b72a-4d7d413d9686", + "prevId": "62fdf61f-883c-4e82-a4ab-4311ff6d39e5", "version": "7", "dialect": "postgresql", "tables": { @@ -21955,6 +21955,153 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.company_workload_identity_keys": { + "name": "company_workload_identity_keys", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "key_id": { + "name": "key_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "algorithm": { + "name": "algorithm", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "public_jwk": { + "name": "public_jwk", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "private_key_material": { + "name": "private_key_material", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "status_changed_at": { + "name": "status_changed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "company_workload_identity_keys_company_key_uq": { + "name": "company_workload_identity_keys_company_key_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "key_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "company_workload_identity_keys_one_active_uq": { + "name": "company_workload_identity_keys_one_active_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"company_workload_identity_keys\".\"status\" = 'active'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "company_workload_identity_keys_one_next_uq": { + "name": "company_workload_identity_keys_one_next_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"company_workload_identity_keys\".\"status\" = 'next'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "company_workload_identity_keys_company_id_companies_id_fk": { + "name": "company_workload_identity_keys_company_id_companies_id_fk", + "tableFrom": "company_workload_identity_keys", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "company_workload_identity_keys_algorithm_check": { + "name": "company_workload_identity_keys_algorithm_check", + "value": "\"company_workload_identity_keys\".\"algorithm\" = 'ES256'" + }, + "company_workload_identity_keys_status_check": { + "name": "company_workload_identity_keys_status_check", + "value": "\"company_workload_identity_keys\".\"status\" in ('next', 'active', 'retiring', 'retired')" + } + }, + "isRLSEnabled": false + }, "public.completion_contracts": { "name": "completion_contracts", "schema": "", @@ -38923,6 +39070,169 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.issue_connection_content_deletions": { + "name": "issue_connection_content_deletions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "requested_by_actor_type": { + "name": "requested_by_actor_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "requested_by_actor_id": { + "name": "requested_by_actor_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "requested_at": { + "name": "requested_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "progress": { + "name": "progress", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "not_before": { + "name": "not_before", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "issue_connection_content_deletions_issue_idx": { + "name": "issue_connection_content_deletions_issue_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issue_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "issue_connection_content_deletions_pending_idx": { + "name": "issue_connection_content_deletions_pending_idx", + "columns": [ + { + "expression": "not_before", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"issue_connection_content_deletions\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "issue_connection_content_deletions_company_id_companies_id_fk": { + "name": "issue_connection_content_deletions_company_id_companies_id_fk", + "tableFrom": "issue_connection_content_deletions", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.issue_create_idempotency_keys": { "name": "issue_create_idempotency_keys", "schema": "", @@ -52614,6 +52924,23 @@ ], "onDelete": "set null", "onUpdate": "no action" + }, + "responsibilities_owned_area_fk": { + "name": "responsibilities_owned_area_fk", + "tableFrom": "responsibilities", + "tableTo": "responsibility_areas", + "columnsFrom": [ + "company_id", + "owner_user_id", + "area_id" + ], + "columnsTo": [ + "company_id", + "owner_user_id", + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" } }, "compositePrimaryKeys": {}, @@ -52656,6 +52983,12 @@ "primaryKey": false, "notNull": true }, + "owner_user_id": { + "name": "owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, "title": { "name": "title", "type": "text", @@ -52732,8 +53065,8 @@ "method": "btree", "with": {} }, - "responsibility_areas_company_title_uq": { - "name": "responsibility_areas_company_title_uq", + "responsibility_areas_identity_uq": { + "name": "responsibility_areas_identity_uq", "columns": [ { "expression": "company_id", @@ -52741,6 +53074,39 @@ "asc": true, "nulls": "last" }, + { + "expression": "owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_areas_owner_title_uq": { + "name": "responsibility_areas_owner_title_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, { "expression": "lower(\"title\")", "asc": true, @@ -53043,6 +53409,12 @@ "primaryKey": false, "notNull": false }, + "skill_id": { + "name": "skill_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, "created_at": { "name": "created_at", "type": "timestamp with time zone", @@ -53133,6 +53505,28 @@ "method": "btree", "with": {} }, + "responsibility_links_responsibility_skill_uq": { + "name": "responsibility_links_responsibility_skill_uq", + "columns": [ + { + "expression": "responsibility_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "skill_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"responsibility_links\".\"skill_id\" is not null", + "concurrently": false, + "method": "btree", + "with": {} + }, "responsibility_links_project_idx": { "name": "responsibility_links_project_idx", "columns": [ @@ -53177,6 +53571,21 @@ "concurrently": false, "method": "btree", "with": {} + }, + "responsibility_links_skill_idx": { + "name": "responsibility_links_skill_idx", + "columns": [ + { + "expression": "skill_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} } }, "foreignKeys": { @@ -53244,6 +53653,19 @@ ], "onDelete": "cascade", "onUpdate": "no action" + }, + "responsibility_links_skill_id_company_skills_id_fk": { + "name": "responsibility_links_skill_id_company_skills_id_fk", + "tableFrom": "responsibility_links", + "tableTo": "company_skills", + "columnsFrom": [ + "skill_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" } }, "compositePrimaryKeys": {}, @@ -53252,7 +53674,7 @@ "checkConstraints": { "responsibility_links_single_target_check": { "name": "responsibility_links_single_target_check", - "value": "(\"responsibility_links\".\"project_id\" is not null)::int + (\"responsibility_links\".\"issue_id\" is not null)::int + (\"responsibility_links\".\"routine_id\" is not null)::int = 1" + "value": "(\"responsibility_links\".\"project_id\" is not null)::int + (\"responsibility_links\".\"issue_id\" is not null)::int + (\"responsibility_links\".\"routine_id\" is not null)::int + (\"responsibility_links\".\"skill_id\" is not null)::int = 1" } }, "isRLSEnabled": false @@ -57529,6 +57951,114 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.stored_object_deletions": { + "name": "stored_object_deletions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "log_store": { + "name": "log_store", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "object_key": { + "name": "object_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "not_before": { + "name": "not_before", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "stored_object_deletions_due_idx": { + "name": "stored_object_deletions_due_idx", + "columns": [ + { + "expression": "not_before", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "stored_object_deletions_company_idx": { + "name": "stored_object_deletions_company_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.summary_slots": { "name": "summary_slots", "schema": "", @@ -61070,6 +61600,12 @@ "primaryKey": false, "notNull": false }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, "token_hash": { "name": "token_hash", "type": "text", @@ -63514,6 +64050,12 @@ "primaryKey": false, "notNull": false }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, "identity_context_id": { "name": "identity_context_id", "type": "uuid", diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index 2e48d538cf6..b0b07864814 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -3501,6 +3501,13 @@ "when": 1795444424088, "tag": "0501_charming_living_lightning", "breakpoints": true + }, + { + "idx": 502, + "version": "7", + "when": 1795451480643, + "tag": "0502_dapper_hedge_knight", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/issue_connection_content_deletions.ts b/packages/db/src/schema/issue_connection_content_deletions.ts index 2586628dfe0..9d4c2534507 100644 --- a/packages/db/src/schema/issue_connection_content_deletions.ts +++ b/packages/db/src/schema/issue_connection_content_deletions.ts @@ -8,7 +8,7 @@ export const issueConnectionContentDeletions = pgTable( id: uuid("id").primaryKey().defaultRandom(), companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), issueId: uuid("issue_id").notNull(), - scope: jsonb("scope").$type<{ runIds: string[]; invocationIds: string[]; eventIds?: string[] }>().notNull(), + scope: jsonb("scope").$type<{ runIds: string[]; invocationIds: string[]; eventIds?: string[]; createdAfter?: string | null }>().notNull(), status: text("status").$type<"pending" | "completed">().notNull().default("pending"), requestedByActorType: text("requested_by_actor_type").notNull(), requestedByActorId: text("requested_by_actor_id"), diff --git a/packages/db/src/schema/tool_access.ts b/packages/db/src/schema/tool_access.ts index 095bc4f630a..48f97a23b95 100644 --- a/packages/db/src/schema/tool_access.ts +++ b/packages/db/src/schema/tool_access.ts @@ -716,6 +716,7 @@ export const toolGatewaySessions = pgTable( clientName: text("client_name"), mcpSessionId: text("mcp_session_id"), correlationId: text("correlation_id"), + createdByUserId: text("created_by_user_id"), tokenHash: text("token_hash").notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), lastUsedAt: timestamp("last_used_at", { withTimezone: true }), @@ -918,6 +919,7 @@ export const toolMcpTasks = pgTable( actorId: text("actor_id"), /** The person whose grant applied, and the run identity, so background checks see the same caller. */ responsibleUserId: text("responsible_user_id"), + createdByUserId: text("created_by_user_id"), identityContextId: uuid("identity_context_id"), catalogToolName: text("catalog_tool_name").notNull(), /** Endpoint, tool, and full arguments; a call attaches only on an exact match. */ diff --git a/packages/shared/src/app-definitions/asana.json b/packages/shared/src/app-definitions/asana.json index 4cc2859043a..42d051d84a5 100644 --- a/packages/shared/src/app-definitions/asana.json +++ b/packages/shared/src/app-definitions/asana.json @@ -55,6 +55,7 @@ "defaults": { "serverUrl": "https://mcp.asana.com/v2/mcp", "discoveryUrl": "https://mcp.asana.com/.well-known/oauth-protected-resource/v2", + "tokenEndpoint": "https://app.asana.com/-/oauth_token", "scopesHint": [ "default" ] diff --git a/packages/shared/src/app-definitions/google.json b/packages/shared/src/app-definitions/google.json index f0da4ff3af0..f0bab046761 100644 --- a/packages/shared/src/app-definitions/google.json +++ b/packages/shared/src/app-definitions/google.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "slug": "google", - "name": "Google", + "name": "Google Antigravity and Gemini", "description": "Connect Google Antigravity accounts or Gemini API keys for your agents.", "categories": [ "ai" diff --git a/packages/shared/src/app-definitions/railway.json b/packages/shared/src/app-definitions/railway.json index 96193b680a1..11cd0177e4a 100644 --- a/packages/shared/src/app-definitions/railway.json +++ b/packages/shared/src/app-definitions/railway.json @@ -33,7 +33,8 @@ ], "oauthAuthorizationParams": { "prompt": "consent" - } + }, + "tokenEndpoint": "https://backboard.railway.com/oauth/token" }, "guidanceMd": "Sign in to Railway and select the workspaces your agents may use. Paperclip adds direct service, deployment, and bounded log tools when Railway accepts the connection for API access. Container commands require the separate SSH setup on the connection. Project tokens are not supported by Railway's hosted connection.", "riskTier": "S4", diff --git a/packages/shared/src/google-workspace-connectors.test.ts b/packages/shared/src/google-workspace-connectors.test.ts index 0021bf50e20..26316900a50 100644 --- a/packages/shared/src/google-workspace-connectors.test.ts +++ b/packages/shared/src/google-workspace-connectors.test.ts @@ -172,10 +172,14 @@ describe("combined Google Workspace consent", () => { expect(isGoogleWorkspaceToolGranted("gmail__send_message", profiles["workspace.all"].scopes)).toBe(false); }); - it("sends every service to Google's MCP servers by default and reports the transport on each target", () => { + it("runs the six launch services on Paperclip's REST tools, keeps the others on Google's MCP servers, and reports the transport on each target", () => { expect(Object.keys(GOOGLE_WORKSPACE_TOOL_TRANSPORT).sort()).toEqual(Object.keys(GOOGLE_WORKSPACE_SERVICES).sort()); - expect(new Set(Object.values(GOOGLE_WORKSPACE_TOOL_TRANSPORT))).toEqual(new Set(["google_mcp"])); - expect(googleWorkspaceToolTarget("gmail__get_message")?.transport).toBe("google_mcp"); + expect(GOOGLE_WORKSPACE_TOOL_TRANSPORT).toEqual({ + gmail: "paperclip_rest", drive: "paperclip_rest", docs: "paperclip_rest", sheets: "paperclip_rest", + slides: "paperclip_rest", calendar: "paperclip_rest", chat: "google_mcp", people: "google_mcp", search: "google_mcp", + }); + expect(googleWorkspaceToolTarget("gmail__get_message")?.transport).toBe("paperclip_rest"); + expect(googleWorkspaceToolTarget("chat__list_messages")?.transport).toBe("google_mcp"); expect(googleWorkspaceServiceToolNames("docs")).toEqual(["read_doc", "update_doc"]); }); diff --git a/packages/shared/src/google-workspace-connectors.ts b/packages/shared/src/google-workspace-connectors.ts index 270fbd40c0f..88d942d1e66 100644 --- a/packages/shared/src/google-workspace-connectors.ts +++ b/packages/shared/src/google-workspace-connectors.ts @@ -136,8 +136,8 @@ export type GoogleWorkspaceService = keyof typeof GOOGLE_WORKSPACE_SERVICES; export type GoogleWorkspaceToolTransport = "google_mcp" | "paperclip_rest"; export const GOOGLE_WORKSPACE_TOOL_TRANSPORT: Record = { - gmail: "google_mcp", drive: "google_mcp", docs: "google_mcp", sheets: "google_mcp", - slides: "google_mcp", calendar: "google_mcp", chat: "google_mcp", + gmail: "paperclip_rest", drive: "paperclip_rest", docs: "paperclip_rest", sheets: "paperclip_rest", + slides: "paperclip_rest", calendar: "paperclip_rest", chat: "google_mcp", people: "google_mcp", search: "google_mcp", }; diff --git a/packages/shared/src/types/tool-access.ts b/packages/shared/src/types/tool-access.ts index dd1cfc8b5e3..95a5673f5b9 100644 --- a/packages/shared/src/types/tool-access.ts +++ b/packages/shared/src/types/tool-access.ts @@ -1282,6 +1282,8 @@ export interface ConnectToolAppAuthChallenge { resource?: string | null; registrationSource?: ToolOAuthClientRegistrationSource | null; manualClientRequired?: boolean; + /** Plain-language reason shown with the client fields, when Paperclip has one. */ + manualClientReason?: string | null; } /** Public half of a key Paperclip holds for machine sign-in. Safe to show and share. */ @@ -1733,6 +1735,7 @@ export interface ToolAccessDecisionInput { clientSubjectId?: string | null; clientName?: string | null; externalClient?: boolean | null; + sessionOpenedByUserId?: string | null; } | null; request: { applicationId?: string | null; diff --git a/scripts/ingest-app-definitions.mjs b/scripts/ingest-app-definitions.mjs index 05d997338f1..96af5ceb254 100644 --- a/scripts/ingest-app-definitions.mjs +++ b/scripts/ingest-app-definitions.mjs @@ -232,6 +232,7 @@ const apps = [ serverUrl: "https://mcp.railway.com", scopesHint: ["openid", "offline_access", "workspace:member"], oauthAuthorizationParams: { prompt: "consent" }, + tokenEndpoint: "https://backboard.railway.com/oauth/token", }, "S4", "Sign in to Railway and select the workspaces your agents may use. Paperclip adds direct service, deployment, and bounded log tools when Railway accepts the connection for API access. Container commands require the separate SSH setup on the connection. Project tokens are not supported by Railway's hosted connection.", @@ -1251,6 +1252,7 @@ const specialMethodsFor = (entry) => { defaults: { serverUrl: entry.serverUrl, discoveryUrl: "https://mcp.asana.com/.well-known/oauth-protected-resource/v2", + tokenEndpoint: "https://app.asana.com/-/oauth_token", scopesHint: ["default"], }, oauthClientSecretRequired: true, diff --git a/server/scripts/migrate-skill-packages.ts b/server/scripts/migrate-skill-packages.ts index 7f761cf5afc..8d30219357b 100644 --- a/server/scripts/migrate-skill-packages.ts +++ b/server/scripts/migrate-skill-packages.ts @@ -38,4 +38,6 @@ try { const result = await action({ apply, writersStopped: process.argv.includes("--writers-stopped"), clearLegacy: process.argv.includes("--clear-legacy"), limit, after: value("--after"), companyId: value("--company") }); console.log(JSON.stringify({ phase, apply, ...result })); + if (phase === "runtime-assets" && (result as Awaited>).results + .some(row => row.status === "unsaved")) process.exitCode = 1; } finally { await db.$client.end({ timeout: 1 }); } diff --git a/server/src/__tests__/ai-legacy-compatibility.test.ts b/server/src/__tests__/ai-legacy-compatibility.test.ts index 7264ccf77e0..1c9f5409c97 100644 --- a/server/src/__tests__/ai-legacy-compatibility.test.ts +++ b/server/src/__tests__/ai-legacy-compatibility.test.ts @@ -198,6 +198,25 @@ it("enforces local attempt ownership, company, target, cancellation, and expiry" expect(row.status).toBe("timed_out"); }); +it("tells the owner why an ended attempt stopped instead of calling every one expired", async () => { + vi.stubGlobal("fetch", vi.fn(async () => new Response("{}"))); + const ownCompany = randomUUID(); + await db.insert(companies).values({ id: ownCompany, name: "Ended attempts", issuePrefix: "END" }); + await db.insert(companyMemberships).values({ companyId: ownCompany, principalId: owner, principalType: "user", status: "active", membershipRole: "owner" }); + const login = localAiLoginService(db); + const replacedMessage = "This sign-in attempt was cancelled or replaced by a newer one. Start sign-in again."; + const first = await login.start(ownCompany, owner, loginIntent()); + const retry = await login.start(ownCompany, owner, loginIntent(), true); + expect(await login.check(ownCompany, owner, loginIntent(), first.sessionId)).toEqual({ status: "expired", error: replacedMessage }); + await login.cancel(ownCompany, owner, retry.sessionId); + expect(await login.check(ownCompany, owner, loginIntent(), retry.sessionId)).toEqual({ status: "expired", error: replacedMessage }); + const completed = await login.start(ownCompany, owner, loginIntent()); + await writeFile(path.join(directoryFor(completed.sessionId), "auth.json"), auth("completed-login")); + await login.complete(ownCompany, owner, completed.sessionId, loginIntent()); + expect(await login.check(ownCompany, owner, loginIntent(), completed.sessionId)) + .toEqual({ status: "expired", error: "This sign-in already connected the account." }); +}); + it("explicit retry replaces another owned local attempt while ordinary navigation preserves it", async () => { const login = localAiLoginService(db); const first = await login.start(companyId, owner, loginIntent()); diff --git a/server/src/__tests__/generic-mcp-connection.test.ts b/server/src/__tests__/generic-mcp-connection.test.ts index 76c00292fc0..ae85753be94 100644 --- a/server/src/__tests__/generic-mcp-connection.test.ts +++ b/server/src/__tests__/generic-mcp-connection.test.ts @@ -2281,9 +2281,10 @@ describeEmbeddedPostgres("generic remote MCP connections", () => { expect(fixture.requestsTo("/register")).toHaveLength(1); }); - it("prefers a deployment-preconfigured client over any registration", async () => { - const fixture = installMcpOAuthFixture({ auth: "oauth", cimd: true }); + it("never offers a deployment-wide client to a custom server", async () => { + installMcpOAuthFixture({ auth: "oauth", cimd: true }); vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_ID", "preconfigured-client"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_SECRET", "preconfigured-secret"); const company = await createCompany(db); const service = toolAccessService(db); @@ -2293,9 +2294,45 @@ describeEmbeddedPostgres("generic remote MCP connections", () => { actor: { actorType: "user", actorId: "board-user" }, }); - expect(start.registrationSource).toBe("preconfigured"); - expect(new URL(start.authorizationUrl).searchParams.get("client_id")).toBe("preconfigured-client"); - expect(fixture.requestsTo("/register")).toHaveLength(0); + expect(start.registrationSource).not.toBe("preconfigured"); + expect(new URL(start.authorizationUrl).searchParams.get("client_id")).not.toBe("preconfigured-client"); + }); + + it("explains that a deployment-wide client cannot be used when a custom server has no other client", async () => { + installMcpOAuthFixture({ auth: "oauth", dcr: false }); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_ID", "preconfigured-client"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_SECRET", "preconfigured-secret"); + const company = await createCompany(db); + const service = toolAccessService(db); + + const connected = await service.connectGalleryApp(company.id, { link: MCP_URL, name: "Fixture refused deployment client" }); + await expect(service.startOAuth(company.id, connected.connectionId, { + redirectUri: REDIRECT_URI, + actor: { actorType: "user", actorId: "board-user" }, + })).rejects.toMatchObject({ details: { code: "oauth_manual_client_required", reason: expect.stringContaining("Add a client ID and secret") } }); + }); + + it("keeps the draft and asks for a client, with the reason, when a deployment-wide client cannot be used", async () => { + installMcpOAuthFixture({ auth: "oauth", dcr: false }); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_ID", "preconfigured-client"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_SECRET", "preconfigured-secret"); + const company = await createCompany(db); + const app = createRouteApp(db); + vi.stubEnv("PAPERCLIP_PUBLIC_URL", PUBLIC_BASE_URL); + + const response = await request(app) + .post(`/api/companies/${company.id}/tools/apps/connect`) + .send({ link: MCP_URL, name: "Fixture refused deployment client" }) + .expect(201); + + expect(response.body.connectionId).toEqual(expect.any(String)); + expect(response.body.auth).toMatchObject({ + kind: "oauth", + startUrl: null, + manualClientRequired: true, + manualClientReason: expect.stringContaining("Add a client ID and secret"), + }); + await expect(db.select().from(toolConnections)).resolves.toHaveLength(1); }); it("asks for a preregistered client when the server offers neither CIMD nor DCR", async () => { diff --git a/server/src/__tests__/google-workspace-injection-screening.test.ts b/server/src/__tests__/google-workspace-injection-screening.test.ts index 3a7cb32e5da..a4c61a2364e 100644 --- a/server/src/__tests__/google-workspace-injection-screening.test.ts +++ b/server/src/__tests__/google-workspace-injection-screening.test.ts @@ -10,7 +10,7 @@ import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { createDb, companies, companyMemberships, agents, issues, heartbeatRuns, toolApplications, toolConnections, connectionGrants, toolCatalogEntries, toolConnectionInstalls, toolPolicies, toolInvocations, toolActionRequests, toolProfiles, toolProfileEntries, promptInjectionInvocations } from "@paperclipai/db"; -import { PROMPT_INJECTION_DEFAULT_MODEL } from "@paperclipai/shared"; +import { GOOGLE_WORKSPACE_TOOL_TRANSPORT, PROMPT_INJECTION_DEFAULT_MODEL } from "@paperclipai/shared"; import { createToolGatewayService } from "../services/tool-gateway.js"; import { mcpGatewayProtocolRoutes } from "../routes/tool-gateway.js"; import { initializeRunIdentity } from "../services/run-identity.js"; @@ -37,11 +37,13 @@ function googleResult(body: string) { } const support = await getEmbeddedPostgresTestSupport(); -(support.supported ? describe : describe.skip)("Google Workspace results pass the prompt-injection guard", () => { +(support.supported ? describe : describe.skip)("Google Workspace results from Google's MCP servers pass the prompt-injection guard", () => { let db: ReturnType; let database: Awaited>; let home: string; + const savedTransport = { ...GOOGLE_WORKSPACE_TOOL_TRANSPORT }; beforeAll(async () => { + for (const service of Object.keys(GOOGLE_WORKSPACE_TOOL_TRANSPORT) as Array) GOOGLE_WORKSPACE_TOOL_TRANSPORT[service] = "google_mcp"; home = await realpath(await mkdtemp(path.join(os.tmpdir(), "paperclip-google-guard-"))); vi.stubEnv("PAPERCLIP_HOME", home); database = await startEmbeddedPostgresTestDatabase("paperclip-google-guard-db-"); @@ -49,6 +51,7 @@ const support = await getEmbeddedPostgresTestSupport(); await instanceSettingsService(db).updateExperimental({ enableGoogleWorkspaceConnector: true }); }, 90_000); afterAll(async () => { + Object.assign(GOOGLE_WORKSPACE_TOOL_TRANSPORT, savedTransport); await database?.cleanup(); vi.unstubAllEnvs(); if (home) await rm(home, { recursive: true, force: true }); diff --git a/server/src/__tests__/google-workspace-rest-transport.test.ts b/server/src/__tests__/google-workspace-rest-transport.test.ts index c800dddc13f..590ddfbc08b 100644 --- a/server/src/__tests__/google-workspace-rest-transport.test.ts +++ b/server/src/__tests__/google-workspace-rest-transport.test.ts @@ -1,9 +1,9 @@ import { randomUUID } from "node:crypto"; -import { and, eq } from "drizzle-orm"; +import { and, eq, inArray } from "drizzle-orm"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import { agents, companies, companyMemberships, connectionGrants, createDb, heartbeatRuns, issues, - toolAccessAuditEvents, toolActionRequests, toolInvocations, + toolAccessAuditEvents, toolActionRequests, toolCallEvents, toolCatalogEntries, toolInvocations, } from "@paperclipai/db"; import { GOOGLE_WORKSPACE_DEFAULT_SELECTION, GOOGLE_WORKSPACE_TOOL_TRANSPORT, googleWorkspaceServiceToolNames, @@ -50,9 +50,43 @@ function gmailMessage(body: string) { }; } +const REST_HOSTS = new Set(["gmail.googleapis.com", "www.googleapis.com", "docs.googleapis.com", "sheets.googleapis.com", "slides.googleapis.com"]); + +function googleDocument(text: string) { + return { + documentId: "doc1", title: "Plan", revisionId: "rev-1", + tabs: [{ tabProperties: { tabId: "t.0", title: "Tab 1", index: 0 }, documentTab: { body: { content: [ + { endIndex: 1, sectionBreak: {} }, + { startIndex: 1, endIndex: text.length + 2, paragraph: { elements: [{ startIndex: 1, endIndex: text.length + 2, textRun: { content: `${text}\n` } }] } }, + ] } } }], + }; +} + const MCP_TOOLS: Record = { "gmailmcp.googleapis.com": ["get_message", "search_threads", "create_draft"], - "docsmcp.googleapis.com": ["read_doc"], + "docsmcp.googleapis.com": ["read_doc", "update_doc"], +}; + +const GOOGLE_MCP_SCHEMAS: Record> = { + read_doc: { + type: "object", + properties: { documentId: { type: "string" }, commentsIncluded: { type: "boolean" } }, + required: ["documentId"], + }, + update_doc: { + type: "object", + properties: { + documentId: { type: "string" }, + requests: { type: "array", items: { type: "object" } }, + writeControl: { type: "object", properties: { requiredRevisionId: { type: "string" }, targetRevisionId: { type: "string" } } }, + }, + required: ["documentId", "requests"], + }, + get_message: { + type: "object", + properties: { messageId: { type: "string" }, messageFormat: { type: "string", enum: ["MINIMAL", "FULL_CONTENT", "METADATA_ONLY"] } }, + required: ["messageId"], + }, }; const support = await getEmbeddedPostgresTestSupport(); @@ -81,7 +115,7 @@ const support = await getEmbeddedPostgresTestSupport(); GOOGLE_WORKSPACE_TOOL_TRANSPORT[service] = transport; } - async function connectWorkspace(options: { permissions?: string[]; askFirst?: string[] } = {}) { + async function connectWorkspace(options: { permissions?: string[]; askFirst?: string[]; off?: string[] } = {}) { const permissions = (options.permissions ?? ["gmail.readonly", "gmail.compose", "documents.readonly"]).map(scope); const [company] = await db.insert(companies).values({ name: `Google REST ${randomUUID()}`, issuePrefix: `GR${randomUUID().slice(0, 6).toUpperCase()}` }).returning(); const userId = `google-rest-${randomUUID()}`; @@ -105,18 +139,33 @@ const support = await getEmbeddedPostgresTestSupport(); revoke: vi.fn(async () => undefined), } as unknown as PaperclipCloudConnector; - const gmailRequests: Array<{ method: string; path: string; authorization: string | null; signal: AbortSignal | null }> = []; + const restRequests: Array<{ method: string; host: string; path: string; authorization: string | null; signal: AbortSignal | null }> = []; const mcpRequests: string[] = []; - let gmailOverride: ((url: URL, init: RequestInit) => Response | Promise | undefined) | undefined; + let restOverride: ((url: URL, init: RequestInit) => Response | Promise | undefined) | undefined; let messageBody = BENIGN_BODY; let mcpCallOverride: ((init: RequestInit) => Promise | undefined) | undefined; const remoteHttpRequest = vi.fn(async (href: string, init: RequestInit) => { const url = new URL(href); - if (url.hostname === "gmail.googleapis.com" || url.hostname === "www.googleapis.com") { - gmailRequests.push({ method: init.method ?? "GET", path: url.pathname, authorization: new Headers(init.headers).get("authorization"), signal: init.signal ?? null }); - const overridden = await gmailOverride?.(url, init); + if (REST_HOSTS.has(url.hostname)) { + restRequests.push({ method: init.method ?? "GET", host: url.hostname, path: url.pathname, authorization: new Headers(init.headers).get("authorization"), signal: init.signal ?? null }); + const overridden = await restOverride?.(url, init); if (overridden) return overridden; - if (url.pathname === "/calendar/v3/users/me/calendarList") return Response.json({ items: [{ id: "primary" }] }); + if (url.pathname === "/calendar/v3/users/me/calendarList") return Response.json({ items: [{ id: "primary", summary: "Team" }] }); + if (url.pathname === "/calendar/v3/calendars/primary/events" && init.method === "POST") { + return Response.json({ id: "event1", status: "confirmed", summary: "Planning", start: { dateTime: "2026-11-24T10:00:00Z" }, end: { dateTime: "2026-11-24T10:30:00Z" } }); + } + if (url.pathname === "/drive/v3/about") return Response.json({ kind: "drive#about" }); + if (url.pathname === "/gmail/v1/users/me/threads") return Response.json({ threads: [], resultSizeEstimate: 0 }); + if (url.pathname === "/drive/v3/files/file1") return Response.json({ id: "file1", name: "Plan", mimeType: "text/plain" }); + if (/^(\/upload)?\/drive\/v3\/files$/.test(url.pathname) && init.method === "POST") return Response.json({ id: "file2", name: "Notes", mimeType: "application/vnd.google-apps.folder" }); + if (url.pathname === "/v1/documents/doc1") return Response.json(googleDocument(BENIGN_BODY)); + if (url.pathname === "/v1/documents/doc1:batchUpdate") return Response.json({ documentId: "doc1", replies: [{}], writeControl: { requiredRevisionId: "rev-2" } }); + if (url.pathname.startsWith("/v4/spreadsheets/sheet1/values/") && init.method === "PUT") { + return Response.json({ spreadsheetId: "sheet1", updatedRange: "Sheet1!A1:B1", updatedRows: 1, updatedColumns: 2, updatedCells: 2 }); + } + if (url.pathname.startsWith("/v4/spreadsheets/sheet1/values/")) return Response.json({ range: "Sheet1!A1:B1", majorDimension: "ROWS", values: [["Owner", "Sam"]] }); + if (url.pathname === "/v1/presentations/deck1:batchUpdate") return Response.json({ presentationId: "deck1", replies: [{}], writeControl: { requiredRevisionId: "rev-2" } }); + if (url.pathname === "/v1/presentations/deck1") return Response.json({ presentationId: "deck1", title: "Deck", revisionId: "rev-1", slides: [] }); if (url.pathname === "/calendar/v3/calendars/primary/events") return Response.json({ items: [] }); if (url.pathname === "/calendar/v3/freeBusy") return Response.json({ calendars: { primary: { busy: [] } } }); if (url.pathname === "/gmail/v1/users/me/profile") return Response.json({ emailAddress: "owner@example.test", messagesTotal: 1 }); @@ -132,7 +181,9 @@ const support = await getEmbeddedPostgresTestSupport(); const result = body.method === "initialize" ? { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "google-fixture", version: "1" } } : body.method === "tools/list" - ? { tools: (MCP_TOOLS[url.hostname] ?? []).map((name) => ({ name, inputSchema: { type: "object", properties: {} }, annotations: { readOnlyHint: name !== "create_draft" } })) } + ? { tools: (MCP_TOOLS[url.hostname] ?? []).map((name) => ({ name, description: `Google's ${name}.`, + inputSchema: GOOGLE_MCP_SCHEMAS[name] ?? { type: "object", properties: {} }, + annotations: { readOnlyHint: name !== "create_draft" && name !== "update_doc" } })) } : { content: [{ type: "text", text: "ok from Google MCP" }] }; return Response.json({ jsonrpc: "2.0", id: body.id, result }); }); @@ -154,7 +205,7 @@ const support = await getEmbeddedPostgresTestSupport(); const [agent] = await db.insert(agents).values({ companyId: company!.id, name: `Inbox ${randomUUID()}`, role: "engineer", adapterType: "process", adapterConfig: {}, runtimeConfig: {} }).returning(); await service.finishGalleryAppConnection(company!.id, connected.connectionId, { - enabledCatalogEntryIds: completed.catalog.map((entry) => entry.id), + enabledCatalogEntryIds: completed.catalog.filter((entry) => !options.off?.includes(entry.toolName)).map((entry) => entry.id), askFirstCatalogEntryIds: completed.catalog.filter((entry) => options.askFirst?.includes(entry.toolName)).map((entry) => entry.id), access: { agentIds: [agent!.id] }, }, actor); @@ -177,20 +228,22 @@ const support = await getEmbeddedPostgresTestSupport(); eq(connectionGrants.connectionId, connected.connectionId), eq(connectionGrants.status, "active"))))[0]; return { company: company!, actor, agent: agent!, service, gateway, session, connector, connectionId: connected.connectionId, catalog: completed.catalog, - gmailRequests, mcpRequests, remoteHttpRequest, toolNamed, call, grant, - setGmail: (override: typeof gmailOverride) => { gmailOverride = override; }, + restRequests, mcpRequests, remoteHttpRequest, toolNamed, call, grant, + setGoogle: (override: typeof restOverride) => { restOverride = override; }, setMessageBody: (body: string) => { messageBody = body; }, setMcpCall: (override: typeof mcpCallOverride) => { mcpCallOverride = override; }, invocations: () => db.select().from(toolInvocations).where(eq(toolInvocations.companyId, company!.id)), }; } - describe("with the default transport map", () => { - it("sends every Google call to Google's MCP servers and never calls the REST adapter", async () => { + describe("with a service switched back to google_mcp", () => { + it("sends that service's calls to Google's MCP server and never calls the REST adapter", async () => { + useTransport("gmail", "google_mcp"); + useTransport("docs", "google_mcp"); const f = await connectWorkspace(); await expect(f.call("gmail__get_message", { messageId: "msg1" })).resolves.toMatchObject({ status: "completed" }); expect(f.mcpRequests).toContain("gmailmcp.googleapis.com tools/call get_message"); - expect(f.gmailRequests).toEqual([]); + expect(f.restRequests).toEqual([]); expect(restDispatch.callGoogleWorkspaceRest).not.toHaveBeenCalled(); expect(restDispatch.probeGoogleWorkspaceRest).not.toHaveBeenCalled(); expect(restDispatch.listGoogleWorkspaceRest).not.toHaveBeenCalled(); @@ -203,9 +256,8 @@ const support = await getEmbeddedPostgresTestSupport(); const f = await connectWorkspace(); expect(f.catalog.map((entry) => entry.toolName).sort()).toEqual(gmailCatalog(true)); expect(f.catalog.find((entry) => entry.toolName === "gmail__create_draft")?.riskLevel).toBe("write"); - expect(f.mcpRequests.some((request) => request.startsWith("gmailmcp."))).toBe(false); - expect(f.mcpRequests).toContain("docsmcp.googleapis.com tools/list"); - expect(f.gmailRequests).toEqual([expect.objectContaining({ method: "GET", path: "/gmail/v1/users/me/profile", authorization: "Bearer workspace-access-1" })]); + expect(f.mcpRequests).toEqual([]); + expect(f.restRequests).toEqual([expect.objectContaining({ method: "GET", path: "/gmail/v1/users/me/profile", authorization: "Bearer workspace-access-1" })]); const readOnly = await connectWorkspace({ permissions: ["gmail.readonly", "documents.readonly"] }); expect(readOnly.catalog.map((entry) => entry.toolName).sort()).toEqual(gmailCatalog(false)); @@ -214,11 +266,11 @@ const support = await getEmbeddedPostgresTestSupport(); it("runs a Gmail read in process with the caller's token, screens it, and audits it", async () => { useTransport("gmail", "paperclip_rest"); const f = await connectWorkspace(); - f.gmailRequests.length = 0; + f.restRequests.length = 0; const result = await f.call("gmail__get_message", { messageId: "msg1" }); expect(result.status).toBe("completed"); expect(JSON.stringify(result.result)).toContain("Lunch is moved to Thursday"); - expect(f.gmailRequests).toEqual([expect.objectContaining({ method: "GET", path: "/gmail/v1/users/me/messages/msg1", authorization: "Bearer workspace-access-1" })]); + expect(f.restRequests).toEqual([expect.objectContaining({ method: "GET", path: "/gmail/v1/users/me/messages/msg1", authorization: "Bearer workspace-access-1" })]); expect(f.mcpRequests.some((request) => request.includes("tools/call"))).toBe(false); expect(restDispatch.callGoogleWorkspaceRest).toHaveBeenCalledOnce(); const [invocation] = await f.invocations(); @@ -232,14 +284,14 @@ const support = await getEmbeddedPostgresTestSupport(); it("asks for approval before creating a draft and creates it over REST once approved", async () => { useTransport("gmail", "paperclip_rest"); const f = await connectWorkspace({ askFirst: ["gmail__create_draft"] }); - f.gmailRequests.length = 0; + f.restRequests.length = 0; const draft = { to: ["sam@example.test"], subject: "Thursday", body: "Thursday works." }; await expect(f.call("gmail__create_draft", draft)).rejects.toMatchObject({ reasonCode: "approval_required" }); - expect(f.gmailRequests).toEqual([]); + expect(f.restRequests).toEqual([]); const [action] = await db.select().from(toolActionRequests).where(eq(toolActionRequests.companyId, f.company.id)); await expect(f.gateway.approveActionRequest({ companyId: f.company.id, actionRequestId: action!.id, actor: { userId: f.actor.actorId } })) .resolves.toMatchObject({ status: "executed" }); - expect(f.gmailRequests).toEqual([expect.objectContaining({ method: "POST", path: "/gmail/v1/users/me/drafts" })]); + expect(f.restRequests).toEqual([expect.objectContaining({ method: "POST", path: "/gmail/v1/users/me/drafts" })]); const [invocation] = await db.select().from(toolInvocations).where(eq(toolInvocations.id, action!.invocationId)); expect(invocation).toMatchObject({ status: "succeeded" }); expect(JSON.stringify(invocation!.resultSummary)).toContain("draft1"); @@ -248,7 +300,7 @@ const support = await getEmbeddedPostgresTestSupport(); it("refuses a tool the grant does not cover, and rechecks consent before every dispatch", async () => { useTransport("gmail", "paperclip_rest"); const f = await connectWorkspace(); - f.gmailRequests.length = 0; + f.restRequests.length = 0; const tool = await f.toolNamed("gmail__get_message"); const grant = await f.grant(); const narrowTo = (permissions: string[]) => db.update(connectionGrants) @@ -261,14 +313,14 @@ const support = await getEmbeddedPostgresTestSupport(); await narrowTo(["documents.readonly"]); await expect(f.gateway.executeTool({ sessionToken: f.session.token, tool: tool.name, parameters: { messageId: "msg1" } })) .rejects.toMatchObject({ reasonCode: "oauth_insufficient_scope" }); - expect(f.gmailRequests).toEqual([]); + expect(f.restRequests).toEqual([]); expect(restDispatch.callGoogleWorkspaceRest).not.toHaveBeenCalled(); }); it("maps Google's insufficient-scope answer to the gateway's scope error", async () => { useTransport("gmail", "paperclip_rest"); const f = await connectWorkspace(); - f.setGmail((url) => url.pathname.includes("/messages/") + f.setGoogle((url) => url.pathname.includes("/messages/") ? Response.json({ error: { code: 403, status: "PERMISSION_DENIED", errors: [{ reason: "insufficientPermissions" }] } }, { status: 403 }) : undefined); await expect(f.call("gmail__get_message", { messageId: "msg1" })).rejects.toMatchObject({ status: 403, reasonCode: "oauth_insufficient_scope" }); @@ -277,20 +329,20 @@ const support = await getEmbeddedPostgresTestSupport(); it("refreshes the token after Google rejects it, never replays the call, and the explicit retry uses the new token", async () => { useTransport("gmail", "paperclip_rest"); const f = await connectWorkspace(); - f.gmailRequests.length = 0; + f.restRequests.length = 0; let rejectNext = true; - f.setGmail((url) => { + f.setGoogle((url) => { if (!url.pathname.includes("/messages/") || !rejectNext) return undefined; rejectNext = false; return Response.json({ error: { code: 401, status: "UNAUTHENTICATED" } }, { status: 401 }); }); const refreshesBefore = vi.mocked(f.connector.refresh).mock.calls.length; await expect(f.call("gmail__get_message", { messageId: "msg1" })).rejects.toMatchObject({ status: 409, reasonCode: "oauth_refreshed_retry_required" }); - expect(f.gmailRequests).toHaveLength(1); + expect(f.restRequests).toHaveLength(1); expect(vi.mocked(f.connector.refresh).mock.calls.length).toBeGreaterThan(refreshesBefore); await expect(f.call("gmail__get_message", { messageId: "msg1" })).resolves.toMatchObject({ status: "completed" }); - expect(f.gmailRequests).toHaveLength(2); - expect(f.gmailRequests[1]!.authorization).not.toBe(f.gmailRequests[0]!.authorization); + expect(f.restRequests).toHaveLength(2); + expect(f.restRequests[1]!.authorization).not.toBe(f.restRequests[0]!.authorization); }); it("blocks an injected email before the agent sees it", async () => { @@ -330,12 +382,12 @@ const support = await getEmbeddedPostgresTestSupport(); useTransport("gmail", "paperclip_rest"); const f = await connectWorkspace(); f.setMessageBody(`${BENIGN_BODY}\n`.repeat(Math.ceil(520_000 / (BENIGN_BODY.length + 1)))); - f.gmailRequests.length = 0; + f.restRequests.length = 0; await expect(f.call("gmail__get_message", { messageId: "msg1" })).rejects.toMatchObject({ status: 502, reasonCode: "tool_error", message: expect.stringMatching(new RegExp(`more than the ${GOOGLE_WORKSPACE_REST_MAX_RESULT_BYTES.toLocaleString("en-US")} bytes this tool can return, so it was not returned\\. Read it with messageFormat METADATA_ONLY or MINIMAL`)), }); - expect(f.gmailRequests).toHaveLength(1); + expect(f.restRequests).toHaveLength(1); expect(vi.mocked(restDispatch.callGoogleWorkspaceRest).mock.calls[0]![0].maxResultBytes).toBe(GOOGLE_WORKSPACE_REST_MAX_RESULT_BYTES); }); @@ -343,7 +395,7 @@ const support = await getEmbeddedPostgresTestSupport(); useTransport("gmail", "paperclip_rest"); const f = await connectWorkspace(); let observed: AbortSignal | undefined; - f.setGmail((url, init) => url.pathname.includes("/messages/") ? new Promise((_resolve, reject) => { + f.setGoogle((url, init) => url.pathname.includes("/messages/") ? new Promise((_resolve, reject) => { observed = init.signal ?? undefined; init.signal?.addEventListener("abort", () => reject(init.signal!.reason), { once: true }); }) : undefined); @@ -355,17 +407,17 @@ const support = await getEmbeddedPostgresTestSupport(); useTransport("gmail", "paperclip_rest"); const f = await connectWorkspace(); const tool = await f.toolNamed("gmail__get_message"); - f.gmailRequests.length = 0; + f.restRequests.length = 0; await instanceSettingsService(db).updateExperimental({ enableGoogleWorkspaceConnector: false }); await expect(f.gateway.executeTool({ sessionToken: f.session.token, tool: tool.name, parameters: { messageId: "msg1" } })).rejects.toBeTruthy(); await expect(f.service.refreshCatalog(f.connectionId, f.actor)).rejects.toBeTruthy(); - expect(f.gmailRequests).toEqual([]); + expect(f.restRequests).toEqual([]); }); it("keeps other services usable when the Gmail probe fails, and restores Gmail once it passes", async () => { useTransport("gmail", "paperclip_rest"); const f = await connectWorkspace(); - f.setGmail((url) => url.pathname.endsWith("/profile") ? Response.json({ error: { code: 403, errors: [{ reason: "accessNotConfigured" }] } }, { status: 403 }) : undefined); + f.setGoogle((url) => url.pathname.endsWith("/profile") ? Response.json({ error: { code: 403, errors: [{ reason: "accessNotConfigured" }] } }, { status: 403 }) : undefined); const refreshed = await f.service.refreshCatalog(f.connectionId, f.actor); expect(refreshed.connection).toMatchObject({ healthStatus: "ok", healthMessage: expect.stringContaining("gmail") }); expect(refreshed.catalog.map((entry) => entry.toolName)).toEqual(["docs__read_doc"]); @@ -374,7 +426,7 @@ const support = await getEmbeddedPostgresTestSupport(); const events = await db.select().from(toolAccessAuditEvents).where(eq(toolAccessAuditEvents.connectionId, f.connectionId)); expect(events).toContainEqual(expect.objectContaining({ reasonCode: "google_workspace_service_unavailable", details: { service: "gmail" } })); await expect(f.call("docs__read_doc", { documentId: "doc1" })).resolves.toMatchObject({ status: "completed" }); - f.setGmail(undefined); + f.setGoogle(undefined); const recovered = await f.service.refreshCatalog(f.connectionId, f.actor); expect(recovered.catalog.map((entry) => entry.toolName).sort()).toEqual(gmailCatalog(true)); }); @@ -383,7 +435,7 @@ const support = await getEmbeddedPostgresTestSupport(); useTransport("gmail", "paperclip_rest"); const f = await connectWorkspace(); const refreshesBefore = vi.mocked(f.connector.refresh).mock.calls.length; - f.setGmail(() => Response.json({ error: { code: 401, status: "UNAUTHENTICATED" } }, { status: 401 })); + f.setGoogle(() => Response.json({ error: { code: 401, status: "UNAUTHENTICATED" } }, { status: 401 })); await expect(f.service.refreshCatalog(f.connectionId, f.actor)).rejects.toMatchObject({ details: { code: "oauth_reauthorization_required" } }); expect(vi.mocked(f.connector.refresh).mock.calls.length).toBeGreaterThan(refreshesBefore); const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, f.connectionId)); @@ -399,7 +451,7 @@ const support = await getEmbeddedPostgresTestSupport(); it("warns that a timed-out draft may already exist, in the error, the invocation and the audit", async () => { useTransport("gmail", transport); const f = await connectWorkspace(); - f.setGmail((url, init) => url.pathname.endsWith("/drafts") ? hang(init) : undefined); + f.setGoogle((url, init) => url.pathname.endsWith("/drafts") ? hang(init) : undefined); f.setMcpCall((init) => JSON.parse(String(init.body)).params?.name === "create_draft" ? hang(init) : undefined); await expect(f.call("gmail__create_draft", { to: ["sam@example.test"], subject: "Thursday", body: "Thursday works." }, { timeoutMs: 100 })) .rejects.toMatchObject({ status: 504, reasonCode: "tool_timeout", message: expect.stringContaining(UNCERTAIN) }); @@ -413,16 +465,216 @@ const support = await getEmbeddedPostgresTestSupport(); it("returns the uncertain-write warning from an approved REST draft whose request was lost", async () => { useTransport("gmail", "paperclip_rest"); const f = await connectWorkspace({ askFirst: ["gmail__create_draft"] }); - f.setGmail((url) => url.pathname.endsWith("/drafts") ? Promise.reject(new TypeError("socket hang up")) : undefined); + f.setGoogle((url) => url.pathname.endsWith("/drafts") ? Promise.reject(new TypeError("socket hang up")) : undefined); await expect(f.call("gmail__create_draft", { to: ["sam@example.test"], subject: "Thursday", body: "Thursday works." })) .rejects.toMatchObject({ reasonCode: "approval_required" }); const [action] = await db.select().from(toolActionRequests).where(eq(toolActionRequests.companyId, f.company.id)); const approved = await f.gateway.approveActionRequest({ companyId: f.company.id, actionRequestId: action!.id, actor: { userId: f.actor.actorId } }); expect(JSON.stringify(approved)).toContain("may or may not have been made"); }); + describe("the six launch services on paperclip_rest", () => { + const LAUNCH_SERVICES = ["gmail", "drive", "docs", "sheets", "slides", "calendar"] as const; + const DEFAULT_PERMISSIONS = ["gmail.readonly", "gmail.compose", "drive.readonly", "drive.file", "documents.readonly", "documents", + "spreadsheets.readonly", "spreadsheets", "presentations.readonly", "presentations", "calendar.calendarlist.readonly", "calendar.events", + "calendar.events.freebusy"]; + const READ_ONLY_PERMISSIONS = ["gmail.readonly", "drive.readonly", "documents.readonly", "spreadsheets.readonly", "presentations.readonly", + "calendar.calendarlist.readonly", "calendar.events.freebusy", "calendar.events.readonly"]; + const allowlisted = (services: readonly GoogleWorkspaceService[], keep: (name: string) => boolean = () => true) => + services.flatMap((service) => googleWorkspaceServiceToolNames(service).map((name) => `${service}__${name}`)).filter(keep).sort(); + const names = (catalog: Array<{ toolName: string }>) => catalog.map((entry) => entry.toolName).sort(); + const REVISION = { requiredRevisionId: "rev-1" }; + const READS: Array<[string, Record, string]> = [ + ["gmail__get_message", { messageId: "msg1" }, "gmail.googleapis.com GET /gmail/v1/users/me/messages/msg1"], + ["drive__get_file_metadata", { fileId: "file1" }, "www.googleapis.com GET /drive/v3/files/file1"], + ["docs__read_doc", { documentId: "doc1" }, "docs.googleapis.com GET /v1/documents/doc1"], + ["sheets__get_values", { spreadsheetId: "sheet1", range: "Sheet1!A1:B1" }, "sheets.googleapis.com GET /v4/spreadsheets/sheet1/values/Sheet1!A1%3AB1"], + ["slides__read_presentation", { presentationId: "deck1" }, "slides.googleapis.com GET /v1/presentations/deck1"], + ["calendar__list_calendars", {}, "www.googleapis.com GET /calendar/v3/users/me/calendarList"], + ]; + const WRITES: Array<[string, Record, string]> = [ + ["gmail__create_draft", { to: ["sam@example.test"], subject: "Thursday", body: "Thursday works." }, "gmail.googleapis.com POST /gmail/v1/users/me/drafts"], + ["drive__create_file", { title: "Notes", mimeType: "application/vnd.google-apps.folder" }, "www.googleapis.com POST /drive/v3/files"], + ["docs__update_doc", { documentId: "doc1", requests: [{ insertText: { text: "Hi", location: { index: 1 } } }], writeControl: REVISION }, "docs.googleapis.com POST /v1/documents/doc1:batchUpdate"], + ["sheets__update_values", { spreadsheetId: "sheet1", range: "Sheet1!A1:B1", values: [["Owner", "Sam"]] }, "sheets.googleapis.com PUT /v4/spreadsheets/sheet1/values/Sheet1!A1%3AB1"], + ["slides__update_presentation", { presentationId: "deck1", requests: [{ createSlide: {} }], writeControl: REVISION }, "slides.googleapis.com POST /v1/presentations/deck1:batchUpdate"], + ["calendar__create_event", { summary: "Planning", startTime: "2026-11-24T10:00:00Z", endTime: "2026-11-24T10:30:00Z", timeZone: "UTC" }, "www.googleapis.com POST /calendar/v3/calendars/primary/events"], + ]; + + it("puts exactly the six launch services on paperclip_rest and leaves the rest on google_mcp", () => { + expect(Object.entries(GOOGLE_WORKSPACE_TOOL_TRANSPORT).filter(([, transport]) => transport === "paperclip_rest").map(([service]) => service).sort()) + .toEqual([...LAUNCH_SERVICES].sort()); + expect(GOOGLE_WORKSPACE_TOOL_TRANSPORT).toMatchObject({ chat: "google_mcp", people: "google_mcp", search: "google_mcp" }); + }); + + it("lists all 36 allowlisted actions for a full read & write grant without contacting a Google MCP server", async () => { + const f = await connectWorkspace({ permissions: DEFAULT_PERMISSIONS }); + expect(names(f.catalog)).toEqual(allowlisted(LAUNCH_SERVICES)); + expect(f.catalog).toHaveLength(36); + expect(names(f.catalog)).toEqual(expect.arrayContaining(["gmail__list_threads", "gmail__search_messages"])); + expect(f.mcpRequests).toEqual([]); + expect(f.restRequests.map((request) => `${request.host} ${request.path}`).sort()).toEqual([ + "gmail.googleapis.com /gmail/v1/users/me/profile", "www.googleapis.com /calendar/v3/users/me/calendarList", "www.googleapis.com /drive/v3/about", + ]); + expect((await f.gateway.listToolsForSession(f.session.token)).filter((tool) => tool.connectionId === f.connectionId)).toHaveLength(36); + }); + + it("lists only the read actions for a read-only grant", async () => { + const f = await connectWorkspace({ permissions: READ_ONLY_PERMISSIONS }); + const writes = new Set(WRITES.map(([name]) => name).concat("calendar__update_event", "calendar__delete_event", "calendar__respond_to_event", + "drive__copy_file", "sheets__update_spreadsheet", "sheets__update_formulas", "sheets__insert_dimension")); + expect(names(f.catalog)).toEqual(allowlisted(LAUNCH_SERVICES, (name) => !writes.has(name))); + expect(f.catalog).toHaveLength(23); + expect(f.catalog.every((entry) => entry.riskLevel === "read")).toBe(true); + }); + + it.each([ + ["Gmail read & write", ["gmail.readonly", "gmail.compose"], allowlisted(["gmail"])], + ["Drive read only", ["drive.readonly", "documents.readonly", "spreadsheets.readonly", "presentations.readonly"], + allowlisted(["drive", "docs", "sheets", "slides"], (name) => /__(read|get|list|search|download)/.test(name))], + ["Drive read & write", ["drive.readonly", "drive.file", "documents.readonly", "documents", "spreadsheets.readonly", "spreadsheets", "presentations.readonly", "presentations"], + allowlisted(["drive", "docs", "sheets", "slides"])], + ["Calendar read & write", ["calendar.calendarlist.readonly", "calendar.events", "calendar.events.freebusy"], allowlisted(["calendar"])], + ])("lists exactly the %s group's actions", async (_label, permissions, expected) => { + const f = await connectWorkspace({ permissions }); + expect(names(f.catalog)).toEqual(expected); + expect(f.mcpRequests).toEqual([]); + }); + + it.each([...READS, ...WRITES])("runs %s through executeTool over REST, with the default Allowed policy, and audits it", async (name, parameters, request) => { + const f = await connectWorkspace({ permissions: DEFAULT_PERMISSIONS }); + f.restRequests.length = 0; + const result = await f.call(name, parameters); + expect(result.status).toBe("completed"); + expect(f.restRequests.map((sent) => `${sent.host} ${sent.method} ${sent.path}`)).toEqual([request.replace(/\?.*$/, "")]); + expect(f.restRequests[0]!.authorization).toBe("Bearer workspace-access-1"); + expect(f.mcpRequests).toEqual([]); + expect(restDispatch.callGoogleWorkspaceRest).toHaveBeenCalledWith(expect.objectContaining({ service: name.split("__")[0], toolName: name.split("__")[1] })); + await expect(db.select().from(toolActionRequests).where(eq(toolActionRequests.companyId, f.company.id))).resolves.toEqual([]); + const [invocation] = await f.invocations(); + expect(invocation).toMatchObject({ status: "succeeded", errorCode: null, connectionId: f.connectionId }); + const events = await db.select().from(toolCallEvents).where(eq(toolCallEvents.invocationId, invocation!.id)); + expect(events.filter((event) => event.eventType === "call_completed")).toEqual([expect.objectContaining({ connectionId: f.connectionId })]); + const audit = await db.select().from(toolAccessAuditEvents).where(and(eq(toolAccessAuditEvents.companyId, f.company.id), eq(toolAccessAuditEvents.action, "call_completed"))); + expect(audit).toHaveLength(1); + expect(JSON.stringify(audit[0])).toContain("Google Workspace REST"); + expect(JSON.stringify(audit[0])).toContain(`paperclip-rest:google-workspace/${name.split("__")[0]}`); + }); + + it.each([ + ["docs__read_doc", { documentId: "doc1" }, (url: URL) => url.pathname === "/v1/documents/doc1" ? Response.json(googleDocument(INJECTED_BODY)) : undefined], + ["sheets__get_values", { spreadsheetId: "sheet1", range: "Sheet1!A1:B1" }, + (url: URL) => url.hostname === "sheets.googleapis.com" ? Response.json({ range: "Sheet1!A1:B1", majorDimension: "ROWS", values: [[INJECTED_BODY]] }) : undefined], + ["slides__read_presentation", { presentationId: "deck1" }, (url: URL) => url.pathname === "/v1/presentations/deck1" + ? Response.json({ presentationId: "deck1", title: INJECTED_BODY, revisionId: "rev-1", slides: [] }) : undefined], + ["drive__get_file_metadata", { fileId: "file1" }, (url: URL) => url.pathname === "/drive/v3/files/file1" + ? Response.json({ id: "file1", name: "Plan", mimeType: "text/plain", description: INJECTED_BODY }) : undefined], + ["calendar__list_calendars", {}, (url: URL) => url.pathname === "/calendar/v3/users/me/calendarList" + ? Response.json({ items: [{ id: "primary", summary: "Team", description: INJECTED_BODY }] }) : undefined], + ] as const)("blocks injected instructions returned by %s over REST", async (name, parameters, answer) => { + const f = await connectWorkspace({ permissions: DEFAULT_PERMISSIONS }); + f.setGoogle(answer); + await expect(f.call(name, parameters)).rejects.toMatchObject({ status: 422, reasonCode: "prompt_injection_blocked" }); + const [invocation] = await f.invocations(); + expect(invocation).toMatchObject({ status: "failed", errorCode: "prompt_injection_blocked" }); + expect(JSON.stringify(invocation)).not.toContain("ignore all previous instructions"); + }); + + it("keeps an existing connection's actions usable when its services move from Google's MCP servers to REST", async () => { + for (const service of LAUNCH_SERVICES) useTransport(service, "google_mcp"); + const f = await connectWorkspace(); + expect(names(f.catalog)).toEqual(["docs__read_doc", "gmail__create_draft", "gmail__get_message", "gmail__search_threads"]); + Object.assign(GOOGLE_WORKSPACE_TOOL_TRANSPORT, savedTransport); + const refreshed = await f.service.refreshCatalog(f.connectionId, f.actor); + expect(names(refreshed.catalog)).toEqual(gmailCatalog(true)); + expect(refreshed.catalog.filter((entry) => entry.status !== "active")).toEqual([]); + f.restRequests.length = 0; + await expect(f.call("gmail__list_threads", { labelIds: ["INBOX"] })).resolves.toMatchObject({ status: "completed" }); + await expect(f.call("gmail__get_message", { messageId: "msg1" })).resolves.toMatchObject({ status: "completed" }); + expect(f.restRequests.map((request) => request.path)).toContain("/gmail/v1/users/me/messages/msg1"); + }); + + it("advertises the REST definitions to agents for a connection saved with Google's MCP schemas, with no refresh, and the edit succeeds", async () => { + for (const service of LAUNCH_SERVICES) useTransport(service, "google_mcp"); + const f = await connectWorkspace({ permissions: ["gmail.readonly", "documents.readonly", "documents"] }); + const saved = f.catalog.find((entry) => entry.toolName === "docs__update_doc")!; + expect(saved.inputSchema).toEqual(GOOGLE_MCP_SCHEMAS.update_doc); + const before = await f.toolNamed("docs__update_doc"); + expect(before.parametersSchema).toMatchObject({ required: ["documentId", "requests"] }); + Object.assign(GOOGLE_WORKSPACE_TOOL_TRANSPORT, savedTransport); + f.restRequests.length = 0; + const refreshesBefore = f.mcpRequests.length; + + const update = await f.toolNamed("docs__update_doc"); + const restDefinition = restDispatch.listGoogleWorkspaceRest("docs").find((tool) => tool.name === "update_doc")!; + expect(update.parametersSchema).toEqual(restDefinition.inputSchema); + expect((update.parametersSchema as { required: string[] }).required).toContain("writeControl"); + expect(update.description).toBe(restDefinition.description); + expect(update.displayName).toBe("Docs: Edit a document"); + expect(update.description).toContain("requiredRevisionId"); + const read = await f.toolNamed("docs__read_doc"); + expect(read.parametersSchema).toEqual(restDispatch.listGoogleWorkspaceRest("docs").find((tool) => tool.name === "read_doc")!.inputSchema); + + const document = await f.call("docs__read_doc", { documentId: "doc1" }); + expect(JSON.stringify(document.result)).toContain("rev-1"); + await expect(f.call("docs__update_doc", { documentId: "doc1", requests: [{ insertText: { text: "Hi", location: { index: 1 } } }], + writeControl: { requiredRevisionId: "rev-1" } })).resolves.toMatchObject({ status: "completed" }); + expect(f.restRequests.map((request) => `${request.method} ${request.path}`)).toEqual(["GET /v1/documents/doc1", "POST /v1/documents/doc1:batchUpdate"]); + expect(f.mcpRequests).toHaveLength(refreshesBefore); + }); + + it("on the first refresh after the switch, releases actions held for review and keeps Off and Ask first", async () => { + for (const service of LAUNCH_SERVICES) useTransport(service, "google_mcp"); + const f = await connectWorkspace({ off: ["gmail__search_threads"], askFirst: ["gmail__create_draft"] }); + const held = f.catalog.find((entry) => entry.toolName === "gmail__get_message")!; + await db.update(toolCatalogEntries).set({ status: "quarantined", quarantineReason: "pending_review", quarantinedAt: new Date() }) + .where(eq(toolCatalogEntries.id, held.id)); + const listed = async () => (await f.gateway.listToolsForSession(f.session.token)) + .filter((tool) => tool.connectionId === f.connectionId).map((tool) => tool.upstreamToolName).sort(); + expect(await listed()).toEqual(["docs__read_doc", "gmail__create_draft"]); + + Object.assign(GOOGLE_WORKSPACE_TOOL_TRANSPORT, savedTransport); + const refreshed = await f.service.refreshCatalog(f.connectionId, f.actor); + expect(refreshed.catalog.find((entry) => entry.toolName === "gmail__get_message")).toMatchObject({ status: "active", quarantineReason: null }); + expect(refreshed.catalog.filter((entry) => entry.status !== "active")).toEqual([]); + const after = await listed(); + expect(after).toContain("gmail__get_message"); + expect(after).not.toContain("gmail__search_threads"); + await expect(f.call("gmail__get_message", { messageId: "msg1" })).resolves.toMatchObject({ status: "completed" }); + await expect(f.call("gmail__create_draft", { to: ["sam@example.test"], subject: "Thursday", body: "Thursday works." })) + .rejects.toMatchObject({ reasonCode: "approval_required" }); + }); + + it("keeps an action that is both Off and held for review Off, and one that is both Ask first and held for review Ask first", async () => { + for (const service of LAUNCH_SERVICES) useTransport(service, "google_mcp"); + const f = await connectWorkspace({ off: ["gmail__get_message"], askFirst: ["gmail__create_draft"] }); + const held = f.catalog.filter((entry) => entry.toolName === "gmail__get_message" || entry.toolName === "gmail__create_draft").map((entry) => entry.id); + expect(held).toHaveLength(2); + await db.update(toolCatalogEntries).set({ status: "quarantined", quarantineReason: "pending_review", quarantinedAt: new Date() }) + .where(inArray(toolCatalogEntries.id, held)); + const listed = async () => (await f.gateway.listToolsForSession(f.session.token)) + .filter((tool) => tool.connectionId === f.connectionId).map((tool) => tool.upstreamToolName).sort(); + const draft = { to: ["sam@example.test"], subject: "Thursday", body: "Thursday works." }; + + Object.assign(GOOGLE_WORKSPACE_TOOL_TRANSPORT, savedTransport); + expect(await listed()).toEqual(["docs__read_doc", "gmail__search_threads"]); + for (let refresh = 0; refresh < 2; refresh += 1) { + const refreshed = await f.service.refreshCatalog(f.connectionId, f.actor); + expect(refreshed.catalog.filter((entry) => held.includes(entry.id))).toEqual([ + expect.objectContaining({ status: "active" }), expect.objectContaining({ status: "active" }), + ]); + const after = await listed(); + expect(after).not.toContain("gmail__get_message"); + expect(after).toContain("gmail__create_draft"); + expect(after).toEqual(expect.arrayContaining(["gmail__list_threads", "gmail__search_messages"])); + await expect(f.call("gmail__create_draft", draft)).rejects.toMatchObject({ reasonCode: "approval_required" }); + } + expect(f.restRequests.filter((request) => request.path.endsWith("/drafts") || request.path.endsWith("/messages/msg1"))).toEqual([]); + }); + }); + describe("probing only with what the grant allows", () => { const calendarTools = (catalog: Array<{ toolName: string }>) => catalog.map((entry) => entry.toolName).filter((name) => name.startsWith("calendar__")).sort(); - const restPaths = (f: Awaited>) => f.gmailRequests.map((request) => request.path); + const restPaths = (f: Awaited>) => f.restRequests.map((request) => request.path); it.each([ [["calendar.events"], "/calendar/v3/calendars/primary/events", @@ -442,13 +694,13 @@ const support = await getEmbeddedPostgresTestSupport(); useTransport("gmail", "paperclip_rest"); const f = await connectWorkspace({ permissions: ["gmail.compose", "documents.readonly"] }); expect(f.catalog.map((entry) => entry.toolName).sort()).toEqual(["docs__read_doc", "gmail__create_draft"]); - expect(f.gmailRequests).toEqual([]); + expect(f.restRequests).toEqual([]); }); it("keeps a service whose probe answers with insufficient scope", async () => { useTransport("calendar", "paperclip_rest"); const f = await connectWorkspace({ permissions: ["calendar.calendarlist.readonly", "calendar.events", "documents.readonly"] }); - f.setGmail((url) => url.pathname.startsWith("/calendar/") ? Response.json({ error: { code: 403, errors: [{ reason: "insufficientPermissions" }] } }, { status: 403 }) : undefined); + f.setGoogle((url) => url.pathname.startsWith("/calendar/") ? Response.json({ error: { code: 403, errors: [{ reason: "insufficientPermissions" }] } }, { status: 403 }) : undefined); const refreshed = await f.service.refreshCatalog(f.connectionId, f.actor); expect(refreshed.connection.healthMessage ?? "").not.toContain("calendar"); expect(calendarTools(refreshed.catalog)).toContain("calendar__list_calendars"); @@ -458,7 +710,7 @@ const support = await getEmbeddedPostgresTestSupport(); it("drops nothing but asks for reconnection when Google rejects a revoked Calendar token", async () => { useTransport("calendar", "paperclip_rest"); const f = await connectWorkspace({ permissions: ["calendar.events", "documents.readonly"] }); - f.setGmail((url) => url.pathname.startsWith("/calendar/") ? Response.json({ error: { code: 401, status: "UNAUTHENTICATED" } }, { status: 401 }) : undefined); + f.setGoogle((url) => url.pathname.startsWith("/calendar/") ? Response.json({ error: { code: 401, status: "UNAUTHENTICATED" } }, { status: 401 }) : undefined); await expect(f.service.refreshCatalog(f.connectionId, f.actor)).rejects.toMatchObject({ details: { code: "oauth_reauthorization_required" } }); const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, f.connectionId)); expect(grant!.status).toBe("needs_reauthorization"); diff --git a/server/src/__tests__/helpers/google-workspace-transport.ts b/server/src/__tests__/helpers/google-workspace-transport.ts new file mode 100644 index 00000000000..6e0768e6b19 --- /dev/null +++ b/server/src/__tests__/helpers/google-workspace-transport.ts @@ -0,0 +1,10 @@ +import { onTestFinished } from "vitest"; +import { GOOGLE_WORKSPACE_TOOL_TRANSPORT, type GoogleWorkspaceService } from "@paperclipai/shared"; + +export function useGoogleMcpTransport() { + const saved = { ...GOOGLE_WORKSPACE_TOOL_TRANSPORT }; + for (const service of Object.keys(saved) as GoogleWorkspaceService[]) GOOGLE_WORKSPACE_TOOL_TRANSPORT[service] = "google_mcp"; + onTestFinished(() => { + Object.assign(GOOGLE_WORKSPACE_TOOL_TRANSPORT, saved); + }); +} diff --git a/server/src/__tests__/login-cleanup-work.test.ts b/server/src/__tests__/login-cleanup-work.test.ts index 081fc6eece6..f5ea6d84dea 100644 --- a/server/src/__tests__/login-cleanup-work.test.ts +++ b/server/src/__tests__/login-cleanup-work.test.ts @@ -12,7 +12,7 @@ import { loginCleanupSchedule, orphanLoginLeases } from "../services/login-clean import { createDbAdapterAuthSessionStore, LOGIN_LEASE_SESSION_TAG_KEY } from "../services/device-login-service.js"; import { createDeviceLoginReaper, createProductionLoginSessionReaperRuntime } from "../services/device-login-reaper.js"; import { createDbSetupTokenCleanupStore, transitionSetupTokenSessionToStored } from "../services/setup-token-session.js"; -import { createSetupTokenReaper } from "../services/setup-token-reaper.js"; +import { createProductionSetupTokenReaper, createSetupTokenReaper } from "../services/setup-token-reaper.js"; import { idleWorkSnapshot } from "../services/task-admission.js"; const coordinators: ReturnType[] = []; @@ -193,6 +193,31 @@ describe.skipIf(!support.supported)("durable login cleanup", () => { await vi.advanceTimersByTimeAsync(10_000); expect(driver.releaseRunLease).toHaveBeenCalledTimes(1); failedDelete = false; await quiet(c); expect(driver.releaseRunLease).toHaveBeenCalledTimes(2); }); + it("clears setup-token sessions a restart left in submitting, with and without a lease", async () => { + const expired = new Date(Date.now() - 1_000); + const orphan = async (providerLeaseId: string | null) => { + const sessionId = randomUUID(); + await db.insert(adapterAuthSessions).values({ companyId, environmentId, adapterType: "claude_local", startedByUserId: randomUUID(), + publicSessionId: sessionId, status: "submitting", providerLeaseId, expiresAt: expired }); + return sessionId; + }; + const withoutLease = await orphan(null); + const leaseSession = randomUUID(); + const leaseId = await lease(leaseSession); + const withLease = await orphan(leaseId); + const lines: string[] = []; + const reaper = createProductionSetupTokenReaper({ db: observed, environmentRuntime: { getDriver: () => driver } as any, log: line => lines.push(line) }); + + expect(await reaper.sweep()).toEqual({ released: 2, failed: 0 }); + expect(await reaper.sweep()).toEqual({ released: 0, failed: 0 }); + + const remaining = await db.select().from(adapterAuthSessions).where(eq(adapterAuthSessions.companyId, companyId)); + expect(remaining.map(row => row.publicSessionId)).not.toEqual(expect.arrayContaining([withoutLease])); + expect(remaining.map(row => row.publicSessionId)).not.toEqual(expect.arrayContaining([withLease])); + expect(driver.releaseRunLease).toHaveBeenCalledTimes(1); + expect(driver.releaseRunLease.mock.calls[0]![0].lease.id).toBe(leaseId); + expect(lines).toEqual([]); + }); it.each([false, true])("keeps nested producer intent until outer settlement (rollback=%s)", async rollback => { const c = await adapterWorker(); await quiet(c); let release!: () => void, written!: () => void, id!: string; diff --git a/server/src/__tests__/mcp-tasks.test.ts b/server/src/__tests__/mcp-tasks.test.ts index a75d81d73d4..2abddab643a 100644 --- a/server/src/__tests__/mcp-tasks.test.ts +++ b/server/src/__tests__/mcp-tasks.test.ts @@ -684,6 +684,113 @@ const support = await getEmbeddedPostgresTestSupport(); expect((await ctx.rows())[0]).toMatchObject({ status: "expired", errorCode: "access_removed", nextPollAt: null }); }); + async function personalGrantSetup(server: ReturnType) { + const ctx = await setup(server); + for (const userId of ["task-owner", "task-opener"]) { + await db.insert(companyMemberships).values({ companyId: ctx.org.id, principalType: "user", principalId: userId, status: "active", membershipRole: "member" }); + } + await db.update(heartbeatRuns).set({ responsibleUserId: "task-owner" }).where(eq(heartbeatRuns.id, ctx.run.id)); + return ctx; + } + const usePersonalGrants = async (ctx: Awaited>) => { + await db.update(toolConnections).set({ credentialPolicy: "per_user" }).where(eq(toolConnections.id, ctx.connected.connectionId)); + const grants = new Map(); + for (const userId of ["task-owner", "task-opener"]) { + const [grant] = await db.insert(connectionGrants).values({ + companyId: ctx.org.id, connectionId: ctx.connected.connectionId, kind: "user", subjectUserId: userId, + credentialSecretRefs: [], status: "active", isDefault: false, + }).returning(); + grants.set(userId, grant!.id); + } + return grants; + }; + const callAs = async (ctx: Awaited>, createdByUserId: string | null, ref: string, + extra: { runId?: string; timeoutMs?: number; idempotencyKey?: string } = {}) => { + const session = await ctx.gateway().createSession({ companyId: ctx.org.id, agentId: ctx.agent.id, runId: extra.runId ?? ctx.run.id, createdByUserId }); + const tool = (await ctx.gateway().listToolsForSession(session.token)).find((candidate) => candidate.name.endsWith(":build"))!; + return ctx.gateway().executeTool({ sessionToken: session.token, tool: tool.name, parameters: { ref }, timeoutMs: extra.timeoutMs ?? 400, idempotencyKey: extra.idempotencyKey }); + }; + const releaseLeases = (orgId: string) => db.update(toolMcpTasks).set({ leaseExpiresAt: null, leaseOwner: null }).where(eq(toolMcpTasks.companyId, orgId)); + + it("keeps the opener's personal grant on a person-started task and never hands its result to another grant", async () => { + const server = taskServer(); + const ctx = await personalGrantSetup(server); + const grants = await usePersonalGrants(ctx); + + await expect(callAs(ctx, null, "shared-ref")).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + const agentTaskId = server.only().id; + await releaseLeases(ctx.org.id); + const callsBeforeOwnerRetry = server.count("tools/call"); + await expect(callAs(ctx, "task-owner", "shared-ref")).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + expect(server.count("tools/call")).toBe(callsBeforeOwnerRetry); + await expect(callAs(ctx, "task-opener", "shared-ref")).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + const openerTaskId = server.only().id; + expect(openerTaskId).not.toBe(agentTaskId); + await releaseLeases(ctx.org.id); + const callsBeforeOpenerRetry = server.count("tools/call"); + await expect(callAs(ctx, "task-opener", "shared-ref")).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + expect(server.count("tools/call")).toBe(callsBeforeOpenerRetry); + const rows = await ctx.rows(); + const openerRow = rows.find((row) => row.createdByUserId === "task-opener")!; + expect(openerRow).toMatchObject({ grantId: grants.get("task-opener"), responsibleUserId: "task-opener" }); + expect(rows.find((row) => row.createdByUserId === null)).toMatchObject({ grantId: grants.get("task-owner") }); + + server.tasks.get(openerTaskId)!.status = "completed"; + server.tasks.get(openerTaskId)!.result = { content: [{ type: "text", text: "opener result" }], isError: false }; + await releaseLeases(ctx.org.id); + const callsBeforeRetry = server.count("tools/call"); + await expect(callAs(ctx, null, "shared-ref")).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + expect(server.count("tools/call")).toBe(callsBeforeRetry); + + await releaseLeases(ctx.org.id); + await db.update(toolMcpTasks).set({ nextPollAt: new Date(Date.now() - 1_000) }).where(eq(toolMcpTasks.id, openerRow.id)); + await ctx.poll(); + const [polled] = await db.select().from(toolMcpTasks).where(eq(toolMcpTasks.id, openerRow.id)); + expect(polled!.errorCode).not.toBe("access_removed"); + + const [woken] = await db.insert(heartbeatRuns).values({ companyId: ctx.org.id, agentId: ctx.agent.id, invocationSource: "automation", + status: "running", responsibleUserId: "task-owner", + contextSnapshot: { issueId: ctx.issue.id, toolTask: { tool: openerRow.catalogToolName, status: "completed", taskRecordId: openerRow.id } } }).returning(); + await releaseLeases(ctx.org.id); + const callsBeforeContinuation = server.count("tools/call"); + expect(await callAs(ctx, null, "shared-ref", { runId: woken!.id, timeoutMs: 2_000 })).toMatchObject({ status: "completed" }); + expect(server.count("tools/call")).toBe(callsBeforeContinuation); + const [collected] = await db.select().from(toolMcpTasks).where(eq(toolMcpTasks.id, openerRow.id)); + expect(collected!.deliveredAt).toBeInstanceOf(Date); + + await expect(callAs(ctx, "task-opener", "revoked-ref")).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + const revokedTaskId = server.only().id; + const [revokedRow] = (await ctx.rows()).filter((row) => row.createdByUserId === "task-opener" && !row.deliveredAt); + server.tasks.get(revokedTaskId)!.status = "completed"; + await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, grants.get("task-opener")!)); + const [wokenAgain] = await db.insert(heartbeatRuns).values({ companyId: ctx.org.id, agentId: ctx.agent.id, invocationSource: "automation", + status: "running", responsibleUserId: "task-owner", + contextSnapshot: { issueId: ctx.issue.id, toolTask: { tool: revokedRow!.catalogToolName, status: "completed", taskRecordId: revokedRow!.id } } }).returning(); + await releaseLeases(ctx.org.id); + const callsBeforeRevokedContinuation = server.count("tools/call"); + await expect(callAs(ctx, null, "revoked-ref", { runId: wokenAgain!.id, timeoutMs: 2_000 })) + .rejects.toMatchObject({ reasonCode: "provider_task_expired" }); + expect(server.count("tools/call")).toBe(callsBeforeRevokedContinuation); + }); + + it("lets any person collect a task on a shared grant, including one started before openers were recorded", async () => { + const server = taskServer(); + const ctx = await personalGrantSetup(server); + await expect(callAs(ctx, "task-opener", "shared-grant")).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + const callsBefore = server.count("tools/call"); + server.finish(); + await releaseLeases(ctx.org.id); + expect(await callAs(ctx, "task-owner", "shared-grant", { timeoutMs: 2_000 })).toMatchObject({ status: "completed" }); + expect(server.count("tools/call")).toBe(callsBefore); + + await expect(callAs(ctx, null, "legacy-shared")).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + const legacyCalls = server.count("tools/call"); + server.finish(); + await releaseLeases(ctx.org.id); + expect(await callAs(ctx, "task-opener", "legacy-shared", { timeoutMs: 2_000 })).toMatchObject({ status: "completed" }); + expect(server.count("tools/call")).toBe(legacyCalls); + }); + it("keeps a completed task recoverable until its result is recorded, then wakes the agent", async () => { const server = taskServer(); const ctx = await setup(server); diff --git a/server/src/__tests__/runtime-skill-preservation.test.ts b/server/src/__tests__/runtime-skill-preservation.test.ts index 2539879ce35..08d2eccb01b 100644 --- a/server/src/__tests__/runtime-skill-preservation.test.ts +++ b/server/src/__tests__/runtime-skill-preservation.test.ts @@ -51,13 +51,13 @@ describe("admitted unversioned runtime skill preservation", () => { await database?.cleanup(); if (home) await removeRuntimeAssetTree(home); }); - async function fixture() { + async function fixture(skill = "# original admitted skill\n") { const companyId = randomUUID(), agentId = randomUUID(), runId = randomUUID(), issueId = randomUUID(); await db.insert(companies).values({ id: companyId, name: "Skill preservation", issuePrefix: `R${companyId.slice(0, 6)}` }); await db.insert(agents).values({ id: agentId, companyId, name: "Recovery source" }); await db.insert(issues).values({ id: issueId, companyId, title: "Preserve admitted skill" }); const bundle = await materializeAsset([ - { path: "SKILL.md", content: Buffer.from("# original admitted skill\n"), mode: 0o400 }, + { path: "SKILL.md", content: Buffer.from(skill), mode: 0o400 }, { path: "scripts/run.sh", content: Buffer.from("#!/bin/sh\necho preserve\n"), mode: 0o500 }, { path: "binary", content: Buffer.from([0, 255, 7]), mode: 0o444 }, ]); @@ -187,6 +187,20 @@ describe("admitted unversioned runtime skill preservation", () => { await removeRuntimeAssetTree(f.bundle.rootPath); expect(await preserveRuntimeSkillAssets(db, f, storage)).toEqual({ preserved: 1 }); }); + it("names a retained run whose bundle left this disk and still saves the runs after it", async () => { + const lost = await fixture("# lost admitted skill\n"), kept = await fixture("# kept admitted skill\n"); + await removeRuntimeAssetTree(lost.bundle.rootPath); + const page = await migrateRuntimeSkillAssets(db, { apply: true }, storage); + expect([...page.results].sort((a, b) => a.runId.localeCompare(b.runId))).toEqual([ + { runId: lost.runId, status: "unsaved", code: "runtime_skill_source_absent:missing" }, + { runId: kept.runId, status: "preserved", preserved: 1 }, + ].sort((a, b) => a.runId.localeCompare(b.runId))); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, kept.runId)))[0]!.runnerProfileJson) + .toHaveProperty("nativeRuntimeSkillPreservation"); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, lost.runId)))[0]!.runnerProfileJson) + .not.toHaveProperty("nativeRuntimeSkillPreservation"); + expect(await hasLocalRuntimeSkillObligations(db)).toBe(true); + }); it("retains the original receipt through a contract revision but rejects a changed admitted asset or binding", async () => { const f = await fixture(); await preserveRuntimeSkillAssets(db, f, storage); diff --git a/server/src/__tests__/skill-package-storage-throttle.test.ts b/server/src/__tests__/skill-package-storage-throttle.test.ts new file mode 100644 index 00000000000..d5cedb98a16 --- /dev/null +++ b/server/src/__tests__/skill-package-storage-throttle.test.ts @@ -0,0 +1,154 @@ +import { randomUUID } from "node:crypto"; +import { promises as fs } from "node:fs"; +import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; +import type { AddressInfo } from "node:net"; +import os from "node:os"; +import path from "node:path"; +import express from "express"; +import request from "supertest"; +import { eq } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { companies, companySkillRepositorySnapshots as snapshots, createDb } from "@paperclipai/db"; +import type { CompanySkillVersionFileInventoryEntry } from "@paperclipai/shared"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { errorHandler } from "../middleware/error-handler.js"; +import { skillPackageStore } from "../services/skill-package-store.js"; +import { createS3StorageProvider } from "../storage/s3-provider.js"; +import { createStorageService } from "../storage/service.js"; + +const captureExceptionMock = vi.hoisted(() => vi.fn()); +vi.mock("../sentry.js", () => ({ captureException: captureExceptionMock })); +vi.mock("../telemetry.js", () => ({ getTelemetryClient: () => null })); + +const SLOW_DOWN = ` +SlowDownPlease reduce your request rate.req-503`; + +const objects = new Map(); +const puts: Array<{ key: string; contentMd5: string | undefined }> = []; +let throttledPuts = 0; + +function respond(req: IncomingMessage, res: ServerResponse, body: Buffer) { + const key = decodeURIComponent((req.url ?? "").split("?")[0]!.replace(/^\/bucket\//, "")); + if (req.method === "PUT") { + puts.push({ key, contentMd5: req.headers["content-md5"] as string | undefined }); + if (throttledPuts > 0) { + throttledPuts--; + res.writeHead(503, { "content-type": "application/xml" }); + res.end(SLOW_DOWN); + return; + } + objects.set(key, body); + res.writeHead(200, { etag: '"saved"' }); + res.end(); + return; + } + if (req.method === "GET" || req.method === "HEAD") { + const object = objects.get(key); + if (!object) { + res.writeHead(404, { "content-type": "application/xml" }); + res.end("NoSuchKey"); + return; + } + res.writeHead(200, { "content-length": object.length, etag: '"saved"' }); + res.end(req.method === "GET" ? object : undefined); + return; + } + res.writeHead(204); + res.end(); +} + +const server = createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", chunk => chunks.push(chunk as Buffer)); + req.on("end", () => respond(req, res, Buffer.concat(chunks))); +}); + +const files: CompanySkillVersionFileInventoryEntry[] = [ + { path: "skills/one/SKILL.md", kind: "skill", content: "---\nname: one\ndescription: Test one\n---\nUse it.\n" }, +]; + +const support = await getEmbeddedPostgresTestSupport(); +describe.skipIf(!support.supported)("skill package uploads under storage request-rate limits", () => { + let database: Awaited>; + let db: ReturnType; + let home: string; + let storage: ReturnType; + const savedEnv = { ...process.env }; + + beforeAll(async () => { + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + const endpoint = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + process.env.AWS_ACCESS_KEY_ID = "fixture-access-key"; + process.env.AWS_SECRET_ACCESS_KEY = "fixture-secret-key"; + delete process.env.AWS_SESSION_TOKEN; + delete process.env.AWS_PROFILE; + home = await fs.mkdtemp(path.join(os.tmpdir(), "skill-package-throttle-")); + process.env.PAPERCLIP_HOME = home; + database = await startEmbeddedPostgresTestDatabase("skill-package-throttle-"); + db = createDb(database.connectionString, { maxConnections: 2 }); + storage = createStorageService(createS3StorageProvider({ bucket: "bucket", region: "us-east-1", endpoint, forcePathStyle: true })); + }); + + beforeEach(() => { + objects.clear(); + puts.length = 0; + throttledPuts = 0; + captureExceptionMock.mockReset(); + vi.spyOn(Math, "random").mockReturnValue(0); + }); + afterEach(() => vi.restoreAllMocks()); + + afterAll(async () => { + process.env = savedEnv; + server.closeAllConnections(); + await new Promise(resolve => server.close(() => resolve())); + await db?.$client.end({ timeout: 1 }); + await database?.cleanup(); + if (home) await fs.rm(home, { recursive: true, force: true }); + }); + + async function company() { + const id = randomUUID(); + await db.insert(companies).values({ id, name: "Throttle test", issuePrefix: `T${id.slice(0, 6)}` }); + return id; + } + + it("resends the archive after a transient SlowDown and publishes the package", async () => { + const companyId = await company(); + throttledPuts = 1; + + const id = await skillPackageStore(db, storage).prepare(companyId, files); + + const [row] = await db.select().from(snapshots).where(eq(snapshots.id, id)); + expect(row!.storage?.archiveKey).toBeTruthy(); + const archivePuts = puts.filter(put => put.key.endsWith("files.tar.gz")); + expect(archivePuts).toHaveLength(2); + expect(archivePuts.every(put => put.contentMd5)).toBe(true); + }); + + it("answers persistent throttling with 503 and lets the same caller retry at once", async () => { + const companyId = await company(); + throttledPuts = Number.POSITIVE_INFINITY; + const store = skillPackageStore(db, storage); + const app = express(); + app.post("/prepare", async (_req, res) => { res.json({ id: await store.prepare(companyId, files) }); }); + app.use(errorHandler); + + const throttled = await request(app).post("/prepare"); + + expect(throttled.status).toBe(503); + expect(throttled.headers["retry-after"]).toBe("30"); + expect(throttled.body).toEqual({ + error: "File storage is temporarily unavailable or is limiting requests. Try again in a moment.", + code: "storage_unavailable", + }); + expect(captureExceptionMock).not.toHaveBeenCalled(); + + throttledPuts = 0; + const retried = await request(app).post("/prepare"); + + expect(retried.status).toBe(200); + const [row] = await db.select().from(snapshots).where(eq(snapshots.id, retried.body.id)); + expect(row!.storage).not.toBeNull(); + }); +}); diff --git a/server/src/__tests__/storage-unavailable-error-handler.test.ts b/server/src/__tests__/storage-unavailable-error-handler.test.ts new file mode 100644 index 00000000000..809143a6df3 --- /dev/null +++ b/server/src/__tests__/storage-unavailable-error-handler.test.ts @@ -0,0 +1,45 @@ +import express from "express"; +import request from "supertest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { errorHandler } from "../middleware/error-handler.js"; +import { recordStorageFailure } from "../storage/failure-diagnostics.js"; + +const captureExceptionMock = vi.hoisted(() => vi.fn()); +vi.mock("../sentry.js", () => ({ captureException: captureExceptionMock })); +vi.mock("../telemetry.js", () => ({ getTelemetryClient: () => null })); + +function createApp(error: unknown) { + const app = express(); + app.post("/work", async () => { throw error; }); + app.use(errorHandler); + return app; +} + +function storageFailure(error: Error, errorCode: string, httpStatus: number | null) { + recordStorageFailure(error, { provider: "s3", operation: "read_object_body", errorCode, httpStatus, requestId: null, attempts: 3 }); + return error; +} + +describe("storage failures in the error handler", () => { + beforeEach(() => captureExceptionMock.mockReset()); + + it("answers a storage connection reset with 503, not as a client abort", async () => { + const reset = storageFailure(Object.assign(new Error("aborted"), { code: "ECONNRESET" }), "ECONNRESET", null); + + const res = await request(createApp(reset)).post("/work"); + + expect(res.status).toBe(503); + expect(res.headers["retry-after"]).toBe("30"); + expect(res.body.code).toBe("storage_unavailable"); + expect(captureExceptionMock).not.toHaveBeenCalled(); + }); + + it("still reports a storage credential rejection as a server fault", async () => { + const rejected = storageFailure(Object.assign(new Error("expired"), { name: "ExpiredToken" }), "ExpiredToken", 400); + + const res = await request(createApp(rejected)).post("/work"); + + expect(res.status).toBe(500); + expect(captureExceptionMock).toHaveBeenCalledTimes(1); + }); +}); diff --git a/server/src/__tests__/tool-access-service.test.ts b/server/src/__tests__/tool-access-service.test.ts index 8aac435e157..15dd9b5afaa 100644 --- a/server/src/__tests__/tool-access-service.test.ts +++ b/server/src/__tests__/tool-access-service.test.ts @@ -11,6 +11,7 @@ import { afterAll, afterEach, beforeAll, + beforeEach, describe, expect, it, @@ -79,6 +80,7 @@ import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase, } from "./helpers/embedded-postgres.js"; +import { useGoogleMcpTransport } from "./helpers/google-workspace-transport.js"; import { classifyRisk, normalizeConnectionMethodConfig, @@ -2999,6 +3001,7 @@ describeEmbeddedPostgres("tool access service", () => { ["with", ["calendar.calendarlist.readonly", "calendar.events", "calendar.events.freebusy"]], ["without", ["calendar.calendarlist.readonly", "calendar.events"]], ] as const)("asks for free/busy with read and write Calendar and keeps Calendar working %s it", async (_label, granted) => { + useGoogleMcpTransport(); const company = await createCompany(db); const userId = `workspace-calendar-${randomUUID()}`; await grantBoardUser(db, company.id, userId, [], "owner"); @@ -8846,6 +8849,7 @@ describeEmbeddedPostgres("tool access service", () => { }); it.each(["user", "organization"] as const)("builds one Workspace catalog from actual partial consent for a %s grant", async (grantKind) => { + useGoogleMcpTransport(); const company = await createCompany(db); const userId = `workspace-member-${randomUUID()}`; await grantBoardUser(db, company.id, userId, [], "owner"); @@ -8884,6 +8888,7 @@ describeEmbeddedPostgres("tool access service", () => { }); describe("combined Workspace service isolation and refresh consent", () => { + beforeEach(() => useGoogleMcpTransport()); async function connectWorkspace(mode: "managed" | "customer", permissions = ["documents.readonly", "gmail.readonly"]) { const company = await createCompany(db); const userId = `workspace-refresh-${randomUUID()}`; @@ -12017,14 +12022,6 @@ describeEmbeddedPostgres("tool access service", () => { // records discovery's universe as its scope set, a later refresh compares the provider's // response against the wider list and an asserted extra scope stops looking unrequested. it("keeps the narrowed request as the refresh baseline for a generic MCP connection", async () => { - vi.stubEnv( - "PAPERCLIP_TOOL_OAUTH_NARROW_EXAMPLE_TEST_CLIENT_ID", - "narrow-client-id", - ); - vi.stubEnv( - "PAPERCLIP_TOOL_OAUTH_NARROW_EXAMPLE_TEST_CLIENT_SECRET", - "narrow-client-secret", - ); const company = await createCompany(db); const userId = `narrow-scope-${randomUUID()}`; await grantBoardUser(db, company.id, userId, [], "owner"); @@ -12084,13 +12081,13 @@ describeEmbeddedPostgres("tool access service", () => { throw new Error(`unexpected fetch ${href}`); }); - const connection = await service.createConnection(company.id, connectionInput({ + const connected = await service.connectGalleryApp(company.id, { + link: "https://narrow.example.test/mcp", name: `Narrow generic ${randomUUID()}`, - transport: "mcp_remote", - config: { url: "https://narrow.example.test/mcp" }, - enabled: true, - status: "active", - })); + authMode: "oauth", + oauthClient: { clientId: "narrow-client-id", clientSecret: "narrow-client-secret" }, + }); + const connection = { id: connected.connectionId }; const started = await service.startOAuth(company.id, connection.id, { redirectUri: "https://paperclip.example/api/tools/oauth/callback", actor: { actorType: "user", actorId: userId }, @@ -15247,9 +15244,50 @@ describeEmbeddedPostgres("tool access service", () => { expect(fetchMock).not.toHaveBeenCalled(); }); - it("uses OAuth client credentials for shared machine-to-machine MCP connections", async () => { + it("sends a deployment OAuth client for a gallery app only to the token endpoint its definition pins", async () => { + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_ID", "slack-deployment-id"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_SECRET", "slack-deployment-secret"); + const company = await createCompany(db); + const userId = `deployment-client-${randomUUID()}`; + await grantBoardUser(db, company.id, userId, ["tools:use", "tools:manage_connections"]); + const service = createTestToolAccessService(db); + const connected = await service.connectGalleryApp(company.id, { galleryKey: "slack", name: "Deployment client" }, + { actorType: "user", actorId: userId }); + const started = await service.startOAuth(company.id, connected.connectionId, { + redirectUri: "https://paperclip.example/api/tools/oauth/callback", + actor: { actorType: "user", actorId: userId }, + }); + expect(new URL(started.authorizationUrl).searchParams.get("client_id")).toBe("slack-deployment-id"); + const tokenRequests: Array<{ url: string; clientId: string | null; clientSecret: string | null }> = []; + vi.spyOn(globalThis, "fetch").mockImplementation(async (url, init) => { + const href = String(url); + if (href === "https://slack.com/api/oauth.v2.access") { + const body = new URLSearchParams(String(init?.body ?? "")); + tokenRequests.push({ url: href, clientId: body.get("client_id"), clientSecret: body.get("client_secret") }); + return { ok: true, status: 200, json: async () => ({ access_token: "deployment-access", refresh_token: "deployment-refresh", expires_in: 3600 }) } as Response; + } + if (href === "https://mcp.slack.com/mcp") { + const payload = JSON.parse(String(init?.body ?? "{}")) as { id?: string; method?: string }; + if (payload.method === "tools/list") return mcpHttpResponse({ jsonrpc: "2.0", id: payload.id, result: { tools: [] } }); + return mcpHttpResponse({ jsonrpc: "2.0", id: payload.id, result: { + protocolVersion: "2025-03-26", capabilities: { tools: {} }, serverInfo: { name: "Slack test", version: "1.0.0" } } }); + } + throw new Error(`unexpected fetch ${href}`); + }); + await service.completeOAuthCallback({ + state: new URL(started.authorizationUrl).searchParams.get("state")!, + code: "deployment-authorization-code", + redirectUri: "https://paperclip.example/api/tools/oauth/callback", + actor: { actorType: "user", actorId: userId }, + }); + expect(tokenRequests).toEqual([{ url: "https://slack.com/api/oauth.v2.access", clientId: "slack-deployment-id", clientSecret: "slack-deployment-secret" }]); + }); + + it("never sends a deployment OAuth client to a machine-to-machine token endpoint of a custom server", async () => { vi.stubEnv("PAPERCLIP_TOOL_OAUTH_M2M_CLIENT_ID", "m2m-client-id"); vi.stubEnv("PAPERCLIP_TOOL_OAUTH_M2M_CLIENT_SECRET", "m2m-client-secret"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_ID", "generic-client-id"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_SECRET", "generic-client-secret"); const company = await createCompany(db); const service = createTestToolAccessService(db); const connection = await service.createConnection(company.id, connectionInput({ @@ -15267,63 +15305,22 @@ describeEmbeddedPostgres("tool access service", () => { enabled: true, status: "active", })); + const sentSecrets: string[] = []; const fetchMock = vi .spyOn(globalThis, "fetch") .mockImplementation(async (url, init) => { - const href = String(url); - if (href === "https://m2m.example.test/oauth/token") { - const body = init?.body as URLSearchParams; - expect(body.get("grant_type")).toBe("client_credentials"); - expect(body.get("client_id")).toBe("m2m-client-id"); - expect(body.get("client_secret")).toBe("m2m-client-secret"); - expect(body.get("scope")).toBe("tools.read"); - return { - ok: true, - json: async () => ({ - access_token: "m2m-access-token", - expires_in: 3600, - token_type: "Bearer", - }), - } as Response; - } - if (href === "https://m2m.example.test/mcp") { - expect(init?.headers).toEqual( - expect.objectContaining({ - Authorization: "Bearer m2m-access-token", - }), - ); - return mcpHttpResponse(catalogResponse([ - { name: "machine_read", annotations: { readOnlyHint: true } }, - ])); - } - throw new Error(`unexpected fetch ${href}`); + const body = init?.body instanceof URLSearchParams ? init.body : null; + if (body?.get("client_secret")) sentSecrets.push(body.get("client_secret")!); + throw new Error(`unexpected fetch ${String(url)}`); }); - const health = await service.checkHealth(connection.id, { + await service.checkHealth(connection.id, { actorType: "system", actorId: "health-check", - }); - expect(health.connection.healthStatus).toBe("ok"); - // Token request, the one-time MCP version probe, and the catalog listing. - expect(fetchMock).toHaveBeenCalledTimes(3); - const [updated] = await db - .select() - .from(toolConnections) - .where(eq(toolConnections.id, connection.id)); - expect(updated.credentialSecretRefs).toEqual([ - expect.objectContaining({ - configPath: "oauth.access_token", - label: "OAuth access token", - }), - ]); - expect(updated.credentialRefs).toEqual([ - expect.objectContaining({ - name: "oauth.access_token", - key: "Authorization", - prefix: "Bearer ", - }), - ]); - expect(JSON.stringify(updated.config)).not.toContain("m2m-access-token"); + }).catch(() => null); + + expect(fetchMock.mock.calls.map(([url]) => String(url))).not.toContain("https://m2m.example.test/oauth/token"); + expect(sentSecrets).toEqual([]); }); it.each(["catalog", "catalog/refresh", "health-check"])("returns reconnect instructions on %s for expired OAuth without a refresh token", async (path) => { @@ -17248,14 +17245,6 @@ describeEmbeddedPostgres("tool access service", () => { ); it("discovers OAuth for pasted MCP links and completes sign-in without a gallery entry", async () => { - vi.stubEnv( - "PAPERCLIP_TOOL_OAUTH_GENERIC_EXAMPLE_TEST_CLIENT_ID", - "generic-client-id", - ); - vi.stubEnv( - "PAPERCLIP_TOOL_OAUTH_GENERIC_EXAMPLE_TEST_CLIENT_SECRET", - "generic-client-secret", - ); vi.stubEnv("PAPERCLIP_PUBLIC_URL", "http://paperclip.test"); const company = await createCompany(db); await grantBoardUser(db, company.id, "board-user", [ @@ -17318,6 +17307,8 @@ describeEmbeddedPostgres("tool access service", () => { .send({ link: "https://generic.example.test/mcp", name: "Generic OAuth MCP", + authMode: "oauth", + oauthClient: { clientId: "generic-client-id", clientSecret: "generic-client-secret" }, }); expect(connectRes.status).toBe(201); diff --git a/server/src/__tests__/tool-connection-content-deletion-canary.test.ts b/server/src/__tests__/tool-connection-content-deletion-canary.test.ts index c36607ce4be..e827469d504 100644 --- a/server/src/__tests__/tool-connection-content-deletion-canary.test.ts +++ b/server/src/__tests__/tool-connection-content-deletion-canary.test.ts @@ -131,7 +131,7 @@ describeEmbeddedPostgres("deleting a connection's stored content leaves no copy companyId: company!.id, name: "Canary agent", role: "engineer", status: "active", adapterType: "process", adapterConfig: {}, runtimeConfig: {}, }).returning(); const [application] = await db.insert(toolApplications).values({ companyId: company!.id, name: `Docs ${randomUUID().slice(0, 6)}`, type: "mcp_http" }).returning(); - const [issue] = await db.insert(issues).values({ companyId: company!.id, title: "Summarise the drive" }).returning(); + const [issue] = await db.insert(issues).values({ companyId: company!.id, title: "Summarise the drive", createdAt: new Date(Date.now() - 60 * 60_000) }).returning(); return { company: company!, agent: agent!, application: application!, issue: issue! }; } @@ -324,7 +324,7 @@ describeEmbeddedPostgres("deleting a connection's stored content leaves no copy const kept = `CANARY${randomUUID().replace(/-/g, "")}`; const flow = await seedConnectionFlow(base, logs, marker); await seedDeliveryRun(base, logs, [{ actionRequestId: flow.actionRequest.id, marker }]); - const [otherIssue] = await db.insert(issues).values({ companyId: base.company.id, title: "Another task" }).returning(); + const [otherIssue] = await db.insert(issues).values({ companyId: base.company.id, title: "Another task", createdAt: new Date(Date.now() - 60 * 60_000) }).returning(); const otherBase = { ...base, issue: otherIssue! }; const otherFlow = await seedConnectionFlow(otherBase, logs, kept); await seedDeliveryRun(otherBase, logs, [{ actionRequestId: otherFlow.actionRequest.id, marker: kept }]); @@ -376,6 +376,123 @@ describeEmbeddedPostgres("deleting a connection's stored content leaves no copy expect(await scan([marker], logs, { taskOwnedCopies: true })).toEqual([]); }); + it("leaves the marker nowhere after deleting a task whose only trace is a connection audit entry", async () => { + const logs = stores(path.join(baseDir, "task-audit-only")); + const base = await seedCompany(); + const marker = `CANARY${randomUUID().replace(/-/g, "")}`; + const [connection] = await db.insert(toolConnections).values({ + companyId: base.company.id, applicationId: base.application.id, name: "Docs audit", uid: randomUUID(), transport: "mcp_remote", status: "active", + }).returning(); + await db.insert(toolAccessAuditEvents).values({ + companyId: base.company.id, connectionId: connection!.id, action: "tool_access.policy_decision", outcome: "denied", + details: { decision: "deny", issueId: base.issue.id, runId: null, toolName: "read_doc", argumentsSummary: summarizeToolValue({ query: marker }) }, + }); + expect((await scan([marker], logs)).length).toBeGreaterThan(0); + + await issueService(db).remove(base.issue.id); + const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage }); + await drainPending(service); + expect(await scan([marker], logs, { taskOwnedCopies: true })).toEqual([]); + }); + + it("only checks open work while waiting, and clears content once the open run settles", async () => { + const logs = stores(path.join(baseDir, "task-wait-cheap")); + const base = await seedCompany(); + const marker = `CANARY${randomUUID().replace(/-/g, "")}`; + const flow = await seedConnectionFlow(base, logs, marker); + const openRunId = randomUUID(); + await db.insert(heartbeatRuns).values({ id: openRunId, companyId: base.company.id, agentId: base.agent.id, issueId: base.issue.id, status: "running" }); + await issueService(db).remove(base.issue.id); + const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage }); + await service.processPending(new AbortController().signal); + const [first] = await db.select().from(issueConnectionContentDeletions).where(eq(issueConnectionContentDeletions.issueId, base.issue.id)); + expect(first!.progress).toMatchObject({ phase: "done", waiting: true }); + + const late = summarizeToolValue({ text: `Late ${marker}` }); + const [lateCall] = await db.insert(toolInvocations).values({ + companyId: base.company.id, connectionId: flow.connection.id, runId: flow.callingRunId, toolName: "read_doc", status: "succeeded", + argumentsSummary: late, resultSummary: late, + }).returning(); + await db.update(issueConnectionContentDeletions).set({ notBefore: new Date() }).where(eq(issueConnectionContentDeletions.id, first!.id)); + await service.processPending(new AbortController().signal); + const [rechecked] = await db.select().from(issueConnectionContentDeletions).where(eq(issueConnectionContentDeletions.id, first!.id)); + expect(rechecked!.progress).toMatchObject({ phase: "done", waiting: true }); + const [untouched] = await db.select().from(toolInvocations).where(eq(toolInvocations.id, lateCall!.id)); + expect(untouched!.resultSummary?.summary).toContain(marker); + + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, openRunId)); + await db.update(issueConnectionContentDeletions).set({ notBefore: new Date() }).where(eq(issueConnectionContentDeletions.id, first!.id)); + await drainPending(service); + expect(await scan([marker], logs, { taskOwnedCopies: true })).toEqual([]); + }); + + it.each(["approval", "wake"] as const)("waits while only an open %s remains, then clears the task's content", async (open) => { + const logs = stores(path.join(baseDir, `task-open-${open}`)); + const base = await seedCompany(); + const marker = `CANARY${randomUUID().replace(/-/g, "")}`; + const flow = await seedConnectionFlow(base, logs, marker); + await seedDeliveryRun(base, logs, [{ actionRequestId: flow.actionRequest.id, marker }]); + const reopen = open === "approval" + ? () => db.update(toolActionRequests).set({ status: "pending" }).where(eq(toolActionRequests.id, flow.actionRequest.id)) + : () => db.update(agentWakeupRequests).set({ status: "queued" }).where(eq(agentWakeupRequests.companyId, base.company.id)); + const settle = open === "approval" + ? () => db.update(toolActionRequests).set({ status: "executed" }).where(eq(toolActionRequests.id, flow.actionRequest.id)) + : () => db.update(agentWakeupRequests).set({ status: "completed" }).where(eq(agentWakeupRequests.companyId, base.company.id)); + await reopen(); + + await issueService(db).remove(base.issue.id); + const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage }); + await service.processPending(new AbortController().signal); + const [job] = await db.select().from(issueConnectionContentDeletions).where(eq(issueConnectionContentDeletions.issueId, base.issue.id)); + expect(job!.progress).toMatchObject({ phase: "done", waiting: true }); + await db.update(issueConnectionContentDeletions).set({ notBefore: new Date() }).where(eq(issueConnectionContentDeletions.id, job!.id)); + await service.processPending(new AbortController().signal); + const [still] = await db.select().from(issueConnectionContentDeletions).where(eq(issueConnectionContentDeletions.id, job!.id)); + expect(still!.progress).toMatchObject({ waiting: true }); + + await settle(); + await db.update(issueConnectionContentDeletions).set({ notBefore: new Date() }).where(eq(issueConnectionContentDeletions.id, job!.id)); + await drainPending(service); + expect(await scan([marker], logs, { taskOwnedCopies: true })).toEqual([]); + }); + + it("does not wait for an open wake that carries no result of the task", async () => { + const logs = stores(path.join(baseDir, "task-unrelated-wake")); + const base = await seedCompany(); + const marker = `CANARY${randomUUID().replace(/-/g, "")}`; + await seedConnectionFlow(base, logs, marker); + await db.insert(agentWakeupRequests).values([ + { companyId: base.company.id, agentId: base.agent.id, source: "automation", status: "queued", payload: { issueId: base.issue.id } }, + { companyId: base.company.id, agentId: base.agent.id, source: "automation", status: "queued", + payload: { issueId: base.issue.id, toolActionRequestIds: [randomUUID()] } }, + ]); + await issueService(db).remove(base.issue.id); + const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage }); + await service.processPending(new AbortController().signal); + const [job] = await db.select().from(issueConnectionContentDeletions).where(eq(issueConnectionContentDeletions.issueId, base.issue.id)); + expect(job!.status).toBe("completed"); + expect(await scan([marker], logs, { taskOwnedCopies: true })).toEqual([]); + }); + + it("does not wait for an audit entry whose run no longer exists", async () => { + const logs = stores(path.join(baseDir, "task-dangling-run")); + const base = await seedCompany(); + const marker = `CANARY${randomUUID().replace(/-/g, "")}`; + const [connection] = await db.insert(toolConnections).values({ + companyId: base.company.id, applicationId: base.application.id, name: "Docs dangling", uid: randomUUID(), transport: "mcp_remote", status: "active", + }).returning(); + await db.insert(toolAccessAuditEvents).values({ + companyId: base.company.id, connectionId: connection!.id, action: "tool_access.policy_decision", outcome: "success", + details: { decision: "allow", issueId: base.issue.id, runId: randomUUID(), toolName: "read_doc", argumentsSummary: summarizeToolValue({ query: marker }) }, + }); + await issueService(db).remove(base.issue.id); + const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage }); + await service.processPending(new AbortController().signal); + const [job] = await db.select().from(issueConnectionContentDeletions).where(eq(issueConnectionContentDeletions.issueId, base.issue.id)); + expect(job!.status).toBe("completed"); + expect(await scan([marker], logs, { taskOwnedCopies: true })).toEqual([]); + }); + it("removes content a run of the task writes after the task is deleted", async () => { const logs = stores(path.join(baseDir, "task-late")); const base = await seedCompany(); diff --git a/server/src/__tests__/tool-gateway-service.test.ts b/server/src/__tests__/tool-gateway-service.test.ts index b7b61a5f4f0..4aeadc56de2 100644 --- a/server/src/__tests__/tool-gateway-service.test.ts +++ b/server/src/__tests__/tool-gateway-service.test.ts @@ -69,6 +69,7 @@ import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase, } from "./helpers/embedded-postgres.js"; +import { useGoogleMcpTransport } from "./helpers/google-workspace-transport.js"; import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; @@ -3308,6 +3309,7 @@ describeEmbeddedPostgres("tool gateway service", () => { ["people__get_user_profile", "userinfo.profile", "people"], ["search__search_corpus", null, "workspacemcp"], ] as const)("routes %s and denies cached actions after consent changes", async (toolName, permission, host) => { + useGoogleMcpTransport(); const { company, agent, run } = await createRunFixture(db); await db.insert(companyMemberships).values({ companyId: company.id, principalType: "user", principalId: "board", status: "active", membershipRole: "owner" }); const { connection, catalogEntry } = await createRemoteMcpToolFixture(db, company.id); @@ -3609,6 +3611,45 @@ describeEmbeddedPostgres("tool gateway service", () => { expect(resolvedGrants).toHaveLength(3); }); + it("selects the managed GitHub identity of the person who opened the session", async () => { + const { company, agent, issue, run } = await createRunFixture(db); + const { connection } = await createRemoteMcpToolFixture(db, company.id); + await db.update(toolConnections).set({ authKind: "oauth", credentialSource: "paperclip_vault", + config: { ...connection.config, sourceTemplateKey: "github" }, + }).where(eq(toolConnections.id, connection.id)); + await db.insert(toolConnectionInstalls).values({ companyId: company.id, + connectionId: connection.id, targetType: "agent", targetId: agent.id }); + await db.insert(companyMemberships).values(["A", "B", "C"].map(principalId => ({ companyId: company.id, + principalType: "user", principalId, status: "active", membershipRole: "member" }))); + const grants = await db.insert(connectionGrants).values(["A", "B"].map(subjectUserId => ({ + companyId: company.id, connectionId: connection.id, kind: "user" as const, subjectUserId, + status: "active" as const, credentialSecretRefs: [], + }))).returning(); + await initializeRunIdentity(db, { companyId: company.id, runId: run.id, issueId: issue.id, + responsibleUserId: "A", cause: "instruction" }); + await db.insert(toolPolicies).values(readPolicyRow(company, "Allow reads")); + const resolvedGrants: string[] = []; + const gateway = createTestToolGatewayService(db, { + oauthGrantRefresher: async ({ grantId }) => { + resolvedGrants.push(grantId); + return db.select().from(connectionGrants).where(eq(connectionGrants.id, grantId)).then(rows => rows[0]!); + }, + remoteHttpRequest: async (_url, init) => new Response(JSON.stringify({ jsonrpc: "2.0", + id: JSON.parse(String(init.body)).id, result: { content: [{ type: "text", text: "ok" }] }, + }), { status: 200, headers: { "content-type": "application/json" } }), + }); + const callAs = async (createdByUserId: string) => { + const session = await gateway.createSession({ ...runSessionInput(company, agent, run), createdByUserId }); + const tool = (await gateway.listToolsForSession(session.token)).find(t => t.providerType === "mcp_remote_http")!; + return gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: {} }); + }; + + expect((await callAs("B")).status).toBe("completed"); + expect(resolvedGrants).toEqual([grants[1]!.id]); + await expect(callAs("C")).rejects.toMatchObject({ reasonCode: "github_identity_unavailable" }); + expect(resolvedGrants).toEqual([grants[1]!.id]); + }); + it.each([false, true])("reselects a duplicate only before GitHub dispatch (upstream failure: %s)", async (upstreamFailure) => { const { company, agent, issue, run } = await createRunFixture(db); const first = await createRemoteMcpToolFixture(db, company.id); diff --git a/server/src/__tests__/tool-gateway.test.ts b/server/src/__tests__/tool-gateway.test.ts index 3135bd8010e..81d7751a28b 100644 --- a/server/src/__tests__/tool-gateway.test.ts +++ b/server/src/__tests__/tool-gateway.test.ts @@ -5,7 +5,7 @@ import { createServer, type IncomingMessage } from "node:http"; import { tmpdir } from "node:os"; import { join } from "node:path"; import express from "express"; -import { and, eq, sql } from "drizzle-orm"; +import { and, desc, eq, sql } from "drizzle-orm"; import type { LiveEvent } from "@paperclipai/shared"; import { requestConfirmationPayloadSchema } from "@paperclipai/shared"; import { subscribeCompanyLiveEvents } from "../services/live-events.js"; @@ -57,6 +57,8 @@ import { resolveNativeRuntimeMcpSnapshot } from "../services/native-runtime/runt import type { ToolMcpGatewayTokenAction } from "@paperclipai/shared"; import type { PluginToolDispatcher } from "../services/plugin-tool-dispatcher.js"; import { mcpGatewayProtocolRoutes, toolGatewayRoutes } from "../routes/tool-gateway.js"; +import { issueRoutes } from "../routes/issues.js"; +import { errorHandler } from "../middleware/error-handler.js"; import { toolAccessService } from "../services/tool-access.js"; import { canonicalToolArguments, @@ -2229,6 +2231,173 @@ rl.on("line", (line) => { }, ); + it("acts as the person who opened a session and never uses another member's personal grant", async () => { + const company = await createCompany(db); + const agent = await createAgent(db, company.id); + const { issue, run } = await createIssueAndRun(db, company.id, agent.id); + for (const userId of ["alice", "bob", "carol"]) await createActiveMember(db, company.id, userId); + await db.update(heartbeatRuns).set({ responsibleUserId: "alice" }).where(eq(heartbeatRuns.id, run.id)); + const secrets = secretService(db); + const definition = await secrets.createUserSecretDefinition(company.id, { + name: "Personal mail token", + key: `personal_mail_${randomUUID().replace(/-/g, "")}`, + provider: "local_encrypted", + }); + const personal = await createRemoteMcpTool(db, company.id, { toolName: "read_mail" }); + await secrets.syncUserSecretDeclarationsForTarget(company.id, + { targetType: "tool_connection", targetId: personal.connection.id }, + [{ definitionKey: definition.key, configPath: "credentials.authorization", envKey: "Authorization", versionSelector: "latest", required: true }], + { replaceAll: true }); + const personalSecrets = new Map(); + for (const userId of ["alice", "bob"]) { + const secret = await secrets.createCurrentUserSecretValue(company.id, userId, { + definitionId: definition.id, value: `${userId}-personal-token`, + }); + personalSecrets.set(userId, secret.id); + await db.insert(connectionGrants).values({ + companyId: company.id, connectionId: personal.connection.id, kind: "user", subjectUserId: userId, + credentialSecretRefs: [{ secretId: secret.id, configPath: "credentials.authorization", versionSelector: "latest" }], + status: "active", isDefault: false, + }); + } + await db.update(toolConnections).set({ + credentialPolicy: "per_user", + credentialRefs: [{ name: "credentials.authorization", secretId: personalSecrets.get("alice")!, placement: "header", key: "Authorization", prefix: "Bearer " }], + }).where(eq(toolConnections.id, personal.connection.id)); + const shared = await createRemoteMcpTool(db, company.id, { toolName: "shared_lookup" }); + await allowAllToolsForAgent(db, company.id, agent.id); + const authorizations: string[] = []; + const gateway = createTestToolGatewayService(db, { remoteHttpRequest: async (_url, init) => { + authorizations.push(new Headers(init.headers).get("authorization") ?? ""); + const body = JSON.parse(String(init.body)) as { id: string }; + return new Response(JSON.stringify({ jsonrpc: "2.0", id: body.id, + result: { content: [{ type: "text", text: "synthetic result" }] } }), + { headers: { "content-type": "application/json" } }); + } }); + const boardActor = (userId: string): Express.Request["actor"] => ({ + type: "board", + userId, + source: "session", + companyIds: [company.id], + memberships: [{ companyId: company.id, membershipRole: "member", status: "active" }], + isInstanceAdmin: false, + }); + const openSession = async (userId: string) => { + const response = await request(createGatewayRouteApp(db, gateway, boardActor(userId))) + .post("/api/tool-gateway/sessions") + .send({ companyId: company.id, agentId: agent.id, runId: run.id }); + expect(response.status).toBe(201); + return response.body.token as string; + }; + const callTool = async (token: string, connectionId: string) => { + const tool = (await gateway.listToolsForSession(token)).find((item) => item.connectionId === connectionId)!; + return request(createGatewayRouteApp(db, gateway)) + .post("/api/tool-gateway/tools/call") + .set("x-paperclip-tool-gateway-token", token) + .send({ tool: tool.name, parameters: { key: "test", value: randomUUID() } }); + }; + const lastAuthorization = () => authorizations.at(-1); + const callWith = async (token: string, connectionId: string, parameters: Record) => { + const tool = (await gateway.listToolsForSession(token)).find((item) => item.connectionId === connectionId)!; + return request(createGatewayRouteApp(db, gateway)) + .post("/api/tool-gateway/tools/call") + .set("x-paperclip-tool-gateway-token", token) + .send({ tool: tool.name, parameters }); + }; + + const bobToken = await openSession("bob"); + expect((await callTool(bobToken, personal.connection.id)).body.status).toBe("completed"); + expect(lastAuthorization()).toBe("Bearer bob-personal-token"); + expect((await callTool(bobToken, shared.connection.id)).body.status).toBe("completed"); + + const aliceToken = await openSession("alice"); + expect((await callTool(aliceToken, personal.connection.id)).body.status).toBe("completed"); + expect(lastAuthorization()).toBe("Bearer alice-personal-token"); + + const sameWrite = { key: "same", value: randomUUID() }; + expect((await callWith(bobToken, personal.connection.id, sameWrite)).body.status).toBe("completed"); + expect(lastAuthorization()).toBe("Bearer bob-personal-token"); + const aliceSameWrite = await callWith(aliceToken, personal.connection.id, sameWrite); + expect(aliceSameWrite.body.status).toBe("completed"); + expect(lastAuthorization()).toBe("Bearer alice-personal-token"); + const bobRetry = await callWith(bobToken, personal.connection.id, sameWrite); + expect(bobRetry.body.status).toBe("replayed"); + + const savedBeforeUpgrade = async (parameters: Record, recordedActor: { actorType: string; actorId: string } | null) => { + expect((await callWith(bobToken, personal.connection.id, parameters)).body.status).toBe("completed"); + const [row] = await db.select().from(toolInvocations) + .where(and(eq(toolInvocations.companyId, company.id), sql`${toolInvocations.idempotencyKey} like '%:opened_by:%'`)) + .orderBy(desc(toolInvocations.createdAt)).limit(1); + const { sessionOpenedByUserId: _opener, ...explanation } = (row!.policyExplanation ?? {}) as Record; + await db.update(toolInvocations).set({ + idempotencyKey: row!.idempotencyKey!.split(":opened_by:")[0], + policyExplanation: explanation, + ...(recordedActor ?? {}), + }).where(eq(toolInvocations.id, row!.id)); + return authorizations.length; + }; + const attributedWrite = { key: "upgrade-attributed", value: randomUUID() }; + let providerCalls = await savedBeforeUpgrade(attributedWrite, { actorType: "user", actorId: "bob" }); + expect((await callWith(bobToken, personal.connection.id, attributedWrite)).body.status).toBe("replayed"); + expect(authorizations).toHaveLength(providerCalls); + expect((await callWith(aliceToken, personal.connection.id, attributedWrite)).body.status).toBe("completed"); + expect(lastAuthorization()).toBe("Bearer alice-personal-token"); + + const unattributedWrite = { key: "upgrade-unattributed", value: randomUUID() }; + providerCalls = await savedBeforeUpgrade(unattributedWrite, null); + const unattributedRetry = await callWith(bobToken, personal.connection.id, unattributedWrite); + expect(unattributedRetry.status).toBe(409); + expect(authorizations).toHaveLength(providerCalls); + + const agentSession = await gateway.createSession({ companyId: company.id, agentId: agent.id, runId: run.id, actorType: "agent", actorId: agent.id }); + expect((await callTool(agentSession.token, personal.connection.id)).body.status).toBe("completed"); + expect(lastAuthorization()).toBe("Bearer alice-personal-token"); + + const callsBeforeCarol = authorizations.length; + const carol = await callTool(await openSession("carol"), personal.connection.id); + expect(carol.status).toBe(409); + expect(carol.body.reasonCode).toBe("user_authorization_required"); + expect(authorizations).toHaveLength(callsBeforeCarol); + const prompts = await db.select({ addresseeUserId: issueThreadInteractions.addresseeUserId }) + .from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, issue.id)); + expect(prompts.map((prompt) => prompt.addresseeUserId)).toEqual(["carol"]); + + await db.insert(toolPolicies).values({ + companyId: company.id, + name: "Review personal mail", + policyType: "require_approval", + selectors: { connectionId: personal.connection.id }, + priority: 10, + }); + const reviewed = await callTool(bobToken, personal.connection.id); + expect(reviewed.status).toBe(409); + expect(reviewed.body.reasonCode).toBe("approval_required"); + const [pending] = await db.select().from(toolActionRequests) + .where(and(eq(toolActionRequests.companyId, company.id), eq(toolActionRequests.status, "pending"))); + await gateway.approveActionRequest({ companyId: company.id, actionRequestId: pending!.id, actor: { userId: "bob" } }); + expect(lastAuthorization()).toBe("Bearer bob-personal-token"); + }); + + it("refuses a person-created session when the person may not act on the agent", async () => { + const company = await createCompany(db); + const agent = await createAgent(db, company.id); + const { run } = await createIssueAndRun(db, company.id, agent.id); + await db.insert(companyMemberships).values({ + companyId: company.id, principalType: "user", principalId: "viewer-user", status: "active", membershipRole: "viewer", + }); + const response = await request(createGatewayRouteApp(db, createTestToolGatewayService(db), { + type: "board", + userId: "viewer-user", + source: "session", + companyIds: [company.id], + memberships: [{ companyId: company.id, membershipRole: "member", status: "active" }], + isInstanceAdmin: false, + })) + .post("/api/tool-gateway/sessions") + .send({ companyId: company.id, agentId: agent.id, runId: run.id }); + expect(response.status).toBe(403); + }); + it("passes only the selected grant identity to local stdio MCP processes", async () => { const company = await createCompany(db); const agent = await createAgent(db, company.id); @@ -5739,6 +5908,147 @@ rl.on("line", (line) => { } }); + it.each([ + { scenario: "a chat owned by one member", outsiderAllowed: false, outsiderStatus: 403, + issuePatch: (agentId: string) => ({ conversationAgentId: agentId, conversationUserId: "alice", conversationState: "active" as const }) }, + { scenario: "a personal dashboard conversation", outsiderAllowed: false, outsiderStatus: 404, + issuePatch: () => ({ originKind: "responsibility_dashboard", originId: "alice" }) }, + { scenario: "an ordinary task", outsiderAllowed: true, outsiderStatus: 200, + issuePatch: () => ({}) }, + ])("gives the direct tool review routes and the issue thread path the same answer for $scenario", async ({ outsiderAllowed, outsiderStatus, issuePatch }) => { + const company = await createCompany(db); + const agent = await createAgent(db, company.id); + const { issue, run } = await createIssueAndRun(db, company.id, agent.id); + await createActiveMember(db, company.id, "alice"); + await createActiveMember(db, company.id, "bob"); + const patch = issuePatch(agent.id); + if (Object.keys(patch).length > 0) await db.update(issues).set(patch).where(eq(issues.id, issue.id)); + const remote = await createRemoteMcpTool(db, company.id, { toolName: "send_note", riskLevel: "write" }); + await allowAllToolsForAgent(db, company.id, agent.id); + await db.insert(toolPolicies).values({ + companyId: company.id, + name: "Review note writes", + policyType: "require_approval", + selectors: { connectionId: remote.connection.id }, + priority: 10, + }); + const gateway = createTestToolGatewayService(db, { remoteHttpRequest: async (_url, init) => { + const body = JSON.parse(String(init.body)) as { id: string }; + return new Response(JSON.stringify({ jsonrpc: "2.0", id: body.id, result: { content: [{ type: "text", text: "sent" }] } }), + { headers: { "content-type": "application/json" } }); + } }); + const session = await gateway.createSession({ companyId: company.id, agentId: agent.id, runId: run.id }); + const tool = (await gateway.listToolsForSession(session.token)).find((item) => item.connectionId === remote.connection.id)!; + const requestReview = async () => { + await gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: { key: "note", value: randomUUID() } }) + .then(() => { throw new Error("Expected the call to need review"); }, (error) => expectGatewayError(error, 409, "approval_required")); + const [pending] = await db.select().from(toolActionRequests) + .where(and(eq(toolActionRequests.companyId, company.id), eq(toolActionRequests.status, "pending"))); + return pending!; + }; + const boardActor = (userId: string): Express.Request["actor"] => ({ + type: "board", + userId, + source: "session", + companyIds: [company.id], + memberships: [{ companyId: company.id, membershipRole: "member", status: "active" }], + isInstanceAdmin: false, + }); + const issueApp = (userId: string) => { + const app = express(); + app.use(express.json()); + app.use((req, _res, next) => { + req.actor = boardActor(userId); + next(); + }); + app.use("/api", issueRoutes(db, {} as never, { + approveToolActionRequest: (input) => gateway.approveActionRequest(input), + declineToolActionRequest: (input) => gateway.declineActionRequest(input), + })); + app.use(errorHandler); + return app; + }; + const direct = (userId: string, actionRequestId: string, decision: "approve" | "decline") => + request(createGatewayRouteApp(db, gateway, boardActor(userId))) + .post(`/api/tool-gateway/action-requests/${actionRequestId}/${decision}`) + .send({ companyId: company.id }); + const outcomes = async (userId: string, decision: "approve" | "decline") => { + const viaIssue = await requestReview(); + const issueStatus = (await request(issueApp(userId)) + .post(`/api/issues/${issue.id}/interactions/${viaIssue.interactionId}/${decision === "approve" ? "accept" : "reject"}`) + .send({})).status; + const viaDirect = await requestReview(); + const directStatus = (await direct(userId, viaDirect.id, decision)).status; + const [after] = await db.select({ status: toolActionRequests.status }).from(toolActionRequests) + .where(eq(toolActionRequests.id, viaDirect.id)); + await db.update(toolActionRequests).set({ status: "expired" }) + .where(and(eq(toolActionRequests.companyId, company.id), eq(toolActionRequests.status, "pending"))); + return { issueAllowed: issueStatus < 300, directAllowed: directStatus < 300, directRequestStatus: after!.status }; + }; + + for (const decision of ["approve", "decline"] as const) { + const outsider = await outcomes("bob", decision); + expect(outsider.issueAllowed).toBe(outsiderAllowed); + expect(outsider.directAllowed).toBe(outsiderAllowed); + if (!outsiderAllowed) expect(outsider.directRequestStatus).toBe("pending"); + const owner = await outcomes("alice", decision); + expect(owner).toMatchObject({ issueAllowed: true, directAllowed: true }); + } + + const settled = await requestReview(); + expect((await direct("alice", settled.id, "approve")).status).toBe(200); + expect((await direct("bob", settled.id, "approve")).status).toBe(outsiderAllowed ? 200 : outsiderStatus); + expect((await direct("bob", settled.id, "decline")).status).toBe(outsiderAllowed ? 409 : outsiderStatus); + + await db.update(toolActionRequests).set({ status: "approved" }).where(eq(toolActionRequests.id, settled.id)); + await expect(gateway.approveActionRequest({ + companyId: company.id, actionRequestId: settled.id, actor: { userId: "alice" }, recoveringApprovedReview: true, + })).resolves.toBeDefined(); + + const unverifiable = await requestReview(); + await db.update(toolActionRequests).set({ signedArguments: "unverifiable" }).where(eq(toolActionRequests.id, unverifiable.id)); + const outsiderOnUnverifiable = await direct("bob", unverifiable.id, "approve"); + if (!outsiderAllowed) { + expect(outsiderOnUnverifiable.status).toBe(outsiderStatus); + const [untouched] = await db.select({ status: toolActionRequests.status }).from(toolActionRequests) + .where(eq(toolActionRequests.id, unverifiable.id)); + expect(untouched!.status).toBe("pending"); + const expired = await requestReview(); + await db.update(toolActionRequests).set({ expiresAt: new Date(Date.now() - 60_000) }).where(eq(toolActionRequests.id, expired.id)); + const outsiderOnExpired = await direct("bob", expired.id, "approve"); + expect(outsiderOnExpired.status).toBe(outsiderStatus); + expect(JSON.stringify(outsiderOnExpired.body)).not.toMatch(/expire|approvalId|target_changed/i); + await db.update(toolActionRequests).set({ status: "expired" }).where(eq(toolActionRequests.id, expired.id)); + } + await db.update(toolActionRequests).set({ status: "expired" }).where(eq(toolActionRequests.id, unverifiable.id)); + + const anonymous = await requestReview(); + await expect(gateway.approveActionRequest({ companyId: company.id, actionRequestId: anonymous.id, actor: { userId: null } })) + .rejects.toMatchObject({ status: 403 }); + await expect(gateway.declineActionRequest({ companyId: company.id, actionRequestId: anonymous.id, actor: { userId: null } })) + .rejects.toMatchObject({ status: 403 }); + const [stillPending] = await db.select({ status: toolActionRequests.status }).from(toolActionRequests) + .where(eq(toolActionRequests.id, anonymous.id)); + expect(stillPending!.status).toBe("pending"); + await db.update(toolActionRequests).set({ status: "expired" }).where(eq(toolActionRequests.id, anonymous.id)); + + const legacyApproved = await requestReview(); + await db.update(toolActionRequests).set({ status: "approved", decidedAt: new Date(), decidedByUserId: null, resolvedByUserId: null }) + .where(eq(toolActionRequests.id, legacyApproved.id)); + await expect(gateway.recoverApprovedActionReviews(company.id)).resolves.toMatchObject({ retry: false }); + const [recovered] = await db.select({ status: toolActionRequests.status }).from(toolActionRequests) + .where(eq(toolActionRequests.id, legacyApproved.id)); + expect(recovered!.status).not.toBe("approved"); + await expect(gateway.recoverApprovedActionReviews(company.id)).resolves.toMatchObject({ retry: false }); + + const detached = await requestReview(); + expect((await direct("alice", detached.id, "approve")).status).toBe(200); + await db.update(toolActionRequests).set({ issueId: null, interactionId: null, requestedByUserId: "alice", decidedByUserId: null, resolvedByUserId: null }) + .where(eq(toolActionRequests.id, detached.id)); + expect((await direct("bob", detached.id, "approve")).status).toBe(404); + expect((await direct("alice", detached.id, "approve")).status).toBe(200); + }); + it("denies agents without responsible-user authority from runtime control and gateway audit routes", async () => { const company = await createCompany(db); const agent = await createAgent(db, company.id); diff --git a/server/src/adapters/registry.ts b/server/src/adapters/registry.ts index adc1304bd10..8512db5a0ff 100644 --- a/server/src/adapters/registry.ts +++ b/server/src/adapters/registry.ts @@ -2,6 +2,7 @@ import { pluginRunnerAiConnectionRequiredTestResult } from "../services/plugin-r import { HttpError } from "../errors.js"; import type { AdapterRuntimeCommandSpec, ServerAdapterModule } from "./types.js"; import { parseAdapterModelsEnv } from "../services/adapter-models-env.js"; +import { isAiKeyVerificationFailureCode } from "../services/ai-api-key-failures.js"; import { validateAiApiKey } from "../services/ai-api-key-test.js"; import type { AdapterEnvironmentTestResult } from "@paperclipai/shared"; import { stampClaudeAgentIdHeader } from "./claude-agent-id-header.js"; @@ -169,9 +170,10 @@ async function verifyNativeAcpxApiKey( } catch (error) { const details = error && typeof error === "object" && "details" in error ? error.details as { code?: string } | undefined : undefined; + const code = isAiKeyVerificationFailureCode(details?.code) ? details.code : "ai_connection_verification_failed"; + const reason = code !== "ai_connection_verification_failed" && error instanceof Error ? error.message : "Check the connection and try again."; return { ...result, status: "fail", checks: [...result.checks, { - code: details?.code === "ai_connection_api_key_rejected" ? details.code : "ai_connection_verification_failed", - level: "error", message: `Could not verify the ${account.name} API key. Check the connection and try again.`, + code, level: "error", message: `Could not verify the ${account.name} API key. ${reason}`, }] }; } } diff --git a/server/src/google-workspace-rest-tools/README.md b/server/src/google-workspace-rest-tools/README.md index b84398a501b..11d2d43bf14 100644 --- a/server/src/google-workspace-rest-tools/README.md +++ b/server/src/google-workspace-rest-tools/README.md @@ -113,9 +113,10 @@ deployment is ever needed; the gateway does not use it. One setting per service, `GOOGLE_WORKSPACE_TOOL_TRANSPORT` in `packages/shared/src/google-workspace-connectors.ts`: -- `google_mcp` (every service today): calls go to Google's hosted MCP server - for that service, exactly as before this folder existed. -- `paperclip_rest`: calls go to this folder. +- `paperclip_rest`: calls go to this folder. Gmail, Drive, Docs, Sheets, + Slides and Calendar use it since 2026-11-23. +- `google_mcp`: calls go to Google's hosted MCP server for that service. + Chat, People and Search use it; they are not offered for new setup. `googleWorkspaceToolTarget(name)` returns the setting as `transport`. It is a plain constant: no environment variable, instance setting or database row. @@ -242,6 +243,60 @@ result and 0.24 ms for a 700 KB one. `google-workspace-rest-dispatch.test.ts`, fails while any service set to `paperclip_rest` is missing an allowlisted tool, so a partial flip cannot ship. +### Connections saved before a switch + +A connection keeps the tool definitions its last catalog refresh saved. After +a service switches to `paperclip_rest`, the saved definitions of an existing +connection are still Google's MCP definitions. Two things keep such a +connection working with no user action: + +- **Agents see this folder's definitions at once.** When the gateway lists a + connection's tools for an agent, it takes the input schema, output schema, + description and annotations of a `paperclip_rest` tool from this folder, not + from the saved row. It asks `paperclipDefinedTool` in + `server/src/services/connectors/paperclip-defined-tools.ts`, which calls + `googleWorkspaceRestToolDefinition` in the adapter. + Routing and the advertised definition read the same transport setting in + the same process, so an agent never gets Google's MCP schema for a call that + goes to REST. This is an in-memory lookup: no request and no refresh before + the turn starts. +- **The next catalog refresh saves this folder's definitions.** Catalog + publication asks the same `paperclipDefinedTool`. It never holds such an + action for review, and it clears the review hold (`quarantined`, + `pending_review`) of an action held only because a remote definition + changed. Clearing the hold does not count the action as new, so it does not + add the action to the connection's profile: an action a person turned Off + (left out of the profile) stays Off, also when it was held, and an Ask first + policy stays in force. Only actions the connection never had (Gmail + `list_threads` and `search_messages`) get the connection's default for new + actions. + +The saved risk level of an action changes only on that refresh. Until then, +`docs__update_doc`, `slides__update_presentation`, `sheets__update_spreadsheet` +and `calendar__update_event` keep the level saved from Google's MCP +definition (`write`); after it they are `destructive`. Write actions are +Allowed by default at either level. + +### Input differences an agent meets after a switch + +Checked against Google's published MCP references, since no `tools/list` +from Google's servers is recorded yet. These are the cases where a call that +Google's saved schema allowed is refused by this folder; each is also stated +in the tool's own description and schema, which agents now receive: + +| Tool | Google's schema | This folder | +| --- | --- | --- | +| `docs__update_doc`, `slides__update_presentation` | `writeControl` optional; `targetRevisionId` allowed | `writeControl.requiredRevisionId` required (read the document first); `targetRevisionId` refused | +| `docs__update_doc`, `slides__update_presentation` | any request kind | closed list of request kinds; kinds that read another file refused | +| `sheets__update_spreadsheet` | `writeControl` allowed | `writeControl` refused (no revision check in Sheets REST) | +| `sheets__get_spreadsheet` | `commentsIncluded: true` allowed | refused (not in the Sheets API) | +| `sheets__insert_dimension` | `DIMENSION_UNSPECIFIED` in the enum | refused | +| `calendar__delete_event` | a recurring series ID deletes the series | refused; pass one occurrence | +| `gmail__create_draft` | attachments | refused, as Google's tool does today | +| `drive__search_files` | full MCP query language and `orderBy` | terms without a Drive `q` equivalent refused; `orderBy` limited | + +Each refusal is a tool error that says what to do, and nothing is changed. + ## Known differences from Google's MCP tools - **Descriptions** are our own wording; names, fields, types, enums, required diff --git a/server/src/middleware/error-handler.ts b/server/src/middleware/error-handler.ts index 758c3b26c67..a58bd7eba1e 100644 --- a/server/src/middleware/error-handler.ts +++ b/server/src/middleware/error-handler.ts @@ -24,6 +24,7 @@ import { isOpenRouterCatalogUnavailable } from "../services/openrouter-models.js import { ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE, readTransientSandboxCreationRefusal } from "../services/environment-provider-unavailable-error.js"; import { isEndedDbPoolError } from "../database-retry.js"; import { ToolGatewayHttpError } from "../services/tool-gateway.js"; +import { isStorageCredentialRejection, isStorageUnavailableError, recordedStorageFailureDiagnostics, STORAGE_TEMPORARILY_UNAVAILABLE_MESSAGE, STORAGE_UNAVAILABLE_CODE } from "../storage/storage-unavailable.js"; export interface ErrorContext { error: { @@ -299,7 +300,8 @@ export function errorHandler( // answer, so skip the error sinks and just close out the response. if ( rootError.message === "aborted" && - (rootError as NodeJS.ErrnoException).code === "ECONNRESET" + (rootError as NodeJS.ErrnoException).code === "ECONNRESET" && + !isStorageUnavailableError(rootError) ) { if (!res.headersSent) res.status(499); res.end(); @@ -355,6 +357,18 @@ export function errorHandler( return; } + if (isStorageUnavailableError(rootError) && !isStorageCredentialRejection(rootError)) { + logger.warn({ method: req.method, route: req.route?.path, storageFailure: recordedStorageFailureDiagnostics(rootError) }, + "File storage was unavailable for a request"); + if (!res.headersSent) { + res.set("Retry-After", "30"); + res.status(503).json({ error: STORAGE_TEMPORARILY_UNAVAILABLE_MESSAGE, code: STORAGE_UNAVAILABLE_CODE }); + } else { + res.end(); + } + return; + } + const reportableError = sanitizeSecretSensitiveError(req, rootError); attachErrorContext( req, diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 55be61b9e94..00d6b137e2a 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -406,6 +406,7 @@ import { import { addressedHumanOnlyDenialMessage, evaluateIssueThreadInteractionResolverAudience, + conversationInteractionResponderAllowed, issueThreadInteractionAttentionAgentAllowed, type IssueThreadInteractionResolverAudienceDecision, type IssueThreadInteractionResolverRestriction, @@ -6426,7 +6427,7 @@ export function issueRoutes( interactionId: string, relayedHumanUserId?: string | null, ) { - if (issue.conversationAgentId && req.actor.type === "board" && req.actor.userId !== issue.conversationUserId) { + if (req.actor.type === "board" && !conversationInteractionResponderAllowed(issue, req.actor.userId)) { throw forbidden("Only the conversation owner can respond to chat interactions"); } // Actor-only gates deliberately precede the interaction lookup. An actor diff --git a/server/src/routes/tool-access.ts b/server/src/routes/tool-access.ts index 4aed848a535..cc7058b729c 100644 --- a/server/src/routes/tool-access.ts +++ b/server/src/routes/tool-access.ts @@ -1063,9 +1063,14 @@ function connectorEnrollmentPrincipal(req: Request): string { // client they registered themselves. Report that instead of a 4xx so // the wizard can ask for it rather than losing the draft. const code = error instanceof HttpError ? String((error.details as { code?: unknown })?.code ?? "") : ""; - if (code !== "oauth_manual_client_required" && code !== "oauth_manual_client_rebinding_required") throw error; + if (code !== "oauth_manual_client_required" && code !== "oauth_manual_client_rebinding_required" + && code !== "oauth_instance_client_endpoint_mismatch") throw error; + const reason = (error as HttpError).details as { reason?: unknown } | undefined; result.auth.startUrl = null; result.auth.manualClientRequired = true; + result.auth.manualClientReason = typeof reason?.reason === "string" + ? reason.reason + : code === "oauth_instance_client_endpoint_mismatch" ? (error as HttpError).message : null; } } await logActivity(db, { diff --git a/server/src/routes/tool-gateway.ts b/server/src/routes/tool-gateway.ts index 75db9c435a8..f4853ed5254 100644 --- a/server/src/routes/tool-gateway.ts +++ b/server/src/routes/tool-gateway.ts @@ -17,6 +17,7 @@ import { assertBoard, assertBoardOrAgent, assertCompanyAccess, getActorInfo } fr import { ToolGatewayHttpError, type ToolGatewayService } from "../services/tool-gateway.js"; import { forbidden, HttpError } from "../errors.js"; import { accessService } from "../services/index.js"; +import { authorizationDeniedDetails } from "../services/authorization.js"; import { listConnectionLifecycleEvents } from "../services/tool-connection-activity.js"; const TOOL_ACTIVITY_EVENT_TYPES = [ @@ -575,6 +576,17 @@ export function toolGatewayRoutes(db: Db, toolGateway: ToolGatewayService) { return; } assertCompanyAccess(req, companyId); + if (req.actor.type === "board") { + const decision = await access.decide({ + actor: req.actor, + action: "agent:wake", + resource: { type: "agent", companyId, agentId }, + }); + if (!decision.allowed) throw forbidden(decision.explanation, authorizationDeniedDetails(decision)); + } + const createdByUserId = req.actor.type === "board" && req.actor.source !== "local_implicit" + ? req.actor.userId ?? null + : null; const session = await toolGateway.createSession({ companyId, @@ -585,6 +597,7 @@ export function toolGatewayRoutes(db: Db, toolGateway: ToolGatewayService) { ttlMs: body.ttlMs, actorType: actor.actorType, actorId: actor.actorId, + createdByUserId, }); res.status(201).json({ diff --git a/server/src/services/agent-environment-test.ts b/server/src/services/agent-environment-test.ts index 38cb939f11c..78d9a983c66 100644 --- a/server/src/services/agent-environment-test.ts +++ b/server/src/services/agent-environment-test.ts @@ -19,6 +19,7 @@ import { resolveEnvironmentExecutionTarget } from "./environment-execution-targe import { prepareManagedAiRuntime, assertManagedAiProjectAuth } from "./ai-connection-runtime.js"; import { isRunnerRevisionMismatch, runnerRevisionMismatchTestResult } from "./runner-revision-mismatch.js"; import { aiConnectionService } from "./ai-connections.js"; +import { isAiKeyVerificationFailureCode } from "./ai-api-key-failures.js"; import { validateAiApiKey } from "./ai-api-key-test.js"; import { probeCopilotExecutionTarget } from "./copilot-connection-probe.js"; import type { PluginWorkerManager } from "./plugin-worker-manager.js"; @@ -630,8 +631,8 @@ export function agentEnvironmentTestService(db: Db, pluginWorkerManager?: Plugin result.checks.push({ code: "ai_connection_api_key_reverified", level: "info", message: "The provider verified this API key for adoption." }); } catch (error) { result.status = "fail"; - const rejected = error instanceof HttpError && asRecord(error.details)?.code === "ai_connection_api_key_rejected"; - result.checks.push({ code: rejected ? "ai_connection_api_key_rejected" : "ai_connection_verification_failed", level: "error", message: error instanceof HttpError ? error.message : "Could not verify the account. Try again." }); + const code = error instanceof HttpError ? asRecord(error.details)?.code : undefined; + result.checks.push({ code: isAiKeyVerificationFailureCode(code) ? code : "ai_connection_verification_failed", level: "error", message: error instanceof HttpError ? error.message : "Could not verify the account. Try again." }); } return finishManagedConnectionTest(adapterType, context, result); } diff --git a/server/src/services/ai-api-key-failures.ts b/server/src/services/ai-api-key-failures.ts new file mode 100644 index 00000000000..fb76d358dd2 --- /dev/null +++ b/server/src/services/ai-api-key-failures.ts @@ -0,0 +1,17 @@ +export const AI_KEY_VERIFICATION_FAILURES = { + rejected: { code: "ai_connection_api_key_rejected", message: "The provider rejected this API key." }, + billing: { code: "ai_connection_billing_required", message: "The provider account for this API key has no credit or billing set up. Add credit with the provider, then try again." }, + rateLimited: { code: "ai_connection_rate_limited", message: "The provider is limiting requests for this account right now. Wait a minute, then try again." }, + unavailable: { code: "ai_connection_provider_unavailable", message: "The provider is having problems right now. Try again in a few minutes." }, + timeout: { code: "ai_connection_verification_timeout", message: "The provider did not answer in time. Try again." }, + unreachable: { code: "ai_connection_provider_unreachable", message: "Paperclip could not reach the provider. Check this server's network connection, then try again." }, + failed: { code: "ai_connection_verification_failed", message: "The provider could not verify this account. Try again." }, +} as const; + +export type AiKeyVerificationFailure = keyof typeof AI_KEY_VERIFICATION_FAILURES; + +const VERIFICATION_FAILURE_CODES: ReadonlySet = new Set(Object.values(AI_KEY_VERIFICATION_FAILURES).map(failure => failure.code)); + +export function isAiKeyVerificationFailureCode(code: unknown): code is (typeof AI_KEY_VERIFICATION_FAILURES)[AiKeyVerificationFailure]["code"] { + return typeof code === "string" && VERIFICATION_FAILURE_CODES.has(code); +} diff --git a/server/src/services/ai-api-key-test.test.ts b/server/src/services/ai-api-key-test.test.ts new file mode 100644 index 00000000000..db1f9776494 --- /dev/null +++ b/server/src/services/ai-api-key-test.test.ts @@ -0,0 +1,103 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const warn = vi.hoisted(() => vi.fn()); +vi.mock("../middleware/logger.js", () => ({ logger: { warn } })); + +const { validateAiApiKey } = await import("./ai-api-key-test.js"); + +const KEY = "sk-ant-api03-fixture-key-0123456789"; + +function respond(status: number, body: unknown = "") { + return vi.fn().mockResolvedValue(new Response(typeof body === "string" ? body : JSON.stringify(body), { status })); +} + +async function failure(request: typeof fetch, provider: Parameters[0] = "anthropic") { + const error = await validateAiApiKey(provider, KEY, request).then(() => null, (thrown: unknown) => thrown); + expect(error).not.toBeNull(); + const { status, message, details } = error as { status: number; message: string; details: { code: string } }; + return { status, message, code: details.code }; +} + +describe("validateAiApiKey", () => { + beforeEach(() => warn.mockReset()); + + it("accepts a key the provider verifies", async () => { + await expect(validateAiApiKey("anthropic", KEY, respond(200, { data: [] }))).resolves.toBeUndefined(); + expect(warn).not.toHaveBeenCalled(); + }); + + it.each([401, 403])("keeps rejecting the key on %s", async status => { + expect(await failure(respond(status, `{"error":{"type":"authentication_error","message":"invalid x-api-key ${KEY}"}}`))) + .toEqual({ status: 422, code: "ai_connection_api_key_rejected", message: "The provider rejected this API key." }); + }); + + it.each([ + ["a 400", 400, { error: { type: "invalid_request_error" } }, "ai_connection_verification_failed"], + ["a 402", 402, { error: { code: 402, message: "Insufficient credits" } }, "ai_connection_billing_required"], + ["an Anthropic billing error", 400, { type: "error", error: { type: "billing_error" } }, "ai_connection_billing_required"], + ["an OpenAI quota error on 429", 429, { error: { type: "insufficient_quota", code: "insufficient_quota" } }, "ai_connection_billing_required"], + ["a quota code behind another error type on 429", 429, { error: { type: "invalid_request_error", code: "insufficient_quota" } }, "ai_connection_billing_required"], + ["a 429", 429, { error: { type: "rate_limit_error" } }, "ai_connection_rate_limited"], + ["a 500", 500, { error: { type: "api_error" } }, "ai_connection_provider_unavailable"], + ["an Anthropic overload", 529, { error: { type: "overloaded_error" } }, "ai_connection_provider_unavailable"], + ])("gives %s its own code", async (_label, status, body, code) => { + const result = await failure(respond(status, body)); + expect(result.code).toBe(code); + expect(result.status).toBe(422); + }); + + it("gives each failure its own message", async () => { + const messages = new Set(); + for (const [status, body] of [[400, {}], [402, {}], [429, {}], [500, {}]] as const) { + messages.add((await failure(respond(status, body))).message); + } + expect(messages.size).toBe(4); + }); + + it("logs the status and the provider's error type without the key or the response text", async () => { + await failure(respond(429, { error: { type: "rate_limit_error", message: `slow down ${KEY}` } })); + + expect(warn).toHaveBeenCalledWith( + { provider: "anthropic", status: 429, providerErrorType: "rate_limit_error", failure: "ai_connection_rate_limited" }, + "AI provider did not verify an API key", + ); + expect(JSON.stringify(warn.mock.calls)).not.toContain(KEY); + expect(JSON.stringify(warn.mock.calls)).not.toContain("slow down"); + }); + + it("logs the billing field when the error type and code differ", async () => { + await failure(respond(429, { error: { type: "invalid_request_error", code: "insufficient_quota" } })); + + expect(warn.mock.calls[0]![0]).toMatchObject({ providerErrorType: "insufficient_quota", failure: "ai_connection_billing_required" }); + }); + + it("logs only known provider error types", async () => { + await failure(respond(500, { error: { type: KEY } })); + await failure(respond(500, { error: { type: `${KEY}_suffix` } })); + await failure(respond(500, { error: { type: "fixture" } }), "openai"); + await failure(respond(429, { error: { type: "custom_upstream_type", code: "rate_limit_exceeded" } }), "openai"); + await failure(respond(503, { error: { status: "UNAVAILABLE" } }), "google"); + await failure(respond(500, "upstream error")); + + expect(warn.mock.calls.map(([fields]) => fields.providerErrorType)) + .toEqual([null, null, null, "rate_limit_exceeded", "UNAVAILABLE", null]); + expect(JSON.stringify(warn.mock.calls)).not.toContain(KEY); + }); + + it("reads at most a bounded part of a large error body", async () => { + const body = `{"error":{"type":"api_error"},"padding":"${"x".repeat(64 * 1024)}"}`; + const result = await failure(respond(500, body)); + expect(result.code).toBe("ai_connection_provider_unavailable"); + expect(warn.mock.calls[0]![0].providerErrorType).toBeNull(); + }); + + it("separates a timeout from an unreachable provider", async () => { + const timedOut = await failure(vi.fn().mockRejectedValue(new DOMException("The operation timed out.", "TimeoutError"))); + expect(timedOut.code).toBe("ai_connection_verification_timeout"); + + const unreachable = await failure(vi.fn().mockRejectedValue(new TypeError("fetch failed", { cause: { code: "ENOTFOUND" } }))); + expect(unreachable.code).toBe("ai_connection_provider_unreachable"); + + expect(warn.mock.calls.map(([fields]) => fields.networkError)).toEqual(["timeout", "ENOTFOUND"]); + }); +}); diff --git a/server/src/services/ai-api-key-test.ts b/server/src/services/ai-api-key-test.ts index 4ed513f28e3..8c103f18725 100644 --- a/server/src/services/ai-api-key-test.ts +++ b/server/src/services/ai-api-key-test.ts @@ -1,5 +1,62 @@ import type { AiProvider } from "@paperclipai/shared"; import { unprocessable } from "../errors.js"; +import { logger } from "../middleware/logger.js"; +import { AI_KEY_VERIFICATION_FAILURES, type AiKeyVerificationFailure } from "./ai-api-key-failures.js"; + +const KNOWN_PROVIDER_ERROR_TYPES: ReadonlySet = new Set([ + "invalid_request_error", "authentication_error", "permission_error", "not_found_error", "request_too_large", + "rate_limit_error", "api_error", "overloaded_error", "billing_error", "timeout_error", + "insufficient_quota", "invalid_api_key", "rate_limit_exceeded", "server_error", "model_not_found", "insufficient_credits", + "INVALID_ARGUMENT", "FAILED_PRECONDITION", "PERMISSION_DENIED", "UNAUTHENTICATED", "NOT_FOUND", + "RESOURCE_EXHAUSTED", "INTERNAL", "UNAVAILABLE", "DEADLINE_EXCEEDED", +]); +const MAX_ERROR_BODY_BYTES = 8 * 1024; +const BILLING_ERROR_TYPES = new Set(["billing_error", "insufficient_quota", "insufficient_credits"]); + +async function readBoundedBody(response: Response): Promise { + const reader = response.body?.getReader(); + if (!reader) return ""; + const chunks: Uint8Array[] = []; + let bytes = 0; + try { + while (bytes < MAX_ERROR_BODY_BYTES) { + const { done, value } = await reader.read(); + if (done) break; + chunks.push(value); + bytes += value.length; + } + } finally { + await reader.cancel().catch(() => {}); + } + return Buffer.concat(chunks).subarray(0, MAX_ERROR_BODY_BYTES).toString("utf8"); +} + +async function providerErrorTypes(response: Response): Promise { + let parsed: unknown; + try { + parsed = JSON.parse(await readBoundedBody(response)); + } catch { + return []; + } + const error = parsed && typeof parsed === "object" ? (parsed as { error?: unknown }).error : undefined; + if (!error || typeof error !== "object") return []; + const { type, code, status } = error as { type?: unknown; code?: unknown; status?: unknown }; + return [type, code, status].filter((candidate): candidate is string => + typeof candidate === "string" && KNOWN_PROVIDER_ERROR_TYPES.has(candidate)); +} + +function classify(status: number, errorTypes: string[]): AiKeyVerificationFailure { + if (status === 401 || status === 403) return "rejected"; + if (status === 402 || errorTypes.some(type => BILLING_ERROR_TYPES.has(type))) return "billing"; + if (status === 429) return "rateLimited"; + if (status >= 500) return "unavailable"; + return "failed"; +} + +function fail(failure: AiKeyVerificationFailure): never { + const { code, message } = AI_KEY_VERIFICATION_FAILURES[failure]; + throw unprocessable(message, { code }); +} /** Fixed provider endpoints; credentials are never sent to a caller-supplied URL or through a redirect. */ export async function validateAiApiKey( @@ -25,15 +82,22 @@ export async function validateAiApiKey( ? { "x-api-key": key, "anthropic-version": "2023-06-01" } : { Authorization: `Bearer ${key}` }, }); - } catch { - throw unprocessable("Could not verify the account. Try again.", { code: "ai_connection_verification_failed" }); + } catch (error) { + const timedOut = error instanceof Error && error.name === "TimeoutError"; + const cause = error instanceof Error && error.cause && typeof error.cause === "object" ? error.cause as { code?: unknown } : undefined; + logger.warn({ provider, networkError: timedOut ? "timeout" : typeof cause?.code === "string" ? cause.code : "request_failed" }, + "AI provider API key verification request failed"); + fail(timedOut ? "timeout" : "unreachable"); } - await response.body?.cancel(); - if (!response.ok) - throw unprocessable( - response.status === 401 || response.status === 403 - ? "The provider rejected this API key." - : "The provider could not verify this account. Try again.", - { code: response.status === 401 || response.status === 403 ? "ai_connection_api_key_rejected" : "ai_connection_verification_failed" }, - ); + if (response.ok) { + await response.body?.cancel(); + return; + } + const errorTypes = response.status === 401 || response.status === 403 ? [] : await providerErrorTypes(response); + if (response.status === 401 || response.status === 403) await response.body?.cancel(); + const failure = classify(response.status, errorTypes); + const errorType = errorTypes.find(type => BILLING_ERROR_TYPES.has(type)) ?? errorTypes[0] ?? null; + logger.warn({ provider, status: response.status, providerErrorType: errorType, failure: AI_KEY_VERIFICATION_FAILURES[failure].code }, + "AI provider did not verify an API key"); + fail(failure); } diff --git a/server/src/services/connectors/paperclip-defined-tools.ts b/server/src/services/connectors/paperclip-defined-tools.ts new file mode 100644 index 00000000000..673c5d4c408 --- /dev/null +++ b/server/src/services/connectors/paperclip-defined-tools.ts @@ -0,0 +1,16 @@ +import { googleWorkspaceRestToolDefinition, type GoogleWorkspaceRestToolDefinition } from "../google-workspace-rest-dispatch.js"; + +export type PaperclipDefinedTool = GoogleWorkspaceRestToolDefinition; + +type Connection = { config: Record }; + +const PAPERCLIP_DEFINED_TOOL_SOURCES: ReadonlyArray<{ + matches: (connection: Connection) => boolean; + definition: (toolName: string) => PaperclipDefinedTool | null; +}> = [ + { matches: (connection) => connection.config.sourceTemplateKey === "google-workspace", definition: googleWorkspaceRestToolDefinition }, +]; + +export function paperclipDefinedTool(connection: Connection, toolName: string): PaperclipDefinedTool | null { + return PAPERCLIP_DEFINED_TOOL_SOURCES.find((source) => source.matches(connection))?.definition(toolName) ?? null; +} diff --git a/server/src/services/ephemeral-server-contract.ts b/server/src/services/ephemeral-server-contract.ts index 629bf01b026..7c0bc6107b7 100644 --- a/server/src/services/ephemeral-server-contract.ts +++ b/server/src/services/ephemeral-server-contract.ts @@ -120,39 +120,70 @@ export async function assertEphemeralServerData(db: Db) { throw new Error(`Volume-free server data is not eligible: ${blockers.map(detail).join(", ")}`); } +const failedCheckCode = (error: unknown) => { + const message = error instanceof Error ? error.message : ""; + if (/^[a-z_]{1,80}$/.test(message)) return `:${message}`; + if (error instanceof SyntaxError) return ":invalid_source_json"; + const errno = (error as { code?: unknown } | null)?.code; + return typeof errno === "string" && /^E[A-Z]{2,20}$/.test(errno) ? `:source_${errno.toLowerCase()}` : ""; +}; + export async function readEphemeralServerDataEligibility(db: Db, options: { purpose?: "migration" | "startup" } = {}) { const blockers: string[] = []; - const [missingFiles] = await db.select({ id: agents.id }).from(agents).leftJoin(agentFileRoots, - and(eq(agentFileRoots.companyId, agents.companyId), eq(agentFileRoots.agentId, agents.id))) - .where(isNull(agentFileRoots.agentId)).limit(1); - if (missingFiles) blockers.push("agent_files_require_migration"); - if (await hasUnsettledLocalInstructionCopies(db)) blockers.push("local_instruction_copies_require_settlement"); + const check = async (area: string, blocker: string, inspect: () => Promise) => { + try { + if (await inspect()) blockers.push(blocker); + } catch (error) { + logger.warn({ err: error, blocker }, "Volume-free data eligibility check failed"); + blockers.push(`${area}_check_failed${failedCheckCode(error)}`); + } + }; + await check("agent_files", "agent_files_require_migration", async () => { + const [missingFiles] = await db.select({ id: agents.id }).from(agents).leftJoin(agentFileRoots, + and(eq(agentFileRoots.companyId, agents.companyId), eq(agentFileRoots.agentId, agents.id))) + .where(isNull(agentFileRoots.agentId)).limit(1); + return Boolean(missingFiles); + }); + await check("local_instruction_copies", "local_instruction_copies_require_settlement", () => hasUnsettledLocalInstructionCopies(db)); // Only inspect configuration here; filesystem reads must never adopt an // empty directory on the replacement machine as the old server's content. - const configured = await db.select({ id: agents.id, companyId: agents.companyId, name: agents.name, adapterConfig: agents.adapterConfig }).from(agents); - if (configured.some(agent => agentInstructionsBundleMode(agent) === "external")) blockers.push("external_agent_instructions"); - const [localWorkspace] = await db.select({ id: executionWorkspaces.id }).from(executionWorkspaces) - .where(localWorkspaceDependencyWhere(db)).limit(1); - if (localWorkspace) blockers.push("workspaces_require_migration"); - const [localLog] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and( - eq(heartbeatRuns.logStore, "local_file"), isNotNull(heartbeatRuns.logRef), - )).limit(1); - if (localLog) blockers.push("run_logs_require_migration"); - const [localTrace] = await db.select({ id: providerTraceRecords.id }).from(providerTraceRecords).where(and( - isNull(providerTraceRecords.deletedAt), sql`${providerTraceRecords.traceRef} not like 's3-segments-v1:%'`, - )).limit(1); - if (localTrace) blockers.push("provider_traces_require_migration"); - if (await hasLocalNativeHarnessObligations(db)) blockers.push("native_harness_backups_require_migration"); - const controller = await findLocalNativeControllerObligation(db); - if (controller) blockers.push("native_controllers_require_migration"); - if (await hasLocalRuntimeSkillObligations(db)) blockers.push(RUNTIME_SKILL_ASSETS_BLOCKER); - const skills = skillInstallationMaintenance(db); - let after: string | undefined; - for (;;) { - const page = await skills.eligibility({ after, limit: 50, purpose: options.purpose }); - if (page.results.some(skill => skill.status !== "version_backed")) { blockers.push("skills_require_migration"); break; } - if (page.inspected < 50 || !page.after) break; - after = page.after; - } - return { eligible: blockers.length === 0, blockers, controller }; + await check("agent_instructions", "external_agent_instructions", async () => { + const configured = await db.select({ id: agents.id, companyId: agents.companyId, name: agents.name, adapterConfig: agents.adapterConfig }).from(agents); + return configured.some(agent => agentInstructionsBundleMode(agent) === "external"); + }); + await check("workspaces", "workspaces_require_migration", async () => { + const [localWorkspace] = await db.select({ id: executionWorkspaces.id }).from(executionWorkspaces) + .where(localWorkspaceDependencyWhere(db)).limit(1); + return Boolean(localWorkspace); + }); + await check("run_logs", "run_logs_require_migration", async () => { + const [localLog] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.logStore, "local_file"), isNotNull(heartbeatRuns.logRef), + )).limit(1); + return Boolean(localLog); + }); + await check("provider_traces", "provider_traces_require_migration", async () => { + const [localTrace] = await db.select({ id: providerTraceRecords.id }).from(providerTraceRecords).where(and( + isNull(providerTraceRecords.deletedAt), sql`${providerTraceRecords.traceRef} not like 's3-segments-v1:%'`, + )).limit(1); + return Boolean(localTrace); + }); + await check("native_harness_backups", "native_harness_backups_require_migration", () => hasLocalNativeHarnessObligations(db)); + const found: { controller: Awaited> } = { controller: null }; + await check("native_controllers", "native_controllers_require_migration", async () => { + found.controller = await findLocalNativeControllerObligation(db); + return Boolean(found.controller); + }); + await check("runtime_skill_assets", RUNTIME_SKILL_ASSETS_BLOCKER, () => hasLocalRuntimeSkillObligations(db)); + await check("skills", "skills_require_migration", async () => { + const skills = skillInstallationMaintenance(db); + let after: string | undefined; + for (;;) { + const page = await skills.eligibility({ after, limit: 50, purpose: options.purpose }); + if (page.results.some(skill => skill.status !== "version_backed")) return true; + if (page.inspected < 50 || !page.after) return false; + after = page.after; + } + }); + return { eligible: blockers.length === 0, blockers, controller: found.controller }; } diff --git a/server/src/services/google-workspace-rest-dispatch.test.ts b/server/src/services/google-workspace-rest-dispatch.test.ts index 1052ab144d0..05af29aa319 100644 --- a/server/src/services/google-workspace-rest-dispatch.test.ts +++ b/server/src/services/google-workspace-rest-dispatch.test.ts @@ -2,8 +2,10 @@ import { GOOGLE_WORKSPACE_TOOL_TRANSPORT, googleWorkspaceServiceToolNames } from import { describe, expect, it, vi } from "vitest"; import { callGoogleWorkspaceRest, + googleWorkspaceRestToolDefinition, googleWorkspaceCatalogToolTitle, googleWorkspaceRestTransportGaps, + listGoogleWorkspaceRest, probeGoogleWorkspaceRest, } from "./google-workspace-rest-dispatch.js"; @@ -23,6 +25,25 @@ describe("Google Workspace REST transport eligibility", () => { }); }); +describe("googleWorkspaceRestToolDefinition", () => { + it("returns this folder's definition for a tool of a service on paperclip_rest, and nothing otherwise", () => { + const rest = listGoogleWorkspaceRest("docs").find((tool) => tool.name === "update_doc")!; + expect(googleWorkspaceRestToolDefinition("docs__update_doc")).toEqual({ name: rest.name, title: "Docs: Edit a document", description: rest.description, + inputSchema: rest.inputSchema, outputSchema: rest.outputSchema, annotations: rest.annotations }); + expect(googleWorkspaceRestToolDefinition("docs__update_doc")?.inputSchema.required).toContain("writeControl"); + expect(googleWorkspaceRestToolDefinition("chat__list_messages")).toBeNull(); + expect(googleWorkspaceRestToolDefinition("gmail__send_message")).toBeNull(); + expect(googleWorkspaceRestToolDefinition("update_doc")).toBeNull(); + const saved = GOOGLE_WORKSPACE_TOOL_TRANSPORT.docs; + GOOGLE_WORKSPACE_TOOL_TRANSPORT.docs = "google_mcp"; + try { + expect(googleWorkspaceRestToolDefinition("docs__update_doc")).toBeNull(); + } finally { + GOOGLE_WORKSPACE_TOOL_TRANSPORT.docs = saved; + } + }); +}); + describe("googleWorkspaceCatalogToolTitle", () => { const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i; diff --git a/server/src/services/google-workspace-rest-dispatch.ts b/server/src/services/google-workspace-rest-dispatch.ts index 535224f969c..1876809efe5 100644 --- a/server/src/services/google-workspace-rest-dispatch.ts +++ b/server/src/services/google-workspace-rest-dispatch.ts @@ -43,6 +43,29 @@ export function listGoogleWorkspaceRest(service: GoogleWorkspaceService): Tool[] return listGoogleWorkspaceRestTools(restService(service)); } +export interface GoogleWorkspaceRestToolDefinition { + name: string; + title: string | null; + description: string | null; + inputSchema: Record; + outputSchema: Record | null; + annotations: Record; +} + +export function googleWorkspaceRestToolDefinition(toolName: string): GoogleWorkspaceRestToolDefinition | null { + const target = googleWorkspaceToolTarget(toolName); + if (!target || target.transport !== "paperclip_rest" || !isGoogleWorkspaceRestService(target.service)) return null; + const tool = listGoogleWorkspaceRestTools(target.service).find((candidate) => candidate.name === target.leaf); + return tool ? { + name: tool.name, + title: googleWorkspaceCatalogToolTitle("google-workspace", toolName, tool.title), + description: tool.description ?? null, + inputSchema: { ...tool.inputSchema }, + outputSchema: tool.outputSchema ? { ...tool.outputSchema } : null, + annotations: { ...tool.annotations }, + } : null; +} + export function googleWorkspaceCatalogToolTitle( sourceTemplateKey: unknown, name: string, diff --git a/server/src/services/issue-thread-interaction-resolution.ts b/server/src/services/issue-thread-interaction-resolution.ts index a972fe4ae3e..1d0762d53ad 100644 --- a/server/src/services/issue-thread-interaction-resolution.ts +++ b/server/src/services/issue-thread-interaction-resolution.ts @@ -4,6 +4,7 @@ import type { } from "@paperclipai/shared"; import { normalizeIssueThreadInteractionResolverPolicy } from "@paperclipai/shared"; import { HttpError } from "../errors.js"; +import { dashboardConversationReadable, type DashboardConversationFields } from "./responsibility-privacy.js"; export const ISSUE_THREAD_INTERACTION_RESOLUTION_DENIAL_CODES = [ "interaction_not_found", @@ -18,6 +19,7 @@ export const ISSUE_THREAD_INTERACTION_RESOLUTION_DENIAL_CODES = [ "interaction_issue_closed", "interaction_governed_action_denied", "review_policy_denied", + "interaction_conversation_owner_required", ] as const; export type IssueThreadInteractionResolutionDenialCode = @@ -427,3 +429,52 @@ export function issueThreadInteractionAttentionAgentAllowed(input: { governedAction: input.governedAction, }).allowed; } + +export function conversationInteractionResponderAllowed( + issue: { conversationAgentId?: string | null; conversationUserId?: string | null }, + userId: string | null | undefined, +) { + return !issue.conversationAgentId || (Boolean(userId) && userId === issue.conversationUserId); +} + +export type HumanToolReviewResolutionDecision = + | { allowed: true } + | { + allowed: false; + status: 403 | 404 | 422; + code: IssueThreadInteractionResolutionDenialCode; + message: string; + details?: Record; + }; + +export function evaluateHumanToolReviewResolution(input: { + userId: string; + issue: DashboardConversationFields & { conversationAgentId?: string | null; conversationUserId?: string | null }; + interaction: IssueThreadInteractionResolverAudienceInput["interaction"]; +}): HumanToolReviewResolutionDecision { + if (!dashboardConversationReadable({ type: "board", userId: input.userId }, input.issue)) { + return { allowed: false, status: 404, code: "interaction_not_found", message: "Issue not found" }; + } + if (!conversationInteractionResponderAllowed(input.issue, input.userId)) { + return { + allowed: false, + status: 403, + code: "interaction_conversation_owner_required", + message: "Only the conversation owner can respond to chat interactions", + }; + } + const decision = evaluateIssueThreadInteractionResolverAudience({ + actor: { type: "user", userId: input.userId }, + interaction: input.interaction, + governedAction: true, + }); + if (decision.allowed) return { allowed: true }; + return { allowed: false, status: decision.status, code: decision.code, message: decision.message, details: decision.details }; +} + +export function assertHumanToolReviewResolution(input: Parameters[0]) { + const decision = evaluateHumanToolReviewResolution(input); + if (!decision.allowed) { + throw issueThreadInteractionResolutionError(decision.status, decision.code, decision.message, decision.details); + } +} diff --git a/server/src/services/local-ai-login.ts b/server/src/services/local-ai-login.ts index 78129d6edb4..505c1bc2256 100644 --- a/server/src/services/local-ai-login.ts +++ b/server/src/services/local-ai-login.ts @@ -288,6 +288,10 @@ export function localAiLoginService(db: Db) { )); if (!session?.aiConnection || !sameTarget(session.aiConnection, intent)) throw notFound("Local sign-in attempt not found for this connection."); + if (session.status === "authenticated" || session.connectionId) + return { status: "expired", error: "This sign-in already connected the account." }; + if (session.status === "cancelled" || session.failureReason === RETIREMENT_PENDING) + return { status: "expired", error: "This sign-in attempt was cancelled or replaced by a newer one. Start sign-in again." }; if (session.status !== "waiting_for_user" || !session.expiresAt || session.expiresAt.getTime() <= Date.now()) return { status: "expired" }; directory = loginHome(id); diff --git a/server/src/services/mcp-task-work.ts b/server/src/services/mcp-task-work.ts index 54ea554f0b9..8804f37c045 100644 --- a/server/src/services/mcp-task-work.ts +++ b/server/src/services/mcp-task-work.ts @@ -42,7 +42,7 @@ export function registerMcpTaskWork( mutation: "tool_task", wakeReason: "issue_commented", source: "mcp_task.settled", - toolTask: { tool: task.toolName, status: task.status }, + toolTask: { tool: task.toolName, status: task.status, taskRecordId: task.taskRecordId }, }, issueStateGuard: { statuses: ["todo", "in_progress", "in_review", "blocked"], assigneeAgentId: task.agentId }, }); diff --git a/server/src/services/native-runtime/native-controller-migration.integration.test.ts b/server/src/services/native-runtime/native-controller-migration.integration.test.ts index bebd6db2bf9..84984a33168 100644 --- a/server/src/services/native-runtime/native-controller-migration.integration.test.ts +++ b/server/src/services/native-runtime/native-controller-migration.integration.test.ts @@ -1,5 +1,5 @@ import { createHash, randomUUID } from "node:crypto"; -import { mkdir, open, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { chmod, link, mkdir, open, readFile, rm, stat, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; import { and, eq } from "drizzle-orm"; import { afterEach, expect, it, vi } from "vitest"; @@ -25,9 +25,10 @@ import { createStorageService } from "../../storage/service.js"; import { legacyNativeControllerArchive } from "./native-controller-archive.js"; import { restoreDurableNativeHarnessBackup } from "./native-harness-backup-storage.js"; import { claimVolumeFreeControllerState } from "./volume-free-controller-state.js"; -import { assertEphemeralServerData } from "../ephemeral-server-contract.js"; +import { assertEphemeralServerData, readEphemeralServerDataEligibility } from "../ephemeral-server-contract.js"; +import { readOnlineEphemeralEnrollmentEligibility } from "../ephemeral-enrollment.js"; -describeEmbeddedPostgres.each(["volume_free_owner", "archive_online", "archive_online_owned", "archive_online_changed", "archive_online_commit", "archive_online_active", "archive_online_foreign", +describeEmbeddedPostgres.each(["volume_free_owner", "eligibility_unreadable", "archive_online", "archive_online_owned", "archive_online_changed", "archive_online_commit", "archive_online_active", "archive_online_foreign", "active_warm", "source_scan", "active_durable", "active_durable_cold", "online_success", "online_owned", "online_same_source", "online_busy", "online_changed", "online_evidence", "import", "archive", "success", "batch", "durable_failed", "durable_inline_failed", "stale_confirmed", "stale_foreign", "stale_changed", "stale_queued", "stale_overlap", "stale_success", "stale_busy", "stale_durable", "stale_durable_absent", "stale_durable_runner", "stale_durable_session", "stale_durable_snapshot", @@ -96,6 +97,25 @@ describeEmbeddedPostgres.each(["volume_free_owner", "archive_online", "archive_o taskKey: f.issueId, lastRunId: f.runId }).returning(); return { ...f, companyId, agentId, paperclipHome, runtimeRoot, paths, file, source, profile, session, queuedId, identity, snapshot }; } + if (scenario === "eligibility_unreadable") it("names a controller check that cannot read its source instead of failing the eligibility read", async () => { + const f = await fixture(); + await link(f.file, `${f.file}.alias`); + const failed = "native_controllers_check_failed:native_controller_migration_unsafe_source"; + expect((await readEphemeralServerDataEligibility(f.db, { purpose: "startup" })).blockers).toContain(failed); + const online = await readOnlineEphemeralEnrollmentEligibility(f.db); + expect(online.eligible).toBe(false); + expect(online.blockers).toContain(failed); + expect(online.blockers).not.toContain("native_controllers_require_migration"); + expect(await readFile(f.file, "utf8")).toBe(f.source); + await rm(`${f.file}.alias`); + if (process.getuid?.() !== 0) { + await chmod(f.file, 0o000); + try { + expect((await readEphemeralServerDataEligibility(f.db, { purpose: "startup" })).blockers) + .toContain("native_controllers_check_failed:source_eacces"); + } finally { await chmod(f.file, 0o600); } + } + }); if (scenario === "volume_free_owner") it("starts a volume-free server over controller state it wrote itself and keeps unmarked state blocked", async () => { vi.stubEnv("PAPERCLIP_EPHEMERAL_SERVER", "true"); expect(await claimVolumeFreeControllerState(true)).toBe("claimed"); diff --git a/server/src/services/native-runtime/native-harness-backup-migration.ts b/server/src/services/native-runtime/native-harness-backup-migration.ts index 1afac2805a8..685245aafd9 100644 --- a/server/src/services/native-runtime/native-harness-backup-migration.ts +++ b/server/src/services/native-runtime/native-harness-backup-migration.ts @@ -15,8 +15,15 @@ import { hasValidNativeHarnessFilesystemIndependence } from "./native-harness-fi const MAX_PARALLEL_INDEPENDENCE_CHECKS = 4; export async function hasLocalNativeHarnessObligations(db: Db): Promise { + for await (const _ of localNativeHarnessObligationScopes(db)) return true; + return false; +} + +async function* localNativeHarnessObligationScopes(db: Db, all = false, signal?: AbortSignal, + skip: ReadonlySet = new Set()): AsyncGenerator { let afterSession = "", afterScope = ""; for (;;) { + signal?.throwIfAborted(); const rows = await db.execute<{ company_id: string; selected_session_id: string; scope_digest: string; has_receipt: boolean }>(sql`with selected_sessions as materialized ( select s.company_id, s.id, s.last_run_id, r.native_issue_id, r.native_session_id from agent_task_sessions s @@ -33,20 +40,24 @@ export async function hasLocalNativeHarnessObligations(db: Db): Promise and b.scope_digest = e.metadata->'nativeHarnessBackup'->>'sessionScopeSha256' and b.status = 'current') and (s.id::text, coalesce(e.metadata->'nativeHarnessBackup'->>'sessionScopeSha256', '')) > (${afterSession}, ${afterScope}) order by selected_session_id, scope_digest limit 100`); - let next = 0, invalid = false; + let next = 0, failed = false; + const invalid: string[] = []; const checked = await Promise.allSettled(Array.from({ length: Math.min(MAX_PARALLEL_INDEPENDENCE_CHECKS, rows.length) }, async () => { - while (!invalid && next < rows.length) { + while (!failed && (all || !invalid.length) && next < rows.length) { + signal?.throwIfAborted(); const row = rows[next++]!; + if (skip.has(row.scope_digest)) continue; try { if (!row.has_receipt || !await hasValidNativeHarnessFilesystemIndependence(db, { companyId: row.company_id, selectedSessionId: row.selected_session_id, scopeDigest: row.scope_digest, - })) invalid = true; - } catch (error) { invalid = true; throw error; } + })) invalid.push(row.scope_digest); + } catch (error) { failed = true; throw error; } } })); for (const result of checked) if (result.status === "rejected") throw result.reason; - if (invalid) return true; - if (rows.length < 100) return false; + signal?.throwIfAborted(); + yield* invalid; + if (rows.length < 100) return; afterSession = rows.at(-1)!.selected_session_id; afterScope = rows.at(-1)!.scope_digest; } } @@ -183,11 +194,13 @@ export async function migrateNativeHarnessBackups(db: Db, input: { } export async function prestageNativeHarnessBackups(db: Db, input: { storage: StorageService; signal: AbortSignal; onOutcome?: (outcome: string) => void }) { + const visited = new Set(); const deferSource = (scopeDigest: string, reason: string, outcome: string) => { console.warn(JSON.stringify({ schema: "paperclip.native-harness-prestage-source.v1", scopeDigest, reason })); return outcome; }; const outcomes = await mapSources({ ...input, concurrency: 1, onResult: (outcome: string) => input.onOutcome?.(outcome), unavailableSource: (error, scopeDigest) => { + visited.add(scopeDigest); if (error instanceof NativeHarnessBackupSourceError || error instanceof Error && error.message === "native_harness_migration_source_unsettled") { return deferSource(scopeDigest, error.message, "source_unavailable"); } @@ -197,6 +210,7 @@ export async function prestageNativeHarnessBackups(db: Db, input: { storage: Sto return undefined; } }, async (source, signal) => { signal.throwIfAborted(); + visited.add(source.scopeDigest); const run = await sourceRun(db, source).catch(error => { if (error instanceof Error && error.message === "native_harness_migration_binding_mismatch") return null; throw error; @@ -264,7 +278,16 @@ export async function prestageNativeHarnessBackups(db: Db, input: { storage: Sto throw error; } }); + let absent = 0; + for await (const scopeDigest of localNativeHarnessObligationScopes(db, true, input.signal, visited)) { + input.signal.throwIfAborted(); + if (visited.has(scopeDigest)) continue; + visited.add(scopeDigest); + absent++; + input.onOutcome?.("selected_source_absent"); + } const counts = { inspected: outcomes.length, published: 0, current: 0, deferred: {} as Record }; + if (absent) counts.deferred.selected_source_absent = absent; for (const outcome of outcomes) { if (outcome === "published" || outcome === "current") counts[outcome]++; else counts.deferred[outcome] = (counts.deferred[outcome] ?? 0) + 1; diff --git a/server/src/services/native-runtime/native-harness-backup-storage.integration.test.ts b/server/src/services/native-runtime/native-harness-backup-storage.integration.test.ts index 65b648d3b84..468250efab4 100644 --- a/server/src/services/native-runtime/native-harness-backup-storage.integration.test.ts +++ b/server/src/services/native-runtime/native-harness-backup-storage.integration.test.ts @@ -3,7 +3,7 @@ import { createHash, randomUUID } from "node:crypto"; import { chmod, mkdir, readFile, rename, stat, symlink, readlink, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { and, eq, inArray } from "drizzle-orm"; -import { agentTaskSessions, environmentLeases, heartbeatRuns, issues, nativeHarnessBackups, nativeRunFinalizations, nativeRunResults, +import { activityLog, agentTaskSessions, environmentLeases, heartbeatRuns, issues, nativeHarnessBackups, nativeRunFinalizations, nativeRunResults, nativeProviderArtifacts, nativeProviderArtifactReferences, nativeRunnerCheckpoints } from "@paperclipai/db"; import { afterEach, expect, it, vi } from "vitest"; import { describeEmbeddedPostgres, nativeRestartFixture } from "../../__tests__/helpers/native-restart.js"; @@ -609,11 +609,14 @@ describeEmbeddedPostgres("durable native provider backups", () => { expect(put).not.toHaveBeenCalled(); expect(await f.db.select().from(nativeHarnessBackups).where(eq(nativeHarnessBackups.scopeDigest, f.scopeDigest))).toEqual([]); }); - it("defers failed history without treating pre-copy as offline authority", async () => { + it("preserves settled failed history of an unselected session through the settled-source owner, never offline authority", async () => { const [f] = await offlineFixtures(1); expect(await prestageNativeHarnessBackups(f.db, { storage: f.storage, signal: AbortSignal.timeout(15_000) })) - .toEqual({ inspected: 1, published: 0, current: 0, deferred: { source_session_not_selected: 1 } }); - expect(await f.db.select().from(nativeHarnessBackups).where(eq(nativeHarnessBackups.scopeDigest, f.scopeDigest))).toEqual([]); + .toEqual({ inspected: 1, published: 1, current: 0, deferred: {} }); + expect((await f.db.select().from(nativeHarnessBackups).where(eq(nativeHarnessBackups.scopeDigest, f.scopeDigest)))[0].status).toBe("current"); + const [preserved] = await f.db.select().from(activityLog).where(and(eq(activityLog.companyId, f.companyId), + eq(activityLog.action, "native_harness_backup_preserved"), eq(activityLog.runId, f.runId))); + expect(preserved).toMatchObject({ actorId: "native-harness-preservation", details: { scopeDigest: f.scopeDigest, originalFilesRetained: true } }); }); it("defers a source being replaced online while offline migration still refuses it", async () => { const f = await inactiveFixture(); diff --git a/server/src/services/native-runtime/native-harness-online-preservation.integration.test.ts b/server/src/services/native-runtime/native-harness-online-preservation.integration.test.ts index 2a22ca49cbf..af570f736ee 100644 --- a/server/src/services/native-runtime/native-harness-online-preservation.integration.test.ts +++ b/server/src/services/native-runtime/native-harness-online-preservation.integration.test.ts @@ -1,5 +1,5 @@ import { createHash, randomUUID } from "node:crypto"; -import { cp, mkdir, readFile, symlink, writeFile } from "node:fs/promises"; +import { cp, mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { eq } from "drizzle-orm"; import { agentTaskSessions, createDb, environmentLeases, heartbeatRuns, issues, nativeHarnessBackups, nativeRunFinalizations, nativeRunResults } from "@paperclipai/db"; @@ -15,6 +15,7 @@ import { persistNativeHarnessBackup, restoreDurableNativeHarnessBackup } from ". import { settledNativeHarnessBackupOwner } from "./native-harness-preservation-source.js"; import { tryLockNativeWorkspaceFinalization } from "./native-workspace-finalization-ownership.js"; import * as backupStamp from "./native-harness-backup-stamp.js"; +import * as independence from "./native-harness-filesystem-independence.js"; import { nativeHarnessPrestageDatabaseUrl } from "../../maintenance/native-harness-prestage-runtime.js"; describeEmbeddedPostgres("online preservation of settled legacy harness backups", () => { @@ -104,17 +105,81 @@ describeEmbeddedPostgres("online preservation of settled legacy harness backups" ["scheduled_retry", "source_run_active"], ["failed_unfinished", "source_run_unfinished"], ["coordinator_missing", "source_coordinator_missing"], - ["session_not_selected", "source_session_not_selected"], ])("names why a %s source stays local", async (kind, outcome) => { const f = await fixture(), put = vi.spyOn(f.storage, "putFile"); if (kind === "running" || kind === "scheduled_retry") await f.db.update(heartbeatRuns).set({ status: kind, finishedAt: null }).where(eq(heartbeatRuns.id, f.runId)); if (kind === "failed_unfinished") await f.db.update(heartbeatRuns).set({ finishedAt: null }).where(eq(heartbeatRuns.id, f.runId)); if (kind === "coordinator_missing") await f.db.delete(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)); - if (kind === "session_not_selected") await f.db.delete(agentTaskSessions).where(eq(agentTaskSessions.lastRunId, f.runId)); expect(await prestageNativeHarnessBackups(f.db, { storage: f.storage, signal: AbortSignal.timeout(15_000) })) .toMatchObject({ published: 0, deferred: { [outcome]: 1 } }); expect(put).not.toHaveBeenCalled(); }); + it.each(["unselected", "ambiguous"])("preserves a settled source whose session is %s, as the offline migration does", async selection => { + const f = await fixture(); + if (selection === "unselected") await f.db.delete(agentTaskSessions).where(eq(agentTaskSessions.lastRunId, f.runId)); + else await f.db.insert(agentTaskSessions).values({ companyId: f.companyId, agentId: environment.current.agentId, + adapterType: "paperclip_runner", taskKey: `${f.issueId}:second`, lastRunId: f.runId }); + const sessions = await f.db.select().from(agentTaskSessions).where(eq(agentTaskSessions.lastRunId, f.runId)); + const [before] = await f.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + const result = await prestageNativeHarnessBackups(f.db, { storage: f.storage, signal: AbortSignal.timeout(15_000) }); + expect(result.published).toBe(1); + vi.stubEnv("PAPERCLIP_RUNNER_STATE_DIR", join(environment.current.runtimeRoot, randomUUID())); + const leftover = await prestageNativeHarnessBackups(f.db, { storage: f.storage, signal: AbortSignal.timeout(15_000) }); + vi.stubEnv("PAPERCLIP_RUNNER_STATE_DIR", f.base); + expect(leftover).toMatchObject({ inspected: 0, published: 0 }); + expect(result.deferred).toEqual(leftover.deferred); + expect((await f.db.select().from(nativeHarnessBackups).where(eq(nativeHarnessBackups.scopeDigest, f.scopeDigest)))[0].status).toBe("current"); + expect((await f.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)))[0]).toEqual(before); + expect(await f.db.select().from(agentTaskSessions).where(eq(agentTaskSessions.lastRunId, f.runId))).toEqual(sessions); + expect(await readFile(join(f.root, "codex-home", "sessions", "history.json"), "utf8")).toBe(JSON.stringify(f.saved)); + const restored = join(environment.current.runtimeRoot, randomUUID()); homes.push(restored); + expect(await restoreDurableNativeHarnessBackup({ ...f, backupRoot: restored })).toBe(true); + expect(JSON.parse(await readFile(join(restored, "current", "codex-home", "sessions", "history.json"), "utf8"))).toEqual(f.saved); + }); + it("keeps the source local when its session selection changes before publication", async () => { + const f = await fixture(), put = f.storage.putFile.bind(f.storage); + await f.db.delete(agentTaskSessions).where(eq(agentTaskSessions.lastRunId, f.runId)); + vi.spyOn(f.storage, "putFile").mockImplementation(async input => { + const result = await put(input); + await f.db.insert(agentTaskSessions).values({ companyId: f.companyId, agentId: environment.current.agentId, + adapterType: "paperclip_runner", taskKey: f.issueId, lastRunId: f.runId }); + return result; + }); + expect(await prestageNativeHarnessBackups(f.db, { storage: f.storage, signal: AbortSignal.timeout(15_000) })) + .toMatchObject({ published: 0, deferred: { source_changed: 1 } }); + expect(await f.db.select({ status: nativeHarnessBackups.status }).from(nativeHarnessBackups).where(eq(nativeHarnessBackups.scopeDigest, f.scopeDigest))) + .toEqual([{ status: "pending" }]); + }); + it("names a selected session whose backup source is not on this disk", async () => { + const f = await fixture(), signal = AbortSignal.timeout(15_000); + await f.db.update(heartbeatRuns).set({ status: "running", finishedAt: null }).where(eq(heartbeatRuns.id, f.runId)); + const present = await prestageNativeHarnessBackups(f.db, { storage: f.storage, signal }); + expect(present.deferred.source_run_active).toBe(1); + await rm(join(f.base, f.scopeDigest), { recursive: true }); + const absent = await prestageNativeHarnessBackups(f.db, { storage: f.storage, signal }); + expect(absent.deferred.source_run_active).toBeUndefined(); + expect(absent.deferred.selected_source_absent).toBe((present.deferred.selected_source_absent ?? 0) + 1); + expect(absent).toMatchObject({ inspected: 0, published: 0 }); + }); + it("stops the selected-source scan once the pass is cancelled", async () => { + const f = await fixture(), controller = new AbortController(); + await rm(join(f.base, f.scopeDigest), { recursive: true }); + const [run] = await f.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + await f.db.update(heartbeatRuns).set({ runnerProfileJson: { ...run.runnerProfileJson, nativeHarnessFilesystemIndependence: {} } }) + .where(eq(heartbeatRuns.id, f.runId)); + const check = vi.spyOn(independence, "hasValidNativeHarnessFilesystemIndependence"); + const execute = f.db.execute.bind(f.db); + const scan = vi.spyOn(f.db, "execute").mockImplementation(((query: Parameters[0]) => { + controller.abort(new Error("budget spent")); + return execute(query); + }) as typeof f.db.execute); + const outcomes: string[] = []; + await expect(prestageNativeHarnessBackups(f.db, { storage: f.storage, signal: controller.signal, + onOutcome: outcome => outcomes.push(outcome) })).rejects.toThrow("budget spent"); + expect(scan).toHaveBeenCalledTimes(1); + expect(check).not.toHaveBeenCalled(); + expect(outcomes).toEqual([]); + }); it("respects the physical advisory lock while unrelated work stays active", async () => { const f = await fixture(), put = vi.spyOn(f.storage, "putFile"); let release!: () => void, entered!: () => void; @@ -185,7 +250,7 @@ describeEmbeddedPostgres("online preservation of settled legacy harness backups" const good = await fixture({ base: bad.base, scopeId: "a" }); expect(bad.scopeDigest < good.scopeDigest).toBe(true); expect(await prestageNativeHarnessBackups(bad.db, { storage: bad.storage, signal: AbortSignal.timeout(15_000) })) - .toMatchObject({ inspected: 2, published: 1, deferred: { source_changed: 1 } }); + .toMatchObject({ published: 1, deferred: { source_changed: 1 } }); expect(await bad.db.select().from(nativeHarnessBackups).where(eq(nativeHarnessBackups.scopeDigest, bad.scopeDigest))).toEqual([]); expect((await good.db.select().from(nativeHarnessBackups).where(eq(nativeHarnessBackups.scopeDigest, good.scopeDigest)))[0].status).toBe("current"); }); diff --git a/server/src/services/native-runtime/native-harness-preservation-source.ts b/server/src/services/native-runtime/native-harness-preservation-source.ts index 8564ba6e101..2495d547d4c 100644 --- a/server/src/services/native-runtime/native-harness-preservation-source.ts +++ b/server/src/services/native-runtime/native-harness-preservation-source.ts @@ -1,6 +1,6 @@ import { createHash } from "node:crypto"; import { resolve } from "node:path"; -import { and, eq, inArray, or, sql } from "drizzle-orm"; +import { and, asc, eq, inArray, or, sql } from "drizzle-orm"; import { agentTaskSessions, environmentLeases, heartbeatRuns, issues, nativeRunFinalizations, type Db } from "@paperclipai/db"; import { adapterExecutionControls } from "../adapter-execution-control.js"; import { nativeSha256 } from "./canonical.js"; @@ -16,7 +16,7 @@ export type SettledNativeHarnessBackupOwner = { kind: "settled_native_harness_backup"; companyId: string; issueId: string; agentId: string; runId: string; sessionId: string; runnerInstanceId: string; scopeDigest: string; root: string; manifestSha256: string; - selectedSessionId: string; selectedLastRunId: string; sourceLeaseId: string; providerLeaseId: string; + selections: Array<{ id: string; lastRunId: string | null }>; sourceLeaseId: string; providerLeaseId: string; runDigest: string; coordinatorDigest: string; leaseDigest: string; }; const runDigest = (run: Run) => nativeSha256({ status: run.status, finishedAt: run.finishedAt?.toISOString(), @@ -31,6 +31,14 @@ const leaseDigest = (row: Lease) => nativeSha256({ heartbeatRunId: row.heartbeat const settled = (row: Coordinator) => row.leaseOwner === null && row.nextAttemptAt === null && (row.phase === "terminal_failure" || row.phase === "committed" && row.resultId !== null); const fail = (): never => { throw new Error("native_harness_preservation_source_unsettled"); }; +const sessionSelections = (db: Db, input: { companyId: string; agentId: string; issueId: string; sessionId: string }) => + db.select({ id: agentTaskSessions.id, lastRunId: agentTaskSessions.lastRunId }).from(agentTaskSessions).where(and( + eq(agentTaskSessions.companyId, input.companyId), eq(agentTaskSessions.agentId, input.agentId), + eq(agentTaskSessions.adapterType, "paperclip_runner"), + sql`exists (select 1 from ${heartbeatRuns} where ${heartbeatRuns.id} = ${agentTaskSessions.lastRunId} + and ${heartbeatRuns.companyId} = ${agentTaskSessions.companyId} and ${heartbeatRuns.agentId} = ${agentTaskSessions.agentId} + and ${heartbeatRuns.nativeIssueId} = ${input.issueId} and ${heartbeatRuns.nativeSessionId} = ${input.sessionId})`, + )).orderBy(asc(agentTaskSessions.id)); /** Copy sealed historical files without certifying provider termination, changing * a failed run, or taking an expired coordinator. Every publication rechecks it. */ @@ -38,17 +46,12 @@ export async function settledNativeHarnessBackupOwner(db: Db, input: { companyId: string; issueId: string; runId: string; sessionId: string; runnerInstanceId: string; scopeDigest: string; root: string; manifestSha256: string; providerLeaseId: string; signal: AbortSignal; }): Promise<{ owner: SettledNativeHarnessBackupOwner; reason?: never } - | { owner: null; reason: "coordinator_missing" | "coordinator_unsettled" | "session_not_selected" | "lease_missing" }> { + | { owner: null; reason: "coordinator_missing" | "coordinator_unsettled" | "lease_missing" }> { const [run] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.id, input.runId))); const [coordinator] = await db.select().from(nativeRunFinalizations).where(and(eq(nativeRunFinalizations.companyId, input.companyId), eq(nativeRunFinalizations.issueId, input.issueId), eq(nativeRunFinalizations.runId, input.runId))); if (!run || !coordinator || !settled(coordinator)) return { owner: null, reason: run && coordinator ? "coordinator_unsettled" : "coordinator_missing" }; - const selected = await db.select({ id: agentTaskSessions.id, lastRunId: agentTaskSessions.lastRunId }).from(agentTaskSessions) - .innerJoin(heartbeatRuns, and(eq(heartbeatRuns.companyId, agentTaskSessions.companyId), eq(heartbeatRuns.agentId, agentTaskSessions.agentId), - eq(heartbeatRuns.id, agentTaskSessions.lastRunId))).where(and(eq(agentTaskSessions.companyId, input.companyId), - eq(agentTaskSessions.agentId, run.agentId), eq(agentTaskSessions.adapterType, "paperclip_runner"), - eq(heartbeatRuns.nativeIssueId, input.issueId), eq(heartbeatRuns.nativeSessionId, input.sessionId))).limit(2); - if (selected.length !== 1 || !selected[0]!.lastRunId) return { owner: null, reason: "session_not_selected" }; + const selections = await sessionSelections(db, { ...input, agentId: run.agentId }); const leases = await db.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.issueId, input.issueId), eq(environmentLeases.providerLeaseId, input.providerLeaseId), sql`${environmentLeases.metadata}->'nativeHarnessBackup'->>'manifestSha256' = ${input.manifestSha256}`)); @@ -57,7 +60,7 @@ export async function settledNativeHarnessBackupOwner(db: Db, input: { const owner: SettledNativeHarnessBackupOwner = { kind: "settled_native_harness_backup", companyId: input.companyId, issueId: input.issueId, agentId: run.agentId, runId: input.runId, sessionId: input.sessionId, runnerInstanceId: input.runnerInstanceId, scopeDigest: input.scopeDigest, root: input.root, manifestSha256: input.manifestSha256, - selectedSessionId: selected[0]!.id, selectedLastRunId: selected[0]!.lastRunId, + selections, sourceLeaseId: lease.id, providerLeaseId: input.providerLeaseId, runDigest: runDigest(run), coordinatorDigest: coordinatorDigest(coordinator), leaseDigest: leaseDigest(lease) }; await db.transaction(tx => assertSettledNativeHarnessBackupSource(tx as unknown as Db, owner, input.signal)); @@ -74,18 +77,12 @@ export async function assertSettledNativeHarnessBackupSource(db: Db, owner: Sett const [coordinator] = await db.select().from(nativeRunFinalizations).where(and(eq(nativeRunFinalizations.companyId, owner.companyId), eq(nativeRunFinalizations.issueId, owner.issueId), eq(nativeRunFinalizations.runId, owner.runId))).for("update"); if (!coordinator || !settled(coordinator) || coordinatorDigest(coordinator) !== owner.coordinatorDigest) fail(); - const [selection] = await db.select().from(agentTaskSessions).where(and(eq(agentTaskSessions.companyId, owner.companyId), - eq(agentTaskSessions.agentId, owner.agentId), eq(agentTaskSessions.id, owner.selectedSessionId), - eq(agentTaskSessions.adapterType, "paperclip_runner"), - eq(agentTaskSessions.lastRunId, owner.selectedLastRunId))).for("share"); - const [selectedRun] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, owner.companyId), - eq(heartbeatRuns.agentId, owner.agentId), eq(heartbeatRuns.id, owner.selectedLastRunId), - eq(heartbeatRuns.nativeIssueId, owner.issueId), eq(heartbeatRuns.nativeSessionId, owner.sessionId))); + const selections = await sessionSelections(db, owner).for("share"); const [run] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, owner.companyId), eq(heartbeatRuns.agentId, owner.agentId), eq(heartbeatRuns.id, owner.runId), eq(heartbeatRuns.nativeIssueId, owner.issueId), eq(heartbeatRuns.nativeSessionId, owner.sessionId), eq(heartbeatRuns.runnerInstanceId, owner.runnerInstanceId), eq(heartbeatRuns.runtimeMode, "native"))).for("share"); const [clock] = await db.execute<{ now: Date }>(sql`select clock_timestamp() as now`); - if (!selection || !selectedRun || !run?.finishedAt || !["failed", "cancelled", "interrupted", "timed_out"].includes(run.status) + if (JSON.stringify(selections) !== JSON.stringify(owner.selections) || !run?.finishedAt || !["failed", "cancelled", "interrupted", "timed_out"].includes(run.status) || run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date(clock.now) || adapterExecutionControls.has(run.id) || run.runnerProfileJson?.nativeWorkspaceFinalizationOwner != null || runDigest(run) !== owner.runDigest) fail(); diff --git a/server/src/services/native-runtime/runtime-skill-preservation.ts b/server/src/services/native-runtime/runtime-skill-preservation.ts index df8ad79216c..066f2ed14c5 100644 --- a/server/src/services/native-runtime/runtime-skill-preservation.ts +++ b/server/src/services/native-runtime/runtime-skill-preservation.ts @@ -268,13 +268,19 @@ export async function migrateRuntimeSkillAssets(db: Db, options: { companyId?: s .where(and(retainedRuntimeSkillsSql(), options.companyId ? eq(heartbeatRuns.companyId, options.companyId) : undefined, options.after ? gt(heartbeatRuns.id, options.after) : undefined)).orderBy(asc(heartbeatRuns.id)) .limit(Math.max(1, Math.min(50, options.limit ?? 10))); - const results: Array<{ runId: string; status: "candidate" | "preserved"; preserved?: number }> = []; + const results: Array<{ runId: string; status: "candidate" } | { runId: string; status: "preserved"; preserved: number } + | { runId: string; status: "unsaved"; code: `runtime_skill_source_absent:${RuntimeSkillSourceAbsent["reason"]}` }> = []; await withSkillPackageReadScope(db, async () => { for (const row of rows) { options.signal?.throwIfAborted(); if (!options.apply) { results.push({ runId: row.id, status: "candidate" }); continue; } - const result = await preserveRuntimeSkillAssets(db, { companyId: row.companyId, runId: row.id, signal: options.signal }, storage); - results.push({ runId: row.id, status: "preserved", preserved: result.preserved }); + try { + const result = await preserveRuntimeSkillAssets(db, { companyId: row.companyId, runId: row.id, signal: options.signal }, storage); + results.push({ runId: row.id, status: "preserved", preserved: result.preserved }); + } catch (error) { + if (!(error instanceof RuntimeSkillSourceAbsent)) throw error; + results.push({ runId: row.id, status: "unsaved", code: `runtime_skill_source_absent:${error.reason}` }); + } } }); return { inspected: rows.length, after: rows.at(-1)?.id ?? null, results }; diff --git a/server/src/services/online-durable-data-migration.test.ts b/server/src/services/online-durable-data-migration.test.ts index 83da5636465..9f594546974 100644 --- a/server/src/services/online-durable-data-migration.test.ts +++ b/server/src/services/online-durable-data-migration.test.ts @@ -194,6 +194,34 @@ describe("online durable-data migration pass", () => { expect(result.deferred).toMatchObject({ "runtime_skill_assets:runtime_skill_source_absent:missing": 1 }); }); + it("names each retained runtime skill run it could not save", async () => { + const fixture = owners({ runtimeSkillAssets: async () => ({ inspected: 3, after: null, results: [ + { runId: "r1", status: "preserved", preserved: 1 }, + { runId: "r2", status: "unsaved", code: "runtime_skill_source_absent:missing" }, + { runId: "r3", status: "unsaved", code: "runtime_skill_source_absent:missing" }] }) }); + const result = await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners); + expect(result.counts.runtimeSkillRuns).toBe(1); + expect(result.deferred["runtime_skill_assets:runtime_skill_source_absent:missing"]).toBe(2); + }); + + it("keeps naming an unsaved runtime skill run after a later pass resumes past it", async () => { + let clock = 0; + const fixture = owners({ + runtimeSkillAssets: async () => { + clock = 61_000; + return { inspected: 1, after: null, results: [{ runId: "r1", status: "unsaved", code: "runtime_skill_source_absent:missing" }] }; + }, + eligibility: vi.fn(async () => ({ eligible: false, blockers: ["runtime_skill_assets_require_migration"] })), + }); + const first = await runOnlineDurableDataMigration(db, { budgetMs: 60_000, now: () => clock }, fixture.owners); + expect(first).toMatchObject({ state: "budget_exhausted", resumePhase: "run_logs" }); + clock = 0; + const second = await runOnlineDurableDataMigration(db, { budgetMs: 60_000, now: () => clock }, fixture.owners); + expect(second.state).toBe("completed"); + expect(second.deferred["runtime_skill_assets:runtime_skill_source_absent:missing"]).toBe(1); + expect(second.deferred["runtime_skill_assets:pending_inspection"]).toBeUndefined(); + }); + it("passes the page size to the skill object copy so a slow page can shrink", async () => { const skillObjects = vi.fn(async () => ({ inspected: 0, migrated: 0, busy: 0, after: null })); await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, owners({ skillObjects }).owners); @@ -309,7 +337,7 @@ describe("online durable-data migration pass", () => { it("names every durable-data blocker that readiness can report", async () => { const source = await fs.readFile(new URL("./ephemeral-server-contract.ts", import.meta.url), "utf8"); - const blockers = [...new Set([...source.matchAll(/blockers\.push\("([a-z_]+)"\)/g)].map(match => match[1]!)), RUNTIME_SKILL_ASSETS_BLOCKER]; + const blockers = [...new Set([...source.matchAll(/(?:blockers\.push\(|check\(\s*"[a-z_]+",)\s*"([a-z_]+)"/g)].map(match => match[1]!)), RUNTIME_SKILL_ASSETS_BLOCKER]; expect(blockers).toEqual(expect.arrayContaining(["workspaces_require_migration", "local_instruction_copies_require_settlement", "external_agent_instructions"])); for (const blocker of blockers) { resetOnlineDurableDataMigrationProgressForTests(); @@ -345,6 +373,18 @@ describe("online durable-data migration pass", () => { expect(result.deferred).toMatchObject({ "workspaces:pending_inspection": 1 }); }); + it("names why a workspace source scope is unproven", async () => { + const fixture = owners({ + localWorkspaces: async () => [workspace(1), workspace(2)], + inventoryWorkspace: async (_db: Db, input: { workspaceId: string }) => input.workspaceId === "w1" + ? { reasons: ["online_workspace_source_scope_unproven"], sourceScopeUnproven: "git_link_stale" } + : { reasons: ["online_workspace_source_scope_unproven"], sourceScopeUnproven: "/private path" }, + }); + const result = await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners); + expect(result.deferred).toMatchObject({ "workspaces:online_workspace_source_scope_unproven": 2, "workspaces:source_scope_git_link_stale": 1 }); + expect(JSON.stringify(result)).not.toContain("private"); + }); + it("migrates an idle workspace through the online owner with a bounded source-lock wait, never the offline mode", async () => { const migrateWorkspace = vi.fn(async () => ({ alreadyMigrated: true, reasons: [] })); const fixture = owners({ localWorkspaces: async () => [workspace(1)], migrateWorkspace }); diff --git a/server/src/services/online-durable-data-migration.ts b/server/src/services/online-durable-data-migration.ts index d8baec60846..b042f7ef632 100644 --- a/server/src/services/online-durable-data-migration.ts +++ b/server/src/services/online-durable-data-migration.ts @@ -43,7 +43,7 @@ type Owners = { workspaceCompanies: typeof listLocalWorkspaceCompanies; workspaceOperations: (db: Db, input: { companyId: string; signal: AbortSignal }) => Promise<{ reconciled: number; held: Array<{ reason: string }> }>; localWorkspaces: typeof listLocalWorkspaces; - inventoryWorkspace: (db: Db, input: { companyId: string; workspaceId: string }) => Promise<{ reasons: string[] }>; + inventoryWorkspace: (db: Db, input: { companyId: string; workspaceId: string }) => Promise<{ reasons: string[]; sourceScopeUnproven?: string }>; migrateWorkspace: (input: { db: Db; storage: StorageService; companyId: string; workspaceId: string; apply: true; signal: AbortSignal; sourceLockWaitMs: number }) => Promise<{ alreadyMigrated: boolean; reasons: string[] }>; nativeHarnessBackups: typeof prestageNativeHarnessBackups; @@ -214,7 +214,10 @@ async function migrate(db: Db, input: { budgetMs: number; now?: () => number }, } case "runtime_skill_assets": { const result = await owners.runtimeSkillAssets(db, { apply: true, after, limit, signal }, storage); - add(counts, "runtimeSkillRuns", result.results.filter(row => row.status === "preserved").length); + for (const row of result.results) { + if (row.status === "preserved") add(counts, "runtimeSkillRuns"); + else if (row.status === "unsaved") defer(`runtime_skill_assets:${row.code}`); + } return result.inspected < limit || !result.after ? null : result.after; } case "run_logs": @@ -252,7 +255,9 @@ async function migrate(db: Db, input: { budgetMs: number; now?: () => number }, for (const { companyId, workspaceId } of rows) { let reasons: string[]; try { - reasons = (await owners.inventoryWorkspace(db, { companyId, workspaceId })).reasons; + const inventory = await owners.inventoryWorkspace(db, { companyId, workspaceId }); + reasons = inventory.sourceScopeUnproven && /^[a-z_]{1,60}$/.test(inventory.sourceScopeUnproven) + ? [...inventory.reasons, `source_scope_${inventory.sourceScopeUnproven}`] : inventory.reasons; if (!reasons.length) { const work = owners.migrateWorkspace({ db, storage, companyId, workspaceId, apply: true, signal, sourceLockWaitMs: WORKSPACE_SOURCE_LOCK_WAIT_MS }); diff --git a/server/src/services/online-workspace-source.ts b/server/src/services/online-workspace-source.ts index 3ba9b3b8576..3a52d3a29a5 100644 --- a/server/src/services/online-workspace-source.ts +++ b/server/src/services/online-workspace-source.ts @@ -4,7 +4,7 @@ import { createHash } from "node:crypto"; import { and, eq, gt, inArray, ne, sql } from "drizzle-orm"; import { executionWorkspaces, heartbeatRuns, issueRecoveryActions, type Db } from "@paperclipai/db"; import { resolvePaperclipInstanceRoot } from "../home-paths.js"; -import { inspectImportedWorkspaceSourcePaths, inspectOnlineOrdinarySource, physicalPath, requiresOnlineOrdinarySource, type WorkspaceSourceScope } from "./remote-workspace-migration-tree.js"; +import { explainOnlineOrdinarySource, inspectImportedWorkspaceSourcePaths, physicalPath, requiresOnlineOrdinarySource, type WorkspaceSourceScope } from "./remote-workspace-migration-tree.js"; import { workspaceSourceIdentities } from "./workspace-source-lock.js"; import { readNestedWorkspaceGitSourceRoots, readWorkspaceGitLinkedRoots, readWorkspaceGitSourceRoots, type WorkspaceGitSourceRoots } from "./workspace-git-source-roots.js"; import { inspectOnlineLegacyWorkspaceRecoveryHold, inspectOnlineLegacyWorkspaceRecoverySource, type OnlineLegacyWorkspaceRecoveryHold } from "./online-legacy-workspace-recovery.js"; @@ -45,7 +45,7 @@ async function companion(db: ReadDb, workspace: Workspace, runs: CompanionRun[]) const sources: LegacyWorkspaceRecoverySource[] = []; for (const run of runs.filter(run => run.state === "prepared")) { const source = await inspectOnlineLegacyWorkspaceRecoverySource(db, { workspace, runId: run.id }); - if (!source) return null; + if (!source) return "companion_copyback_unresolved"; sources.push(source); } const issueIds = [...new Set([workspace.sourceIssueId, ...runs.map(run => run.issueId)].filter((id): id is string => Boolean(id)))]; @@ -56,23 +56,45 @@ async function companion(db: ReadDb, workspace: Workspace, runs: CompanionRun[]) const holds: Array = []; for (const recovery of actions) { const hold = await inspectOnlineLegacyWorkspaceRecoveryHold(db, { workspace, recovery }); - if (!hold) return null; + if (!hold) return "companion_recovery_unresolved"; holds.push({ actionId: recovery.id, ...hold }); } return { workspaceId: workspace.id, sources, holds, recoveryIssueIds: issueIds }; } export async function inspectOnlineWorkspaceSource(db: ReadDb, workspace: Workspace): Promise { + const result = await explainOnlineWorkspaceSource(db, workspace); + return "unproven" in result ? null : result; +} + +function gitLinkUnproven(error: unknown) { + const message = error instanceof Error ? error.message : ""; + return message === "workspace_git_link_stale" ? "git_link_stale" : message === "workspace_git_links_exceeded" ? "git_links_exceeded" : "git_links_unreadable"; +} + +function memberUnproven(row: Workspace) { + if (!row.sourceIssueId) return "member_task_binding_missing"; + if (row.cwd && row.providerRef && row.cwd !== row.providerRef) return "member_locator_mismatch"; + if (!["active", "idle", "in_review", "archived"].includes(row.status)) return "member_status_unsupported"; + if (row.metadata?.remoteWorkspace) return "member_already_remote"; + if (hasPendingGitExpiration(row)) return "member_git_expiration_pending"; + return null; +} + +export async function explainOnlineWorkspaceSource(db: ReadDb, workspace: Workspace): Promise { + const unproven = (code: string) => ({ unproven: code }); const cwd = workspace.cwd ?? workspace.providerRef; - if (!cwd || !path.isAbsolute(cwd) || !["local_fs", "git_worktree"].includes(workspace.providerType)) return null; - const ordinary = await inspectOnlineOrdinarySource(db, workspace); + if (!cwd || !path.isAbsolute(cwd) || !["local_fs", "git_worktree"].includes(workspace.providerType)) return unproven("locator_unsupported"); + const explained = await explainOnlineOrdinarySource(db, workspace); + const ordinary = explained && !("unproven" in explained) ? explained : null; + const ordinaryUnproven = explained && "unproven" in explained ? explained.unproven : null; let nestedGit: WorkspaceGitSourceRoots[] = []; if (ordinary) { const marker = await fs.lstat(path.join(ordinary.root, ".git")).catch((error: NodeJS.ErrnoException) => { if (error.code !== "ENOENT") throw error; return null; }); if (!marker) { - try { nestedGit = await readNestedWorkspaceGitSourceRoots(ordinary.root); } catch { return null; } + try { nestedGit = await readNestedWorkspaceGitSourceRoots(ordinary.root); } catch { return unproven("nested_git_unreadable"); } if (!nestedGit.length) return { ...ordinary, kind: "ordinary", projectIds: ordinary.projectId ? [ordinary.projectId] : [], companions: [] }; } } @@ -82,50 +104,53 @@ export async function inspectOnlineWorkspaceSource(db: ReadDb, workspace: Worksp issueIds: [...ordinary.issueIds], unownedPaths: [], git: null } : await workspaceSourceIdentities(workspace.companyId, cwd); for (const source of nestedGit) { const nested = await workspaceSourceIdentities(workspace.companyId, source.root); - if (!nested.git || nested.git.fingerprint !== source.fingerprint) return null; + if (!nested.git || nested.git.fingerprint !== source.fingerprint) return unproven("nested_git_changed"); selected.projectIds = [...new Set([...selected.projectIds, ...nested.projectIds])].sort(); selected.issueIds = [...new Set([...selected.issueIds, ...nested.issueIds])].sort(); selected.unownedPaths = [...new Set([...selected.unownedPaths, ...nested.unownedPaths])].sort(); } - } catch { return null; } + } catch { return unproven("git_identity_unreadable"); } const captureRoot = await physicalPath(cwd), gitSources = selected.git ? [selected.git] : nestedGit; - if (!gitSources.length || selected.git && selected.git.root !== captureRoot || selected.unownedPaths.length || !workspace.sourceIssueId - || workspace.cwd && workspace.providerRef && workspace.cwd !== workspace.providerRef) return null; + if (!gitSources.length) return unproven(ordinaryUnproven ?? "not_git_source"); + if (selected.git && selected.git.root !== captureRoot) return unproven("git_root_mismatch"); + if (selected.unownedPaths.length) return unproven("unowned_path"); + if (!workspace.sourceIssueId) return unproven("task_binding_missing"); + if (workspace.cwd && workspace.providerRef && workspace.cwd !== workspace.providerRef) return unproven("locator_mismatch"); for (const source of gitSources) { const head = await fs.lstat(path.join(source.gitDirectory.path, "HEAD")).catch((error: NodeJS.ErrnoException) => { if (error.code !== "ENOENT") throw error; return null; }); - if (!head || !head.isFile() && !head.isSymbolicLink()) return null; + if (!head || !head.isFile() && !head.isSymbolicLink()) return unproven("git_head_missing"); } const linkedSources = new Map>[number]>(); try { for (const source of gitSources) { for (const proof of await readWorkspaceGitLinkedRoots(source)) { const existing = linkedSources.get(proof.commonDirectory.path); - if (existing && JSON.stringify(existing) !== JSON.stringify(proof)) return null; + if (existing && JSON.stringify(existing) !== JSON.stringify(proof)) return unproven("git_links_conflict"); linkedSources.set(proof.commonDirectory.path, proof); } } for (const proof of linkedSources.values()) { for (const link of proof.links) { const linked = await workspaceSourceIdentities(workspace.companyId, link.root.path); - if (!linked.git || linked.git.gitDirectory.path !== link.gitDirectory.path) return null; + if (!linked.git || linked.git.gitDirectory.path !== link.gitDirectory.path) return unproven("git_link_changed"); selected.projectIds = [...new Set([...selected.projectIds, ...linked.projectIds])].sort(); selected.issueIds = [...new Set([...selected.issueIds, ...linked.issueIds])].sort(); selected.unownedPaths = [...new Set([...selected.unownedPaths, ...linked.unownedPaths])].sort(); } } - } catch { return null; } - if (selected.unownedPaths.length) return null; + } catch (error) { return unproven(gitLinkUnproven(error)); } + if (selected.unownedPaths.length) return unproven("unowned_path"); const selectedFingerprint = createHash("sha256").update(JSON.stringify([gitSources, [...linkedSources.values()]])).digest("hex"); const entry = await fs.lstat(cwd); const rows = await db.select().from(executionWorkspaces).where(and(eq(executionWorkspaces.companyId, workspace.companyId), inArray(executionWorkspaces.providerType, ["local_fs", "git_worktree"]))).orderBy(executionWorkspaces.id).limit(1001); - if (rows.length > 1000) return null; + if (rows.length > 1000) return unproven("company_records_exceeded"); const nodes: Array<{ row: Workspace; identities: Identities; fingerprint: string | null }> = []; for (const row of rows) { const paths = localWorkspaceSourcePaths(row); - if (!paths.length || paths.some(cwd => !path.isAbsolute(cwd))) return null; + if (!paths.length || paths.some(cwd => !path.isAbsolute(cwd))) return unproven("member_locator_invalid"); try { const identities = paths[0] === captureRoot ? { ...selected, projectIds: [...selected.projectIds], issueIds: [...selected.issueIds] } : await workspaceSourceIdentities(workspace.companyId, paths[0]); @@ -135,7 +160,7 @@ export async function inspectOnlineWorkspaceSource(db: ReadDb, workspace: Worksp identities.issueIds = [...new Set([...identities.issueIds, ...alternate.issueIds])].sort(); } nodes.push({ row, identities, fingerprint: paths[0] === captureRoot ? selectedFingerprint : identities.git?.fingerprint ?? null }); - } catch { return null; } + } catch { return unproven("member_unreadable"); } } const projectIds = new Set(selected.projectIds), physicalIssueIds = new Set(selected.issueIds), aliases = new Set(); const importedChildren: NonNullable = []; @@ -143,12 +168,12 @@ export async function inspectOnlineWorkspaceSource(db: ReadDb, workspace: Worksp for (const child of await inspectImportedWorkspaceSourcePaths(db, workspace, [...linkedSources.values()].flatMap(proof => proof.links.map(link => link.root.path)))) { const identities = await workspaceSourceIdentities(workspace.companyId, child.sourcePath); - if (identities.unownedPaths.length) return null; + if (identities.unownedPaths.length) return unproven("imported_child_unowned"); for (const id of identities.projectIds) projectIds.add(id); for (const id of identities.issueIds) physicalIssueIds.add(id); importedChildren.push({ ...child, gitFingerprint: identities.git?.fingerprint ?? null }); } - } catch { return null; } + } catch { return unproven("imported_child_unreadable"); } for (;;) { let changed = false; for (const node of nodes) { @@ -157,9 +182,8 @@ export async function inspectOnlineWorkspaceSource(db: ReadDb, workspace: Worksp && !intersects(node.identities.issueIds, physicalIssueIds) && !(node.row.projectId && projectIds.has(node.row.projectId)) && !(node.row.sourceIssueId && physicalIssueIds.has(node.row.sourceIssueId))) continue; - if (!node.row.sourceIssueId || node.row.cwd && node.row.providerRef && node.row.cwd !== node.row.providerRef - || !["active", "idle", "in_review", "archived"].includes(node.row.status) - || node.row.metadata?.remoteWorkspace || hasPendingGitExpiration(node.row)) return null; + const member = memberUnproven(node.row); + if (member) return unproven(member); aliases.add(node.row.id); changed = true; for (const id of node.identities.projectIds) projectIds.add(id); for (const id of node.identities.issueIds) physicalIssueIds.add(id); @@ -167,14 +191,15 @@ export async function inspectOnlineWorkspaceSource(db: ReadDb, workspace: Worksp } if (!changed) break; } - if (!aliases.has(workspace.id) || aliases.size > 256) return null; + if (!aliases.has(workspace.id)) return unproven("self_excluded"); + if (aliases.size > 256) return unproven("members_exceeded"); const included = nodes.filter(node => aliases.has(node.row.id)); const registeredRoots = await Promise.all([...included.flatMap(node => localWorkspaceSourcePaths(node.row)), ...importedChildren.map(child => child.sourcePath)].map(physicalPath)); if ([...linkedSources.values()].some(proof => proof.links.some(link => !registeredRoots.some(root => - link.root.path === root || link.root.path.startsWith(root + path.sep))))) return null; + link.root.path === root || link.root.path.startsWith(root + path.sep))))) return unproven("git_link_unregistered"); const issueIds = [...new Set([...physicalIssueIds, ...included.map(node => node.row.sourceIssueId!)])].sort(); - if (issueIds.length + projectIds.size > 128) return null; + if (issueIds.length + projectIds.size > 128) return unproven("source_keys_exceeded"); const instance = await physicalPath(resolvePaperclipInstanceRoot()); const gitSourceRoots = [...[...projectIds].map(id => path.join(instance, "projects", workspace.companyId, id)), ...issueIds.flatMap(id => ["isolated-workspaces", "isolated-workspace-attempts", "isolated-repository-sources"].map(kind => @@ -188,21 +213,21 @@ export async function inspectOnlineWorkspaceSource(db: ReadDb, workspace: Worksp .orderBy(executionWorkspaces.id).limit(256); for (const row of foreign) { for (const cwd of localWorkspaceSourcePaths(row)) { - if (!path.isAbsolute(cwd)) return null; + if (!path.isAbsolute(cwd)) return unproven("foreign_locator_invalid"); try { - if (owned(await physicalPath(cwd))) return null; + if (owned(await physicalPath(cwd))) return unproven("foreign_alias"); const git = await readWorkspaceGitSourceRoots(cwd, { ancestors: true }); - if (git && [git.gitDirectory.path, git.commonDirectory.path, ...git.objectDirectories.map(root => root.path)].some(owned)) return null; - } catch { return null; } + if (git && [git.gitDirectory.path, git.commonDirectory.path, ...git.objectDirectories.map(root => root.path)].some(owned)) return unproven("foreign_git_alias"); + } catch { return unproven("foreign_unreadable"); } } } if (foreign.length < 256) break; - if (page === 39) return null; + if (page === 39) return unproven("foreign_records_exceeded"); after = foreign.at(-1)!.id; } const recipe = readGitCacheRestoration(workspace); if (recipe && (!recipe.restoredAt || recipe.contents && !recipe.contentsRestoredAt - || recipe.restorePoint && !recipe.restorePoint.expiredAt && !recipe.restorePoint.appliedAt)) return null; + || recipe.restorePoint && !recipe.restorePoint.expiredAt && !recipe.restorePoint.appliedAt)) return unproven("git_restoration_pending"); const runs = await db.select({ id: heartbeatRuns.id, issueId: heartbeatRuns.nativeIssueId, workspaceId: sql`${heartbeatRuns.runnerProfileJson}->'nativeWorkspaceSync'->>'workspaceId'`, state: sql`${heartbeatRuns.runnerProfileJson}->'nativeWorkspaceSync'->>'state'` }).from(heartbeatRuns).where(and( @@ -219,7 +244,7 @@ export async function inspectOnlineWorkspaceSource(db: ReadDb, workspace: Worksp const companions: OnlineWorkspaceSource["companions"] = [], settledPreparedWorkspaceIds: string[] = [], settledRecoveryIssueIds = new Set(); for (const node of included) { const proof = await companion(db, node.row, runsByWorkspace.get(node.row.id) ?? []); - if (!proof) return null; + if (typeof proof === "string") return unproven(proof); companions.push({ workspaceId: proof.workspaceId, sources: proof.sources, holds: proof.holds }); if (proof.sources.length) settledPreparedWorkspaceIds.push(proof.workspaceId); for (const id of proof.recoveryIssueIds) settledRecoveryIssueIds.add(id); diff --git a/server/src/services/paperclip-cloud-connector-enrollment.test.ts b/server/src/services/paperclip-cloud-connector-enrollment.test.ts index 8d731f426ba..4671d95bdde 100644 --- a/server/src/services/paperclip-cloud-connector-enrollment.test.ts +++ b/server/src/services/paperclip-cloud-connector-enrollment.test.ts @@ -403,7 +403,7 @@ describe("Paperclip Cloud self-host enrollment", () => { delete partialManagedEnv[omitted]; expect(paperclipCloudConnectorEnrollmentStatus(partialManagedEnv)).toMatchObject({ configured: false, - status: "unverified", + status: "misconfigured", instanceId: null, environment: "staging", }); diff --git a/server/src/services/paperclip-cloud-connector-enrollment.ts b/server/src/services/paperclip-cloud-connector-enrollment.ts index 0fbbd9755c7..83cde3ed7f4 100644 --- a/server/src/services/paperclip-cloud-connector-enrollment.ts +++ b/server/src/services/paperclip-cloud-connector-enrollment.ts @@ -46,7 +46,14 @@ export type PaperclipCloudConnectorIdentity = { export type PaperclipCloudConnectorEnrollmentStatus = { configured: boolean; - status: PaperclipCloudConnectorIdentity["status"] | "not_configured" | "suspended" | "unverified"; + /** + * `unverified`: a saved self-hosted identity belongs to another broker; + * registering again fixes it. `misconfigured`: managed identity settings are + * incomplete; self-hosted registration is unavailable, so an administrator + * must finish them. `unreachable`: the identity is complete, but Cloud did + * not answer the check (rate limit, outage, network); a retry is the fix. + */ + status: PaperclipCloudConnectorIdentity["status"] | "not_configured" | "suspended" | "unverified" | "misconfigured" | "unreachable"; brokerBaseUrl: string; instanceId: string | null; environment: LocalConnectorEnvironment; @@ -84,7 +91,7 @@ export function paperclipCloudConnectorEnrollmentStatus( if (!managedInstanceId || !managedSignPrivateKey || !managedSealPrivateKey || !managedEnvironment) { return { configured: false, - status: "unverified", + status: "misconfigured", brokerBaseUrl, instanceId: null, environment, diff --git a/server/src/services/paperclip-cloud-connector-saved-answers.test.ts b/server/src/services/paperclip-cloud-connector-saved-answers.test.ts new file mode 100644 index 00000000000..ddad1c2cddc --- /dev/null +++ b/server/src/services/paperclip-cloud-connector-saved-answers.test.ts @@ -0,0 +1,222 @@ +import { generateKeyPairSync, type KeyObject } from "node:crypto"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { + createPaperclipCloudConnector, + invalidatePaperclipCloudConnectorCapabilities, + paperclipCloudConnectorCapabilitiesFromEnv, + type PaperclipCloudConnectorConfig, +} from "./paperclip-cloud-connector.js"; +import { reconcilePaperclipCloudConnectorEnrollmentStatus } from "./paperclip-cloud-connector-status.js"; + +// A busy or failing broker gives no verdict, so the last answer Cloud confirmed +// stands. Production Cloud stacks hit this when the broker rate-limited their +// checks: managed GitHub sign-in vanished and the card asked for a key. + +function rawPrivateKey(key: KeyObject): string { + const jwk = key.export({ format: "jwk" }) as { d?: string }; + if (!jwk.d) throw new Error("missing private key bytes"); + return jwk.d; +} + +function config(): PaperclipCloudConnectorConfig { + return { + baseUrl: "https://my.example.test", + instanceId: "inst_saved_answers", + environment: "staging", + signPrivateKey: rawPrivateKey(generateKeyPairSync("ed25519").privateKey), + sealPrivateKey: rawPrivateKey(generateKeyPairSync("x25519").privateKey), + }; +} + +function managedEnv(keys: PaperclipCloudConnectorConfig): NodeJS.ProcessEnv { + return { + PAPERCLIP_CLOUD_CONNECTOR_BASE_URL: keys.baseUrl, + PAPERCLIP_CLOUD_CONNECTOR_INSTANCE_ID: keys.instanceId, + PAPERCLIP_CLOUD_CONNECTOR_ENVIRONMENT: keys.environment, + PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY: keys.signPrivateKey, + PAPERCLIP_CLOUD_CONNECTOR_SEAL_PRIVATE_KEY: keys.sealPrivateKey, + }; +} + +const busy = () => new Response(JSON.stringify({ error: "RATE_LIMITED" }), { status: 429 }); +const active = (profiles: string[] = ["github.code"]) => Response.json({ active: true, status: "active", profiles }); + +function connectorAnswering(...responses: Response[]) { + return createPaperclipCloudConnector({ + config: config(), + request: vi.fn(async () => responses.shift()!) as typeof fetch, + }); +} + +describe("Paperclip Cloud connector saved answers", () => { + beforeEach(() => invalidatePaperclipCloudConnectorCapabilities()); + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + invalidatePaperclipCloudConnectorCapabilities(); + }); + + it("keeps the last confirmed sign-ins and standing while Cloud rate-limits or fails", async () => { + const connector = connectorAnswering( + active(), + busy(), + new Response("upstream", { status: 503 }), + Response.json({ active: true, status: "active" }), + busy(), + ); + await expect(connector.getCapabilities()).resolves.toEqual(["github.code"]); + await expect(connector.readCapabilities()).resolves.toEqual({ profiles: ["github.code"], confirmed: false }); + await expect(connector.getCapabilities()).resolves.toEqual(["github.code"]); + await expect(connector.getInstanceStatus()).resolves.toBe("active"); + await expect(connector.getInstanceStatus()).resolves.toBe("active"); + }); + + it("treats an unreadable answer or a gateway timeout as no verdict, but a wrong-shaped answer as one", async () => { + const connector = connectorAnswering( + active(), + new Response("gateway", { status: 200 }), + new Response("timeout", { status: 408 }), + Response.json({ active: "yes" }), + ); + await expect(connector.getCapabilities()).resolves.toEqual(["github.code"]); + await expect(connector.getCapabilities()).resolves.toEqual(["github.code"]); + await expect(connector.getCapabilities()).resolves.toEqual(["github.code"]); + await expect(connector.getCapabilities()).resolves.toEqual([]); + }); + + it("reports no verdict when Cloud is busy and nothing was confirmed yet", async () => { + const connector = connectorAnswering(busy(), busy()); + await expect(connector.readCapabilities()).resolves.toEqual({ profiles: [], confirmed: false }); + await expect(connector.getInstanceStatus()).rejects.toMatchObject({ status: 429 }); + }); + + it("does not bring sign-ins back after Cloud rejects the registration", async () => { + const connector = connectorAnswering(active(), new Response("removed", { status: 401 }), busy()); + await expect(connector.getCapabilities()).resolves.toEqual(["github.code"]); + await expect(connector.getCapabilities()).resolves.toEqual([]); + await expect(connector.getCapabilities()).resolves.toEqual([]); + }); + + it("drops saved sign-ins when Cloud confirms the instance is removed or suspended", async () => { + for (const confirmation of [ + new Response("unknown instance", { status: 401 }), + Response.json({ active: false, status: "suspended" }), + ]) { + invalidatePaperclipCloudConnectorCapabilities(); + const connector = connectorAnswering(active(), confirmation, busy()); + await expect(connector.getCapabilities()).resolves.toEqual(["github.code"]); + await expect(connector.getInstanceStatus()).resolves.not.toBe("active"); + await expect(connector.getCapabilities()).resolves.toEqual([]); + } + }); + + it("stops advertising cached sign-ins as soon as Cloud confirms removal", async () => { + const keys = config(); + const env = managedEnv(keys); + vi.spyOn(globalThis, "fetch").mockResolvedValue(active()); + await expect(paperclipCloudConnectorCapabilitiesFromEnv(env)).resolves.toEqual(["github.code"]); + const connector = createPaperclipCloudConnector({ + config: keys, + request: vi.fn(async () => new Response("removed", { status: 401 })) as typeof fetch, + }); + await expect(connector.getInstanceStatus()).resolves.toBe("removed"); + vi.mocked(globalThis.fetch).mockResolvedValue(Response.json({ active: false, status: "removed" })); + await expect(paperclipCloudConnectorCapabilitiesFromEnv(env)).resolves.toEqual([]); + }); + + it("does not let a gallery read in flight restore sign-ins after Cloud confirms removal", async () => { + const keys = config(); + const env = managedEnv(keys); + const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(active()); + await expect(paperclipCloudConnectorCapabilitiesFromEnv(env)).resolves.toEqual(["github.code"]); + vi.useFakeTimers({ toFake: ["Date"], now: Date.now() + 61_000 }); + let answerLate!: (response: Response) => void; + fetchMock.mockImplementationOnce(() => new Promise((resolve) => { answerLate = resolve; })); + const inFlight = paperclipCloudConnectorCapabilitiesFromEnv(env); + const connector = createPaperclipCloudConnector({ + config: keys, + request: vi.fn(async () => new Response("removed", { status: 401 })) as typeof fetch, + }); + await expect(connector.getInstanceStatus()).resolves.toBe("removed"); + answerLate(active()); + await inFlight; + // Cloud is now busy: the fallback must be the removal, not the late list. + fetchMock.mockResolvedValue(busy()); + await expect(paperclipCloudConnectorCapabilitiesFromEnv(env)).resolves.toEqual([]); + }); + + it("keeps a recovery answer when an older removal answer arrives while it is in flight", async () => { + let answerOldRemoval!: (response: Response) => void; + let answerRecovery!: (response: Response) => void; + const responses: Array> = [ + new Promise((resolve) => { answerOldRemoval = resolve; }), + new Promise((resolve) => { answerRecovery = resolve; }), + busy(), + ]; + const connector = createPaperclipCloudConnector({ + config: config(), + request: vi.fn(async () => responses.shift()!) as typeof fetch, + }); + const oldRemoval = connector.getInstanceStatus(); + invalidatePaperclipCloudConnectorCapabilities(); + const recovery = connector.getInstanceStatus(); + answerOldRemoval(new Response("removed", { status: 401 })); + await expect(oldRemoval).resolves.toBe("removed"); + answerRecovery(Response.json({ active: true, status: "active" })); + await expect(recovery).resolves.toBe("active"); + // Cloud is busy now; the recovery answer is the one that stands. + await expect(connector.getInstanceStatus()).resolves.toBe("active"); + }); + + it("does not let an answer that started before an invalidation replace a newer one", async () => { + let answerLate!: (response: Response) => void; + const responses: Array> = [ + new Promise((resolve) => { answerLate = resolve; }), + active(), + busy(), + ]; + const connector = createPaperclipCloudConnector({ + config: config(), + request: vi.fn(async () => responses.shift()!) as typeof fetch, + }); + const late = connector.getCapabilities(); + invalidatePaperclipCloudConnectorCapabilities(); + await expect(connector.getCapabilities()).resolves.toEqual(["github.code"]); + answerLate(Response.json({ active: false, status: "pending" })); + await expect(late).resolves.toEqual([]); + await expect(connector.getCapabilities()).resolves.toEqual(["github.code"]); + }); + + it("keeps a rate-limited capability check only briefly", async () => { + const env = managedEnv(config()); + vi.useFakeTimers({ toFake: ["Date"], now: Date.UTC(2026, 10, 23) }); + const request = vi.spyOn(globalThis, "fetch") + .mockResolvedValueOnce(busy()) + .mockResolvedValue(active()); + await expect(paperclipCloudConnectorCapabilitiesFromEnv(env)).resolves.toEqual([]); + // Reads during the short hold reuse the fallback instead of calling Cloud. + await expect(paperclipCloudConnectorCapabilitiesFromEnv(env)).resolves.toEqual([]); + expect(request).toHaveBeenCalledTimes(1); + vi.advanceTimersByTime(5_001); + await expect(paperclipCloudConnectorCapabilitiesFromEnv(env)).resolves.toEqual(["github.code"]); + await expect(paperclipCloudConnectorCapabilitiesFromEnv(env)).resolves.toEqual(["github.code"]); + expect(request).toHaveBeenCalledTimes(2); + }); + + it("reports an unanswered status check as unreachable, and a local problem as unverified", async () => { + const env = managedEnv(config()); + await expect(reconcilePaperclipCloudConnectorEnrollmentStatus(env, vi.fn(async () => busy()) as typeof fetch)) + .resolves.toMatchObject({ configured: false, status: "unreachable" }); + await expect(reconcilePaperclipCloudConnectorEnrollmentStatus(env, vi.fn(async () => { + throw new Error("network down"); + }) as typeof fetch)).resolves.toMatchObject({ status: "unreachable" }); + await expect(reconcilePaperclipCloudConnectorEnrollmentStatus( + env, + vi.fn(async () => new Response("bad request", { status: 400 })) as typeof fetch, + )).resolves.toMatchObject({ status: "unverified" }); + const incomplete = { ...env, PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY: "" }; + await expect(reconcilePaperclipCloudConnectorEnrollmentStatus(incomplete, vi.fn() as typeof fetch)) + .resolves.toMatchObject({ status: "misconfigured" }); + }); +}); diff --git a/server/src/services/paperclip-cloud-connector-status.ts b/server/src/services/paperclip-cloud-connector-status.ts index 19cfda69637..a4fe0ea3869 100644 --- a/server/src/services/paperclip-cloud-connector-status.ts +++ b/server/src/services/paperclip-cloud-connector-status.ts @@ -4,6 +4,7 @@ import { } from "./paperclip-cloud-connector-enrollment.js"; import { createPaperclipCloudConnector, + isTransientPaperclipCloudConnectorError, paperclipCloudConnectorConfigFromEnv, } from "./paperclip-cloud-connector.js"; @@ -20,7 +21,11 @@ export async function reconcilePaperclipCloudConnectorEnrollmentStatus( if (status === "active") return { ...local, configured: true, status: "active" }; if (status === "suspended") return { ...local, configured: false, status: "suspended" }; return { ...local, configured: false, status: "not_configured" }; - } catch { - return { ...local, configured: false, status: "unverified" }; + } catch (error) { + return { + ...local, + configured: false, + status: isTransientPaperclipCloudConnectorError(error) ? "unreachable" : "unverified", + }; } } diff --git a/server/src/services/paperclip-cloud-connector.ts b/server/src/services/paperclip-cloud-connector.ts index a5078c4f3dd..65ecd3d1393 100644 --- a/server/src/services/paperclip-cloud-connector.ts +++ b/server/src/services/paperclip-cloud-connector.ts @@ -224,6 +224,31 @@ export class PaperclipCloudConnectorError extends Error { } } +/** + * True when the broker never gave a verdict: it was unreachable, rate-limited + * the request, or failed on its side. Such a failure says nothing about the + * instance's enrollment or which sign-ins it has. + */ +export function isTransientPaperclipCloudConnectorError(error: unknown): boolean { + if (!(error instanceof PaperclipCloudConnectorError)) return false; + if (error.code === "CONNECTOR_UNAVAILABLE" || error.brokerReason === UNREADABLE_RESPONSE) return true; + const status = error.status ?? 0; + return status === 408 || status === 429 || status >= 500; +} + +const UNREADABLE_RESPONSE = "UNREADABLE_RESPONSE"; + +// Last answers the broker confirmed, per connector identity, for this process. +// The generation stops a request that started before an invalidation from +// saving its older answer over the newer state. +const lastKnownCapabilities = new Map(); +const lastKnownInstanceStatus = new Map(); +let savedAnswerGeneration = 0; + +function connectorConfigKey(config: PaperclipCloudConnectorConfig): string { + return `${config.baseUrl}|${config.instanceId}|${config.environment}`; +} + export function paperclipCloudConnectorConfigFromEnv( env: NodeJS.ProcessEnv = process.env, ): PaperclipCloudConnectorConfig | null { @@ -301,6 +326,11 @@ export function createPaperclipCloudConnector(input: { const now = input.now ?? Date.now; const signingKey = privateKey(config.signPrivateKey, "ed25519"); const sealKey = privateKey(config.sealPrivateKey, "x25519"); + const configKey = connectorConfigKey(config); + function remember(store: Map, value: T, generation: number): T { + if (generation === savedAnswerGeneration) store.set(configKey, value); + return value; + } let eventWakeVersion: 1 | null = null; async function call( @@ -370,7 +400,16 @@ export function createPaperclipCloudConnector(input: { try { return await response.json() as ConnectorResponse; } catch { - throw new PaperclipCloudConnectorError("Paperclip Cloud connector returned an invalid response", "CONNECTOR_BAD_RESPONSE"); + // A body that is not JSON (for example a gateway page during an outage) + // is no verdict; a readable answer with the wrong shape stays a + // protocol error. + throw new PaperclipCloudConnectorError( + "Paperclip Cloud connector returned an invalid response", + "CONNECTOR_BAD_RESPONSE", + response.status, + undefined, + UNREADABLE_RESPONSE, + ); } } @@ -412,6 +451,36 @@ export function createPaperclipCloudConnector(input: { return credentials; } + async function readCapabilities(): Promise<{ profiles: PaperclipCloudConnectorProfileId[]; confirmed: boolean }> { + const generation = savedAnswerGeneration; + let response: ConnectorResponse; + try { + response = await call("status", { + subject: "instance-capabilities", + companyId: "instance-capabilities", + }); + } catch (error) { + // A rate limit or outage says nothing about which sign-ins this + // instance has. Falling back to "none" hid managed sign-in and offered + // a pasted key instead, so keep the last confirmed list. + if (isTransientPaperclipCloudConnectorError(error)) { + return { profiles: lastKnownCapabilities.get(configKey) ?? [], confirmed: false }; + } + // A rejection (for example a removed registration) is an answer: a + // later outage must not bring the old sign-ins back. + return { profiles: remember(lastKnownCapabilities, [], generation), confirmed: false }; + } + if (response.active !== true || response.status !== "active" || !Array.isArray(response.profiles)) { + return { profiles: remember(lastKnownCapabilities, [], generation), confirmed: true }; + } + return { + profiles: remember(lastKnownCapabilities, [...new Set(response.profiles.flatMap((value) => + typeof value === "string" && isPaperclipCloudConnectorProfileId(value) ? [value] : [] + ))], generation), + confirmed: true, + }; + } + return { instanceIdentity: () => Object.freeze({ instanceId: config.instanceId, environment: config.environment }), async syncMcpClientMirror(serialized: string): Promise { @@ -492,6 +561,22 @@ export function createPaperclipCloudConnector(input: { return opened; }, async getInstanceStatus(): Promise<"active" | "suspended" | "removed"> { + const generation = savedAnswerGeneration; + const settle = (status: "active" | "suspended" | "removed") => { + remember(lastKnownInstanceStatus, status, generation); + // An inactive registration has no usable sign-ins either, including + // the gallery's cached list. Advancing both generations stops reads + // already in flight from saving or caching their pre-removal list. + // A response from before a later invalidation is stale: it must not + // fence out the answers of checks that started after it. + if (status !== "active" && generation === savedAnswerGeneration) { + remember(lastKnownCapabilities, [], generation); + savedAnswerGeneration += 1; + capabilityCacheGeneration += 1; + if (capabilityCache?.key === configKey) capabilityCache = null; + } + return status; + }; let response: ConnectorResponse; try { response = await call("status", { @@ -499,28 +584,21 @@ export function createPaperclipCloudConnector(input: { companyId: "instance-status", }); } catch (error) { - if (error instanceof PaperclipCloudConnectorError && error.status === 401) return "removed"; + if (error instanceof PaperclipCloudConnectorError && error.status === 401) return settle("removed"); + // A busy or unreachable broker gave no verdict on this instance. Keep + // the standing it last confirmed rather than reporting it unenrolled. + const known = lastKnownInstanceStatus.get(configKey); + if (known && isTransientPaperclipCloudConnectorError(error)) return known; throw error; } - if (response.status === "active" && response.active === true) return "active"; - if (response.status === "suspended" && response.active === false) return "suspended"; - if (response.status === "removed" && response.active === false) return "removed"; + if (response.status === "active" && response.active === true) return settle("active"); + if (response.status === "suspended" && response.active === false) return settle("suspended"); + if (response.status === "removed" && response.active === false) return settle("removed"); throw new PaperclipCloudConnectorError("Paperclip Cloud connector returned an invalid instance status", "CONNECTOR_BAD_RESPONSE"); }, + readCapabilities, async getCapabilities(): Promise { - let response: ConnectorResponse; - try { - response = await call("status", { - subject: "instance-capabilities", - companyId: "instance-capabilities", - }); - } catch { - return []; - } - if (response.active !== true || response.status !== "active" || !Array.isArray(response.profiles)) return []; - return [...new Set(response.profiles.flatMap((value) => - typeof value === "string" && isPaperclipCloudConnectorProfileId(value) ? [value] : [] - ))]; + return (await readCapabilities()).profiles; }, async getSlackManagerAppId(): Promise { const response = await call("status", { subject: "instance-capabilities", companyId: "instance-capabilities" }); @@ -734,7 +812,8 @@ function parseCloudHandoff(value: unknown): { kind: "paperclip_cloud"; session: return { kind: "paperclip_cloud", session }; } -export type PaperclipCloudConnector = Omit, "instanceIdentity" | "slackFormOperation"> & { +export type PaperclipCloudConnector = Omit, "instanceIdentity" | "slackFormOperation" | "readCapabilities"> & { + readCapabilities?: ReturnType["readCapabilities"]; instanceIdentity?: () => Readonly<{ instanceId: string; environment: PaperclipCloudConnectorEnvironment }>; slackFormOperation?: ReturnType["slackFormOperation"]; }; @@ -773,10 +852,14 @@ export function paperclipCloudConnectorConsentAllowed(profile: string): boolean let capabilityCache: { key: string; expiresAt: number; profiles: PaperclipCloudConnectorProfileId[] } | null = null; let capabilityCacheGeneration = 0; +const UNCONFIRMED_CAPABILITIES_TTL_MS = 5_000; export function invalidatePaperclipCloudConnectorCapabilities(): void { capabilityCacheGeneration += 1; capabilityCache = null; + savedAnswerGeneration += 1; + lastKnownCapabilities.clear(); + lastKnownInstanceStatus.clear(); } export async function paperclipCloudConnectorCapabilitiesFromEnv( @@ -794,13 +877,16 @@ export async function paperclipCloudConnectorCapabilitiesFromEnv( throw error; } if (!config) return []; - const key = `${config.baseUrl}|${config.instanceId}|${config.environment}`; + const key = connectorConfigKey(config); if (capabilityCache?.key === key && capabilityCache.expiresAt > Date.now()) return capabilityCache.profiles; const generation = capabilityCacheGeneration; const connector = createPaperclipCloudConnector({ config }); - const profiles = await connector.getCapabilities(); + const { profiles, confirmed } = await connector.readCapabilities(); + // An unanswered check keeps its fallback only briefly, so the next gallery + // read soon asks Cloud again without sending one request per read to a + // broker that is already failing. if (generation === capabilityCacheGeneration) { - capabilityCache = { key, expiresAt: Date.now() + 60_000, profiles }; + capabilityCache = { key, expiresAt: Date.now() + (confirmed ? 60_000 : UNCONFIRMED_CAPABILITIES_TTL_MS), profiles }; } return profiles; } diff --git a/server/src/services/remote-workspace-migration-tree.ts b/server/src/services/remote-workspace-migration-tree.ts index 6a080775e0c..78e43820233 100644 --- a/server/src/services/remote-workspace-migration-tree.ts +++ b/server/src/services/remote-workspace-migration-tree.ts @@ -85,7 +85,29 @@ export async function requiresOnlineOrdinarySource(workspace: Workspace): Promis return false; } -export async function inspectOnlineOrdinarySource(db: ReadDb, workspace: Workspace): Promise | null> { +type OrdinarySource = Omit; + +export async function inspectOnlineOrdinarySource(db: ReadDb, workspace: Workspace): Promise { + const result = await explainOnlineOrdinarySource(db, workspace); + return result && !("unproven" in result) ? result : null; +} + +function ordinaryMemberUnproven(row: { cwd: string | null; providerRef: string | null; providerType: string; repoUrl: string | null; + branchName: string | null; sourceIssueId: string | null; strategyType: string; mode: string; status: string; + metadata: Record | null }, root: string, isolatedIssueId: string | null) { + if (row.cwd?.startsWith(`${root}/`)) return "ordinary_member_nested"; + if (row.cwd !== root || row.providerRef && row.providerRef !== root) return "ordinary_member_locator_mismatch"; + if (row.providerType !== "local_fs" || row.repoUrl || row.branchName) return "ordinary_member_git"; + if (!row.sourceIssueId || isolatedIssueId && row.sourceIssueId !== isolatedIssueId) return "ordinary_member_task_binding"; + if (row.strategyType !== "project_primary" || !["isolated_workspace", "shared_workspace"].includes(row.mode)) return "ordinary_member_strategy_unsupported"; + if (!["active", "idle", "in_review", "archived"].includes(row.status)) return "member_status_unsupported"; + if (row.metadata?.remoteWorkspace) return "member_already_remote"; + if (row.metadata?.gitCacheRestoration || row.metadata?.nestedCloneMigrationPending) return "ordinary_member_restoration_pending"; + return null; +} + +export async function explainOnlineOrdinarySource(db: ReadDb, workspace: Workspace): Promise { + const unproven = (code: string) => ({ unproven: code }); if (!workspace.cwd || workspace.providerType !== "local_fs" || workspace.repoUrl || workspace.branchName) return null; const root = await physicalPath(workspace.cwd); const instance = await physicalPath(resolvePaperclipInstanceRoot()); @@ -96,11 +118,11 @@ export async function inspectOnlineOrdinarySource(db: ReadDb, workspace: Workspa || parts[0] === "isolated-workspace-attempts" && parts.length === 4 && /^[a-zA-Z0-9_-]+$/.test(parts[3])); const projectId = await managedProjectSourceIdentity(workspace.companyId, root); if (root !== workspace.cwd || !(isolated || projectId && path.dirname(root) === path.join( - instance, "projects", workspace.companyId, projectId))) return null; + instance, "projects", workspace.companyId, projectId))) return unproven("ordinary_root_unmanaged"); const entry = await fs.lstat(root).catch((error: NodeJS.ErrnoException) => { if (error.code === "ENOENT") return null; throw error; }); - if (!entry?.isDirectory() || entry.isSymbolicLink()) return null; + if (!entry?.isDirectory() || entry.isSymbolicLink()) return unproven("ordinary_root_missing"); const columns = { id: executionWorkspaces.id, companyId: executionWorkspaces.companyId, cwd: executionWorkspaces.cwd, providerRef: executionWorkspaces.providerRef, providerType: executionWorkspaces.providerType, repoUrl: executionWorkspaces.repoUrl, branchName: executionWorkspaces.branchName, sourceIssueId: executionWorkspaces.sourceIssueId, @@ -113,19 +135,15 @@ export async function inspectOnlineOrdinarySource(db: ReadDb, workspace: Workspa const rows = await db.select(columns).from(executionWorkspaces).where(and( eq(executionWorkspaces.companyId, workspace.companyId), inArray(executionWorkspaces.providerType, ["local_fs", "git_worktree"]))).limit(1001); - if (rows.length > 1000) return null; + if (rows.length > 1000) return unproven("company_records_exceeded"); const aliases: typeof rows = []; for (const row of rows) { const paths = localWorkspaceSourcePaths(row); let physical: string[]; - try { physical = await Promise.all(paths.map(physicalPath)); } catch { return null; } + try { physical = await Promise.all(paths.map(physicalPath)); } catch { return unproven("member_unreadable"); } if (!physical.some(cwd => overlaps(root, cwd))) continue; - if (row.cwd !== root || row.providerRef && row.providerRef !== root - || row.providerType !== "local_fs" || row.repoUrl || row.branchName || !row.sourceIssueId - || isolated && row.sourceIssueId !== workspace.sourceIssueId - || row.strategyType !== "project_primary" || !["isolated_workspace", "shared_workspace"].includes(row.mode) - || !["active", "idle", "in_review", "archived"].includes(row.status) || row.metadata?.remoteWorkspace - || row.metadata?.gitCacheRestoration || row.metadata?.nestedCloneMigrationPending) return null; + const member = ordinaryMemberUnproven(row, root, isolated ? workspace.sourceIssueId : null); + if (member) return unproven(member); aliases.push(row); } let after: string | undefined; @@ -138,14 +156,15 @@ export async function inspectOnlineOrdinarySource(db: ReadDb, workspace: Workspa )).orderBy(executionWorkspaces.id).limit(256); for (const row of foreign) { for (const cwd of localWorkspaceSourcePaths(row)) { - try { if (overlaps(root, await physicalPath(cwd))) return null; } catch { return null; } + try { if (overlaps(root, await physicalPath(cwd))) return unproven("foreign_alias"); } catch { return unproven("foreign_unreadable"); } } } if (foreign.length < 256) break; - if (page === 39) return null; + if (page === 39) return unproven("foreign_records_exceeded"); after = foreign.at(-1)!.id; } - if (!aliases.some(row => row.id === workspace.id) || aliases.length > 64) return null; + if (!aliases.some(row => row.id === workspace.id)) return unproven("self_excluded"); + if (aliases.length > 64) return unproven("members_exceeded"); return { root, projectId, device: entry.dev, inode: entry.ino, issueIds: [...new Set(aliases.map(row => row.sourceIssueId!))].sort(), workspaceIds: aliases.map(row => row.id).sort() }; } diff --git a/server/src/services/remote-workspace-migration.test.ts b/server/src/services/remote-workspace-migration.test.ts index b145ed1c7bb..20b0ad53ea5 100644 --- a/server/src/services/remote-workspace-migration.test.ts +++ b/server/src/services/remote-workspace-migration.test.ts @@ -1897,7 +1897,8 @@ describe.skipIf(!support.supported)("remote workspace migration", () => { await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).rejects.toThrow("online_workspace_source_scope_unproven"); expect(readRemoteWorkspaceAuthority((await workspace(f.workspaceId)).metadata)).toBeNull(); }); - it.each(["unregistered", "backlink", "pointer", "symlink-backlink"])("refuses a nested Git wrapper with an unproven linked %s", async mode => { + it.each([["unregistered", "git_link_unregistered"], ["backlink", "git_links_unreadable"], ["pointer", "git_links_unreadable"], + ["symlink-backlink", "git_links_unreadable"], ["stale", "git_link_stale"]])("refuses a nested Git wrapper with an unproven linked %s and names it", async (mode, code) => { const { f, nested } = await nestedGitWrapperFixture(), issueId = randomUUID(); await db.insert(issues).values({ id: issueId, companyId: f.companyId, title: "Linked wrapper" }); const cwd = path.join(resolvePaperclipInstanceRoot(), "isolated-workspaces", f.companyId, issueId), alias = path.join(cwd, "nested"); @@ -1908,7 +1909,9 @@ describe.skipIf(!support.supported)("remote workspace migration", () => { if (mode === "backlink") await fs.writeFile(backlink, path.join(alias, "wrong-marker") + "\n"); if (mode === "pointer") await fs.writeFile(path.join(alias, ".git"), `gitdir: ${path.join(admin, "wrong")}\n`); if (mode === "symlink-backlink") { await fs.rename(backlink, backlink + ".real"); await fs.symlink(backlink + ".real", backlink); } - expect(await inventoryRemoteWorkspaceMigration(db, f)).toMatchObject({ eligible: false, reasons: ["online_workspace_source_scope_unproven"] }); + if (mode === "stale") await fs.rm(alias, { recursive: true, force: true }); + expect(await inventoryRemoteWorkspaceMigration(db, f)).toMatchObject({ eligible: false, reasons: ["online_workspace_source_scope_unproven"], + sourceScopeUnproven: code }); await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).rejects.toThrow("online_workspace_source_scope_unproven"); expect(await db.select().from(workspaceOperations)).toHaveLength(0); expect(await db.select().from(executionWorkspaceSnapshots)).toHaveLength(0); diff --git a/server/src/services/remote-workspace-migration.ts b/server/src/services/remote-workspace-migration.ts index 3d206007389..1c8e5463ec4 100644 --- a/server/src/services/remote-workspace-migration.ts +++ b/server/src/services/remote-workspace-migration.ts @@ -25,7 +25,7 @@ import { readNativeWorkspaceSyncReference } from "./native-runtime/native-worksp import { isLegacyWorkspaceTaskRelated, readLegacyWorkspaceRecoveryAllocations, LEGACY_WORKSPACE_RECOVERY_MIGRATION, type LegacyWorkspaceRecoverySource } from "./legacy-workspace-recovery-migration.js"; import { createNestedWorkspaceImportVerifier, onlineOrdinarySourceBlockers, offlineWorkspaceMigrationBlockers, prepareNestedWorkspaceImports, validateImportedWorkspaceChildren, workspaceMigrationLayoutBlockers, type WorkspaceMigrationCohort } from "./remote-workspace-migration-tree.js"; -import { inspectOnlineWorkspaceSource, requiresOnlineWorkspaceSource, type OnlineWorkspaceSource } from "./online-workspace-source.js"; +import { explainOnlineWorkspaceSource, inspectOnlineWorkspaceSource, requiresOnlineWorkspaceSource, type OnlineWorkspaceSource } from "./online-workspace-source.js"; import { withWorkspaceSourceLocks, withIndependentWorkspaceSourceLocks, IsolatedRepositorySourceBusy } from "./workspace-source-lock.js"; import { inspectOnlineLegacyWorkspaceRecoverySource, inspectOnlineLegacyWorkspaceRecoveryHold, isTaskDispositionRecovery, lockOnlineLegacyWorkspaceRecoverySources, ONLINE_LEGACY_WORKSPACE_PRESERVATION, type OnlineLegacyWorkspaceRecoveryHold } from "./online-legacy-workspace-recovery.js"; import { inspectNativeWorkspaceMigration, nativeWorkspaceMigrationMarker } from "./native-runtime/native-workspace-migration.js"; @@ -344,11 +344,12 @@ async function inspect(db: ReadDb, input: { companyId: string; workspaceId: stri export async function inventoryRemoteWorkspaceMigration(db: Db, input: { companyId: string; workspaceId: string; writersStopped?: boolean }) { const [workspace] = !input.writersStopped ? await db.select().from(executionWorkspaces).where(and( eq(executionWorkspaces.companyId, input.companyId), eq(executionWorkspaces.id, input.workspaceId))) : []; - const onlineSource = workspace && !readRemoteWorkspaceAuthority(workspace.metadata) - ? await inspectOnlineWorkspaceSource(db, workspace) ?? undefined : undefined; - const result = await inspect(db, { ...input, onlineSource, onlineSourceUnproven: Boolean(workspace && !onlineSource - && !readRemoteWorkspaceAuthority(workspace.metadata) && await requiresOnlineWorkspaceSource(workspace)) }); + const explained = workspace && !readRemoteWorkspaceAuthority(workspace.metadata) ? await explainOnlineWorkspaceSource(db, workspace) : undefined; + const onlineSource = explained && !("unproven" in explained) ? explained : undefined; + const onlineSourceUnproven = Boolean(workspace && explained && !onlineSource && await requiresOnlineWorkspaceSource(workspace)); + const result = await inspect(db, { ...input, onlineSource, onlineSourceUnproven }); return { companyId: input.companyId, workspaceId: input.workspaceId, eligible: result.reasons.length === 0, + ...(onlineSourceUnproven && explained && "unproven" in explained ? { sourceScopeUnproven: explained.unproven } : {}), alreadyMigrated: Boolean(result.authority), reasons: result.reasons, localPath: result.workspace.cwd ?? result.workspace.providerRef, source: result.source, operationId: typeof result.marker.operationId === "string" ? result.marker.operationId : null, snapshotId: result.authority?.snapshotId ?? null }; diff --git a/server/src/services/setup-token-reaper.test.ts b/server/src/services/setup-token-reaper.test.ts index e74ee4acd3c..1d7d1f6a2e9 100644 --- a/server/src/services/setup-token-reaper.test.ts +++ b/server/src/services/setup-token-reaper.test.ts @@ -124,6 +124,48 @@ describe("setup-token reaper", () => { expect(store.rows.size).toBe(0); }); + it("logs the class and code of a failed release without its message", async () => { + const store = createMemoryStore(); + store.seed({ sessionId: "orphan-3", leaseId: "lease-orphan-3", state: "failed" }); + const leases = createFakeLeases({ + releaseImpl: async () => { + throw Object.assign(new Error("invalid input syntax for type uuid: \"sk-ant-oat01-should-not-log\""), { name: "PostgresError", code: "22P02" }); + }, + }); + const lines: string[] = []; + const reaper = createSetupTokenReaper({ store, leases, now: () => NOW, log: (line) => lines.push(line) }); + + expect((await reaper.sweep()).failed).toBe(1); + + expect(lines).toEqual(["[paperclip] Setup-token reaper: a lease release failed; it stays retryable. Cause: PostgresError (22P02)."]); + }); + + it("logs the database error that a query wrapper carries as its cause", async () => { + const store = createMemoryStore(); + store.seed({ sessionId: "orphan-5", leaseId: "lease-orphan-5", state: "failed" }); + const database = Object.assign(new Error("invalid input syntax for type uuid: \"sk-ant-oat01-should-not-log\""), { name: "PostgresError", code: "22P02" }); + const wrapped = Object.assign(new Error("Failed query: select ... params: sk-ant-oat01-should-not-log", { cause: database }), { name: "DrizzleQueryError" }); + const leases = createFakeLeases({ releaseImpl: async () => { throw wrapped; } }); + const lines: string[] = []; + const reaper = createSetupTokenReaper({ store, leases, now: () => NOW, log: (line) => lines.push(line) }); + + await reaper.sweep(); + + expect(lines).toEqual(["[paperclip] Setup-token reaper: a lease release failed; it stays retryable. Cause: DrizzleQueryError > PostgresError (22P02)."]); + }); + + it("logs a generic cause for a thrown value that is not an error", async () => { + const store = createMemoryStore(); + store.seed({ sessionId: "orphan-4", leaseId: "lease-orphan-4", state: "failed" }); + const leases = createFakeLeases({ releaseImpl: async () => { throw "provider text"; } }); + const lines: string[] = []; + const reaper = createSetupTokenReaper({ store, leases, now: () => NOW, log: (line) => lines.push(line) }); + + await reaper.sweep(); + + expect(lines).toEqual(["[paperclip] Setup-token reaper: a lease release failed; it stays retryable. Cause: unknown error."]); + }); + it("reaps every reapable record in one sweep and stays idempotent on the next", async () => { const store = createMemoryStore(); store.seed({ sessionId: "orphan-a", leaseId: "lease-a", state: "failed" }); diff --git a/server/src/services/setup-token-session.ts b/server/src/services/setup-token-session.ts index 6de393af020..53dca34265f 100644 --- a/server/src/services/setup-token-session.ts +++ b/server/src/services/setup-token-session.ts @@ -320,6 +320,21 @@ export interface SetupTokenReapResult { failed: number; } +function releaseFailureLink(error: unknown): string { + const name = error instanceof Error && /^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(error.name) ? error.name : "unknown error"; + const code = error && typeof error === "object" && "code" in error ? (error as { code?: unknown }).code : undefined; + return typeof code === "string" && /^[A-Za-z0-9_.-]{1,64}$/.test(code) ? `${name} (${code})` : name; +} + +function releaseFailureCause(error: unknown): string { + const links: string[] = []; + for (let current = error, depth = 0; current !== undefined && current !== null && depth < 4; depth++) { + links.push(releaseFailureLink(current)); + current = current instanceof Error ? current.cause : undefined; + } + return links.join(" > "); +} + /** * The shared setup-token reap logic. It reads the durable store and releases any * lease whose session is terminal, past its deadline, or already consumed. It @@ -350,9 +365,9 @@ export async function reapSetupTokenLeases( adapterType: record.adapterType, }); released += 1; - } catch { + } catch (error) { failed += 1; - log("[paperclip] Setup-token reaper: a lease release failed; it stays retryable."); + log(`[paperclip] Setup-token reaper: a lease release failed; it stays retryable. Cause: ${releaseFailureCause(error)}.`); } } return { released, failed }; diff --git a/server/src/services/skill-package-store.ts b/server/src/services/skill-package-store.ts index 11c14f3765b..56b3cdaf104 100644 --- a/server/src/services/skill-package-store.ts +++ b/server/src/services/skill-package-store.ts @@ -514,7 +514,7 @@ export function skillPackageStore(db: Db, suppliedStorage?: StorageService, cach try { const archive = await writeSkillPackageArchive(archivePath, files, signal); await backend.putFile({ companyId, namespace: "skill-packages", objectKey: upload.archiveKey, originalFilename: "files.tar.gz", - contentType: "application/gzip", body: createReadStream(archivePath), byteSize: archive.bytes, sha256: archive.sha256, signal }); + contentType: "application/gzip", body: createReadStream(archivePath), byteSize: archive.bytes, sha256: archive.sha256, sourceFile: archivePath, signal }); await backend.putFile({ companyId, namespace: "skill-packages", objectKey: upload.manifestKey, originalFilename: "manifest.json", contentType: "application/json", body: manifestBuffer, signal }); const receipt: SkillPackageStorageReceipt = { format: "tar-gzip-v1", provider: backend.provider, ...(!restore ? { durable: true } : {}), diff --git a/server/src/services/tool-access-policy.ts b/server/src/services/tool-access-policy.ts index c1c10e4a610..6b0944c38ad 100644 --- a/server/src/services/tool-access-policy.ts +++ b/server/src/services/tool-access-policy.ts @@ -313,6 +313,12 @@ function trustRuleIsActive(policy: typeof toolPolicies.$inferSelect, now = new D return true; } +function invocationOpener(row: { actorType: string; actorId: string | null; policyExplanation: Record | null }) { + const recorded = row.policyExplanation?.sessionOpenedByUserId; + if (typeof recorded === "string" && recorded) return recorded; + return row.actorType === "user" && row.actorId ? row.actorId : null; +} + function sideEffectIdempotencyKey(ctx: ToolAccessContext, argumentsHash: string, version: 1 | 2 = 2): string { return `side_effect:${version === 2 ? "v2:" : ""}${sha256({ ...(version === 2 ? { actorType: ctx.actorType, actorId: ctx.actorId, agentId: ctx.agentId } : {}), @@ -1868,8 +1874,12 @@ export function toolAccessPolicyService(db: Pick conflict( + "An earlier operation with this request cannot be attributed to the person who opened this session. Reconcile it before retrying; use a new explicit idempotency key only for an intentional new operation.", + { reasonCode: "legacy_tool_idempotency_unverifiable" }, + ); + if (sessionOpener && unscopedIdempotencyKey) { + const [unscoped] = await db.select().from(toolInvocations).where(and( + eq(toolInvocations.companyId, input.companyId), + eq(toolInvocations.idempotencyKey, unscopedIdempotencyKey), + )); + if (unscoped) { + const opener = invocationOpener(unscoped); + if (opener === sessionOpener) return { invocation: unscoped, replayed: true, actionRequest: null }; + if (opener === null) throw unattributedEarlierOperation(); + } + } if (input.request.sideEffecting && input.request.idempotencyKey == null) { // Before complete request identities, default keys used shortened and // redacted preview hashes. Check both historical key-redaction variants @@ -1891,7 +1916,11 @@ export function toolAccessPolicyService(db: Pick = []; let quarantinedCount = 0; + const releasedNames = new Set(); const sourceTemplateKey = typeof asRecord(connection.config).sourceTemplateKey === "string" ? String(asRecord(connection.config).sourceTemplateKey) @@ -232,8 +234,11 @@ export function createToolCatalogPublication(db: Db, { now, audit, getConnection const changed = existing && (existing.versionHash !== hash || existing.schemaHash !== schemaHash); + const paperclipDefined = paperclipDefinedTool(connection, descriptor.name) !== null; + if (paperclipDefined && existing?.status === "quarantined") releasedNames.add(descriptor.name); const shouldQuarantine = quarantineOnRefresh && + !paperclipDefined && (!existing || changed) && existing?.status !== "disabled" && (!safeDefault || riskLevel !== "read" || nativeProvider); @@ -247,7 +252,7 @@ export function createToolCatalogPublication(db: Db, { now, audit, getConnection ? "quarantined" : existing?.status === "disabled" && existing.quarantineReason !== "mcp_tool_removed" ? "disabled" - : quarantineOnRefresh && existing?.status === "quarantined" + : quarantineOnRefresh && existing?.status === "quarantined" && !paperclipDefined ? "quarantined" : "active"; if (shouldQuarantine && !providerPermanentlyBlocked) quarantinedCount += 1; @@ -285,7 +290,7 @@ export function createToolCatalogPublication(db: Db, { now, audit, getConnection versionHash: sql`excluded.version_hash`, schemaHash: sql`excluded.schema_hash`, lastSeenAt: sql`excluded.last_seen_at`, quarantinedAt: sql`excluded.quarantined_at`, quarantineReason: sql`excluded.quarantine_reason`, updatedAt: sql`excluded.updated_at`, } }).returning(); - for (const row of rows) if (!existingNonQuarantinedNames.has(row.name)) newCatalogEntryIds.add(row.id); + for (const row of rows) if (!existingNonQuarantinedNames.has(row.name) && !releasedNames.has(row.name)) newCatalogEntryIds.add(row.id); return rows; })); } diff --git a/server/src/services/tool-access/connections/content-cleaning.ts b/server/src/services/tool-access/connections/content-cleaning.ts new file mode 100644 index 00000000000..2b271e6bcb3 --- /dev/null +++ b/server/src/services/tool-access/connections/content-cleaning.ts @@ -0,0 +1,42 @@ +export const RESULT_TEXT_KEYS = ["summary", "result", "message", "text", "output", "content", "body"]; + +export function withoutActionResults(value: unknown, actionRequestIds: ReadonlySet): { value: unknown; changed: boolean } { + let changed = false; + const walk = (node: unknown): unknown => { + if (Array.isArray(node)) return node.map(walk); + if (!node || typeof node !== "object") return node; + const record = node as Record; + const next: Record = {}; + for (const [key, entry] of Object.entries(record)) next[key] = walk(entry); + if (typeof record.actionRequestId === "string" && actionRequestIds.has(record.actionRequestId) + && typeof record.resultSummary === "string" && record.resultSummary !== "") { + next.resultSummary = ""; + changed = true; + } + return next; + }; + const result = walk(value); + return { value: changed ? result : value, changed }; +} + +export function withoutResultText(value: Record | null): { value: Record | null; changed: boolean } { + if (!value || typeof value !== "object") return { value, changed: false }; + let changed = false; + const walk = (node: unknown, topLevel: boolean): unknown => { + if (Array.isArray(node)) return node.map((entry) => walk(entry, false)); + if (!node || typeof node !== "object") return node; + const next: Record = {}; + for (const [key, entry] of Object.entries(node as Record)) { + if (RESULT_TEXT_KEYS.includes(key) && typeof entry === "string") { + if (entry !== "") changed = true; + if (!topLevel) next[key] = ""; + else if (entry === "") next[key] = entry; + continue; + } + next[key] = walk(entry, false); + } + return next; + }; + const next = walk(value, true) as Record; + return { value: changed ? next : value, changed }; +} diff --git a/server/src/services/tool-access/connections/content-deletion.ts b/server/src/services/tool-access/connections/content-deletion.ts index 6a9226ba223..7e22903babf 100644 --- a/server/src/services/tool-access/connections/content-deletion.ts +++ b/server/src/services/tool-access/connections/content-deletion.ts @@ -26,6 +26,7 @@ import { logActivity, type LogActivityInput } from "../../activity-log.js"; import { getStorageService } from "../../../storage/index.js"; import type { StorageService } from "../../../storage/types.js"; import { createStoredObjectDeletion } from "./stored-object-deletion.js"; +import { RESULT_TEXT_KEYS, withoutActionResults, withoutResultText } from "./content-cleaning.js"; const BATCH_SIZE = 200; const EVENT_BATCH_SIZE = 1000; @@ -35,7 +36,6 @@ const SETTLED_RUN_STATUSES = ["succeeded", "failed", "cancelled", "timed_out", " const UNSETTLED_INVOCATION_STATUSES = ["pending", "authorized", "awaiting_approval", "executing"]; const UNSETTLED_ACTION_REQUEST_STATUSES = ["pending", "approved", "executing"]; const UNSETTLED_WAKE_STATUSES = ["queued", "deferred_issue_execution", "claimed"]; -const RESULT_TEXT_KEYS = ["summary", "result", "message", "text", "output", "content", "body"]; const STRUCTURAL_EVENT_TYPES = [ "lifecycle", "run.terminal", @@ -62,6 +62,7 @@ type RunInProgress = { id: string; eventAfterId: number; changed: boolean; stage type Progress = { phase: Phase; + waiting: boolean; cursor: { createdAt: string; id: string } | null; runCursor: string | null; currentRun: RunInProgress | null; @@ -77,7 +78,7 @@ type JobActivity = Pick = { load(id: string): Promise; scope(row: Row): Scope; - waitMs(row: Row, progress: Progress): number | null; + waitMs(row: Row, open: number): number | null; save(tx: Db, row: Row, progress: Progress, waitMs: number | null): Promise; finish(tx: Db, row: Row, now: Date): Promise; activity(row: Row, counts: ToolConnectionContentDeletionCounts): JobActivity | null; @@ -92,10 +93,11 @@ type Scope = { runIds: string[]; invocationIds: string[]; eventIds: string[]; + createdAfter: Date | null; }; function connectionScope(connection: { id: string; companyId: string }, cutoff: Date): Scope { - return { companyId: connection.companyId, cutoff, connectionId: connection.id, issueId: null, runIds: [], invocationIds: [], eventIds: [] }; + return { companyId: connection.companyId, cutoff, connectionId: connection.id, issueId: null, runIds: [], invocationIds: [], eventIds: [], createdAfter: null }; } export function uuidList(values: string[]): SQL { @@ -119,6 +121,11 @@ function invocationsInScopeSql(scope: Scope) { return callsInScopeSql(scope, { connectionId: sql`${toolInvocations.connectionId}`, runId: sql`${toolInvocations.runId}`, invocationId: sql`${toolInvocations.id}` }); } +function wakeCarriesResultsSql(requestIds: SQL): SQL { + return sql`(${agentWakeupRequests.payload}->'toolActionRequestIds' ?| ${requestIds} + or ${agentWakeupRequests.payload}->'_paperclipWakeContext'->'toolActionRequestIds' ?| ${requestIds})`; +} + function savedResultSql(runId: SQL): SQL { return sql`exists (select 1 from ${runnerApiResponseReservations} capture where capture.run_id = ${runId} and capture.asset_id is not null @@ -139,7 +146,8 @@ function readProgress(row: { progress: unknown }): Progress { const raw = row.progress as Partial; const counts = { ...emptyContentDeletionCounts(), ...(raw.counts ?? {}) }; const phase = PHASES.includes(raw.phase as Phase) ? raw.phase as Phase : "invocations"; - return { phase, cursor: raw.cursor ?? null, runCursor: raw.runCursor ?? null, currentRun: raw.currentRun ?? null, pendingRuns: raw.pendingRuns ?? [], counts }; + return { phase, waiting: phase === "done" && raw.waiting === true, cursor: raw.cursor ?? null, runCursor: raw.runCursor ?? null, + currentRun: raw.currentRun ?? null, pendingRuns: raw.pendingRuns ?? [], counts }; } function nextPhase(phase: Phase): Phase { @@ -205,47 +213,6 @@ function clearedSummary(column: SQL, deletedAt: string): SQL { else ${column} || jsonb_build_object('summary', '', 'contentDeletedAt', ${deletedAt}::text) end`; } -export function withoutActionResults(value: unknown, actionRequestIds: ReadonlySet): { value: unknown; changed: boolean } { - let changed = false; - const walk = (node: unknown): unknown => { - if (Array.isArray(node)) return node.map(walk); - if (!node || typeof node !== "object") return node; - const record = node as Record; - const next: Record = {}; - for (const [key, entry] of Object.entries(record)) next[key] = walk(entry); - if (typeof record.actionRequestId === "string" && actionRequestIds.has(record.actionRequestId) - && typeof record.resultSummary === "string" && record.resultSummary !== "") { - next.resultSummary = ""; - changed = true; - } - return next; - }; - const result = walk(value); - return { value: changed ? result : value, changed }; -} - -export function withoutResultText(value: Record | null): { value: Record | null; changed: boolean } { - if (!value || typeof value !== "object") return { value, changed: false }; - let changed = false; - const walk = (node: unknown, topLevel: boolean): unknown => { - if (Array.isArray(node)) return node.map((entry) => walk(entry, false)); - if (!node || typeof node !== "object") return node; - const next: Record = {}; - for (const [key, entry] of Object.entries(node as Record)) { - if (RESULT_TEXT_KEYS.includes(key) && typeof entry === "string") { - if (entry !== "") changed = true; - if (!topLevel) next[key] = ""; - else if (entry === "") next[key] = entry; - continue; - } - next[key] = walk(entry, false); - } - return next; - }; - const next = walk(value, true) as Record; - return { value: changed ? next : value, changed }; -} - function toDeletion(row: DeletionRow): ToolConnectionContentDeletion { return { id: row.id, @@ -258,7 +225,7 @@ function toDeletion(row: DeletionRow): ToolConnectionContentDeletion { } export function initialContentDeletionProgress(): Progress { - return { phase: "invocations", cursor: null, runCursor: null, currentRun: null, pendingRuns: [], counts: emptyContentDeletionCounts() }; + return { phase: "invocations", waiting: false, cursor: null, runCursor: null, currentRun: null, pendingRuns: [], counts: emptyContentDeletionCounts() }; } export function createConnectionContentDeletion(db: Db, deps: { @@ -368,6 +335,15 @@ export function createConnectionContentDeletion(db: Db, deps: { return new Set(rows.map((row) => row.id)); } + async function openRunIds(tx: Db, runIds: string[]) { + if (runIds.length === 0) return new Set(); + const rows = await tx + .select({ id: heartbeatRuns.id }) + .from(heartbeatRuns) + .where(and(inArray(heartbeatRuns.id, runIds), sql`not ${settledRunSql(sql`${heartbeatRuns.id}`)}`)); + return new Set(rows.map((row) => row.id)); + } + async function clearDeliveredResults(tx: Db, scope: Scope, progress: Progress, requests: Array<{ id: string; issueId: string | null }>) { const issueIds = scope.issueId ? [scope.issueId] : [...new Set(requests.flatMap((row) => row.issueId ? [row.issueId] : []))]; if (issueIds.length === 0) return []; @@ -399,8 +375,7 @@ export function createConnectionContentDeletion(db: Db, deps: { .where(and( eq(agentWakeupRequests.companyId, scope.companyId), inArray(sql`${agentWakeupRequests.payload}->>'issueId'`, issueIds), - sql`(${agentWakeupRequests.payload}->'toolActionRequestIds' ?| ${idList} - or ${agentWakeupRequests.payload}->'_paperclipWakeContext'->'toolActionRequestIds' ?| ${idList})`, + wakeCarriesResultsSql(idList), )) .for("update"); for (const wake of wakes) { @@ -549,6 +524,7 @@ export function createConnectionContentDeletion(db: Db, deps: { .where(and( eq(toolAccessAuditEvents.companyId, scope.companyId), cutoffSql(sql`${toolAccessAuditEvents.createdAt}`, scope), + scope.createdAfter ? sql`${toolAccessAuditEvents.createdAt} >= ${scope.createdAfter.toISOString()}::timestamptz` : undefined, cursor ? sql`(${toolAccessAuditEvents.createdAt}, ${toolAccessAuditEvents.id}) > (${cursor.createdAt}::timestamptz, ${cursor.id}::uuid)` : undefined, scope.connectionId ? eq(toolAccessAuditEvents.connectionId, scope.connectionId) @@ -561,8 +537,8 @@ export function createConnectionContentDeletion(db: Db, deps: { if (page.length === 0) return true; const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; const runIds = [...new Set(page.flatMap((row) => row.runId && uuid.test(row.runId) ? [row.runId] : []))]; - const settledRuns = await settledRunIds(tx, runIds); - const ids = page.filter((row) => !row.runId || !uuid.test(row.runId) || settledRuns.has(row.runId)).map((row) => row.id); + const openRuns = await openRunIds(tx, runIds); + const ids = page.filter((row) => !row.runId || !uuid.test(row.runId) || !openRuns.has(row.runId)).map((row) => row.id); progress.counts.itemsInProgress += page.length - ids.length; if (ids.length > 0) { const cleared = await tx @@ -774,7 +750,7 @@ export function createConnectionContentDeletion(db: Db, deps: { eq(toolConnectionContentDeletions.id, row.id), eq(toolConnectionContentDeletions.status, "pending"), eq(toolConnectionContentDeletions.updatedAt, row.updatedAt), - sql`${toolConnectionContentDeletions.progress}->>'phase' = 'done'`, + sql`${toolConnectionContentDeletions.progress}->>'phase' = 'done' and coalesce(${toolConnectionContentDeletions.progress}->>'waiting', 'false') <> 'true'`, )) .returning())[0], activity: (row, counts) => ({ action: "tool_connection.content_deleted", entityType: "tool_connection", entityId: row.connectionId, details: { ...counts } }), @@ -789,10 +765,11 @@ export function createConnectionContentDeletion(db: Db, deps: { const issueJobs: JobStore = { load: async (id) => (await db.select().from(issueConnectionContentDeletions).where(eq(issueConnectionContentDeletions.id, id)))[0], scope: (row) => ({ companyId: row.companyId, cutoff: null, connectionId: null, issueId: row.issueId, - runIds: row.scope.runIds ?? [], invocationIds: row.scope.invocationIds ?? [], eventIds: row.scope.eventIds ?? [] }), - waitMs: (row, progress) => { + runIds: row.scope.runIds ?? [], invocationIds: row.scope.invocationIds ?? [], eventIds: row.scope.eventIds ?? [], + createdAfter: row.scope.createdAfter ? new Date(row.scope.createdAfter) : null }), + waitMs: (row, open) => { const waitedMs = Date.now() - row.requestedAt.getTime(); - if (waitedMs >= ISSUE_WAIT_LIMIT_MS || progress.counts.itemsInProgress + progress.counts.runsInProgress === 0) return null; + if (waitedMs >= ISSUE_WAIT_LIMIT_MS || open === 0) return null; return Math.min(Math.max(ISSUE_WAIT_MS, waitedMs / 10), ISSUE_WAIT_MAX_MS); }, save: async (tx, row, progress, waitMs) => (await tx @@ -815,7 +792,7 @@ export function createConnectionContentDeletion(db: Db, deps: { eq(issueConnectionContentDeletions.id, row.id), eq(issueConnectionContentDeletions.status, "pending"), eq(issueConnectionContentDeletions.updatedAt, row.updatedAt), - sql`${issueConnectionContentDeletions.progress}->>'phase' = 'done'`, + sql`${issueConnectionContentDeletions.progress}->>'phase' = 'done' and coalesce(${issueConnectionContentDeletions.progress}->>'waiting', 'false') <> 'true'`, )) .returning())[0], activity: (row, counts) => { @@ -833,6 +810,26 @@ export function createConnectionContentDeletion(db: Db, deps: { }, }; + async function countOpenWork(tx: Db, scope: Scope) { + const requestIds = sql`array(select ${toolActionRequests.id}::text from ${toolActionRequests} + join ${toolInvocations} on ${toolInvocations.id} = ${toolActionRequests.invocationId} + where ${toolActionRequests.companyId} = ${scope.companyId} and ${invocationsInScopeSql(scope)})`; + const [open] = await tx.execute<{ count: number }>(sql`select ( + (select count(*) from ${heartbeatRuns} where ${heartbeatRuns.companyId} = ${scope.companyId} + and ${heartbeatRuns.id} = any(${uuidList(scope.runIds)}) and not ${settledRunSql(sql`${heartbeatRuns.id}`)}) + + (select count(*) from ${toolInvocations} where ${toolInvocations.companyId} = ${scope.companyId} + and ${invocationsInScopeSql(scope)} and ${toolInvocations.status} in (${listSql(UNSETTLED_INVOCATION_STATUSES)})) + + (select count(*) from ${toolActionRequests} join ${toolInvocations} on ${toolInvocations.id} = ${toolActionRequests.invocationId} + where ${toolActionRequests.companyId} = ${scope.companyId} and ${invocationsInScopeSql(scope)} + and ${toolActionRequests.status} in (${listSql(UNSETTLED_ACTION_REQUEST_STATUSES)})) + + (select count(*) from ${agentWakeupRequests} where ${agentWakeupRequests.companyId} = ${scope.companyId} + and ${agentWakeupRequests.payload}->>'issueId' = ${scope.issueId}::text + and ${agentWakeupRequests.status} in (${listSql(UNSETTLED_WAKE_STATUSES)}) + and ${wakeCarriesResultsSql(requestIds)}) + )::int as count`); + return Number(open?.count ?? 0); + } + async function countOpenRunsWithoutTools(tx: Db, scope: Scope) { if (scope.runIds.length === 0) return 0; const [open] = await tx @@ -856,6 +853,18 @@ export function createConnectionContentDeletion(db: Db, deps: { const removedResults = await removeSavedResults(scope.companyId, progress.currentRun.id, signal); if (removedLog || removedResults) progress.currentRun.changed = true; } + if (progress.waiting) { + return db.transaction(async (rawTx) => { + const tx = rawTx as unknown as Db; + const waitMs = store.waitMs(job, await countOpenWork(tx, scope)); + if (waitMs === null) { + Object.assign(progress, { ...initialContentDeletionProgress(), counts: { ...progress.counts, itemsInProgress: 0, runsInProgress: 0 } }); + } + const saved = await store.save(tx, job, progress, waitMs); + if (!saved) throw new ProgressConflict(); + return { row: saved, waiting: waitMs !== null }; + }); + } return db.transaction(async (rawTx) => { const tx = rawTx as unknown as Db; const done = progress.phase === "invocations" ? await invocationsStep(tx, scope, progress, deletedAt) @@ -872,10 +881,8 @@ export function createConnectionContentDeletion(db: Db, deps: { progress.pendingRuns = []; if (progress.phase === "done" && scope.issueId) progress.counts.runsInProgress += await countOpenRunsWithoutTools(tx, scope); } - const waitMs = progress.phase === "done" ? store.waitMs(job, progress) : null; - if (waitMs !== null) { - Object.assign(progress, { ...initialContentDeletionProgress(), counts: { ...progress.counts, itemsInProgress: 0, runsInProgress: 0 } }); - } + const waitMs = progress.phase === "done" ? store.waitMs(job, progress.counts.itemsInProgress + progress.counts.runsInProgress) : null; + progress.waiting = waitMs !== null; const saved = await store.save(tx, job, progress, waitMs); if (!saved) throw new ProgressConflict(); return { row: saved, waiting: waitMs !== null }; @@ -908,7 +915,8 @@ export function createConnectionContentDeletion(db: Db, deps: { let job: Row = loaded; try { while (!signal.aborted) { - if (readProgress(job).phase === "done") return await complete(store, job); + const current = readProgress(job); + if (current.phase === "done" && !current.waiting) return await complete(store, job); const next: { row: Row; waiting: boolean } = await step(store, job, signal); job = next.row; if (next.waiting || Date.now() - startedAt >= budgetMs) return job; diff --git a/server/src/services/tool-access/connections/issue-content-deletion.ts b/server/src/services/tool-access/connections/issue-content-deletion.ts index 15595954b9b..77948a86bce 100644 --- a/server/src/services/tool-access/connections/issue-content-deletion.ts +++ b/server/src/services/tool-access/connections/issue-content-deletion.ts @@ -1,5 +1,5 @@ import { and, eq, sql } from "drizzle-orm"; -import { heartbeatRuns, issueConnectionContentDeletions, toolCallEvents, toolInvocations, type Db } from "@paperclipai/db"; +import { heartbeatRuns, issueConnectionContentDeletions, issues, toolAccessAuditEvents, toolCallEvents, toolInvocations, type Db } from "@paperclipai/db"; import { initialContentDeletionProgress, runUsedToolsSql, settledRunSql, uuidList } from "./content-deletion.js"; import { requestIssueAttachmentObjectDeletion } from "./stored-object-deletion.js"; @@ -8,6 +8,7 @@ export async function requestIssueConnectionContentDeletion( input: { companyId: string; issueId: string; actorAgentId?: string | null }, ) { await requestIssueAttachmentObjectDeletion(tx, input); + const [issue] = await tx.select({ createdAt: issues.createdAt }).from(issues).where(eq(issues.id, input.issueId)); const runs = await tx .select({ id: heartbeatRuns.id }) .from(heartbeatRuns) @@ -36,7 +37,20 @@ export async function requestIssueConnectionContentDeletion( sql`(${toolCallEvents.invocationId} is null or not (${toolCallEvents.invocationId} = any(${uuidList(invocationIds)})))`, )); const eventIds = events.map((row) => row.id); - if (runIds.length === 0 && invocationIds.length === 0 && eventIds.length === 0) return null; + if (runIds.length === 0 && invocationIds.length === 0 && eventIds.length === 0) { + const [audit] = await tx + .select({ id: toolAccessAuditEvents.id }) + .from(toolAccessAuditEvents) + .where(and( + eq(toolAccessAuditEvents.companyId, input.companyId), + sql`${toolAccessAuditEvents.createdAt} >= (select created_at from issues where id = ${input.issueId})`, + sql`${toolAccessAuditEvents.details}->>'issueId' = ${input.issueId}::text`, + sql`jsonb_typeof(${toolAccessAuditEvents.details}->'argumentsSummary') = 'object'`, + sql`${toolAccessAuditEvents.details}->'argumentsSummary'->>'contentDeletedAt' is null`, + )) + .limit(1); + if (!audit) return null; + } const now = new Date(); const [created] = await tx .insert(issueConnectionContentDeletions) @@ -47,7 +61,7 @@ export async function requestIssueConnectionContentDeletion( updatedAt: now, companyId: input.companyId, issueId: input.issueId, - scope: { runIds, invocationIds, eventIds }, + scope: { runIds, invocationIds, eventIds, createdAfter: issue?.createdAt.toISOString() ?? null }, requestedByActorType: input.actorAgentId ? "agent" : "system", requestedByActorId: input.actorAgentId ?? null, progress: initialContentDeletionProgress() as unknown as Record, diff --git a/server/src/services/tool-access/oauth/client-registration.ts b/server/src/services/tool-access/oauth/client-registration.ts index 92710807205..8850e04423c 100644 --- a/server/src/services/tool-access/oauth/client-registration.ts +++ b/server/src/services/tool-access/oauth/client-registration.ts @@ -13,7 +13,7 @@ import { type RemoteHttpEndpointLookup } from "../../remote-http-endpoint-guard. import type { OAuthCredentialStore } from "./credential-store.js"; import { singleFlight } from "../single-flight.js"; -import { configuredOAuthClientForConnection, oauthSecretRef } from "./client-settings.js"; +import { configuredOAuthClientForConnection, manualOAuthClientRequiredError, oauthSecretRef, refusedDeploymentClientError } from "./client-settings.js"; const oauthRegistrationFlights = new Map>(); type RegistrationDependencies = { @@ -421,6 +421,7 @@ function canRegisterOAuthClientDynamically( const configured = configuredOAuthClientForConnection( input.connection, input.endpoints.provider, + input.endpoints.tokenUrl, ); if (configured.clientId) { return { @@ -462,6 +463,7 @@ function canRegisterOAuthClientDynamically( client: await oauthClientForConnection( bound, input.endpoints.provider, + input.endpoints.tokenUrl, input.actor, ), source: storedOAuthClientRegistrationSource(bound), @@ -488,6 +490,9 @@ function canRegisterOAuthClientDynamically( input.galleryEntry, ) ) { + if (refusedDeploymentClientError(input.endpoints.provider)) { + throw manualOAuthClientRequiredError(input.endpoints.provider, ""); + } throw unprocessable( `OAuth client id is not configured for ${input.endpoints.provider}`, { @@ -511,6 +516,7 @@ function canRegisterOAuthClientDynamically( const latestConfigured = configuredOAuthClientForConnection( latest, input.endpoints.provider, + input.endpoints.tokenUrl, ); if (latestConfigured.clientId) { return { @@ -537,6 +543,7 @@ function canRegisterOAuthClientDynamically( client: await oauthClientForConnection( bound, input.endpoints.provider, + input.endpoints.tokenUrl, input.actor, ), source: storedOAuthClientRegistrationSource(bound), @@ -557,6 +564,7 @@ function canRegisterOAuthClientDynamically( client: await oauthClientForConnection( adopted, input.endpoints.provider, + input.endpoints.tokenUrl, input.actor, ), source: "cimd" as const, @@ -564,9 +572,9 @@ function canRegisterOAuthClientDynamically( } // 4. Dynamic client registration. if (!input.endpoints.registrationUrl) { - throw unprocessable( + throw manualOAuthClientRequiredError( + input.endpoints.provider, "This server needs sign-in details you create yourself. Register Paperclip with the provider, then add the client ID and secret it gives you.", - { code: "oauth_manual_client_required" }, ); } const registered = await registerOAuthClient({ @@ -580,6 +588,7 @@ function canRegisterOAuthClientDynamically( client: await oauthClientForConnection( registered, input.endpoints.provider, + input.endpoints.tokenUrl, input.actor, ), source: "dcr" as const, diff --git a/server/src/services/tool-access/oauth/client-settings.test.ts b/server/src/services/tool-access/oauth/client-settings.test.ts new file mode 100644 index 00000000000..0998a32d556 --- /dev/null +++ b/server/src/services/tool-access/oauth/client-settings.test.ts @@ -0,0 +1,150 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { toolConnections } from "@paperclipai/db"; +import { APP_DEFINITIONS } from "@paperclipai/shared"; +import { configuredOAuthClientForConnection } from "./client-settings.js"; + +type Connection = typeof toolConnections.$inferSelect; + +function connection(config: Record): Connection { + return { + id: "connection-1", + companyId: "company-1", + transport: "mcp_remote", + config, + transportConfig: {}, + credentialSecretRefs: [], + } as unknown as Connection; +} + +const slack = (oauth: Record = {}) => + connection({ sourceTemplateKey: "slack", connectionMethodKey: "mcp-oauth", oauth }); +const generic = (oauth: Record = {}) => + connection({ url: "https://mcp.example.test/mcp", oauth }); + +afterEach(() => { + vi.unstubAllEnvs(); +}); + +describe("instance OAuth clients", () => { + it("uses the instance client only at the token endpoint its app definition fixes", () => { + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_ID", "instance-slack-id"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_SECRET", "instance-slack-secret"); + + expect(configuredOAuthClientForConnection(slack(), "slack", "https://slack.com/api/oauth.v2.access")).toMatchObject({ + clientId: "instance-slack-id", + clientSecret: "instance-slack-secret", + }); + }); + + it.each([ + ["a different host", "https://attacker.example/token"], + ["a lookalike path on the vendor host", "https://slack.com/api/oauth.v2.access/../../collect"], + ["plain http on the vendor host", "http://slack.com/api/oauth.v2.access"], + ["a vendor subdomain", "https://evil.slack.com/api/oauth.v2.access"], + ["no token endpoint", null], + ])("never returns the instance secret for %s", (_label, tokenUrl) => { + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_ID", "instance-slack-id"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_SECRET", "instance-slack-secret"); + + const client = configuredOAuthClientForConnection(slack({ tokenUrl }), "slack", tokenUrl); + expect(client.clientId).toBeNull(); + expect(client.clientSecret).toBeNull(); + }); + + it("never gives a custom connection the instance client of a provider it names", () => { + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_ID", "instance-slack-id"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_SECRET", "instance-slack-secret"); + + const client = configuredOAuthClientForConnection( + generic({ provider: "slack", tokenUrl: "https://attacker.example/token" }), + "slack", + "https://attacker.example/token", + ); + expect(client.clientId).toBeNull(); + expect(client.clientSecret).toBeNull(); + }); + + it("never gives a custom connection the unsuffixed instance client", () => { + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_ID", "instance-generic-id"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_SECRET", "instance-generic-secret"); + + const client = configuredOAuthClientForConnection(generic(), "mcp_example_test", "https://mcp.example.test/token"); + expect(client.clientId).toBeNull(); + expect(client.clientSecret).toBeNull(); + }); + + it("never gives a custom server a host-named instance client, even at that host", () => { + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_MCP_EXAMPLE_TEST_CLIENT_ID", "instance-host-id"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_MCP_EXAMPLE_TEST_CLIENT_SECRET", "instance-host-secret"); + + expect(configuredOAuthClientForConnection(generic(), "mcp_example_test", "https://mcp.example.test/oauth/token").clientId).toBeNull(); + const lookalike = connection({ url: "https://mcp-example.test/mcp", oauth: {} }); + expect(configuredOAuthClientForConnection(lookalike, "mcp_example_test", "https://mcp-example.test/oauth/token").clientId).toBeNull(); + }); + + it.each(["", " ", " slack"])("never treats the gallery marker %j as an app definition", (marker) => { + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_ID", "instance-generic-id"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_SECRET", "instance-generic-secret"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_ID", "instance-slack-id"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_SECRET", "instance-slack-secret"); + const marked = connection({ sourceTemplateKey: marker, url: "https://attacker.example/mcp", oauth: {} }); + + for (const provider of [marker, "slack", "attacker_example"]) { + const client = configuredOAuthClientForConnection(marked, provider, "https://attacker.example/token"); + expect(client.clientId).toBeNull(); + expect(client.clientSecret).toBeNull(); + } + expect(configuredOAuthClientForConnection(marked, "slack", "https://slack.com/api/oauth.v2.access").clientId).toBeNull(); + }); + + it("never uses one app's instance client for a connection that claims another provider", () => { + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_GMAIL_CLIENT_ID", "instance-gmail-id"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_GMAIL_CLIENT_SECRET", "instance-gmail-secret"); + + const client = configuredOAuthClientForConnection( + slack({ provider: "gmail" }), + "gmail", + "https://oauth2.googleapis.com/token", + ); + expect(client.clientId).toBeNull(); + expect(client.clientSecret).toBeNull(); + }); + + it("allows a discovered token endpoint only on a host the definition fixes when it fixes no token endpoint", () => { + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_NOTION_CLIENT_ID", "instance-notion-id"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_NOTION_CLIENT_SECRET", "instance-notion-secret"); + const notion = connection({ sourceTemplateKey: "notion", connectionMethodKey: "mcp-oauth" }); + + expect(configuredOAuthClientForConnection(notion, "notion", "https://mcp.notion.com/token").clientId).toBe("instance-notion-id"); + for (const tokenUrl of [ + "https://api.notion.com/v1/oauth/token", + "https://evil.notion.com/token", + "https://mcp.notion.com:8443/token", + "https://attacker.example/token", + ]) { + expect(configuredOAuthClientForConnection(notion, "notion", tokenUrl).clientId).toBeNull(); + } + }); + + it.each([ + ["asana", "mcp-own-oauth", "https://app.asana.com/-/oauth_token"], + ["railway", "mcp-oauth", "https://backboard.railway.com/oauth/token"], + ])("allows the token endpoint that the %s definition pins", (slug, methodKey, tokenUrl) => { + vi.stubEnv(`PAPERCLIP_TOOL_OAUTH_${slug.toUpperCase()}_CLIENT_ID`, "instance-id"); + vi.stubEnv(`PAPERCLIP_TOOL_OAUTH_${slug.toUpperCase()}_CLIENT_SECRET`, "instance-secret"); + const pinned = connection({ sourceTemplateKey: slug, connectionMethodKey: methodKey }); + + expect(configuredOAuthClientForConnection(pinned, slug, tokenUrl).clientId).toBe("instance-id"); + expect(configuredOAuthClientForConnection(pinned, slug, "https://attacker.example/token").clientId).toBeNull(); + }); + + it("makes every customer OAuth method pin its token endpoint or name its same-host fallback", () => { + const sameHostFallback = new Set(["box:mcp-own-oauth", "notion:mcp-oauth", "posthog:mcp-oauth", "sentry:mcp-oauth", "xero:mcp-own-oauth"]); + const noFixedEndpoint = new Set(["oauth-generic:oauth"]); + const unpinned = APP_DEFINITIONS.flatMap((app) => app.methods + .filter((method) => method.auth === "oauth" && !method.oauthStrategy && method.ownershipModes.includes("customer") + && method.purpose !== "ai" && method.transport !== "runtime_auth" && !method.defaults?.tokenEndpoint) + .map((method) => `${app.slug}:${method.key}`)); + expect(unpinned.sort()).toEqual([...sameHostFallback, ...noFixedEndpoint].sort()); + }); +}); diff --git a/server/src/services/tool-access/oauth/client-settings.ts b/server/src/services/tool-access/oauth/client-settings.ts index b9f5f2aab69..3a7ed566909 100644 --- a/server/src/services/tool-access/oauth/client-settings.ts +++ b/server/src/services/tool-access/oauth/client-settings.ts @@ -37,9 +37,65 @@ export function oauthClientConfig(provider: string) { }; } +function httpsUrl(value: string | null | undefined): URL | null { + if (!value) return null; + try { + const url = new URL(value); + return url.protocol === "https:" && !url.username && !url.password ? url : null; + } catch { + return null; + } +} + +function instanceClientTokenUrlAllowed( + connection: typeof toolConnections.$inferSelect, + provider: string, + tokenUrl: string | null | undefined, +): boolean { + const target = httpsUrl(tokenUrl); + if (!target) return false; + const sourceTemplateKey = connection.config.sourceTemplateKey; + if (typeof sourceTemplateKey !== "string" || !sourceTemplateKey || provider !== sourceTemplateKey) return false; + const app = getConnectableAppDefinition(sourceTemplateKey); + if (!app) return false; + let method: ReturnType; + try { + method = connectionMethodForConnection(app, connection); + } catch { + return false; + } + if (method.auth !== "oauth" || !method.ownershipModes.includes("customer")) return false; + const defaults = method.defaults ?? {}; + if (defaults.tokenEndpoint) { + return httpsUrl(defaults.tokenEndpoint)?.href === target.href; + } + const fixedHosts = [defaults.serverUrl, defaults.discoveryUrl, defaults.metadataUrl, defaults.authorizationEndpoint] + .map((value) => httpsUrl(value)) + .filter((url): url is URL => url !== null) + .map((url) => url.host.toLowerCase()); + return fixedHosts.includes(target.host.toLowerCase()); +} + +const REFUSED_DEPLOYMENT_CLIENT_MESSAGE = + "The sign-in app set up for this Paperclip server can only be used with the app it was set up for. Add a client ID and secret for this server to the connection, then sign in again."; + +export function refusedDeploymentClientError(provider: string) { + if (!oauthClientConfig(provider).clientId) return null; + return unprocessable(REFUSED_DEPLOYMENT_CLIENT_MESSAGE, { code: "oauth_instance_client_endpoint_mismatch" }); +} + +export function manualOAuthClientRequiredError(provider: string, message: string) { + const refused = Boolean(oauthClientConfig(provider).clientId); + return unprocessable(refused ? REFUSED_DEPLOYMENT_CLIENT_MESSAGE : message, { + code: "oauth_manual_client_required", + ...(refused ? { reason: REFUSED_DEPLOYMENT_CLIENT_MESSAGE } : {}), + }); +} + export function configuredOAuthClientForConnection( connection: typeof toolConnections.$inferSelect, provider: string, + tokenUrl: string | null | undefined, ) { if (isSmokeLabOAuthFixture(connection) && provider === "smoke_lab") { return { @@ -49,7 +105,10 @@ export function configuredOAuthClientForConnection( clientSecret: null, }; } - return oauthClientConfig(provider); + const configured = oauthClientConfig(provider); + return instanceClientTokenUrlAllowed(connection, provider, tokenUrl) + ? configured + : { ...configured, clientId: null, clientSecret: null }; } export function credentialScope( diff --git a/server/src/services/tool-access/oauth/connection-refresh.ts b/server/src/services/tool-access/oauth/connection-refresh.ts index c67de010179..c646940da72 100644 --- a/server/src/services/tool-access/oauth/connection-refresh.ts +++ b/server/src/services/tool-access/oauth/connection-refresh.ts @@ -148,6 +148,7 @@ const oauthRefreshFlights = new Map>(); const client = machineSignIn ? null : await oauthClientForConnection( connection, oauth.provider, + oauth.tokenUrl, actor, ); if (client && !client.clientId) diff --git a/server/src/services/tool-access/oauth/credential-store.ts b/server/src/services/tool-access/oauth/credential-store.ts index 872abd2f364..d424230ecda 100644 --- a/server/src/services/tool-access/oauth/credential-store.ts +++ b/server/src/services/tool-access/oauth/credential-store.ts @@ -6,11 +6,11 @@ import { and, eq, inArray } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { connectionGrants, toolConnections } from "@paperclipai/db"; import type { ToolConnection, ToolCredentialSecretRef } from "@paperclipai/shared"; -import { notFound } from "../../../errors.js"; +import { notFound, unprocessable } from "../../../errors.js"; import { secretService } from "../../secrets.js"; import { resolveConnectionGrantSecret, writeConnectionCredential } from "../../connection-credentials.js"; -import { configuredOAuthClientForConnection, oauthSecretRef } from "./client-settings.js"; +import { configuredOAuthClientForConnection, oauthSecretRef, refusedDeploymentClientError } from "./client-settings.js"; export function actorForSecret( actor?: ActorInfo, ): { userId?: string | null; agentId?: string | null } | undefined { @@ -58,16 +58,21 @@ async function syncCredentialBindings( async function oauthClientForConnection( connection: typeof toolConnections.$inferSelect, provider: string, + tokenUrl: string | null | undefined, actor?: ActorInfo, ) { - const configured = configuredOAuthClientForConnection(connection, provider); + const configured = configuredOAuthClientForConnection(connection, provider, tokenUrl); if (configured.clientId) return configured; const oauth = oauthConfig(connection); const clientId = typeof oauth.clientId === "string" && oauth.clientId.trim() ? oauth.clientId.trim() : null; - if (!clientId) return configured; + if (!clientId) { + const refused = refusedDeploymentClientError(provider); + if (refused) throw refused; + return configured; + } // CIMD clients and public DCR clients have no token-endpoint secret. A DCR // authorization server may instead issue a confidential client (for // example, `client_secret_basic`); in that case the registration secret is diff --git a/server/src/services/tool-access/oauth/direct-callback.ts b/server/src/services/tool-access/oauth/direct-callback.ts index 17404dc6002..728a4d10087 100644 --- a/server/src/services/tool-access/oauth/direct-callback.ts +++ b/server/src/services/tool-access/oauth/direct-callback.ts @@ -134,6 +134,7 @@ export function createDirectOAuthCallback(db: Db, dependencies: Dependencies) { const client = await oauthClientForConnection( connection, endpoints.provider, + endpoints.tokenUrl, input.actor, ); if (!client.clientId) diff --git a/server/src/services/tool-access/oauth/grant-refresh.ts b/server/src/services/tool-access/oauth/grant-refresh.ts index b811431f04c..3f3981411bc 100644 --- a/server/src/services/tool-access/oauth/grant-refresh.ts +++ b/server/src/services/tool-access/oauth/grant-refresh.ts @@ -306,6 +306,7 @@ export function createOAuthGrantRefresh(db: Db, { now, store, leases, currentClo const client = await oauthClientForConnection( connection, oauthProvider, + oauthTokenUrl, credentialActor, ); if (!client.clientId) diff --git a/server/src/services/tool-action-review.ts b/server/src/services/tool-action-review.ts index 59502b42c17..7d82e266689 100644 --- a/server/src/services/tool-action-review.ts +++ b/server/src/services/tool-action-review.ts @@ -11,7 +11,7 @@ import { type Db, } from "@paperclipai/db"; import { conflict, forbidden, notFound } from "../errors.js"; -import { assertIssueThreadInteractionResolverAudience } from "./issue-thread-interaction-resolution.js"; +import { assertHumanToolReviewResolution } from "./issue-thread-interaction-resolution.js"; import { emitConnectionInvoked } from "./connector-telemetry.js"; import { toolAccessPolicyService } from "./tool-access-policy.js"; import { @@ -34,8 +34,9 @@ export async function commitToolActionReview( actor: { agentId?: string | null; userId?: string | null }; }, ) { - if (input.actor.agentId) - throw forbidden("Only a human can resolve a tool review"); + if (input.actor.agentId || !input.actor.userId) + throw forbidden("Only a human can resolve a tool review", { code: "human_review_required" }); + const userId = input.actor.userId; const [source] = await db .select() .from(toolActionRequests) @@ -133,10 +134,11 @@ export async function commitToolActionReview( payload.toolAction.invocationId !== current.invocationId ) throw conflict("Tool review context does not match"); - assertIssueThreadInteractionResolverAudience({ - actor: { type: "user", userId: input.actor.userId ?? "board" }, + if (!issue) throw conflict("Tool review context does not match"); + assertHumanToolReviewResolution({ + userId, + issue, interaction, - governedAction: true, }); if (interaction.status !== "pending") throw conflict("This review has already been resolved"); @@ -148,8 +150,8 @@ export async function commitToolActionReview( .update(toolActionRequests) .set({ status: input.decision, - resolvedByUserId: input.actor.userId ?? "board", - decidedByUserId: input.actor.userId ?? "board", + resolvedByUserId: userId, + decidedByUserId: userId, decidedAt: now, resolvedAt: now, updatedAt: now, @@ -165,7 +167,7 @@ export async function commitToolActionReview( companyId: input.companyId, actionRequestId: current.id, body: { approvalThreshold: 1, priority: 40, argumentMode: "action" }, - actor: { userId: input.actor.userId ?? "board" }, + actor: { userId: userId }, }); } await tx @@ -193,7 +195,7 @@ export async function commitToolActionReview( .update(issueThreadInteractions) .set({ status: input.decision === "approved" ? "accepted" : "rejected", - resolvedByUserId: input.actor.userId ?? "board", + resolvedByUserId: userId, resolvedAt: now, updatedAt: now, result: @@ -226,7 +228,7 @@ export async function commitToolActionReview( { companyId: input.companyId, actorType: "user", - actorId: input.actor.userId ?? "board", + actorId: userId, action: input.decision === "approved" ? "issue.thread_interaction_accepted" diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index 89c40afd7fc..56a77d116d1 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -34,6 +34,7 @@ import { notifyDeliveryWork, DELIVERY_QUEUES } from "./delivery-work-notificatio import { measureToolDiscovery, measureRunPhase, recordConnectionCatalogCounts } from "./execution-preparation-timing.js"; import { nativeProviderCatalogFor } from "./native-provider-catalogs.js"; import { callGoogleWorkspaceRest, googleWorkspaceCatalogToolTitle, googleWorkspaceRestAuditEndpoint } from "./google-workspace-rest-dispatch.js"; +import { paperclipDefinedTool } from "./connectors/paperclip-defined-tools.js"; import { composeConnectionInstructions } from "./connection-instructions.js"; import { googleWorkspaceToolTarget, googleWorkspaceGrantedScopes, isGoogleWorkspaceToolGranted } from "@paperclipai/shared"; import { isInsufficientConnectionScope, INSUFFICIENT_CONNECTION_SCOPE_MESSAGE } from "./connection-permission-errors.js"; @@ -105,6 +106,7 @@ import { eq, gt, inArray, + isNotNull, isNull, lt, lte, @@ -264,6 +266,7 @@ import { import { toolDiscoveryScheduler, ToolDiscoveryBusyError } from "./tool-discovery-scheduler.js"; import { commitToolActionReview } from "./tool-action-review.js"; import { issueThreadInteractionService } from "./issue-thread-interactions.js"; +import { evaluateHumanToolReviewResolution } from "./issue-thread-interaction-resolution.js"; import { createToolRuntimeSupervisor, ToolRuntimeSupervisorError, @@ -467,6 +470,7 @@ export interface ToolGatewaySession { gatewayTokenAllowedActions?: ToolMcpGatewayTokenAction[]; actorType?: "agent" | "user" | "system" | "plugin"; actorId?: string | null; + createdByUserId?: string | null; /** Human whose personal connection grant applies to this execution. */ responsibleUserId?: string | null; /** Captured by the controller for this request, never accepted from tool arguments. */ @@ -1019,11 +1023,17 @@ function gatewaySessionFromRow( runId: row.runId, issueId: row.issueId, projectId: row.projectId, + createdByUserId: row.createdByUserId ?? null, createdAt: row.createdAt, expiresAt: row.expiresAt, }; } +function sessionOpenerFromInvocation(invocation: { policyExplanation?: Record | null }) { + const opener = invocation.policyExplanation?.sessionOpenedByUserId; + return typeof opener === "string" && opener ? opener : null; +} + function timeoutMs(value: number | undefined, tool?: ToolGatewayDescriptor) { if (!Number.isFinite(value)) return tool?.providerType === "paperclip_github_chat" ? GITHUB_BOT_TOOL_TIMEOUT_MS @@ -2018,13 +2028,15 @@ export function createToolGatewayService( ...(baseNameCounts.get(baseName)! > 1 ? [catalogEntry.id] : []), ]); const applicationKey = application.applicationKey ?? null; + const currentDefinition = paperclipDefinedTool(connection, catalogEntry.toolName); const inputSchema = projectedConnectionToolInputSchema( connection, - catalogEntry.inputSchema ?? {}, + currentDefinition?.inputSchema ?? catalogEntry.inputSchema ?? {}, catalogEntry.toolName, ); - const outputSchema = catalogEntry.outputSchema ?? null; - const annotations = catalogEntry.annotations ?? {}; + const outputSchema = currentDefinition?.outputSchema ?? catalogEntry.outputSchema ?? null; + const annotations = currentDefinition?.annotations ?? catalogEntry.annotations ?? {}; + const description = currentDefinition?.description ?? catalogEntry.description; const risk = riskFromCatalogEntry(catalogEntry); const onDemandTools = readOnDemandToolsEnabled(connection); const providerMetadata: ConnectedMcpGatewayMetadata = { @@ -2051,12 +2063,12 @@ export function createToolGatewayService( }; return { name: gatewayToolName, - displayName: googleWorkspaceCatalogToolTitle(connection.config.sourceTemplateKey, catalogEntry.toolName, catalogEntry.title) ?? catalogEntry.toolName, + displayName: currentDefinition?.title ?? googleWorkspaceCatalogToolTitle(connection.config.sourceTemplateKey, catalogEntry.toolName, catalogEntry.title) ?? catalogEntry.toolName, description: gmailArchiveToolDescription( connection, catalogEntry.toolName, - googleChatToolDescription(connection, catalogEntry.toolName, catalogEntry.description), + googleChatToolDescription(connection, catalogEntry.toolName, description), ) ?? `Connected MCP tool ${catalogEntry.toolName} from ${connection.name}.`, parametersSchema: inputSchema, @@ -2233,6 +2245,41 @@ export function createToolGatewayService( }; } + async function assertHumanMayActOnToolReview( + actionRequest: typeof toolActionRequests.$inferSelect, + userId: string | null | undefined, + ) { + if (!userId) { + throw new ToolGatewayHttpError(403, "Only a human can resolve a tool review", "human_review_required"); + } + if (!actionRequest.issueId || !actionRequest.interactionId) { + if (actionRequest.status === "pending" + || [actionRequest.requestedByUserId, actionRequest.decidedByUserId, actionRequest.resolvedByUserId].includes(userId)) return; + throw new ToolGatewayHttpError(404, "Tool action request not found", "action_request_not_found"); + } + const [interaction] = await db + .select() + .from(issueThreadInteractions) + .where(and( + eq(issueThreadInteractions.id, actionRequest.interactionId), + eq(issueThreadInteractions.companyId, actionRequest.companyId), + eq(issueThreadInteractions.issueId, actionRequest.issueId), + )) + .limit(1); + const [issue] = await db + .select() + .from(issues) + .where(and(eq(issues.id, actionRequest.issueId), eq(issues.companyId, actionRequest.companyId))) + .limit(1); + if (!interaction || !issue) { + throw new ToolGatewayHttpError(404, "Tool action request not found", "action_request_not_found"); + } + const decision = evaluateHumanToolReviewResolution({ userId, issue, interaction }); + if (!decision.allowed) { + throw new ToolGatewayHttpError(decision.status, decision.message, decision.code); + } + } + async function resolveRunContext(input: { companyId: string; agentId: string; @@ -3329,6 +3376,7 @@ export function createToolGatewayService( issueId: input.session.issueId, projectId: input.session.projectId, gatewayId: input.session.gatewayId ?? null, + sessionOpenedByUserId: input.session.createdByUserId ?? null, }); } @@ -3347,6 +3395,7 @@ export function createToolGatewayService( issueId?: string | null; projectId?: string | null; gatewayId?: string | null; + sessionOpenedByUserId?: string | null; }): ToolAccessDecisionInput { const actorType = input.actorType ?? (input.agentId ? "agent" : "system"); const actorId = @@ -3365,6 +3414,7 @@ export function createToolGatewayService( projectId: input.projectId ?? null, gatewayId: input.gatewayId ?? null, gatewayTokenId: input.gatewayTokenId ?? null, + ...(input.sessionOpenedByUserId ? { sessionOpenedByUserId: input.sessionOpenedByUserId } : {}), }, request: { toolName: input.tool.name, @@ -3469,7 +3519,7 @@ export function createToolGatewayService( session.companyId, { agentId: session.agentId, - responsibleUserId: session.responsibleUserId, + responsibleUserId: session.createdByUserId ?? session.responsibleUserId, allowStandingDelegation: false, }, ); @@ -3530,7 +3580,7 @@ export function createToolGatewayService( session.companyId, { agentId: session.agentId, - responsibleUserId: session.responsibleUserId, + responsibleUserId: session.createdByUserId ?? session.responsibleUserId, allowStandingDelegation: false, excludeGrantId: original.id, }, @@ -5231,6 +5281,22 @@ export function createToolGatewayService( session: ToolGatewaySession, connection: typeof toolConnections.$inferSelect, allowInteraction = true, + ): Promise { + const grant = await resolveConnectionGrantForSession(session, connection, allowInteraction); + if (session.createdByUserId && grant.subjectUserId && grant.subjectUserId !== session.createdByUserId) { + throw new ToolGatewayHttpError( + 403, + "Only the person who owns this personal connection can use it from a session they open.", + "personal_grant_owner_required", + ); + } + return grant; + } + + async function resolveConnectionGrantForSession( + session: ToolGatewaySession, + connection: typeof toolConnections.$inferSelect, + allowInteraction: boolean, ): Promise { if (!(await pluginAppCatalogFor(db, [connection])).isAvailable(connectionSourceSlug(connection))) { throw new ToolGatewayHttpError( @@ -5255,9 +5321,9 @@ export function createToolGatewayService( ) .limit(1) : []; - const actingUserId = session.identityContextId + const actingUserId = session.createdByUserId ?? (session.identityContextId ? (session.responsibleUserId ?? null) - : (run?.responsibleUserId ?? session.responsibleUserId ?? null); + : (run?.responsibleUserId ?? session.responsibleUserId ?? null)); if ( session.identityContextId && session.agentId && @@ -5269,7 +5335,7 @@ export function createToolGatewayService( ? { grant: captured.grant, error: undefined } : await resolveManagedGitHubIdentitySelection(db, session.companyId, { agentId: session.agentId, - responsibleUserId: session.responsibleUserId, + responsibleUserId: session.createdByUserId ?? session.responsibleUserId, allowStandingDelegation: false, }); if (!selected.grant || selected.grant.connectionId !== connection.id) { @@ -7605,7 +7671,7 @@ export function createToolGatewayService( ? await db.select({ responsibleUserId: heartbeatRuns.responsibleUserId }).from(heartbeatRuns) .where(and(eq(heartbeatRuns.id, input.session.runId), eq(heartbeatRuns.companyId, input.session.companyId))).limit(1) : []; - const responsibleUserId = input.session.responsibleUserId ?? run?.responsibleUserId ?? null; + const responsibleUserId = input.session.createdByUserId ?? input.session.responsibleUserId ?? run?.responsibleUserId ?? null; const now = Date.now(); const inserted = await db.transaction(async (tx) => { await notifyDeliveryWork(tx, DELIVERY_QUEUES.mcpTasks); @@ -7621,6 +7687,7 @@ export function createToolGatewayService( actorType: input.session.actorType ?? "agent", actorId: input.session.actorId ?? null, responsibleUserId, + createdByUserId: input.session.createdByUserId ?? null, identityContextId: input.session.identityContextId ?? null, catalogToolName: input.catalogToolName, requestHash: input.requestHash, @@ -7678,23 +7745,57 @@ export function createToolGatewayService( /** An undelivered task this exact call already started, for this grant, agent, and task. */ async function findAttachableMcpTask(input: { - session: ToolGatewaySession; connectionId: string; grantId: string; requestHash: string; rowId?: string; + session: ToolGatewaySession; connectionId: string; grant: typeof connectionGrants.$inferSelect; requestHash: string; rowId?: string; }): Promise { + const opener = input.session.createdByUserId ?? null; + const personalOwner = input.grant.kind === "user" ? input.grant.subjectUserId : null; + const sameOpener = opener ? eq(toolMcpTasks.createdByUserId, opener) : isNull(toolMcpTasks.createdByUserId); + const legacyForOwner = opener && opener === personalOwner ? isNull(toolMcpTasks.createdByUserId) : undefined; const [row] = await db.select().from(toolMcpTasks).where(and( eq(toolMcpTasks.companyId, input.session.companyId), ...(input.rowId ? [eq(toolMcpTasks.id, input.rowId)] : []), eq(toolMcpTasks.connectionId, input.connectionId), eq(toolMcpTasks.requestHash, input.requestHash), - eq(toolMcpTasks.grantId, input.grantId), + eq(toolMcpTasks.grantId, input.grant.id), + ...(personalOwner ? [legacyForOwner ? or(sameOpener, legacyForOwner)! : sameOpener] : []), input.session.agentId ? eq(toolMcpTasks.agentId, input.session.agentId) : isNull(toolMcpTasks.agentId), input.session.issueId ? eq(toolMcpTasks.issueId, input.session.issueId) : isNull(toolMcpTasks.issueId), eq(toolMcpTasks.actorType, input.session.actorType ?? "agent"), input.session.actorId ? eq(toolMcpTasks.actorId, input.session.actorId) : isNull(toolMcpTasks.actorId), mcpTaskCollectable(), - )).orderBy(desc(toolMcpTasks.createdAt)).limit(1); + )).orderBy( + desc(opener ? sql`${toolMcpTasks.createdByUserId} = ${opener}` : sql`${toolMcpTasks.createdByUserId} is null`), + desc(toolMcpTasks.createdAt), + ).limit(1); return row ?? null; } + async function continuedMcpTask( + session: ToolGatewaySession, + connection: typeof toolConnections.$inferSelect, + requestHash: string, + ): Promise { + if (session.createdByUserId || !session.runId || !session.agentId || !session.issueId) return null; + const [run] = await db.select({ contextSnapshot: heartbeatRuns.contextSnapshot }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.id, session.runId), eq(heartbeatRuns.companyId, session.companyId))).limit(1); + const taskRecordId = asRecord(asRecord(run?.contextSnapshot)?.toolTask)?.taskRecordId; + if (typeof taskRecordId !== "string" || !taskRecordId) return null; + const [row] = await db.select().from(toolMcpTasks).where(and( + eq(toolMcpTasks.id, taskRecordId), + eq(toolMcpTasks.companyId, session.companyId), + eq(toolMcpTasks.connectionId, connection.id), + eq(toolMcpTasks.requestHash, requestHash), + eq(toolMcpTasks.agentId, session.agentId), + eq(toolMcpTasks.issueId, session.issueId), + isNotNull(toolMcpTasks.createdByUserId), + )).limit(1); + if (!row) return null; + const [collectable] = await db.select({ id: toolMcpTasks.id }).from(toolMcpTasks) + .where(and(eq(toolMcpTasks.id, row.id), mcpTaskCollectable())).limit(1); + if (!collectable) throw mcpTaskExpiredError(); + return row; + } + /** * The task a keyed retry should collect, checked before the call changes * anything. A call interrupted mid-wait (a crash) left its invocation @@ -7942,6 +8043,7 @@ export function createToolGatewayService( id: `mcp-task:${row.id}`, token: "", companyId: row.companyId, agentId: row.agentId, runId: row.runId, issueId: row.issueId, projectId: null, actorType: row.actorType as ToolGatewaySession["actorType"], actorId: row.actorId, responsibleUserId: row.responsibleUserId, identityContextId: row.identityContextId, + createdByUserId: row.createdByUserId ?? null, createdAt: new Date(), expiresAt: new Date(Date.now() + 5 * 60_000), }; // The same access check a live call makes, as the same caller: audience, @@ -8521,17 +8623,25 @@ export function createToolGatewayService( deadline: controller.signal, runSignal: taskSignals.run, callerSignal: taskSignals.caller, execution, }); if (taskIdentity) { - const attachable = await findAttachableMcpTask({ - session, connectionId: connection.id, grantId: grant.id, requestHash: taskIdentity.requestHash, - rowId: taskSignals.attachToTaskRecordId ?? undefined, - }); + const attachable = (taskSignals.attachToTaskRecordId ? null : await continuedMcpTask(session, connection, taskIdentity.requestHash)) + ?? await findAttachableMcpTask({ + session, connectionId: connection.id, grant, requestHash: taskIdentity.requestHash, + rowId: taskSignals.attachToTaskRecordId ?? undefined, + }); const attachedTaskId = attachable ? openMcpTaskId(mcpTaskSecret(), mcpTaskScope(attachable), attachable.sealedProviderTaskId) : null; + if (attachable && !attachedTaskId && attachable.grantId !== grant.id) throw mcpTaskExpiredError(); if (attachable && attachedTaskId) { // Only one caller collects a task at a time; another one waiting on // it means this call is told to try again, never handed a copy. const claimed = await claimMcpTask(attachable, taskOwner, ms + 15_000, { lastInvocationId: invocationId, runId: session.runId ?? attachable.runId }); if (!claimed) throw mcpTaskPendingError(); - return await completeRemoteMcpCall(await waitOnTask(claimed, attachedTaskId)); + if (claimed.grantId === grant.id) return await completeRemoteMcpCall(await waitOnTask(claimed, attachedTaskId)); + const original = await storedMcpTaskContext(claimed); + if ("closed" in original) throw mcpTaskExpiredError(); + return await completeRemoteMcpCall(await waitForMcpTask({ + row: claimed, owner: taskOwner, taskId: original.taskId, session, tool, invocationId, transport: original.transport, + deadline: controller.signal, runSignal: taskSignals.run, callerSignal: taskSignals.caller, execution, + })); } } if (taskSignals.attachToTaskRecordId) { @@ -10796,6 +10906,7 @@ export function createToolGatewayService( actorType: invocation.actorType as ToolGatewaySession["actorType"], actorId: invocation.actorId, originatingAgentId: typeof invocation.policyExplanation?.delegatedGatewayIssuer === "string" ? invocation.policyExplanation.delegatedGatewayIssuer : invocation.actorType === "agent" && invocation.gatewayId && !invocation.runId && !invocation.gatewayTokenId ? invocation.actorId : null, + createdByUserId: sessionOpenerFromInvocation(invocation), createdAt: new Date(), expiresAt: new Date(Date.now() + DEFAULT_SESSION_TTL_MS), }; @@ -11095,6 +11206,9 @@ export function createToolGatewayService( inArray(toolActionRequests.canonicalArgumentsHash, [input.argumentsHash, summarizeToolValue(input.parameters).sha256]), eq(toolInvocations.agentId, input.session.agentId), eq(toolInvocations.toolName, input.toolName), + input.session.createdByUserId + ? sql`${toolInvocations.policyExplanation}->>'sessionOpenedByUserId' = ${input.session.createdByUserId}` + : sql`(${toolInvocations.policyExplanation}->>'sessionOpenedByUserId') is null`, inArray(toolActionRequests.status, [ "pending", "approved", @@ -11874,6 +11988,7 @@ export function createToolGatewayService( ttlMs?: number; actorType?: LogActivityInput["actorType"]; actorId?: string; + createdByUserId?: string | null; }): Promise { await assertAgentInCompany(input.companyId, input.agentId); const { issueId, projectId } = await resolveRunContext(input); @@ -11888,6 +12003,7 @@ export function createToolGatewayService( runId: input.runId, issueId, projectId, + createdByUserId: input.createdByUserId ?? null, createdAt: now, expiresAt: new Date(now.getTime() + sessionTtlMs(input.ttlMs)), }; @@ -11901,6 +12017,7 @@ export function createToolGatewayService( runId: input.runId, issueId: session.issueId, projectId: session.projectId, + createdByUserId: session.createdByUserId, tokenHash: hashGatewayToken(token), expiresAt: session.expiresAt, createdAt: session.createdAt, @@ -12726,7 +12843,7 @@ export function createToolGatewayService( const { request, invocation, payload } = prepared; if (!isTestOriginInvocation(invocation) && payload.executionOnApprove !== true) return false; await this.approveActionRequest({ companyId: request.companyId, actionRequestId: request.id, - actor: { userId: request.decidedByUserId ?? request.resolvedByUserId } }); + actor: { userId: request.decidedByUserId ?? request.resolvedByUserId }, recoveringApprovedReview: true }); const [remaining] = await db.select({ status: toolActionRequests.status, errorCode: toolInvocations.errorCode }) .from(toolActionRequests).innerJoin(toolInvocations, eq(toolInvocations.id, toolActionRequests.invocationId)) .where(eq(toolActionRequests.id, request.id)); @@ -12748,6 +12865,7 @@ export function createToolGatewayService( async approveActionRequest(input: { companyId: string; + recoveringApprovedReview?: boolean; rememberAction?: boolean; issueId?: string; interactionId?: string; @@ -12772,6 +12890,7 @@ export function createToolGatewayService( "action_request_not_found", ); } + if (!input.recoveringApprovedReview) await assertHumanMayActOnToolReview(actionRequest, input.actor.userId); const [invocation] = await db .select() .from(toolInvocations) @@ -12957,6 +13076,7 @@ export function createToolGatewayService( actorType: "agent", actorId: invocation.actorId, originatingAgentId: typeof invocation.policyExplanation?.delegatedGatewayIssuer === "string" ? invocation.policyExplanation.delegatedGatewayIssuer : invocation.actorType === "agent" && invocation.gatewayId && !invocation.runId && !invocation.gatewayTokenId ? invocation.actorId : null, + createdByUserId: sessionOpenerFromInvocation(invocation), gatewayId: invocation.gatewayId, gatewayPublicId: invocation.gatewayPublicId, gatewayTokenId: invocation.gatewayTokenId, @@ -13048,6 +13168,14 @@ export function createToolGatewayService( reason?: string; actor: { agentId?: string | null; userId?: string | null }; }) { + if (!input.actor.agentId) { + const [actionRequest] = await db + .select() + .from(toolActionRequests) + .where(and(eq(toolActionRequests.id, input.actionRequestId), eq(toolActionRequests.companyId, input.companyId))) + .limit(1); + if (actionRequest) await assertHumanMayActOnToolReview(actionRequest, input.actor.userId); + } const updated = await commitToolActionReview(db, { ...input, decision: "rejected", @@ -13730,6 +13858,9 @@ export function createToolGatewayService( consumeRateLimit: true, }); let accessDecision = await policyService.decide(decisionInput); + if (session.createdByUserId) { + accessDecision = { ...accessDecision, policyExplanation: { ...accessDecision.policyExplanation, sessionOpenedByUserId: session.createdByUserId } }; + } if (accessDecision.allowed && tool.providerType === "paperclip_slack_chat" && SLACK_TOOLS.some(t => t.name === tool.upstreamToolName && t.risk === "approval")) { accessDecision = { ...accessDecision, allowed: false, decision: "require_approval", reasonCode: "requires_approval_policy", explanation: "Slack destructive actions, channel creation and invitations require approval." }; } diff --git a/server/src/services/workspace-git-source-roots.ts b/server/src/services/workspace-git-source-roots.ts index 6321536a3c6..8de3a319ddb 100644 --- a/server/src/services/workspace-git-source-roots.ts +++ b/server/src/services/workspace-git-source-roots.ts @@ -154,7 +154,7 @@ export async function readWorkspaceGitLinkedRoots(source: WorkspaceGitSourceRoot const target = path.join(commonDirectory.path, "worktrees"), present = await entry(target); if (!present) { results.push({ commonDirectory, directory: null, links: [], metadata: [] }); continue; } const directory = await directoryIdentity(target), names = (await fs.readdir(directory.path)).sort(); - if (names.length > 256) throw invalid(); + if (names.length > 256) throw new Error("workspace_git_links_exceeded"); const links: Array<{ root: Identity; gitDirectory: Identity }> = [], metadata: Metadata[] = []; for (const name of names) { const gitDirectory = await directoryIdentity(path.join(directory.path, name)); @@ -163,6 +163,7 @@ export async function readWorkspaceGitLinkedRoots(source: WorkspaceGitSourceRoot if (!backlink || !common || path.resolve(gitDirectory.path, metadataPath(common.text)) !== commonDirectory.path) throw invalid(); const marker = path.resolve(gitDirectory.path, metadataPath(backlink.text)); if (path.basename(marker) !== ".git") throw invalid(); + if (!await entry(path.dirname(marker))) throw new Error("workspace_git_link_stale"); const root = await directoryIdentity(path.dirname(marker)), pointer = await readMetadata(marker, 4096); if (marker !== path.join(root.path, ".git") || !pointer?.text.startsWith("gitdir: ") || path.resolve(root.path, metadataPath(pointer.text.slice(8))) !== gitDirectory.path) throw invalid(); diff --git a/server/src/storage/storage-unavailable.ts b/server/src/storage/storage-unavailable.ts index 111cc0649fc..ac87eaa3e71 100644 --- a/server/src/storage/storage-unavailable.ts +++ b/server/src/storage/storage-unavailable.ts @@ -9,6 +9,8 @@ export const STORAGE_UNAVAILABLE_WAIT_RETRY_REASON = "storage_unavailable_wait"; export const STORAGE_UNAVAILABLE_MESSAGE = "File storage was unavailable, so this attempt stopped before it could save its work. Paperclip will retry automatically when storage is back."; +export const STORAGE_TEMPORARILY_UNAVAILABLE_MESSAGE = "File storage is temporarily unavailable or is limiting requests. Try again in a moment."; + export const STORAGE_CREDENTIALS_REJECTED_MESSAGE = "File storage rejected Paperclip's storage credentials (they may have expired or been rotated), so this attempt stopped before it could save its work. Paperclip will retry automatically when valid credentials are available."; /** For a storage failure that no storage wait owns, such as a run whose native @@ -64,6 +66,10 @@ function recordedStorageFailure(error: unknown) { return null; } +export function recordedStorageFailureDiagnostics(error: unknown) { + return recordedStorageFailure(error)?.diagnostics ?? null; +} + export function isStorageCredentialRejection(error: unknown): boolean { const recorded = recordedStorageFailure(error); return recorded !== null && isCredentialRejectionCode(recorded.diagnostics.errorCode, recorded.diagnostics.httpStatus); diff --git a/tests/runner-e2e/connection-evidence.ts b/tests/runner-e2e/connection-evidence.ts index 9ccb4c4d105..f221fa0f516 100644 --- a/tests/runner-e2e/connection-evidence.ts +++ b/tests/runner-e2e/connection-evidence.ts @@ -4,6 +4,18 @@ import type { RunnerE2EResult } from "./types.js"; export const connectionCheckpoints = ["target", "connection_created", "connection_reloaded", "agent_created", "binding", "setup_probe", "first_run", "artifact", "tool_receipt", "followup", "visible_result"] as const; export type ConnectionCheckpoint = typeof connectionCheckpoints[number]; export const connectionRunSignals = ["provider_overloaded", "provider_quota", "missing_file_conversion", "unsupported_session_configuration", "command_substitution_denied"] as const; +export const connectionVerificationFailureCodes = [ + "ai_connection_api_key_rejected", + "ai_connection_billing_required", + "ai_connection_rate_limited", + "ai_connection_provider_unavailable", + "ai_connection_verification_timeout", + "ai_connection_provider_unreachable", + "ai_connection_verification_failed", +] as const; +export const connectionCreationFailureCodes = [...connectionVerificationFailureCodes, "connection_request_rejected"] as const; +export type ConnectionCreationFailureCode = (typeof connectionCreationFailureCodes)[number]; + export interface ConnectionRunDiagnostic { runId: string; status: "succeeded" | "failed" | "cancelled" | "interrupted" | "timed_out" | "unknown"; @@ -28,7 +40,7 @@ export interface ConnectionEvidence { model?: string; inputTransport?: "prompt_base64"; setupChecks?: Array<{ code: string; level: "info" | "warn" | "error" }>; - creationFailure?: { status: number; code: "ai_connection_api_key_rejected" | "ai_connection_verification_failed" | "connection_request_rejected" }; + creationFailure?: { status: number; code: ConnectionCreationFailureCode }; cleanupRetained?: boolean; companyArchived?: boolean; artifactChecks?: Array<{ filename: string; runId: string; sha256: string; fields: Record; exactFields: boolean }>; diff --git a/tests/runner-e2e/connection-flow.ts b/tests/runner-e2e/connection-flow.ts index 1e6393c0189..ce7b540e08d 100644 --- a/tests/runner-e2e/connection-flow.ts +++ b/tests/runner-e2e/connection-flow.ts @@ -5,7 +5,7 @@ import { getConnectableAppDefinition } from "../../packages/shared/src/app-defin import { connectionCell, type ConnectionHarness, type ConnectionMode } from "./connection-cases.js"; import { ConnectionBlock, ConnectionFailure, type ConnectionConfig, type resolveConnectionSettings } from "./connection-config.js"; import { ConnectionApi, connectionDelay } from "./connection-target.js"; -import { createConnectionProof, verifyConnectionArtifact, verifyConnectionRun, completedConnectionArtifactRun, connectionProbeChecks, type ConnectionEvidence } from "./connection-evidence.js"; +import { createConnectionProof, verifyConnectionArtifact, verifyConnectionRun, completedConnectionArtifactRun, connectionProbeChecks, connectionVerificationFailureCodes, type ConnectionCreationFailureCode, type ConnectionEvidence } from "./connection-evidence.js"; import { createTaskThroughUi, submitTaskReply } from "./user-actions.js"; import { collectRunEvents } from "./run-observations.js"; import type { MatrixExecution } from "./types.js"; @@ -56,8 +56,8 @@ async function submitConnection(input: ConnectionFlowInput, submit: () => Promis if (!created) throw new ConnectionFailure("connection_request_timeout"); if (created.ok()) return; const payload = await created.json().catch(() => ({})); - const allowed = ["ai_connection_api_key_rejected", "ai_connection_verification_failed"]; - const code = allowed.includes(payload?.details?.code) ? payload.details.code : "connection_request_rejected"; + const allowed: readonly string[] = connectionVerificationFailureCodes; + const code: ConnectionCreationFailureCode = allowed.includes(payload?.details?.code) ? payload.details.code : "connection_request_rejected"; input.evidence.creationFailure = { status: created.status(), code }; if (code === "ai_connection_api_key_rejected") throw new ConnectionBlock("missing_credential", code); throw new ConnectionFailure(code); diff --git a/tests/runner-e2e/connection-support.test.ts b/tests/runner-e2e/connection-support.test.ts index 98fb816bca3..7f5978eb56b 100644 --- a/tests/runner-e2e/connection-support.test.ts +++ b/tests/runner-e2e/connection-support.test.ts @@ -3,11 +3,12 @@ import { chmod, mkdtemp, writeFile, rm } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { AGENT_ADAPTER_TYPES } from "../../packages/shared/src/constants.js"; +import { AI_KEY_VERIFICATION_FAILURES } from "../../server/src/services/ai-api-key-failures.js"; import { runnerMatrix } from "./catalog.js"; import { parseRunnerSelectors, selectRunnerExecutions, buildMatrixJobs } from "./selectors.js"; import { connectionHarnesses, connectionScopeGaps, connectionCell, supportsConnection } from "./connection-cases.js"; import { parseConnectionConfig, targetOrigin, selectedSecret, resolveConnectionSecret, resolveConnectionSettings } from "./connection-config.js"; -import { connectionCheckpoints, connectionEvidencePasses, connectionRunDiagnostic, createConnectionProof, verifyConnectionArtifact, verifyConnectionRun, completedConnectionArtifactRun, connectionProbeChecks, type ConnectionEvidence } from "./connection-evidence.js"; +import { connectionCheckpoints, connectionVerificationFailureCodes, connectionEvidencePasses, connectionRunDiagnostic, createConnectionProof, verifyConnectionArtifact, verifyConnectionRun, completedConnectionArtifactRun, connectionProbeChecks, type ConnectionEvidence } from "./connection-evidence.js"; import { validateRetainedRunnerResult } from "./result-validation.js"; import { ConnectionApi, verifyConnectionTarget } from "./connection-target.js"; import { cleanupConnectionCompany, connectionCreationReceipt, runConnectionCampaign, safeConnectionFailure, withConnectionCampaignCancellation } from "./connection-launch.js"; @@ -300,3 +301,10 @@ describe("independent qualification", () => { expect(cleanupFailed.failed).toBe(1); expect(cleanupFailed.incomplete).toBe(0); }); }); + +describe("connection creation failure codes", () => { + it("keeps every API key verification code the server can return", () => { + expect([...connectionVerificationFailureCodes].sort()) + .toEqual(Object.values(AI_KEY_VERIFICATION_FAILURES).map(failure => failure.code).sort()); + }); +}); diff --git a/tests/runner-e2e/result-validation.ts b/tests/runner-e2e/result-validation.ts index b89ab770fec..31901bc1f44 100644 --- a/tests/runner-e2e/result-validation.ts +++ b/tests/runner-e2e/result-validation.ts @@ -2,7 +2,7 @@ import { SCREENSHOT_PRIVACY_REASONS } from "./screenshot-privacy.js"; import { POSTGRES_IMAGE, POSTGRES_IMAGE_ID, POSTGRES_AMD64_IMAGE, POSTGRES_AMD64_IMAGE_IDS, reviewedPostgresReceiptIdentity } from "./docker-postgres.js"; import { agentJourneyRuns, agentJourneyRunCountValid, journeyRequiredChecks } from "./product-journeys/success-contract.js"; import { validateWorkerTiming } from "./worker-timing.js"; -import { connectionCheckpoints, connectionEvidencePasses, connectionRunSignals } from "./connection-evidence.js"; +import { connectionCreationFailureCodes, connectionCheckpoints, connectionEvidencePasses, connectionRunSignals } from "./connection-evidence.js"; import { githubJourneyCheckpoints, gradeGitHubReviewJourney } from "./github-review-evidence.js"; import { gradeAntigravityJourney, validateAntigravityJourneyEvidence } from "./antigravity-journey-evidence.js"; import { STARTUP_REUSE_LAYERS, STARTUP_REUSE_REASONS } from "../../packages/adapter-utils/src/startup-reuse.js"; @@ -395,7 +395,7 @@ const fields = { inputTransport: optional(oneOf("prompt_base64")), setupChecks: optional(array(shape({ code: string, level: oneOf("info", "warn", "error") }))), runDiagnostics: optional(array(shape({ runId: string, status: oneOf("succeeded", "failed", "cancelled", "interrupted", "timed_out", "unknown"), signals: array(oneOf(...connectionRunSignals)), logAvailable: boolean }))), - creationFailure: optional(shape({ status: integer, code: oneOf("ai_connection_api_key_rejected", "ai_connection_verification_failed", "connection_request_rejected") })), + creationFailure: optional(shape({ status: integer, code: oneOf(...connectionCreationFailureCodes) })), connectionId: optional(string), agentId: optional(string), companyId: optional(string), artifactSha256: optional(string), model: optional(string), cleanupRetained: optional(boolean), companyArchived: optional(boolean), })), completionQuality: optional(array(shape({ diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index b8997d084a3..ddfc3d3bc2c 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -85,7 +85,7 @@ "packages/shared/src/app-definitions/anthropic.json": "6c7cd96eefb4db6dca244fcddeb1c4a585a2af14", "packages/shared/src/app-definitions/api-key-generic.json": "09e6d4295513ac9f1002eaf37c34e7c2d00a3c05", "packages/shared/src/app-definitions/arcade.json": "c8379450055d4ea226d229b1cbf99c7ed2e52beb", - "packages/shared/src/app-definitions/asana.json": "4cc2859043a30037fd5cdc3ebd0909938b9344a8", + "packages/shared/src/app-definitions/asana.json": "42d051d84a576509d75a73fe49b23443d34759f8", "packages/shared/src/app-definitions/aws.json": "f6413552f37f06e3b003486324c7d892d8f3e5f3", "packages/shared/src/app-definitions/bedrock.json": "962d8a722ac6e2e4db00abc34f71947a3fdb733a", "packages/shared/src/app-definitions/beehiiv.json": "47aec8fdfbf5aed0919b6ac9bddb435de4988db3", @@ -130,7 +130,7 @@ "packages/shared/src/app-definitions/google-slides.json": "289366009d46be6b770eee6cd0bc650eb59a240c", "packages/shared/src/app-definitions/google-workspace-search.json": "f3ec9d00ed0116b7cb8b9b1b71353cb8d6dc8cf4", "packages/shared/src/app-definitions/google-workspace.json": "c3b55dc3ec502f6b86008e1e5b421748bdd50e91", - "packages/shared/src/app-definitions/google.json": "f0da4ff3af061649309c0544af7e1f6822d911a1", + "packages/shared/src/app-definitions/google.json": "f0bab0467612f915c88137eddbac0b320ac1aa2a", "packages/shared/src/app-definitions/gsc-wizard.json": "a4ba6f183d5f35a25d0a420ade18f00d3fb64534", "packages/shared/src/app-definitions/honcho.json": "17185eaf5189fc8c443388997c90ebf833bc9327", "packages/shared/src/app-definitions/hugging-face.json": "6567ad1e62c007da1702fc314736c2d3aa1d4499", @@ -162,7 +162,7 @@ "packages/shared/src/app-definitions/planetscale.json": "96d64734ee4b5b918461c6169ce97e9027bdfdc1", "packages/shared/src/app-definitions/posthog.json": "6042a291a24354e3eaba2ca283ec59c9cc7a258e", "packages/shared/src/app-definitions/postman.json": "bcee846eabd7d8592342324b2f6c0a825a912e3f", - "packages/shared/src/app-definitions/railway.json": "96193b680a11a41e1fa34fd5c96233b70c608ed8", + "packages/shared/src/app-definitions/railway.json": "11cd0177e4aac114875ebf8f70f48eb08596e9f5", "packages/shared/src/app-definitions/razorpay.json": "e2abe5d6f56864c2dae26b34c738c175307339d5", "packages/shared/src/app-definitions/resend.json": "38f7595265f9ff6afdc84b9bce18602cd2c6ebfa", "packages/shared/src/app-definitions/responses-api.json": "29ad92e4c41a0dc0e3a3b07f518200bdc8e2e6ff", @@ -267,8 +267,8 @@ "packages/shared/src/github-connectors.ts": "b8448b1eddac9a9d1308b94e4d136c761cbd4a00", "packages/shared/src/github-skill-repository.ts": "b00a9963472723bcb7fcd433aae442f75d7a138b", "packages/shared/src/gitignore-runtime.test.ts": "e334ab0eca8faeab5807171983ec9102a3f1c734", - "packages/shared/src/google-workspace-connectors.test.ts": "0021bf50e20076e9862b13e97f84e0e5bf5d5b35", - "packages/shared/src/google-workspace-connectors.ts": "270fbd40c0f96e8f4140c880a2c36a3150d4b9aa", + "packages/shared/src/google-workspace-connectors.test.ts": "26316900a50e5ab384e0dcf9c45a2bb4abc0830d", + "packages/shared/src/google-workspace-connectors.ts": "88d942d1e66d7facc68cf8645f665cdc80c8c005", "packages/shared/src/grok-bot.ts": "9de68f00e7926c397729ff62bf8e277f5a41c525", "packages/shared/src/heartbeat-inbox.ts": "227dc89705c20460ca02194091cb162e11503186", "packages/shared/src/home-paths.test.ts": "81235c17c376224e1be3abd3f034a8400f079c66", @@ -456,7 +456,7 @@ "packages/shared/src/types/tailscale.ts": "d02a917945d7779009a2dea4c4b535e9478e0680", "packages/shared/src/types/task-workspace.ts": "a23afa13d2cb58dc2eb72692ed28c16ed6fb84fb", "packages/shared/src/types/teams-catalog.ts": "632fe75f8e5a4cfc455843c2a1a2daff28a022be", - "packages/shared/src/types/tool-access.ts": "dd1cfc8b5e36f3ec572890022625402fe3fb637e", + "packages/shared/src/types/tool-access.ts": "95a5673f5b9fda95f4e84495508dc19a2d41ae5a", "packages/shared/src/types/user-profile.ts": "1ac26e033a79fab21dc267fd983959814c8b680f", "packages/shared/src/types/voice-sessions.ts": "95e3b62cdd51f62290e68536728ddd7297bc0459", "packages/shared/src/types/work-product.ts": "26f9129f606a207ce7a218ccef40f96747283086", diff --git a/ui/src/api/tools.ts b/ui/src/api/tools.ts index eed67960c40..51b6bfa9897 100644 --- a/ui/src/api/tools.ts +++ b/ui/src/api/tools.ts @@ -113,7 +113,7 @@ export type ToolGalleryResponse = { export type ToolMcpGatewaysResponse = { gateways: ToolMcpGatewayWithTokens[] }; export type CloudConnectorEnrollmentStatus = { configured: boolean; - status: "not_configured" | "unenrolled" | "pending" | "active" | "suspended" | "unverified"; + status: "not_configured" | "unenrolled" | "pending" | "active" | "suspended" | "unverified" | "misconfigured" | "unreachable"; brokerBaseUrl: string; instanceId: string | null; environment: "development" | "test" | "staging" | "production"; diff --git a/ui/src/features/connections/ConnectionSetupFlow.tsx b/ui/src/features/connections/ConnectionSetupFlow.tsx index c45cd32ec05..7b482da544c 100644 --- a/ui/src/features/connections/ConnectionSetupFlow.tsx +++ b/ui/src/features/connections/ConnectionSetupFlow.tsx @@ -1672,7 +1672,8 @@ function StandardConnectionSetupFlow({ if (result.auth.manualClientRequired) { oauthPopupRef.current?.close(); oauthPopupRef.current = null; - setLinkGuidance(genericConnectGuidance("oauth_manual_client_required", null)); + const guidance = genericConnectGuidance("oauth_manual_client_required", null); + setLinkGuidance(result.auth.manualClientReason ? { ...guidance, body: result.auth.manualClientReason } : guidance); setLinkAuthMode("oauth"); setLinkAdvancedOpen(true); setGenericOAuthPending(false); @@ -2396,12 +2397,19 @@ function StandardConnectionSetupFlow({ && (directOAuthEntry || oauthPhase !== "entry"), ); + // "unreachable" means Cloud did not answer the check, not that this instance + // is unenrolled. Offering enrollment there sends a Cloud workspace (or an + // already-enrolled instance) into a flow that cannot succeed; a retry can. + const cloudConnectorUnreachable = connectorEnrollmentQuery.data?.status === "unreachable"; + // Incomplete managed identity settings: registration cannot run here, and + // only an administrator can finish the settings. + const cloudConnectorMisconfigured = connectorEnrollmentQuery.data?.status === "misconfigured"; const managedConnectorUnavailable = Boolean( step === "key" && entry && requestedDefinitionUsesManagedConnector && !entryAdvertisesManagedConnector - && connectorEnrollmentQuery.data?.configured === true + && (connectorEnrollmentQuery.data?.configured === true || cloudConnectorUnreachable || cloudConnectorMisconfigured) ); const showConnectorEnrollmentStep = Boolean( @@ -2409,6 +2417,8 @@ function StandardConnectionSetupFlow({ && entry && requestedDefinitionUsesManagedConnector && !entryAdvertisesManagedConnector + && !cloudConnectorUnreachable + && !cloudConnectorMisconfigured && ( connectorEnrollmentQuery.isLoading || connectorEnrollmentView.kind === "error" @@ -2713,7 +2723,11 @@ function StandardConnectionSetupFlow({

{entry.name} sign-in is unavailable

- This instance is connected to Paperclip, but {entry.name} sign-in is not currently available. Try again shortly or contact your instance administrator. + {cloudConnectorUnreachable + ? `Paperclip couldn’t reach Paperclip Cloud to start ${entry.name} sign-in. Try again in a moment.` + : cloudConnectorMisconfigured + ? `${entry.name} sign-in through Paperclip Cloud isn’t set up on this instance. Ask your instance administrator to finish the Paperclip Cloud settings.` + : `This instance is connected to Paperclip, but ${entry.name} sign-in is not currently available. Try again shortly or contact your instance administrator.`}

{customOAuthMethod ? ( -
diff --git a/ui/src/features/connections/googleAccessRemoval.ts b/ui/src/features/connections/googleAccessRemoval.ts index 566bef7d984..ccc04b85e39 100644 --- a/ui/src/features/connections/googleAccessRemoval.ts +++ b/ui/src/features/connections/googleAccessRemoval.ts @@ -16,6 +16,7 @@ const openGoogleAccountConnections: ToastAction = { export function googleAccessRemovalNotice( providerAccess: ManagedGoogleAccessRemoval | null | undefined, + removed: "connection" | "credentials" = "connection", ): GoogleAccessRemovalNotice | null { if (providerAccess?.provider !== "google") return null; if (providerAccess.result === "ended") { @@ -36,7 +37,7 @@ export function googleAccessRemovalNotice( } return { tone: "warn", - body: "Paperclip removed the connection but couldn't end its access at Google. You can remove Paperclip from your Google account's third-party connections.", + body: `Paperclip removed the ${removed} but couldn't end its access at Google. You can remove Paperclip from your Google account's third-party connections.`, action: openGoogleAccountConnections, }; } diff --git a/ui/src/lib/activity-format.test.ts b/ui/src/lib/activity-format.test.ts index a4af097746b..fe3319ee7ee 100644 --- a/ui/src/lib/activity-format.test.ts +++ b/ui/src/lib/activity-format.test.ts @@ -1,6 +1,11 @@ import type { Agent } from "@paperclipai/shared"; import { describe, expect, it } from "vitest"; -import { formatActivityVerb, formatIssueActivityAction } from "./activity-format"; +import { + formatActivityEntityLabel, + formatActivityOutcome, + formatActivityVerb, + formatIssueActivityAction, +} from "./activity-format"; describe("activity formatting", () => { const agentMap = new Map([ @@ -161,4 +166,86 @@ describe("activity formatting", () => { "Run finished without a next step - recovery escalated", ); }); + describe("connected app activity", () => { + const connectionId = "7f3c2a10-5b4e-4d2a-9c1f-0e8d6b5a4c3d"; + const gatewayName = "mcp.google-workspace-7f3c2a10:gmail-get-message"; + const internalName = /__|[a-z]_[a-z]|[0-9a-f]{8}-[0-9a-f]{4}|7f3c2a10/i; + + it("names Google Workspace actions with the same label as the Permissions page", () => { + const details = { tool: gatewayName, upstreamToolName: "gmail__get_message", connectionId }; + expect(formatActivityVerb("tool_gateway.call_completed", details)).toBe("used Gmail: Get message on"); + expect(formatActivityVerb("tool_gateway.call_completed", { ...details, source: "test" })).toBe("tested Gmail: Get message on"); + expect(formatActivityVerb("tool_gateway.call_denied", details)).toBe("was blocked from using Gmail: Get message on"); + expect(formatActivityVerb("tool_gateway.approval_requested", details)).toBe("asked to use Gmail: Get message on"); + expect(formatActivityVerb("tool_gateway.call_completed", { ...details, toolTitle: "Read a message" })) + .toBe("used Gmail: Read a message on"); + for (const action of [ + "tool_gateway.call_completed", "tool_gateway.call_allowed", "tool_gateway.call_denied", + "tool_gateway.approval_requested", "tool_gateway.call_failed", "tool_gateway.call_deferred", + ]) { + expect(formatActivityVerb(action, details)).not.toMatch(internalName); + } + }); + + it("keeps a readable name for other tools", () => { + expect(formatActivityVerb("tool_gateway.call_completed", { tool: "get_repository" })).toBe("used get repository on"); + expect(formatActivityVerb("tool_gateway.call_completed", { tool: "create_issue", toolTitle: "Create issue" })) + .toBe("used Create issue on"); + expect(formatActivityVerb("tool_gateway.call_denied", {})).toBe("was blocked from using an app action on"); + }); + + it("describes failed and delayed calls in words", () => { + const details = { upstreamToolName: "calendar__list_events" }; + expect(formatActivityVerb("tool_gateway.call_failed", details)).toBe("could not use Calendar: List events on"); + expect(formatActivityVerb("tool_gateway.call_deferred", details)).toBe("could not finish using Calendar: List events on"); + expect(formatActivityVerb("tool_gateway.call_deferred", { ...details, source: "test" })).toBe("could not finish testing Calendar: List events on"); + }); + + it("drops the connection namespace when a row has only the gateway tool name", () => { + const verb = formatActivityVerb("tool_gateway.call_failed", { tool: gatewayName, connectionId }); + expect(verb).toBe("could not use gmail get message on"); + expect(verb).not.toMatch(internalName); + }); + + it("drops the length-bound hash from a long gateway tool name", () => { + const verb = formatActivityVerb("tool_gateway.call_failed", { + tool: "mcp.app-gallery-github-connection:create-repository-0123456789abcdef", + connectionId, + }); + expect(verb).toBe("could not use create repository on"); + }); + + it("names a Google connection when its removal reports Google access", () => { + const providerAccess = { provider: "google", result: "ended", outcomes: [] }; + expect(formatActivityVerb("tool_connection.archived", { transport: "remote_http", providerAccess })).toBe("removed"); + expect(formatActivityEntityLabel("tool_connection", { providerAccess })).toBe("the Google Workspace connection"); + expect(formatActivityEntityLabel("tool_connection", { transport: "remote_http" })).toBe("the connection"); + expect(formatActivityOutcome("tool_connection.archived", { providerAccess })).toBeNull(); + }); + + it("reads app removal as a sentence with the app's name", () => { + const details = { type: "mcp", name: "Google Workspace", reason: "last_connection_removed" }; + expect(formatActivityVerb("tool_application.archived", details)).toBe("removed"); + expect(formatActivityEntityLabel("tool_application", details)).toBe("Google Workspace"); + expect(formatActivityOutcome("tool_application.archived", details)).toBe("Its last connection was removed."); + expect(formatActivityEntityLabel("tool_application", {})).toBe("the app"); + expect(formatActivityEntityLabel("heartbeat_run", {})).toBe("a run"); + expect(formatActivityEntityLabel("company", {})).toBe("the organization"); + }); + + it("describes stored content deletion in words", () => { + expect(formatActivityVerb("tool_connection.content_deletion_requested")).toBe("asked to delete stored content from"); + expect(formatActivityVerb("tool_connection.content_deleted")).toBe("deleted stored content from"); + expect(formatActivityVerb("issue.connection_content_deleted")).toBe("deleted connected app content from"); + expect(formatActivityVerb("issue.connection_content_deletion_incomplete")).toBe("partly deleted connected app content from"); + expect(formatIssueActivityAction("issue.connection_content_deleted")).toBe("deleted connected app content"); + expect(formatIssueActivityAction("issue.connection_content_deletion_incomplete")) + .toBe("partly deleted connected app content; some is still in use"); + }); + + it("reads connect and reconnect rows without internal names", () => { + expect(formatActivityVerb("tool_app.connected", { galleryKey: "google_workspace", applicationId: connectionId })).toBe("connected"); + expect(formatActivityVerb("tool_app.reconnected", { healthStatus: "healthy" })).toBe("reconnected"); + }); + }); }); diff --git a/ui/src/lib/activity-format.ts b/ui/src/lib/activity-format.ts index 79328fe10d5..ce2ba251886 100644 --- a/ui/src/lib/activity-format.ts +++ b/ui/src/lib/activity-format.ts @@ -1,4 +1,4 @@ -import type { Agent } from "@paperclipai/shared"; +import { googleWorkspaceToolTitle, type Agent } from "@paperclipai/shared"; import type { CompanyUserProfile } from "./company-members"; import { formatReviewPolicyValue } from "./review-policy"; @@ -132,6 +132,7 @@ const ACTIVITY_ROW_VERBS: Record = { "tool_app.oauth_access_finalized": "finished credential access for", "tool_app.finished": "finished setup for", "tool_app.reconnected": "reconnected", + "tool_application.archived": "removed", "tool_connection.created": "created", "tool_connection.updated": "updated", "tool_connection.archived": "removed", @@ -143,6 +144,10 @@ const ACTIVITY_ROW_VERBS: Record = { "tool_connection.grant_revoked": "revoked credentials from", "tool_connection.grant_delegated": "delegated credentials for", "tool_connection.grant_delegation_revoked": "revoked credential delegation for", + "tool_connection.content_deletion_requested": "asked to delete stored content from", + "tool_connection.content_deleted": "deleted stored content from", + "issue.connection_content_deleted": "deleted connected app content from", + "issue.connection_content_deletion_incomplete": "partly deleted connected app content from", }; const ISSUE_ACTIVITY_LABELS: Record = { @@ -212,8 +217,53 @@ const ISSUE_ACTIVITY_LABELS: Record = { "issue.thread_interaction_expired": "expired the request", "issue.thread_interaction_item_verdicts_submitted": "submitted verdicts on the request", "issue.stalled_review_decided": "recorded a review verdict", + "issue.connection_content_deleted": "deleted connected app content", + "issue.connection_content_deletion_incomplete": "partly deleted connected app content; some is still in use", }; +const ENTITY_LABELS: Record = { + company: "the organization", + agent: "an agent", + goal: "a goal", + project: "a project", + routine: "a routine", + heartbeat_run: "a run", + approval: "an approval", + tool_connection: "the connection", + tool_application: "the app", +}; + +function readText(value: unknown): string | null { + return typeof value === "string" && value.trim() ? value.trim() : null; +} + +function googleProviderAccessResult(details: ActivityDetails): string | null { + const access = asRecord(details?.providerAccess); + return access?.provider === "google" ? readText(access.result) : null; +} + +function formatToolLabel(details: ActivityDetails): string { + const name = readText(details?.upstreamToolName) + ?? readText(details?.tool)?.replace(/^(?:mcp|app)\.[^:]*:|^(?:mcp|app)\.[a-z0-9-]*-[0-9a-f]{8}\./, "").replace(/-[0-9a-f]{16}$/, ""); + const title = readText(details?.toolTitle); + if (!name) return title ?? "an app action"; + return googleWorkspaceToolTitle(name, title) ?? name.replace(/[._-]+/g, " "); +} + +export function formatActivityEntityLabel(entityType: string, details?: Record | null): string { + const name = readText(details?.name); + if (entityType === "tool_application" && name) return name; + if (entityType === "tool_connection" && googleProviderAccessResult(details)) return "the Google Workspace connection"; + return ENTITY_LABELS[entityType] ?? entityType.replace(/[._]+/g, " "); +} + +export function formatActivityOutcome(action: string, details?: Record | null): string | null { + if (action === "tool_application.archived" && details?.reason === "last_connection_removed") { + return "Its last connection was removed."; + } + return null; +} + /** * `issue.stalled_review_decided` carries the verb the actor chose, so the line * names the verdict ("approved the review") rather than the generic action. @@ -471,17 +521,14 @@ export function formatActivityVerb( options: ActivityFormatOptions = {}, ): string { if (action.startsWith("tool_gateway.")) { - const rawTool = typeof details?.tool === "string" - ? details.tool - : typeof details?.upstreamToolName === "string" - ? details.upstreamToolName - : "an app action"; - const tool = rawTool.replace(/[._-]+/g, " "); + const tool = formatToolLabel(details); const isTest = details?.source === "test"; if (action === "tool_gateway.call_completed") return `${isTest ? "tested" : "used"} ${tool} on`; if (action === "tool_gateway.call_allowed") return `${isTest ? "started a test of" : "was allowed to use"} ${tool} on`; if (action === "tool_gateway.call_denied") return `was blocked from using ${tool} on`; if (action === "tool_gateway.approval_requested") return `asked to use ${tool} on`; + if (action === "tool_gateway.call_failed") return `could not ${isTest ? "test" : "use"} ${tool} on`; + if (action === "tool_gateway.call_deferred") return `could not finish ${isTest ? "testing" : "using"} ${tool} on`; if (action === "tool_gateway.session_created") return "opened an app session for"; if (action === "tool_gateway.session_rejected") return "was blocked from opening an app session for"; if (action === "tool_gateway.discovery") return "discovered app actions for"; diff --git a/ui/src/pages/apps/AppsConnect.test.tsx b/ui/src/pages/apps/AppsConnect.test.tsx index ea1af85bb4b..9bae807e0ed 100644 --- a/ui/src/pages/apps/AppsConnect.test.tsx +++ b/ui/src/pages/apps/AppsConnect.test.tsx @@ -1740,6 +1740,62 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => { expect(mockNavigate).not.toHaveBeenCalledWith("/apps/connect", { replace: true }); }); + it("offers a retry, not Cloud registration, when Paperclip could not reach Cloud to check GitHub sign-in", async () => { + // Production Cloud workspaces hit this when the broker rate-limited the + // status check: registration cannot succeed there and only looked broken. + mockParams.appKey = "github"; + listGalleryMock.mockResolvedValue({ apps: [customerOwnedApp(GITHUB)] }); + getCloudConnectorEnrollmentMock.mockResolvedValue({ + configured: false, + status: "unreachable", + brokerBaseUrl: "https://my.paperclip.app", + instanceId: "stack-test", + environment: "production", + origins: ["https://paperclip.example.test"], + }); + + await render(); + await passAccessStep(); + + expect(container.textContent).not.toContain("You must connect this instance to Paperclip"); + expect(buttonByText("Connect with Paperclip")).toBeFalsy(); + expect(container.textContent).toContain("Paperclip couldn’t reach Paperclip Cloud to start GitHub sign-in. Try again in a moment."); + const calls = getCloudConnectorEnrollmentMock.mock.calls.length; + getCloudConnectorEnrollmentMock.mockResolvedValue(activeConnectorEnrollment()); + await act(async () => { + buttonByText("Try again")?.dispatchEvent(new MouseEvent("click", { bubbles: true })); + }); + await flushReact(); + expect(getCloudConnectorEnrollmentMock.mock.calls.length).toBeGreaterThan(calls); + expect(startCloudConnectorEnrollmentMock).not.toHaveBeenCalled(); + }); + + it("asks for an administrator, not registration, when managed Cloud settings are incomplete", async () => { + mockParams.appKey = "github"; + listGalleryMock.mockResolvedValue({ apps: [customerOwnedApp(GITHUB)] }); + getCloudConnectorEnrollmentMock.mockResolvedValue({ ...unconfiguredConnectorEnrollment(), status: "misconfigured" }); + + await render(); + await passAccessStep(); + + expect(container.textContent).not.toContain("You must connect this instance to Paperclip"); + expect(container.textContent).toContain("Ask your instance administrator to finish the Paperclip Cloud settings."); + }); + + it("keeps Cloud registration available when the local Cloud identity is unverified", async () => { + // "unverified" is a local identity problem (for example a saved identity + // for another broker); registering again fixes it, a retry does not. + mockParams.appKey = "github"; + listGalleryMock.mockResolvedValue({ apps: [customerOwnedApp(GITHUB)] }); + getCloudConnectorEnrollmentMock.mockResolvedValue({ ...unconfiguredConnectorEnrollment(), status: "unverified" }); + + await render(); + await passAccessStep(); + + expect(container.textContent).toContain("You must connect this instance to Paperclip to connect to GitHub"); + expect(container.textContent).not.toContain("couldn’t reach Paperclip Cloud"); + }); + it("prompts for one-time Cloud registration inside Gmail when managed methods are not yet advertised", async () => { mockParams.appKey = "gmail"; listGalleryMock.mockResolvedValue({ @@ -5118,6 +5174,30 @@ describe("AppsConnect — guided generic MCP flow (PAP-17087)", () => { expect(navigateTopLevelMock).not.toHaveBeenCalled(); }); + it("shows why a client is needed when the deployment's sign-in app cannot be used", async () => { + const reason = "The sign-in app set up for this Paperclip server can only be used with the app it was set up for. Add a client ID and secret for this server to the connection, then sign in again."; + connectAppMock.mockResolvedValue({ + connectionId: "conn-1", + application: { id: "app-1", name: "mcp.example.test" }, + actions: { readOnly: [], canMakeChanges: [] }, + catalog: [], + suggestedDefaults: {}, + auth: { kind: "oauth", startUrl: null, manualClientRequired: true, manualClientReason: reason }, + }); + await render(); + await gotoLinkFrame(container, "https://mcp.example.test/mcp"); + await act(async () => { + buttonByText("Check link")?.dispatchEvent(new MouseEvent("click", { bubbles: true })); + }); + await flushReact(); + await flushReact(); + + expect(container.textContent).toContain(reason); + expect(container.textContent).toContain("Client ID"); + expect(container.textContent).toContain("Client secret"); + expect(navigateTopLevelMock).not.toHaveBeenCalled(); + }); + it("submits custom headers as secret-backed credential values", async () => { await render(); await gotoLinkFrame(container, "https://mcp.example.test/mcp"); diff --git a/ui/src/pages/apps/Browse.test.tsx b/ui/src/pages/apps/Browse.test.tsx index 800140377fd..c7eb3dad542 100644 --- a/ui/src/pages/apps/Browse.test.tsx +++ b/ui/src/pages/apps/Browse.test.tsx @@ -332,6 +332,15 @@ describe("Connectors landing page", () => { expect(container.querySelector('[data-app-slug="openai"]')).toBeNull(); }); + it("titles the Google AI connector after Antigravity and Gemini", async () => { + listGalleryMock.mockResolvedValue({ apps: [getAppStoreDefinition("google")] }); + await renderBrowse(false); + const google = container.querySelector('[data-app-slug="google"]'); + expect(google?.querySelector("h2")?.textContent).toBe("Google Antigravity and Gemini"); + expect(google?.textContent).toContain("Connect Google Antigravity accounts or Gemini API keys for your agents."); + expect(container.querySelector('[aria-label="Connect Google Antigravity and Gemini"]')).not.toBeNull(); + }); + it("does not advertise Tailscale setup or request tailnets for non-instance-admin members", async () => { boardAccessMock.mockResolvedValue({ source: "session", isInstanceAdmin: false }); await renderBrowse(false); diff --git a/ui/src/pages/apps/Connections.test.tsx b/ui/src/pages/apps/Connections.test.tsx index c88424abfc0..23dc14e6566 100644 --- a/ui/src/pages/apps/Connections.test.tsx +++ b/ui/src/pages/apps/Connections.test.tsx @@ -200,6 +200,53 @@ describe("Connections table (M1b / PAP-13254 door 2)", () => { await flushReact(); } + it("checks an unreachable Cloud again until it answers", async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + try { + getCloudConnectorEnrollmentMock.mockResolvedValue({ + configured: false, + status: "unreachable", + brokerBaseUrl: "https://my.paperclip.app", + instanceId: "instance-test", + environment: "production", + origins: [], + }); + await renderApps(); + expect(container.textContent).toContain("Paperclip couldn’t reach Paperclip Cloud."); + getCloudConnectorEnrollmentMock.mockResolvedValue({ + configured: true, + status: "active", + brokerBaseUrl: "https://my.paperclip.app", + instanceId: "instance-test", + environment: "production", + origins: [], + }); + await act(async () => { await vi.advanceTimersByTimeAsync(15_100); }); + await flushReact(); + expect(container.textContent).toContain("Paperclip-managed sign-in is ready"); + } finally { + vi.useRealTimers(); + } + }); + + it.each([ + ["unreachable", "Paperclip couldn’t reach Paperclip Cloud."], + ["misconfigured", "Paperclip Cloud settings on this instance are incomplete."], + ])("does not offer enrollment when the Cloud status is %s", async (status, message) => { + getCloudConnectorEnrollmentMock.mockResolvedValue({ + configured: false, + status, + brokerBaseUrl: "https://my.paperclip.app", + instanceId: status === "unreachable" ? "instance-test" : null, + environment: "production", + origins: [], + }); + await renderApps(); + expect(container.textContent).toContain(message); + expect(container.textContent).not.toContain("Enable Paperclip-managed sign-in"); + expect([...container.querySelectorAll("button")].some((button) => button.textContent === "Enable")).toBe(false); + }); + it("renders applications without connections as not connected with a Connect action", async () => { listApplicationsMock.mockResolvedValue({ applications: [application({ id: "app-github", name: "GitHub" })], diff --git a/ui/src/pages/apps/Connections.tsx b/ui/src/pages/apps/Connections.tsx index 846d98979a5..645fa088cb5 100644 --- a/ui/src/pages/apps/Connections.tsx +++ b/ui/src/pages/apps/Connections.tsx @@ -166,6 +166,9 @@ export function Connections() { const connectorEnrollmentQuery = useQuery({ queryKey: ["cloud-connector", "enrollment"], queryFn: () => toolsApi.getCloudConnectorEnrollment(), + // An unanswered Cloud check is a successful response, so query retries do + // not run; check again on a timer until Cloud answers. + refetchInterval: (query) => query.state.data?.status === "unreachable" ? CLOUD_RECHECK_INTERVAL_MS : false, }); const authorization = useAuthorizationWindow(); const galleryView = useQueryView(galleryQuery); @@ -583,6 +586,8 @@ export function Connections() { ); } +const CLOUD_RECHECK_INTERVAL_MS = 15_000; + function CloudConnectorEnrollmentBanner({ status, unavailable, @@ -607,11 +612,19 @@ function CloudConnectorEnrollmentBanner({ ); } - if (unavailable) { + // Neither state can be fixed by enrolling: Cloud did not answer, or the + // managed settings are incomplete and only an administrator can finish them. + if (unavailable || status?.status === "unreachable" || status?.status === "misconfigured") { return (
-
Paperclip Cloud enrollment status is unavailable.
+
+ {status?.status === "unreachable" + ? "Paperclip couldn’t reach Paperclip Cloud. Managed sign-in will be checked again shortly." + : status?.status === "misconfigured" + ? "Paperclip Cloud settings on this instance are incomplete. Ask your instance administrator to finish them." + : "Paperclip Cloud enrollment status is unavailable."} +
); } diff --git a/ui/src/pages/audit/AuditFeed.test.tsx b/ui/src/pages/audit/AuditFeed.test.tsx index b3ee572d9c0..c76b0f0efc4 100644 --- a/ui/src/pages/audit/AuditFeed.test.tsx +++ b/ui/src/pages/audit/AuditFeed.test.tsx @@ -246,6 +246,68 @@ describe("AuditFeed", () => { expect(container.textContent).toContain("tool_gateway.call_completed"); }); + it("shows connected Google activity as plain sentences without internal names or IDs", async () => { + const connectionId = "7f3c2a10-5b4e-4d2a-9c1f-0e8d6b5a4c3d"; + const applicationId = "1b2c3d4e-5f60-4718-8293-a4b5c6d7e8f9"; + const google = { tool: "mcp.google-workspace-7f3c2a10:gmail-get-message", upstreamToolName: "gmail__get_message", connectionId, applicationId }; + const providerAccess = { provider: "google", result: "ended", outcomes: ["revoked"] }; + const row = (id: string, overrides: Record) => record({ + id, actorType: "user", actorId: "user-1", agentId: null, runId: null, responsibleUserId: null, + entityType: "tool_connection", entityId: connectionId, + entity: { issue: null, comment: null, document: null }, ...overrides, + }); + listAgentActionsMock.mockResolvedValue({ + items: [ + row("evt-used", { actorType: "agent", actorId: "agent-1", agentId: "agent-1", action: "tool_gateway.call_completed", entityType: "agent", entityId: "agent-1", details: google }), + row("evt-denied", { actorType: "agent", actorId: "agent-1", agentId: "agent-1", action: "tool_gateway.call_denied", entityType: "agent", entityId: "agent-1", details: { ...google, decision: "deny", reasonCode: "policy_denied" } }), + row("evt-held", { actorType: "agent", actorId: "agent-1", agentId: "agent-1", action: "tool_gateway.approval_requested", entityType: "agent", entityId: "agent-1", details: { ...google, decision: "require_approval" } }), + row("evt-connected", { action: "tool_app.connected", details: { galleryKey: "google_workspace", applicationId } }), + row("evt-reconnected", { action: "tool_app.reconnected", details: { healthStatus: "healthy" } }), + row("evt-removed", { action: "tool_connection.archived", details: { transport: "remote_http", grantsRevoked: 1, providerAccess } }), + row("evt-app-removed", { action: "tool_application.archived", entityType: "tool_application", entityId: applicationId, details: { type: "mcp", name: "Google Workspace", reason: "last_connection_removed" } }), + row("evt-content-requested", { action: "tool_connection.content_deletion_requested", details: { toolCalls: 3 } }), + row("evt-content-deleted", { actorType: "system", actorId: null, action: "tool_connection.content_deleted", details: { toolCalls: 3 } }), + row("evt-failed", { actorType: "agent", actorId: "agent-1", agentId: "agent-1", action: "tool_gateway.call_failed", entityType: "agent", entityId: "agent-1", details: { tool: google.tool, connectionId, reasonCode: "prompt_injection_blocked" } }), + row("evt-credential-revoked", { action: "tool_connection.grant_revoked", details: { connectionId, kind: "oauth", providerAccess: { provider: "google", result: "not_ended", outcomes: ["broker_error"] } } }), + ], + nextCursor: null, + accessTier: "full", + }); + + await render({ actionDomain: "tool_" }); + + const rows = Array.from(container.querySelectorAll('ul[aria-label="Audit activity"] > li')); + expect(rows).toHaveLength(11); + const primary = rows.map((li) => { + const copy = li.cloneNode(true) as HTMLElement; + copy.querySelectorAll(".font-mono, time").forEach((node) => node.remove()); + const walker = document.createTreeWalker(copy, NodeFilter.SHOW_TEXT); + const parts: string[] = []; + while (walker.nextNode()) parts.push(walker.currentNode.textContent ?? ""); + return parts.join(" ").replace(/\s+/g, " "); + }); + for (const text of primary) { + expect(text).not.toMatch(/__|[a-z]_[a-z]|[0-9a-f]{8}-[0-9a-f]{4}|7f3c2a10/i); + } + expect(primary[0]).toContain("used Gmail: Get message on"); + expect(primary[1]).toContain("was blocked from using Gmail: Get message on"); + expect(primary[2]).toContain("asked to use Gmail: Get message on"); + expect(primary[3]).toContain("connected the connection"); + expect(primary[4]).toContain("reconnected the connection"); + expect(primary[5]).toContain("removed the Google Workspace connection"); + expect(primary[5]).toContain("Paperclip's access to this Google account was also ended at Google."); + expect(primary[6]).toContain("removed Google Workspace"); + expect(primary[6]).toContain("Its last connection was removed."); + expect(primary[7]).toContain("asked to delete stored content from the connection"); + expect(primary[8]).toContain("deleted stored content from the connection"); + expect(primary[9]).toContain("could not use gmail get message on the connection"); + expect(primary[10]).toContain("revoked credentials from the Google Workspace connection"); + expect(primary[10]).toContain("couldn't end its access at Google"); + expect(primary[10]).toContain("Paperclip removed the credentials"); + expect(primary[10]).not.toContain("removed the connection but"); + expect(rows[0].textContent).toContain("tool_gateway.call_completed"); + }); + it("shows case history with case links and the acting agent's avatar", async () => { listAgentActionsMock.mockResolvedValue({ items: [record({ diff --git a/ui/src/pages/audit/AuditFeed.tsx b/ui/src/pages/audit/AuditFeed.tsx index 482e9c5097f..b84f92fbffc 100644 --- a/ui/src/pages/audit/AuditFeed.tsx +++ b/ui/src/pages/audit/AuditFeed.tsx @@ -2,7 +2,7 @@ import { AgentAvatar } from "@/components/AgentAvatar"; import { useEffect, useMemo, useState } from "react"; import { useInfiniteQuery, useQuery } from "@tanstack/react-query"; import { Download, ScrollText, ShieldAlert } from "lucide-react"; -import type { Agent, CaseWorkflowTransition } from "@paperclipai/shared"; +import type { Agent, CaseWorkflowTransition, ManagedGoogleAccessRemoval } from "@paperclipai/shared"; import { Link, useCaseHref } from "@/lib/router"; import { Button } from "@/components/ui/button"; import { Card, CardContent } from "@/components/ui/card"; @@ -18,7 +18,7 @@ import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Identity } from "@/components/Identity"; import { cn, relativeTime } from "@/lib/utils"; import { queryKeys } from "@/lib/queryKeys"; -import { formatActivityVerb } from "@/lib/activity-format"; +import { formatActivityEntityLabel, formatActivityOutcome, formatActivityVerb } from "@/lib/activity-format"; import { buildCompanyUserProfileMap, type CompanyUserProfile } from "@/lib/company-members"; import { auditApi, type AuditActionRecord, type AuditActionFilters } from "@/api/audit"; import { agentsApi } from "@/api/agents"; @@ -28,6 +28,7 @@ import { describeError } from "@/api/errors"; import { QueryErrorState, useQueryView } from "@/components/QueryView"; import { useToastActions } from "@/context/ToastContext"; import { instanceSettingsApi } from "@/api/instanceSettings"; +import { googleAccessRemovalNotice } from "@/features/connections/googleAccessRemoval"; const PAGE_SIZE = 50; const ALL = "__all"; @@ -200,12 +201,22 @@ function AuditEntityNode({ record }: { record: AuditActionRecord }) { if (connectionId) { return ( - the connection + {formatActivityEntityLabel("tool_connection", record.details)} ); } // Non-linkable entities (company, agent, goal, …) — show a plain descriptor. - return {record.entityType}; + return {formatActivityEntityLabel(record.entityType, record.details)}; +} + +function auditOutcome(record: AuditActionRecord): string | null { + if (record.action === "tool_connection.archived" || record.action === "tool_connection.grant_revoked") { + return googleAccessRemovalNotice( + record.details?.providerAccess as ManagedGoogleAccessRemoval | undefined, + record.action === "tool_connection.grant_revoked" ? "credentials" : "connection", + )?.body ?? null; + } + return formatActivityOutcome(record.action, record.details); } function AuditRow({ @@ -220,6 +231,7 @@ function AuditRow({ casesEnabled: boolean; }) { const verb = formatActivityVerb(record.action, record.details, { agentMap, userProfileMap }); + const outcome = auditOutcome(record); const responsible = record.responsibleUserId ? userProfileMap.get(record.responsibleUserId) : null; // Suppress the "on behalf of" chip when the human actor *is* the responsible user. const showOnBehalf = Boolean( @@ -242,6 +254,7 @@ function AuditRow({ {verb} + {outcome ?

{outcome}

: null} {excerpt ? (

“{excerpt}” diff --git a/ui/src/pages/tools/PasteConfigTab.tsx b/ui/src/pages/tools/PasteConfigTab.tsx index 5085183ad19..037dcef9a13 100644 --- a/ui/src/pages/tools/PasteConfigTab.tsx +++ b/ui/src/pages/tools/PasteConfigTab.tsx @@ -205,7 +205,8 @@ export function PasteConfigTab({ companyId }: { companyId: string }) { authorization.cancel(); setOAuthPhase("error"); setOAuthError( - "This server requires OAuth client details from its provider settings. Continue in setup to add them.", + result.auth.manualClientReason + ?? "This server requires OAuth client details from its provider settings. Continue in setup to add them.", ); return; }