From 2f6fa3b6dc3c016050b224e5f56741dc6de189ed Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 30 Sep 2026 06:39:37 -0500 Subject: [PATCH] fix: recover provider authentication inside tasks (#14629) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agents need a working model provider connection to run a task. > - A provider can reject a stored credential after the task starts. > - The failed run must ask the responsible user to repair that connection. > - This pull request adds that request directly to the task and reuses Connections sign-in. > - The user can choose an API key or subscription, then continue the task with a fresh session. ## Linked Issues or Issue Description **What happened?** A run that ended with `acpx_auth_required` or another known provider authentication error did not immediately offer an inline way to connect the provider. A repair form could also lock the user to the failed account's sign-in method. **Expected behavior** Show a provider connection card in the task as soon as the authentication failure is saved. Allow the responsible user to connect or repair the provider with any supported sign-in method. Keep the connection name automatic and resume the task after successful setup. **Steps to reproduce** 1. Run a task with a supported provider and an expired or invalid credential. 2. Let the run fail with a provider authentication error. 3. Open the task and attempt to repair the connection. Related work: Refs #13724 and #13726. This change adds the inline task repair flow and method choice. ## What Changed - Classify provider authentication failures and create one connection request for the current task. A persisted blocked classification suppresses automatic retries only after the repair card is created; unsupported providers retain their existing recovery path. - Mark only the attributed, unchanged credential as needing sign-in. Preserve credentials that were refreshed after the failed run started. - Reuse the provider sign-in controls inside the task. Allow API key and subscription choices for Claude, Codex, and Grok. Keep names hidden and generate a default from the user, provider, and method. - Keep the existing account when reconnecting with the same method. Create and select another account when the method changes. Validate updates to explicit agent bindings through the normal agent save path. - Require explicit adoption for legacy agent authentication. Validate in the agent environment, then commit the binding, connection install, audit, and card completion in one transaction. Keep failed setup and account selection visible and retryable. - Add regression tests and update the specification and Connections documentation. ## Verification - Fresh local verification: 199 tests passed across the inline form, provider method selector, default naming, authentication and recovery classifiers, run liveness, OpenAPI routes, database adoption/rollback, and Cursor execution suites. The adoption database suite also passed against disposable Docker PostgreSQL. - Full repository `pnpm build` and `pnpm -r typecheck` passed on the latest commit. Token gates are clean. - Embedded browser: opened real task cards from seeded authentication failures; switched Claude from API key to subscription and back; switched Codex from subscription to API key; confirmed the name field stays hidden. Provider sign-in was not completed with real credentials. - The broad local `pnpm test:run` started before review fixes and was interrupted after the working tree changed; it is not counted as a passing full run. Fresh focused tests passed. CI supplies the full test and browser suite results for the current commit. - CI is green on commit `4b97a4e447045ff3d7516525a187a5d1d21e0d4c`: 54 checks passed and two Storybook checks were skipped by their path rules. The workspace preview job passed on one rerun after a local-server startup timeout; its rerun passed 835 tests. - Greptile is 5/5 on the same commit with no actionable findings and no unresolved review threads. ## Risks - Incorrect authentication classification could prompt for a connection unnecessarily. Tests exclude tool authorization, quota, and unrelated runtime failures. - A method change selects the new personal provider default, which also applies to other agents that use that user's default. Explicit account bindings use the existing permission and runtime validation path. - Credential invalidation must not race with refresh or reconnect. The code compares the saved credential generation and grant update time under locks. - No database migration or new credential storage format is required. ## Model Used OpenAI GPT-6 through Codex. The exact model ID and context window size were not exposed in this session. Capabilities used: reasoning, repository editing, shell commands, database tests, and embedded-browser interaction. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass (focused tests listed above) - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- doc/SPEC-implementation.md | 6 + doc/SPEC.md | 5 + doc/connections/AI-CONNECTIONS.md | 33 ++++- .../shared/src/types/connection-intent.ts | 2 + server/src/__tests__/ai-connections.test.ts | 120 ++++++++++++++++-- server/src/routes/agents.ts | 30 +++++ server/src/routes/openapi.ts | 18 +++ server/src/services/ai-auth-failure.test.ts | 26 ++++ server/src/services/ai-auth-failure.ts | 25 ++++ server/src/services/ai-connections.ts | 50 +++++++- server/src/services/connection-intents.ts | 107 ++++++++++++++-- server/src/services/heartbeat.ts | 21 ++- .../provider-failure-classification.test.ts | 16 +++ server/src/services/recovery/service.ts | 3 +- server/src/services/run-liveness.ts | 7 + ui/src/api/agents.ts | 4 + .../components/IssueThreadInteractionCard.tsx | 1 + .../AiConnectionCredentialStep.tsx | 14 +- .../components/ai-connections/model.test.ts | 10 ++ ui/src/components/ai-connections/model.ts | 9 ++ .../AgentProviderConnection.test.tsx | 74 ++++++++++- .../new-agent/AgentProviderConnection.tsx | 30 ++++- .../TaskChatCompactInteractionCard.tsx | 1 + .../ConnectionIntentInteractionBody.test.tsx | 93 +++++++++++++- .../ConnectionIntentInteractionBody.tsx | 101 +++++++++++++-- 25 files changed, 748 insertions(+), 58 deletions(-) create mode 100644 server/src/services/ai-auth-failure.test.ts create mode 100644 server/src/services/ai-auth-failure.ts diff --git a/doc/SPEC-implementation.md b/doc/SPEC-implementation.md index 7e0f656ab2f..6d73543da1e 100644 --- a/doc/SPEC-implementation.md +++ b/doc/SPEC-implementation.md @@ -1672,6 +1672,12 @@ harness/model routing and fails closed without ambient credential fallback. Legacy agents retain their authentication until validated adoption. See [AI Connections](connections/AI-CONNECTIONS.md) for company isolation, compatible methods, lifecycle, runtime enforcement, and migration details. + +Provider login failures create a provider-specific Connections card on the task +when the run fails, before generic recovery retries. Reconnect preserves account +identity and permissions. Compatible legacy agents may explicitly adopt a +validated connection inline; late failures must not invalidate newer credentials. + ### Experimental task-bound email AgentMail channel connections extend the experimental conversation/task pipeline diff --git a/doc/SPEC.md b/doc/SPEC.md index e1c6020b881..93c08b93461 100644 --- a/doc/SPEC.md +++ b/doc/SPEC.md @@ -34,6 +34,11 @@ human approval, decline, or scoped remembered permission. Connections and task views resolve the same review, and the agent continues with the server-recorded outcome. See [the implementation contract](SPEC-implementation.md#124-connection-tool-reviews). +Model authentication failures also surface a provider-specific Connections card +on the task immediately after failure. Users can reconnect inline and resume; +legacy agents keep their authentication until an explicit, validated adoption. +See [AI Connections](connections/AI-CONNECTIONS.md). + #### Board Powers (Always Available) The Board has **unrestricted access** to the entire system at all times: diff --git a/doc/connections/AI-CONNECTIONS.md b/doc/connections/AI-CONNECTIONS.md index 6c55738c5e8..e74390255fa 100644 --- a/doc/connections/AI-CONNECTIONS.md +++ b/doc/connections/AI-CONNECTIONS.md @@ -99,6 +99,34 @@ Sending `environmentId: null` tests a change back to the instance default. ## Runtime isolation +Provider authentication failures, including `acpx_auth_required`, adapter login +requirements, and expired/invalidated refresh tokens, create an AI connection +card as the failed run is finalized. The card names the provider and uses the +same inline connection/reconnect controls as missing-account setup. Pending +cards are deduplicated. Creating a repair card persists a blocked run classification +that suppresses immediate and periodic generic retries until the responsible user +repairs the connection. Unsupported providers and failures that could not create +a card retain their existing recovery path. Tool permission errors and provider quota failures do not +request model authentication. + +An attributed managed credential is marked as needing reauthorization only if +its stored generation still matches the failed run. Late failures cannot +invalidate a refreshed or reconnected credential. Repair preserves the selected +account and its permissions when the same sign-in method is selected. The card +also lets the user switch between API key and subscription authentication for +providers that support both. Switching creates a separate account, then selects +it as the user's provider default or validates and updates the agent's explicit +account binding. The original account is retained. Accepting the card resumes with a fresh session +through the existing durable continuation delivery. + +For compatible legacy agents, the card offers the responsible person's provider +connection without changing authentication automatically. After connecting, +**Use connection and continue** checks agent-update permissions and validates in +the agent's execution environment before committing the agent binding, connection +install, audit, and card completion in one transaction. A failed validation or +completion leaves the request pending and the old agent configuration and access +intact. Unsupported harness/provider routes are not guessed. + Codex ACP terminal failures with category `limit` and explicit usage-exhaustion wording enter provider-quota recovery. A supported reset clock uses the existing Codex parser; when none is available, recovery uses its existing quota backoff. @@ -324,7 +352,10 @@ Native Codex and ACPX/Claude provider selections follow the same compatibility r Hiring may succeed before that personal account exists or while it needs repair, including hires awaiting board approval. The first assigned task then shows an AI connection card. First-time setup presents the provider's subscription/API controls -inside the task. Connecting installs access for that agent and resumes the pending +inside the task. The inline form omits the connection name field and names new +accounts from the user's display name, provider, and selected authentication +method (for example, `dotta's Claude API account`). Reconnecting preserves the +existing account name. Connecting installs access for that agent and resumes the pending work automatically. Explicit incompatible bindings and shared-account permission denials still fail; hiring never expands a restricted shared account's audience. diff --git a/packages/shared/src/types/connection-intent.ts b/packages/shared/src/types/connection-intent.ts index 99e7771a7fb..8ed66ef8e51 100644 --- a/packages/shared/src/types/connection-intent.ts +++ b/packages/shared/src/types/connection-intent.ts @@ -57,6 +57,8 @@ export type ConnectionIntentSetupConnection = Pick { afterAll(async () => { await database?.cleanup(); vi.unstubAllEnvs(); if (home) await rm(home, { recursive: true, force: true }); }); describe("managed AI connections", () => { + it.each([ + ["anthropic", false], ["openai", false], ["anthropic", true], ["openai", true], + ] as const)("turns a %s auth failure into one card and resumes after repair (switch method: %s)", async (provider, switchMethod) => { + const userId = `auth-recovery-${provider}-${switchMethod}`; + const id = randomUUID(); + const issueId = randomUUID(); + const runId = randomUUID(); + const adapterType = provider === "openai" ? "codex_local" : "claude_local"; + const selectedBinding = { provider, method: "api_key", mode: "responsible_user" } as const; + await db.insert(companyMemberships).values({ companyId, principalId: userId, principalType: "user", status: "active", membershipRole: "member" }); + await db.insert(agents).values({ id, companyId, name: "Auth recovery", adapterType, runtimeConfig: { aiConnection: selectedBinding } }); + await db.insert(issues).values({ id: issueId, companyId, title: "Fix provider login", status: "in_progress", assigneeAgentId: id }); + const account = await service.save(companyId, userId, { provider, method: "api_key", ownership: "personal", name: "Recovery account", apiKey: "fixture", agentIds: [id], allAgents: false }, "fixture-recovery-key"); + const runtime = await prepareManagedAiRuntime(db, { companyId, agentId: id, responsibleUserId: userId, adapterType, binding: selectedBinding, config: {} }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId: id, status: "failed", errorCode: "acpx_auth_required", responsibleUserId: userId, + contextSnapshot: { issueId, aiConnection: { ...runtime.attribution, identity: runtime.identity } } }); + await runtime.cleanup(); + const intents = connectionIntentService(db); + const card = await intents.requestForRunAuthFailure(runId); + expect(card).toMatchObject({ state: "needs_user_action", service: provider }); + expect((await intents.requestForRunAuthFailure(runId))?.interactionId).toBe(card!.interactionId); + const setup = await intents.setupOptions(card!.interactionId!); + expect(setup.existingConnections).toEqual([]); + expect(setup.aiRepair).toMatchObject({ canReconnect: true, connection: { id: account.connectionId, status: "needs_attention" } }); + await expect(intents.complete(card!.interactionId!, account.connectionId, userId)).rejects.toThrow(); + // A stopped run's token cannot call the public request path. + await expect(intents.request({ sub: id, company_id: companyId, run_id: runId, responsible_user_id: userId }, provider, { purpose: "ai" })).rejects.toThrow("no longer active"); + // Reverification can keep the same credential bytes; it still supersedes the failure. + let repaired = account; + if (switchMethod) { + const token = provider === "openai" ? JSON.stringify({ tokens: { access_token: "fixture-subscription", refresh_token: "fixture-refresh", id_token: "fixture-id", account_id: "fixture-account" } }) : "fixture-subscription"; + repaired = await service.save(companyId, userId, { provider, method: "subscription", ownership: "personal", name: "Recovery subscription", loginSessionId: "fixture", agentIds: [id], allAgents: false }, token); + await service.setDefault(companyId, userId, repaired.grantId); + const [original] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, account.grantId)); + expect(original.status).toBe("needs_reauthorization"); + } else { + await service.save(companyId, userId, { provider, method: "api_key", ownership: "personal", name: "Recovery account", connectionId: account.connectionId, apiKey: "fixture", agentIds: [id], allAgents: false }, provider === "openai" ? "fixture-recovery-key" : "fixture-repaired-key"); + } + expect((await intents.setupOptions(card!.interactionId!)).existingConnections.map(connection => connection.id)).toEqual([repaired.connectionId]); + await intents.complete(card!.interactionId!, repaired.connectionId, userId); + const wakeup = vi.fn(async (_agentId, opts) => { + await db.insert(agentWakeupRequests).values({ companyId, agentId: id, source: "automation", status: "queued", idempotencyKey: opts.idempotencyKey }); + return null; + }); + await connectionIntentDeliveryService(db, { wakeup } as never).deliver(card!.interactionId!); + expect(wakeup).toHaveBeenCalledTimes(1); + expect(wakeup).toHaveBeenCalledWith(id, expect.objectContaining({ contextSnapshot: expect.objectContaining({ forceFreshSession: true }) })); + // Reprocessing an old failure cannot invalidate the newly saved credential. + await intents.requestForRunAuthFailure(runId); + expect((await service.select({ companyId, agentId: id, userId, adapterType, binding: selectedBinding })).grant.status).toBe("active"); + }); + + it("offers a compatible connection for legacy auth failures without silently adopting it", async () => { + const id = randomUUID(); + const issueId = randomUUID(); + const runId = randomUUID(); + await db.insert(agents).values({ id, companyId, name: "Legacy Codex", adapterType: "paperclip_runner", adapterConfig: { provider: "codex" } }); + await db.insert(issues).values({ id: issueId, companyId, title: "Legacy auth", status: "in_progress", assigneeAgentId: id }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId: id, nativeIssueId: issueId, status: "failed", errorCode: "acpx_auth_required", responsibleUserId: "alice", contextSnapshot: {} }); + const intents = connectionIntentService(db); + const card = await intents.requestForRunAuthFailure(runId); + expect(card).toMatchObject({ service: "openai", state: "needs_user_action" }); + expect(await intents.setupOptions(card!.interactionId!)).toMatchObject({ aiConnectionRequiresAdoption: true, aiConnection: { provider: "openai", mode: "responsible_user" } }); + const [unchanged] = await db.select().from(agents).where(eq(agents.id, id)); + expect(unchanged.runtimeConfig.aiConnection).toBeUndefined(); + await db.insert(heartbeatRuns).values({ companyId, agentId: id, status: "succeeded", responsibleUserId: "alice", contextSnapshot: { issueId }, createdAt: new Date(Date.now() + 1000) }); + expect(await intents.requestForRunAuthFailure(runId)).toBeNull(); + }); it.each([ ["anthropic", "claude_local", "CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_API_KEY"], ["openai", "codex_local", "CODEX_HOME", "OPENAI_API_KEY"], @@ -668,7 +736,7 @@ describe("managed AI connections", () => { expect((await service.select(selectionInput)).grant.id).toBe(account.grantId); }); - it("validates runner account adoption in the inherited sandbox and refuses an unavailable target", async () => { + it.each([false, true])("validates runner account adoption in the inherited sandbox (inline: %s)", async (inline) => { const { agentRoutes } = await import("../routes/agents.js"); const { instanceSettingsService } = await import("../services/instance-settings.js"); const targetModule = await import("../services/environment-execution-target.js"); @@ -676,12 +744,20 @@ describe("managed AI connections", () => { const { requireServerAdapter } = await import("../adapters/index.js"); const settings = instanceSettingsService(db); const previous = await settings.get(); - const [environment] = await db.insert(environments).values({ name: "Adoption sandbox", driver: "sandbox", config: { provider: "daytona" } }).returning(); + const [environment] = await db.insert(environments).values({ name: `Adoption sandbox ${inline}`, driver: "sandbox", config: { provider: "daytona" } }).returning(); await settings.update({ defaultEnvironmentId: environment.id }); const id = randomUUID(); await db.insert(agents).values({ id, companyId, name: "Runner adoption", adapterType: "paperclip_runner", adapterConfig: { provider: "codex", model: "gpt-5.6-sol" } }); - const account = await service.save(companyId, "alice", { provider: "openai", method: "api_key", ownership: "personal", name: "Runner adoption account", apiKey: "fixture-adoption-key", agentIds: [id], allAgents: false }, "fixture-adoption-key"); + const account = await service.save(companyId, "alice", { provider: "openai", method: "api_key", ownership: "personal", name: "Runner adoption account", apiKey: "fixture-adoption-key", agentIds: inline ? [] : [id], allAgents: false }, "fixture-adoption-key"); await service.setDefault(companyId, "alice", account.grantId); + let interactionId: string | undefined; + if (inline) { + const issueId = randomUUID(); + const runId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Atomic adoption", status: "in_progress", assigneeAgentId: id }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId: id, status: "failed", errorCode: "acpx_auth_required", responsibleUserId: "alice", contextSnapshot: { issueId } }); + interactionId = (await connectionIntentService(db).requestForRunAuthFailure(runId))!.interactionId!; + } const target = { kind: "remote", transport: "sandbox", remoteCwd: "/workspace", providerKey: "daytona", runner: { execute: vi.fn(async () => ({ exitCode: 0, stdout: "", stderr: "", timedOut: false })) } } as const; const resolveTarget = vi.spyOn(targetModule, "resolveEnvironmentExecutionTarget").mockResolvedValue(target); const release = vi.fn(async () => undefined); @@ -695,26 +771,54 @@ describe("managed AI connections", () => { app.use((error: { status?: number; message: string }, _req: express.Request, res: express.Response, _next: express.NextFunction) => { res.status(error.status ?? 500).json({ error: error.message }); }); const selected = { provider: "openai", method: "api_key", mode: "responsible_user" } as const; const providerRequest = vi.spyOn(globalThis, "fetch").mockImplementation(async () => new Response(null, { status: 200 })); + const adopt = () => inline + ? request(app).post(`/api/agents/${id}/connection-intents/${interactionId}/adopt`).send({ connectionId: account.connectionId }) + : request(app).patch(`/api/agents/${id}`).send({ runtimeConfig: { aiConnection: selected } }); try { // Target resolution can return only warning checks. Adoption still must // fail closed, rather than quietly running the probe on the server host. resolveTarget.mockResolvedValueOnce(null); - const unavailable = await request(app).patch(`/api/agents/${id}`).send({ runtimeConfig: { aiConnection: selected } }); + const unavailable = await adopt(); expect(unavailable.status, JSON.stringify(unavailable.body)).toBe(422); expect(probe).not.toHaveBeenCalled(); expect(providerRequest).not.toHaveBeenCalled(); expect((await db.select().from(agents).where(eq(agents.id, id)))[0].runtimeConfig.aiConnection).toBeUndefined(); - const saved = await request(app).patch(`/api/agents/${id}`).send({ runtimeConfig: { aiConnection: selected } }); + if (inline) { + const assertUnchanged = async () => { + expect((await db.select().from(agents).where(eq(agents.id, id)))[0].runtimeConfig.aiConnection).toBeUndefined(); + expect(await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, account.connectionId))).toEqual([]); + expect((await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, interactionId!)))[0].status).toBe("pending"); + }; + await assertUnchanged(); + // Force the last write to fail after binding and install changes. + await db.execute(sql.raw(`CREATE FUNCTION reject_atomic_adoption() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.id = '${interactionId}'::uuid THEN RAISE EXCEPTION 'injected resolution failure'; END IF; RETURN NEW; END $$`)); + await db.execute(sql.raw("CREATE TRIGGER reject_atomic_adoption BEFORE UPDATE ON issue_thread_interactions FOR EACH ROW EXECUTE FUNCTION reject_atomic_adoption()")); + try { + const failed = await adopt(); + expect(failed.status).toBe(500); + await assertUnchanged(); + } finally { + await db.execute(sql.raw("DROP TRIGGER reject_atomic_adoption ON issue_thread_interactions")); + await db.execute(sql.raw("DROP FUNCTION reject_atomic_adoption()")); + } + } + const saved = await adopt(); expect(saved.status, JSON.stringify(saved.body)).toBe(200); - expect(saved.body.defaultEnvironmentId).toBeNull(); - expect(saved.body.runtimeConfig.aiConnection).toEqual(selected); + const savedAgent = (await db.select().from(agents).where(eq(agents.id, id)))[0]; + expect(savedAgent.defaultEnvironmentId).toBeNull(); + expect(savedAgent.runtimeConfig.aiConnection).toEqual(inline ? { ...selected, method: "subscription" } : selected); + if (inline) { + expect(saved.body.status).toBe("accepted"); + expect(await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, account.connectionId))).toHaveLength(1); + expect((await adopt()).status).toBe(200); + } expect(acquire).toHaveBeenCalledWith(expect.objectContaining({ companyId, environment: expect.objectContaining({ id: environment.id }) })); expect(probe).toHaveBeenCalledWith(expect.objectContaining({ executionTarget: target, config: expect.objectContaining({ provider: "codex", model: "gpt-5.6-sol", managedAiConnection: expect.any(Object) }) })); expect(providerRequest).toHaveBeenCalledWith("https://api.openai.com/v1/models", expect.objectContaining({ headers: { Authorization: "Bearer fixture-adoption-key" }, redirect: "error", })); - expect(release).toHaveBeenCalledTimes(2); + expect(release).toHaveBeenCalledTimes(inline ? 3 : 2); expect(JSON.stringify(saved.body)).not.toContain("fixture-adoption-key"); } finally { providerRequest.mockRestore(); probe.mockRestore(); runtime.mockRestore(); resolveTarget.mockRestore(); diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts index 756d0c7c377..3f15799110a 100644 --- a/server/src/routes/agents.ts +++ b/server/src/routes/agents.ts @@ -1,3 +1,5 @@ +import { connectionIntentService } from "../services/connection-intents.js"; +import { completeConnectionIntentSchema } from "@paperclipai/shared"; import { agentFileStore, agentFileTokenFromHash } from "../services/agent-file-store.js"; import { pipeline } from "node:stream/promises"; import { resolveAgentAppearance, agentAvatarUrl } from "@paperclipai/shared"; @@ -5367,6 +5369,34 @@ export function agentRoutes( res.json(result.bundle); }); + router.post("/agents/:id/connection-intents/:interactionId/adopt", validate(completeConnectionIntentSchema), async (req, res) => { + assertBoard(req); + const agent = await getAccessibleResource(req, res, svc.getById(req.params.id as string), "Agent not found"); + if (!agent) return; + await assertCanUpdateAgent(req, agent); + const userId = responsibleUserForAiRequest(req); + const intents = connectionIntentService(db); + const interactionId = req.params.interactionId as string; + const loaded = await intents.loadIntent(interactionId); + if (loaded.issue.companyId !== agent.companyId || loaded.interaction.payload.requestingAgentId !== agent.id) throw notFound("Connection intent not found"); + if (!userId || loaded.interaction.addresseeUserId !== userId) throw forbidden("Only the addressed user can adopt this connection"); + const connectionId = req.body.connectionId as string; + if (loaded.interaction.status === "accepted" && loaded.interaction.result?.connectionId === connectionId) { + res.json(loaded.interaction); + return; + } + if (loaded.interaction.status !== "pending") throw conflict("Connection intent is already resolved"); + const setup = await intents.setupOptions(interactionId); + if (!setup.aiConnectionRequiresAdoption || !setup.aiConnection) throw conflict("The agent’s AI configuration changed. Reload the task and try again."); + // Probe in the agent's execution environment without installing access. + // The binding, install, audit, and card resolution commit together below. + const validatedConnectionId = await validateManagedAgentBinding(req, agent.companyId, agent.id, agent.adapterType, agent.adapterConfig, setup.aiConnection, agent.defaultEnvironmentId, true, true); + if (validatedConnectionId !== connectionId) throw conflict("This is no longer the selected account. Reload the task and try again."); + res.json(await intents.complete(interactionId, connectionId, userId, { + validatedAdoption: { agentUpdatedAt: agent.updatedAt, binding: setup.aiConnection }, + })); + }); + router.patch("/agents/:id", validate(updateAgentSchema), async (req, res) => { const id = req.params.id as string; const existing = await getAccessibleResource(req, res, svc.getById(id), "Agent not found"); diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index b9970f24034..322c15d90d9 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -1442,6 +1442,7 @@ const BOARD_ONLY_OPERATIONS = new Set([ "GET /api/connection-intents/{interactionId}/setup-options", "POST /api/connection-intents/{interactionId}/phase", "POST /api/connection-intents/{interactionId}/complete", + "POST /api/agents/{id}/connection-intents/{interactionId}/adopt", "POST /api/connection-intents/{interactionId}/decline", "GET /api/companies/{companyId}/tools/profiles", "POST /api/companies/{companyId}/tools/profiles", @@ -10256,6 +10257,23 @@ registerCurrentRoute({ body: completeConnectionIntentSchema, }); +registerCurrentRoute({ + method: "post", + path: "/api/agents/{id}/connection-intents/{interactionId}/adopt", + tags: ["connection-intents", "agents"], + summary: "Validate and atomically adopt an AI connection for a legacy agent", + body: completeConnectionIntentSchema, + responses: { + 200: r.ok(), + 400: r.badRequest, + 401: r.unauthorized, + 403: r.forbidden, + 404: r.notFound, + 409: r.conflict, + 422: r.unprocessable, + }, +}); + registerCurrentRoute({ method: "post", path: "/api/connection-intents/{interactionId}/decline", diff --git a/server/src/services/ai-auth-failure.test.ts b/server/src/services/ai-auth-failure.test.ts new file mode 100644 index 00000000000..0f17104e7e1 --- /dev/null +++ b/server/src/services/ai-auth-failure.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from "vitest"; +import { aiBindingForAuthRecovery, isAiAuthenticationFailure } from "./ai-auth-failure.js"; + +describe("AI authentication failure recovery", () => { + it.each(["acpx_auth_required", "claude_auth_required", "codex_auth_required", "grok_auth_required", "adapter_auth_missing", "refresh_token_reused", "refresh_token_expired", "refresh_token_invalidated"])("recognizes %s", (code) => { + expect(isAiAuthenticationFailure(code)).toBe(true); + }); + it.each(["github_auth_required", "native_adopted_runner_authentication_timeout", "rate_limit", "adapter_failed", "permission_denied", undefined])("does not treat %s as model authentication", (code) => { + expect(isAiAuthenticationFailure(code)).toBe(false); + }); + it.each([ + ["codex_local", {}, "openai"], + ["claude_local", {}, "anthropic"], + ["paperclip_runner", { provider: "codex" }, "openai"], + ["paperclip_runner", { provider: "acpx", acpxAgent: "claude" }, "anthropic"], + ["paperclip_runner", { provider: "acpx", acpxAgent: "grok" }, "xai"], + ["opencode_local", { model: "openrouter/model" }, "openrouter"], + ] as const)("maps %s %j to %s", (adapter, config, provider) => { + expect(aiBindingForAuthRecovery(adapter, config)).toMatchObject({ provider, mode: "responsible_user" }); + }); + it("does not guess a provider for unsupported harnesses or routes", () => { + expect(aiBindingForAuthRecovery("gemini_local", {})).toBeUndefined(); + expect(aiBindingForAuthRecovery("opencode_local", { model: "anthropic/claude" })).toBeUndefined(); + expect(aiBindingForAuthRecovery("paperclip_runner", { provider: "acpx", acpxAgent: "custom" })).toBeUndefined(); + }); +}); diff --git a/server/src/services/ai-auth-failure.ts b/server/src/services/ai-auth-failure.ts new file mode 100644 index 00000000000..5064ab1666b --- /dev/null +++ b/server/src/services/ai-auth-failure.ts @@ -0,0 +1,25 @@ +import { AI_PROVIDERS, isAiConnectionCompatible, type AiConnectionBinding } from "@paperclipai/shared"; + +/** Provider authentication signals only. Tool authorization and quotas need different repairs. */ +export function isAiAuthenticationFailure(code: string | null | undefined): boolean { + return Boolean(code && ( + /^(acpx|claude|codex|grok|opencode|gemini|kimi|pi|cursor)_auth_required$/.test(code) + || ["adapter_auth_missing", "authentication_required", "auth_required", "refresh_token_reused", "refresh_token_expired", "refresh_token_invalidated"].includes(code) + )); +} + +/** Only a persisted blocked classification confirms that an inline repair owns recovery. */ +export function isAiAuthenticationBlocked(run: { errorCode?: string | null; livenessState?: string | null } | null | undefined): boolean { + return run?.livenessState === "blocked" && isAiAuthenticationFailure(run.errorCode); +} + +export function aiBindingForAuthRecovery( + adapterType: string, + config: Record, +): AiConnectionBinding | undefined { + for (const provider of AI_PROVIDERS) { + const binding = { provider, method: provider === "openrouter" ? "api_key" : "subscription", mode: "responsible_user" } as const; + if (isAiConnectionCompatible(binding, adapterType, config.model, config.provider, config.acpxAgent)) return binding; + } + return undefined; +} diff --git a/server/src/services/ai-connections.ts b/server/src/services/ai-connections.ts index 4d06acb853e..26e69d673e1 100644 --- a/server/src/services/ai-connections.ts +++ b/server/src/services/ai-connections.ts @@ -1,5 +1,5 @@ import { syncConnectionCredentialBindings } from "./connection-credential-bindings.js"; -import { randomUUID } from "node:crypto"; +import { createHash, randomUUID } from "node:crypto"; import { and, eq, inArray, or } from "drizzle-orm"; import { type Db, @@ -373,7 +373,7 @@ export function aiConnectionService(db: Db) { } satisfies AiConnectionAttribution, }; } - async function credential(row: Awaited>) { + async function credential(row: Pick>, "connection" | "grant">) { const ref = row.grant.credentialSecretRefs.find( (r) => r.configPath === "ai.credential", ); @@ -775,5 +775,49 @@ export function aiConnectionService(db: Db) { return { connectionId: id, grantId }; }); } - return { list, select, credential, save, setDefault, membership }; + /** A late failure must never invalidate credentials that were refreshed or reconnected meanwhile. */ + async function markAuthenticationFailed(input: { + companyId: string; + runId: string; + agentId: string; + runStartedAt: Date; + attribution: AiConnectionAttribution & { identity: string }; + }) { + return db.transaction(async (tx) => { + const { attribution } = input; + const [grant] = await tx.select().from(connectionGrants).where(and( + eq(connectionGrants.companyId, input.companyId), + eq(connectionGrants.id, attribution.grantId), + eq(connectionGrants.connectionId, attribution.connectionId), + )).for("update"); + if (!grant || grant.status !== "active" || grant.updatedAt > input.runStartedAt) return; + const [connection] = await tx.select().from(toolConnections).where(and( + eq(toolConnections.companyId, input.companyId), + eq(toolConnections.id, attribution.connectionId), + eq(toolConnections.connectionPurpose, "ai"), + )); + if (!connection) return; + const metadata = aiConnectionMetadataSchema.safeParse(connection.config.ai); + if (!metadata.success || metadata.data.provider !== attribution.provider || metadata.data.method !== attribution.method) return; + const ref = grant.credentialSecretRefs.find((candidate) => candidate.configPath === "ai.credential"); + if (!ref) return; + await tx.select({ id: companySecrets.id }).from(companySecrets).where(and( + eq(companySecrets.companyId, input.companyId), eq(companySecrets.id, ref.secretId), + )).for("update"); + const value = await aiConnectionService(tx as unknown as Db).credential({ connection, grant }); + const generation = createHash("sha256").update(value).digest("hex").slice(0, 16); + if (attribution.identity !== `${grant.id}:${attribution.responsibleUserId ?? "shared"}:${generation}`) return; + await tx.update(connectionGrants).set({ status: "needs_reauthorization", updatedAt: new Date() }) + .where(eq(connectionGrants.id, grant.id)); + await tx.update(toolConnections).set({ healthStatus: "error", healthMessage: "Sign in again to restore this AI connection.", updatedAt: new Date() }) + .where(eq(toolConnections.id, connection.id)); + await logActivity(tx as unknown as Db, { + companyId: input.companyId, actorType: "system", actorId: "heartbeat", + agentId: input.agentId, runId: input.runId, action: "ai_connection.authentication_failed", + entityType: "tool_connection", entityId: connection.id, + details: { provider: attribution.provider, grantId: grant.id }, + }); + }); + } + return { list, select, credential, save, setDefault, membership, markAuthenticationFailed }; } diff --git a/server/src/services/connection-intents.ts b/server/src/services/connection-intents.ts index 66137faaebf..46390d7da90 100644 --- a/server/src/services/connection-intents.ts +++ b/server/src/services/connection-intents.ts @@ -1,7 +1,9 @@ +import { agentService } from "./agents.js"; import { logActivity } from "./activity-log.js"; import { aiConnectionService } from "./ai-connections.js"; import { aiConnectionBindingSchema } from "@paperclipai/shared"; -import { and, eq, desc, isNull } from "drizzle-orm"; +import { aiBindingForAuthRecovery, isAiAuthenticationFailure } from "./ai-auth-failure.js"; +import { and, eq, desc, isNull, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { agents, @@ -30,6 +32,8 @@ import { type ConnectionsSearchResult, type ToolApplication, type ToolConnection, + type AiConnectionAttribution, + type AiConnectionBinding, } from "@paperclipai/shared"; import { conflict, forbidden, notFound, unprocessable } from "../errors.js"; import type { RuntimeToolsTokenClaims } from "../runtime-tools-token.js"; @@ -137,16 +141,18 @@ export function connectionIntentService(db: Db) { } } - async function loadRunContext(claims: ConnectionRunClaims) { + async function loadRunContext(claims: ConnectionRunClaims, failedAuthRun = false) { let run = await db .select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId, status: heartbeatRuns.status, + errorCode: heartbeatRuns.errorCode, responsibleUserId: heartbeatRuns.responsibleUserId, activeIdentityContextId: heartbeatRuns.activeIdentityContextId, contextSnapshot: heartbeatRuns.contextSnapshot, + nativeIssueId: heartbeatRuns.nativeIssueId, }) .from(heartbeatRuns) .where(eq(heartbeatRuns.id, claims.run_id)) @@ -157,14 +163,16 @@ export function connectionIntentService(db: Db) { || run.agentId !== claims.sub || (!run.activeIdentityContextId && run.responsibleUserId !== claims.responsible_user_id) ) throw forbidden("Runtime tool token does not match its heartbeat run"); - if (run.status !== "running") throw forbidden("Runtime tool token is no longer active"); - if (run.activeIdentityContextId) { + if (failedAuthRun ? run.status !== "failed" || !isAiAuthenticationFailure(run.errorCode) : run.status !== "running") { + throw forbidden("Runtime tool token is no longer active"); + } + if (run.activeIdentityContextId && !failedAuthRun) { const current = await captureRunIdentity(db, { companyId: run.companyId, agentId: run.agentId, runId: run.id }); run = { ...run, responsibleUserId: current.run.responsibleUserId }; } if (!run.responsibleUserId) throw forbidden("This task needs a responsible user to connect a service"); const snapshot = record(run.contextSnapshot); - const issueId = text(snapshot?.issueId) ?? text(snapshot?.taskId); + const issueId = text(snapshot?.issueId) ?? text(snapshot?.taskId) ?? run.nativeIssueId; if (!issueId) throw unprocessable("Connection requests require a task-bound heartbeat run"); const [issue, agent, responsibleMembership] = await Promise.all([ db.select({ @@ -214,10 +222,11 @@ export function connectionIntentService(db: Db) { }; } - async function managedAgent(companyId: string, agentId: string, serviceSlug: string) { + async function managedAgent(companyId: string, agentId: string, serviceSlug: string, fallback?: AiConnectionBinding) { const [agent] = await db.select().from(agents).where(and(eq(agents.companyId, companyId), eq(agents.id, agentId))); - const binding = aiConnectionBindingSchema.safeParse(agent?.runtimeConfig?.aiConnection).data; - return agent && binding?.provider === serviceSlug ? { agent, binding } : null; + const saved = aiConnectionBindingSchema.safeParse(agent?.runtimeConfig?.aiConnection).data; + const binding = saved ?? fallback; + return agent && binding?.provider === serviceSlug ? { agent, binding, requiresAdoption: !saved } : null; } async function usableConnectionForAgent(input: { @@ -534,6 +543,15 @@ export function connectionIntentService(db: Db) { options: { purpose?: "ai"; selectionInteractionId?: string; targetService?: string } = {}, ): Promise { const context = await loadRunContext(claims); + return requestWithContext(context, serviceSlug, options); + } + + async function requestWithContext( + context: Awaited>, + serviceSlug: string, + options: { purpose?: "ai"; selectionInteractionId?: string; targetService?: string } = {}, + ): Promise { + const claims = { sub: context.agent.id, company_id: context.run.companyId, run_id: context.run.id, responsible_user_id: context.run.responsibleUserId! }; const route = parseAggregatorRoute(serviceSlug); let upstreamService: { slug: string; name: string; selectionInteractionId?: string } | undefined; if (options.targetService) { @@ -645,13 +663,34 @@ export function connectionIntentService(db: Db) { const loaded = await loadIntent(interactionId); const payload = connectionIntentPayloadSchema.parse(loaded.interaction.payload); const app = await resolveService(payload.serviceSlug, loaded.issue.companyId, loaded.interaction.addresseeUserId!, payload.requestingAgentId, payload.purpose); - const managed = payload.purpose === "ai" ? await managedAgent(loaded.issue.companyId, payload.requestingAgentId, app.slug) : null; + let managed = payload.purpose === "ai" ? await managedAgent(loaded.issue.companyId, payload.requestingAgentId, app.slug) : null; + if (payload.purpose === "ai" && !managed) { + const [source] = await db.select().from(heartbeatRuns).where(and( + eq(heartbeatRuns.id, loaded.interaction.sourceRunId!), eq(heartbeatRuns.companyId, loaded.issue.companyId), + eq(heartbeatRuns.agentId, payload.requestingAgentId), + )); + const [agent] = await db.select().from(agents).where(and(eq(agents.id, payload.requestingAgentId), eq(agents.companyId, loaded.issue.companyId))); + if (source?.status === "failed" && isAiAuthenticationFailure(source.errorCode) && !source.contextSnapshot?.aiConnection && agent && !agent.runtimeConfig.aiConnection) { + managed = await managedAgent(loaded.issue.companyId, agent.id, app.slug, aiBindingForAuthRecovery(agent.adapterType, agent.adapterConfig)); + } + } if (payload.purpose === "ai" && !managed) throw conflict("The agent’s AI configuration changed. Start a new execution."); const inventory = await connectionInventory(loaded.issue.companyId); - const usableAiConnection = managed ? await usableConnectionForAgent({ + let usableAiConnection = managed ? await usableConnectionForAgent({ companyId: loaded.issue.companyId, agentId: payload.requestingAgentId, responsibleUserId: loaded.interaction.addresseeUserId!, serviceSlug: app.slug, purpose: "ai", }) : null; + if (managed?.requiresAdoption) { + try { + const selected = await aiConnectionService(db).select({ + companyId: loaded.issue.companyId, agentId: managed.agent.id, userId: loaded.interaction.addresseeUserId!, + adapterType: managed.agent.adapterType, model: managed.agent.adapterConfig.model, + runnerProvider: managed.agent.adapterConfig.provider, acpxAgent: managed.agent.adapterConfig.acpxAgent, + binding: managed.binding, allowUninstalledPersonal: true, + }); + usableAiConnection = await access.getConnection(selected.connection.id, loaded.issue.companyId); + } catch (error) { if (![403, 404, 422].includes((error as { status?: number }).status ?? 0)) throw error; } + } const aiAccounts = managed ? await aiConnectionService(db).list(loaded.issue.companyId, loaded.interaction.addresseeUserId!) : []; const selectedAiAccount = managed ? aiAccounts.find((account) => account.provider === managed.binding.provider && (managed.binding.mode === "responsible_user" || account.method === managed.binding.method) @@ -694,6 +733,7 @@ export function connectionIntentService(db: Db) { })), requestedAgentId: payload.requestingAgentId, aiConnection: managed?.binding, + aiConnectionRequiresAdoption: managed?.requiresAdoption || undefined, aiRepair: selectedAiAccount ? { connection: selectedAiAccount, canReconnect: selectedAiGrant?.createdByUserId === loaded.interaction.addresseeUserId @@ -711,6 +751,7 @@ export function connectionIntentService(db: Db) { options: { canManageOrganizationGrant?: boolean; bypassCurrentMembershipCheck?: boolean; + validatedAdoption?: { agentUpdatedAt: Date; binding: AiConnectionBinding }; } = {}, ) { const loaded = await loadIntent(interactionId); @@ -760,7 +801,27 @@ export function connectionIntentService(db: Db) { if (payload.purpose === "ai" && selectedConnection.connectionPurpose !== "ai") throw conflict("Select an AI account for this authentication request"); if (selectedConnection.connectionPurpose === "ai") { if (payload.purpose !== "ai") throw conflict("AI authentication cannot satisfy a tool connection request"); - const managed = await managedAgent(loaded.issue.companyId, payload.requestingAgentId, payload.serviceSlug); + let managed; + if (options.validatedAdoption) { + const [agent] = await tx.select().from(agents).where(and(eq(agents.id, payload.requestingAgentId), eq(agents.companyId, loaded.issue.companyId))).for("update"); + if (!agent || agent.runtimeConfig.aiConnection || agent.updatedAt.getTime() !== options.validatedAdoption.agentUpdatedAt.getTime()) { + throw conflict("The agent changed during validation. Reload the task and try again."); + } + const binding = options.validatedAdoption.binding; + if (binding.provider !== payload.serviceSlug || binding.mode !== "responsible_user") throw conflict("Invalid legacy adoption binding"); + const updated = await agentService(txDb).update(agent.id, { + runtimeConfig: { ...agent.runtimeConfig, aiConnection: binding }, + }, { recordRevision: { createdByUserId: userId, source: "patch" } }); + if (!updated) throw notFound("Agent not found"); + await logActivity(txDb, { + companyId: loaded.issue.companyId, actorType: "user", actorId: userId, + action: "agent.updated", entityType: "agent", entityId: agent.id, + details: { connectionIntentId: interactionId, aiConnectionAdopted: true }, + }); + managed = { agent: updated, binding, requiresAdoption: false }; + } else { + managed = await managedAgent(loaded.issue.companyId, payload.requestingAgentId, payload.serviceSlug); + } if (!managed) throw conflict("Configure the agent’s AI connection before using this account"); const service = aiConnectionService(txDb); if (managed.binding.mode === "responsible_user") { @@ -883,6 +944,30 @@ export function connectionIntentService(db: Db) { usableConnectionForAgent, search, request, + // Controller-only entry point. Runtime tokens still require a running run. + requestForRunAuthFailure: async (runId: string) => { + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + if (!run || run.status !== "failed" || !isAiAuthenticationFailure(run.errorCode) || !run.responsibleUserId) return null; + const context = await loadRunContext({ sub: run.agentId, company_id: run.companyId, run_id: run.id, responsible_user_id: run.responsibleUserId }, true); + const [latest] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, run.companyId), + sql`coalesce(${heartbeatRuns.contextSnapshot}->>'issueId', ${heartbeatRuns.contextSnapshot}->>'taskId', ${heartbeatRuns.nativeIssueId}::text) = ${context.issue.id}`, + )).orderBy(desc(heartbeatRuns.createdAt)).limit(1); + if (latest?.id !== run.id) return null; + const [agent] = await db.select().from(agents).where(and(eq(agents.id, run.agentId), eq(agents.companyId, run.companyId))); + if (!agent) return null; + const saved = aiConnectionBindingSchema.safeParse(agent.runtimeConfig.aiConnection).data; + const binding = saved ?? aiBindingForAuthRecovery(agent.adapterType, agent.adapterConfig); + if (!binding) return null; + const attribution = record(run.contextSnapshot?.aiConnection); + if (attribution && attribution.provider !== binding.provider) return null; + if (saved && attribution && typeof attribution.identity === "string" && typeof attribution.connectionId === "string" && typeof attribution.grantId === "string") { + await aiConnectionService(db).markAuthenticationFailed({ companyId: run.companyId, runId: run.id, agentId: run.agentId, + runStartedAt: run.startedAt ?? run.createdAt, + attribution: attribution as unknown as AiConnectionAttribution & { identity: string } }); + } + return requestWithContext(context, binding.provider, { purpose: "ai" }); + }, loadIntent, setupOptions, complete, diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index 9b2d4fde920..493a012b4a0 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -1,3 +1,4 @@ +import { isAiAuthenticationBlocked } from "./ai-auth-failure.js"; import { CHAT_COMPLETION_WAKE_REASON, prepareChatCompletionTurn, chatCompletionInstruction, isCompletedOnboardingHandoffWake } from "./chat-completion-delivery.js"; import { isAgentDirectoryCopy } from "./agent-directory-working-copies.js"; @@ -18295,9 +18296,16 @@ export function heartbeatService( run: typeof heartbeatRuns.$inferSelect, resultJson?: Record | null, ) { - const classification = classifyRunLiveness( - await buildRunLivenessInput(run, resultJson), - ); + const authRepair = run.status === "failed" + ? await connectionIntentService(db).requestForRunAuthFailure(run.id).catch(() => { + logger.warn({ runId: run.id }, "Could not attach provider authentication repair; run failure remains available"); + return null; + }) + : null; + const classification = classifyRunLiveness({ + ...await buildRunLivenessInput(run, resultJson), + authenticationRepairRequested: Boolean(authRepair?.interactionId), + }); return db .update(heartbeatRuns) .set({ @@ -21436,7 +21444,7 @@ export function heartbeatService( await finalizeAiConnectionBusyDeferral(run, error, !authorizedNonAssigneeWake); return; } - if (responsibleUserId && issueId && aiBinding.mode === "responsible_user") { + if (responsibleUserId && issueId) { await connectionIntentService(db).request({ sub: agent.id, company_id: agent.companyId, run_id: run.id, responsible_user_id: responsibleUserId }, aiBinding.provider, { purpose: "ai" }).catch(() => { logger.warn({ runId: run.id, agentId: agent.id }, "Could not attach AI connection request; runtime configuration action remains available"); }); @@ -26443,11 +26451,14 @@ export function heartbeatService( options: { suppressImmediateRecovery?: boolean } = {}, ) { try { + const source = await getRun(run.id); const { postCommitEffects } = await wakeQueue.releaseIssueExecution({ companyId: run.companyId, runId: run.id, now: new Date(), - suppressImmediateRecovery: options.suppressImmediateRecovery, + // A durable authentication card owns recovery. This covers the review path, + // while continuation classification blocks periodic generic retries. + suppressImmediateRecovery: options.suppressImmediateRecovery || isAiAuthenticationBlocked(source), }); await applyWakeQueuePostCommitEffects(postCommitEffects); const completed = await getRun(run.id); diff --git a/server/src/services/recovery/provider-failure-classification.test.ts b/server/src/services/recovery/provider-failure-classification.test.ts index d356144fe03..17226f5e946 100644 --- a/server/src/services/recovery/provider-failure-classification.test.ts +++ b/server/src/services/recovery/provider-failure-classification.test.ts @@ -1,3 +1,5 @@ +import { classifyRunLiveness } from "../run-liveness.js"; +import { isAiAuthenticationBlocked } from "../ai-auth-failure.js"; import { describe, expect, it } from "vitest"; import { PROVIDER_QUOTA_RECOVERY_DEFAULT_BACKOFF_MS, @@ -7,6 +9,20 @@ import { import { legacyExecutionNeedsReconciliation } from "../legacy-execution-recovery.js"; describe("classifyAdapterFailureForRecovery", () => { + it.each(["acpx_auth_required", "claude_auth_required", "codex_auth_required", "adapter_auth_missing", "refresh_token_reused", "authentication_required"])("does not automatically retry provider authentication failure %s", (errorCode) => { + const classification = classifyRunLiveness({ runStatus: "failed", issue: null, errorCode, authenticationRepairRequested: true }); + const run = { errorCode, ...classification }; + expect(isAiAuthenticationBlocked(run)).toBe(true); + expect(classifyContinuationFailure(run as never)).toMatchObject({ kind: "non_retryable", maxAttempts: 0 }); + }); + + it.each(["kimi_auth_required", "acpx_auth_required", "gemini_auth_required"])("preserves recovery when %s did not produce an inline repair card", (errorCode) => { + const classification = classifyRunLiveness({ runStatus: "failed", issue: null, errorCode, authenticationRepairRequested: false }); + const run = { errorCode, ...classification }; + expect(isAiAuthenticationBlocked(run)).toBe(false); + expect(classifyContinuationFailure(run as never).kind).toBe("default"); + }); + it("uses a typed ACP quota reset without needing the provider's original message", () => { const now = new Date("2026-07-15T20:00:00.000Z"); expect(classifyAdapterFailureForRecovery({ diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index 10ab3d98248..a238785b079 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -1,3 +1,4 @@ +import { isAiAuthenticationBlocked } from "../ai-auth-failure.js"; import { isNativeWorkspaceExportRepairCause } from "@paperclipai/shared"; import { settleSlackConversation } from "../slack-conversation-lifecycle.js"; import { externalConversationStateSql } from "../slack-conversation-state.js"; @@ -710,7 +711,7 @@ export function classifyContinuationFailure( errorCode, }; } - if (errorCode && NON_RETRYABLE_CONTINUATION_ERROR_CODES.has(errorCode)) { + if (isAiAuthenticationBlocked(latestRun) || (errorCode && NON_RETRYABLE_CONTINUATION_ERROR_CODES.has(errorCode))) { return { kind: "non_retryable", maxAttempts: 0, diff --git a/server/src/services/run-liveness.ts b/server/src/services/run-liveness.ts index 8f257c44d75..dc5ca30e365 100644 --- a/server/src/services/run-liveness.ts +++ b/server/src/services/run-liveness.ts @@ -1,3 +1,4 @@ +import { isAiAuthenticationFailure } from "./ai-auth-failure.js"; import type { HeartbeatRunStatus, IssueStatus, RunLivenessState } from "@paperclipai/shared"; export type RunLivenessActionability = @@ -37,6 +38,8 @@ export interface RunLivenessClassificationInput { errorCode?: string | null; continuationAttempt?: number | null; evidence?: Partial | null; + /** Set by the controller only after creating a durable connection card. */ + authenticationRepairRequested?: boolean; } export interface RunLivenessClassification { @@ -320,6 +323,10 @@ export function classifyRunLiveness(input: RunLivenessClassificationInput): RunL return output("needs_followup", input.errorCode ? `Run interrupted (${input.errorCode})` : "Run interrupted"); } + if (input.runStatus === "failed" && input.authenticationRepairRequested && isAiAuthenticationFailure(input.errorCode)) { + return output("blocked", "Waiting for provider authentication repair", "Complete the connection request to continue this task"); + } + if (input.runStatus !== "succeeded") { if (hasUnmanagedBackgroundTaskEvidence(input.resultJson)) { return output("failed", UNMANAGED_BACKGROUND_TASK_LIVENESS_REASON); diff --git a/ui/src/api/agents.ts b/ui/src/api/agents.ts index 62de19bcfcf..d1709a68007 100644 --- a/ui/src/api/agents.ts +++ b/ui/src/api/agents.ts @@ -1,5 +1,6 @@ import type { Agent, + ConnectionIntentInteraction, AgentDesiredSkillEntry, AgentSkillAssignmentMode, AgentPermissions, @@ -108,6 +109,9 @@ function agentPath(id: string, companyId?: string, suffix = "") { } export const agentsApi = { + adoptAiConnection: (agentId: string, interactionId: string, connectionId: string, companyId: string) => + api.post(withCompanyScope(`/agents/${agentId}/connection-intents/${interactionId}/adopt`, companyId), { connectionId }), + list: (companyId: string) => api.get(`/companies/${companyId}/agents`), org: (companyId: string) => api.get(`/companies/${companyId}/org`), listConfigurations: (companyId: string) => diff --git a/ui/src/components/IssueThreadInteractionCard.tsx b/ui/src/components/IssueThreadInteractionCard.tsx index 4c91d7559d5..d839990ffc1 100644 --- a/ui/src/components/IssueThreadInteractionCard.tsx +++ b/ui/src/components/IssueThreadInteractionCard.tsx @@ -3856,6 +3856,7 @@ export function IssueThreadInteractionCard({ interaction={interaction} currentUserId={currentUserId} addresseeLabel={addresseeLabel ?? "the addressed person"} + addresseeName={interaction.addresseeUserId ? userLabelMap?.get(interaction.addresseeUserId) : undefined} /> ) : interaction.kind === "request_item_verdicts" ? ( string; ownership: "personal" | "shared"; agentIds: string[]; allAgents: boolean; @@ -34,7 +36,7 @@ export function AiConnectionCredentialStep(props: Props) { return ; } -function SubscriptionConnectionStep({ companyId, provider, initialMethod, fixedMethod, connectionId, name: initialName, ownership, agentIds, allAgents, environmentId: suppliedEnvironmentId, onComplete, onCancel }: Props) { +function SubscriptionConnectionStep({ companyId, provider, initialMethod, fixedMethod, connectionId, name: initialName, hideName, nameForMethod, ownership, agentIds, allAgents, environmentId: suppliedEnvironmentId, onComplete, onCancel }: Props) { const [name, setName] = useState(initialName); const [chosenEnvironment, setChosenEnvironment] = useState(); const client = useQueryClient(); @@ -74,7 +76,7 @@ function SubscriptionConnectionStep({ companyId, provider, initialMethod, fixedM const error = environmentError ?? [envs, caps, settings, experimental, general].find((query) => query.error)?.error?.message; const intent: AiConnectionLoginIntent = { provider, method: "subscription", name, ownership, agentIds, allAgents, connectionId }; return
- + {!hideName && } {!suppliedEnvironmentId && !forced.forced && loginEnvironments.length > 1 && setName(event.target.value)} disabled={Boolean(connectionId)} /> + {!hideName && } {save.error &&

{save.error.message}

} save.mutate()} disabled={save.isPending} placeholder="Enter API key here" autoFocus />
diff --git a/ui/src/components/ai-connections/model.test.ts b/ui/src/components/ai-connections/model.test.ts index 719bfab561c..61005a89653 100644 --- a/ui/src/components/ai-connections/model.test.ts +++ b/ui/src/components/ai-connections/model.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import { aiConnectionProblem, + defaultAiConnectionName, bindingProblem, matchesAiRequirement, personalAiDefault, @@ -150,3 +151,12 @@ describe("AI connection selection presentation", () => { ).toBe("Not in the shared audience"); }); }); + +describe("default AI account names", () => { + it("uses provider and method labels with a personal fallback", () => { + expect(defaultAiConnectionName("dotta", "anthropic", "api_key")).toBe("dotta's Claude API account"); + expect(defaultAiConnectionName("Dotta", "openai", "subscription")).toBe("Dotta's ChatGPT subscription account"); + expect(defaultAiConnectionName("You", "openai", "api_key")).toBe("My OpenAI API account"); + expect(defaultAiConnectionName(undefined, "openrouter", "api_key")).toBe("My OpenRouter API account"); + }); +}); diff --git a/ui/src/components/ai-connections/model.ts b/ui/src/components/ai-connections/model.ts index 4d1c6915f0f..8f2c2cbb50f 100644 --- a/ui/src/components/ai-connections/model.ts +++ b/ui/src/components/ai-connections/model.ts @@ -40,6 +40,15 @@ export const AI_CONNECTION_STATUS: Record = { revoked: "Revoked", }; +export function defaultAiConnectionName(ownerName: string | undefined, provider: AiProvider, method: AiAuthMethod) { + const owner = ownerName?.trim(); + const prefix = owner && owner !== "You" ? `${owner}'s` : "My"; + const providerName = method === "subscription" + ? AI_PROVIDERS[provider].subscriptionName ?? AI_PROVIDERS[provider].name + : `${AI_PROVIDERS[provider].name} API`; + return `${prefix} ${providerName} account`; +} + export function aiMethodLabel(provider: AiProvider, method: AiAuthMethod) { return method === "subscription" ? (AI_PROVIDERS[provider].subscriptionName ?? "Subscription unavailable") diff --git a/ui/src/components/new-agent/AgentProviderConnection.test.tsx b/ui/src/components/new-agent/AgentProviderConnection.test.tsx index c4301be34f2..6b06006e0ae 100644 --- a/ui/src/components/new-agent/AgentProviderConnection.test.tsx +++ b/ui/src/components/new-agent/AgentProviderConnection.test.tsx @@ -4,6 +4,7 @@ import { createRoot, type Root } from "react-dom/client"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { afterEach, describe, expect, it, vi } from "vitest"; import { AgentProviderConnection } from "./AgentProviderConnection"; +import { defaultAiConnectionName } from "../ai-connections/model"; import { ApiError } from "@/api/client"; const mocks = vi.hoisted(() => ({ auth: vi.fn(), @@ -44,7 +45,7 @@ afterEach(() => { vi.resetAllMocks(); }); async function mount( - adapterType: "claude_local" | "codex_local" = "claude_local", + adapterType: "claude_local" | "codex_local" | "grok_local" = "claude_local", savedLogin = false, canLogin = true, codexSubscriptions = false, @@ -148,6 +149,77 @@ function openProvider() { ); } describe("AgentProviderConnection reuse", () => { + it.each([ + ["anthropic", "claude_local"], ["openai", "codex_local"], ["xai", "grok_local"], + ] as const)("lets %s recovery switch methods without overwriting the original account", async (provider, adapterType) => { + const onComplete = vi.fn(); + const intent = { provider, method: "subscription" as const, name: "Existing API account", ownership: "personal" as const, agentIds: ["agent"], allAgents: false, connectionId: "original" }; + await mount(adapterType, false, true, false, false, false, { + intent, initialMethod: "api_key", fixedMethod: false, onComplete, + nameForMethod: method => defaultAiConnectionName("dotta", provider, method), + }); + openProvider(); + expect(host.querySelector('input[type="password"]')).not.toBeNull(); + click("Use subscription instead"); + const subscription = mocks.loginPanel.mock.calls.at(-1)![0].aiConnection; + expect(subscription).toMatchObject({ provider, method: "subscription", name: defaultAiConnectionName("dotta", provider, "subscription") }); + expect(subscription.connectionId).toBeUndefined(); + expect(host.querySelector('input[type="password"]')).toBeNull(); + click("Use API key instead"); + flushSync(() => { + const input = host.querySelector('input[type="password"]')!; + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "test-api-key"); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + click("Connect"); + await vi.waitFor(() => expect(onComplete).toHaveBeenCalled()); + expect(managedApi.create).toHaveBeenCalledWith("c1", expect.objectContaining({ connectionId: "original", name: "Existing API account", method: "api_key" })); + }); + it("creates an API account when recovering a subscription with an API key", async () => { + const onComplete = vi.fn(); + await mount("claude_local", false, true, false, false, false, { + intent: { provider: "anthropic", method: "subscription", name: "Existing subscription", ownership: "personal", agentIds: [], allAgents: false, connectionId: "subscription" }, + initialMethod: "subscription", fixedMethod: false, onComplete, + nameForMethod: method => defaultAiConnectionName("dotta", "anthropic", method), + }); + openProvider(); + click("Use API key instead"); + flushSync(() => { + const input = host.querySelector('input[type="password"]')!; + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "test-api-key"); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + click("Connect"); + await vi.waitFor(() => expect(onComplete).toHaveBeenCalled()); + const saved = managedApi.create.mock.calls.at(-1)! as unknown as [string, {connectionId?: string; name: string; method: string}]; + expect(saved[1]).toMatchObject({ name: "dotta's Claude API account", method: "api_key" }); + expect(saved[1].connectionId).toBeUndefined(); + }); + + it.each([false, true])("names the selected method automatically and preserves reconnect names (reconnect: %s)", async (reconnect) => { + const onComplete = vi.fn(); + const intent = { provider: "anthropic" as const, method: "subscription" as const, name: "Existing account", ownership: "personal" as const, agentIds: [], allAgents: false, ...(reconnect ? { connectionId: "existing" } : {}) }; + await mount("claude_local", false, true, false, false, false, { + intent, onComplete, + nameForMethod: method => defaultAiConnectionName("dotta", "anthropic", method), + }); + openProvider(); + expect(mocks.loginPanel.mock.calls.at(-1)![0].aiConnection.name).toBe(reconnect ? "Existing account" : "dotta's Claude subscription account"); + click("Back"); + click("Use API key instead"); + openProvider(); + flushSync(() => { + const input = host.querySelector('input[type="password"]')!; + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "test-api-key"); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + click("Connect"); + await vi.waitFor(() => expect(onComplete).toHaveBeenCalled()); + expect(managedApi.create).toHaveBeenCalledWith("c1", expect.objectContaining({ + name: reconnect ? "Existing account" : "dotta's Claude API account", method: "api_key", apiKey: "test-api-key", + })); + }); + it.each(["claude_local", "codex_local"] as const)("does not offer a server-host command when health disables local login: %s", async adapterType => { const onComplete = vi.fn(); const intent = { provider: adapterType === "claude_local" ? "anthropic" as const : "openai" as const, method: "subscription" as const, name: "Hosted account", ownership: "personal" as const, agentIds: [], allAgents: false }; diff --git a/ui/src/components/new-agent/AgentProviderConnection.tsx b/ui/src/components/new-agent/AgentProviderConnection.tsx index 137adf39502..391330fdb76 100644 --- a/ui/src/components/new-agent/AgentProviderConnection.tsx +++ b/ui/src/components/new-agent/AgentProviderConnection.tsx @@ -57,6 +57,7 @@ export function AgentProviderConnection({ /** Connections supplies its access intent; presentation and login controllers stay shared. */ managedAccount?: { intent: AiConnectionLoginIntent; + nameForMethod?: (method: "subscription" | "api_key") => string; initialMethod?: "subscription" | "api_key"; fixedMethod?: boolean; disabled?: boolean; @@ -119,7 +120,20 @@ export function AgentProviderConnection({ (savedKeys.subscriptions.length > 0 || (adapterType === "claude_local" && !savedSubscription && storedLogin.data)) ? "subscription" : savedKeys.options.length ? "api" : "subscription" ); - const localLogin = useLocalAiLogin(companyId, managedAccount?.intent ?? { + const authMethod = method === "api" ? "api_key" : "subscription"; + // Reconnect preserves an account's method. Choosing another method creates + // an account for the same provider; the task host selects it after sign-in. + const reconnecting = managedAccount?.intent.connectionId && ( + managedAccount.fixedMethod !== false || managedAccount.initialMethod === authMethod + ); + const managedIntent: AiConnectionLoginIntent | undefined = managedAccount ? { + ...managedAccount.intent, + connectionId: reconnecting ? managedAccount.intent.connectionId : undefined, + name: reconnecting + ? managedAccount.intent.name + : managedAccount.nameForMethod?.(authMethod) ?? managedAccount.intent.name, + } : undefined; + const localLogin = useLocalAiLogin(companyId, managedIntent ?? { provider: aiProvider, method: "subscription", name: `My ${provider} subscription`, ownership: "personal", agentIds: [], allAgents: true, }, canUseLocalLogin && method === "subscription" && !savedSubscription && !storedLogin.data, @@ -145,11 +159,11 @@ export function AgentProviderConnection({ setBusy(true); setError(null); try { - if (managedAccount) { + if (managedAccount && managedIntent) { if (method === "subscription" && !canUseLocalLogin) return; const result = savedManagedAccount.current ?? await (method === "api" - ? aiConnectionsApi.create(companyId, { ...managedAccount.intent, method: "api_key", apiKey: apiKey.trim() }) - : localLogin.connect(managedAccount.intent)); + ? aiConnectionsApi.create(companyId, { ...managedIntent, method: "api_key", apiKey: apiKey.trim() }) + : localLogin.connect(managedIntent)); savedManagedAccount.current = result; setApiKey(""); if (run === epoch.current) managedAccount.onComplete({ ...result, method: method === "api" ? "api_key" : "subscription" }); @@ -231,13 +245,17 @@ export function AgentProviderConnection({ collapsed={opened} onSelect={() => { if (!managedAccount?.disabled) setOpened(true); }} /> - {!opened && !managedAccount?.fixedMethod && ( + {(!opened || managedAccount) && !managedAccount?.fixedMethod && (
{ + cancel(); + setOpened(opened); savedManagedAccount.current = null; setMethod(next); + setApiKey(""); + setStoredConnection(null); setError(null); }} /> @@ -315,7 +333,7 @@ export function AgentProviderConnection({ adapterType={adapterType} environmentId={environmentId} chrome="onboarding" - aiConnection={managedAccount?.intent ?? { provider: aiProvider, method: "subscription", name: `My ${provider} subscription`, ownership: "personal", agentIds: [], allAgents: true }} + aiConnection={managedIntent ?? { provider: aiProvider, method: "subscription", name: `My ${provider} subscription`, ownership: "personal", agentIds: [], allAgents: true }} autoStart onStored={() => {}} onPromptReady={(url) => { diff --git a/ui/src/components/task-chat/TaskChatCompactInteractionCard.tsx b/ui/src/components/task-chat/TaskChatCompactInteractionCard.tsx index c655bb299ec..6450f488c4a 100644 --- a/ui/src/components/task-chat/TaskChatCompactInteractionCard.tsx +++ b/ui/src/components/task-chat/TaskChatCompactInteractionCard.tsx @@ -1930,6 +1930,7 @@ export function TaskChatCompactInteractionCard({ interaction={interaction} currentUserId={currentUserId} addresseeLabel={addresseeLabel ?? "the addressed user"} + addresseeName={interaction.addresseeUserId ? userLabelMap?.get(interaction.addresseeUserId) : undefined} /> ); diff --git a/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsx b/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsx index 2687086f9c7..a8b0a741925 100644 --- a/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsx +++ b/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsx @@ -21,6 +21,22 @@ const setupOptionsMock = vi.hoisted(() => vi.fn()); const completeMock = vi.hoisted(() => vi.fn()); const declineMock = vi.hoisted(() => vi.fn()); const setPhaseMock = vi.hoisted(() => vi.fn()); +const getAgentMock = vi.hoisted(() => vi.fn()); +const updateAgentMock = vi.hoisted(() => vi.fn()); +const setDefaultMock = vi.hoisted(() => vi.fn()); +vi.mock("@/api/ai-connections", () => ({ aiConnectionsApi: { setDefault: (...args: unknown[]) => setDefaultMock(...args) } })); +const adoptMock = vi.hoisted(() => vi.fn()); +const installMock = vi.hoisted(() => vi.fn()); +vi.mock("@/api/tools", () => ({ toolsApi: { + getConnectionInstalls: async () => ({ installs: [] }), + putConnectionInstalls: (...args: unknown[]) => installMock(...args), +} })); + +vi.mock("@/api/agents", () => ({ agentsApi: { + adoptAiConnection: (...args: unknown[]) => adoptMock(...args), + get: (...args: unknown[]) => getAgentMock(...args), + update: (...args: unknown[]) => updateAgentMock(...args), +} })); vi.mock("@/api/connection-intents", () => ({ connectionIntentsApi: { @@ -32,8 +48,8 @@ vi.mock("@/api/connection-intents", () => ({ })); vi.mock("@/components/ai-connections/AiConnectionCredentialStep", () => ({ - AiConnectionCredentialStep: (props: { connectionId?: string; name: string; fixedMethod?: boolean; onComplete: (result: {connectionId: string; grantId: string; method: "api_key"}) => void; onCancel: () => void }) => { credentialRender(props); return
- {props.name}{String(props.fixedMethod)} + AiConnectionCredentialStep: (props: { connectionId?: string; name: string; hideName?: boolean; fixedMethod?: boolean; onComplete: (result: {connectionId: string; grantId: string; method: "api_key"}) => void; onCancel: () => void }) => { credentialRender(props); return
+ {!props.hideName && {props.name}}{String(props.fixedMethod)}
; }, @@ -159,6 +175,11 @@ function button(label: string) { } beforeEach(() => { + setDefaultMock.mockReset(); + getAgentMock.mockReset(); + updateAgentMock.mockReset(); + installMock.mockReset(); + adoptMock.mockReset(); setupOptionsMock.mockReset(); completeMock.mockReset(); declineMock.mockReset(); @@ -435,6 +456,24 @@ describe("ConnectionIntentInteractionBody dialog behavior", () => { describe("AI repair inside the card", () => { const interaction: ConnectionIntentInteraction = { ...pendingConnectionIntentInteraction, payload: { ...pendingConnectionIntentInteraction.payload, purpose: "ai" } }; const connection = { id: "selected-account", name: "My Codex account", provider: "openai", method: "api_key", ownership: "personal", ownerName: "Dotta", status: "revoked" }; + it.each([false, true])("requires atomic validated legacy adoption (validation fails: %s)", async (fails) => { + const binding = { provider: "openai", method: "subscription", mode: "responsible_user" }; + setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiConnection: binding, aiConnectionRequiresAdoption: true }); + if (fails) adoptMock.mockRejectedValue(new Error("Connection test failed")); + else adoptMock.mockResolvedValue({ ...interaction, status: "accepted" }); + renderBody(interaction); await flush(); + await act(() => button("Fix connection")!.click()); + await act(() => button("Reconnect selected account")!.click()); + expect(adoptMock).not.toHaveBeenCalled(); + expect(document.body.textContent).toContain("This replaces the agent’s existing authentication"); + await act(() => button("Use connection and continue")!.click()); + await flush(); + expect(adoptMock).toHaveBeenCalledWith(interaction.payload.requestingAgentId, interaction.id, "new-ai-account", interaction.companyId); + expect(updateAgentMock).not.toHaveBeenCalled(); + expect(installMock).not.toHaveBeenCalled(); + expect(completeMock).not.toHaveBeenCalled(); + if (fails) expect(document.querySelector('[role="alert"]')?.textContent).toContain("Connection test failed"); + }); it.each(["anthropic", "openai"])("connects a missing %s default directly in the task", async (provider) => { setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiConnection: { provider, method: "api_key", mode: "responsible_user" } }); completeMock.mockResolvedValue({ ...interaction, status: "accepted" }); @@ -443,7 +482,7 @@ describe("AI repair inside the card", () => { expect(document.querySelector('[role="dialog"]')).toBeNull(); expect(document.querySelector('[data-testid="shared-connection-setup"]')).toBeNull(); expect(document.querySelector('[data-testid="shared-ai-credentials"]')).not.toBeNull(); - expect(credentialRender.mock.lastCall![0]).toMatchObject({ provider, ownership: "personal", agentIds: [interaction.payload.requestingAgentId], allAgents: false }); + expect(credentialRender.mock.lastCall![0]).toMatchObject({ provider, hideName: true, ownership: "personal", agentIds: [interaction.payload.requestingAgentId], allAgents: false }); expect(credentialRender.mock.lastCall![0].connectionId).toBeUndefined(); expect(credentialRender.mock.lastCall![0].fixedMethod).toBeUndefined(); expect(document.body.textContent).toContain("This task can’t run until"); @@ -457,7 +496,8 @@ describe("AI repair inside the card", () => { await flush(); await act(() => button("Fix connection")!.click()); expect(document.querySelector('[role="dialog"]')).toBeNull(); - expect(document.querySelector('[data-testid="ai-connection-inline-repair"]')?.textContent).toContain("My Codex account"); + expect(document.querySelector('[data-testid="ai-connection-inline-repair"]')?.textContent).not.toContain("My Codex account"); + expect(credentialRender.mock.lastCall![0]).toMatchObject({ name: "My Codex account", hideName: true, fixedMethod: false, connectionId: "selected-account" }); await act(() => button("Cancel repair")!.click()); await waitForAssertion(() => expect(document.activeElement?.getAttribute("data-testid")).toBe("connection-intent-focus-target")); expect(completeMock).not.toHaveBeenCalled(); @@ -465,6 +505,51 @@ describe("AI repair inside the card", () => { await act(() => button("Reconnect selected account")!.click()); expect(completeMock).toHaveBeenCalledWith(interaction.id, "selected-account"); }); + it.each(["responsible_user", "delegated", "shared"] as const)("selects a different authentication method for a %s binding before resuming", async (mode) => { + const binding = { provider: "openai", method: "api_key", mode, ...(mode !== "responsible_user" ? { connectionId: connection.id, grantId: "old-grant" } : {}) }; + setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiConnection: binding, aiRepair: { connection: { ...connection, grantId: "old-grant" }, canReconnect: true } }); + getAgentMock.mockResolvedValue({ id: interaction.payload.requestingAgentId, runtimeConfig: { aiConnection: binding, heartbeat: { enabled: true } } }); + completeMock.mockResolvedValue({ ...interaction, status: "accepted" }); + renderBody(interaction); await flush(); + await act(() => button("Fix connection")!.click()); + await act(() => credentialRender.mock.lastCall![0].onComplete({ connectionId: "new-subscription", grantId: "new-grant", method: "subscription" })); + await flush(); + if (mode === "responsible_user") { + expect(setDefaultMock).toHaveBeenCalledWith(interaction.companyId, "new-grant"); + expect(updateAgentMock).not.toHaveBeenCalled(); + } else { + expect(updateAgentMock).toHaveBeenCalledWith(interaction.payload.requestingAgentId, { runtimeConfig: { heartbeat: { enabled: true }, aiConnection: { ...binding, method: "subscription", connectionId: "new-subscription", grantId: "new-grant" } } }, interaction.companyId); + expect(setDefaultMock).not.toHaveBeenCalled(); + } + expect(completeMock).toHaveBeenCalledWith(interaction.id, "new-subscription"); + }); + it("keeps a failed account switch pending and retries the saved account", async () => { + setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiConnection: { provider: "openai", method: "api_key", mode: "responsible_user" }, aiRepair: { connection, canReconnect: true } }); + setDefaultMock.mockRejectedValueOnce(new Error("Could not select this account")); + renderBody(interaction); await flush(); + await act(() => button("Fix connection")!.click()); + await act(() => credentialRender.mock.lastCall![0].onComplete({ connectionId: "new-subscription", grantId: "new-grant", method: "subscription" })); + await flush(); + expect(completeMock).not.toHaveBeenCalled(); + expect(document.querySelector('[role="alert"]')?.textContent).toContain("Could not select this account"); + await act(() => button("Retry using this connection")!.click()); + await flush(); + expect(completeMock).toHaveBeenCalledWith(interaction.id, "new-subscription"); + }); + it("clears an account-selection retry when its setup is abandoned", async () => { + setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiConnection: { provider: "openai", method: "api_key", mode: "responsible_user" }, aiRepair: { connection, canReconnect: true } }); + setDefaultMock.mockRejectedValueOnce(new Error("Could not select this account")); + renderBody(interaction); await flush(); + await act(() => button("Fix connection")!.click()); + await act(() => credentialRender.mock.lastCall![0].onComplete({ connectionId: "new-subscription", grantId: "new-grant", method: "subscription" })); + await flush(); + expect(button("Retry using this connection")).toBeDefined(); + await act(() => button("Cancel repair")!.click()); + await act(() => button("Fix connection")!.click()); + expect(button("Retry using this connection")).toBeUndefined(); + expect(document.querySelector('[role="alert"]')).toBeNull(); + expect(completeMock).not.toHaveBeenCalled(); + }); it("keeps a late credential save after cancellation from accepting the request", async () => { setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiRepair: { connection, canReconnect: true } }); renderBody(interaction); await flush(); diff --git a/ui/src/features/connections/ConnectionIntentInteractionBody.tsx b/ui/src/features/connections/ConnectionIntentInteractionBody.tsx index 91c214c3652..17010fd026d 100644 --- a/ui/src/features/connections/ConnectionIntentInteractionBody.tsx +++ b/ui/src/features/connections/ConnectionIntentInteractionBody.tsx @@ -8,10 +8,12 @@ import { RotateCcw, XCircle, } from "lucide-react"; -import type { ConnectionIntentInteraction } from "@paperclipai/shared"; +import type { AiAuthMethod, ConnectionIntentInteraction } from "@paperclipai/shared"; import { connectionIntentsApi } from "@/api/connection-intents"; +import { aiConnectionsApi } from "@/api/ai-connections"; +import { agentsApi } from "@/api/agents"; import { AiConnectionCredentialStep } from "@/components/ai-connections/AiConnectionCredentialStep"; -import { AI_PROVIDERS } from "@/components/ai-connections/model"; +import { defaultAiConnectionName } from "@/components/ai-connections/model"; import { AppLogo } from "@/pages/apps/AppLogo"; import { Button } from "@/components/ui/button"; import { @@ -32,6 +34,7 @@ export interface ConnectionIntentInteractionBodyProps { interaction: ConnectionIntentInteraction; currentUserId?: string | null; addresseeLabel: string; + addresseeName?: string; renderSetup?: (props: ConnectionSetupFlowProps) => ReactNode; } @@ -39,14 +42,17 @@ export function ConnectionIntentInteractionBody({ interaction, currentUserId, addresseeLabel, + addresseeName, renderSetup, }: ConnectionIntentInteractionBodyProps) { const [open, setOpen] = useState(false); + const [adoptionConnectionId, setAdoptionConnectionId] = useState(null); const focusTargetRef = useRef(null); const setupGeneration = useRef(0); const generation = setupGeneration.current; const closeSetup = () => { setupGeneration.current += 1; + selectAiAccountMutation.reset(); setOpen(false); }; const queryClient = useQueryClient(); @@ -122,6 +128,17 @@ export function ConnectionIntentInteractionBody({ returnFocusToCard(); }, }); + const adoptMutation = useMutation({ + mutationFn: (connectionId: string) => agentsApi.adoptAiConnection( + interaction.payload.requestingAgentId, interaction.id, connectionId, interaction.companyId, + ), + onSuccess: async (updatedInteraction) => { + await invalidateTask(updatedInteraction); + setAdoptionConnectionId(null); + setOpen(false); + returnFocusToCard(); + }, + }); const declineMutation = useMutation({ mutationFn: () => connectionIntentsApi.decline(interaction.id), onSuccess: async (updatedInteraction) => { @@ -158,9 +175,41 @@ export function ConnectionIntentInteractionBody({ returnFocusToCard(); return; } - completeMutation.mutate(completion.connectionId); + if (setupQuery.data?.aiConnectionRequiresAdoption) { + setAdoptionConnectionId(completion.connectionId); + } else { + completeMutation.mutate(completion.connectionId); + } }; + const selectAiAccountMutation = useMutation({ + mutationFn: async (result: { connectionId: string; grantId: string; method: AiAuthMethod; generation: number }) => { + if (result.generation !== setupGeneration.current) { + await setupQuery.refetch(); + return; + } + const binding = setupQuery.data?.aiConnection; + const previous = setupQuery.data?.aiRepair?.connection; + if (binding && previous && result.connectionId !== previous.id) { + if (binding.mode === "responsible_user") { + await aiConnectionsApi.setDefault(interaction.companyId, result.grantId); + } else { + const agent = await agentsApi.get(interaction.payload.requestingAgentId, interaction.companyId); + const current = agent.runtimeConfig.aiConnection; + if (!current || current.mode === "responsible_user" || current.connectionId !== previous.id || current.grantId !== previous.grantId) { + throw new Error("The agent’s AI connection changed. Reload the task and try again."); + } + if (result.generation !== setupGeneration.current) return; + await agentsApi.update(agent.id, { + runtimeConfig: { ...agent.runtimeConfig, aiConnection: { ...binding, method: result.method, connectionId: result.connectionId, grantId: result.grantId } }, + }, interaction.companyId); + } + await queryClient.invalidateQueries({ queryKey: ["ai-connections", interaction.companyId] }); + } + if (result.generation === setupGeneration.current) await finishNewConnection(result); + }, + }); + const setupProps: ConnectionSetupFlowProps | null = setupQuery.data ? { host: "dialog", upstreamServiceName: interaction.payload.upstreamService?.name, @@ -260,6 +309,9 @@ export function ConnectionIntentInteractionBody({ const repair = setupQuery.data?.aiRepair; const selectedReady = repair && setupQuery.data?.existingConnections.some((connection) => connection.id === repair.connection.id); + const readyForAdoption = setupQuery.data?.aiConnectionRequiresAdoption + ? adoptionConnectionId ?? (selectedReady ? repair.connection.id : null) + : null; const setupContent = setupQuery.isLoading ? (
Loading @@ -286,7 +338,17 @@ export function ConnectionIntentInteractionBody({ ) : setupProps ? ( renderSetup ? renderSetup(setupProps) : ) : null; + const aiConnection = setupQuery.data?.aiConnection; const inlineContent = setupQuery.isLoading || setupQuery.isError ? setupContent + : readyForAdoption ?
+

+ Use Connections for {interaction.payload.requestingAgentName}? This replaces the agent’s existing authentication + with the responsible person’s {interaction.payload.serviceName} connection. The model stays the same. +

+ +
: selectedReady ?

{repair.connection.name} is ready.

} - {isAi ? : @@ -406,20 +472,31 @@ export function ConnectionIntentInteractionBody({ {isAi && open ?
{inlineContent}
: null} {completeMutation.isError || + (selectAiAccountMutation.isError && selectAiAccountMutation.variables?.generation === generation) || + adoptMutation.isError || declineMutation.isError || phaseMutation.isError ? (

{(completeMutation.error ?? + selectAiAccountMutation.error ?? + adoptMutation.error ?? declineMutation.error ?? phaseMutation.error) instanceof Error ? ( completeMutation.error ?? + selectAiAccountMutation.error ?? + adoptMutation.error ?? declineMutation.error ?? phaseMutation.error )?.message : "Couldn’t update this connection request."}

) : null} + {selectAiAccountMutation.isError && selectAiAccountMutation.variables?.generation === generation && ( + + )}
);