From ba1b0585bcefca4f00a6f88f63b9e5fdff02d3bd Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:41:15 -0600 Subject: [PATCH 01/19] fix(server): send deployment OAuth client secrets only to the token endpoint they are configured for (#22649) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - App connections sign in with OAuth, and an operator can set a deployment-wide OAuth client with `PAPERCLIP_TOOL_OAUTH_*` variables > - The server picked that client by a provider name, and a connection's own settings could set both the provider name and the token URL > - So a deployment client secret could go to a token URL that the deployment did not choose > - A deployment secret must go only to the endpoint of the app it was set up for > - This pull request pins each deployment client to the token endpoint that its app definition fixes, and fails closed for any other endpoint > - The benefit is that member-entered or custom endpoints get only a member-entered client ## Linked Issues or Issue Description Refs #22635 **What happened?** `configuredOAuthClientForConnection` returned the deployment client for any connection whose provider name matched, or the unsuffixed client for any connection. The token exchange then sent that client secret to the connection's token URL. **What did you expect to happen?** A deployment client goes only to the token endpoint that its app definition fixes. A custom endpoint needs a client that the member adds. **Steps to reproduce** Set a provider-specific deployment client. Create a custom connection that names that provider and a different token URL, and start sign-in. The new unit tests cover this case. **Impact** Secret-handling hardening for deployment OAuth clients. ## What Changed - `configuredOAuthClientForConnection` now takes the token URL that the caller will post to. It returns a deployment client only when the connection comes from a real app definition, the provider is that app, the method lists `customer` ownership, and the token URL equals the method's `defaults.tokenEndpoint` (or, when the method fixes no token endpoint, is on the exact host of its fixed server, discovery, metadata or authorization URL). - A pasted (custom) server never gets a deployment client, including the unsuffixed one. It needs a client of its own, or CIMD or dynamic registration. - The token URL is required at every call site: start, callback, connection refresh and grant refresh. - When a deployment client exists but the endpoint does not match, and the connection has no client of its own, sign-in fails with `oauth_instance_client_endpoint_mismatch` and a clear message. - Pin `defaults.tokenEndpoint` in the Asana and Railway definitions, whose token endpoints are on another host than their MCP servers. - Update `doc/connections/GENERIC-REMOTE-MCP.md` and `doc/connections/CONNECTOR-PLAYBOOK.md`. ## Verification - New `server/src/services/tool-access/oauth/client-settings.test.ts` (16 tests): other hosts, a path that resolves elsewhere, plain HTTP, vendor subdomains, another port, a missing URL, empty or padded gallery markers, colliding host names, a custom connection that names a provider, the unsuffixed client on a custom connection, and a connection that names another app's provider all get no deployment client. Slack's fixed endpoint, Notion's server host and the pinned Asana and Railway endpoints still get it. These cases failed before the fix and pass now. - `server/src/__tests__/generic-mcp-connection.test.ts` and the machine-to-machine test in `tool-access-service.test.ts` now check that a pasted server never receives the deployment client or secret. Both failed before the fix. Two other pasted-server tests now use a client of their own. - A positive test sends the Slack deployment client to Slack's pinned token endpoint, with its secret, and nowhere else. - The connect route keeps the draft and returns `manualClientRequired` with a plain reason when a deployment client cannot be used (route and UI tests). - `npx vitest run` on the OAuth service and connection tests: 686 tests pass. Shared app-definition tests pass. `tsc --noEmit` for `server` passes. - `pnpm verify` exits 2 because a global CI input (a doc) changed. Required CI gives the broad coverage. ## Risks - A self-hosted deployment that used `PAPERCLIP_TOOL_OAUTH_*` for a pasted server must add a client to that connection. Sign-in shows a clear error instead of sending the secret. - A gallery app with `customer` ownership whose token endpoint is on another host than its fixed URLs needs `defaults.tokenEndpoint` to keep using a deployment client. Asana and Railway are pinned here. Box, Notion, PostHog, Sentry and Xero rely on the same-host rule: 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. A test lists these apps by name, so a new app must choose. Gallery apps with a fixed token endpoint (Slack, Linear, Google) do not change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- doc/connections/CONNECTOR-PLAYBOOK.md | 12 +- doc/connections/GENERIC-REMOTE-MCP.md | 6 +- .../shared/src/app-definitions/asana.json | 1 + .../shared/src/app-definitions/railway.json | 3 +- packages/shared/src/types/tool-access.ts | 2 + scripts/ingest-app-definitions.mjs | 2 + .../__tests__/generic-mcp-connection.test.ts | 47 +++++- .../src/__tests__/tool-access-service.test.ts | 132 +++++++-------- server/src/routes/tool-access.ts | 7 +- .../tool-access/oauth/client-registration.ts | 15 +- .../tool-access/oauth/client-settings.test.ts | 150 ++++++++++++++++++ .../tool-access/oauth/client-settings.ts | 61 ++++++- .../tool-access/oauth/connection-refresh.ts | 1 + .../tool-access/oauth/credential-store.ts | 13 +- .../tool-access/oauth/direct-callback.ts | 1 + .../tool-access/oauth/grant-refresh.ts | 1 + .../runner-e2e/source-sdk-public-inputs.json | 6 +- .../connections/ConnectionSetupFlow.tsx | 3 +- ui/src/pages/apps/AppsConnect.test.tsx | 24 +++ ui/src/pages/tools/PasteConfigTab.tsx | 3 +- 20 files changed, 394 insertions(+), 96 deletions(-) create mode 100644 server/src/services/tool-access/oauth/client-settings.test.ts 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/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/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/types/tool-access.ts b/packages/shared/src/types/tool-access.ts index dd1cfc8b5e3..0827fd3cfc6 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. */ 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/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__/tool-access-service.test.ts b/server/src/__tests__/tool-access-service.test.ts index 8aac435e157..dad5e4c1922 100644 --- a/server/src/__tests__/tool-access-service.test.ts +++ b/server/src/__tests__/tool-access-service.test.ts @@ -12017,14 +12017,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 +12076,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 +15239,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 +15300,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 +17240,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 +17302,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/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/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/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index b8997d084a3..f5711f2796e 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", @@ -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", @@ -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": "0827fd3cfc63431077aef0cedc42bc7709957f57", "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/features/connections/ConnectionSetupFlow.tsx b/ui/src/features/connections/ConnectionSetupFlow.tsx index c45cd32ec05..e4a81a937a1 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); diff --git a/ui/src/pages/apps/AppsConnect.test.tsx b/ui/src/pages/apps/AppsConnect.test.tsx index ea1af85bb4b..b2c74ff24f9 100644 --- a/ui/src/pages/apps/AppsConnect.test.tsx +++ b/ui/src/pages/apps/AppsConnect.test.tsx @@ -5118,6 +5118,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/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; } From ffb300e22a4101a94feab25d04cd7b38d2952818 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:50:27 -0600 Subject: [PATCH 02/19] fix(cloud): name a failed durable-data check instead of answering the eligibility read with 500 (#22646) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A hosted server moves from a volume to a volume-free shape without an outage > - Before the move, Cloud reads `GET /api/instance/ephemeral-enrollment/eligibility`, and the stack moves only when the read has no blockers > - On two staging stacks the read answers HTTP 500, so Cloud shows only "eligibility unavailable: HTTP 500" > - Each durable-data check in the read can throw, and one throw fails the whole read without a reason > - This pull request makes each check that throws report a named blocker with the owner's code > - The benefit is that a stack that cannot move always says which check stopped it and why ## Linked Issues or Issue Description Refs #22240, #22294, #22337 **What happened?** On current Core, the eligibility read answers HTTP 500 for some hosted stacks. The online durable-data pass also fails, because it reads the same eligibility at the end of each pass. **Expected behavior** The read always answers. When a check cannot finish, the read reports a named blocker, and the move stays blocked. **Steps to reproduce** 1. Keep a failed Runner run whose session is selected and whose local controller file has a second hard link (or another source that the controller check refuses, such as an execution input that no longer parses). 2. Call `readOnlineEphemeralEnrollmentEligibility`. 3. See that it throws `native_controller_migration_unsafe_source`. The route answers 500. **Additional context** Every check in `readEphemeralServerDataEligibility` can throw: the native controller scan reads files and parses saved execution input, the harness scan reads files, and the other checks query the database. The controller scan is the first one that throws on old Runner state. ## What Changed - `readEphemeralServerDataEligibility` runs each check through one guard. A check that throws adds `_check_failed`, plus `:` when the error message is a code such as `native_controller_migration_unsafe_source`. The guard logs the error. - The same blockers reach the startup gate, the offline migration and online preparation. Each of them still refuses, as before, but now with the named blocker instead of the raw error. ## Verification - Red: `cd server && npx vitest run src/services/native-runtime/native-controller-migration.integration.test.ts -t eligibility_unreadable` failed with `Error: native_controller_migration_unsafe_source` thrown from `readEphemeralServerDataEligibility` (embedded PostgreSQL, real controller file with a second hard link). - Green: the same test passes. The read returns `native_controllers_check_failed:native_controller_migration_unsafe_source`, the online read returns `eligible: false` with that blocker, and the controller file is unchanged. - `npx vitest run src/__tests__/ephemeral-server-data.test.ts src/services/ephemeral-enrollment.test.ts src/__tests__/runtime-skill-preservation.test.ts` and the `volume_free_owner` controller scenario pass. - `pnpm --filter @paperclipai/server typecheck` passes. - `pnpm verify` result is in a comment below. ## Risks - Low risk. A check that throws still blocks the move, the startup gate and the offline migration. Only the shape of the refusal changes: a named blocker instead of an exception. - Cloud receives new blocker names of the form `_check_failed[:code]`. Cloud shows unknown blockers as they are and does not move the stack. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../src/services/ephemeral-server-contract.ts | 93 ++++++++++++------- ...e-controller-migration.integration.test.ts | 26 +++++- 2 files changed, 85 insertions(+), 34 deletions(-) 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/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"); From 574448e9105105effe2834310384f9007a3e293d Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:50:38 -0600 Subject: [PATCH 03/19] fix(server): apply the issue interaction resolution policy to direct tool review decisions (#22656) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - When an agent's tool call needs review, Paperclip creates a tool action request and an approval card on the task > - A person can decide it on the card (the issue thread path) or through `POST /api/tool-gateway/action-requests/:id/approve|decline` > - The issue thread path applies the interaction resolution policy, but the direct routes checked only company membership > - So the two paths could give different answers for the same review, for example in another member's private chat > - This pull request puts the human rule for tool reviews in one shared function and applies it to every human decision on a pending review > - The benefit is that the direct routes and the card always agree on who can decide a tool review ## Linked Issues or Issue Description Refs #22635 **What happened?** The direct approve and decline routes for tool action requests skipped the issue-interaction resolution policy. A member could decide a tool review that the issue thread path refuses, for example a review in a chat conversation that another member owns. **What did you expect to happen?** Both paths use the same policy and give the same result. **Steps to reproduce** Open a chat conversation as one member, let the agent request a reviewed tool call, then approve it through the direct route as a different member. The new test covers this case. **Impact** Access-control hardening for tool reviews. ## What Changed - Add `evaluateHumanToolReviewResolution`, `assertHumanToolReviewResolution` and `conversationInteractionResponderAllowed` to `server/src/services/issue-thread-interaction-resolution.ts`. The rule applies the personal-conversation visibility rule, the conversation owner rule and the existing audience evaluator (`evaluateIssueThreadInteractionResolverAudience`, as a governed action). - `commitToolActionReview` applies this rule inside its decision transaction, on the issue and interaction rows it already locks. Both the issue thread path and the direct routes reach it, so one rule decides for both. - The direct approve and decline routes call the same rule function first, for pending and settled reviews, before any state change or detail is returned (for example a cancelled request after a signature failure, expiry, or formal approval details). The in-transaction check stays the authoritative one. - A settled request with no task or interaction can be read only by the person who requested it; others get `404`. Only the explicit internal recovery flag skips the check. - A decision with no user identity is refused with `human_review_required`; the code no longer substitutes a placeholder identity. - The issue thread route uses `conversationInteractionResponderAllowed` for its existing conversation owner check. - Recovery of an already approved review passes an explicit internal flag and skips the human check, so interrupted executions still resume with no user action. ## Verification - New table test in `server/src/__tests__/tool-gateway.test.ts` mounts the real issue routes and the gateway routes on one database, for a chat owned by one member, a personal dashboard conversation and an ordinary task. For approve and decline it compares both paths for the owner and another member. It also checks settled reviews through the direct route, the recovery of an approved review, that a non-owner cannot cancel a review with an unverifiable signature or see expiry details, that a decision without a user is refused, and that a detached settled request is visible only to its requester. Before the fix the direct route let the other member approve a chat review and the action ran (`200`, `executed`). After the fix both paths refuse the other member for chats (`403`) and personal dashboards (`404`), both allow the other member for ordinary tasks, and both allow the owner. - `npx vitest run` on `tool-gateway`, `issue-thread-interaction-routes`, `agent-conversations`, `connection-management.integration`, `mcp-tasks` and `prompt-injection-gateway`: 497 tests pass. - `tsc --noEmit` for `server` passes. ## Risks - A member who is not the owner of a private chat can no longer approve or decline its tool reviews through the direct routes. The card already refused this. - Low risk otherwise. Ordinary task reviews have no addressee and stay open to non-viewer members, as before. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- server/src/__tests__/tool-gateway.test.ts | 143 ++++++++++++++++++ server/src/routes/issues.ts | 3 +- .../issue-thread-interaction-resolution.ts | 51 +++++++ server/src/services/tool-action-review.ts | 24 +-- server/src/services/tool-gateway.ts | 48 +++++- 5 files changed, 256 insertions(+), 13 deletions(-) diff --git a/server/src/__tests__/tool-gateway.test.ts b/server/src/__tests__/tool-gateway.test.ts index 3135bd8010e..1e763874195 100644 --- a/server/src/__tests__/tool-gateway.test.ts +++ b/server/src/__tests__/tool-gateway.test.ts @@ -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, @@ -5739,6 +5741,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/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/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/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..508fca57d1d 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -264,6 +264,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, @@ -2233,6 +2234,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; @@ -12726,7 +12762,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 +12784,7 @@ export function createToolGatewayService( async approveActionRequest(input: { companyId: string; + recoveringApprovedReview?: boolean; rememberAction?: boolean; issueId?: string; interactionId?: string; @@ -12772,6 +12809,7 @@ export function createToolGatewayService( "action_request_not_found", ); } + if (!input.recoveringApprovedReview) await assertHumanMayActOnToolReview(actionRequest, input.actor.userId); const [invocation] = await db .select() .from(toolInvocations) @@ -13048,6 +13086,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", From 949bc3765c28df63aadfd0a22807bad75ae5b5ca Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:51:32 -0600 Subject: [PATCH 04/19] fix(cloud): preserve a settled harness backup whose session is not selected, as offline does (#22647) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A hosted server copies its Runner harness backups to shared storage before it moves to a volume-free shape > - The online pass copies a settled backup only when exactly one task session selects the backup's native session > - Some stacks stay blocked with `native_harness:source_session_not_selected`, but the offline migration publishes the same backup > - A selected session whose backup source is not on the disk is reported with no code at all > - This pull request applies the offline outcome online with a selection fence, and names the missing-source case > - The benefit is that these stacks can move, and the native harness blocker always says why it remains ## Linked Issues or Issue Description Refs #19715, #22294 **What happened?** On staging, two stacks stay ineligible with `native_harness_backups_require_migration`. Each online pass defers one backup as `native_harness:source_session_not_selected`. That code means that no task session, or more than one, points at the backup's native session. **Expected behavior** The online pass gives a settled backup the same outcome as the offline migration. The offline migration publishes the backup whether or not a session selects it. **Steps to reproduce** 1. Keep a sealed backup of a failed native run with a settled coordinator and a verified lease stamp. 2. Delete the task session that selects it (or add a second one for the same native session). 3. Run the online pre-copy. It defers the backup as `source_session_not_selected`. The offline migration publishes it. **Additional context** The selection check exists so that publication does not race a change of the selected session. It does not need exactly one selection for that. ## What Changed - The settled-source owner records the exact set of task sessions that select the native session: none, one or several. Publication rechecks the same set under a share lock. A changed selection keeps the source local (`source_changed`), as before. The `session_not_selected` reason is removed. - The run, coordinator, task, lease, finalization lock and payload checks do not change. - After the source walk, the pre-copy lists the selected sessions that still need a backup. A selected scope with no source on this disk is reported as `selected_source_absent`. Before, it produced no outcome. ## Verification - Red (embedded PostgreSQL, real files): `cd server && npx vitest run src/services/native-runtime/native-harness-online-preservation.integration.test.ts` failed 4 new tests: unselected and ambiguous sources were deferred, and a missing selected source produced no outcome. - Green: the same file passes (20 tests). New tests show that an unselected or ambiguous source publishes, the run and task sessions do not change, the backup restores the exact bytes, and a selection that appears before publication keeps the receipt pending. - `native-harness-backup-storage.integration.test.ts`: the former `source_session_not_selected` expectation now expects publication by the settled-source owner (activity `native_harness_backup_preserved`), not by the offline owner. - `npx vitest run` of all 8 files that use these owners (startup gate, prestage command, filesystem independence, obligations, storage, online preservation): 240 tests pass. - `pnpm --filter @paperclipai/server typecheck` passes. - `pnpm verify` result is in a comment below. ## Risks - A settled backup of an unselected session now moves to shared storage online. The offline migration already does this, and the source files stay on the disk. - The pre-copy now runs the obligation scan once after the source walk. This is the same scan that the eligibility read runs. - Pass deferral codes change: `native_harness:source_session_not_selected` is gone, and `native_harness:selected_source_absent` is new. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../native-harness-backup-migration.ts | 35 +++++++-- ...harness-backup-storage.integration.test.ts | 11 ++- ...ss-online-preservation.integration.test.ts | 73 ++++++++++++++++++- .../native-harness-preservation-source.ts | 33 ++++----- 4 files changed, 120 insertions(+), 32 deletions(-) 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(); From fd6317de236a0c5bc236b4291063696e9c303f9d Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:51:59 -0600 Subject: [PATCH 05/19] fix(cloud): name a retained runtime skill run whose bundle left the disk and keep saving the runs after it (#22648) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A hosted server copies the runtime skill bundles that retained runs still need to shared storage before it moves to a volume-free shape > - The online pass copies them a page at a time with `migrateRuntimeSkillAssets` > - The page fails at the first run whose bundle is no longer on the disk, so the later runs on that page are never saved and the pass names only the first failure > - The offline migration continues past such a run, collects it as unsaved, and refuses at the end > - This pull request gives the online page the same behavior and names each unsaved run > - The benefit is that the pass saves every bundle it can and reports each one it cannot ## Linked Issues or Issue Description Refs #22190, #22294, #22641 **What happened?** On staging, one stack reports `runtime_skill_assets_require_migration`. Its passes showed `runtime_skill_assets:runtime_skill_source_absent:missing` as a whole-page failure: the runs after the first missing bundle were not visited. **Expected behavior** The page saves every run whose bundle is on the disk and names each run whose bundle is gone. **Steps to reproduce** 1. Keep two retained native runs with unversioned skill bundles. Remove the bundle of the first run from the disk. 2. Run `migrateRuntimeSkillAssets` with `apply`. 3. See that it throws `runtime_skill_source_absent:missing` and does not save the second run. **Additional context** #22641 already makes every blocker in the pass result carry a code. This pull request was reduced to the runtime skill page after #22641 merged. ## What Changed - `migrateRuntimeSkillAssets` returns `{ status: "unsaved", code: "runtime_skill_source_absent:" }` for a run whose bundle is not on this disk, and continues. Other errors still stop the page, as in the offline migration. - The result type is a discriminated union, so `unsaved` always carries a code. - The online pass reports each unsaved run as `runtime_skill_assets:`. - `migrate-skill-packages --phase=runtime-assets` prints the unsaved rows and exits 1 when any run stays unsaved. ## Verification - Red: `cd server && npx vitest run src/services/online-durable-data-migration.test.ts src/__tests__/runtime-skill-preservation.test.ts` failed 2 new tests: the real page (embedded PostgreSQL, real bundle files) threw `runtime_skill_source_absent:missing` before it saved the next run, and the pass had no code for unsaved runs. - Green: the same files and `online-durable-data-migration-postgres.test.ts` pass (42 tests). - `pnpm --filter @paperclipai/server typecheck` passes. - Local `pnpm verify` selects most of the suite for this change (2,979 of 3,855 files). Required CI supplies that coverage. ## Risks - No migration rule changes. A run whose bundle is gone still blocks the move, online and offline. - The maintenance command now exits 1 when a run stays unsaved, as it did before when the page threw. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- server/scripts/migrate-skill-packages.ts | 2 ++ .../runtime-skill-preservation.test.ts | 18 ++++++++++-- .../runtime-skill-preservation.ts | 12 ++++++-- .../online-durable-data-migration.test.ts | 28 +++++++++++++++++++ .../services/online-durable-data-migration.ts | 5 +++- 5 files changed, 59 insertions(+), 6 deletions(-) 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__/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/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..0c5bff3f285 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); diff --git a/server/src/services/online-durable-data-migration.ts b/server/src/services/online-durable-data-migration.ts index d8baec60846..f9aa3d5ead2 100644 --- a/server/src/services/online-durable-data-migration.ts +++ b/server/src/services/online-durable-data-migration.ts @@ -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": From f3a5367b418cd57b072a312c192e0129e4ad33ed Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:55:16 -0600 Subject: [PATCH 06/19] fix(ui): show readable connector action names in the Activity feed (#22659) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Connectors let agents use outside apps, such as Google Workspace. The company Activity page records each connector event. > - #22630 gave Google Workspace actions readable names on the Review and Permissions tabs. > - The Activity page still showed internal names. A Gmail call read "used mcp google workspace 7f3c2a10 gmail get message on". The short ID in that text comes from the connection ID. > - Some connector rows also showed raw event names or entity types, such as "tool connection content deleted" or "tool_application". > - Users must not see internal names or IDs. Google's app reviewers will also look at this page. > - This pull request makes these Activity rows use the same readable action name as the other pages, and plain sentences for connection events. > - The benefit is that people and reviewers can read what each connector event did. ## Linked Issues or Issue Description Refs #22630 **What happened?** On the company Activity page (Apps & tools filter), connector rows showed internal names. A Google tool call read "used mcp google workspace 7f3c2a10 gmail get message on". An app removal read "tool application archived tool_application". Stored content deletion read "tool connection content deletion requested". Connection removal did not say what happened to Google access. **Expected behavior** Each row reads as a plain sentence. Google actions use the readable name from the Permissions page, for example "used Gmail: Get message on the connection". No row shows a `service__tool` name, an underscore name or an ID in its main text. **Steps to reproduce** 1. Connect Google Workspace and let an agent read a Gmail message. 2. Remove the connection. 3. Open Activity and pick "Apps & tools". **Paperclip version or commit** master at 624a78fd5d. ## What Changed - `ui/src/lib/activity-format.ts`: tool call rows now name the action from `upstreamToolName` first, then the gateway name without its `mcp.-.` namespace. They use `googleWorkspaceToolTitle` from `packages/shared`, the same helper as `actionLabel` on the Permissions page. A `toolTitle` in the details wins when it is there. Other tools keep the old readable fallback. - New verbs for `tool_gateway.call_failed` ("could not use"), `tool_gateway.call_deferred` ("could not finish using"), `tool_application.archived` ("removed"), `tool_connection.content_deletion_requested`, `tool_connection.content_deleted`, `issue.connection_content_deleted` and `issue.connection_content_deletion_incomplete`. - New `formatActivityEntityLabel`: an app removal shows the app name (for example "Google Workspace"). A connection removal with a Google access result says "the Google Workspace connection". Other entity types read as words ("a run", "the organization") instead of the raw type. - New `formatActivityOutcome`: an app removal says "Its last connection was removed." - A connection removal or a credential revocation says what happened to Google access. The feed uses `googleAccessRemovalNotice`, the same text as the removal toast, for example "Paperclip's access to this Google account was also ended at Google." - `ui/src/pages/audit/AuditFeed.tsx`: the row uses these labels and shows the outcome sentence under the main line. - No API, schema or server change. | Row | Before | After | | --- | --- | --- | | Tool call completed | used mcp google workspace 7f3c2a10 gmail get message on the connection | used Gmail: Get message on the connection | | Tool call denied | was blocked from using mcp google workspace 7f3c2a10 gmail get message on | was blocked from using Gmail: Get message on | | Approval requested | asked to use mcp google workspace 7f3c2a10 gmail get message on | asked to use Gmail: Get message on | | Tool call failed | tool gateway call failed | could not use Gmail: Get message on (only the gateway name: could not use gmail get message on) | | Tool call deferred | tool gateway call deferred | could not finish using Gmail: Get message on | | Connection removed | removed the connection | removed the Google Workspace connection. Paperclip's access to this Google account was also ended at Google. | | App removed | tool application archived tool_application | removed Google Workspace. Its last connection was removed. | | Content deletion asked | tool connection content deletion requested the connection | asked to delete stored content from the connection | | Content deleted | tool connection content deleted the connection | deleted stored content from the connection | | Task content deleted | issue connection content deleted PAP-1 | deleted connected app content from PAP-1 | ## Verification - Red, then green: `ui/src/lib/activity-format.test.ts` (new "connected app activity" tests) and `ui/src/pages/audit/AuditFeed.test.tsx` ("shows connected Google activity as plain sentences without internal names or IDs"). The rows use real UUIDs and a real gateway tool name. The feed test renders 11 connector rows. It checks that the main text of each row has no `__`, no underscore name, no UUID and no short connection ID. - Before the fix: 7 tests failed, for example `expected 'used mcp google workspace 7f3c2a10 gm…' to be 'used Gmail: Get message on'`. - After the fix: `npx vitest run src/lib/activity-format.test.ts src/pages/audit/` passes (69 tests). - `pnpm --filter @paperclipai/ui typecheck` passes. - `pnpm verify` selected 2,983 of 3,857 Vitest files (conservative selection for a `ui/src/lib` change). I stopped it and use required CI for broad coverage. ## Risks - Low risk. Only display text in the Activity feed changes. - The small mono action name on each row (for example `tool_gateway.call_completed`) stays. `DESIGN.md` principle 6 says machine values use the monospace style. Nothing marks it as a debug-only item. - `AuditFeed.production.tsx` (the old design snapshot that `AgentDetail.production` uses) gets the new verbs but keeps its own entity text. This change does not edit that snapshot. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), in Claude Code with tool use (shell, file edit, test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../connections/googleAccessRemoval.ts | 3 +- ui/src/lib/activity-format.test.ts | 89 ++++++++++++++++++- ui/src/lib/activity-format.ts | 61 +++++++++++-- ui/src/pages/audit/AuditFeed.test.tsx | 62 +++++++++++++ ui/src/pages/audit/AuditFeed.tsx | 21 ++++- 5 files changed, 223 insertions(+), 13 deletions(-) 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/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}” From 348749305c5e5a96476dcbba30ac59ef2d25d179 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:55:29 -0600 Subject: [PATCH 07/19] fix(connections): keep managed sign-in when Paperclip Cloud is busy or unreachable (#22662) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - On Cloud workspaces, connectors such as GitHub use managed sign-in through Paperclip Cloud > - Paperclip asks the Cloud connector broker which sign-ins this instance has and whether its registration is active > - When the broker rate-limits or fails that check, Paperclip treats the failure as "no Cloud sign-ins" and "not registered" > - The GitHub card then says "Add key", and the connect screen offers self-hosted Cloud registration, which cannot succeed on a Cloud workspace > - This pull request keeps the last answer Cloud confirmed when the broker does not answer, and shows a retry instead of registration > - The benefit is that a busy or unreachable broker no longer changes what the user sees, or sends them into a setup flow that cannot work ## Linked Issues or Issue Description **What happened?** On a production Cloud workspace, the GitHub card on the Connectors page said "Add key" instead of "Connect". On the GitHub connect screen, "Connect with Paperclip" failed with "Paperclip Cloud enrollment could not be started". On another production workspace, "Continue to GitHub" failed with "Internal server error". **Steps to reproduce** 1. Open Connectors on a Cloud workspace while the Cloud connector broker returns 429 to the workspace's signed requests. 2. Look at the GitHub card. It says "Add key". 3. Open Connect GitHub. The self-hosted registration card shows. Its button fails. **Expected behavior** The card says "Connect". A broker that is busy or unreachable gives a retry, not a registration flow that cannot succeed. **Root cause** The broker rate-limited signed requests from production stacks (`429 RATE_LIMITED`; Sentry shows it from 8 production stacks in 7 days, and none on staging). The fix for that is in paperclipai/paperclip-cloud#1751. In this repository, `getCapabilities()` mapped every error to an empty list and cached it for 60 seconds. The enrollment status check mapped every error to `unverified`, and the connect screen treated `unverified` like "not registered". Refs paperclipai/paperclip-cloud#1751 ## What Changed - `paperclip-cloud-connector.ts`: a 429, a 5xx, or an unreachable broker is now a "no verdict" failure (`isTransientPaperclipCloudConnectorError`). - On a "no verdict" failure, capability and instance-status checks return the last answer Cloud confirmed for this connector identity. `invalidatePaperclipCloudConnectorCapabilities()` clears those saved answers. - `paperclipCloudConnectorCapabilitiesFromEnv` keeps an unanswered check for only 5 seconds, not 60. Gallery reads soon ask Cloud again, but a failing broker does not get one request per read. - `paperclip-cloud-connector-status.ts`: when Cloud does not answer the status check (429, 5xx, or network), the status is the new `unreachable`. Incomplete managed settings now report `misconfigured`: the connect screen and the Connections banner tell the user to ask their administrator, because registration cannot run there. `unverified` stays for a saved identity that belongs to another broker, which keeps the registration step. - `Connections.tsx`: the Cloud banner shows a message without the Enable button for `unreachable` and `misconfigured`. - A Cloud rejection, or a confirmed removed or suspended registration, clears the saved sign-ins and the gallery's cached list. An unreadable answer (a non-JSON body) or a 408 counts as no verdict. An answer from a request that started before an invalidation is not saved. - `ConnectionSetupFlow.tsx`: when the Cloud status is `unreachable`, the screen shows "Paperclip couldn’t reach Paperclip Cloud to start GitHub sign-in. Try again in a moment." with a Try again button. It no longer offers registration. Try again reloads both the gallery and the Cloud status. ## Verification - New file `server/src/services/paperclip-cloud-connector-saved-answers.test.ts` (7 tests): the last confirmed sign-ins and status are kept through 429 and 503 responses; a busy broker with no earlier answer gives no verdict; a rejection or removal is not undone by a later 429; a late answer does not replace a newer one; a 429 capability check is kept for only 5 seconds; `unreachable` and `unverified` are reported separately. They fail without this change and pass with it. - `ui/src/pages/apps/AppsConnect.test.tsx`: an `unreachable` status shows the retry and not "Connect with Paperclip"; an `unverified` status still shows registration. - Server connector tests (saved-answers, connector, enrollment): 94/94 pass. Cloud-related AppsConnect tests: 4/4 pass. - `pnpm verify` selected a broad set of server tests and was stopped (exit 143) under machine load. The Cloud-floor tests that it reported as failing pass when run alone (`company-cloud-floor.test.ts` 3/3). CI covers the full suite. ## Risks - Low risk. The saved answers live in memory and are cleared by the existing invalidation and by a restart. A workspace whose Cloud registration was removed still sees that on the next confirmed answer: a 401 maps to `removed` as before. - A saved `active` status can stay in use while the broker keeps failing. This is intended: a failure gives no new information. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, browser, Sentry reads). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- ...perclip-cloud-connector-enrollment.test.ts | 2 +- .../paperclip-cloud-connector-enrollment.ts | 11 +- ...clip-cloud-connector-saved-answers.test.ts | 222 ++++++++++++++++++ .../paperclip-cloud-connector-status.ts | 9 +- .../src/services/paperclip-cloud-connector.ts | 130 ++++++++-- ui/src/api/tools.ts | 2 +- .../connections/ConnectionSetupFlow.tsx | 28 ++- ui/src/pages/apps/AppsConnect.test.tsx | 56 +++++ ui/src/pages/apps/Connections.test.tsx | 47 ++++ ui/src/pages/apps/Connections.tsx | 17 +- 10 files changed, 490 insertions(+), 34 deletions(-) create mode 100644 server/src/services/paperclip-cloud-connector-saved-answers.test.ts 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/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 e4a81a937a1..7b482da544c 100644 --- a/ui/src/features/connections/ConnectionSetupFlow.tsx +++ b/ui/src/features/connections/ConnectionSetupFlow.tsx @@ -2397,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( @@ -2410,6 +2417,8 @@ function StandardConnectionSetupFlow({ && entry && requestedDefinitionUsesManagedConnector && !entryAdvertisesManagedConnector + && !cloudConnectorUnreachable + && !cloudConnectorMisconfigured && ( connectorEnrollmentQuery.isLoading || connectorEnrollmentView.kind === "error" @@ -2714,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/pages/apps/AppsConnect.test.tsx b/ui/src/pages/apps/AppsConnect.test.tsx index b2c74ff24f9..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({ 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."} +
); } From e856a607edebba6ddf340c86e20b3119eabb9fe6 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:56:12 -0600 Subject: [PATCH 08/19] fix(cloud): name why an online workspace source scope is unproven (#22644) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A hosted server moves each local workspace to shared storage in bounded online passes while it serves work > - Before a Git or managed workspace moves online, the server must prove which tasks and projects can write its files > - Staging stacks stay blocked with many `online_workspace_source_scope_unproven` workspaces after repeated passes > - The proof has more than 30 separate checks, and the pass does not say which check failed > - This pull request names the failed check for each workspace > - The benefit is that the next pass on a blocked stack shows the exact cause, so the right fix can follow ## Linked Issues or Issue Description Refs #22270, #22294 **What happened?** After repeated online passes, staging stacks report `workspaces:online_workspace_source_scope_unproven` for 26 to 49 workspaces each. The code does not say which part of the source proof failed. Most of the same workspaces also report `overlapping_workspace_requires_maintenance`, because a workspace without a proven scope cannot treat its Git siblings as one unit. **Expected behavior** The pass names the part of the source proof that failed for each workspace. **Steps to reproduce** 1. Create a nested Git wrapper workspace with a linked worktree. 2. Remove the linked worktree directory without `git worktree prune`. 3. Run the online inventory. It reports only `online_workspace_source_scope_unproven`. ## What Changed - `explainOnlineWorkspaceSource` and `explainOnlineOrdinarySource` return `{ unproven: }` for each failed check. `inspectOnlineWorkspaceSource` and `inspectOnlineOrdinarySource` keep their old `null` result. - Inventory returns `sourceScopeUnproven` with the code. The `reasons` list does not change. - The online pass reports the code as `workspaces:source_scope_` next to `workspaces:online_workspace_source_scope_unproven`. - The linked-worktree reader throws `workspace_git_link_stale` when a registered worktree directory is gone, and `workspace_git_links_exceeded` above 256 links. Both still reject the proof. - Codes include `git_link_stale`, `git_link_unregistered`, `git_links_unreadable`, `member_status_unsupported`, `member_task_binding_missing`, `member_locator_mismatch`, `member_git_expiration_pending`, `source_keys_exceeded`, `members_exceeded`, `foreign_alias`, `companion_recovery_unresolved`, `companion_copyback_unresolved`, `ordinary_member_nested` and others. ## Verification - `cd server && npx vitest run src/services/remote-workspace-migration.test.ts src/services/remote-workspace-online-source.test.ts src/services/remote-workspace-cohort-migration.test.ts src/services/workspace-git-source-roots.test.ts src/services/online-durable-data-migration.test.ts src/services/online-durable-data-migration-postgres.test.ts src/services/finalized-workspace-recovery-migration.test.ts` (embedded PostgreSQL): 7 files, 407 tests passed. - Red/green: the linked-worktree test now checks the code for five cases (unregistered, wrong backlink, wrong pointer, symlinked backlink, stale). On `origin/master` the result has no `sourceScopeUnproven` field. The new pass test fails on `origin/master` because the pass has no `source_scope_` key. - `pnpm --filter @paperclipai/server typecheck`: passed. ## Risks - Low risk. No proof accepts more than before. Each check returns the same accept or reject result. Only the reported code is new. - The pass result gets new `workspaces:source_scope_` keys. Readers that count deferral keys see more keys. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- .../online-durable-data-migration.test.ts | 12 +++ .../services/online-durable-data-migration.ts | 6 +- .../src/services/online-workspace-source.ts | 91 ++++++++++++------- .../remote-workspace-migration-tree.ts | 47 +++++++--- .../remote-workspace-migration.test.ts | 7 +- .../services/remote-workspace-migration.ts | 11 ++- .../services/workspace-git-source-roots.ts | 3 +- 7 files changed, 120 insertions(+), 57 deletions(-) diff --git a/server/src/services/online-durable-data-migration.test.ts b/server/src/services/online-durable-data-migration.test.ts index 0c5bff3f285..6cb3e69f263 100644 --- a/server/src/services/online-durable-data-migration.test.ts +++ b/server/src/services/online-durable-data-migration.test.ts @@ -373,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 f9aa3d5ead2..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; @@ -255,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/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/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(); From b865dd112bc9628f0b86006d610a80b17e5c853d Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:12:16 -0600 Subject: [PATCH 09/19] feat(google-workspace): run Gmail, Drive, Docs, Sheets, Slides and Calendar on Paperclip's REST tools (#22634) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The built-in Google Workspace connector gives agents Gmail, Drive, Docs, Sheets, Slides and Calendar actions through one connection > - Google's hosted Workspace MCP servers are a Developer Preview, so Paperclip cannot offer them to the public > - Paperclip has its own REST tool set for all 36 allowlisted actions, but every service still sent its calls to Google's MCP servers > - The owner decided on 2026-11-23 to launch all six services on REST now and to live-test on the staging tester after deploy > - This pull request switches the six services to `paperclip_rest` and fixes what the switch breaks > - The benefit is that the connector no longer depends on Developer Preview servers, and agents get all 36 actions, including the two Gmail actions Google's live server did not offer ## Linked Issues or Issue Description Refs #22016 (the transport switch), #22000, #22014, #22017, #22027, #22028, #22029 (the REST tool set). **Subsystem affected** Built-in Google Workspace connector (`google-workspace`, `workspace.all`): transport setting, catalog publication, tests and docs. **Problem or motivation** All six launch services used Google's hosted MCP servers. These servers are a Developer Preview and are not available to the public. Google's live Gmail MCP server also did not offer `gmail__list_threads` and `gmail__search_messages`. **Proposed solution** Set Gmail, Drive, Docs, Sheets, Slides and Calendar to `paperclip_rest` in `GOOGLE_WORKSPACE_TOOL_TRANSPORT`. Keep Chat, People and Search on `google_mcp`. Fix the catalog refresh so that an existing connection keeps its actions active after the switch. **Alternatives considered** Switch one service at a time after a live test (the Nov 17 rule). The owner replaced this rule on Nov 23: switch all six now and fix forward. **Roadmap alignment** This is the planned launch step for the Google Workspace connector. It does not overlap other core work. ## What Changed - `packages/shared/src/google-workspace-connectors.ts`: set `gmail`, `drive`, `docs`, `sheets`, `slides` and `calendar` to `paperclip_rest`. `chat`, `people` and `search` stay `google_mcp`. - Connections saved before the switch keep Google's MCP definitions in their catalog. Two changes make them work with no user action: - New resolver `paperclipDefinedTool(connection, toolName)` in `server/src/services/connectors/paperclip-defined-tools.ts` (typed result). It is the one place that says which tools are Paperclip-defined; for a `google-workspace` connection it calls `googleWorkspaceRestToolDefinition` in the dispatch adapter, which returns the REST definition when the service is on `paperclip_rest`. - `server/src/services/tool-gateway.ts`: when the gateway lists a connection's tools, it takes the input schema, output schema, description and annotations of a Paperclip-defined tool from the resolver, not from the saved row. Routing and the advertised definition read the same transport setting in the same process. This is an in-memory lookup, so it adds no request to the turn start. Example: an agent gets the REST `docs__update_doc` schema, where `writeControl.requiredRevisionId` is required, not Google's schema, where it is optional. - `server/src/services/tool-access/catalog/publication.ts`: catalog publication asks the same resolver. It never holds a Paperclip-defined 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 is never added to the profile: Off stays Off and Ask first stays, also for a held action. Only actions the connection never had (Gmail `list_threads` and `search_messages`) get the default for new actions. Before this fix, a refresh after the switch put every action of an existing managed connection into `pending_review` (10 of 10 in the regression test). - `server/src/__tests__/google-workspace-rest-transport.test.ts`: the fake Google now answers the Docs, Sheets and Slides REST hosts and the Drive and Calendar paths. New tests: - The transport map has exactly the six launch services on `paperclip_rest`. - A full read and write grant lists exactly the 36 allowlisted actions (with `gmail__list_threads` and `gmail__search_messages`) and sends no MCP request. A read-only grant lists the 23 read actions. Gmail, Drive and Calendar group grants list exactly their actions. - One read and one write per service run through the real `executeTool` path on REST with the default policy (no approval request). Each call records the invocation and the `call_completed` event with the connection ID (the "Delete data" bookkeeping keys), and audits the protocol `Google Workspace REST` with the service endpoint. - Injected instructions in Docs, Sheets, Slides, Drive and Calendar REST results are blocked. - An existing connection discovered over MCP keeps its actions active after the switch and can call the new Gmail actions. - Migration without refresh: a connection saved with Google's MCP schemas (`update_doc` with `writeControl` optional) advertises the REST schemas after the switch with no refresh, and `read_doc` then `update_doc` with the revision succeed over REST. - The first refresh after the switch releases an action held for `pending_review`, keeps an Off action unlisted and keeps Ask first (`approval_required`). - An action that is both Off and held stays Off, and one that is both Ask first and held stays Ask first, after the switch and after two refreshes. - The MCP-path test pins Gmail and Docs to `google_mcp` explicitly. - `server/src/__tests__/helpers/google-workspace-transport.ts`: new helper `useGoogleMcpTransport()`. Tests whose fixtures act as Google's MCP servers use it (`tool-access-service`, `tool-gateway-service`) or pin the transport in `beforeAll` (`google-workspace-injection-screening`). These tests still cover the MCP path, which stays available for Chat, People, Search and a switch back. - `packages/shared/src/google-workspace-connectors.test.ts`: assert the new transport map. - Docs: `doc/connections/GOOGLE-WORKSPACE.md` and the REST folder `README.md` say that the six services run on REST. `doc/memory/google-connector-memory.md` has three dated Nov 23 decisions (all six switched to REST, writes default to Allowed, image-by-URL inserts allowed), and the two items are removed from "Still open". ## Verification - Red: after the flip, 50 tests failed in four files because their fixtures act as Google's MCP servers. These are fixture assumptions, not product bugs. - Red: without the gateway change, the migration test gets Google's saved schema; without the publication change, the held action stays `quarantined`; without excluding released rows from the new-action default, the Off and held action comes back. All green with the fixes. - Red: the new test "keeps an existing connection's actions usable when its services move from Google's MCP servers to REST" failed before the `publication.ts` fix: 10 catalog entries were `quarantined` with `pending_review`. Green after the fix. - `cd server && npx vitest run src/__tests__/google-workspace-rest-transport.test.ts src/__tests__/google-workspace-injection-screening.test.ts src/__tests__/tool-gateway-service.test.ts src/__tests__/tool-access-service.test.ts src/services/google-workspace-rest-dispatch.test.ts src/google-workspace-rest-tools`: with `connection-management.integration.test.ts` added: 60 files, 2232 tests pass. `google-workspace-rest-transport.test.ts`: 52 tests pass. - `cd packages/shared && npx vitest run src/google-workspace-connectors.test.ts`: 14 tests pass. - `npx tsc -p server/tsconfig.json --noEmit`: no errors. - Trace of a read (`gmail__get_message`) and a write (`gmail__create_draft`) through `executeTool` in `server/src/services/tool-gateway.ts`: policy decision and invocation record (13723, 13731), approval gate (13820), `call_allowed` audit (13885), dispatch to `executeRemoteHttpTool` (13915), prompt-injection screening of the result (13964), `call_completed` event and audit (14022, 14044), failure audit (14187). In `executeRemoteHttpTool` the grant scope check (8172) runs before the REST branch (8276), which rechecks the current grant and returns before any MCP session, MCP Task or elicitation code. The REST adapter (`google-workspace-rest-dispatch.ts`) calls `google-http.ts` only through the gateway's guarded fetch. - Not verified: calls against real Google. The live test on the staging tester runs after deploy. ## Risks - Real Google answers can differ from the fixtures. The REST tools are not yet run against real Google. The live test on the staging tester runs after this deploys, and problems are fixed forward. - The OAuth client on the staging tester is marked for AI agents and was only used through MCP. If Google refuses REST calls from that client, all six services fail on the tester until the client changes. - Existing connections keep their stored MCP schemas until a catalog refresh, but agents receive the REST definitions at once. The stored risk level of the four update actions stays `write` until that refresh, then becomes `destructive`. The two new Gmail actions appear after a refresh. - Input differences between Google's MCP schemas and the REST tools are listed in the REST folder `README.md` ("Input differences an agent meets after a switch"). Agents receive the REST schemas, so these differences are visible to them. No `tools/list` from Google's servers is recorded, so the check uses Google's published references. - Accepted risk (owner decision, 2026-11-23): Docs and Slides edits may insert an image from any public web address. Google, not Paperclip, fetches the address, and Paperclip's own requests still go only to the allowed Google hosts. The residual risk is that an agent could put data in the address it chooses. Links to Drive or Docs files stay refused. - Update actions (`update_doc`, `update_presentation`, `update_spreadsheet`, `update_event`) are labelled destructive on REST, as decided on Nov 17. This does not add an approval step: write actions stay Allowed by default. - A switch back to `google_mcp` stays possible with a one-line change. The MCP path tests still run. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- doc/connections/GOOGLE-WORKSPACE.md | 15 +- doc/memory/google-connector-memory.md | 44 +-- .../src/google-workspace-connectors.test.ts | 10 +- .../shared/src/google-workspace-connectors.ts | 4 +- ...ogle-workspace-injection-screening.test.ts | 7 +- .../google-workspace-rest-transport.test.ts | 346 +++++++++++++++--- .../helpers/google-workspace-transport.ts | 10 + .../src/__tests__/tool-access-service.test.ts | 5 + .../__tests__/tool-gateway-service.test.ts | 2 + .../src/google-workspace-rest-tools/README.md | 61 ++- .../connectors/paperclip-defined-tools.ts | 16 + .../google-workspace-rest-dispatch.test.ts | 21 ++ .../google-workspace-rest-dispatch.ts | 23 ++ .../tool-access/catalog/publication.ts | 9 +- server/src/services/tool-gateway.ts | 13 +- .../runner-e2e/source-sdk-public-inputs.json | 4 +- 16 files changed, 500 insertions(+), 90 deletions(-) create mode 100644 server/src/__tests__/helpers/google-workspace-transport.ts create mode 100644 server/src/services/connectors/paperclip-defined-tools.ts 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..dafe7633f3b 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. 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/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__/tool-access-service.test.ts b/server/src/__tests__/tool-access-service.test.ts index dad5e4c1922..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()}`; diff --git a/server/src/__tests__/tool-gateway-service.test.ts b/server/src/__tests__/tool-gateway-service.test.ts index b7b61a5f4f0..bfa25a92f46 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); 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/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/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/tool-access/catalog/publication.ts b/server/src/services/tool-access/catalog/publication.ts index 2483655153b..d2ea419ff96 100644 --- a/server/src/services/tool-access/catalog/publication.ts +++ b/server/src/services/tool-access/catalog/publication.ts @@ -12,6 +12,7 @@ import { connectionMethodForConnection } from "../connection-methods.js"; import { stableHash, descriptorHash } from "../../tool-catalog-hash.js"; import { nativeProviderCatalogFor } from "../../native-provider-catalogs.js"; import { restConnectorFor } from "../../connectors/rest-registry.js"; +import { paperclipDefinedTool } from "../../connectors/paperclip-defined-tools.js"; import { googleWorkspaceToolTarget, googleWorkspaceGrantedScopes, isGoogleWorkspaceToolGranted } from "@paperclipai/shared"; import { retainMcpConnectionFailure } from "../../mcp-connection-failure.js"; import { isRemoteMcpConnectorMethod } from "@paperclipai/shared"; @@ -185,6 +186,7 @@ export function createToolCatalogPublication(db: Db, { now, audit, getConnection } const catalogValues: Array = []; 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-gateway.ts b/server/src/services/tool-gateway.ts index 508fca57d1d..b241730ae23 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"; @@ -2019,13 +2020,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 = { @@ -2052,12 +2055,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, diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index f5711f2796e..ba205a897b5 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -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", From d28becf0f5f1f001b6f3ad023296e5df78e69c88 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:16:22 -0600 Subject: [PATCH 10/19] fix(server): run person-opened gateway sessions as their opener for personal connection grants (#22643) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The tool gateway lets an agent run call connected apps through a short-lived session > - A person on the board can also open a gateway session for a running agent > - Such a session resolved credentials for the run's responsible person, not for the person who opened it > - A member could therefore use another member's personal connection grant through that member's running agent > - This pull request limits personal grants in a person-opened session to the grant owner and requires permission to act on the agent > - The benefit is that a personal connection is used only by its owner or by the owner's own agent runs ## Linked Issues or Issue Description Refs #22635 **What happened?** `POST /api/tool-gateway/sessions` let any non-viewer member open a session for any running agent in the company. Tool calls in that session used the personal grant of the run's responsible person. **What did you expect to happen?** A person who opens a session can use a personal (user-owned) grant only when they own it. The person needs permission to act on the agent. Company-shared connections and agent-opened sessions work as before. **Steps to reproduce** Two members are in one company. Member A has a personal grant on a connection that agent X uses. While a run of X is active, member B opens a gateway session for that run and calls a tool on that connection. The new route test covers this case. **Impact** Access-control hardening for personal connection grants. ## What Changed - Add the nullable column `tool_gateway_sessions.created_by_user_id` (migration `0502`, which also adds `tool_mcp_tasks.created_by_user_id`). The route sets it when a person (not a local implicit board) opens a session. - Grant resolution for such a session acts as the person who opened it. That person's own personal grant is used, or a connect card is addressed to that person. Another member's personal grant is never selected, and that member gets no card. - The opener is recorded on the tool invocation (server-written `policyExplanation.sessionOpenedByUserId`) and restored when an approved action runs. An approved call from that session therefore uses the same person's grant. - A guard after grant resolution refuses a user-owned grant of another person with `403` and `reasonCode: personal_grant_owner_required`, as defense in depth. - Saved-call replay is scoped to the opener: idempotency keys get an opener suffix for such sessions, and approval replay matches only invocations recorded with the same opener. The lookup of keys saved before this change still runs: a saved call that can be attributed to the same person replays, one attributed to another person does not, and one that cannot be attributed returns the existing `legacy_tool_idempotency_unverifiable` conflict instead of running the write again. - Long-running provider tasks (`tool_mcp_tasks`) record the opener in a new `created_by_user_id` column (same migration) and restore it on each background poll, so the task keeps the opener's grant and is attributed to the opener. - Managed GitHub identity selection uses the opener, in the first and the fallback selection. - A call attaches to an existing long-running provider task only when the task uses the same grant the call resolves to. On a personal grant it must also be the same person (an agent session matches only tasks with no opener; the grant owner may also collect a legacy task with no opener). On a shared grant any person may collect. The wake for a finished task now carries the task id, so the agent's continuation resolves the opener's grant and collects the result instead of calling the provider again. - `POST /api/tool-gateway/sessions` checks the existing `agent:wake` permission for a board caller, the same check as invoking the agent. - Agent-opened sessions do not set the column, so agent runs and the recovery of interrupted runs do not change. - Document the rule in `doc/MCP-ACCESS-GOVERNANCE.md`. - I checked the sibling routes. Named gateway tokens minted by a person need `tools:admin` and carry no responsible person. Board test calls and MCP app view calls already run as the caller. Stored MCP task continuations stay pinned to the grant they started with. ## Verification - New route tests in `server/src/__tests__/tool-gateway.test.ts`: - Three members, two with personal grants, on a run that belongs to the first. A session opened by the second member uses only that member's credential. The run owner's session and an agent-opened session use the run owner's credential. A member with no grant gets `409 user_authorization_required`, the card is addressed to that member, and the remote server gets no request. A reviewed call from the second member's session, once approved, runs with that member's credential. The same write from two people's sessions runs once for each person, and only the same person's retry replays. - A pre-upgrade saved write retried by the same person replays (or conflicts when it cannot be attributed) and never reaches the provider twice; another person's identical write runs. - `mcp-tasks.test.ts`: a person-started task keeps the opener's grant through a background poll; an agent retry never receives that task's result and keeps its own task; the continuation after a wake collects once with no new provider call; on a shared grant another person collects the task, including a task started before openers were recorded. - `tool-gateway-service.test.ts`: an opener with their own managed GitHub grant uses it; an opener without one is refused and the run owner's grant is never used. - A viewer cannot open a session for the agent. - Before the fix, the second member's session used the run owner's credential, and the viewer got `201`. Both tests pass now. - `npx vitest run src/__tests__/tool-gateway.test.ts src/__tests__/connection-management.integration.test.ts src/__tests__/mcp-tasks.test.ts`: with `tool-access-service.test.ts` and the policy tests, 833 tests pass. - `tsc --noEmit` for `server` passes. - `pnpm verify` exits 2 because a global CI input (a doc) changed. Required CI gives the broad coverage. ## Risks - A person who opened a session for another member's run used that member's personal grants before. Now the session uses the opener's own grants. This was not an intended flow. Shared connections and agent runs do not change. - A person-opened session that repeats exactly the same side-effecting call an agent session already made in the same run gets a `409` conflict instead of a second write, because that earlier call has no recorded opener. Use a new explicit idempotency key for an intentional repeat. - The migration only adds nullable columns. Sessions and review requests created before this change have no opener record and keep the previous behavior until they expire (15 to 60 minutes). - Follow-up, out of scope: in the experimental MCP Tasks path, a call with a new explicit idempotency key and the same arguments still attaches to the same person's open task under the same grant. That is the existing de-duplication for every caller and does not depend on the opener rule. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- doc/MCP-ACCESS-GOVERNANCE.md | 2 +- .../migrations/0502_dapper_hedge_knight.sql | 2 + ...{0497_snapshot.json => 0502_snapshot.json} | 552 +++++++++++++++++- packages/db/src/migrations/meta/_journal.json | 7 + packages/db/src/schema/tool_access.ts | 2 + packages/shared/src/types/tool-access.ts | 1 + server/src/__tests__/mcp-tasks.test.ts | 107 ++++ .../__tests__/tool-gateway-service.test.ts | 39 ++ server/src/__tests__/tool-gateway.test.ts | 169 +++++- server/src/routes/tool-gateway.ts | 13 + server/src/services/mcp-task-work.ts | 2 +- server/src/services/tool-access-policy.ts | 33 +- server/src/services/tool-gateway.ts | 110 +++- .../runner-e2e/source-sdk-public-inputs.json | 2 +- 14 files changed, 1016 insertions(+), 25 deletions(-) create mode 100644 packages/db/src/migrations/0502_dapper_hedge_knight.sql rename packages/db/src/migrations/meta/{0497_snapshot.json => 0502_snapshot.json} (99%) 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/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/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/types/tool-access.ts b/packages/shared/src/types/tool-access.ts index 0827fd3cfc6..95a5673f5b9 100644 --- a/packages/shared/src/types/tool-access.ts +++ b/packages/shared/src/types/tool-access.ts @@ -1735,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/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__/tool-gateway-service.test.ts b/server/src/__tests__/tool-gateway-service.test.ts index bfa25a92f46..4aeadc56de2 100644 --- a/server/src/__tests__/tool-gateway-service.test.ts +++ b/server/src/__tests__/tool-gateway-service.test.ts @@ -3611,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 1e763874195..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"; @@ -2231,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); 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/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/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 | 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 @@ -3368,6 +3376,7 @@ export function createToolGatewayService( issueId: input.session.issueId, projectId: input.session.projectId, gatewayId: input.session.gatewayId ?? null, + sessionOpenedByUserId: input.session.createdByUserId ?? null, }); } @@ -3386,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 = @@ -3404,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, @@ -3508,7 +3519,7 @@ export function createToolGatewayService( session.companyId, { agentId: session.agentId, - responsibleUserId: session.responsibleUserId, + responsibleUserId: session.createdByUserId ?? session.responsibleUserId, allowStandingDelegation: false, }, ); @@ -3569,7 +3580,7 @@ export function createToolGatewayService( session.companyId, { agentId: session.agentId, - responsibleUserId: session.responsibleUserId, + responsibleUserId: session.createdByUserId ?? session.responsibleUserId, allowStandingDelegation: false, excludeGrantId: original.id, }, @@ -5270,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( @@ -5294,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 && @@ -5308,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) { @@ -7644,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); @@ -7660,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, @@ -7717,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 @@ -7981,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, @@ -8560,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) { @@ -10835,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), }; @@ -11134,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", @@ -11913,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); @@ -11927,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)), }; @@ -11940,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, @@ -12998,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, @@ -13779,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/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index ba205a897b5..28eec022ac9 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -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": "0827fd3cfc63431077aef0cedc42bc7709957f57", + "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", From 2181df544c0927e9b35788caeb409e54eb57ab72 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Mon, 23 Nov 2026 11:52:16 -0800 Subject: [PATCH 11/19] fix(claude-local): skip the setup-token login-method line (#22652) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - People connect a Claude subscription from "Connect a model". Paperclip runs `claude setup-token` in a terminal and reads the sign-in link from the output > - `parseSetupTokenPrompt` binds the link only when the browser-code prompt follows the URL block. It skips repeated URL rows and the copy hint, and it fails closed on any other line > - Claude Code 2.1.306 prints a new line, `Login method pre-selected: Subscription Plan (Claude Pro/Max)`, between the copy hint and the prompt > - The parser returns null for that layout, and the runner waits for the 5-minute timeout. The dialog stays on "Preparing browser sign-in…", and the log says only "timed out" > - This pull request skips the login-method line with a bounded pattern and logs one fixed line when the prompt is on screen but the parser does not bind it > - The benefit is that Claude subscription sign-in works on Claude Code 2.1.306, and the next layout change shows up in the log at once ## Linked Issues or Issue Description Fixes #19949 Refs #19958 (the same fix by @adity982, written before #19211 changed the copy-hint check; this pull request ports it onto `master` and widens the pattern to other method names). Refs #19211, #15550 (earlier copy-hint fixes). Refs #20050 (PTY window size, a separate fix). Refs #22520 (the 2.1.330 short link, a separate fix in the URL validator). The plain-text URL reassembly defect from the same issue is in a separate pull request, as the triage comment asks. ## What Changed - `setup-token-parse.ts`: add `LOGIN_METHOD_LINE_RE`. `findBrowserCodePrompt` skips a line that matches it. The method name is 1 to 80 characters of prose with no `:`, so a URL or a `code:value` cannot hide in it. Any other unknown line still returns null. - `setup-token-parse.ts`: add `hasSetupTokenPromptLine`. It returns true when the output holds the prompt line. It binds no value. - `setup-token-runner.ts`: when the prompt line is on screen and `parseSetupTokenPrompt` still returns null, log one fixed line: `Setup-token login: the browser-code prompt is on screen, but the parser did not recognize the sign-in screen.` The line holds no input bytes, and the runner logs it at most one time per run. - Tests: the 2.1.306 layout (OSC 8 link per row, CHA-spaced words, copy hint, login-method line, prompt), the login-method line without a copy hint, four malformed login-method lines that must fail closed, and two runner tests for the new log line. ## Verification - `pnpm exec vitest run packages/adapters/claude-local/src/server/`: 396 passed, 2 skipped. - The two positive parser tests fail on `master` and pass with this change. - `pnpm --filter @paperclipai/adapter-claude-local typecheck` passes. - I ran the parser on a synthetic 2.1.306 screen built from the output in #19949. `master` returns null. This branch returns the full URL. - Not run: a live `claude setup-token` sign-in on 2.1.306. ## Risks - Low risk. The change adds one allowlisted line shape. The parser keeps its fail-closed contract for every other line. - A future CLI can print another new line. The parser then still returns null, but the new log line names the cause. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with shell, file edit, and code execution tools. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --- .../src/server/setup-token-parse.test.ts | 32 +++++++++++++++++ .../src/server/setup-token-parse.ts | 15 ++++++-- .../src/server/setup-token-runner.test.ts | 35 +++++++++++++++++++ .../src/server/setup-token-runner.ts | 6 ++++ 4 files changed, 86 insertions(+), 2 deletions(-) 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..4205453ae4e 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 @@ -366,6 +366,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..d4f704d67aa 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}, @@ -378,8 +386,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 +400,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); } From c294f21a34e8f0bb0e024e2dca35f022b836bbe4 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Mon, 23 Nov 2026 11:52:21 -0800 Subject: [PATCH 12/19] fix(claude-local): join every row of a hard-wrapped setup-token URL (#22653) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - People connect a Claude subscription from "Connect a model". Paperclip runs `claude setup-token` in a terminal and reads the sign-in link from the output > - When the CLI prints the link as plain text, the terminal hard-wraps it over several rows. `reassembleUrl` joins the rows and validates the result > - It returns the first join that validates. `state` is the last query key and needs only 16 characters, so a join that stops inside `state` can validate one row early > - The leftover row then sits where the prompt should be. Prompt binding returns null, and the sign-in dialog hangs. No truncated URL gets out, because the parser fails closed > - This pull request uses the wrap shape: every row but the last has the same width, so the parser joins until a row is shorter than the first row > - The benefit is that the plain-text path works at every terminal width, not only at the widths where the break misses `state` ## Linked Issues or Issue Description Refs #19949 (the plain-text path section). The fix follows the change that @aron-intframe proposed and measured in the first comment on that issue. The login-method line defect from the same issue is in a separate pull request, as the triage comment asks. Refs #20050 (PTY window size). ## What Changed - `setup-token-parse.ts`: `reassembleUrl` no longer returns at the first join that validates. If the first row validates on its own, the URL is unwrapped, and the parser stops there as before. Otherwise it joins until a row is shorter than the first row, and it returns the last join that validated. - Tests: the 64-column `claude.com` wrap from #19949, a sweep of every width from 40 to 200 columns for both accepted URLs, and a test that a two-row wrap with a valid first row still fails closed. ## Verification - `pnpm exec vitest run packages/adapters/claude-local/src/server/`: 391 passed, 2 skipped. - The 64-column test and the width sweep fail on `master` and pass with this change. - `pnpm --filter @paperclipai/adapter-claude-local typecheck` passes. - With a 385-character URL like the one in #19949, `master` fails at 49 of 161 widths from 40 to 200. This branch passes at all 161. ## Risks - Low risk. Each existing test passes, including the code-like value after the URL, the repeated OSC 8 rows, and the hostile line between fragments. - One gap stays: a two-row wrap whose first row already holds 16 or more `state` characters. One row gives no width to compare, so the parser fails closed as it does today. A 200-column PTY (#20050) avoids this for current URL lengths. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with shell, file edit, and code execution tools. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --- .../src/server/setup-token-parse.test.ts | 30 +++++++++++++++++++ .../src/server/setup-token-parse.ts | 16 ++++++---- 2 files changed, 40 insertions(+), 6 deletions(-) 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 4205453ae4e..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 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 d4f704d67aa..b52a472c11f 100644 --- a/packages/adapters/claude-local/src/server/setup-token-parse.ts +++ b/packages/adapters/claude-local/src/server/setup-token-parse.ts @@ -360,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; } /** From 0bff5abd049fd5bf41bb0d9a57dc0cd11d31a755 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Mon, 23 Nov 2026 11:52:43 -0800 Subject: [PATCH 13/19] fix(setup-token): log why a reaper release fails and guard restart cleanup (#22667) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A Claude subscription login in a sandbox environment runs `claude setup-token` and keeps a durable cleanup row with the session and its provider lease > - The setup-token reaper releases the lease and removes the row when the session is terminal, past its deadline, or consumed > - #14777 reports a reaper that failed to release the same leases every 30 seconds forever after a restart, and logged no cause > - #15200 later fixed the cause: a session with no lease had a blank lease id, and the UUID lookup for it failed on every sweep > - The reaper still discards the error, so the next permanent failure will be just as hard to diagnose, and no test covers the restart case > - This pull request logs the error class and code, and adds a PostgreSQL regression test for the reported restart case > - The benefit is that operators can see why a release fails, and the restart cleanup stays fixed ## Linked Issues or Issue Description Fixes #14777 Refs #15200 (the blank lease id fix). Overlapping open pull requests for the same issue: #15363 (logs the full error message), #16663, #18706, #19446, #18088, #14236. ## What Changed - `setup-token-session.ts`: when a lease release fails, the reaper logs `Cause: ()` for the error and up to three of its causes, for example `DrizzleQueryError > PostgresError (22P02)`. It does not log the error message, because a database or provider message can quote input values. A thrown value that is not an `Error` logs `unknown error`. The record stays retryable, as before. - `setup-token-reaper.test.ts`: three tests for the log line, including a database error wrapped by the query layer. They check that the message text is not logged. - `login-cleanup-work.test.ts`: a PostgreSQL test with the production reaper. A restart left two sandbox setup-token sessions in `submitting` past their deadline, one with no lease and one with a lease. One sweep releases both, the lease goes through the environment driver, and the next sweep finds nothing. With the #15200 guard removed, this test fails with `{ released: 1, failed: 1 }`, which is the reported symptom. What the issue reported, and where it stands on `master`: | Report | State | |---|---| | Release fails every 30 s forever | Fixed by #15200. This PR adds the regression test. | | Reaper swallows the cause | Fixed here. | | Cancel answers `200 {}` and cancels nothing after a restart | The route now falls back to a durable cancel for `starting` and `awaiting_code`. A `submitting` session is not cancellable on purpose (a credential write may be in progress), and the route keeps its uniform `200` answer. Such a session leaves `/active` when its 5-minute deadline passes, and the next sweep releases it. | | No cancel in the UI | The UI now calls the cancel route. | | Local subscription logins | They now use a separate flow (`local-ai-login.ts`). This reaper skips `local_subscription` rows. | ## Verification - `pnpm exec vitest run server/src/services/setup-token-session.test.ts server/src/services/setup-token-reaper.test.ts server/src/__tests__/login-cleanup-work.test.ts`: 3 files, 90 tests passed. - The two log tests fail on `master`. The restart test fails when the #15200 guard is removed. - `pnpm --filter @paperclipai/server typecheck` passes. ## Risks - Low risk. The change adds a log field and tests. - This pull request does not add a startup sweep that ends every live session at boot. In a rolling deploy, an old process can still be completing a login while the new one starts, so the 5-minute deadline stays the recovery path. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with shell, file edit, and code execution tools. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --- .../src/__tests__/login-cleanup-work.test.ts | 27 +++++++++++- .../src/services/setup-token-reaper.test.ts | 42 +++++++++++++++++++ server/src/services/setup-token-session.ts | 19 ++++++++- 3 files changed, 85 insertions(+), 3 deletions(-) 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/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 }; From eada94a6d293b6723f74ec264cf7855c7f77c6da Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Mon, 23 Nov 2026 11:52:50 -0800 Subject: [PATCH 14/19] fix(storage): answer storage throttling with 503 and retry skill archive uploads (#22664) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - First-agent setup saves the agent's skill packages to object storage (S3 on hosted installs) > - S3 can answer an upload with `503 SlowDown` when it limits the request rate > - The S3 provider retries a throttled upload, but when the retries run out the error reaches the HTTP error handler unclassified > - The person then sees "Internal server error", and the server reports a handler crash for a transient storage condition > - This pull request answers a storage-unavailable error with 503 and retry guidance, and makes the skill archive upload always use the retryable file-source path > - The benefit is that a throttle is retried, persistent throttling gives a clear retryable answer, and crash reports stay for real faults ## Linked Issues or Issue Description **What happened?** During first-agent setup, a skill package upload hit S3 request-rate throttling (`SlowDown`, HTTP 503). The person saw "Internal server error". The server logged `error.handler_crash` with `error_code=SlowDown`. A retry soon after got "This skill package is being saved. Retry after its upload settles." on a build before #22477. **Expected behavior** A transient throttle is retried. Persistent throttling answers with a retryable status and guidance. The same person can retry at once. **Steps to reproduce** 1. Use S3 storage and make the bucket answer `PUT` with `503 SlowDown` until the provider's retries run out. 2. Start first-agent setup, or call `skillPackageStore().prepare` for a new package. 3. The request fails with 500, and the error handler reports a crash. **Paperclip version or commit** `master` at `5f5ac154368`. **Deployment mode** Hosted (S3 storage). Self-hosted installs with S3-compatible storage behave the same way. Refs #22477 (failed upload claims expire at once, so an immediate retry no longer gets 409). Refs #22404 (throttle backoff for small uploads without a source file). ## What Changed - `error-handler.ts`: a recorded storage-unavailable error (throttling, 5xx, timeouts, network failures, as `isStorageUnavailableError` already defines) answers `503` with `Retry-After: 30` and code `storage_unavailable`. The response text is fixed. The handler logs the fixed-shape storage diagnostics (operation, error code, HTTP status, request id) as a warning, not as a crash. Storage credential rejections still report as server faults. - `error-handler.ts`: the client-abort shortcut (`aborted` with `ECONNRESET`, answered as 499) no longer catches a recorded storage failure. A storage read that the backend reset now answers 503 while the caller is still connected. - `storage-unavailable.ts`: add the response text and `recordedStorageFailureDiagnostics`. - `skill-package-store.ts`: pass the staged archive as `sourceFile`. The S3 provider then re-reads the file on each attempt, so it can resend the archive after a throttle even when the shared upload buffer is full. The upload also gets a Content-MD5 check. - The claim behavior from #22477 does not change: a failed attempt's claim expires at once, its exact keys go to the deletion outbox, and a retry uses fresh keys. - New test `storage-unavailable-error-handler.test.ts`: a storage connection reset answers 503, and a storage credential rejection still reports as a server fault. - New test `skill-package-storage-throttle.test.ts` (real PostgreSQL, the real S3 provider, and a local S3 stand-in): a transient `SlowDown` is resent and the package publishes; persistent throttling answers 503 with no crash report, and an immediate retry by the same caller succeeds. ## Verification - `pnpm exec vitest run server/src/__tests__/skill-package-storage-throttle.test.ts`: 2 passed. Both tests fail on `master` (no Content-MD5 on the archive upload; 500 instead of 503). - Related suites (skill package store and upload, error handler, sandbox outage handler, storage-unavailable, S3 throttle and backoff): 17 files, 175 tests passed. - `pnpm --filter @paperclipai/server typecheck` passes. ## Risks - Other routes that fail on a storage outage now answer 503 instead of 500 and do not send a crash report. This is the intent, but storage outages are now visible only as warning logs, not as crash reports. - The archive upload now hashes the archive for Content-MD5 before it sends it. Skill archives are small, so the cost is low. - This change does not explain why one company's prefix hit the S3 request-rate limit. That needs a separate operations check. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with shell, file edit, and code execution tools. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --- .../skill-package-storage-throttle.test.ts | 154 ++++++++++++++++++ .../storage-unavailable-error-handler.test.ts | 45 +++++ server/src/middleware/error-handler.ts | 16 +- server/src/services/skill-package-store.ts | 2 +- server/src/storage/storage-unavailable.ts | 6 + 5 files changed, 221 insertions(+), 2 deletions(-) create mode 100644 server/src/__tests__/skill-package-storage-throttle.test.ts create mode 100644 server/src/__tests__/storage-unavailable-error-handler.test.ts 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/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/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/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); From 7f343549dbf9e2aa0fbbcaaa2bda23d3558783b8 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Mon, 23 Nov 2026 11:52:56 -0800 Subject: [PATCH 15/19] fix(ai-connections): tell people why an API key could not be verified (#22666) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - During onboarding, a person can connect a model with a provider API key. Paperclip checks the key with one request to the provider before it stores it > - `validateAiApiKey` returns "The provider rejected this API key." only for 401 and 403. Every other answer, and every network error, returns "The provider could not verify this account. Try again." > - The server does not log the upstream status, so nobody can tell later what the provider said > - A person whose key is valid but whose account has no credit, is rate-limited, or hits a provider outage cannot know what to fix > - This pull request gives each case its own code and message, and logs the status and the provider's error type without the key > - The benefit is that people can fix the real problem, and support can see the provider's answer in the logs ## Linked Issues or Issue Description **What happened?** During onboarding, a person entered a Claude API key and saw "Could not store the API key: The provider could not verify this account. Try again." They then switched to a Claude subscription. The server log did not show which status the provider returned. **Expected behavior** The person learns whether the key is wrong, the account has no credit, the provider is limiting requests, or the provider is down. The server logs the upstream status. **Steps to reproduce** 1. Call `validateAiApiKey("anthropic", key, request)` with a `request` stub that returns 400, 402, 429 or 500. 2. Observe that all four throw `ai_connection_verification_failed` with the same message. **Paperclip version or commit** `master` at `5f5ac154368`. **Deployment mode** Hosted onboarding. Self-hosted installs use the same check. Refs #12675 (related: server-owned user-secret definitions for onboarding API keys). ## What Changed - `ai-api-key-failures.ts` (new): one code and message for each result. The codes are `ai_connection_api_key_rejected` (unchanged), `ai_connection_billing_required`, `ai_connection_rate_limited`, `ai_connection_provider_unavailable`, `ai_connection_verification_timeout`, `ai_connection_provider_unreachable`, and `ai_connection_verification_failed` (unchanged, for all other answers). - `ai-api-key-test.ts`: map 401/403 to rejected (unchanged); 402, or the error type `billing_error`, `insufficient_quota` or `insufficient_credits`, to billing; 429 to rate limited; 5xx (including Anthropic's 529) to provider unavailable. A `TimeoutError` maps to timeout, and other network errors map to unreachable. - Log the provider, the HTTP status, the provider's error type and the result code. The error type comes from `error.type`, `error.code` or `error.status` in at most 8 KiB of the error body. It is used and logged only when it is on a closed list of documented provider error types (Anthropic, OpenAI and xAI, Google, OpenRouter). Any other value is ignored. The key and the response text are never logged. 401/403 bodies are not read. - `adapters/registry.ts` and `agent-environment-test.ts`: keep the specific code in the environment check instead of collapsing it to rejected or failed. - The billing check looks at `error.type`, `error.code` and `error.status` together, so a 429 with `type: invalid_request_error` and `code: insufficient_quota` is a billing problem, not a rate limit. - `tests/runner-e2e`: the connection harness keeps every new code in `creationFailure` instead of saving it as `connection_request_rejected`. One shared list feeds `connection-flow.ts`, `connection-evidence.ts` and `result-validation.ts`, and a test keeps it equal to the server's codes. - Tests: `ai-api-key-test.test.ts` (17 tests) and `connection-support.test.ts`. **The user-facing text needs a person's review.** The new messages are a first draft. They read after the onboarding prefix "Could not store the API key:": | Code | Message | |---|---| | `ai_connection_billing_required` | The provider account for this API key has no credit or billing set up. Add credit with the provider, then try again. | | `ai_connection_rate_limited` | The provider is limiting requests for this account right now. Wait a minute, then try again. | | `ai_connection_provider_unavailable` | The provider is having problems right now. Try again in a few minutes. | | `ai_connection_verification_timeout` | The provider did not answer in time. Try again. | | `ai_connection_provider_unreachable` | Paperclip could not reach the provider. Check this server's network connection, then try again. | ## Verification - `pnpm exec vitest run server/src/services/ai-api-key-test.test.ts`: 17 passed. On `master`, 11 of the original 15 fail. - Callers: `ai-connections.test.ts`, `adapters/registry.test.ts`, `agent-environment-test-status.test.ts` and `agent-test-environment-routes.test.ts` with the new file: 5 files, 331 tests passed. - `pnpm --filter @paperclipai/server typecheck` passes. - Not run: a live check against each provider. The billing mapping uses the documented error types (`billing_error` for Anthropic, `insufficient_quota` for OpenAI, 402 for OpenRouter). The models endpoint may not report a billing problem for every provider. ## Risks - Low risk. The HTTP status of the store request stays 422, and 401/403 behavior does not change. - An answer that does not match a known case still returns `ai_connection_verification_failed`, as before. - A code that consumers compare by value can now be one of five new values. No UI code compares these codes, and the server callers now pass them through. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with shell, file edit, and code execution tools. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --- server/src/adapters/registry.ts | 6 +- server/src/services/agent-environment-test.ts | 5 +- server/src/services/ai-api-key-failures.ts | 17 +++ server/src/services/ai-api-key-test.test.ts | 103 ++++++++++++++++++ server/src/services/ai-api-key-test.ts | 84 ++++++++++++-- tests/runner-e2e/connection-evidence.ts | 14 ++- tests/runner-e2e/connection-flow.ts | 6 +- tests/runner-e2e/connection-support.test.ts | 10 +- tests/runner-e2e/result-validation.ts | 4 +- 9 files changed, 228 insertions(+), 21 deletions(-) create mode 100644 server/src/services/ai-api-key-failures.ts create mode 100644 server/src/services/ai-api-key-test.test.ts 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/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/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({ From ff68490d03601cdced37e21d919affb079fafc61 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Mon, 23 Nov 2026 11:53:02 -0800 Subject: [PATCH 16/19] fix(ai-connections): say why a local sign-in attempt ended (#22668) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Onboarding and the agent setup screen connect a subscription account with local sign-in (`useLocalAiLogin`) when the login environment is local and the server supports it > - A local sign-in attempt lasts 30 minutes. The client polls `POST /companies/:id/ai-connections/local/check` > - The check answers `{ status: "expired" }` whenever the attempt is no longer waiting for the user, not only after the deadline > - So a cancelled attempt, an attempt that "Start sign-in again" replaced, and an attempt that already connected the account all show "This sign-in attempt expired" > - This pull request keeps the status and adds the real reason as the error text that the sign-in panel already shows > - The benefit is that people see why sign-in stopped, and support can tell an expiry from a replacement ## Linked Issues or Issue Description **What happened?** A person saw "This sign-in attempt expired. Start sign-in again." during subscription sign-in, well inside the 30-minute attempt window. In `localAiLoginService().check`, any attempt whose status is not `waiting_for_user` answers `{ status: "expired" }`. That includes `cancelled` (a cancel, or a replacement by "Start sign-in again" in another tab or step), an attempt whose cancel is still in progress, and `authenticated` (already connected). **Expected behavior** "Expired" appears only when the 30-minute deadline has passed. A cancelled, replaced or completed attempt says what happened. **Steps to reproduce** 1. Start local sign-in for an account. 2. Choose "Start sign-in again" (or cancel the attempt). 3. Check the first attempt. It answers `{ status: "expired" }`, and the panel shows "This sign-in attempt expired". **Paperclip version or commit** `master` at `5f5ac154368`. **Deployment mode** Any deployment where local sign-in is available, including onboarding. ## What Changed - `local-ai-login.ts` `check()`: an attempt that is `authenticated` or has a connection answers `{ status: "expired", error: "This sign-in already connected the account." }`. An attempt that is `cancelled`, or whose cancel is still in progress, answers `{ status: "expired", error: "This sign-in attempt was cancelled or replaced by a newer one. Start sign-in again." }`. An attempt past its deadline or `timed_out` still answers `{ status: "expired" }`. - The `LocalAiLoginStatus` type and the client do not change. `useLocalAiLogin` already shows a server `error` before its default expiry text. - Test: `ai-legacy-compatibility.test.ts` covers a replaced attempt, a cancelled attempt, and a completed attempt. ## Verification - `pnpm exec vitest run server/src/__tests__/antigravity-local-ai-login.test.ts server/src/__tests__/ai-connections.test.ts server/src/__tests__/ai-legacy-compatibility.test.ts`: 3 files, 186 tests passed. - The new test fails on `master`. - `pnpm --filter @paperclipai/server typecheck` passes. ## Risks - Low risk. The status values stay the same, so client logic does not change. Only the error text changes for cancelled, replaced and completed attempts. - A completed attempt still answers `expired`, so the panel offers "Start sign-in again". Answering `ready` would let the client reconnect the same attempt, but it would also start the client's connect flow again, so this change keeps the existing status. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with shell, file edit, and code execution tools. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --- .../__tests__/ai-legacy-compatibility.test.ts | 19 +++++++++++++++++++ server/src/services/local-ai-login.ts | 4 ++++ 2 files changed, 23 insertions(+) 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/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); From 427d13c38c63133bc6a86f48557896f302a3dbeb Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:00:36 -0600 Subject: [PATCH 17/19] fix(connections): clean up audit-only task traces and wait without rescanning content (#22658) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - #22636 removes connection content (for example Google results) when a task or a company is deleted > - Review on #22636 found two more gaps after it merged > - A task whose only connection trace is an audit entry (for example a denied call) got no cleanup job, so the argument preview stayed after the task was deleted > - A cleanup job that waits for open runs re-ran all content steps on every recheck, which is wasted database work > - This pull request queues a job for audit-only tasks and adds a `waiting` phase that only counts open work > - The benefit is that no audit preview of a deleted task is left behind, and a waiting job stays cheap ## Linked Issues or Issue Description Refs #22636 **Problem** 1. Deleting a task whose only connection trace is a `tool_access_audit_events` row with the task's ID creates no cleanup job, so its argument preview stays. 2. While a task cleanup job waits for open runs or approvals, every recheck runs the six content steps again from the start. **Expected behavior** 1. The audit preview is cleared after the task is deleted. 2. A waiting job only checks whether work is still open, and runs the content steps once when the work settles. **Steps to reproduce** 1. Write a denied policy audit entry with the task's ID and no call or call event. Delete the task. The preview stays. 2. Delete a task while one of its runs is working. Each recheck scans every content table of the task again. ## What Changed - `issue-content-deletion.ts`: when the task has no recorded runs, calls or call events, check for an audit entry with the task's ID. If one exists, queue the job. The audit step already matches by task ID. - `content-deletion.ts`: new `waiting` phase. After a content pass with open work, the job moves to `waiting` instead of restarting. Each recheck counts open runs, open calls, open approvals and open wakes with results for the task. When the count is zero, or after the one-day bound, the job runs the content steps once more and finishes. - Moved the pure JSON cleaning helpers to `content-cleaning.ts` to keep `content-deletion.ts` under 1,000 lines. No behaviour change. - Two canary tests: a task with only an audit entry, and a waiting job that leaves new content alone on a recheck and clears it after the open run settles. Both failed before the fix. - The working memory note is updated. ## Verification - `cd server && npx vitest run src/__tests__/tool-connection-content-deletion-canary.test.ts src/__tests__/tool-connection-content-deletion.test.ts src/__tests__/server-startup-feedback-export.test.ts` (156 tests pass). The two new tests failed before the fix. - `cd server && pnpm typecheck` passes. ## Risks - Task deletion with no other connection trace runs one more query on `tool_access_audit_events` for the company, with `limit 1`. That table has no index on the task ID in its details. - No schema change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use (shell, file edit, test runs). Extended reasoning on. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- doc/memory/google-connector-memory.md | 6 +- .../issue_connection_content_deletions.ts | 2 +- ...connection-content-deletion-canary.test.ts | 121 ++++++++++++++++- .../connections/content-cleaning.ts | 42 ++++++ .../connections/content-deletion.ts | 128 ++++++++++-------- .../connections/issue-content-deletion.ts | 20 ++- 6 files changed, 251 insertions(+), 68 deletions(-) create mode 100644 server/src/services/tool-access/connections/content-cleaning.ts diff --git a/doc/memory/google-connector-memory.md b/doc/memory/google-connector-memory.md index dafe7633f3b..ccfc382edb0 100644 --- a/doc/memory/google-connector-memory.md +++ b/doc/memory/google-connector-memory.md @@ -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/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/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/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, From 7906db1ac9b80cde22405bfdf5677f053abad4d7 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:18:19 -0600 Subject: [PATCH 18/19] fix(apps): title the Google AI connector "Google Antigravity and Gemini" (#22673) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The Connectors page lists the services and model providers that a company can connect > - The Google model-provider connector has the title "Google" > - That title does not tell people that this connector is for Google Antigravity sign-in and Gemini API keys. It is easy to confuse with the Google Workspace connectors > - This pull request changes the connector title to "Google Antigravity and Gemini" > - The benefit is that people can find the correct connector for their Google AI accounts ## Linked Issues or Issue Description **What existing behavior does this improve?** The title of the Google model-provider connector on the Connectors page. **Subsystem affected** UI: the Connectors page (`//apps`) and the shared app definition for `google`. **Current behavior** The connector title is "Google". The title does not name the products that it connects, and people can confuse it with the Google Workspace connectors. **Proposed behavior** The connector title is "Google Antigravity and Gemini". **Reason and benefit** People can find the correct connector for Google Antigravity sign-in and Gemini API keys. **Breaking changes** None. The provider id, the app slug, and all stored values stay the same. ## What Changed - Change the `name` of the `google` app definition (`packages/shared/src/app-definitions/google.json`). - Before: `Google` - After: `Google Antigravity and Gemini` - These texts read the name, so they also change: - Card heading: `Google` -> `Google Antigravity and Gemini` - Card button accessible name: `Connect Google` -> `Connect Google Antigravity and Gemini`. The visible button text stays `Connect`. - Setup screen heading: `Connect Google` -> `Connect Google Antigravity and Gemini` - The service name that new connection requests show to agents and in chat cards. - Add a Connectors page test that checks the new card title, description, and button name. - Resync `tests/runner-e2e/source-sdk-public-inputs.json`, because the app definition is a pinned input. Not changed, on purpose: - The provider id `google`, the app slug `google`, and all stored values. Existing application rows are found by their `app-gallery:google` key, not by name. - The short provider name `Google` in `ui/src/components/ai-connections/model.ts` and `packages/shared/src/ai-connections.ts`. Sentences such as "Your Google default" and default account names such as "My Google API account" use this name. Account names are stored when people create them, and the long title makes these sentences awkward. - The `Google` choice in the model provider picker, next to `OpenAI`, `Anthropic`, and `xAI`. Its description already says "Antigravity sign-in or Gemini API key". - The Google Workspace and Search Console connectors. ## Verification - Red/green: `cd ui && npx vitest run src/pages/apps/Browse.test.tsx -t "Antigravity and Gemini"` fails with the old name and passes with the new name. - `cd ui && npx vitest run src/pages/apps/Browse.test.tsx` passes (119 tests). - `cd ui && npx vitest run src/components/ai-connections src/pages/apps/AppsConnect.test.tsx` passes (362 tests). - `cd packages/shared && npx vitest run src/app-definitions` passes (50 tests). - `pnpm verify` exits 2 because the pinned-input registry changed. Required CI supplies the broad coverage. ## Risks - Low risk. This is a display text change. - Old chat cards keep the service name that they stored when they were created ("Google"). This is only display text. - The Connectors page matches aggregator apps by slug and name. The slug `google` does not change, so the match does not change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- packages/shared/src/app-definitions/google.json | 2 +- tests/runner-e2e/source-sdk-public-inputs.json | 2 +- ui/src/pages/apps/Browse.test.tsx | 9 +++++++++ 3 files changed, 11 insertions(+), 2 deletions(-) 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/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 28eec022ac9..ddfc3d3bc2c 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -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", 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); From 32375d302fbc3a233531674aedefa273adee2d97 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:41:47 -0600 Subject: [PATCH 19/19] test(cloud): read durable-data blocker names from the check() calls (#22686) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The online durable-data migration pass names every blocker that the volume-free readiness check can report > - A test reads the blocker names from `ephemeral-server-contract.ts` with a regex, and checks that the pass names each one > - #22641 added that test. It looks for `blockers.push("...")` > - #22646 merged at about the same time. It moved each check into a `check(area, blocker, inspect)` helper, so the regex now finds no names > - The test fails on master, in `ci / General tests (server (8/12))`, on every pull request > - This pull request changes the regex to read the blocker name from each `check(...)` call > - The benefit is that shard 8/12 is green again, and the test again covers every blocker ## Linked Issues or Issue Description Refs #22641 (added the test). Refs #22646 (changed the source the test reads). Refs #22682 (blocked by this failure). **What happened?** `server/src/services/online-durable-data-migration.test.ts > names every durable-data blocker that readiness can report` fails on master `b865dd112b`: ``` - Expected + Received - ArrayContaining [ "workspaces_require_migration", "local_instruction_copies_require_settlement", "external_agent_instructions" ] + [ "runtime_skill_assets_require_migration" ] ``` **Why?** The regex `/blockers\.push\("([a-z_]+)"\)/g` matched nothing after #22646. Only the constant that the test adds by hand stayed in the list. **Expected behavior** The test finds the 10 blocker names (9 from the source, plus `RUNTIME_SKILL_ASSETS_BLOCKER`) from the `check(...)` calls and checks each one. ## What Changed - Change the scan regex in the test to `/(?:blockers\.push\(|check\(\s*"[a-z_]+",)\s*"([a-z_]+)"/g`. It reads the blocker name from each `check(area, blocker, ...)` call, also when the call spans lines. It still reads the old `blockers.push("...")` form. - No product code changes. ## Verification - `cd server && npx vitest run src/services/online-durable-data-migration.test.ts` - On master: 1 failed, 31 passed (the failure above). - With this change: 32 passed. - The existing `arrayContaining` check still fails if a later refactor makes the scan find nothing again. ## Risks - Low risk. Only one test regex changes. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with shell, file edit, and code execution tools. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- server/src/services/online-durable-data-migration.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/src/services/online-durable-data-migration.test.ts b/server/src/services/online-durable-data-migration.test.ts index 6cb3e69f263..9f594546974 100644 --- a/server/src/services/online-durable-data-migration.test.ts +++ b/server/src/services/online-durable-data-migration.test.ts @@ -337,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();