From 137bd29531d99a1da7d82f03f27fa0fe2eb56c5e Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:01:19 -0600 Subject: [PATCH] fix(heartbeat): a provider usage-limit hold applies only to the account that reported it (#22800) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents run on an AI connection: a connected provider account (a connection grant), or the host's own account > - When a provider reports an exhausted allowance, Paperclip holds new work for that agent until the reported reset (`provider_limit_wait`), and schedules one recheck at the reset > - The hold was keyed by agent only. After a user connected a different, working account and the agent moved to it, every new run was still cancelled with the old account's reset time. A reply on the task did not recheck the wait. Only a manual "Check now" got work moving > - A usage limit belongs to the account that reported it. When that account is gone or replaced, the hold must be gone too, and waiting work must start without manual repair > - The banner's "Check now" button also failed here. It answered 409 "Issue has no scheduled monitor", because the button calls the issue-monitor route and this task has a scheduled retry, not a monitor > - This pull request scopes the hold to the credential, releases waiting work when the account changes or is revoked, makes a reply recheck the wait, and makes "Check now" recheck a waiting retry > - The benefit is that fixing the account fixes the task. The same account stays held, so an exhausted account is not called again ## Linked Issues or Issue Description No public issue exists. Bug report: **What happened?** An agent's connected provider account ran out of quota, with a reset about six days away. Paperclip held the agent's work ("Pool exhausted", runs cancelled with `provider_limit_wait`, one recheck scheduled 24 hours later). The user then connected a different, paid account. The old account became revoked, and the agent was moved to the new account. The agent's connection test passed. But every new run was still cancelled at once with the old account's reset time. A new comment on the task did not start a run, although the composer said "Sending a reply wakes the agent now". The task stayed in `todo`. Pressing "Check now" on the "Pool exhausted" banner did nothing: `POST /issues/:id/monitor/check-now` answered 409, because the task has no issue monitor (`triggerIssueMonitor` throws "Issue has no scheduled monitor"). **Expected behavior** A limit reported on account A must not hold a run that uses account B. When account A is revoked, removed or replaced on the agent, the hold stops. Work that waited on it starts promptly. While the agent still uses account A, the hold stays, with the plain message. A reply does what the composer says. **Steps to reproduce** 1. Bind an agent to connected account A. 2. Let a run fail with `quota_exhausted` and a reported reset days away. The next wake is cancelled with `provider_limit_wait`, and a recheck is scheduled about 24 hours later. 3. Connect account B and move the agent to it, or revoke account A. 4. Wake the agent on the task, or reply on the task. Before this change, the run is cancelled with `provider_limit_wait` again, and the reply does not recheck. ## What Changed - `server/src/services/native-runtime/native-startup-retry.ts`: limit evidence now comes only from runs on the checked credential. A run records its grant in `contextSnapshot.aiConnection.grantId`. A run with no recorded grant used the host's own account. Evidence from a revoked, expired or removed grant never applies. A later success on another account no longer clears this account's limit. New helpers resolve the credential of an agent's next run from its saved binding (`shared`/`delegated`: the bound grant; `responsible_user`: that user's default grants for the provider). - `server/src/services/heartbeat/provider-limit-wait.ts`: the pre-dispatch hold checks the agent's current credential, and records the limited grant on `providerLimitWait.grantId`. New `releaseProviderLimitWaits` makes waiting usage-limit retries due now, notifies retry dispatch in the same transaction, and logs `issue.scheduled_retry_retry_now` activity with `source: provider_limit_recheck`. The recheck goes through normal dispatch. It reads saved evidence only, so a still-limited account is held again with no provider work. - `server/src/services/agent-configuration.ts`: a change to an agent's `runtimeConfig.aiConnection` releases that agent's waits, in the same transaction as the change. - `server/src/services/tool-access/connections/grants.ts` and `removal.ts`: revoking or removing an account releases the waits whose limit was reported on it (after commit, best effort; the evidence rule alone already stops the hold). - `server/src/services/heartbeat/queue.ts`: a user's wake that is folded into a usage wait (comment or other user wake) rechecks it at once. Agent and system wakes keep the scheduled time, so they cannot loop. - `server/src/routes/issues.ts`: `POST /issues/:id/monitor/check-now` on a task with no monitor and a waiting scheduled retry now starts that retry (the same path as "retry now"). The retry rechecks availability before any work. It logs `issue.scheduled_retry_retry_now` with `source: monitor_check_now`. If the check cannot start, the 409 has a plain reason. Tasks with a monitor keep the old behavior. - `ui/src/components/IssueMonitorBanner.tsx`: for a usage wait, the composer now says "Sending a reply checks usage again now. The agent starts as soon as usage is available." The banner says work also resumes when the agent uses a different account. - Upgrade safety: holds are derived from saved run evidence, so old holds resolve by the new rule after deploy. A wait saved before this change has no `grantId`; the release finds its account from the run that reported the limit (`providerLimitWait.sourceRunId`). - `queue.ts` was already far above 1,000 lines. This change adds one small helper beside the two coalescing paths that need it, rather than a new module for one call. ## Verification - Red first: the new tests ran against the `origin/master` sources and 6 of them failed (hold on account A blocked a run on account B; revoked account still held; rebind and reply did not release the 24-hour retry; old-shape release missing). The shared-account test passed on master too, as intended: it guards that the hold stays. - Check now: a route test covers a `todo` task with no monitor and a waiting retry (200, the retry starts, the monitor path is not called, activity is logged) and a refused check (409 with a plain reason). An integration test covers the exact saved state: `todo` task, cancelled `provider_limit_wait` run, `scheduled_retry` successor, agent already moved to another account. "Check now" starts the retry, and it is not held again. - Green: `pnpm --filter @paperclipai/server exec vitest run src/__tests__/heartbeat-provider-limit-wait.test.ts src/services/native-runtime/native-provider-limit-cooldown.integration.test.ts src/services/native-runtime/native-startup-retry.integration.test.ts` passes (58 tests), and `src/__tests__/issue-execution-policy-routes.test.ts`. - UI: `ui/src/components/IssueMonitorBanner.test.tsx` passes (2 tests). - `npx tsc --noEmit -p server` passes. - `pnpm verify` exited 2 ("broader verification required"; its graph worker was killed under machine load). I ran the focused checks above and rely on required CI for broad coverage. - New tests cover: same account still held with the plain message; agent moved to another connected account starts; revoked account stops holding; rebind releases the pending retry and logs activity; a wait saved in the old shape is released when its account is revoked, and not when another account is revoked; two agents on one account both stay held when one agent moves away; a user reply rechecks at once and holds again (keeping the reply) while the account is still limited, and an agent's comment does not. - Not run live: I did not reproduce this on a running instance. I read the evidence from a local instance where the bug happened, and I did not change that instance. Live confirmation of the release after deploy is still to do. ## Risks - Behavior change: a limit no longer carries over to a different account. If two accounts share one provider-side quota, the agent can make one call on the new account before that account gets its own hold. - A `responsible_user` agent whose user has no saved default cannot resolve its account before the run. In that case only the revoked-grant rule applies, as before. - A user reply on a still-limited account makes one cancelled recheck run and a new scheduled wait. This is cheap (no workspace or provider work) and is bounded by the number of user replies. - No schema change and no new background worker. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, agentic coding with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- docs/api/issues.md | 16 + .../heartbeat-provider-limit-wait.test.ts | 396 +++++++++++++++++- .../issue-execution-policy-routes.test.ts | 31 ++ .../issue-scheduled-retry-routes.test.ts | 13 + server/src/routes/ai-connections.ts | 12 +- server/src/routes/issues.ts | 34 ++ server/src/services/agent-configuration.ts | 14 + server/src/services/ai-connections.ts | 6 + server/src/services/heartbeat.ts | 23 +- .../services/heartbeat/provider-limit-wait.ts | 185 +++++++- server/src/services/heartbeat/queue.ts | 25 +- ...rovider-limit-cooldown.integration.test.ts | 10 +- .../native-startup-retry.integration.test.ts | 2 +- .../native-runtime/native-startup-retry.ts | 115 ++++- .../tool-access/connections/grants.ts | 12 + .../tool-access/connections/removal.ts | 10 + ui/src/components/IssueMonitorBanner.test.tsx | 30 ++ ui/src/components/IssueMonitorBanner.tsx | 7 +- 18 files changed, 911 insertions(+), 30 deletions(-) create mode 100644 ui/src/components/IssueMonitorBanner.test.tsx diff --git a/docs/api/issues.md b/docs/api/issues.md index 54fca5809d1..e42533798a8 100644 --- a/docs/api/issues.md +++ b/docs/api/issues.md @@ -224,6 +224,22 @@ Saves a Retry request for the task's latest stopped run. The same `idempotencyKe Every answer includes `presentation`, the task's current interruption state. +## Check Now + +``` +POST /api/issues/{issueId}/monitor/check-now +``` + +Starts the task's next check now. This is the "Check now" button on the task banner. + +- When the task has a scheduled monitor, the monitor check starts. The answer is `200` with `{ "ok": true }`. +- When the task has no monitor but its run waits in a scheduled retry (for example, a wait for provider usage), the retry starts now. Before any work, the retry checks again whether the agent's current AI account has usage. If that account is still limited, the run waits again with a plain message. The caller must be a board user who can read the task and has `issue:mutate` access to it, the same access as Retry now. The answer is `200` with `{ "ok": true, "outcome": "promoted" | "already_promoted" | "waiting", "message": "..." }`. + +Refusals: + +- `403` or `404`: the caller cannot start work on this task. A private task that the caller cannot see answers `404`. +- `409` with `details.code: "issue_monitor_check_deferred"`: the check did not start. `error` gives the reason in plain words, for example that nothing waits to be checked anymore or that the task changed. Refresh the task. + ## Comments ### List Comments diff --git a/server/src/__tests__/heartbeat-provider-limit-wait.test.ts b/server/src/__tests__/heartbeat-provider-limit-wait.test.ts index 3a778c6003d..53a267155e8 100644 --- a/server/src/__tests__/heartbeat-provider-limit-wait.test.ts +++ b/server/src/__tests__/heartbeat-provider-limit-wait.test.ts @@ -4,18 +4,32 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { eq } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; -import { agents, authUsers, companies, companyMemberships, createDb, heartbeatRunEvents, heartbeatRuns, issues } from "@paperclipai/db"; +import { + activityLog, agents, authUsers, companies, companyMemberships, connectionGrants, createDb, heartbeatRunEvents, heartbeatRuns, issues, + aiProviderDefaults, toolApplications, toolConnectionInstalls, toolConnections, +} from "@paperclipai/db"; import { registerServerAdapter, unregisterServerAdapter } from "../adapters/index.js"; import { heartbeatService } from "../services/heartbeat.js"; -import { createProviderLimitWait } from "../services/heartbeat/provider-limit-wait.js"; +import { createProviderLimitWait, releaseProviderLimitWaits } from "../services/heartbeat/provider-limit-wait.js"; +import { agentService } from "../services/agents.js"; +import { aiConnectionService } from "../services/ai-connections.js"; +import { toolAccessService } from "../services/tool-access.js"; import { executionProjectionsForRuns } from "../services/execution-projection.js"; import { recoveryPostgresSupport, startRecoveryPostgres } from "./helpers/recovery-postgres.js"; const providerLimitCancellation = vi.hoisted(() => ({ after: null as null | (() => Promise) })); +const releaseFailure = vi.hoisted(() => ({ next: false })); vi.mock("../services/heartbeat/provider-limit-wait.js", async importOriginal => { const actual = await importOriginal(); return { ...actual, + releaseProviderLimitWaits: async (...args: Parameters) => { + if (releaseFailure.next) { + releaseFailure.next = false; + throw new Error("release step failed"); + } + return actual.releaseProviderLimitWaits(...args); + }, createProviderLimitWait: (...[database, deps]: Parameters) => actual.createProviderLimitWait(database, { ...deps, @@ -28,6 +42,18 @@ vi.mock("../services/heartbeat/provider-limit-wait.js", async importOriginal => }; }); +const retryDispatchNotice = vi.hoisted(() => ({ before: null as null | ((transaction: object) => Promise) })); +vi.mock("../services/run-dispatch-notifications.js", async importOriginal => { + const actual = await importOriginal(); + return { + ...actual, + notifyScheduledRetryDispatch: async (...args: Parameters) => { + await retryDispatchNotice.before?.(args[0]); + return actual.notifyScheduledRetryDispatch(...args); + }, + }; +}); + const describePostgres = recoveryPostgresSupport.supported ? describe : describe.skip; if (!recoveryPostgresSupport.supported) console.warn(`Skipping provider limit wait tests: ${recoveryPostgresSupport.reason}`); @@ -232,4 +258,370 @@ describePostgres("heartbeat provider usage limit wait", () => { retryability: "unknown", message: "ACP agent reported a terminal limit failure." } } }]); expect(dispatched.has((await wake(unrelated)).id)).toBe(true); }, 60_000); + + /** + * A usage limit belongs to the account it was reported on. Connecting a + * different account, or revoking the limited one, ends the hold; the same + * account stays held. + */ + describe("account-scoped holds", () => { + type Account = { connectionId: string; grantId: string }; + + async function accounts(companyId: string, count: number): Promise { + const [application] = await db.insert(toolApplications) + .values({ companyId, name: `AI accounts ${randomUUID()}`, type: "mcp_http" }).returning(); + const created: Account[] = []; + for (let index = 0; index < count; index += 1) { + const [connection] = await db.insert(toolConnections).values({ companyId, applicationId: application.id, uid: randomUUID(), + name: `AI account ${index}`, connectionPurpose: "ai", transport: "runtime_auth", authKind: "none" }).returning(); + const [grant] = await db.insert(connectionGrants).values({ companyId, connectionId: connection.id, kind: "organization" }).returning(); + created.push({ connectionId: connection.id, grantId: grant.id }); + } + return created; + } + + const binding = (account: Account) => ({ mode: "shared", provider: "google", method: "subscription", ...account }); + + /** A turn on `account` that the provider refused with a quota reset days away. */ + const quotaOn = (account: Account) => ({ + status: "failed", + startedAt: new Date(Date.now() - 7 * 60_000), + finishedAt: new Date(Date.now() - 5 * 60_000), + errorCode: "native_provider_usage_limit", + contextSnapshot: { aiConnection: { mode: "shared", provider: "google", method: "subscription", ...account } }, + resultJson: { providerFailure: { schema: "paperclip.provider-failure.v1", provider: "antigravity", phase: "turn", + category: "quota_exhausted", httpStatus: 429, providerCode: "RESOURCE_EXHAUSTED", retryability: "requires_action", + retryAt: new Date(Date.now() + 6 * 24 * 60 * 60_000).toISOString(), message: "Usage limit reached for this account." } }, + }); + + /** An agent bound to `bound`, whose earlier turn hit the quota on `limited`. */ + async function heldFixture(options: { count?: number } = {}) { + const f = await seed([]); + const list = await accounts(f.companyId, options.count ?? 2); + await db.update(agents).set({ runtimeConfig: { aiConnection: binding(list[0]) } }).where(eq(agents.id, f.agentId)); + await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, invocationSource: "automation", + triggerDetail: "system", ...quotaOn(list[0]) }); + return { ...f, accounts: list }; + } + + async function deferDirect(f: { companyId: string; agentId: string; issueId: string }, environment: { + early?: () => Promise<"host" | "managed" | null | "undecided">; dispatch?: "host" | "managed" | null; + } = {}) { + const [agent] = await db.select().from(agents).where(eq(agents.id, f.agentId)); + const [run] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running", + invocationSource: "automation", triggerDetail: "system", contextSnapshot: { issueId: f.issueId } }).returning(); + const deps = { + setRunStatusIfRunning: vi.fn(async () => ({ updated: true, run: { ...run, status: "cancelled" } })), + setWakeupStatus: vi.fn(async () => undefined), + appendRunEvent: vi.fn(async () => undefined), + scheduleBoundedRetryForRun: vi.fn(async () => ({ outcome: "scheduled" })), + releaseIssueExecutionAndPromote: vi.fn(async () => undefined), + finalizeAgentStatus: vi.fn(async () => undefined), + ...(environment.early ? { sshAuthentication: environment.early } : {}), + }; + const deferred = await createProviderLimitWait(db, deps as never) + .deferRunForProviderLimit(run, agent, { resumingAdmittedRun: false, conversation: false, + ...(environment.dispatch !== undefined ? { sshAuthentication: environment.dispatch } : {}) }); + return { deferred, deps }; + } + + async function scheduledRetry(agentId: string) { + const rows = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId)); + return rows.find(row => row.status === "scheduled_retry") ?? null; + } + + it("keeps holding the account that reported the limit, with the plain message", async () => { + const f = await heldFixture(); + const finished = await wake(f); + expect(dispatched.has(finished.id)).toBe(false); + expect(finished).toMatchObject({ status: "cancelled", errorCode: "provider_limit_wait", + resultJson: { providerLimitWait: { resetReported: true, category: "quota_exhausted", grantId: f.accounts[0].grantId } } }); + expect(finished.error).toMatch(/^This agent's provider usage limit has a reported reset at .+ Work is held/); + }, 60_000); + + it("starts a run whose agent now uses a different connected account", async () => { + const f = await heldFixture(); + await db.update(agents).set({ runtimeConfig: { aiConnection: binding(f.accounts[1]) } }).where(eq(agents.id, f.agentId)); + const { deferred, deps } = await deferDirect(f); + expect(deferred).toBe(false); + expect(deps.setRunStatusIfRunning).not.toHaveBeenCalled(); + }); + + it("follows the user's default account when the agent uses its responsible user's default", async () => { + const f = await seed([]); + const userId = `limit-user-${f.companyId}`; + const [application] = await db.insert(toolApplications) + .values({ companyId: f.companyId, name: `Personal AI ${randomUUID()}`, type: "mcp_http" }).returning(); + const personal: Account[] = []; + for (const name of ["Personal A", "Personal B"]) { + const [connection] = await db.insert(toolConnections).values({ companyId: f.companyId, applicationId: application.id, + uid: randomUUID(), name, connectionPurpose: "ai", transport: "runtime_auth", authKind: "none", enabled: true, + status: "active", healthStatus: "ok", config: { ai: { provider: "google", method: "subscription" }, aiIsolatedSubscription: true } }).returning(); + const [grant] = await db.insert(connectionGrants).values({ companyId: f.companyId, connectionId: connection.id, + kind: "user", subjectUserId: userId }).returning(); + await db.insert(toolConnectionInstalls).values({ companyId: f.companyId, connectionId: connection.id, + targetType: "company", targetId: f.companyId }); + personal.push({ connectionId: connection.id, grantId: grant.id }); + } + // The agent names no account; each run uses its responsible user's default. + await db.update(agents).set({ adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "antigravity" }, + runtimeConfig: { aiConnection: { mode: "responsible_user", provider: "google", method: "subscription" } } }) + .where(eq(agents.id, f.agentId)); + await db.insert(aiProviderDefaults).values({ companyId: f.companyId, userId, provider: "google", grantId: personal[0].grantId }); + await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, invocationSource: "automation", + triggerDetail: "system", ...quotaOn(personal[0]) }); + const deferAs = async () => { + const [agent] = await db.select().from(agents).where(eq(agents.id, f.agentId)); + const [run] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running", + invocationSource: "automation", triggerDetail: "system", responsibleUserId: userId, + contextSnapshot: { issueId: f.issueId } }).returning(); + return createProviderLimitWait(db, { + setRunStatusIfRunning: async () => ({ updated: true, run: { ...run, status: "cancelled" } }), + setWakeupStatus: async () => undefined, appendRunEvent: async () => undefined, + scheduleBoundedRetryForRun: async () => ({ outcome: "scheduled" }), + releaseIssueExecutionAndPromote: async () => undefined, finalizeAgentStatus: async () => undefined, + } as never).deferRunForProviderLimit(run, agent, { resumingAdmittedRun: false, conversation: false }); + }; + expect(await deferAs()).toBe(true); + // A task already waiting on account A, saved by an earlier hold. + const [wait] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "cancelled", + invocationSource: "automation", triggerDetail: "system", errorCode: "provider_limit_wait", + startedAt: new Date(Date.now() - 60_000), finishedAt: new Date(Date.now() - 60_000), + resultJson: { providerLimitWait: { grantId: personal[0].grantId } }, contextSnapshot: { issueId: f.issueId } }).returning(); + const [waiting] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "scheduled_retry", + invocationSource: "automation", triggerDetail: "system", retryOfRunId: wait.id, scheduledRetryAttempt: 1, + scheduledRetryReason: "ai_connection_pool_wait", scheduledRetryAt: new Date(Date.now() + 24 * 60 * 60_000), + contextSnapshot: { issueId: f.issueId } }).returning(); + + // The user picks account B as their default; the route then releases + // waits whose limit was on the previous default. + const { previousGrantId } = await aiConnectionService(db).setDefault(f.companyId, userId, personal[1].grantId); + expect(previousGrantId).toBe(personal[0].grantId); + expect(await deferAs()).toBe(false); + expect(await releaseProviderLimitWaits(db, { companyId: f.companyId, reason: "ai_connection_changed", + grantIds: [previousGrantId!] })).toEqual([waiting.id]); + const [released] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, waiting.id)); + expect(released.scheduledRetryAt!.getTime()).toBeLessThanOrEqual(Date.now()); + }); + + it("ignores a limit on an account that expired or needs a new sign-in", async () => { + for (const status of ["expired", "needs_reauthorization"] as const) { + const f = await heldFixture(); + await db.update(connectionGrants).set({ status }).where(eq(connectionGrants.id, f.accounts[0].grantId)); + expect((await deferDirect(f)).deferred).toBe(false); + } + }); + + it("keeps holding the bound account when another account later reports a billing refusal", async () => { + const f = await heldFixture(); + // Account B's newer refusal needs billing action and names no reset. + await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, invocationSource: "automation", + triggerDetail: "system", ...quotaOn(f.accounts[1]), startedAt: new Date(Date.now() - 2 * 60_000), finishedAt: new Date(Date.now() - 60_000), + resultJson: { providerFailure: { schema: "paperclip.provider-failure.v1", provider: "antigravity", phase: "turn", + category: "quota_exhausted", retryability: "requires_action", message: "Check your plan and billing details." } } }); + expect((await deferDirect(f)).deferred).toBe(true); + }); + + it("checks the host's own account when the harness signs in with a preconfigured home", async () => { + const f = await heldFixture(); + await db.update(agents).set({ adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "antigravity", homeMode: "preconfigured" } }) + .where(eq(agents.id, f.agentId)); + // The saved account's limit does not hold a run that will use the host sign-in. + expect((await deferDirect(f)).deferred).toBe(false); + await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, invocationSource: "automation", + triggerDetail: "system", ...quotaOn(f.accounts[0]), contextSnapshot: {} }); + // A limit reported on the host sign-in does. + expect((await deferDirect(f)).deferred).toBe(true); + }); + + it("checks a task's own environment only once dispatch knows which account it signs in with", async () => { + // Account A (the agent's binding) is limited; the host sign-in is not. + const f = await heldFixture(); + // Before preparation the task's environment is undecided, so nothing is held yet. + expect((await deferDirect(f, { early: async () => "undecided" })).deferred).toBe(false); + // A low-trust environment with managed credentials uses account A: held. + expect((await deferDirect(f, { dispatch: "managed" })).deferred).toBe(true); + // One that keeps the host's login does not use account A: not held. + expect((await deferDirect(f, { dispatch: "host" })).deferred).toBe(false); + }); + + it("holds a host limit when the task's environment keeps the host login, and not when it uses managed credentials", async () => { + const f = await heldFixture(); + await db.delete(heartbeatRuns).where(eq(heartbeatRuns.agentId, f.agentId)); + // Only the host sign-in is limited. + await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, invocationSource: "automation", + triggerDetail: "system", ...quotaOn(f.accounts[0]), contextSnapshot: {} }); + expect((await deferDirect(f, { dispatch: "host" })).deferred).toBe(true); + expect((await deferDirect(f, { dispatch: "managed" })).deferred).toBe(false); + }); + + it("clears a limit only after a success on the same account", async () => { + const f = await heldFixture(); + const succeededOn = (account: Account) => ({ status: "succeeded", startedAt: new Date(Date.now() - 2 * 60_000), + finishedAt: new Date(Date.now() - 60_000), contextSnapshot: { aiConnection: { grantId: account.grantId } } }); + await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, invocationSource: "automation", + triggerDetail: "system", ...succeededOn(f.accounts[1]) }); + expect((await deferDirect(f)).deferred).toBe(true); + await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, invocationSource: "automation", + triggerDetail: "system", ...succeededOn(f.accounts[0]) }); + expect((await deferDirect(f)).deferred).toBe(false); + }); + + it("stops holding work once the limited account is revoked", async () => { + const f = await heldFixture(); + expect((await deferDirect(f)).deferred).toBe(true); + await db.update(connectionGrants).set({ status: "revoked", revokedAt: new Date() }) + .where(eq(connectionGrants.id, f.accounts[0].grantId)); + expect((await deferDirect(f)).deferred).toBe(false); + }); + + it("releases the waiting retry when the agent is moved to another account", async () => { + const f = await heldFixture(); + const held = await wake(f); + expect(held.errorCode).toBe("provider_limit_wait"); + const retry = await scheduledRetry(f.agentId); + expect(retry!.scheduledRetryAt!.getTime()).toBeGreaterThan(Date.now() + 60 * 60_000); + + // Dispatch hears of the due retry before the write that makes it due. + const seenAtNotice: number[] = []; + retryDispatchNotice.before = async transaction => { + const [row] = await (transaction as typeof db).select({ at: heartbeatRuns.scheduledRetryAt }).from(heartbeatRuns) + .where(eq(heartbeatRuns.id, retry!.id)); + seenAtNotice.push(row!.at!.getTime()); + }; + try { + await agentService(db).update(f.agentId, { runtimeConfig: { aiConnection: binding(f.accounts[1]) } }); + } finally { + retryDispatchNotice.before = null; + } + expect(seenAtNotice).toEqual([retry!.scheduledRetryAt!.getTime()]); + const [released] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, retry!.id)); + expect(released.status).toBe("scheduled_retry"); + expect(released.scheduledRetryAt!.getTime()).toBeLessThanOrEqual(Date.now()); + expect((await heartbeat.promoteDueScheduledRetries(new Date())).runIds).toContain(retry!.id); + const activity = await db.select().from(activityLog).where(eq(activityLog.runId, retry!.id)); + expect(activity).toContainEqual(expect.objectContaining({ action: "issue.scheduled_retry_retry_now", entityId: f.issueId, + details: expect.objectContaining({ reason: "ai_connection_changed" }) })); + }, 60_000); + + it("releases a wait saved before the account was recorded on it when that account is revoked", async () => { + const f = await heldFixture(); + const held = await wake(f); + // Waits saved by the previous release name only the run that reported the limit. + const { grantId: _recorded, ...previousShape } = (held.resultJson as { providerLimitWait: Record }).providerLimitWait; + await db.update(heartbeatRuns).set({ resultJson: { ...held.resultJson, providerLimitWait: previousShape } }) + .where(eq(heartbeatRuns.id, held.id)); + const retry = await scheduledRetry(f.agentId); + + // Another account's revocation leaves the wait alone. + expect(await releaseProviderLimitWaits(db, { companyId: f.companyId, reason: "ai_connection_revoked", + grantIds: [f.accounts[1].grantId] })).toEqual([]); + await db.update(connectionGrants).set({ status: "revoked", revokedAt: new Date() }) + .where(eq(connectionGrants.id, f.accounts[0].grantId)); + expect(await releaseProviderLimitWaits(db, { companyId: f.companyId, reason: "ai_connection_revoked", + grantIds: [f.accounts[0].grantId] })).toEqual([retry!.id]); + expect((await heartbeat.promoteDueScheduledRetries(new Date())).runIds).toContain(retry!.id); + }, 60_000); + + it("commits a revocation and its release together, so a revoked account never leaves work waiting", async () => { + const f = await heldFixture(); + await wake(f); + const retry = await scheduledRetry(f.agentId); + const actor = { actorType: "user" as const, actorId: `limit-user-${f.companyId}` }; + const retryAt = async () => (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, retry!.id)))[0].scheduledRetryAt!.getTime(); + const grantStatus = async () => (await db.select().from(connectionGrants).where(eq(connectionGrants.id, f.accounts[0].grantId)))[0].status; + + // If the release fails, the revocation fails with it: never revoked with work still waiting. + releaseFailure.next = true; + await expect(toolAccessService(db).revokeConnectionGrant(f.accounts[0].connectionId, f.accounts[0].grantId, actor)) + .rejects.toThrow("release step failed"); + expect(await grantStatus()).toBe("active"); + expect(await retryAt()).toBe(retry!.scheduledRetryAt!.getTime()); + + // A committed revocation has already made the waiting work due. + await toolAccessService(db).revokeConnectionGrant(f.accounts[0].connectionId, f.accounts[0].grantId, actor); + expect(await grantStatus()).toBe("revoked"); + expect(await retryAt()).toBeLessThanOrEqual(Date.now()); + expect((await heartbeat.promoteDueScheduledRetries(new Date())).runIds).toContain(retry!.id); + }, 60_000); + + it("keeps holding every agent that still shares the limited account", async () => { + const first = await heldFixture(); + // Two agents in one company share account A; both reported its limit. + const sharedCompany = first.companyId; + const [secondAgent] = await db.insert(agents).values({ id: randomUUID(), companyId: sharedCompany, name: "Second shared agent", + adapterType, status: "idle", adapterConfig: {}, runtimeConfig: { aiConnection: binding(first.accounts[0]) } }).returning(); + const [secondIssue] = await db.insert(issues).values({ id: randomUUID(), companyId: sharedCompany, title: "Second task", + status: "todo", assigneeAgentId: secondAgent.id, issueNumber: 2 }).returning(); + await db.insert(heartbeatRuns).values({ companyId: sharedCompany, agentId: secondAgent.id, invocationSource: "automation", + triggerDetail: "system", ...quotaOn(first.accounts[0]) }); + const shared = { companyId: sharedCompany, agentId: secondAgent.id as typeof first.agentId, issueId: secondIssue.id as typeof first.issueId }; + expect((await wake(first)).errorCode).toBe("provider_limit_wait"); + expect((await wake(shared)).errorCode).toBe("provider_limit_wait"); + const sharedRetry = await scheduledRetry(secondAgent.id); + + // Moving one agent to account B leaves the other's account A hold intact. + await agentService(db).update(first.agentId, { runtimeConfig: { aiConnection: binding(first.accounts[1]) } }); + const [stillWaiting] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, sharedRetry!.id)); + expect(stillWaiting.scheduledRetryAt!.getTime()).toBe(sharedRetry!.scheduledRetryAt!.getTime()); + expect((await deferDirect(shared)).deferred).toBe(true); + }, 60_000); + + it("starts the waiting work on Check now once the agent already uses another account", async () => { + // The state saved before this fix: the task is todo, its run was held + // for account A, its recheck is a day away, and the agent was moved to + // account B without releasing the wait. + const f = await heldFixture(); + const held = await wake(f); + expect(held.errorCode).toBe("provider_limit_wait"); + const retry = await scheduledRetry(f.agentId); + await db.update(agents).set({ runtimeConfig: { aiConnection: binding(f.accounts[1]) } }).where(eq(agents.id, f.agentId)); + const [task] = await db.select().from(issues).where(eq(issues.id, f.issueId)); + expect(task).toMatchObject({ status: "todo", monitorNextCheckAt: null, executionRunId: retry!.id }); + + // "Check now" on this task starts its waiting retry. + const checked = await heartbeat.retryScheduledRetryNow({ issueId: f.issueId, actor: { actorType: "user", actorId: `limit-user-${f.companyId}` } }); + expect(checked.outcome).toBe("promoted"); + await heartbeat.resumeQueuedRuns(); + await heartbeat.drainActiveRunExecutions(); + const [started] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, retry!.id)); + // Account A's limit no longer holds the run. This fixture has no stored + // credential for account B, so the run goes on to that setup check. + expect(started.status).not.toBe("scheduled_retry"); + expect(started.errorCode).not.toBe("provider_limit_wait"); + const waits = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, retry!.id)); + expect(waits.filter(run => run.scheduledRetryReason === "ai_connection_pool_wait")).toEqual([]); + }, 60_000); + + it("rechecks the wait at once when the user replies, and holds again while the account is still limited", async () => { + const f = await heldFixture(); + await wake(f); + const retry = await scheduledRetry(f.agentId); + const userId = `limit-user-${f.companyId}`; + const commentId = randomUUID(); + + // Another agent's comment keeps the scheduled recheck. + await heartbeat.wakeup(f.agentId, { source: "automation", triggerDetail: "system", reason: "issue_commented", + payload: { issueId: f.issueId, commentId: randomUUID() }, requestedByActorType: "agent", requestedByActorId: randomUUID(), + contextSnapshot: { issueId: f.issueId, wakeReason: "issue_commented" } }); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, retry!.id)))[0].scheduledRetryAt!.getTime()) + .toBe(retry!.scheduledRetryAt!.getTime()); + + await heartbeat.wakeup(f.agentId, { source: "automation", triggerDetail: "system", reason: "issue_commented", + payload: { issueId: f.issueId, commentId }, requestedByActorType: "user", requestedByActorId: userId, + contextSnapshot: { issueId: f.issueId, commentId, wakeCommentId: commentId, wakeReason: "issue_commented" } }); + const [rechecking] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, retry!.id)); + expect(rechecking.scheduledRetryAt!.getTime()).toBeLessThanOrEqual(Date.now()); + expect((await heartbeat.promoteDueScheduledRetries(new Date())).runIds).toContain(retry!.id); + await heartbeat.resumeQueuedRuns(); + await heartbeat.drainActiveRunExecutions(); + + const [rechecked] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, retry!.id)); + expect(dispatched.has(retry!.id)).toBe(false); + expect(rechecked).toMatchObject({ status: "cancelled", errorCode: "provider_limit_wait" }); + const [successor] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, retry!.id)); + expect(successor).toMatchObject({ status: "scheduled_retry", scheduledRetryReason: "ai_connection_pool_wait" }); + expect(successor.contextSnapshot).toMatchObject({ wakeCommentId: commentId }); + }, 60_000); + }); }); diff --git a/server/src/__tests__/issue-execution-policy-routes.test.ts b/server/src/__tests__/issue-execution-policy-routes.test.ts index bda24c1dfee..c3fdac21a55 100644 --- a/server/src/__tests__/issue-execution-policy-routes.test.ts +++ b/server/src/__tests__/issue-execution-policy-routes.test.ts @@ -17,6 +17,7 @@ const mockIssueService = vi.hoisted(() => ({ getRelationSummaries: vi.fn(), listWakeableBlockedDependents: vi.fn(), getWakeableParentAfterChildCompletion: vi.fn(), + getCurrentScheduledRetry: vi.fn(async (): Promise<{ status: string } | null> => null), })); const mockHeartbeatService = vi.hoisted(() => ({ @@ -27,6 +28,8 @@ const mockHeartbeatService = vi.hoisted(() => ({ getActiveRunForAgent: vi.fn(async () => null), getQueuedAssignmentRunForIssue: vi.fn(async () => null), cancelRun: vi.fn(async () => null), + retryScheduledRetryNow: vi.fn(async (): Promise<{ outcome: string; message: string; scheduledRetry: null }> => + ({ outcome: "promoted", message: "Scheduled retry was promoted to the queued run pool", scheduledRetry: null })), })); const mockAccessService = vi.hoisted(() => ({ @@ -1214,6 +1217,34 @@ describe("issue execution policy routes", () => { ); }); + it("checks a waiting usage retry now when the task has no monitor", async () => { + // A todo task whose run waits for provider usage: no issue monitor, one scheduled retry. + mockIssueService.getById.mockResolvedValue({ + id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", companyId: "company-1", status: "todo", monitorNextCheckAt: null, + assigneeAgentId: "33333333-3333-4333-8333-333333333333", assigneeUserId: null, executionPolicy: null, executionState: null, + }); + mockIssueService.getCurrentScheduledRetry.mockResolvedValueOnce({ status: "scheduled_retry" }); + mockHeartbeatService.triggerIssueMonitor.mockClear(); + const res = await request(await createApp()) + .post("/api/issues/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/monitor/check-now").send({}); + expect(res.status).toBe(200); + expect(res.body).toMatchObject({ ok: true, outcome: "promoted" }); + expect(mockHeartbeatService.retryScheduledRetryNow).toHaveBeenCalledWith(expect.objectContaining({ + issueId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa" })); + expect(mockHeartbeatService.triggerIssueMonitor).not.toHaveBeenCalled(); + expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ + action: "issue.scheduled_retry_retry_now", details: expect.objectContaining({ source: "monitor_check_now" }) })); + + // A check that cannot start says why, in plain words. + mockIssueService.getCurrentScheduledRetry.mockResolvedValueOnce({ status: "scheduled_retry" }); + mockHeartbeatService.retryScheduledRetryNow.mockResolvedValueOnce({ outcome: "gate_suppressed", + message: "Scheduled retry suppressed because the agent no longer exists", scheduledRetry: null }); + const refused = await request(await createApp()) + .post("/api/issues/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/monitor/check-now").send({}); + expect(refused.status).toBe(409); + expect(refused.body.error).toBe("The check could not start because the task changed. Refresh the task to see its current state."); + }); + it.each(["execution_reconciliation_required", "monitor_dispatch_deferred", "monitor_replaced"])("does not claim success for a skipped monitor check: %s", async (reason) => { mockIssueService.getById.mockResolvedValue({ id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", companyId: "company-1", status: "blocked", diff --git a/server/src/__tests__/issue-scheduled-retry-routes.test.ts b/server/src/__tests__/issue-scheduled-retry-routes.test.ts index e052eba5b62..274acc9be1e 100644 --- a/server/src/__tests__/issue-scheduled-retry-routes.test.ts +++ b/server/src/__tests__/issue-scheduled-retry-routes.test.ts @@ -826,13 +826,26 @@ describeEmbeddedPostgres("issue scheduled retry routes", () => { const retry = await request(app).post(`/api/issues/${f.issueId}/retry`) .send({ idempotencyKey: randomUUID(), observedRunId: f.retryRunId }); const retryNow = await request(app).post(`/api/issues/${f.issueId}/scheduled-retry/retry-now`).send({}); + // The banner's Check now starts the same retry, so it needs the same access. + const checkNow = await request(app).post(`/api/issues/${f.issueId}/monitor/check-now`).send({}); expect(retry.status, JSON.stringify(retry.body)).toBe(404); expect(retryNow.status, JSON.stringify(retryNow.body)).toBe(404); + expect(checkNow.status, JSON.stringify(checkNow.body)).toBe(404); const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.retryRunId)); expect(run!.status).toBe("scheduled_retry"); }); + it("starts the waiting retry from Check now for a member who can see the task", async () => { + const f = await seedIssueWithRetry(); + const app = createApp(boardActor(f.companyId)); + const checkNow = await request(app).post(`/api/issues/${f.issueId}/monitor/check-now`).send({}); + expect(checkNow.status, JSON.stringify(checkNow.body)).toBe(200); + expect(checkNow.body).toMatchObject({ ok: true, outcome: "promoted" }); + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.retryRunId)); + expect(run!.status).toBe("queued"); + }); + it("promotes the existing scheduled retry and treats duplicate clicks as idempotent", async () => { const { companyId, issueId, retryRunId } = await seedIssueWithRetry(); const app = createApp(boardActor(companyId)); diff --git a/server/src/routes/ai-connections.ts b/server/src/routes/ai-connections.ts index 23203f7ad9f..43256c347b0 100644 --- a/server/src/routes/ai-connections.ts +++ b/server/src/routes/ai-connections.ts @@ -32,6 +32,8 @@ import { assertBoard, assertBoardOrAgent, assertCompanyAccess, getActorInfo } fr import { forbidden, notFound, unprocessable } from "../errors.js"; import { accessService } from "../services/access.js"; import { logActivity } from "../services/activity-log.js"; +import { logger } from "../middleware/logger.js"; +import { releaseProviderLimitWaits } from "../services/heartbeat/provider-limit-wait.js"; import { aiConnectionRouterService } from "../services/ai-connection-router.js"; import { aiConnectionService } from "../services/ai-connections.js"; import { validate } from "../middleware/validate.js"; @@ -383,7 +385,7 @@ export function aiConnectionRoutes(db: Db, options: Parameters logger.warn({ err, companyId }, "failed to release usage waits after a default change")); + } res.json({ ok: true }); }, ); diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 00d6b137e2a..efb826a66ca 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -14093,6 +14093,40 @@ export function issueRoutes( ); const actor = getActorInfo(req); + const waitingRetry = issue.monitorNextCheckAt + ? null + : await svc.getCurrentScheduledRetry?.(issue.id, { companyId: issue.companyId }); + if (waitingRetry?.status === "scheduled_retry") { + // The banner also shows "Check now" for a scheduled retry, such as a + // usage wait. With no monitor, the check is that retry: it starts now + // and rechecks availability before any work. It needs the same access + // as starting that retry directly. + assertBoard(req); + if (!(await assertIssueReadAllowed(req, res, issue))) return; + const decision = await decideIssueAccess(req, issue, "issue:mutate"); + if (!decision.allowed) throw forbidden(decision.explanation, authorizationDeniedDetails(decision)); + const retry = await heartbeat.retryScheduledRetryNow({ + issueId: issue.id, + actor: { actorType: actor.actorType, actorId: actor.actorId }, + }); + await logActivity(db, { + companyId: issue.companyId, actorType: actor.actorType, actorId: actor.actorId, + action: "issue.scheduled_retry_retry_now", entityType: "issue", entityId: issue.id, + agentId: retry.scheduledRetry?.agentId ?? issue.assigneeAgentId ?? null, + runId: retry.scheduledRetry?.runId ?? null, + details: { outcome: retry.outcome, message: retry.message, source: "monitor_check_now" }, + }); + if (retry.outcome === "no_scheduled_retry") { + throw conflict("Nothing is waiting to be checked on this task anymore. Refresh the task to see its current state.", + { code: "issue_monitor_check_deferred", reason: "no_scheduled_check" }); + } + if (retry.outcome === "gate_suppressed") { + throw conflict("The check could not start because the task changed. Refresh the task to see its current state.", + { code: "issue_monitor_check_deferred", reason: "gate_suppressed" }); + } + res.json({ ok: true, outcome: retry.outcome, message: retry.message }); + return; + } const result = await heartbeat.triggerIssueMonitor(issue.id, { actorType: actor.actorType, actorId: actor.actorId, diff --git a/server/src/services/agent-configuration.ts b/server/src/services/agent-configuration.ts index 7cda733a3d0..caaa776c708 100644 --- a/server/src/services/agent-configuration.ts +++ b/server/src/services/agent-configuration.ts @@ -25,6 +25,7 @@ import { secretService, assertClaudeOAuthBindingInvariant } from "./secrets.js"; import { agentCredentialService } from "./agent-credentials.js"; import { clearPrimaryAgent } from "./primary-agent.js"; import { budgetServiceInTransaction } from "./budgets.js"; +import { releaseProviderLimitWaits } from "./heartbeat/provider-limit-wait.js"; export async function lockAgentConfigurationInteractions(tx: Db, id: string, data: AgentConfigurationPatch, options?: UpdateAgentOptions) { const pluginOrigin = currentPluginInteractionOrigin(); @@ -193,6 +194,19 @@ export async function completeAgentConfiguration(txDb: Db, existing: AgentConfig ); } + const priorRuntime = isPlainRecord(existing.runtimeConfig) ? existing.runtimeConfig : {}; + const nextRuntime = isPlainRecord(updated.runtimeConfig) ? updated.runtimeConfig : {}; + if (!isDeepStrictEqual(priorRuntime.aiConnection, nextRuntime.aiConnection)) { + // A usage limit belongs to the account it was reported on. Work held for + // it rechecks now, against the account the agent uses from here on. + const actorAgentId = options?.recordRevision?.createdByAgentId; + const actorUserId = options?.recordRevision?.createdByUserId; + await releaseProviderLimitWaits(txDb, { + companyId: existing.companyId, agentId: id, reason: "ai_connection_changed", publications, + actor: actorAgentId ? { actorType: "agent", actorId: actorAgentId } : actorUserId ? { actorType: "user", actorId: actorUserId } : undefined, + }); + } + if (normalizedPatch.budgetMonthlyCents !== undefined) { await budgetServiceInTransaction(txDb, publications).upsertPolicy(existing.companyId, { scopeType: "agent", scopeId: id, amount: normalizedPatch.budgetMonthlyCents, diff --git a/server/src/services/ai-connections.ts b/server/src/services/ai-connections.ts index 58a199f2cc5..ca3d8713e00 100644 --- a/server/src/services/ai-connections.ts +++ b/server/src/services/ai-connections.ts @@ -181,6 +181,7 @@ export function aiConnectionService(db: Db) { userId: string, grantId: string, ) { + /** The grant that was the default before this change, if any. */ return db.transaction(async (tx) => { const [row] = await tx .select({ connection: toolConnections, grant: connectionGrants }) @@ -211,12 +212,17 @@ export function aiConnectionService(db: Db) { ); const metadata = aiConnectionMetadataSchema.parse(row.connection.config.ai); if (metadata.routing) throw unprocessable("Custom providers use an explicit connection selection on the agent."); + const [previous] = await tx.select({ grantId: aiProviderDefaults.grantId }).from(aiProviderDefaults).where(and( + eq(aiProviderDefaults.companyId, companyId), eq(aiProviderDefaults.userId, userId), + eq(aiProviderDefaults.provider, metadata.provider), + )); await tx.insert(aiProviderDefaults) .values({ companyId, userId, provider: metadata.provider, grantId }) .onConflictDoUpdate({ target: [aiProviderDefaults.companyId, aiProviderDefaults.userId, aiProviderDefaults.provider], set: { grantId, updatedAt: new Date() }, }); + return { previousGrantId: previous?.grantId ?? null }; }); } async function readableAccount(companyId: string, userId: string, connectionId: string, grantId?: string) { diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index af4ed40565d..e3a896d0cd1 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -1973,6 +1973,18 @@ export function heartbeatService( scheduleBoundedRetryForRun, releaseIssueExecutionAndPromote, finalizeAgentStatus, + // A task that names its own environment may run there as a low-trust + // review; only workspace preparation decides that, so dispatch checks then. + sshAuthentication: async (agent, run) => { + const issueId = readNonEmptyString(parseObject(run.contextSnapshot).issueId); + const [task] = issueId ? await db.select({ settings: issues.executionWorkspaceSettings }).from(issues) + .where(and(eq(issues.companyId, run.companyId), eq(issues.id, issueId))) : []; + if (parseIssueExecutionWorkspaceSettings(task?.settings, { includeEnvironmentId: true })?.environmentId) return "undecided"; + return resolveSshAuthenticationBeforeRouting({ + agentDefaultEnvironmentId: agent.defaultEnvironmentId, lowTrustIssueEnvironmentId: null, + environmentsSvc, instanceSettings, + }); + }, }); async function executeRunAttempt( @@ -2754,12 +2766,19 @@ export function heartbeatService( if ("homeMode" in homeConfig) config = { ...config, homeMode: homeConfig.homeMode }; } const persistedRouterPoolId = routerHasPersistedInput ? readNonEmptyString(parseObject(context.aiRouterSelection).poolId) : null; + const taskEnvironmentId = parseIssueExecutionWorkspaceSettings(issueContext?.executionWorkspaceSettings, { includeEnvironmentId: true })?.environmentId ?? null; const sshAuthentication = routerHasPersistedInput ? null : await resolveSshAuthenticationBeforeRouting({ agentDefaultEnvironmentId: agent.defaultEnvironmentId, - lowTrustIssueEnvironmentId: trustPreset.kind === "low_trust_review" - ? parseIssueExecutionWorkspaceSettings(issueContext?.executionWorkspaceSettings, { includeEnvironmentId: true })?.environmentId ?? null : null, + lowTrustIssueEnvironmentId: trustPreset.kind === "low_trust_review" ? taskEnvironmentId : null, environmentsSvc, instanceSettings, }); + // A task that names its own environment left the usage-limit check + // undecided before workspace preparation. Its account is known now. + if (taskEnvironmentId && !routerHasPersistedInput && await deferRunForProviderLimit(run, agent, { + resumingAdmittedRun: !!runOptions.nativeLeaseOwner, + conversation: isConversation(conversationIdentity), + sshAuthentication, + })) return; if (agent.adapterType === "paperclip_runner" && sshAuthentication) { config = { ...config, homeMode: sshAuthentication === "host" ? "preconfigured" : "isolated" }; } diff --git a/server/src/services/heartbeat/provider-limit-wait.ts b/server/src/services/heartbeat/provider-limit-wait.ts index 1d11df95ded..88b1be10b87 100644 --- a/server/src/services/heartbeat/provider-limit-wait.ts +++ b/server/src/services/heartbeat/provider-limit-wait.ts @@ -1,9 +1,18 @@ +import { and, eq, gt, inArray, sql } from "drizzle-orm"; +import { alias } from "drizzle-orm/pg-core"; import type { Db } from "@paperclipai/db"; import { agents, heartbeatRuns } from "@paperclipai/db"; import { logger } from "../../middleware/logger.js"; import { AI_CONNECTION_POOL_WAIT_RETRY_REASON } from "../../modules/run-dispatch/index.js"; -import { agentProviderLimitCooldown } from "../native-runtime/native-startup-retry.js"; +import { aiRuntimeConnectionBindingSchema } from "@paperclipai/shared"; +import { + agentHasProviderLimitEvidence, agentProviderLimitCooldown, runProviderLimitCredential, type ProviderLimitCredential, +} from "../native-runtime/native-startup-retry.js"; +import { aiConnectionService } from "../ai-connections.js"; import { parseObject } from "../../adapters/utils.js"; +import { logActivity, publishActivity } from "../activity-log.js"; +import { notifyScheduledRetryDispatch } from "../run-dispatch-notifications.js"; +import type { ActivityPublication } from "../../types/activity-publication.js"; type HeartbeatRun = typeof heartbeatRuns.$inferSelect; type Agent = typeof agents.$inferSelect; @@ -21,8 +30,17 @@ export interface ProviderLimitWaitDependencies { }) => Promise<{ outcome: string }>; releaseIssueExecutionAndPromote: (run: HeartbeatRun) => Promise; finalizeAgentStatus: (agentId: string, outcome: "cancelled") => Promise; + /** + * How the run's SSH environment signs the harness in, as run admission + * decides it, or "undecided" when only later preparation knows the + * environment (a low-trust task's own environment). + */ + sshAuthentication?: (agent: Agent, run: HeartbeatRun) => Promise; } +/** How an SSH environment signs the harness in; null when no SSH environment applies. */ +export type SshAuthentication = "host" | "managed" | null; + /** Holds new work while the agent's provider account is out of allowance. */ export function createProviderLimitWait(db: Db, deps: ProviderLimitWaitDependencies) { const { @@ -40,14 +58,31 @@ export function createProviderLimitWait(db: Db, deps: ProviderLimitWaitDependenc async function deferRunForProviderLimit( run: HeartbeatRun, agent: Agent, - options: { resumingAdmittedRun: boolean; conversation: boolean }, + options: { + resumingAdmittedRun: boolean; conversation: boolean; + /** Set once dispatch has chosen the run's environment. */ + sshAuthentication?: SshAuthentication; + }, ): Promise { if (options.resumingAdmittedRun || options.conversation) return false; if (run.invocationSource === "on_demand" && run.triggerDetail === "manual") return false; if (parseObject(parseObject(agent.runtimeConfig).aiConnection).mode === "router") return false; const now = new Date(); - const cooldown = await agentProviderLimitCooldown(db, { + // The limit belongs to the credential it was reported on. A run that would + // use another account, or whose limited account was revoked, is not held. + // Most agents have no live limit, so resolving the account waits for one. + const cooldown = await agentHasProviderLimitEvidence(db, { companyId: run.companyId, agentId: run.agentId, runId: run.id, now, + }).then(async limited => { + if (!limited) return null; + const ssh = options.sshAuthentication !== undefined ? options.sshAuthentication + : deps.sshAuthentication ? await deps.sshAuthentication(agent, run) : null; + // Dispatch checks again once the environment, and so the account, is known. + if (ssh === "undecided") return null; + return agentProviderLimitCooldown(db, { + companyId: run.companyId, agentId: run.agentId, runId: run.id, now, + credential: await agentProviderLimitCredential(db, agent, run.responsibleUserId, ssh), + }); }).catch((err: unknown) => { // Missing evidence must not stop work; the provider still reports its own limit. logger.warn({ err, runId: run.id }, "provider limit evidence unavailable before dispatch"); @@ -64,7 +99,7 @@ export function createProviderLimitWait(db: Db, deps: ProviderLimitWaitDependenc executionRecovery: { kind: "ai_connection_wait", providerWorkStarted: false }, providerLimitWait: { resetAt, resetReported: cooldown.resetReported, category: cooldown.category, - sourceRunId: cooldown.sourceRunId, actionUrl: `/agents/${agent.id}/runtime`, + sourceRunId: cooldown.sourceRunId, grantId: cooldown.grantId, actionUrl: `/agents/${agent.id}/runtime`, }, cancellation: { source: "control_plane", expected: true, initiator: { type: "system" }, @@ -115,3 +150,145 @@ export function createProviderLimitWait(db: Db, deps: ProviderLimitWaitDependenc return { deferRunForProviderLimit }; } + +/** + * The account the agent's next run would use, chosen by the same selection a + * run makes when it starts. + */ +async function agentProviderLimitCredential( + db: Db, agent: Agent, responsibleUserId: string | null, ssh: SshAuthentication, +): Promise { + const saved = parseObject(agent.runtimeConfig).aiConnection; + if (saved === undefined || saved === null) return { kind: "host" }; + // Run admission ignores the saved account when the harness uses the host's + // own sign-in: an SSH host that keeps its login, or a preconfigured home. + if (ssh === "host" || (ssh !== "managed" && agent.adapterType === "paperclip_runner" + && parseObject(agent.adapterConfig).homeMode === "preconfigured")) return { kind: "host" }; + const parsed = aiRuntimeConnectionBindingSchema.safeParse(saved); + if (!parsed.success || parsed.data.mode === "router") return { kind: "unresolved" }; + const binding = parsed.data; + const config = parseObject(agent.adapterConfig); + try { + const selection = await aiConnectionService(db).select({ + companyId: agent.companyId, agentId: agent.id, userId: responsibleUserId, adapterType: agent.adapterType, + model: config.model, runnerProvider: config.provider, acpxAgent: config.acpxAgent, binding, + }); + return { kind: "grants", grantIds: [selection.grant.id] }; + } catch { + // A run that cannot select an account fails on its own setup check. An + // explicit binding still names the account that check would use. + return binding.mode === "responsible_user" ? { kind: "unresolved" } : { kind: "grants", grantIds: [binding.grantId] }; + } +} + +export type ProviderLimitWaitRelease = + /** The agent's AI connection changed, so its next run may use another account. */ + | "ai_connection_changed" + /** An account was revoked or removed, so limits reported on it no longer apply. */ + | "ai_connection_revoked" + /** Someone replied on the task; the reply rechecks the wait now. */ + | "user_reply"; + +/** + * Makes waiting provider limit retries due now, so each rechecks availability + * through the normal dispatch path. The recheck reads only saved evidence and + * holds the run again, with no provider work, when the same account is still + * out of allowance. A user reply also rechecks a connection pool wait. + */ +export async function releaseProviderLimitWaits(db: Db, input: { + companyId: string; + reason: ProviderLimitWaitRelease; + agentId?: string; + /** A specific waiting retry. */ + runId?: string; + /** Only waits whose limit was reported on one of these grants. */ + grantIds?: readonly string[]; + actor?: { actorType: "user" | "agent" | "system" | "plugin"; actorId: string }; + publications?: ActivityPublication[]; + now?: Date; +}): Promise { + if (input.grantIds && input.grantIds.length === 0) return []; + const now = input.now ?? new Date(); + const waitRun = alias(heartbeatRuns, "provider_limit_wait_run"); + const candidates = await db + .select({ + id: heartbeatRuns.id, + agentId: heartbeatRuns.agentId, + issueId: sql`${heartbeatRuns.contextSnapshot} ->> 'issueId'`, + limitGrantId: sql`${waitRun.resultJson} #>> '{providerLimitWait,grantId}'`, + sourceRunId: sql`${waitRun.resultJson} #>> '{providerLimitWait,sourceRunId}'`, + }) + .from(heartbeatRuns) + .innerJoin(waitRun, and(eq(waitRun.id, heartbeatRuns.retryOfRunId), eq(waitRun.companyId, heartbeatRuns.companyId))) + .where(and( + eq(heartbeatRuns.companyId, input.companyId), + eq(heartbeatRuns.status, "scheduled_retry"), + eq(heartbeatRuns.scheduledRetryReason, AI_CONNECTION_POOL_WAIT_RETRY_REASON), + gt(heartbeatRuns.scheduledRetryAt, now), + ...(input.agentId ? [eq(heartbeatRuns.agentId, input.agentId)] : []), + ...(input.runId ? [eq(heartbeatRuns.id, input.runId)] : []), + // A pool wait rechecks only on a reply; an account change cannot free a pool. + input.reason === "user_reply" + ? inArray(waitRun.errorCode, ["provider_limit_wait", "ai_connection_pool_exhausted"]) + : eq(waitRun.errorCode, "provider_limit_wait"), + )); + let released = candidates; + if (input.grantIds) { + // Waits saved before the grant was recorded on them name their evidence run. + const sourceRunIds = candidates.flatMap(row => !row.limitGrantId && row.sourceRunId && UUID.test(row.sourceRunId) ? [row.sourceRunId] : []); + const sources = sourceRunIds.length === 0 ? [] : await db + .select({ id: heartbeatRuns.id, contextSnapshot: heartbeatRuns.contextSnapshot }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.companyId, input.companyId), inArray(heartbeatRuns.id, sourceRunIds))); + const sourceGrant = new Map(sources.map(source => { + const credential = runProviderLimitCredential(source.contextSnapshot); + return [source.id, credential.kind === "grants" ? credential.grantIds[0] : null] as const; + })); + released = candidates.filter(row => { + const grantId = row.limitGrantId ?? (row.sourceRunId ? sourceGrant.get(row.sourceRunId) : null); + return Boolean(grantId && input.grantIds!.includes(grantId)); + }); + } + if (released.length === 0) return []; + const recheck = { reason: input.reason, requestedAt: now.toISOString() }; + // Inside a caller's transaction its publications commit with it; otherwise + // this release publishes its own after its commit. + const publications = input.publications ?? []; + const releasedIds = await db.transaction(async tx => { + // Dispatch learns of the due retries before they are written, so drain and + // sleep account for them; the notice commits only with the write. + await notifyScheduledRetryDispatch(tx, { companyId: input.companyId }); + const updated = await tx.update(heartbeatRuns) + .set({ + scheduledRetryAt: now, + contextSnapshot: sql`coalesce(${heartbeatRuns.contextSnapshot}, '{}'::jsonb) || ${JSON.stringify({ scheduledRetryAt: now.toISOString(), providerLimitRecheck: recheck })}::jsonb`, + updatedAt: now, + }) + .where(and( + eq(heartbeatRuns.companyId, input.companyId), + inArray(heartbeatRuns.id, released.map(row => row.id)), + eq(heartbeatRuns.status, "scheduled_retry"), + gt(heartbeatRuns.scheduledRetryAt, now), + )) + .returning({ id: heartbeatRuns.id }); + if (updated.length === 0) return []; + const updatedIds = new Set(updated.map(row => row.id)); + for (const row of released.filter(candidate => updatedIds.has(candidate.id))) { + await logActivity(tx as unknown as Db, { + companyId: input.companyId, + actorType: input.actor?.actorType ?? "system", + actorId: input.actor?.actorId ?? "provider-limit-wait", + agentId: row.agentId, + runId: row.id, + action: "issue.scheduled_retry_retry_now", + entityType: row.issueId ? "issue" : "heartbeat_run", + entityId: row.issueId ?? row.id, + details: { source: "provider_limit_recheck", reason: input.reason }, + }, publications); + } + return [...updatedIds]; + }); + if (!input.publications) publications.forEach(publishActivity); + return releasedIds; +} + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts index 0c85d4f75b9..ca4d5e99111 100644 --- a/server/src/services/heartbeat/queue.ts +++ b/server/src/services/heartbeat/queue.ts @@ -191,7 +191,8 @@ import { WORKSPACE_WORKTREE_REQUIRES_PROJECT_REMEDIATION, } from "../execution-workspace-policy.js"; import { readContinuationAttempt } from "../recovery/index.js"; -import { allowsDependencyBlockedWake, extractWakeCommentIds, wakeChatConversationsConflict } from "../../modules/run-dispatch/index.js"; +import { AI_CONNECTION_POOL_WAIT_RETRY_REASON, allowsDependencyBlockedWake, extractWakeCommentIds, wakeChatConversationsConflict } from "../../modules/run-dispatch/index.js"; +import { releaseProviderLimitWaits } from "./provider-limit-wait.js"; import { dispatchForAgent, outsideAgentDispatch } from "../agent-start-lock.js"; import { AgentRunSlotsFull, assertAgentRunSlotFree } from "./run-slot-admission.js"; import { @@ -3508,6 +3509,22 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende } } + /** + * A user's wake folded into a usage wait rechecks it now instead of at its + * scheduled time. The recheck reads saved evidence only and holds the work + * again, without provider work, while the same account is still limited. + */ + const recheckUsageWaitOnReply = async (run: Run | null) => { + if (run?.status === "scheduled_retry" && run.scheduledRetryReason === AI_CONNECTION_POOL_WAIT_RETRY_REASON && + opts.requestedByActorType === "user") { + await releaseProviderLimitWaits(db, { + companyId: agent.companyId, runId: run.id, reason: "user_reply", + ...(opts.requestedByActorId ? { actor: { actorType: "user" as const, actorId: opts.requestedByActorId } } : {}), + }).catch((err: unknown) => logger.warn({ err, runId: run.id }, "failed to recheck a usage wait after a reply")); + } + return run; + }; + if (issueId) { const agentNameKey = normalizeAgentNameKey(agent.name); @@ -3515,7 +3532,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende const issueActivityPublications: ActivityPublication[] = []; const issuePostCommitActions: IssuePostCommitAction[] = []; - return wakeQueue.admitIssueWake( + return recheckUsageWaitOnReply(await wakeQueue.admitIssueWake( { companyId: agent.companyId, issueId, durableChatRequest: durableRequest }, async (tx, { lockedIssue, lockIssue, prepareRecovery }) => { if (executionWaitRequestId) { @@ -5049,7 +5066,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende attachSetupRequest: () => attachQueuedSetupRequest(agent), dispatch: () => startNextQueuedRunForAgent(agent.id), }, - ); + )); } if (durableRequest) throw new Error("chat_inbound_wakeup_binding_denied"); @@ -5143,7 +5160,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende runId: mergedRun.id, finishedAt: new Date(), }); - return mergedRun; + return recheckUsageWaitOnReply(mergedRun); } const queuedRunId = randomUUID(); diff --git a/server/src/services/native-runtime/native-provider-limit-cooldown.integration.test.ts b/server/src/services/native-runtime/native-provider-limit-cooldown.integration.test.ts index 020d115662f..a0de2a577a7 100644 --- a/server/src/services/native-runtime/native-provider-limit-cooldown.integration.test.ts +++ b/server/src/services/native-runtime/native-provider-limit-cooldown.integration.test.ts @@ -6,6 +6,8 @@ import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embed import { agentProviderLimitCooldown, planNativeStartupRetry } from "./native-startup-retry.js"; const HOUR_MS = 60 * 60_000; +/** These agents sign in with the host's own account. */ +const HOST = { kind: "host" } as const; const DAY_MS = 24 * HOUR_MS; /** Claude ACP wording for an exhausted weekly allowance, such as "resets Nov 10, 3pm (UTC)". */ @@ -71,7 +73,7 @@ describe("native provider limit cooldown", () => { it("holds an agent until a dated weekly-limit reset instead of the one-hour default", async () => { const resetAt = new Date(Math.ceil((Date.now() + 20 * HOUR_MS) / HOUR_MS) * HOUR_MS); const agentId = await limitedAgent(resetAt); - expect(await agentProviderLimitCooldown(db, { companyId, agentId, now: new Date() })) + expect(await agentProviderLimitCooldown(db, { companyId, agentId, credential: HOST, now: new Date() })) .toMatchObject({ resetAt, resetReported: true, category: "quota_exhausted" }); }); @@ -85,7 +87,7 @@ describe("native provider limit cooldown", () => { category: "quota_exhausted", providerCode: "insufficient_quota", message: "Check your plan and billing details.", retryability: "requires_action", } } }); - expect(await agentProviderLimitCooldown(db, { companyId, agentId, now: new Date() })).toBeNull(); + expect(await agentProviderLimitCooldown(db, { companyId, agentId, credential: HOST, now: new Date() })).toBeNull(); }); it("keeps the default cooldown for a rate limit without a reset", async () => { @@ -94,7 +96,7 @@ describe("native provider limit cooldown", () => { schema: "paperclip.provider-failure.v1", provider: "anthropic", phase: "startup", category: "rate_limit", message: "Try again later.", retryability: "unknown", } } }).where(eq(heartbeatRuns.agentId, agentId)); - expect(await agentProviderLimitCooldown(db, { companyId, agentId, now: new Date() })) + expect(await agentProviderLimitCooldown(db, { companyId, agentId, credential: HOST, now: new Date() })) .toMatchObject({ resetReported: false, category: "rate_limit" }); }); @@ -111,7 +113,7 @@ describe("native provider limit cooldown", () => { it("re-checks a dated reset days away within one day", async () => { const agentId = await limitedAgent(new Date(Math.ceil((Date.now() + 3 * DAY_MS) / HOUR_MS) * HOUR_MS)); const now = new Date(); - const cooldown = await agentProviderLimitCooldown(db, { companyId, agentId, now }); + const cooldown = await agentProviderLimitCooldown(db, { companyId, agentId, credential: HOST, now }); expect(cooldown).toMatchObject({ resetReported: true }); expect(cooldown!.resetAt.getTime()).toBe(now.getTime() + DAY_MS); }); diff --git a/server/src/services/native-runtime/native-startup-retry.integration.test.ts b/server/src/services/native-runtime/native-startup-retry.integration.test.ts index 56315052149..d5c79aad686 100644 --- a/server/src/services/native-runtime/native-startup-retry.integration.test.ts +++ b/server/src/services/native-runtime/native-startup-retry.integration.test.ts @@ -1039,7 +1039,7 @@ describe("native provider startup retry", () => { await failStartup(seeded, sessionOpenFailure()); const state = await read(seeded); expect(state.coordinator.failureDetail).toMatchObject({ providerCooldownAt: expected.toISOString() }); - expect(await agentProviderLimitCooldown(db, { companyId, agentId, now: new Date() })) + expect(await agentProviderLimitCooldown(db, { companyId, agentId, credential: { kind: "host" }, now: new Date() })) .toMatchObject({ resetAt: expected, resetReported: true }); }); diff --git a/server/src/services/native-runtime/native-startup-retry.ts b/server/src/services/native-runtime/native-startup-retry.ts index 1ce96c08656..627d33d049e 100644 --- a/server/src/services/native-runtime/native-startup-retry.ts +++ b/server/src/services/native-runtime/native-startup-retry.ts @@ -1,6 +1,6 @@ import { createHash } from "node:crypto"; import { and, desc, eq, gte, inArray, ne, or, sql } from "drizzle-orm"; -import { heartbeatRuns, type Db } from "@paperclipai/db"; +import { connectionGrants, heartbeatRuns, type Db } from "@paperclipai/db"; import { readProviderFailure, type ProviderFailure } from "@paperclipai/shared"; import { logger } from "../../middleware/logger.js"; import { infrastructureRetryDelayMs, PROVIDER_LIMIT_DEFAULT_COOLDOWN_MS } from "../system-recovery-state.js"; @@ -14,7 +14,7 @@ const PROVIDER_LIMIT_ERROR_CODES = ["native_provider_usage_limit", "provider_quo const NATIVE_PROVIDER_LIMIT_WINDOW_MS = 24 * 60 * 60_000; const LIMIT_EVIDENCE_ROWS = 20; -type ProviderLimitEvidence = { resetAt: number; resetReported: boolean; category: string; sourceRunId: string | null }; +type ProviderLimitEvidence = { resetAt: number; resetReported: boolean; category: string; sourceRunId: string | null; grantId?: string | null }; function limitEvidence(failure: ProviderFailure | null, observedAt: Date, sourceRunId: string | null): ProviderLimitEvidence | null { if (!failure || !PROVIDER_LIMIT_CATEGORIES.includes(failure.category)) return null; @@ -28,6 +28,74 @@ function limitEvidence(failure: ProviderFailure | null, observedAt: Date, source : { resetAt: observedAt.getTime() + PROVIDER_LIMIT_DEFAULT_COOLDOWN_MS, resetReported: false, category: failure.category, sourceRunId }; } +/** + * The AI credential a provider limit is checked against. A limit belongs to + * the credential it was reported on, so evidence from another credential, or + * from one that was revoked or removed, does not hold work. + */ +export type ProviderLimitCredential = + /** No managed AI connection: the harness signs in with the host's own account. */ + | { kind: "host" } + /** The managed connection grants the next run may use. */ + | { kind: "grants"; grantIds: readonly string[] } + /** A managed connection whose account is chosen only when the run starts. */ + | { kind: "unresolved" }; + +const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +/** The credential a run used, from the account it recorded when it started. */ +export function runProviderLimitCredential(contextSnapshot: unknown): ProviderLimitCredential { + const grantId = recordedGrantId(contextSnapshot); + return grantId ? { kind: "grants", grantIds: [grantId] } : { kind: "host" }; +} + +function recordedGrantId(contextSnapshot: unknown): string | null { + const snapshot = contextSnapshot && typeof contextSnapshot === "object" ? contextSnapshot as Record : {}; + const connection = snapshot.aiConnection && typeof snapshot.aiConnection === "object" + ? snapshot.aiConnection as Record : {}; + return typeof connection.grantId === "string" && UUID_PATTERN.test(connection.grantId) ? connection.grantId : null; +} + +/** + * Whether evidence recorded on `evidenceGrantId` (null: the host's account) + * still describes the credential the agent would use now. + */ +function evidenceApplies(evidenceGrantId: string | null, credential: ProviderLimitCredential, activeGrantIds: ReadonlySet) { + if (evidenceGrantId === null) return credential.kind === "host"; + if (!activeGrantIds.has(evidenceGrantId)) return false; + if (credential.kind === "grants") return credential.grantIds.includes(evidenceGrantId); + return credential.kind === "unresolved"; +} + +/** Narrows the evidence read to the checked credential, so other accounts never crowd it out. */ +function credentialEvidenceFilter(credential: ProviderLimitCredential) { + const recorded = sql`${heartbeatRuns.contextSnapshot} -> 'aiConnection' ->> 'grantId'`; + if (credential.kind === "host") return [sql`${recorded} is null`]; + if (credential.kind === "grants") return [inArray(recorded, [...credential.grantIds])]; + return []; +} + +/** + * Whether any recent run of the agent recorded a provider limit, on any + * account. Without one no account can be held, so callers skip resolving the + * account the next run would use. Never decides that a limit applies. + */ +export async function agentHasProviderLimitEvidence(db: Db, input: { + companyId: string; agentId: string; runId?: string; now: Date; +}): Promise { + const [row] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, input.companyId), + eq(heartbeatRuns.agentId, input.agentId), + gte(heartbeatRuns.startedAt, new Date(input.now.getTime() - NATIVE_PROVIDER_LIMIT_WINDOW_MS)), + ...(input.runId ? [ne(heartbeatRuns.id, input.runId)] : []), + or( + inArray(heartbeatRuns.errorCode, PROVIDER_LIMIT_ERROR_CODES), + inArray(sql`${heartbeatRuns.resultJson} #>> '{providerFailure,category}'`, PROVIDER_LIMIT_CATEGORIES), + ), + )).limit(1); + return Boolean(row); +} + export type AgentProviderLimitCooldown = { /** When the agent's provider allowance is expected to return. */ resetAt: Date; @@ -36,11 +104,15 @@ export type AgentProviderLimitCooldown = { category: string; /** The run whose failure recorded the latest reset. */ sourceRunId: string | null; + /** The connection grant the limit was reported on; null for the host's own account. */ + grantId: string | null; }; /** - * The latest known provider limit for this agent, from the current failure or - * from the agent's recent runs. A later successful run clears older evidence. + * The latest known provider limit for this agent's credential, from the + * current failure or from the agent's recent runs on that same credential. A + * later successful run on the credential clears older evidence. Evidence from + * another credential, or from a revoked or removed one, never applies. */ export async function agentProviderLimitCooldown(db: Db, input: { companyId: string; @@ -48,6 +120,8 @@ export async function agentProviderLimitCooldown(db: Db, input: { /** Excluded from the evidence; the caller supplies its own failure. */ runId?: string; failure?: ProviderFailure | null; + /** The credential being checked. The caller's failure was reported on it. */ + credential: ProviderLimitCredential; now: Date; }): Promise { if (isProviderQuotaActionRequired({ resultJson: { providerFailure: input.failure } }, input.now)) return null; @@ -61,6 +135,7 @@ export async function agentProviderLimitCooldown(db: Db, input: { observedAt: sql`coalesce(${heartbeatRuns.finishedAt}, ${heartbeatRuns.updatedAt})`.mapWith(heartbeatRuns.updatedAt), providerFailure: sql`${heartbeatRuns.resultJson} -> 'providerFailure'`, retryNotBefore: sql`${heartbeatRuns.resultJson} ->> 'retryNotBefore'`, + contextSnapshot: sql`jsonb_build_object('aiConnection', ${heartbeatRuns.contextSnapshot} -> 'aiConnection')`, }) .from(heartbeatRuns) .where(and( @@ -68,6 +143,7 @@ export async function agentProviderLimitCooldown(db: Db, input: { eq(heartbeatRuns.agentId, input.agentId), gte(heartbeatRuns.startedAt, new Date(now - NATIVE_PROVIDER_LIMIT_WINDOW_MS)), ...(input.runId ? [ne(heartbeatRuns.id, input.runId)] : []), + ...credentialEvidenceFilter(input.credential), or( eq(heartbeatRuns.status, "succeeded"), inArray(heartbeatRuns.errorCode, PROVIDER_LIMIT_ERROR_CODES), @@ -76,7 +152,16 @@ export async function agentProviderLimitCooldown(db: Db, input: { )) .orderBy(desc(sql`coalesce(${heartbeatRuns.finishedAt}, ${heartbeatRuns.updatedAt})`)) .limit(LIMIT_EVIDENCE_ROWS); + const recordedGrantIds = [...new Set(rows.flatMap(row => recordedGrantId(row.contextSnapshot) ?? []))]; + const activeGrantIds = new Set(recordedGrantIds.length === 0 ? [] : (await db + .select({ id: connectionGrants.id }).from(connectionGrants).where(and( + eq(connectionGrants.companyId, input.companyId), + inArray(connectionGrants.id, recordedGrantIds), + eq(connectionGrants.status, "active"), + ))).map(row => row.id)); for (const row of rows) { + // Another credential's outcome says nothing about this one. + if (!evidenceApplies(recordedGrantId(row.contextSnapshot), input.credential, activeGrantIds)) continue; // The provider accepted work after this point, so its allowance was restored. if (row.status === "succeeded") break; const failure = readProviderFailure(row.providerFailure); @@ -89,6 +174,7 @@ export async function agentProviderLimitCooldown(db: Db, input: { ? { resetAt: reset, resetReported: true, category: "quota_exhausted", sourceRunId: row.id } : { resetAt: row.observedAt.getTime() + PROVIDER_LIMIT_DEFAULT_COOLDOWN_MS, resetReported: false, category: "quota_exhausted", sourceRunId: row.id }; } + if (recorded) recorded.grantId = recordedGrantId(row.contextSnapshot); if (recorded && (!latest || recorded.resetAt > latest.resetAt)) latest = recorded; } if (!latest || latest.resetAt <= now) return null; @@ -97,6 +183,8 @@ export async function agentProviderLimitCooldown(db: Db, input: { resetReported: latest.resetReported, category: latest.category, sourceRunId: latest.sourceRunId, + grantId: latest.grantId !== undefined ? latest.grantId + : input.credential.kind === "grants" && input.credential.grantIds.length === 1 ? input.credential.grantIds[0] : null, }; } @@ -117,13 +205,18 @@ export async function planNativeStartupRetry(input: { return { nextAttemptAt: null, providerCooldownAt: null }; // Limit evidence only refines the schedule. A failed read must not stop the // failure from settling, so the retry falls back to plain backoff. - const providerCooldownAt = await agentProviderLimitCooldown(input.db, { - companyId: input.binding.companyId, - agentId: input.binding.agentId, - runId: input.binding.runId, - failure: input.failure, - now: input.now, - }).then((cooldown) => cooldown?.resetAt ?? null, (error: unknown) => { + const providerCooldownAt = await input.db + .select({ contextSnapshot: heartbeatRuns.contextSnapshot }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.companyId, input.binding.companyId), eq(heartbeatRuns.id, input.binding.runId))) + .then(([run]) => agentProviderLimitCooldown(input.db, { + companyId: input.binding.companyId, + agentId: input.binding.agentId, + runId: input.binding.runId, + failure: input.failure, + // The failure was reported on the account this run started with. + credential: runProviderLimitCredential(run?.contextSnapshot), + now: input.now, + })).then((cooldown) => cooldown?.resetAt ?? null, (error: unknown) => { logger.warn({ err: error, runId: input.binding.runId }, "native provider limit evidence unavailable"); return null; }); diff --git a/server/src/services/tool-access/connections/grants.ts b/server/src/services/tool-access/connections/grants.ts index c45625b06a3..b1e8828ab36 100644 --- a/server/src/services/tool-access/connections/grants.ts +++ b/server/src/services/tool-access/connections/grants.ts @@ -16,6 +16,9 @@ import type { ConnectionGrantRevocationResult } from "@paperclipai/shared"; import { vercelTokenRequest, type VercelConnectClient } from "../../vercel-connect.js"; import type { createConnectionCredentialValidation } from "./credential-validation.js"; +import { releaseProviderLimitWaits } from "../../heartbeat/provider-limit-wait.js"; +import { publishActivity } from "../../activity-log.js"; +import type { ActivityPublication } from "../../../types/activity-publication.js"; type GrantDependencies = { getConnectionRow(idOrUid: string, companyId?: string): Promise; assertSecretRefs: ReturnType; @@ -538,6 +541,7 @@ replaceConnectionGrantMembers: async ( } } } + const releasedWaitPublications: ActivityPublication[] = []; const grant = await db.transaction(async (tx) => { await notifyGitHubCredentialChange(tx, connection); const [lockedGrant] = await tx.select({ id: connectionGrants.id }).from(connectionGrants) @@ -595,6 +599,13 @@ replaceConnectionGrantMembers: async ( })), ); } + // Usage limits reported on this account no longer hold work. The release + // commits with the revocation, so waiting work never outlives it. + if (updated) await releaseProviderLimitWaits(tx as unknown as Db, { + companyId: connection.companyId, reason: "ai_connection_revoked", grantIds: [grantId], + publications: releasedWaitPublications, + ...(binding.actorType && binding.actorId ? { actor: { actorType: binding.actorType, actorId: binding.actorId } } : {}), + }); return updated; }); if (!grant) throw notFound("Connection grant not found"); @@ -609,6 +620,7 @@ replaceConnectionGrantMembers: async ( reasonCode: "grant_revoked", details: { grantId: grant.id, kind: grant.kind, providerRevocation }, }); + releasedWaitPublications.forEach(publishActivity); return { ...toConnectionGrant(grant), ...(providerAccess ? { providerAccess } : {}) }; } }; diff --git a/server/src/services/tool-access/connections/removal.ts b/server/src/services/tool-access/connections/removal.ts index f950801c4de..ebdb692bdec 100644 --- a/server/src/services/tool-access/connections/removal.ts +++ b/server/src/services/tool-access/connections/removal.ts @@ -21,6 +21,7 @@ import { connectionGrants, connectionTokenIssuances, companySecretBindings, comp import type { ToolConnectionRemovalResult, ToolConnectionRemovalSummary } from "@paperclipai/shared"; import { notFound } from "../../../errors.js"; import { logger } from "../../../middleware/logger.js"; +import { releaseProviderLimitWaits } from "../../heartbeat/provider-limit-wait.js"; import { forgetMcpHttpSessions } from "../../mcp-http.js"; import { secretService } from "../../secrets.js"; import { connectionSecretsUsedByOtherConsumers } from "../../connection-credentials.js"; @@ -312,6 +313,15 @@ async function removeConnection( ), ); } + // Usage limits reported on a removed account no longer hold work. This + // runs before any provider call and covers grants an earlier attempt + // already revoked, so a failed release fails the removal and its retry + // releases them. + await releaseProviderLimitWaits(db, { + companyId: connection.companyId, reason: "ai_connection_revoked", + grantIds: grantRows.map((row) => row.id), + ...(binding.actorType && binding.actorId ? { actor: { actorType: binding.actorType, actorId: binding.actorId } } : {}), + }); let externalCredentialCleanup: ToolConnectionRemovalSummary["externalCredentialCleanup"] = null; if ( diff --git a/ui/src/components/IssueMonitorBanner.test.tsx b/ui/src/components/IssueMonitorBanner.test.tsx new file mode 100644 index 00000000000..3074c002537 --- /dev/null +++ b/ui/src/components/IssueMonitorBanner.test.tsx @@ -0,0 +1,30 @@ +// @vitest-environment node +import { renderToStaticMarkup } from "react-dom/server"; +import { expect, it } from "vitest"; +import type { Issue } from "@paperclipai/shared"; +import { IssueMonitorComposerStrip } from "./IssueMonitorBanner"; + +function waitingIssue(scheduledRetryReason: string) { + return { + id: "issue-1", + status: "todo", + scheduledRetry: { + status: "scheduled_retry", + scheduledRetryAt: new Date(Date.now() + 24 * 60 * 60_000).toISOString(), + scheduledRetryAttempt: 1, + scheduledRetryReason, + }, + } as unknown as Issue; +} + +it("tells a user that a reply rechecks usage, not that it starts work outright", () => { + const markup = renderToStaticMarkup(); + expect(markup).toContain("Pool exhausted"); + expect(markup).toContain("Sending a reply checks usage again now."); + expect(markup).not.toContain("wakes the agent now"); +}); + +it("keeps the wake-now promise for an ordinary scheduled retry", () => { + const markup = renderToStaticMarkup(); + expect(markup).toContain("Sending a reply wakes the agent now"); +}); diff --git a/ui/src/components/IssueMonitorBanner.tsx b/ui/src/components/IssueMonitorBanner.tsx index 50575171494..ba30072750a 100644 --- a/ui/src/components/IssueMonitorBanner.tsx +++ b/ui/src/components/IssueMonitorBanner.tsx @@ -68,6 +68,8 @@ export interface MonitorSurfaceCopy { automaticChecksPaused?: boolean; checkUnavailable?: boolean; executionWait?: boolean; + /** Waiting for AI account usage; a reply rechecks usage instead of starting work outright. */ + usageWait?: boolean; } function capitalize(value: string): string { @@ -157,9 +159,10 @@ export function buildMonitorSurfaceCopy( return { bannerTitle: "Pool exhausted", stripTitle: "Pool exhausted", - bannerMeta: [`Usage recheck ${eta} · ${absolute} (your time)`, "Tasks with a selected account keep it while waiting. Work resumes when usage permits."], + bannerMeta: [`Usage recheck ${eta} · ${absolute} (your time)`, "Tasks with a selected account keep it while waiting. Work resumes when usage permits or the agent uses a different account."], stripMeta: [`Usage recheck ${eta} · ${absolute}`, "Tasks with a selected account keep it while waiting."], tone: "info", + usageWait: true, }; } @@ -374,6 +377,8 @@ export function IssueMonitorComposerStrip({ ? "Review on GitHub, then check status to have the agent verify the result." : copy.workspaceWait || copy.executionWait ? "You can keep sending instructions while the agent waits." + : copy.usageWait + ? "Sending a reply checks usage again now. The agent starts as soon as usage is available." : "Sending a reply wakes the agent now — before the scheduled check."}

) : null}