diff --git a/doc/memory/google-connector-memory.md b/doc/memory/google-connector-memory.md index 6e9e6541231..303f5612579 100644 --- a/doc/memory/google-connector-memory.md +++ b/doc/memory/google-connector-memory.md @@ -408,7 +408,7 @@ nested run answers and migrated log originals. | Approval requests and their approval cards in the task | Preview, arguments and the executed result | Yes, for settled requests. | Yes. Cards are deleted with the task; requests are cleared. | Yes, rows deleted | | Results passed to a later run (run context and wake payload) | Approved action results | Yes, for settled runs and wakes. | Yes | Yes, rows deleted | | App views | Tool input, result and shared context | Yes, rows deleted. | Yes, rows deleted | Yes, rows deleted | -| Run transcripts: the run log in every copy (object journal, archive, original local file and its S3 mirror), run events, output excerpts and answer text at any depth of the run result | Full content | Yes, the whole transcript of every settled run that called the connection or received an approved result. | Yes, for each of the task's runs that called a connection or received an approved result. The runs themselves stay. | Yes. Rows deleted, then every run log is removed from storage in the background. | +| Run transcripts: the run log in every copy (object journal, archive, original local file and its S3 mirror), run events, output excerpts, answer text at any depth of the run result, the free text of every `paperclip.run_result.v1` object in `result_json` (for example `nativeResult` evidence refs, verification details and completion-claim evidence refs), and the session checkpoint copy in `runner_profile_json.sessionCheckpoint` (`semanticResult`, `governedWait.result` and `governedWait.sourceEvent.payload`; `terminalTurns[]` fingerprints become `sha256:` hashes). In a run result only the fixed enum fields (by exact path) and `completionClaim.contractRevision` stay; criterion ids, target agent ids, `idempotencyKey` and `handoffId` become `sha256:` hashes; every other string becomes "Removed because the connection data was deleted.", so the result stays valid | Full content | Yes, the whole transcript of every settled run that called the connection or received an approved result. | Yes, for each of the task's runs that called a connection or received an approved result. The runs themselves stay. | Yes. Rows deleted, then every run log is removed from storage in the background. | | Saved tool results over 500,000 bytes (`runner-api` files and their asset rows) | Full result | Yes, for the runs whose transcript is deleted. Files attached to a task stay. | Yes, for those runs | Yes, file and row | | Comments, documents and attached files agents wrote into tasks | Whatever the agent copied | No, by design. The user edits or deletes them, or the task. | Yes. Attached files are also removed from storage, and retried until it succeeds. | Yes. Every company file is removed from storage in the background. | | Transcripts of later runs that read an app view's shared context | Shared context | No. Nothing records which runs read it. | Only when the run belongs to the deleted task | Yes | @@ -506,6 +506,31 @@ the person chose to disconnect that identity. crash between saving and clearing is never resumed. - A refresh failure counts only if the refresh still holds the grant's refresh lease; a late answer after a new sign-in deletes nothing. +- Connection state (November 25): when a refresh marks a grant + `needs_reauthorization` and no grant on the connection is still active, the + connection gets the existing expired-sign-in state: `health_status` `error`, + `last_error` `oauth_reauthorization_required` and the message "Access to + this app ended. Reconnect to continue." Its status and + enabled flag do not change, so the app list shows "Needs attention" (not + "Paused") and a reconnect keeps the chosen tools. The tool gateway does not + offer a connection's tools while it has a `needs_reauthorization` grant and + no active grant. A successful reconnect refreshes the catalog and sets + health back to `ok`. The removal message and dialog count a connection as + "available to agents" only when it is on, is not waiting for a new sign-in, + and its tools are offered (healthy, personal, or plugin). +- Each store carries its own mark: `result_json.answerCopiesDeletedAt` and + `sessionCheckpoint.contentDeletedAt`. A run in scope whose run result or + checkpoint lacks its mark is cleaned again, so runs cleaned by an older + build, and a checkpoint rewritten later, are fixed by the next deletion. + The control-plane port also cleans a checkpoint it writes for a run whose + result has `contentDeletedAt`. +- Kept on purpose: the task description and prompt copies + (`contextSnapshot.paperclipIssue.description`, + `runnerProfileJson.nativeExecutionInput.task`), which are the user's text, + and structural run fields (status, schema, disposition, criterion ids, + check status, counts, hashes). Not yet covered: the encrypted controller + checkpoint rows (`native_runner_checkpoints`), which the harness backup + expiration removes. - New in the job for every app: tool error text (`tool_invocations` and `tool_call_events` `error_message`, the approval card's `toolAction.errorMessage`), and the session pointers above. diff --git a/docs/guides/board-operator/deleting-connection-data.md b/docs/guides/board-operator/deleting-connection-data.md index 51ad72a1747..7da795cc4e7 100644 --- a/docs/guides/board-operator/deleting-connection-data.md +++ b/docs/guides/board-operator/deleting-connection-data.md @@ -28,7 +28,7 @@ When Paperclip's access to a Google account ends, Paperclip deletes what agents Deletion starts at once. Runs that are still working keep their data until they finish; Paperclip then deletes it too. While work is still running, Paperclip checks again every few minutes, and every hour after the first day. If a step fails, Paperclip keeps trying until it succeeds, also after a restart. The connection's activity shows when the deletion started and when it finished. -The deletion covers everything listed under "What is deleted" for that connection, for all people who used it. If you connect Google again later, Paperclip saves new data from new calls only. Data that was deleted does not come back. Agents also do not resume the conversations of those runs; their next run starts a new one. +The connection then shows **Needs attention**, and agents are not offered its tools until someone signs in to Google again. The deletion covers everything listed under "What is deleted" for that connection, for all people who used it. If you connect Google again later, Paperclip saves new data from new calls only. Data that was deleted does not come back. Agents also do not resume the conversations of those runs; their next run starts a new one. ## Technical details from Google @@ -64,6 +64,7 @@ Deletion starts right away and continues in the background. It finishes even if - Approval previews, arguments and results for those calls, on the approval card and in what was passed back to the agent - Interactive app views from those calls - The whole transcript of every run that called the connection or received an approved action's result, including that run's other steps and its final summary +- The final answer that run reported and the evidence it gave for it, such as links, quoted text and check details. The run page still shows the run's status and outcome. - Tool results too large to pass to the agent directly, which Paperclip saved as files for those runs - Error messages the app returned for those calls - The saved conversation that agents resume in later runs, for the runs whose transcript is deleted. The agent's next run starts a new conversation. diff --git a/server/src/__tests__/google-managed-connection-removal.test.ts b/server/src/__tests__/google-managed-connection-removal.test.ts index 634413cba5c..b51bd3546b0 100644 --- a/server/src/__tests__/google-managed-connection-removal.test.ts +++ b/server/src/__tests__/google-managed-connection-removal.test.ts @@ -4,6 +4,9 @@ import request from "supertest"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import { activityLog, + agents, + heartbeatRuns, + toolGatewaySessions, companyMemberships, companySecrets, connectionGrants, @@ -23,6 +26,7 @@ import { logger } from "../middleware/logger.js"; import { PaperclipCloudConnectorError, type PaperclipCloudConnector } from "../services/paperclip-cloud-connector.js"; import { localEncryptedProvider } from "../secrets/local-encrypted-provider.js"; import { accessService } from "../services/access.js"; +import { createToolGatewayService } from "../services/tool-gateway.js"; import { DELIVERY_QUEUES, subscribeDeliveryWork } from "../services/delivery-work-notifications.js"; import { revokeGoogleAccessForRemovedInstance } from "../services/tool-access/connections/google-pending-revocation.js"; import { @@ -627,6 +631,64 @@ describeEmbeddedPostgres("removing a Paperclip-managed Google connection", () => expect(await contentDeletions(fixture.connectionId)).toEqual([{ status: "pending", reason: "provider_access_ended" }]); }); + it.each(["user", "organization"] as const)("shows a %s connection needs signing in again and stops offering its tools after Google access ends", async (grantKind) => { + const fixture = await connectManagedGmail(grantKind); + vi.spyOn(globalThis, "fetch").mockImplementation(async (_url, init) => { + const body = JSON.parse(String(init?.body)); + if (body.method === "notifications/initialized") return new Response(null, { status: 202 }); + return Response.json({ jsonrpc: "2.0", id: body.id, result: body.method === "initialize" ? { protocolVersion: "2025-06-18" } + : { tools: [{ name: "search_threads", description: "Search mail", inputSchema: { type: "object", properties: {} }, annotations: { readOnlyHint: true } }] } }); + }); + const actor = { actorType: "user" as const, actorId: fixture.userId }; + await fixture.service.refreshCatalog(fixture.connectionId, actor, { enableAllByDefault: true }); + const [agent] = await db.insert(agents).values({ + companyId: fixture.company.id, name: "Mail agent", role: "engineer", status: "active", adapterType: "process", adapterConfig: {}, runtimeConfig: {}, + }).returning(); + const [run] = await db.insert(heartbeatRuns).values({ + companyId: fixture.company.id, agentId: agent!.id, invocationSource: "on_demand", status: "running", responsibleUserId: fixture.userId, + }).returning(); + const gateway = createToolGatewayService(db); + const offered = async () => { + const session = await gateway.createSession({ companyId: fixture.company.id, agentId: agent!.id, runId: run!.id }); + return (await gateway.listToolsForSession(session.token)).filter((tool) => tool.connectionId === fixture.connectionId).length; + }; + let toolName = ""; + try { + expect(await offered()).toBe(1); + const firstSession = await gateway.createSession({ companyId: fixture.company.id, agentId: agent!.id, runId: run!.id }); + toolName = (await gateway.listToolsForSession(firstSession.token)).find((tool) => tool.connectionId === fixture.connectionId)!.name; + fixture.connector.refresh.mockRejectedValueOnce( + new PaperclipCloudConnectorError("rejected", "REAUTHORIZATION_REQUIRED", 409, undefined, "PROVIDER_REAUTHORIZATION_REQUIRED"), + ); + await expect(fixture.service.refreshOAuthGrantCredentials({ + companyId: fixture.company.id, connectionId: fixture.connectionId, grantId: fixture.grant.id, forceRefresh: true, + })).rejects.toMatchObject({ details: { code: "oauth_reauthorization_required" } }); + + const [ended] = await db.select().from(toolConnections).where(eq(toolConnections.id, fixture.connectionId)); + expect(ended).toMatchObject({ status: "active", enabled: true, healthStatus: "error", lastError: "oauth_reauthorization_required" }); + expect(ended!.healthMessage).toBe("Access to this app ended. Reconnect to continue."); + expect(await offered()).toBe(0); + const session = await gateway.createSession({ companyId: fixture.company.id, agentId: agent!.id, runId: run!.id }); + const execution = await gateway.executeTool({ sessionToken: session.token, tool: toolName, parameters: {} }).catch((error: unknown) => error); + expect(execution).not.toMatchObject({ reasonCode: "tool_not_found" }); + + const started = await fixture.service.startOAuth(fixture.company.id, fixture.connectionId, { + redirectUri: "https://paperclip.example/api/tools/oauth/cloud-connector/callback", actor, + }); + await fixture.service.completePaperclipCloudConnectorCallback({ + state: new URL(started.authorizationUrl).searchParams.get("state")!, claimId: "reconnect-claim", actor, + }); + const [reconnected] = await db.select().from(toolConnections).where(eq(toolConnections.id, fixture.connectionId)); + expect(reconnected).toMatchObject({ status: "active", enabled: true, healthStatus: "ok" }); + expect(await offered()).toBe(1); + } finally { + await db.delete(toolGatewaySessions).where(eq(toolGatewaySessions.companyId, fixture.company.id)); + await db.delete(activityLog).where(eq(activityLog.companyId, fixture.company.id)); + await db.delete(heartbeatRuns).where(eq(heartbeatRuns.companyId, fixture.company.id)); + await db.delete(agents).where(eq(agents.companyId, fixture.company.id)); + } + }); + it("keeps the content when a late refresh failure answers after the grant was signed in again", async () => { const fixture = await connectManagedGmail(); fixture.connector.refresh.mockImplementation(async () => { diff --git a/server/src/__tests__/tool-access-oauth-protocol.integration.test.ts b/server/src/__tests__/tool-access-oauth-protocol.integration.test.ts index c74279f6ebd..8b5081101de 100644 --- a/server/src/__tests__/tool-access-oauth-protocol.integration.test.ts +++ b/server/src/__tests__/tool-access-oauth-protocol.integration.test.ts @@ -354,7 +354,9 @@ describe("tool OAuth over local HTTP", () => { // Restore this fixture's original authorization metadata to exercise // manual replacement separately. The recovery worker is already stopped. await db.update(toolConnections).set({ status: beforeReauthConnection.status, - enabled: beforeReauthConnection.enabled, credentialRefs: beforeReauthConnection.credentialRefs, + enabled: beforeReauthConnection.enabled, healthStatus: beforeReauthConnection.healthStatus, + healthMessage: beforeReauthConnection.healthMessage, lastError: beforeReauthConnection.lastError, + credentialRefs: beforeReauthConnection.credentialRefs, credentialSecretRefs: beforeReauthConnection.credentialSecretRefs, }).where(eq(toolConnections.id, connection.id)); await db.update(connectionGrants).set({ status: "active", credentialSecretRefs: beforeReauthGrant.credentialSecretRefs, diff --git a/server/src/__tests__/tool-connection-content-deletion.test.ts b/server/src/__tests__/tool-connection-content-deletion.test.ts index 1cb9cb057a4..10d6c92fa2c 100644 --- a/server/src/__tests__/tool-connection-content-deletion.test.ts +++ b/server/src/__tests__/tool-connection-content-deletion.test.ts @@ -16,6 +16,8 @@ import { agentWakeupRequests, agents, companies, + completionContracts, + nativeRunResults, createDb, heartbeatRunEvents, heartbeatRuns, @@ -42,6 +44,10 @@ import { deleteGoogleContentWhenAccessEnds } from "../services/tool-access/conne import { forgetSessionsOfDeletedRun, runContentDeleted } from "../services/tool-access/connections/run-session-reset.js"; import type { RunLogHandle, RunLogStore } from "../services/run-log-store.js"; import { toolAccessRoutes } from "../routes/tool-access.js"; +import { hasAcceptedSemanticResult } from "../services/heartbeat-run-summary.js"; +import { nativeSha256 } from "../services/native-runtime/canonical.js"; +import { checkpointProfileForRun, DELETED_TEXT } from "../services/tool-access/connections/content-cleaning.js"; +import { validatePrpStructuredRunResult } from "../vendor/paperclip-runner/index.js"; import { errorHandler } from "../middleware/index.js"; const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); @@ -469,6 +475,133 @@ describeEmbeddedPostgres("deleting content stored from a connection's tool calls expect(revisionAgain!.body).toBe(""); }); + it("removes the run's final answer and evidence from its result and session checkpoint, and keeps the task text", async () => { + const runLogs = memoryRunLogs(); + const service = createConnectionContentDeletion(db, { runLogStore: () => runLogs.store }); + const seed = await seedCompany(runLogs); + const link = "https://docs.google.com/document/d/board-notes/edit"; + const answer = { + schema: "paperclip.run_result.v1", + reportedWorkDisposition: "done", + summary: SECRET, + evidence: [{ kind: "url", ref: link }], + verification: [{ commandOrCheck: `Read ${link}`, status: "passed", detail: SECRET }], + completionClaim: { contractRevision: "rev-1", objectiveSatisfied: true, criteria: [{ criterionId: "c1", status: "satisfied", evidenceRefs: [link], explanation: SECRET }], remainingWork: [] }, + artifacts: [{ kind: `${SECRET} kind`, ref: link, title: SECRET }], + continuation: { kind: "response_wake", summary: SECRET, idempotencyKey: "wake-1" }, + }; + expect(validatePrpStructuredRunResult(answer).issues).toEqual([]); + const fingerprint = JSON.stringify({ terminalState: "completed", result: answer }); + const checkpoint = { + backendKind: "harness", driverKind: "codex_app_server", sessionId: "session-1", activeTurnId: null, + identity: { runId: seed.settledRun.id }, + semanticResult: answer, + governedWait: { sourceEvent: { type: "tool.execution.completed", payload: { toolName: "read_doc", output: SECRET } }, result: answer }, + terminalTurns: [{ turnId: "turn-1", fingerprint }], + }; + const task = { description: "Summarise the board notes in the shared drive" }; + const profile = { nativeExecutionInput: { task }, sessionCheckpoint: checkpoint, nativeControllerRecovery: { schema: "paperclip.native-controller-recovery.v1", snapshotSha256: nativeSha256(checkpoint) } }; + await db.update(heartbeatRuns).set({ + resultJson: { executionRecovery: { kind: "none" }, nativeResult: answer, nativeTerminal: { schema: "paperclip.prp.terminal.v1", runTerminalState: "succeeded" } }, + runnerProfileJson: profile, + contextSnapshot: { paperclipIssue: { description: task.description } }, + }).where(eq(heartbeatRuns.id, seed.settledRun.id)); + + const [issue] = await db.insert(issues).values({ companyId: seed.company.id, title: "Native answer" }).returning(); + const [contract] = await db.insert(completionContracts).values({ + companyId: seed.company.id, issueId: issue!.id, revision: 1, schemaVersion: "v1", policyVersion: "v1", risk: "low", + completionAuthority: "agent", incompleteCriteriaPolicy: "block", contractJson: {}, canonicalSha256: "contract-hash", + createdByActorType: "user", createdByActorId: "board-user", + }).returning(); + await db.update(heartbeatRuns).set({ issueId: issue!.id, nativeIssueId: issue!.id, completionContractId: contract!.id }) + .where(eq(heartbeatRuns.id, seed.settledRun.id)); + const terminal = { schema: "paperclip.prp.terminal.v1", runTerminalState: "succeeded", turnTerminalState: "completed", reportedWorkDisposition: "done" }; + const [nativeResult] = await db.insert(nativeRunResults).values({ + companyId: seed.company.id, issueId: issue!.id, runId: seed.settledRun.id, completionContractId: contract!.id, + serverFingerprint: "server-fingerprint", schemaStatus: "accepted", canonicalSha256: "result-hash", + resultJson: { result: answer, terminal, normalizationDiagnostics: { ignoredAttentionRequests: [] } }, + }).returning(); + + await service.request(seed.connection, { actorType: "user", actorId: "board-user" }); + await drain(service); + + const [storedResult] = await db.select().from(nativeRunResults).where(eq(nativeRunResults.id, nativeResult!.id)); + expect(JSON.stringify(storedResult!.resultJson)).not.toContain(SECRET); + expect(JSON.stringify(storedResult!.resultJson)).not.toContain("board-notes"); + expect(storedResult!.resultJson).toMatchObject({ terminal, result: { schema: "paperclip.run_result.v1", reportedWorkDisposition: "done", summary: DELETED_TEXT } }); + expect(validatePrpStructuredRunResult((storedResult!.resultJson as { result: unknown }).result)).toMatchObject({ ok: true }); + + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, seed.settledRun.id)); + for (const value of [run!.resultJson, run!.runnerProfileJson]) { + expect(JSON.stringify(value)).not.toContain(SECRET); + expect(JSON.stringify(value)).not.toContain("board-notes"); + } + expect(run!.status).toBe("succeeded"); + expect(run!.resultJson).toMatchObject({ + executionRecovery: { kind: "none" }, + nativeTerminal: { schema: "paperclip.prp.terminal.v1", runTerminalState: "succeeded" }, + nativeResult: { schema: "paperclip.run_result.v1", reportedWorkDisposition: "done", + verification: [{ status: "passed" }], completionClaim: { contractRevision: "rev-1", objectiveSatisfied: true, criteria: [{ criterionId: expect.stringMatching(/^sha256:[a-f0-9]{64}$/), status: "satisfied" }] }, + continuation: { kind: "response_wake", idempotencyKey: expect.stringMatching(/^sha256:[a-f0-9]{64}$/), summary: DELETED_TEXT } }, + }); + expect(hasAcceptedSemanticResult(run!.resultJson)).toBe(true); + const cleanedAnswer = (run!.resultJson as { nativeResult: unknown }).nativeResult; + expect(validatePrpStructuredRunResult(cleanedAnswer)).toMatchObject({ ok: true }); + expect(cleanedAnswer).toMatchObject({ summary: DELETED_TEXT, evidence: [{ kind: DELETED_TEXT, ref: DELETED_TEXT }], + verification: [{ commandOrCheck: DELETED_TEXT, detail: DELETED_TEXT }], artifacts: [{ kind: DELETED_TEXT, ref: DELETED_TEXT, title: DELETED_TEXT }] }); + const saved = run!.runnerProfileJson as typeof profile; + expect(saved.nativeExecutionInput).toEqual({ task }); + expect(run!.contextSnapshot).toEqual({ paperclipIssue: { description: task.description } }); + expect(saved.sessionCheckpoint).toMatchObject({ + driverKind: "codex_app_server", identity: { runId: seed.settledRun.id }, + semanticResult: { schema: "paperclip.run_result.v1", reportedWorkDisposition: "done", summary: DELETED_TEXT, completionClaim: { contractRevision: "rev-1" }, + evidence: [{ kind: DELETED_TEXT, ref: DELETED_TEXT }], verification: [{ status: "passed", detail: DELETED_TEXT }] }, + governedWait: { sourceEvent: { type: "tool.execution.completed", payload: { output: DELETED_TEXT } }, result: { schema: "paperclip.run_result.v1", summary: DELETED_TEXT } }, + terminalTurns: [{ turnId: "turn-1" }], + contentDeletedAt: expect.any(String), + }); + expect(validatePrpStructuredRunResult(saved.sessionCheckpoint.semanticResult)).toMatchObject({ ok: true }); + expect(saved.sessionCheckpoint.terminalTurns[0]!.fingerprint).toMatch(/^sha256:[a-f0-9]{64}$/); + expect(saved.nativeControllerRecovery.snapshotSha256).toBe(nativeSha256(saved.sessionCheckpoint)); + + const before = { resultJson: run!.resultJson, runnerProfileJson: run!.runnerProfileJson }; + const { answerCopiesDeletedAt: _cleanedAt, ...legacyResult } = run!.resultJson as Record; + const legacyAnswer = { ...(legacyResult.nativeResult as Record), evidence: [{ kind: "url", ref: link }] }; + const legacyCheckpoint = { ...checkpoint, terminalTurns: saved.sessionCheckpoint.terminalTurns, semanticResult: legacyAnswer, + governedWait: { ...checkpoint.governedWait, result: legacyAnswer } }; + await db.update(heartbeatRuns).set({ + resultJson: { ...legacyResult, nativeResult: legacyAnswer }, + runnerProfileJson: { ...profile, sessionCheckpoint: legacyCheckpoint, nativeControllerRecovery: { ...profile.nativeControllerRecovery, snapshotSha256: nativeSha256(legacyCheckpoint) } }, + }).where(eq(heartbeatRuns.id, seed.settledRun.id)); + await service.request(seed.connection, { actorType: "user", actorId: "board-user" }); + await drain(service); + const [again] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, seed.settledRun.id)); + expect(JSON.stringify(again!.resultJson)).not.toContain(SECRET); + expect(JSON.stringify(again!.runnerProfileJson)).not.toContain(SECRET); + expect(JSON.stringify(again!.resultJson)).not.toContain("board-notes"); + expect(JSON.stringify(again!.runnerProfileJson)).not.toContain("board-notes"); + const withoutMark = (value: unknown) => { + const copy = structuredClone(value) as { sessionCheckpoint: Record; nativeControllerRecovery: unknown }; + delete copy.sessionCheckpoint.contentDeletedAt; + delete (copy as Record).nativeControllerRecovery; + return copy; + }; + expect(withoutMark(again!.runnerProfileJson)).toEqual(withoutMark(before.runnerProfileJson)); + expect(again!.resultJson).toMatchObject({ answerCopiesDeletedAt: expect.any(String) }); + + const rewritten = { ...checkpoint }; + await db.update(heartbeatRuns).set({ runnerProfileJson: { ...profile, sessionCheckpoint: rewritten } }).where(eq(heartbeatRuns.id, seed.settledRun.id)); + await service.request(seed.connection, { actorType: "user", actorId: "board-user" }); + await drain(service); + const [afterRewrite] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, seed.settledRun.id)); + expect(JSON.stringify(afterRewrite!.runnerProfileJson)).not.toContain(SECRET); + expect(JSON.stringify(afterRewrite!.runnerProfileJson)).not.toContain("board-notes"); + + const written = checkpointProfileForRun((afterRewrite!.resultJson as Record).contentDeletedAt, { ...profile, sessionCheckpoint: rewritten }); + expect(JSON.stringify(written)).not.toContain(SECRET); + expect(checkpointProfileForRun(null, profile)).toBe(profile); + }); + describe("Google Technical Information", () => { const DAY = 24 * 60 * 60_000; diff --git a/server/src/services/native-runtime/paperclip-control-plane-port.test.ts b/server/src/services/native-runtime/paperclip-control-plane-port.test.ts index db22598f245..012111048c2 100644 --- a/server/src/services/native-runtime/paperclip-control-plane-port.test.ts +++ b/server/src/services/native-runtime/paperclip-control-plane-port.test.ts @@ -1,4 +1,5 @@ import { nativeResponsePresentationWork } from "./native-response-presentation-work.js"; +import { DELETED_TEXT } from "../tool-access/connections/content-cleaning.js"; import { resolveExternalTestDatabaseUrl } from "../../__tests__/helpers/external-test-database.js"; import { plugins } from "@paperclipai/db"; import { readTaskPanelActivations } from "../plugin-task-panels.js"; @@ -578,6 +579,23 @@ describe("PaperclipControlPlanePort conformance", () => { expect(JSON.stringify(result)).toContain('"status":"satisfied"'); }); + it.each([false, true])("cleans a checkpoint saved after the run's connection content was deleted (deleted: %s)", async deleted => { + const f = await terminalObserverFixture(); + const text = "Quarterly board notes from https://docs.google.com/document/d/board-notes"; + if (deleted) await db.update(heartbeatRuns).set({ resultJson: { contentDeletedAt: new Date().toISOString() } }) + .where(eq(heartbeatRuns.id, f.identity.runId)); + await f.port.checkpointSession({ ...f.snapshot, semanticResult: { ...CONTROL_PLANE_CONFORMANCE_RESULT, summary: text } }); + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.identity.runId)); + const checkpoint = run!.runnerProfileJson?.sessionCheckpoint as { semanticResult: { summary: string }; contentDeletedAt?: string }; + if (deleted) { + expect(JSON.stringify(run!.runnerProfileJson)).not.toContain("board-notes"); + expect(checkpoint).toMatchObject({ semanticResult: { summary: DELETED_TEXT }, contentDeletedAt: expect.any(String) }); + } else { + expect(checkpoint.semanticResult.summary).toBe(text); + expect(checkpoint.contentDeletedAt).toBeUndefined(); + } + }); + it.each(["default", "deferred"] as const)("keeps %s terminal observation owned before checkpoint and result acceptance", async mode => { let release!: () => void; const gate = new Promise(resolve => { release = resolve; }); diff --git a/server/src/services/native-runtime/paperclip-control-plane-port.ts b/server/src/services/native-runtime/paperclip-control-plane-port.ts index 495de4852ec..c1a50b3e799 100644 --- a/server/src/services/native-runtime/paperclip-control-plane-port.ts +++ b/server/src/services/native-runtime/paperclip-control-plane-port.ts @@ -1,4 +1,6 @@ import { notifyNativeResultCommit } from "../native-result-commit-notifications.js"; +import { checkpointProfileForRun } from "../tool-access/connections/content-cleaning.js"; +import { RUN_CONTENT_DELETED_MARKER } from "../tool-access/connections/run-session-reset.js"; import { applyNativeAcceptedOutcome, deriveNativeAcceptedOutcome, NATIVE_ACCEPTED_OUTCOME_KEY } from "./native-accepted-outcome.js"; import { readPersistedNativeFailureEvidence } from "./native-provider-failure-evidence.js"; import { notifyNativeWorkspaceFinalization } from "../native-workspace-finalization-notifications.js"; @@ -315,6 +317,7 @@ export class PaperclipControlPlanePort implements ControlPlanePort { contextSnapshot: (publication ? sql>`jsonb_build_object('conversationSessionGeneration', ${heartbeatRuns.contextSnapshot}->'conversationSessionGeneration')` : sql`null`).as("publication_context"), resultJson: (publication ? sql>`jsonb_build_object('nativeCancellation', ${heartbeatRuns.resultJson}->'nativeCancellation', 'cancellation', ${heartbeatRuns.resultJson}->'cancellation', 'startupCancellation', ${heartbeatRuns.resultJson}->'startupCancellation')` : sql`null`).as("publication_cancellation"), + contentDeletedAt: sql`${heartbeatRuns.resultJson}->>${RUN_CONTENT_DELETED_MARKER}`.as("content_deleted_at"), startedAt: heartbeatRuns.startedAt, createdAt: heartbeatRuns.createdAt, companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId, runtimeMode: heartbeatRuns.runtimeMode, nativeIssueId: heartbeatRuns.nativeIssueId, @@ -332,6 +335,7 @@ export class PaperclipControlPlanePort implements ControlPlanePort { // outer clock sample, including when either lock waits. const selected = await tx.with(...(ownerLock ? [ownerLock] : []), ...(publicationIssue ? [publicationIssue] : []), lockedRun).select({ run: { id: lockedRun.id, status: lockedRun.status, contextSnapshot: lockedRun.contextSnapshot, resultJson: lockedRun.resultJson, + contentDeletedAt: lockedRun.contentDeletedAt, startedAt: lockedRun.startedAt, createdAt: lockedRun.createdAt, companyId: lockedRun.companyId, agentId: lockedRun.agentId, runtimeMode: lockedRun.runtimeMode, nativeIssueId: lockedRun.nativeIssueId, @@ -391,7 +395,7 @@ export class PaperclipControlPlanePort implements ControlPlanePort { } } await tx.update(heartbeatRuns).set({ - runnerProfileJson: profile, + runnerProfileJson: checkpointProfileForRun(run.contentDeletedAt, profile), sessionIdAfter: snapshot.providerSessionId ?? snapshot.sessionId, nativePhase: snapshot.semanticResult ? "workspace_finalizing" : "observed", nativePhaseUpdatedAt: new Date(), diff --git a/server/src/services/tool-access/catalog/failures.ts b/server/src/services/tool-access/catalog/failures.ts index 73021fba47b..0bf296a46cf 100644 --- a/server/src/services/tool-access/catalog/failures.ts +++ b/server/src/services/tool-access/catalog/failures.ts @@ -107,7 +107,7 @@ export function sanitizeHttpFailure(error: unknown): { if (code === "oauth_reauthorization_required") { return { status: "error", - message: "OAuth authorization expired. Reconnect this app to continue.", + message: "Access to this app ended. Reconnect to continue.", code: "oauth_reauthorization_required", }; } diff --git a/server/src/services/tool-access/connections/content-cleaning.ts b/server/src/services/tool-access/connections/content-cleaning.ts index 2b271e6bcb3..ad663e3ccbf 100644 --- a/server/src/services/tool-access/connections/content-cleaning.ts +++ b/server/src/services/tool-access/connections/content-cleaning.ts @@ -1,3 +1,6 @@ +import { createHash } from "node:crypto"; +import { canonicalNativeJson, nativeSha256 } from "../../native-runtime/canonical.js"; + export const RESULT_TEXT_KEYS = ["summary", "result", "message", "text", "output", "content", "body"]; export function withoutActionResults(value: unknown, actionRequestIds: ReadonlySet): { value: unknown; changed: boolean } { @@ -25,6 +28,7 @@ export function withoutResultText(value: Record | null): { valu 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; + if ((node as Record).schema === "paperclip.run_result.v1") return node; const next: Record = {}; for (const [key, entry] of Object.entries(node as Record)) { if (RESULT_TEXT_KEYS.includes(key) && typeof entry === "string") { @@ -40,3 +44,117 @@ export function withoutResultText(value: Record | null): { valu const next = walk(value, true) as Record; return { value: changed ? next : value, changed }; } + +const STRUCTURAL_KEYS = new Set(["schema", "kind", "status", "type", "outcome", "state", "version", "code", "id", "reportedWorkDisposition"]); +const TERMINAL_SCHEMA = "paperclip.prp.terminal.v1"; +export const DELETED_TEXT = "Removed because the connection data was deleted."; +export const CHECKPOINT_CONTENT_DELETED_MARKER = "contentDeletedAt"; +const RUN_RESULT_SCHEMA = "paperclip.run_result.v1"; +const HASHED_FINGERPRINT = /^sha256:[a-f0-9]{64}$/; +const RUN_RESULT_KEPT_PATHS = new Set([ + "schema", + "reportedWorkDisposition", + "completionClaim.contractRevision", + "completionClaim.criteria.status", + "verification.status", + "verification.reasonCode", + "blocker.owner.kind", + "blocker.scope", + "attentionRequests.ownerClass", + "continuation.kind", +]); +const RUN_RESULT_HASHED_PATHS = new Set([ + "completionClaim.criteria.criterionId", + "attentionRequests.targetAgentId", + "continuation.idempotencyKey", + "continuation.handoffId", +]); + +function isRecord(value: unknown): value is Record { + return Boolean(value) && typeof value === "object" && !Array.isArray(value); +} + +function hashedText(value: string): string { + return HASHED_FINGERPRINT.test(value) ? value : `sha256:${createHash("sha256").update(value, "utf8").digest("hex")}`; +} + +function deletedText(value: string): string { + return value === "" ? value : DELETED_TEXT; +} + +function withoutRunResultText(value: unknown, path = ""): unknown { + if (typeof value === "string") { + if (RUN_RESULT_KEPT_PATHS.has(path)) return value; + if (RUN_RESULT_HASHED_PATHS.has(path)) return hashedText(value); + return deletedText(value); + } + if (Array.isArray(value)) return value.map((entry) => withoutRunResultText(entry, path)); + if (isRecord(value)) { + return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, withoutRunResultText(entry, path ? `${path}.${key}` : key)])); + } + return value; +} + +export function withoutAllText(value: unknown, key = ""): unknown { + if (typeof value === "string") return /At$/.test(key) ? value : deletedText(value); + if (Array.isArray(value)) return value.map((entry) => withoutAllText(entry, key)); + if (isRecord(value)) return Object.fromEntries(Object.entries(value).map(([entryKey, entry]) => [entryKey, withoutAllText(entry, entryKey)])); + return value; +} + +export function withoutFreeText(value: unknown, key = ""): unknown { + if (typeof value === "string") return STRUCTURAL_KEYS.has(key) || /(Id|At)$/.test(key) ? value : deletedText(value); + if (Array.isArray(value)) return value.map((entry) => withoutFreeText(entry, key)); + if (isRecord(value)) { + if (value.schema === RUN_RESULT_SCHEMA) return withoutRunResultText(value); + if (value.schema === TERMINAL_SCHEMA) return value; + return Object.fromEntries(Object.entries(value).map(([entryKey, entry]) => [entryKey, withoutFreeText(entry, entryKey)])); + } + return value; +} + +function hashedFingerprint(value: unknown): unknown { + return typeof value === "string" ? hashedText(value) : value; +} + +export function withoutRunAnswers(value: Record | null): { value: Record | null; changed: boolean } { + if (!isRecord(value)) return { value, changed: false }; + const walk = (node: unknown): unknown => { + if (Array.isArray(node)) return node.map(walk); + if (!isRecord(node)) return node; + if (node.schema === RUN_RESULT_SCHEMA) return withoutRunResultText(node); + return Object.fromEntries(Object.entries(node).map(([key, entry]) => [key, walk(entry)])); + }; + const next = walk(value) as Record; + const changed = canonicalNativeJson(next) !== canonicalNativeJson(value); + return { value: changed ? next : value, changed }; +} + +export function withoutCheckpointAnswers(profile: Record | null): { value: Record | null; changed: boolean } { + if (!isRecord(profile) || !isRecord(profile.sessionCheckpoint)) return { value: profile, changed: false }; + const checkpoint = profile.sessionCheckpoint; + const nextCheckpoint = { ...(withoutRunAnswers(checkpoint).value as Record) }; + if (isRecord(nextCheckpoint.semanticResult) && "fingerprint" in nextCheckpoint.semanticResult) { + nextCheckpoint.semanticResult = { ...nextCheckpoint.semanticResult, fingerprint: hashedFingerprint(nextCheckpoint.semanticResult.fingerprint) }; + } + if (Array.isArray(nextCheckpoint.terminalTurns)) { + nextCheckpoint.terminalTurns = nextCheckpoint.terminalTurns.map((turn) => isRecord(turn) ? { ...turn, fingerprint: hashedFingerprint(turn.fingerprint) } : turn); + } + if (isRecord(nextCheckpoint.governedWait) && isRecord(nextCheckpoint.governedWait.sourceEvent)) { + const sourceEvent = nextCheckpoint.governedWait.sourceEvent; + nextCheckpoint.governedWait = { ...nextCheckpoint.governedWait, sourceEvent: { ...sourceEvent, payload: withoutAllText(sourceEvent.payload) } }; + } + if (typeof nextCheckpoint[CHECKPOINT_CONTENT_DELETED_MARKER] !== "string") nextCheckpoint[CHECKPOINT_CONTENT_DELETED_MARKER] = new Date().toISOString(); + if (canonicalNativeJson(nextCheckpoint) === canonicalNativeJson(checkpoint)) return { value: profile, changed: false }; + const next: Record = { ...profile, sessionCheckpoint: nextCheckpoint }; + const recovery = profile.nativeControllerRecovery; + if (isRecord(recovery) && recovery.snapshotSha256 === nativeSha256(checkpoint)) { + next.nativeControllerRecovery = { ...recovery, snapshotSha256: nativeSha256(nextCheckpoint) }; + } + return { value: next, changed: true }; +} + +export function checkpointProfileForRun(contentDeletedAt: string | null | undefined, profile: Record): Record { + if (!contentDeletedAt) return profile; + return withoutCheckpointAnswers(profile).value ?? profile; +} diff --git a/server/src/services/tool-access/connections/content-deletion.ts b/server/src/services/tool-access/connections/content-deletion.ts index 4bed6f9c10a..e227c9b70f6 100644 --- a/server/src/services/tool-access/connections/content-deletion.ts +++ b/server/src/services/tool-access/connections/content-deletion.ts @@ -25,9 +25,9 @@ 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"; +import { CHECKPOINT_CONTENT_DELETED_MARKER, DELETED_TEXT, RESULT_TEXT_KEYS, withoutActionResults, withoutCheckpointAnswers, withoutResultText, withoutRunAnswers } from "./content-cleaning.js"; import { forgetRunCopies, forgetRunInTrainingExamples, runCopiesRemainSql } from "./run-copies.js"; -import { forgetRunSessions, RUN_CONTENT_DELETED_MARKER } from "./run-session-reset.js"; +import { forgetRunSessions, RUN_ANSWER_COPIES_DELETED_MARKER, RUN_CONTENT_DELETED_MARKER } from "./run-session-reset.js"; import { initialContentDeletionProgress, nextPhase, @@ -183,15 +183,20 @@ export function runUsedToolsSql(companyId: string): SQL { export function runsWithStoredContentSql(scope: Scope): SQL { const resultText = sql.join(RESULT_TEXT_KEYS.map((key) => - sql.raw(`jsonb_path_exists(coalesce("heartbeat_runs"."result_json", '{}'::jsonb), 'lax $.**.${key} ? (@.type() == "string" && @ != "")')`)), sql` or `); + sql.raw(`jsonb_path_exists(coalesce("heartbeat_runs"."result_json", '{}'::jsonb), 'lax $.**.${key} ? (@.type() == "string" && @ != "" && @ != "${DELETED_TEXT}")')`)), sql` or `); const inScope = scope.connectionId && scope.cutoff ? runsCallingConnectionSql({ ...scope, connectionId: scope.connectionId, cutoff: scope.cutoff }) : sql`${heartbeatRuns.id} = any(${uuidList(scope.runIds)}) and ${runUsedToolsSql(scope.companyId)}`; + const answerCopiesRemainSql = sql`((jsonb_path_exists(coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb), 'lax $.** ? (@.schema == "paperclip.run_result.v1")') + and not coalesce(${heartbeatRuns.resultJson} ? ${RUN_ANSWER_COPIES_DELETED_MARKER}, false)) + or (jsonb_typeof(${heartbeatRuns.runnerProfileJson} -> 'sessionCheckpoint') = 'object' + and not coalesce((${heartbeatRuns.runnerProfileJson} -> 'sessionCheckpoint') ? ${CHECKPOINT_CONTENT_DELETED_MARKER}, false)))`; return sql`${heartbeatRuns.companyId} = ${scope.companyId} and ${inScope} and (${savedResultSql(sql`${heartbeatRuns.id}`)} or ${heartbeatRuns.logRef} is not null or ${heartbeatRuns.logStore} is not null or ${heartbeatRuns.stdoutExcerpt} is not null or ${heartbeatRuns.stderrExcerpt} is not null or ${resultText} + or ${answerCopiesRemainSql} or ${runCopiesRemainSql({ id: sql`${heartbeatRuns.id}`, companyId: sql`${heartbeatRuns.companyId}`, issueId: sql`${heartbeatRuns.issueId}`, error: sql`${heartbeatRuns.error}` })} or exists (select 1 from ${heartbeatRunEvents} where ${heartbeatRunEvents.companyId} = ${heartbeatRuns.companyId} and ${heartbeatRunEvents.runId} = ${heartbeatRuns.id} and ${contentEventSql()}))`; @@ -629,20 +634,25 @@ export function createConnectionContentDeletion(db: Db, deps: { stdoutExcerpt: heartbeatRuns.stdoutExcerpt, stderrExcerpt: heartbeatRuns.stderrExcerpt, resultJson: heartbeatRuns.resultJson, + runnerProfileJson: heartbeatRuns.runnerProfileJson, }) .from(heartbeatRuns) .where(and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, companyId))) .for("update"); if (!row) return; - const result = withoutResultText(row.resultJson); - if (row.stdoutExcerpt !== null || row.stderrExcerpt !== null || row.error !== null || result.changed) run.changed = true; + const text = withoutResultText(row.resultJson); + const result = withoutRunAnswers(text.value); + const checkpoint = withoutCheckpointAnswers(row.runnerProfileJson); + if (row.stdoutExcerpt !== null || row.stderrExcerpt !== null || row.error !== null || text.changed || result.changed || checkpoint.changed) run.changed = true; await tx .update(heartbeatRuns) .set({ stdoutExcerpt: null, stderrExcerpt: null, error: null, - resultJson: { ...(result.value && typeof result.value === "object" ? result.value as Record : {}), [RUN_CONTENT_DELETED_MARKER]: new Date().toISOString() }, + resultJson: { ...(result.value && typeof result.value === "object" ? result.value as Record : {}), + [RUN_CONTENT_DELETED_MARKER]: new Date().toISOString(), [RUN_ANSWER_COPIES_DELETED_MARKER]: new Date().toISOString() }, + ...(checkpoint.changed ? { runnerProfileJson: checkpoint.value } : {}), }) .where(and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, companyId))); await forgetRunInTrainingExamples(tx, companyId, run); diff --git a/server/src/services/tool-access/connections/run-copies.ts b/server/src/services/tool-access/connections/run-copies.ts index f6cac5772fe..aff43737380 100644 --- a/server/src/services/tool-access/connections/run-copies.ts +++ b/server/src/services/tool-access/connections/run-copies.ts @@ -11,6 +11,7 @@ import { import { ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY } from "@paperclipai/shared"; import { settledRunSql } from "./content-deletion.js"; import { RUN_CONTENT_DELETED_MARKER } from "./run-session-reset.js"; +import { withoutFreeText } from "./content-cleaning.js"; export async function forgetRunInTrainingExamples(tx: Db, companyId: string, run: { id: string; changed: boolean }) { const runs = sql`${decisionTrainingExamples.snapshot}->'runs'`; @@ -34,17 +35,6 @@ export async function forgetRunInTrainingExamples(tx: Db, companyId: string, run if (replaced.length > 0) run.changed = true; } -const STRUCTURAL_KEYS = new Set(["schema", "kind", "status", "type", "outcome", "state", "version", "code", "id"]); - -function withoutFreeText(value: unknown, key = ""): unknown { - if (typeof value === "string") return STRUCTURAL_KEYS.has(key) || /(Id|At)$/.test(key) ? value : ""; - if (Array.isArray(value)) return value.map((entry) => withoutFreeText(entry, key)); - if (value && typeof value === "object") { - return Object.fromEntries(Object.entries(value as Record).map(([entryKey, entry]) => [entryKey, withoutFreeText(entry, entryKey)])); - } - return value; -} - export async function forgetRunCopies(tx: Db, companyId: string, run: { id: string; changed: boolean }, row: { issueId: string | null; createdAt: Date }) { const results = await tx .select({ id: nativeRunResults.id, resultJson: nativeRunResults.resultJson }) diff --git a/server/src/services/tool-access/connections/run-session-reset.ts b/server/src/services/tool-access/connections/run-session-reset.ts index eee6b04eb71..18bcf0c9052 100644 --- a/server/src/services/tool-access/connections/run-session-reset.ts +++ b/server/src/services/tool-access/connections/run-session-reset.ts @@ -58,6 +58,7 @@ export async function forgetRunSessions( } export const RUN_CONTENT_DELETED_MARKER = "contentDeletedAt"; +export const RUN_ANSWER_COPIES_DELETED_MARKER = "answerCopiesDeletedAt"; export async function forgetSessionsOfDeletedRun(db: Db, run: { id: string; companyId: string }) { const [row] = await db diff --git a/server/src/services/tool-access/oauth/client.ts b/server/src/services/tool-access/oauth/client.ts index 38e6bf191c5..0f80edcd9fc 100644 --- a/server/src/services/tool-access/oauth/client.ts +++ b/server/src/services/tool-access/oauth/client.ts @@ -412,7 +412,7 @@ export function createOAuthClientProtocol({ fetchRemoteHttpUrl, assertOAuthEndpo ) { throw new HttpError( 422, - "OAuth authorization has expired. Reconnect this app to continue.", + "Access to this app ended. Reconnect to continue.", { code: "oauth_reauthorization_required", providerError, diff --git a/server/src/services/tool-access/oauth/connection-refresh.ts b/server/src/services/tool-access/oauth/connection-refresh.ts index 4d6c5224516..aa23c2a9723 100644 --- a/server/src/services/tool-access/oauth/connection-refresh.ts +++ b/server/src/services/tool-access/oauth/connection-refresh.ts @@ -74,7 +74,7 @@ const oauthRefreshFlights = new Map>(); enabled: false, healthStatus: "error", healthMessage: - "OAuth authorization expired. Reconnect this app to continue.", + "Access to this app ended. Reconnect to continue.", lastError: "oauth_reauthorization_required", config: nextConfig, transportConfig: nextConfig, diff --git a/server/src/services/tool-access/oauth/grant-refresh.ts b/server/src/services/tool-access/oauth/grant-refresh.ts index 4af490ee22e..cd6b56fdd04 100644 --- a/server/src/services/tool-access/oauth/grant-refresh.ts +++ b/server/src/services/tool-access/oauth/grant-refresh.ts @@ -43,6 +43,29 @@ export function createOAuthGrantRefresh(db: Db, { now, store, leases, currentClo const oauthGrantRefreshFlights = new Map>(); const { getOAuthGrantRow, resolveOAuthGrantSecret, createOrRotateOAuthSecret, oauthClientForConnection, syncCredentialBindings } = store; const { acquireOAuthGrantRefreshLease, clearOAuthGrantRefreshLease } = leases; + async function markConnectionNeedsSignInWhenNoGrantIsActive(tx: Db, connection: typeof toolConnections.$inferSelect) { + return writeToolConnectionHealthChange(tx, connection, async inner => { + const connectionScope = and(eq(toolConnections.id, connection.id), eq(toolConnections.companyId, connection.companyId)); + await inner.select({ id: toolConnections.id }).from(toolConnections).where(connectionScope).for("update"); + const [active] = await inner.select({ id: connectionGrants.id }).from(connectionGrants).where(and( + eq(connectionGrants.companyId, connection.companyId), + eq(connectionGrants.connectionId, connection.id), + eq(connectionGrants.status, "active"), + )).limit(1); + if (active) return null; + const [updated] = await inner + .update(toolConnections) + .set({ + healthStatus: "error", + healthMessage: "Access to this app ended. Reconnect to continue.", + lastError: "oauth_reauthorization_required", + updatedAt: now(), + }) + .where(connectionScope) + .returning(); + return updated ?? null; + }); + } async function refreshOAuthGrantCredentials(input: { companyId: string; connectionId: string; @@ -160,7 +183,7 @@ export function createOAuthGrantRefresh(db: Db, { now, store, leases, currentClo const accessEndedAtGoogle = profile.provider === "google" && error.code === "REAUTHORIZATION_REQUIRED" && error.brokerReason === "PROVIDER_REAUTHORIZATION_REQUIRED"; - await db.transaction(async (tx) => { + const needsSignIn = await db.transaction(async (tx) => { const [marked] = await tx .update(connectionGrants) .set({ status: "needs_reauthorization", updatedAt: now() }) @@ -174,7 +197,9 @@ export function createOAuthGrantRefresh(db: Db, { now, store, leases, currentClo ) .returning({ id: connectionGrants.id }); if (marked && accessEndedAtGoogle) await deleteGoogleContentWhenAccessEnds(tx as unknown as Db, connection, "provider_access_ended"); + return marked ? markConnectionNeedsSignInWhenNoGrantIsActive(tx as unknown as Db, connection) : null; }); + if (needsSignIn) emitConnectionUpdated(needsSignIn, connection, "credential_refresh"); throw unprocessable( cloudOnly ? `Reconnect required. ${GOOGLE_SIGN_IN_CLOUD_ONLY_MESSAGE}` : "Managed authorization must be reconnected", { @@ -443,6 +468,8 @@ export function createOAuthGrantRefresh(db: Db, { now, store, leases, currentClo "credential_refresh", ); } else { + const needsSignIn = await markConnectionNeedsSignInWhenNoGrantIsActive(db, connection); + if (needsSignIn) emitConnectionUpdated(needsSignIn, connection, "credential_refresh"); const activeGrantRefs = await db .select({ refs: connectionGrants.credentialSecretRefs, diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index 5112232e6d2..06fe6295ea3 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -1897,6 +1897,10 @@ export function createToolGatewayService( inArray(toolConnections.healthStatus, ["ok", "healthy"]), eq(toolConnections.credentialPolicy, "per_user"), eq(toolConnections.transport, "plugin"), + sql`(exists (select 1 from ${connectionGrants} where ${connectionGrants.companyId} = ${companyId} + and ${connectionGrants.connectionId} = ${toolConnections.id} and ${connectionGrants.status} = 'needs_reauthorization') + and not exists (select 1 from ${connectionGrants} where ${connectionGrants.companyId} = ${companyId} + and ${connectionGrants.connectionId} = ${toolConnections.id} and ${connectionGrants.status} = 'active'))`, ), eq(toolApplications.companyId, companyId), inArray(toolApplications.type, ["mcp_http", "mcp_stdio", "rest_api", "paperclip_plugin"]), @@ -3777,6 +3781,12 @@ export function createToolGatewayService( .filter(tool => !guestBotConnection || !tool.connectionId || (tool.connectionId === guestBotConnection && tool.providerType === "paperclip_github_chat")); const connectionIds = [...new Set(connectedTools.flatMap((tool) => tool.connectionId ? [tool.connectionId] : []))]; if (connectionIds.length) { + const signInRequired = new Set((await db.select({ connectionId: connectionGrants.connectionId }).from(connectionGrants) + .where(and(eq(connectionGrants.companyId, session.companyId), inArray(connectionGrants.connectionId, connectionIds))) + .groupBy(connectionGrants.connectionId) + .having(sql`bool_or(${connectionGrants.status} = 'needs_reauthorization') and not bool_or(${connectionGrants.status} = 'active')`)) + .map((row) => row.connectionId)); + connectedTools = connectedTools.filter((tool) => !tool.connectionId || !signInRequired.has(tool.connectionId)); const connections = await db.select().from(toolConnections).where(and( eq(toolConnections.companyId, session.companyId), inArray(toolConnections.id, connectionIds), )); diff --git a/ui/src/pages/apps/Browse.tsx b/ui/src/pages/apps/Browse.tsx index 23e70677c61..6f9d04c3bc8 100644 --- a/ui/src/pages/apps/Browse.tsx +++ b/ui/src/pages/apps/Browse.tsx @@ -38,6 +38,7 @@ import { Trash2, } from "lucide-react"; import type { ComposioAppSnapshot, ToolApplication, ToolConnection } from "@paperclipai/shared"; +import { isConnectionAvailableToAgents } from "./connection-identity"; import { getAppDefinitionForUrl, getAppDefinitionForApplicationKey, @@ -1373,8 +1374,7 @@ export function ConnectorCard({ remainingConnectionCount: row.connections.filter( (candidate) => candidate.id !== connection.id && - candidate.status === "active" && - candidate.enabled, + isConnectionAvailableToAgents(candidate), ).length, }); }} diff --git a/ui/src/pages/apps/Connections.tsx b/ui/src/pages/apps/Connections.tsx index d53be347a4d..3d51def5e8f 100644 --- a/ui/src/pages/apps/Connections.tsx +++ b/ui/src/pages/apps/Connections.tsx @@ -47,7 +47,7 @@ import { type AppGalleryDisplayEntry, } from "./app-definition-display"; import { useReviewCount } from "./useReviewCount"; -import { connectionNameForCredentialPolicy, connectionTypeLabel } from "./connection-identity"; +import { connectionNameForCredentialPolicy, connectionTypeLabel, isConnectionAvailableToAgents } from "./connection-identity"; import { ConnectionOwnerIdentity, connectionDisplayNameForOwner, @@ -262,9 +262,7 @@ export function Connections() { const logoUrl = appDefinitionLogoUrl(resolvedGalleryEntry); const brandKey = appSourceSlug ?? application.name; const darkLogoUrl = appDefinitionDarkLogoUrl(resolvedGalleryEntry); - const agentAvailableConnectionCount = appConnections.filter( - (connection) => connection.status === "active" && connection.enabled, - ).length; + const agentAvailableConnectionCount = appConnections.filter(isConnectionAvailableToAgents).length; if (appConnections.length === 0) { return [{ application, @@ -298,7 +296,7 @@ export function Connections() { remainingAgentAvailableConnectionCount: Math.max( 0, agentAvailableConnectionCount - - (connection.status === "active" && connection.enabled ? 1 : 0), + (isConnectionAvailableToAgents(connection) ? 1 : 0), ), status: statusFor(application, [connection]), actionCount: actionCountByConnection.get(`app:${connection.id}`) ?? 0, diff --git a/ui/src/pages/apps/connection-identity.test.ts b/ui/src/pages/apps/connection-identity.test.ts index 715e760f32d..318a9d74710 100644 --- a/ui/src/pages/apps/connection-identity.test.ts +++ b/ui/src/pages/apps/connection-identity.test.ts @@ -3,6 +3,7 @@ import { connectionNameForCredentialPolicy, connectionNameForGrantKind, connectionTypeLabel, + isConnectionAvailableToAgents, } from "./connection-identity"; describe("connectionTypeLabel", () => { @@ -62,3 +63,18 @@ describe("connectionNameForCredentialPolicy", () => { .toBe("Notion for the organization"); }); }); + +describe("isConnectionAvailableToAgents", () => { + const base = { status: "active", enabled: true, healthStatus: "ok", credentialPolicy: "shared", transport: "mcp_remote", lastError: null } as const; + it("does not count a connection that must be signed in again", () => { + expect(isConnectionAvailableToAgents(base)).toBe(true); + expect(isConnectionAvailableToAgents({ ...base, healthStatus: "error" })).toBe(false); + expect(isConnectionAvailableToAgents({ ...base, credentialPolicy: "per_user", healthStatus: "error", lastError: "oauth_reauthorization_required" })).toBe(false); + expect(isConnectionAvailableToAgents({ ...base, enabled: false })).toBe(false); + expect(isConnectionAvailableToAgents({ ...base, status: "draft" })).toBe(false); + }); + + it("keeps counting a personal connection whose health check is stale", () => { + expect(isConnectionAvailableToAgents({ ...base, credentialPolicy: "per_user", healthStatus: "error" })).toBe(true); + }); +}); diff --git a/ui/src/pages/apps/connection-identity.ts b/ui/src/pages/apps/connection-identity.ts index 9636893a910..1957564ce91 100644 --- a/ui/src/pages/apps/connection-identity.ts +++ b/ui/src/pages/apps/connection-identity.ts @@ -1,9 +1,11 @@ -import type { - ConnectionGrantKind, - ConnectionAudienceMember, - ConnectionGrant, - ConnectionGrantStatus, - ToolConnectionCredentialPolicy, +import { + isToolConnectionAttentionHealth, + type ConnectionGrantKind, + type ConnectionAudienceMember, + type ConnectionGrant, + type ConnectionGrantStatus, + type ToolConnection, + type ToolConnectionCredentialPolicy, } from "@paperclipai/shared"; /** @@ -160,3 +162,17 @@ export function memberLabel( if (!match) return null; return match.name?.trim() || match.email?.trim() || null; } + +/** + * Counted as available to agents when it is on and agents are offered its tools. + * A personal connection keeps its tools while its health is stale, unless a new sign-in is required. + */ +export function isConnectionAvailableToAgents( + connection: Pick, +): boolean { + if (connection.status !== "active" || !connection.enabled) return false; + if (connection.lastError === "oauth_reauthorization_required") return false; + return !isToolConnectionAttentionHealth(connection.healthStatus) + || connection.credentialPolicy === "per_user" + || connection.transport === "plugin"; +}