From b929ad43de4d61f0a699d310ab2c10b39856fa4d Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 5 Nov 2026 14:55:34 -0600 Subject: [PATCH] fix: keep dependency waits neutral and explain GitHub access failures (#19315) ## Thinking Path > - Paperclip manages agent work and shows users what can move it forward. > - Task status and tool approval cards describe different parts of that work. > - A queued dependency wait has no provider attempt to retry. > - GitHub can reject an approved action while other connection tools still work. > - These cases showed a false Retry banner and an unhelpful provider error. > - This pull request keeps dependency waits neutral and gives GitHub access failures a direct repair path. ## Linked Issues or Issue Description Related: #19268 preserves pending Retry preparation and current failure causes. **What happened?** A queued wake cancelled by the dependency gate appeared as a failed attempt with Retry. A GitHub MCP permission denial appeared as raw HTTP error text after an approved repository action. **Expected behavior** Keep the task's dependency state. Show GitHub access failures with a clear explanation and a link to the selected connection's Permissions page. Preserve actual failures, provider details, and approval gates. **Steps to reproduce** 1. Queue a wake, then leave its task dependent on unfinished work before dispatch. 2. Open the task after the dependency gate cancels that wake. 3. Separately approve a GitHub action whose MCP result contains `403 Resource not accessible by integration`. 4. Reopen the saved tool approval. ## What Changed - Recognize both queues' unstarted dependency-wait receipts in cancellation provenance and task projections. No dispatch or recovery gate changes. - Classify GitHub's specific permission error after MCP result normalization. Keep result validation, the raw diagnostic, and working tools available. - Apply the same display code to both historical GitHub error codes. Identify the provider from company-scoped connection metadata, including renamed apps, without rewriting stored decisions. - Show a token-based inline access card with **Manage GitHub access** and collapsed **Error details**. - Give agents trusted recovery steps after an approved GitHub action fails. Keep provider text in the untrusted result and prevent automatic replay. - Add regressions, a production-component Storybook case, and execution/connector documentation. ## Verification - Red before the fix: cancellation provenance, dependency-wait projection, the real queue cancellation, approved MCP failure classification, saved interaction projection, and the error card assertions failed at the expected behavior. - Green focused tests: queue cancellation, one ready-task executor, approval-before-dispatch, one failed GitHub request, connection reuse, retained provider diagnostics, saved interaction reads, task list/detail projection and redaction. - UI: 106 component tests passed. Token gates and Storybook catalog checks passed. - `node scripts/typecheck-low-memory.mjs`: passed. - Local source instance: verified a saved dependency wait stays neutral after reload; a saved GitHub error shows repair guidance, expands its original error, and opens the correct connection Permissions page. PostgreSQL and HTTP APIs were real. The GitHub denial was a controlled MCP fixture; no account or provider permission changed. - `pnpm build`: passed for all workspace packages, the Runner binary, server, CLI and UI. The server build and all server typecheck layers also passed after the review repair. - Additional safety checks passed for realistic repository arguments, active recovery, failed Retry preparation, and bounded provider diagnostics. - Review repair: 45 pure tests and 7 PostgreSQL cases passed. These cover both historical error codes, renamed apps, and company/provider/application identity boundaries. A second local browser check verified the renamed app, retained error detail, and correct Permissions destination. - Final review regressions: the dispatcher and metadata cases failed before the repair. Afterward, 25 focused cases and 59 projection/identity cases passed, including connection-key precedence. The native wait and app-only GitHub source also passed a local browser check. - The historical read adds at most one connection query per interaction read batch. It selects IDs and the provider key only and runs only for candidate permission failures. It adds no provider requests. - Full local `pnpm test:run` stopped at the chat suite's `afterAll` cleanup timeout. All 268 assertions in that group and the three prior chat groups passed. The failure is retained here; it is not counted as a full-suite pass. CI passed on `e8a692e1e2` after one workspace-startup rerun. Fresh CI is pending for the combined head. Its first workspace-a attempt timed out in the CLI company import/export test's child-server startup wait; 4,968 UI tests and 287 CLI tests passed in that job. The same shard passed on the preceding commit. The workspace shard passed on its one rerun. All other test, build and browser jobs passed. The [first failure](https://github.com/paperclipai/paperclip/actions/runs/42093823928/job/127478869941) is retained in the Actions history. Greptile reviewed the preceding head at 5/5. Fresh review is pending for the combined head. ## Risks The GitHub classifier matches the documented permission-denial phrase, not every 403. Rate limits, missing resources and other providers retain their existing error behavior. Historical normalization affects display only. A dependency cancellation needs an unstarted run and a supported queue receipt; current user gates, Retry preparation and recovery remain authoritative. No schema migration or credential changes. ## Model Used OpenAI GPT-6, through the Codex agent. The exact runtime model ID and context-window size are not exposed in this session. Used reasoning, repository tools, TypeScript, PostgreSQL, MCP fixtures and browser verification. The parallel agent-recovery commit records Anthropic Claude Opus 5.5 as co-author. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used with version and capability details - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have described the issue in-PR using the bug template - [x] I have not referenced internal or instance-local Paperclip issues or links - [x] My branch name describes the change - [x] I have run the focused tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation - [x] I have considered and documented risks - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open findings - [x] I will address reviewer comments before requesting merge --------- Co-authored-by: Paperclip Co-authored-by: Claude Opus 5.5 --- doc/connections/GITHUB.md | 19 ++++++ doc/execution-semantics.md | 8 +++ .../heartbeat-dependency-scheduling.test.ts | 30 ++++++--- .../issue-thread-interactions-service.test.ts | 61 ++++++++++++++++- .../__tests__/tool-gateway-service.test.ts | 67 +++++++++++++++++++ server/src/__tests__/tool-gateway.test.ts | 61 +++++++++++++++++ .../run-dispatch/adapters/postgres.test.ts | 10 +++ .../src/services/issue-thread-interactions.ts | 10 ++- server/src/services/run-cancellation.test.ts | 14 ++++ server/src/services/run-cancellation.ts | 15 ++++- .../task-interruption-presentation.test.ts | 41 ++++++++++++ .../task-interruption-presentation.ts | 11 ++- .../tool-access/github-access-errors.test.ts | 57 ++++++++++++++++ .../tool-access/github-access-errors.ts | 38 +++++++++++ .../github-action-error-projection.ts | 42 ++++++++++++ .../tool-access/source-template-key.ts | 11 +++ server/src/services/tool-action-delivery.ts | 26 +++++-- server/src/services/tool-gateway.ts | 34 +++++----- .../IssueThreadInteractionCard.test.tsx | 22 ++++++ .../components/IssueThreadInteractionCard.tsx | 10 +++ .../connection-reviews.stories.tsx | 14 ++++ 21 files changed, 565 insertions(+), 36 deletions(-) create mode 100644 server/src/services/tool-access/github-access-errors.test.ts create mode 100644 server/src/services/tool-access/github-access-errors.ts create mode 100644 server/src/services/tool-access/github-action-error-projection.ts create mode 100644 server/src/services/tool-access/source-template-key.ts diff --git a/doc/connections/GITHUB.md b/doc/connections/GITHUB.md index 96826dfddfb..3ec3980c032 100644 --- a/doc/connections/GITHUB.md +++ b/doc/connections/GITHUB.md @@ -130,6 +130,25 @@ installation-health failure, not as token expiry. ## Repository access +GitHub can return `403 Resource not accessible by integration` inside an MCP tool +error even when the connection itself is healthy. A failed tool approval shows +**GitHub access needed** and **Manage GitHub access**, which opens that connection's +Permissions page. Check the connected account and the App's access to the intended +account and repository there. The original provider error remains in the action's +error details and diagnostic record. Paperclip does not replay the write or hide +other working tools. Saved GitHub approval errors receive the same presentation. +The agent's continuation wake carries server-written next steps and tells it +not to retry until access is repaired. It must never automatically replay a +stored approval. +Deferred historical errors receive the same guidance as their saved cards. +For an App connection's `create_repository`, the agent +asks the user to create the repository on GitHub, give the App access, and select +**Refresh access**, then continues with that repository. Token connections ask +the user to check token permissions and repository selection, then update or +replace that token. If the method is unavailable, the agent asks the user to +check the connection's authentication method. GitHub's text stays in the +untrusted result. + OAuth completion verifies `/user`, every page of `/user/installations`, and every page of each installation's accessible repositories. Setup remains incomplete until at least one installation and repository are available. Paperclip stores diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 84e5bc00b2c..d1ce86ca425 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -439,6 +439,14 @@ does not replay the cancelled turn or reset recovery limits. ### Known execution waits at admission +A queued wake cancelled by the dependency gate is an expected admission wait, +not a failed provider attempt. Task views use the queue's saved dependency +receipt to keep the existing dependency state without a failure banner or Retry +action. This includes the heartbeat queue receipt and the dispatcher's stale-queue +receipt for unstarted legacy or native runs. Actual provider failures, pending +recovery, and current approval or pause gates retain their existing presentation +and execution checks. + A known execution hold is a waiting condition, not a new execution attempt. Every issue wake must read the current effective reconciliation hold under the issue admission lock before creating a run. Resolved recovery bookkeeping can still carry a no-replay hold; only clearing the effective hold makes admission eligible again. The final dispatch gate remains required for changes after admission. Repeated legacy recovery scans retain one settled no-replay decision for the same diff --git a/server/src/__tests__/heartbeat-dependency-scheduling.test.ts b/server/src/__tests__/heartbeat-dependency-scheduling.test.ts index 652ef8e410c..8ef83219644 100644 --- a/server/src/__tests__/heartbeat-dependency-scheduling.test.ts +++ b/server/src/__tests__/heartbeat-dependency-scheduling.test.ts @@ -40,6 +40,7 @@ import { import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; import { heartbeatService } from "../services/heartbeat.ts"; import { runningProcesses } from "../adapters/index.ts"; +import { taskInterruptionPresentation } from "../services/task-interruption-presentation.js"; const mockAdapterExecute = vi.hoisted(() => vi.fn(async () => ({ @@ -1229,16 +1230,18 @@ describeEmbeddedPostgres("heartbeat dependency-aware queued run selection", () = }) .where(eq(issues.id, blockedIssueId)); + mockAdapterExecute.mockImplementationOnce(async () => { + await db.update(issues).set({ status: "done" }).where(eq(issues.id, readyIssueId)); + return { exitCode: 0, signal: null, timedOut: false, errorMessage: null, + summary: "Ready queued run completed.", provider: "test", model: "test-model" }; + }); await heartbeat.resumeQueuedRuns(); - await waitForCondition(async () => { - const run = await db - .select({ status: heartbeatRuns.status }) - .from(heartbeatRuns) - .where(eq(heartbeatRuns.id, readyRunId)) - .then((rows) => rows[0] ?? null); - return run?.status === "succeeded"; - }); + expect(await waitForCondition(async () => { + const [ready] = await db.select({ status: heartbeatRuns.status }).from(heartbeatRuns).where(eq(heartbeatRuns.id, readyRunId)); + return ready?.status === "succeeded"; + }, 30_000)).toBe(true); + await heartbeat.drainActiveRunExecutions(); const [blockedRun, blockedWakeup, blockedIssue, readyRun] = await Promise.all([ db @@ -1279,6 +1282,13 @@ describeEmbeddedPostgres("heartbeat dependency-aware queued run selection", () = expect(blockedRun?.errorCode).toBe("issue_dependencies_blocked"); expect(blockedRun?.finishedAt).toBeTruthy(); expect(blockedRun?.resultJson).toMatchObject({ stopReason: "issue_dependencies_blocked" }); + expect(blockedRun?.resultJson).toMatchObject({ cancellation: { source: "control_plane", expected: true } }); + const [waitingIssue] = await db.select().from(issues).where(eq(issues.id, blockedIssueId)); + expect(await taskInterruptionPresentation(db, waitingIssue!)).toMatchObject({ state: "resolved", canRetry: false }); + await db.update(heartbeatRuns).set({ resultJson: { ...blockedRun!.resultJson, timeoutFired: true } }) + .where(eq(heartbeatRuns.id, blockedRunId)); + expect(await taskInterruptionPresentation(db, waitingIssue!)).toMatchObject({ state: "failed", canRetry: true }); + await db.update(heartbeatRuns).set({ resultJson: blockedRun!.resultJson }).where(eq(heartbeatRuns.id, blockedRunId)); expect(blockedWakeup?.status).toBe("skipped"); expect(blockedWakeup?.error).toContain("dependencies are still blocked"); expect(blockedIssue).toMatchObject({ @@ -1287,8 +1297,8 @@ describeEmbeddedPostgres("heartbeat dependency-aware queued run selection", () = executionLockedAt: null, }); expect(readyRun?.status).toBe("succeeded"); - expect(mockAdapterExecute.mock.calls.length).toBeGreaterThanOrEqual(1); - }); + expect(mockAdapterExecute).toHaveBeenCalledTimes(1); + }, 40_000); it("suppresses normal wakeups while allowing comment interaction wakes under a pause hold", async () => { const companyId = randomUUID(); diff --git a/server/src/__tests__/issue-thread-interactions-service.test.ts b/server/src/__tests__/issue-thread-interactions-service.test.ts index 8ddda727299..dfb805226ea 100644 --- a/server/src/__tests__/issue-thread-interactions-service.test.ts +++ b/server/src/__tests__/issue-thread-interactions-service.test.ts @@ -27,10 +27,13 @@ import { projectWorkspaces, projects, workspaceOperations, + toolApplications, + toolConnections, } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase, + EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, } from "./helpers/embedded-postgres.js"; import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; import { @@ -60,7 +63,7 @@ describeEmbeddedPostgres("issueThreadInteractionService", () => { db = createDb(externalUrl ?? tempDb!.connectionString); issuesSvc = issueService(db); interactionsSvc = issueThreadInteractionService(db); - }, 20_000); + }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); afterEach(async () => { vi.unstubAllEnvs(); @@ -82,6 +85,8 @@ describeEmbeddedPostgres("issueThreadInteractionService", () => { await db.delete(instanceSettings); await db.delete(companyMemberships); await db.delete(instanceUserRoles); + await db.delete(toolConnections); + await db.delete(toolApplications); await db.delete(companies); await db.delete(authUsers); }); @@ -153,6 +158,60 @@ describeEmbeddedPostgres("issueThreadInteractionService", () => { return { companyId, goalId, issueId }; } + it.each([ + ["tool_error", "GitHub", "config"], ["tool_execution_failed", "GitHub", "config"], + ["tool_error", "GitHub (2)", "config"], ["tool_execution_failed", "Prototype code", "config"], + ["tool_error", "Transport GitHub", "transport"], + ["tool_error", "Imported GitHub", "application"], ["tool_execution_failed", "Legacy GitHub", "legacy_application"], + ])("projects a saved GitHub %s permission error for %s without rewriting its diagnostic record", async (errorCode, appName, source) => { + const { companyId, issueId } = await seedConfirmationIssue("GitHub access repair"); + const [application] = await db.insert(toolApplications).values({ companyId, applicationKey: `github-${randomUUID()}`, + name: appName, type: "mcp_http", metadata: source === "application" ? { sourceTemplateKey: "github" } + : source === "legacy_application" ? { source: "github" } : {} }).returning(); + const [connection] = await db.insert(toolConnections).values({ companyId, applicationId: application!.id, + name: appName, uid: `github-${randomUUID()}`, transport: "mcp_remote", + config: source === "config" ? { sourceTemplateKey: "github" } : {}, + transportConfig: source === "transport" ? { sourceTemplateKey: "github" } : {} }).returning(); + const errorMessage = "failed to create repository: POST https://api.github.com/user/repos: 403 Resource not accessible by integration []"; + const [row] = await db.insert(issueThreadInteractions).values({ companyId, issueId, + kind: "request_confirmation", status: "accepted", payload: { version: 1, prompt: "Create repository?", + toolAction: { version: 1, actionRequestId: randomUUID(), invocationId: randomUUID(), toolName: "github.create_repository", + toolDisplayName: "Create repository", appDisplayName: appName, connectionId: connection!.id, applicationId: application!.id, + risk: "write", previewMarkdown: "Create a private prototype repository", argumentsSummaryJson: "{}", + argumentsHash: "hash", expiresAt: new Date().toISOString() } }, + result: { version: 1, outcome: "accepted", toolAction: { version: 1, status: "failed", + errorCode, errorMessage, updatedAt: new Date().toISOString() } }, + }).returning(); + expect(await interactionsSvc.getById(row!.id)).toMatchObject({ result: { toolAction: { + errorCode: "github_access_denied", errorMessage, + } } }); + expect((await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, row!.id)))[0]?.result) + .toMatchObject({ toolAction: { errorCode, errorMessage } }); + }); + + it.each(["other_company", "other_provider", "other_application"])("does not infer GitHub identity from a card name with %s metadata", async variant => { + const { companyId, issueId } = await seedConfirmationIssue("Connection identity boundary"); + const connectionCompanyId = variant === "other_company" ? randomUUID() : companyId; + if (connectionCompanyId !== companyId) await db.insert(companies).values(interactionCompanyRow(connectionCompanyId)); + const [application] = await db.insert(toolApplications).values({ companyId: connectionCompanyId, + applicationKey: `provider-${randomUUID()}`, name: "GitHub", type: "mcp_http", + metadata: { sourceTemplateKey: "github" } }).returning(); + const [connection] = await db.insert(toolConnections).values({ companyId: connectionCompanyId, applicationId: application!.id, + name: "GitHub", uid: `provider-${randomUUID()}`, transport: "mcp_remote", + config: { sourceTemplateKey: variant === "other_provider" ? "notion" : "github" } }).returning(); + const [row] = await db.insert(issueThreadInteractions).values({ companyId, issueId, + kind: "request_confirmation", status: "accepted", payload: { version: 1, prompt: "Run action?", + toolAction: { version: 1, actionRequestId: randomUUID(), invocationId: randomUUID(), toolName: "provider.action", + toolDisplayName: "Run action", appDisplayName: "GitHub", connectionId: connection!.id, + applicationId: variant === "other_application" ? randomUUID() : application!.id, + risk: "write", previewMarkdown: "Run action", argumentsSummaryJson: "{}", argumentsHash: "hash", + expiresAt: new Date().toISOString() } }, + result: { version: 1, outcome: "accepted", toolAction: { version: 1, status: "failed", + errorCode: "tool_error", errorMessage: "403 Resource not accessible by integration", updatedAt: new Date().toISOString() } }, + }).returning(); + expect(await interactionsSvc.getById(row!.id)).toMatchObject({ result: { toolAction: { errorCode: "tool_error" } } }); + }); + async function attachPlanDocument(companyId: string, issueId: string) { const documentId = randomUUID(); const revisionId = randomUUID(); diff --git a/server/src/__tests__/tool-gateway-service.test.ts b/server/src/__tests__/tool-gateway-service.test.ts index d3355ec2395..78c3b8ea9ff 100644 --- a/server/src/__tests__/tool-gateway-service.test.ts +++ b/server/src/__tests__/tool-gateway-service.test.ts @@ -2043,6 +2043,73 @@ describeEmbeddedPostgres("tool gateway service", () => { expect(consumed.status).toBe("executed"); }); + it.each([ + { method: "managed", errorCode: "github_access_denied", sourceKey: "github" }, + { method: "mcp-key", errorCode: "github_access_denied", sourceKey: "github" }, + { method: "foreign", errorCode: "github_access_denied", sourceKey: "github" }, + { method: "managed", errorCode: "tool_error", sourceKey: "github" }, + { method: "mcp-key", errorCode: "tool_execution_failed", sourceKey: "github" }, + { method: "managed", errorCode: "tool_error", sourceKey: "notion" }, + { method: "foreign", errorCode: "tool_error", sourceKey: "github" }, + ])("tells the agent how to recover from $errorCode with $method access and $sourceKey identity", async ({ method, errorCode, sourceKey }) => { + const { company, agent, run } = await createRunFixture(db); + await db.insert(toolPolicies).values({ companyId: company.id, name: "Ask first", policyType: "require_approval", selectors: { toolName: "mcp-remote-fixture:update_note" } }); + const wakeup = vi.fn(async (agentId: string, input: any) => { + const [wake] = await db.insert(agentWakeupRequests).values({ companyId: company.id, agentId, source: input.source, idempotencyKey: input.idempotencyKey, payload: input.payload }).returning(); + return wake as any; + }); + const deliveries = toolActionDeliveryService(db, { wakeup }); + const gateway = createTestToolGatewayService(db, { onToolActionSettled: deliveries.deliver }); + const session = await gateway.createSession(runSessionInput(company, agent, run)); + await expect(gateway.executeTool({ sessionToken: session.token, tool: "mcp-remote-fixture:update_note", parameters: { noteId: "n1", body: "repo" } })).rejects.toMatchObject({ reasonCode: "approval_required" }); + const [request] = await db.select().from(toolActionRequests); + await gateway.approveActionRequest({ companyId: company.id, actionRequestId: request.id, actor: { userId: "reviewer" } }); + // Record the outcome staging saw: GitHub's integration 403 on the approved + // create_repository call, classified as github_access_denied. + const denied = "failed to create repository: POST https://api.github.com/user/repos: 403 Resource not accessible by integration []"; + const connectionCompany = method === "foreign" ? (await createRunFixture(db)).company : company; + const { connection } = await createRemoteMcpToolFixture(db, connectionCompany.id); + await db.update(toolConnections).set({ config: { ...connection.config, + sourceTemplateKey: sourceKey, connectionMethodKey: method === "foreign" ? "managed" : method } }).where(eq(toolConnections.id, connection.id)); + await db.update(toolActionRequests).set({ status: "failed" }).where(eq(toolActionRequests.id, request.id)); + await db.update(toolInvocations).set({ + connectionId: connection.id, applicationId: connection.applicationId, + status: "failed", toolName: "mcp.app-gallery-github-connection:create-repository", + errorCode, errorMessage: denied, + }).where(eq(toolInvocations.id, request.invocationId)); + const [interaction] = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, request.interactionId!)); + await db.update(issueThreadInteractions).set({ result: { ...(interaction.result as object), toolAction: { + ...((interaction.result as any)?.toolAction ?? {}), status: "failed", errorCode, errorMessage: denied, + } } as any }).where(eq(issueThreadInteractions.id, interaction.id)); + await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, run.id)); + await deliveries.deliverForRun({ companyId: company.id, runId: run.id }); + + expect(wakeup).toHaveBeenCalledTimes(1); + const payload = wakeup.mock.calls[0][1].payload; + const instructions: string = payload.toolAction.instructions; + // Retrying or re-approving hits the same GitHub refusal. + const trustedGitHubDenial = errorCode === "github_access_denied" || (sourceKey === "github" && method !== "foreign"); + expect(instructions).toMatch(trustedGitHubDenial ? /do not retry.*until GitHub access is repaired/i : /did not complete successfully/); + // Concrete next step the agent can relay to the user. + if (!trustedGitHubDenial) { + expect(instructions).not.toMatch(/GitHub App|Refresh access|replace.*token/); + } else if (method === "managed") { + expect(instructions).toContain("github.com/new"); + expect(instructions).toMatch(/Refresh access/); + } else if (method === "mcp-key") { + expect(instructions).toMatch(/token.*permissions/i); + expect(instructions).toMatch(/replace.*token/i); + expect(instructions).not.toMatch(/GitHub App|Refresh access/); + } else { + expect(instructions).toMatch(/authentication method/); + expect(instructions).not.toMatch(/GitHub App|Refresh access/); + } + expect(payload.paperclipAgentMessage.text).toContain(instructions); + // Provider text stays in the untrusted result, not in trusted instructions. + expect(instructions).not.toContain("Resource not accessible"); + expect(payload.paperclipAgentMessage.untrustedToolResults[0].error).toContain("Resource not accessible"); + }); + it("commits one human decision and delivers once after the original run yields, including after service restart", async () => { const { company, agent, issue, run } = await createRunFixture(db); await db.insert(toolPolicies).values({ companyId: company.id, name: "Ask first", policyType: "require_approval", selectors: { toolName: "mcp-remote-fixture:update_note" } }); diff --git a/server/src/__tests__/tool-gateway.test.ts b/server/src/__tests__/tool-gateway.test.ts index 64f09143526..83d3ef70b59 100644 --- a/server/src/__tests__/tool-gateway.test.ts +++ b/server/src/__tests__/tool-gateway.test.ts @@ -665,6 +665,67 @@ describeEmbeddedPostgres("tool gateway acceptance", () => { } }); + it.each(["config", "transport", "application", "legacy_application"])("records an actionable GitHub access error from %s metadata after one approved call and keeps the connection usable", async source => { + const company = await createCompany(db); + const agent = await createAgent(db, company.id); + const { run } = await createIssueAndRun(db, company.id, agent.id); + const denied = "failed to create repository: POST https://api.github.com/user/repos: 403 Resource not accessible by integration []"; + let fail = true; + const remote = await startFakeRemoteMcpServer(({ body }) => ({ body: { + jsonrpc: "2.0", id: body?.id, result: { + content: [{ type: "text", text: fail ? denied : "Repository read succeeded" }], isError: fail, + }, + } })); + try { + const { application, connection, catalogEntry } = await createRemoteMcpTool(db, company.id, { + url: remote.url, applicationKey: "github", toolName: "create_repository", riskLevel: "write", + connectionConfig: source === "config" ? { sourceTemplateKey: "github" } : {}, + }); + if (source === "transport") await db.update(toolConnections).set({ transportConfig: { sourceTemplateKey: "github" } }) + .where(eq(toolConnections.id, connection.id)); + if (source === "application" || source === "legacy_application") await db.update(toolApplications) + .set({ metadata: source === "application" ? { sourceTemplateKey: "github" } : { source: "github" } }) + .where(eq(toolApplications.id, application.id)); + await db.update(toolCatalogEntries).set({ inputSchema: { + type: "object", properties: { name: { type: "string" }, private: { type: "boolean" } }, + required: ["name"], additionalProperties: false, + } }).where(eq(toolCatalogEntries.id, catalogEntry.id)); + const toolName = expectedConnectedToolName({ applicationKey: application.applicationKey, + connectionId: connection.id, toolName: catalogEntry.toolName }); + await allowToolsForAgent(db, company.id, agent.id, [toolName]); + await db.insert(toolPolicies).values({ companyId: company.id, name: "Review GitHub writes", + policyType: "require_approval", selectors: { connectionId: connection.id }, priority: 10 }); + const gateway = createTestToolGatewayService(db); + const session = await gateway.createSession({ companyId: company.id, agentId: agent.id, runId: run.id }); + const parameters = { name: "example-prototype", private: true }; + await expect(gateway.executeTool({ sessionToken: session.token, tool: toolName, parameters })) + .rejects.toMatchObject({ reasonCode: "approval_required" }); + expect(remote.requests).toHaveLength(0); + const [action] = await db.select().from(toolActionRequests).where(eq(toolActionRequests.companyId, company.id)); + await db.update(issueThreadInteractions).set({ status: "accepted", resolvedAt: new Date() }) + .where(eq(issueThreadInteractions.id, action!.interactionId!)); + await db.update(toolActionRequests).set({ status: "approved", resolvedAt: new Date() }) + .where(eq(toolActionRequests.id, action!.id)); + await expect(gateway.executeTool({ sessionToken: session.token, tool: toolName, parameters, + approvedActionRequestId: action!.id })).rejects.toMatchObject({ reasonCode: "github_access_denied" }); + expect(remote.requests).toHaveLength(1); + expect(remote.requests[0]?.body).toMatchObject({ method: "tools/call", + params: { name: "create_repository", arguments: parameters } }); + const [invocation] = await db.select().from(toolInvocations).where(eq(toolInvocations.id, action!.invocationId)); + expect(invocation).toMatchObject({ status: "failed", errorCode: "github_access_denied", + errorMessage: denied }); + const [card] = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, action!.interactionId!)); + expect(card!.result).toMatchObject({ toolAction: { status: "failed", errorCode: "github_access_denied" } }); + expect((await db.select().from(toolConnections).where(eq(toolConnections.id, connection.id)))[0]?.healthStatus).toBe("ok"); + fail = false; + await db.delete(toolPolicies).where(eq(toolPolicies.companyId, company.id)); + const result = await gateway.executeTool({ sessionToken: session.token, tool: toolName, + parameters: { name: "permitted-prototype", private: true } }); + expect(result.status).toBe("completed"); + expect(remote.requests).toHaveLength(2); + } finally { await remote.close(); } + }); + it("returns a JSON-RPC reconciliation error instead of repeating an unverifiable legacy write", async () => { const company = await createCompany(db); const remote = await startFakeRemoteMcpServer(({ body }) => ({ diff --git a/server/src/modules/run-dispatch/adapters/postgres.test.ts b/server/src/modules/run-dispatch/adapters/postgres.test.ts index d2a043b4737..6310be9020f 100644 --- a/server/src/modules/run-dispatch/adapters/postgres.test.ts +++ b/server/src/modules/run-dispatch/adapters/postgres.test.ts @@ -36,6 +36,7 @@ import { import { createPostgresRunDispatchAdapter } from "./postgres.js"; import { settleUnrecoverableExecutions } from "../../../services/execution-recovery-resolution.js"; import { getExecutionBlocker } from "../../../services/execution-blocker.js"; +import { projectTaskInterruption } from "../../../services/task-interruption-presentation.js"; import { reserveRunBudget } from "../../../services/budget-reservations.js"; import { budgetService, flushBudgetEvaluationWork, recheckAdmittedRunBudgetReadOnly } from "../../../services/budgets.js"; import { costService } from "../../../services/costs.js"; @@ -388,6 +389,7 @@ describeEmbeddedPostgres("run-dispatch postgres adapter", () => { const adapter = createPostgresRunDispatchAdapter(db); expect(await adapter.evaluateScheduledRetryGate({ companyId, runId: replacementId, retryReasonOverride: "native_safe_replacement", now: new Date() })) .toMatchObject({ allowed: true }); + await db.update(heartbeatRuns).set({ runtimeMode: "native" }).where(eq(heartbeatRuns.id, replacementId)); await db.insert(issueRelations).values({ companyId, issueId: blockerId, relatedIssueId: issueId, type: "blocks" }); const dispatch = vi.fn(async () => undefined); if (mode === "queued") { @@ -405,6 +407,14 @@ describeEmbeddedPostgres("run-dispatch postgres adapter", () => { }); } expect(dispatch).toHaveBeenCalledTimes(mode === "resolved" ? 1 : 0); + if (mode !== "resolved") { + const [cancelled] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, replacementId)); + expect(cancelled).toMatchObject({ status: "cancelled", runtimeMode: "native", startedAt: null, + resultJson: { stopReason: "issue_dependencies_blocked", timeoutSource: "stale_queued_run_gate" } }); + expect(projectTaskInterruption({ id: issueId, companyId, status: "in_progress", assigneeAgentId: agentId, projectId: null }, { + run: cancelled!, agent: { status: "idle", pauseReason: null }, paused: false, approval: false, + })).toMatchObject({ state: "resolved", canRetry: false }); + } expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]!.status).toBe("in_progress"); }); diff --git a/server/src/services/issue-thread-interactions.ts b/server/src/services/issue-thread-interactions.ts index 9363a9c2ea7..1d7710dc369 100644 --- a/server/src/services/issue-thread-interactions.ts +++ b/server/src/services/issue-thread-interactions.ts @@ -5,6 +5,7 @@ import { notifyIssueReviewState } from "./issue-review-state-notifications.js"; import { notifyChatConfirmationResolution } from "./chat-confirmation-notifications.js"; import { notifyChatRunMilestones } from "./chat-run-milestone-notifications.js"; import { notifyToolReviewChange } from "./tool-review-work-notifications.js"; +import { projectGitHubInteractionErrors } from "./tool-access/github-action-error-projection.js"; import { normalizeEscapedLineBreaks } from "@paperclipai/shared/validators/text"; import { notifyDeliveryWork, DELIVERY_QUEUES } from "./delivery-work-notifications.js"; import { historicalQuestionCondition } from "./issue-question-context.js"; @@ -759,17 +760,19 @@ function hydrateInteraction( row, ), } satisfies AskUserQuestionsInteraction; - case "request_confirmation": + case "request_confirmation": { + const payload = requestConfirmationPayloadSchema.parse(row.payload); return { ...base, kind: "request_confirmation", - payload: requestConfirmationPayloadSchema.parse(row.payload), + payload, result: parseStoredInteractionResult( requestConfirmationResultSchema, row.result, row, ), } satisfies RequestConfirmationInteraction; + } case "request_checkbox_confirmation": return { ...base, @@ -2141,6 +2144,7 @@ export function issueThreadInteractionService( interactions: IssueThreadInteraction[], issueWorkspace?: { companyId: string; executionWorkspaceId: string | null }, ): Promise { + interactions = await projectGitHubInteractionErrors(db, interactions); const guarded = interactions.filter((interaction) => interaction.status === "pending" && interaction.sourceRunId @@ -2165,7 +2169,7 @@ export function issueThreadInteractionService( if (!workspace?.executionWorkspaceId) return interactions; // Only pending confirmations need checks, once per source run even if that - // run produced several cards. Historical interactions add no queries. + // run produced several cards. Historical interactions need no workspace queries. const { companyId, executionWorkspaceId } = workspace; const sourceRunIds = [...new Set(guarded.map((interaction) => interaction.sourceRunId!))]; const pendingRunIds = new Set(); diff --git a/server/src/services/run-cancellation.test.ts b/server/src/services/run-cancellation.test.ts index 3e7dbf5727f..a352d2c9691 100644 --- a/server/src/services/run-cancellation.test.ts +++ b/server/src/services/run-cancellation.test.ts @@ -20,6 +20,20 @@ describe("cancellation provenance", () => { expect(requestedRunCancellation({ queuedCommentInterruptQueueId: "queue", interruptedByActorType: "user", interruptedByActorId: "board" }, "Send messages")) .toMatchObject({ source: "queued_message", initiator: { type: "user", id: "board" } }); }); + it.each([ + { runtimeMode: "legacy", source: "dependency_gate" }, + { runtimeMode: "legacy", source: "stale_queued_run_gate" }, + { runtimeMode: "native", source: "stale_queued_run_gate" }, + ] as const)("records an unstarted $runtimeMode $source dependency cancellation without authorizing a continuation", ({ runtimeMode, source }) => { + const queued = { ...run, runtimeMode, startedAt: null }; + const resultJson = cancellationResultJson(queued, "cancelled", { + stopReason: "issue_dependencies_blocked", timeoutSource: source, + }, "issue_dependencies_blocked"); + expect(resultJson?.cancellation).toMatchObject({ source: "control_plane", expected: true }); + expect(canContinueCancelledRun({ ...queued, resultJson })).toBe(false); + expect(cancellationResultJson(run, "cancelled", {}, "issue_dependencies_blocked")?.cancellation) + .toMatchObject({ expected: false }); + }); it("attributes a host lease loss instead of reporting an unknown stop", () => { const resultJson = cancellationResultJson(run, "cancelled", { cancellation: controllerLeaseLossCancellation("renewal_deadline") }); diff --git a/server/src/services/run-cancellation.ts b/server/src/services/run-cancellation.ts index 89932ecd4df..ab2687e8066 100644 --- a/server/src/services/run-cancellation.ts +++ b/server/src/services/run-cancellation.ts @@ -85,6 +85,17 @@ export function readControllerLeaseLoss(value: unknown): LegacyControllerLeaseLo return loss; } +/** A queue admission wait has no provider attempt to retry. Historical rows can + * carry unknown cancellation provenance, so use the queue's original receipt. */ +export function isQueuedDependencyWait(run: Pick & Partial>): boolean { + const source = run.resultJson?.timeoutSource; + const queueReceipt = (source === "dependency_gate" && run.runtimeMode === "legacy") || + (source === "stale_queued_run_gate" && (run.runtimeMode === "legacy" || run.runtimeMode === "native")); + return run.status === "cancelled" && queueReceipt && run.startedAt === null && + run.errorCode === "issue_dependencies_blocked" && run.resultJson?.stopReason === run.errorCode && + run.resultJson?.timeoutFired !== true; +} + /** Preserve recorded stop intent when adapter completion replaces resultJson. */ export function cancellationResultJson(run: Run, status: string, patch?: Run["resultJson"], errorCode?: string | null, error?: string | null): Run["resultJson"] { if (status !== "cancelled" && status !== "interrupted") return patch ?? run.resultJson; @@ -93,7 +104,9 @@ export function cancellationResultJson(run: Run, status: string, patch?: Run["re let cancellation = previous?.expected ? previous : readRunCancellation(patch) ?? previous; const code = errorCode ?? run.errorCode; if (!cancellation) { - if (code === "server_shutdown_interrupted") { + if (isQueuedDependencyWait({ ...run, status, errorCode: code, resultJson: result })) { + cancellation = requestedRunCancellation(result, "Waiting for task dependencies to resolve"); + } else if (code === "server_shutdown_interrupted") { cancellation = { source: "shutdown", expected: true, initiator: { type: "system" }, reason: "Server shutdown interrupted execution", recordedAt: new Date().toISOString() }; } else if (result.cancelledByActorType || result.cancelledByUserId || result.interruptedByActorType || result.queuedCommentInterruptQueueId) { diff --git a/server/src/services/task-interruption-presentation.test.ts b/server/src/services/task-interruption-presentation.test.ts index ff2de4ab0c1..9be38f14077 100644 --- a/server/src/services/task-interruption-presentation.test.ts +++ b/server/src/services/task-interruption-presentation.test.ts @@ -7,6 +7,47 @@ const run = { id: "run", agentId: "agent", status: "failed", scheduledRetryAt: n resultJson: { projectAccessDenied: { projectId: "22222222-2222-4222-8222-222222222222" } } }; const agent = { status: "idle", pauseReason: null }; +describe("queued dependency wait presentation", () => { + const waitingRun = { ...run, status: "cancelled", runtimeMode: "legacy" as const, startedAt: null, + errorCode: "issue_dependencies_blocked", resultJson: { + stopReason: "issue_dependencies_blocked", timeoutSource: "dependency_gate", + cancellation: { source: "unknown", expected: false }, + } }; + + it("keeps a dependency-gated wake out of the failed-attempt UI, including retained input", () => { + for (const wait of [undefined, { id: "saved-input", requestedAt: new Date(0) }]) { + expect(projectTaskInterruption(issue, { run: waitingRun, agent, wait, paused: false, approval: false })) + .toMatchObject({ state: "resolved", canRetry: false }); + } + }); + + it.each(["legacy", "native"])("keeps an unstarted %s dispatcher dependency wait neutral", runtimeMode => { + const dispatchedWait = { ...waitingRun, runtimeMode, + resultJson: { ...waitingRun.resultJson, timeoutSource: "stale_queued_run_gate" } }; + expect(projectTaskInterruption(issue, { run: dispatchedWait, agent, paused: false, approval: false })) + .toMatchObject({ state: "resolved", canRetry: false }); + expect(projectTaskInterruption(issue, { run: { ...dispatchedWait, startedAt: new Date() }, agent, paused: false, approval: false })) + .toMatchObject({ state: "failed", canRetry: true }); + }); + + it("keeps genuine failures and current user gates visible", () => { + for (const changed of [{ status: "failed" }, { runtimeMode: "native" }, { startedAt: new Date() }, + { errorCode: "setup_failed" }, { resultJson: {} }, { resultJson: { ...waitingRun.resultJson, timeoutFired: true } }]) { + expect(projectTaskInterruption(issue, { run: { ...waitingRun, ...changed }, agent, paused: false, approval: false })) + .toMatchObject({ state: "failed", canRetry: true }); + } + expect(projectTaskInterruption(issue, { run: waitingRun, agent, paused: true, approval: false })) + .toMatchObject({ state: "waiting_for_user", userAction: "resume" }); + expect(projectTaskInterruption(issue, { run: waitingRun, agent, paused: false, approval: true })) + .toMatchObject({ state: "waiting_for_user", userAction: "approval" }); + expect(projectTaskInterruption(issue, { run: waitingRun, agent, paused: false, approval: false, + action: { evidence: {}, status: "active" } as never })).toMatchObject({ state: "failed", canRetry: true }); + expect(projectTaskInterruption(issue, { run: waitingRun, agent, paused: false, approval: false, + retryWait: { id: "retry", sourceRunId: waitingRun.id, requestedAt: new Date(), preparationStatus: "failed" } })) + .toMatchObject({ state: "failed", canRetry: true }); + }); +}); + describe("unadmitted chat Retry presentation", () => { const now = Date.parse("2026-01-01T12:00:00Z"); const failed = { ...run, errorCode: "native_provider_terminal_failed", resultJson: null }; diff --git a/server/src/services/task-interruption-presentation.ts b/server/src/services/task-interruption-presentation.ts index 6379b274ce9..761102fa847 100644 --- a/server/src/services/task-interruption-presentation.ts +++ b/server/src/services/task-interruption-presentation.ts @@ -16,11 +16,12 @@ import { redactCurrentUserText } from "../log-redaction.js"; import { logger } from "../middleware/logger.js"; import { canonicalExecutionUuid } from "./execution-identity.js"; import { chatActionDeadline } from "./chat-action-work.js"; +import { isQueuedDependencyWait } from "./run-cancellation.js"; type ProjectionIssue = Pick; type ProjectionRun = Pick & - Partial>; + Partial>; type ProjectionWait = { id: string; requestedAt: Date; sourceRunId?: string | null; executionWaitReason?: string | null; preparationStatus?: string | null; preparationRetryAt?: number | string | null }; type ProjectionState = { @@ -92,6 +93,9 @@ export function projectTaskInterruption(issue: ProjectionIssue, input: Projectio : [agent?.pauseReason, project?.pauseReason, company?.pauseReason].some(reason => reason === "budget" || reason === "budget_exceeded") ? "budget" : input.paused || project?.pausedAt || agent?.status === "paused" || company?.status === "paused" ? "resume" : null; if (userAction) return { ...base, responsibility: "user", state: "waiting_for_user", userAction }; + // The task's existing dependency UI owns this wait. Keep actual recovery and + // Retry preparation failures authoritative; this does not change admission. + if (!action && !retryWait?.preparationStatus && isQueuedDependencyWait(run)) return base; // Intentional Stop is not an unsuccessful attempt. This is presentation only; // physical containment and pending cleanup keep their execution-side gates. if (!wait && run.runtimeMode === "native" && run.companyId === issue.companyId && run.nativeIssueId === issue.id @@ -174,13 +178,16 @@ export async function taskInterruptionPresentations(db: Db, companyId: string, i const [runs, waits, agentRows, projectRows, pauseRows, approvalRows, companyRows] = await Promise.all([ db.select({ issueId: requestedIssueId, id: heartbeatRuns.id, status: heartbeatRuns.status, agentId: heartbeatRuns.agentId, companyId: heartbeatRuns.companyId, - nativeIssueId: heartbeatRuns.nativeIssueId, runtimeMode: heartbeatRuns.runtimeMode, + nativeIssueId: heartbeatRuns.nativeIssueId, runtimeMode: heartbeatRuns.runtimeMode, startedAt: heartbeatRuns.startedAt, agentAdapter: agents.adapterType, error: sql`case when ${heartbeatRuns.errorCode} = 'setup_failed' and ${heartbeatRuns.error} = 'Project is outside this low-trust boundary.' or ${heartbeatRuns.errorCode} = 'workspace_validation_failed' then ${heartbeatRuns.error} else null end`, errorCode: heartbeatRuns.errorCode, livenessState: heartbeatRuns.livenessState, scheduledRetryAt: heartbeatRuns.scheduledRetryAt, resultJson: sql>`jsonb_build_object('configurationIncomplete', ${heartbeatRuns.resultJson}->'configurationIncomplete', + 'stopReason', ${boundedJsonString(sql`${heartbeatRuns.resultJson}->'stopReason'`, 80)}, + 'timeoutSource', ${boundedJsonString(sql`${heartbeatRuns.resultJson}->'timeoutSource'`, 80)}, + 'timeoutFired', coalesce(${heartbeatRuns.resultJson}->'timeoutFired' = 'true'::jsonb, false), 'projectAccessDenied', ${heartbeatRuns.resultJson}->'projectAccessDenied', 'cancelledByActorType', ${boundedJsonString(sql`${heartbeatRuns.resultJson}->'cancelledByActorType'`, 32)}, 'cancelledByUserId', ${boundedJsonString(sql`${heartbeatRuns.resultJson}->'cancelledByUserId'`, 160)}, diff --git a/server/src/services/tool-access/github-access-errors.test.ts b/server/src/services/tool-access/github-access-errors.test.ts new file mode 100644 index 00000000000..36c4edfac6e --- /dev/null +++ b/server/src/services/tool-access/github-access-errors.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from "vitest"; +import { githubAccessDeniedInstructions, githubAccessError, projectGitHubActionResult } from "./github-access-errors.js"; + +describe("GitHub tool access failures", () => { + it.each(["integration", "personal access token"])("classifies GitHub's %s permission denial", kind => { + expect(githubAccessError("github", `GET https://api.github.com/repos/example/private: 403 Resource not accessible by ${kind} []`)) + .toEqual({ errorCode: "github_access_denied" }); + }); + + it("does not confuse rate limits, missing resources or another provider with a GitHub access denial", () => { + for (const message of ["403 API rate limit exceeded", "404 Not Found", "Repository created successfully", "Bad credentials", + "403 ".repeat(10_000), "x".repeat(4000) + "403 Resource not accessible by integration"]) + expect(githubAccessError("github", message)).toBeNull(); + expect(githubAccessError("notion", "403 Resource not accessible by integration")).toBeNull(); + }); + + it("keeps unrelated saved decisions and provider errors unchanged", () => { + const result = { version: 1 as const, outcome: "accepted" as const, toolAction: { + version: 1 as const, status: "failed" as const, errorCode: "tool_error", + errorMessage: "403 Resource not accessible by integration", updatedAt: new Date().toISOString(), + } }; + expect(projectGitHubActionResult("notion", result)).toBe(result); + expect(projectGitHubActionResult(undefined, result)).toBe(result); + expect(projectGitHubActionResult("github", null)).toBeNull(); + }); + + it.each(["tool_error", "tool_execution_failed"])("projects historical %s errors using verified provider identity", errorCode => { + const result = { version: 1 as const, outcome: "accepted" as const, toolAction: { + version: 1 as const, status: "failed" as const, errorCode, + errorMessage: "403 Resource not accessible by integration", updatedAt: new Date().toISOString(), + } }; + expect(projectGitHubActionResult("github", result)).toMatchObject({ toolAction: { errorCode: "github_access_denied" } }); + }); + + it("gives repository-create recovery steps for both GitHub tool name spellings", () => { + for (const toolName of ["mcp.github:create-repository", "mcp.github:create_repository"]) { + const text = githubAccessDeniedInstructions(toolName, "managed"); + expect(text).toMatch(/Do not retry/); + expect(text).toMatch(/until GitHub access is repaired/); + expect(text).toContain("https://github.com/new"); + expect(text).toContain("Refresh access"); + } + const other = githubAccessDeniedInstructions("mcp.github:create_issue", "managed"); + expect(other).toMatch(/Do not retry/); + expect(other).not.toContain("github.com/new"); + }); + + it("gives token and unknown connections their own repair steps", () => { + const token = githubAccessDeniedInstructions("mcp.github:create_repository", "mcp-key"); + expect(token).toMatch(/token.*permissions/i); + expect(token).toMatch(/replace.*token/i); + expect(token).not.toMatch(/GitHub App|Refresh access|github\.com\/new/); + const unknown = githubAccessDeniedInstructions("mcp.github:create_repository"); + expect(unknown).toMatch(/authentication method/); + expect(unknown).not.toMatch(/GitHub App|Refresh access/); + }); +}); diff --git a/server/src/services/tool-access/github-access-errors.ts b/server/src/services/tool-access/github-access-errors.ts new file mode 100644 index 00000000000..391db245060 --- /dev/null +++ b/server/src/services/tool-access/github-access-errors.ts @@ -0,0 +1,38 @@ +import type { RequestConfirmationResult } from "@paperclipai/shared"; + +/** GitHub reports repository permission failures inside successful MCP HTTP + * responses. Do not infer that every 403 is an access problem (rate limits also + * use 403), or echo provider response text into the repair instructions. */ +export function githubAccessError(sourceTemplateKey: unknown, message: unknown) { + if (sourceTemplateKey !== "github" || typeof message !== "string" || + !/\b403\s+Resource not accessible by (?:integration|personal access token)\b/i.test(message.slice(0, 4000))) return null; + return { errorCode: "github_access_denied" as const }; +} + +/** Upgrade already saved tool errors using verified connection identity. Retain + * the stored error and decision, including both legacy invocation error codes. */ +export function projectGitHubActionResult(sourceTemplateKey: unknown, result: RequestConfirmationResult | null | undefined): RequestConfirmationResult | null | undefined { + const action = result?.toolAction; + if (!action || action.status !== "failed" || + (action.errorCode !== "tool_error" && action.errorCode !== "tool_execution_failed")) return result; + const failure = githubAccessError(sourceTemplateKey, action.errorMessage); + return failure ? { ...result, toolAction: { ...action, ...failure } } : result; +} + +/** Trusted, server-authored next steps for the agent after GitHub denied an + * approved action. Access must be repaired before another attempt. The + * provider text stays in the untrusted result, never in these instructions. */ +export function githubAccessDeniedInstructions(toolName: string, connectionMethodKey: unknown = null): string { + const operation = (toolName.split(":").pop() ?? "").trim().toLowerCase().replace(/-/g, "_"); + const base = "GitHub denied this approved action because the Paperclip GitHub connection cannot access the requested account or repository. Do not retry or request approval for the same call until GitHub access is repaired. Never automatically replay the stored approval."; + if (connectionMethodKey === "mcp-key") { + return `${base} Ask the user to check the personal access token's resource owner, repository selection and required permissions in GitHub. They must update or replace the token on the GitHub connection's Permissions page. Continue after they confirm the access change.`; + } + if (connectionMethodKey !== "managed") { + return `${base} Ask the user to open the GitHub connection's Permissions page and check its connected account, authentication method and requested repository access. Continue after they repair that connection.`; + } + if (operation === "create_repository") { + return `${base} Tell the user that Paperclip cannot create this repository with the current GitHub access. Ask them to create the repository at https://github.com/new, give the Paperclip GitHub App access to it, and select Refresh access on the GitHub connection's Permissions page. Then continue with that existing repository.`; + } + return `${base} Tell the user which account or repository you need. Ask them to give the Paperclip GitHub App access from the GitHub connection's Permissions page and select Refresh access. Continue after they confirm.`; +} diff --git a/server/src/services/tool-access/github-action-error-projection.ts b/server/src/services/tool-access/github-action-error-projection.ts new file mode 100644 index 00000000000..83c75f52c1d --- /dev/null +++ b/server/src/services/tool-access/github-action-error-projection.ts @@ -0,0 +1,42 @@ +import { and, eq, inArray } from "drizzle-orm"; +import { toolApplications, toolConnections, type Db } from "@paperclipai/db"; +import type { IssueThreadInteraction, RequestConfirmationInteraction } from "@paperclipai/shared"; +import { projectGitHubActionResult } from "./github-access-errors.js"; +import { toolSourceTemplateKeySql } from "./source-template-key.js"; + +/** Read-only enrichment of historical errors. Resolve provider identity in one + * company-scoped batch without reading credentials or relying on mutable names. */ +export async function projectGitHubInteractionErrors( + db: Pick, + interactions: IssueThreadInteraction[], +): Promise { + const candidates = interactions.filter((interaction): interaction is RequestConfirmationInteraction => + interaction.kind === "request_confirmation" + && Boolean(interaction.payload.toolAction?.connectionId) + && projectGitHubActionResult("github", interaction.result) !== interaction.result, + ); + if (candidates.length === 0) return interactions; + + const connections = await db.select({ + id: toolConnections.id, + companyId: toolConnections.companyId, + applicationId: toolConnections.applicationId, + sourceTemplateKey: toolSourceTemplateKeySql, + }).from(toolConnections).innerJoin(toolApplications, and( + eq(toolApplications.id, toolConnections.applicationId), + eq(toolApplications.companyId, toolConnections.companyId), + )).where(and( + inArray(toolConnections.id, [...new Set(candidates.map(item => item.payload.toolAction!.connectionId!))]), + inArray(toolConnections.companyId, [...new Set(candidates.map(item => item.companyId))]), + )); + const byCompanyAndId = new Map(connections.map(connection => [`${connection.companyId}:${connection.id}`, connection])); + const projected = new Map(candidates.flatMap(interaction => { + const action = interaction.payload.toolAction!; + const connection = byCompanyAndId.get(`${interaction.companyId}:${action.connectionId}`); + if (!connection || (action.applicationId && action.applicationId !== connection.applicationId)) return []; + return [[interaction.id, { + ...interaction, result: projectGitHubActionResult(connection.sourceTemplateKey, interaction.result), + }] as const]; + })); + return interactions.map(interaction => projected.get(interaction.id) ?? interaction); +} diff --git a/server/src/services/tool-access/source-template-key.ts b/server/src/services/tool-access/source-template-key.ts new file mode 100644 index 00000000000..44ffe60b81d --- /dev/null +++ b/server/src/services/tool-access/source-template-key.ts @@ -0,0 +1,11 @@ +import { sql } from "drizzle-orm"; +import { toolApplications, toolConnections } from "@paperclipai/db"; + +/** Match connection setup's provider identity precedence. Select only this + * value with a company-scoped connection/application join, never credentials. */ +export const toolSourceTemplateKeySql = sql`coalesce( + ${toolConnections.config}->>'sourceTemplateKey', + ${toolConnections.transportConfig}->>'sourceTemplateKey', + ${toolApplications.metadata}->>'sourceTemplateKey', + ${toolApplications.metadata}->>'source' +)`; diff --git a/server/src/services/tool-action-delivery.ts b/server/src/services/tool-action-delivery.ts index 0718ed2d449..92db1431888 100644 --- a/server/src/services/tool-action-delivery.ts +++ b/server/src/services/tool-action-delivery.ts @@ -19,9 +19,14 @@ import { toolActionRequests, toolInvocations, toolActionDeliveries, + toolConnections, + toolApplications, type Db, } from "@paperclipai/db"; import type { heartbeatService } from "./heartbeat.js"; +import type { RequestConfirmationResult } from "@paperclipai/shared"; +import { githubAccessDeniedInstructions, projectGitHubActionResult } from "./tool-access/github-access-errors.js"; +import { toolSourceTemplateKeySql } from "./tool-access/source-template-key.js"; const terminalStatuses: Array = [ "executed", @@ -122,6 +127,8 @@ export function toolActionDeliveryService( request: toolActionRequests, invocation: toolInvocations, interaction: issueThreadInteractions, + connectionMethodKey: sql`case when ${toolApplications.id} is null then null else coalesce(${toolConnections.config}->>'connectionMethodKey', ${toolConnections.transportConfig}->>'connectionMethodKey') end`, + sourceTemplateKey: sql`case when ${toolApplications.id} is null then null else ${toolSourceTemplateKeySql} end`, }) .from(toolActionDeliveries) .innerJoin( @@ -151,6 +158,15 @@ export function toolActionDeliveryService( eq(issueThreadInteractions.issueId, issue.id), ), ) + .leftJoin(toolConnections, and( + eq(toolConnections.id, toolInvocations.connectionId), + eq(toolConnections.companyId, source.companyId), + or(isNull(toolInvocations.applicationId), eq(toolConnections.applicationId, toolInvocations.applicationId)), + )) + .leftJoin(toolApplications, and( + eq(toolApplications.id, toolConnections.applicationId), + eq(toolApplications.companyId, source.companyId), + )) .where( and( eq(toolActionDeliveries.companyId, source.companyId), @@ -216,10 +232,10 @@ export function toolActionDeliveryService( // result reference for omitted or shortened results; never replay calls. const inlineOutcomes = outcomes.slice(0, 8); const toolActions = inlineOutcomes.map( - ({ request, invocation, interaction }) => { - const result = interaction.result as { + ({ request, invocation, interaction, connectionMethodKey, sourceTemplateKey }) => { + const result = projectGitHubActionResult(sourceTemplateKey, interaction.result as RequestConfirmationResult | null) as { reason?: string; - toolAction?: { resultSummary?: string; errorMessage?: string }; + toolAction?: { resultSummary?: string; errorMessage?: string; errorCode?: string | null }; } | null; const instructions = request.status === "executed" @@ -229,7 +245,9 @@ export function toolActionDeliveryService( : request.status === "expired" || request.status === "cancelled" ? "The review is no longer available. Do not execute the stored request. Explain the recorded outcome before requesting another review." - : "The approved action did not complete successfully. Do not automatically replay it; inspect the recorded outcome first."; + : (result?.toolAction?.errorCode ?? invocation.errorCode) === "github_access_denied" + ? githubAccessDeniedInstructions(invocation.toolName, connectionMethodKey) + : "The approved action did not complete successfully. Do not automatically replay it; inspect the recorded outcome first."; return { toolName: invocation.toolName.slice(0, 256), actionRequestId: request.id, diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index 5c19fe5302d..0171c9a498b 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -21,6 +21,8 @@ import { nativeProviderCatalogFor } from "./native-provider-catalogs.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"; +import { githubAccessError } from "./tool-access/github-access-errors.js"; +import { toolSourceTemplateKeySql } from "./tool-access/source-template-key.js"; import { boundedMcpToolName } from "./mcp-tool-names.js"; import { browserUseService } from "./browser-use.js"; import { isBrowserUseConnection } from "./browser-use-client.js"; @@ -5016,9 +5018,13 @@ export function createToolGatewayService( "tool_not_found", ); } - const [connection] = await db - .select() + const [connected] = await db + .select({ connection: toolConnections, sourceTemplateKey: toolSourceTemplateKeySql }) .from(toolConnections) + .innerJoin(toolApplications, and( + eq(toolApplications.id, toolConnections.applicationId), + eq(toolApplications.companyId, toolConnections.companyId), + )) .where( and( eq(toolConnections.id, entry.connectionId), @@ -5026,6 +5032,7 @@ export function createToolGatewayService( ), ) .limit(1); + const connection = connected?.connection; if (!connection || (connection.transport !== "mcp_remote" && !isBrowserUseConnection(connection) && !nativeProviderCatalogFor(connection) && !restConnectorFor(connection))) { throw new ToolGatewayHttpError( 404, @@ -5057,7 +5064,7 @@ export function createToolGatewayService( if (restConnector && !restConnector.isCurrent(entry)) { throw new ToolGatewayHttpError(409, `${restConnector.name}'s action catalog changed. Review the updated actions in Permissions.`, "provider_catalog_changed"); } - return { entry, connection }; + return { entry, connection, sourceTemplateKey: connected?.sourceTemplateKey ?? null }; } async function governedToolArguments( @@ -6170,7 +6177,7 @@ export function createToolGatewayService( spawnedLocalProcess, }, ...(record.isError === true - ? { error: "MCP tool returned an error result" } + ? { error: "MCP tool returned an error result", ...githubAccessError(sourceTemplateKey, providerContent) } : {}), }; } @@ -6184,7 +6191,7 @@ export function createToolGatewayService( callerHeaders?: ExecuteGatewayToolInput["callerHeaders"], useDefaultTimeout = false, ): Promise { - const { entry, connection } = await resolveConnectedRemoteTool( + const { entry, connection, sourceTemplateKey } = await resolveConnectedRemoteTool( session, tool, ); @@ -6591,10 +6598,6 @@ export function createToolGatewayService( request: resultElicitation, }); } - const sourceTemplateKey = - typeof connection.config.sourceTemplateKey === "string" - ? connection.config.sourceTemplateKey - : null; const result = normalizeMcpToolResult( payloadRecord.result, "mcp_http", @@ -7662,8 +7665,9 @@ export function createToolGatewayService( }); const providerResult = asRecord(resultValidation.value); if (providerResult?.error) { - throw new ToolGatewayHttpError(502, String(providerResult.content || providerResult.error), - "tool_error", { execution: connectedMcpExecution.execution }); + throw new ToolGatewayHttpError(providerResult.errorCode === "github_access_denied" ? 403 : 502, + String(providerResult.content || providerResult.error), + providerResult.errorCode === "github_access_denied" ? "github_access_denied" : "tool_error", { execution: connectedMcpExecution.execution }); } } catch (err) { const status = err instanceof ToolGatewayHttpError ? err.status : 502; @@ -8470,9 +8474,9 @@ export function createToolGatewayService( const resultRecord = asRecord(result); if (resultRecord?.error) throw new ToolGatewayHttpError( - 502, + resultRecord.errorCode === "github_access_denied" ? 403 : 502, String(resultRecord.content || resultRecord.error), - "tool_execution_failed", + resultRecord.errorCode === "github_access_denied" ? "github_access_denied" : "tool_execution_failed", ); const resultValidation = await validateToolContent({ value: result, @@ -11203,9 +11207,9 @@ export function createToolGatewayService( : null; if (validatedMcpResult?.error) { throw new ToolGatewayHttpError( - 502, + validatedMcpResult.errorCode === "github_access_denied" ? 403 : 502, String(validatedMcpResult.content || validatedMcpResult.error), - "tool_error", + validatedMcpResult.errorCode === "github_access_denied" ? "github_access_denied" : "tool_error", { execution: connectedMcpExecution?.execution }, ); } diff --git a/ui/src/components/IssueThreadInteractionCard.test.tsx b/ui/src/components/IssueThreadInteractionCard.test.tsx index 56bc6ad5e8f..0aabb550032 100644 --- a/ui/src/components/IssueThreadInteractionCard.test.tsx +++ b/ui/src/components/IssueThreadInteractionCard.test.tsx @@ -1422,6 +1422,28 @@ describe("IssueThreadInteractionCard tool-action card", () => { expect(declined.textContent).not.toContain("Approve & run"); }); + it("makes a GitHub access failure actionable without offering a futile retry", () => { + const interaction = { ...failedToolActionInteraction, + payload: { ...failedToolActionInteraction.payload, toolAction: { + ...failedToolActionInteraction.payload.toolAction!, appDisplayName: "GitHub", + } }, + result: { ...failedToolActionInteraction.result!, toolAction: { + ...failedToolActionInteraction.result!.toolAction!, errorCode: "github_access_denied", + errorMessage: "failed to create repository: POST https://api.github.com/user/repos: 403 Resource not accessible by integration []", + } }, + }; + const host = renderCard({ interaction }); + expect(host.querySelector('[role="alert"]')?.textContent).toContain("GitHub access needed"); + expect(host.textContent).toContain(interaction.result.toolAction.errorMessage); + expect(host.textContent).toContain("Check the connected account"); + expect(host.textContent).toContain("ask the agent to continue"); + expect(host.querySelector("details")?.hasAttribute("open")).toBe(false); + const manage = Array.from(host.querySelectorAll("a")).find(link => link.textContent === "Manage GitHub access"); + expect(manage?.getAttribute("href")).toBe(`/apps/${interaction.payload.toolAction.connectionId}/permissions`); + expect(host.textContent).not.toContain("Retry"); + expect(host.textContent).not.toContain("Approve & run"); + }); + it("renders the expired state without decision controls", () => { const host = renderCard({ interaction: expiredToolActionInteraction }); diff --git a/ui/src/components/IssueThreadInteractionCard.tsx b/ui/src/components/IssueThreadInteractionCard.tsx index 700689afec4..68c6f3c2389 100644 --- a/ui/src/components/IssueThreadInteractionCard.tsx +++ b/ui/src/components/IssueThreadInteractionCard.tsx @@ -2,6 +2,7 @@ import { createContext, useContext, useEffect, useMemo, useRef, useState, type R import type { Agent } from "@paperclipai/shared"; import { AlertTriangle, ArrowUpRight, Bot, Check, CheckCircle2, ChevronDown, ChevronRight, CircleDashed, Clock, ExternalLink, FileText, GitBranch, ImagePlus, KeyRound, Loader2, MessageSquareQuote, MinusCircle, ShieldAlert, ThumbsUp, TriangleAlert, Wrench, X, XCircle } from "lucide-react"; import { Link } from "@/lib/router"; +import { appTabHref } from "@/pages/apps/app-tabs"; import { formatAssigneeUserLabel } from "../lib/assignees"; import { describeInteractionAudience, type InteractionAudienceDescription } from "../lib/interaction-audience"; import { interactionResolutionErrorMessage } from "../lib/interaction-resolution-error"; @@ -1751,6 +1752,15 @@ function ToolActionResolution({ const detail = state === "failed" ? result?.errorMessage?.trim() || "The action could not complete." : state === "declined" ? interaction.result?.reason?.trim() : null; + if (state === "failed" && result?.errorCode === "github_access_denied") { + const connectionId = interaction.payload.toolAction?.connectionId; + return
+

+

This GitHub connection cannot access the requested account or repository. Check the connected account and Paperclip’s repository access, then ask the agent to continue.

+ {connectionId ? : null} + {detail ?
Error details

{detail}

: null} +
; + } const status = <> {labels[state]} diff --git a/ui/storybook/stories/questions-and-approvals/connection-reviews.stories.tsx b/ui/storybook/stories/questions-and-approvals/connection-reviews.stories.tsx index b8b4950de8c..d3deaabfa93 100644 --- a/ui/storybook/stories/questions-and-approvals/connection-reviews.stories.tsx +++ b/ui/storybook/stories/questions-and-approvals/connection-reviews.stories.tsx @@ -324,6 +324,20 @@ export const ResultDetails: Story = { export const ExecutionFailed: Story = { render: () => , }; +export const GitHubAccessNeeded: Story = { + render: () => , +}; export const Declined: Story = { render: () => , };