fix(ai-connections): reconnect typed auth failures and stop quota retry countdowns (#22692)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Runs preserve typed provider failures so recovery can select the
right next action.
> - Authentication repair still recognized only older run error codes.
Native typed authentication failures could miss the reconnect request.
> - A typed exhausted quota with no reset also produced an estimated
one-hour admission hold. Waiting cannot repair that account.
> - This pull request uses the existing reconnect and validated adoption
flow for authentication. It asks for billing and usage repair for typed
quota exhaustion without a reset.
> - Rate limits and provider-reported resets keep their existing
automatic waits. Account authority, saved-work checks, pauses, and
approvals keep their existing gates.

## Linked Issues or Issue Description

Refs #15110. That open PR classifies the legacy Claude monthly-spend
message. This change does not duplicate its adapter parsing or change
older untyped quota recovery.

Refs #21351. That open PR changes legacy Claude edge-error
classification and repeated-failure latching. This change consumes the
typed provider category and retains the existing credential-generation
checks.

**What happened?**

A failed run with `providerFailure.category: authentication` and a
generic native error code did not create its reconnect request. A typed
`quota_exhausted` failure without a reset produced an estimated provider
cooldown, although the account needed attention. Recovery's narrow
PostgreSQL result projection also omitted typed native provider
failures.

**Expected behavior**

Ask the responsible person to repair the selected account or explicitly
adopt a compatible managed connection. Ask for billing and usage repair
when an exhausted allowance has no reported reset. Continue to wait
automatically for transient rate limits and reported allowance resets.

**Steps to reproduce**

Use a failed native run with a typed OpenAI authentication error and a
generic native error code. The existing reconnect controller should
create one card. Use typed `quota_exhausted` evidence with no reset. The
task should offer account review and manual Retry, with no invented
reset or automatic provider retry.

## What Changed

- Recognize typed authentication failures and the reported
`provider_invalid_credentials` run code. Reuse the existing
controller-only reconnect request, account freshness checks, durable
continuation, and explicit legacy adoption.
- Retain typed provider failures in the bounded PostgreSQL recovery
projection.
- Refresh the reviewed SDK public-source pin for the changed shared
interruption type with the repository generator.
- Keep typed quota exhaustion without a reset out of provider cooldown,
bounded retry, and periodic quota-recovery paths. A newer billing
refusal supersedes older reset evidence. Classify a startup billing
refusal before the remote exit-confirmed retry branch, and prevent the
startup planner from falling back to plain backoff.
- Add the derived `provider_billing` task action, an account-review
link, and a matching Inbox label. Preserve saved-work recovery and
current user gates.
- Update the connection documentation for these recovery decisions.

## Verification

- Red: five server regressions failed on current master for typed
authentication, the invalid-credential code, a false quota cooldown, and
the missing billing action. The new task notice regression also failed
before the repair.
- Green: the first focused set passed 241 tests. The final
quota/retry/UI set passed 281 tests. The database-backed reconnect set
passed seven selected cases for Claude, OpenAI, method switching, and
explicit legacy adoption. Sets overlap; these counts are not additive.
- Database tests check current account attribution, refreshed credential
generations, bounded result projection, and preservation of reported
resets. A quota without a reset must not schedule a successor. Two
additional startup regressions failed before the startup repair. The
repaired startup suites pass all 45 integration cases and 11 focused
classification cases. They check a blocked task, billing presentation,
no retry deadline, no resumable claim, and preserved retries for rate
limits and reported resets.
- `pnpm check:token-gates` and `git diff --check` passed.
- The earlier [Runner support
failure](https://github.com/paperclipai/paperclip/actions/runs/45263306284/job/138003893674)
came from a stale reviewed SDK source pin. The same three SDK evidence
files failed locally on `cacdb81`. Regenerating the pin from that
committed tree made all 59 tests in those files pass. Only the shared
`execution-projection.ts` source hash changed; lock and runtime pins
remain unchanged.
- `pnpm build` and repository-wide `pnpm -r typecheck` passed for the
initial change. The authentication/recovery policy set also passed 99
tests. Server typecheck and build also passed for the startup repair at
`cacdb81c26988394e11f934d05531bcbb121c7a2`. The full local `pnpm
test:run` stopped in chat shard 4/6 with 15 failures: fourteen
file/database-open failures during `ENFILE` file-table exhaustion and
one retry polling timeout. The failed run also reported an unhandled
`ENFILE` error. All 40 selected chat cases, including those 15 failures,
passed in a fresh process on `06c14a8`. This does not qualify the full
local suite. The complete CI workflow passed on the final head, as
recorded below.
- Local environment: isolated macOS arm64 checkout and disposable
PostgreSQL fixtures. The branch was replayed onto master at
`32375d302fbc3a233531674aedefa273adee2d97`; that base change touches an
unrelated migration test.
- Live provider account repair and the original reported credential
failure remain unverified. A read-only operational trace confirmed
retained runner checkpoint versions, but the reported runtime string was
absent from retained onboarding and run logs as well as current Core and
available Cloud source refs. Its producer remains unidentified.

- [Trusted PR CI, attempt
2](https://github.com/paperclipai/paperclip/actions/runs/45265943006/attempts/2)
completed successfully on `06c14a8cbcf2480eb9d2841bebda3337d4248bd6`,
including typecheck, build, Runner, serialized server, general test, and
browser suites. The previously cancelled serialized suite passed on that
attempt. All 59 commit checks are terminal: 56 succeeded and three
conditional checks were skipped. The Snyk commit status also passed.
- Greptile completed on `06c14a8cbcf2480eb9d2841bebda3337d4248bd6` with
5/5 and no new findings. Both earlier review threads are resolved.

## Risks

- A typed exhausted allowance without a reported reset now requires
account repair. Older untyped quota errors retain their existing
recovery policy; #15110 remains separate.
- Authentication repair must follow the recorded account rather than
infer an account from a proxy driver's upstream name. Existing
generation checks must still protect newer credentials.
- No schema migration or provider replay authority is added. Existing
stored runs keep their data. The new task action is derived at read
time.
- Live recovery of the originally reported incident remains unverified;
the operational trace did not locate the reported runtime code.

## Model Used

OpenAI `gpt-6.1-sol`, through the Codex harness in T3 Code, with xhigh
reasoning effort, tool use, code editing, and test execution. The
harness does not expose the context-window size.

## 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
- [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 <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip authored and GitHub committed 2026-11-23 14:37:16 -08:00
1 parent 4b5b9b7807
commit 298026eadc
26 files changed
+272 -30

No files matched your search

+12 -1
View File
@@ -351,9 +351,20 @@ 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
a card retain their existing recovery path. Typed provider authentication failures
and the runtime's `provider_invalid_credentials` code enter this same repair path.
Managed repair follows the run's recorded account attribution, including proxy
accounts whose driver reports an upstream provider. Unmanaged adoption requires
a compatible provider. Tool permission errors and provider quota failures do not
request model authentication.
An exhausted provider allowance with typed `quota_exhausted` evidence and no
reported reset asks the user to review billing and usage, then retry. It does
not create an estimated cooldown or an automatic provider retry. The task links
to Apps to review the connected AI account. Rate limits without a reset retain
their default cooldown; allowance limits with a reported reset retain their
scheduled retry. Older untyped quota failures retain their existing recovery.
Pre-dispatch `configuration_incomplete` failures also show this card when every
missing binding is a personal `user_secret_ref` for the same compatible AI
provider. This includes a teammate who has no value for an onboarding
@@ -165,7 +165,7 @@ export interface TaskInterruptionPresentation {
nextRetryAt: string | null;
canRetry: boolean;
retryAction?: "move_forward";
userAction: "approval" | "question" | "reconnect" | "assign_agent" | "choose_model" | "resume" | "budget" | "project_access"
userAction: "approval" | "question" | "reconnect" | "provider_billing" | "assign_agent" | "choose_model" | "resume" | "budget" | "project_access"
/** Board confirms that a previous server, which can no longer report, stopped its workspace copyback. */
| "confirm_owner_stop"
/** Board confirms that a run whose server restarted before it recorded the agent's process has stopped. */
@@ -13,6 +13,34 @@ const failure = (missingBindings: unknown, reason = "secret_binding_missing") =>
});
describe("personal AI credential preflight recovery", () => {
it.each(["startup", "turn"])("routes a typed %s authentication failure through the persisted reconnect request", phase => {
const run = { errorCode: "native_session_interrupted", resultJson: { providerFailure: {
schema: "paperclip.provider-failure.v1", provider: "openai", phase,
category: "authentication", message: "Invalid API key", retryability: "requires_action",
} } };
expect(isAiAuthenticationRepairable(run)).toBe(true);
expect(aiBindingForAuthRecovery("paperclip_runner", { provider: "codex" }, run))
.toMatchObject({ provider: "openai" });
expect(aiBindingForAuthRecovery("claude_local", {}, run)).toBeUndefined();
expect(isAiAuthenticationBlocked({ ...run, livenessState: "failed" })).toBe(false);
expect(classifyRunLiveness({ ...run, runStatus: "failed", issue: null, authenticationRepairRequested: true }))
.toMatchObject({ livenessState: "blocked", nextAction: "Complete the connection request to continue this task" });
});
it.each(["quota_exhausted", "permission", "rate_limit"])("does not reconnect for typed %s failures", category => {
expect(isAiAuthenticationRepairable({ errorCode: "native_session_interrupted", resultJson: { providerFailure: {
schema: "paperclip.provider-failure.v1", provider: "openai", phase: "turn",
category, message: "Provider refused the request", retryability: "requires_action",
} } })).toBe(false);
});
it("does not offer model sign-in for sandbox authentication", () => {
expect(isAiAuthenticationRepairable({ resultJson: { providerFailure: {
schema: "paperclip.provider-failure.v1", provider: "sandbox", phase: "startup",
category: "authentication", message: "Sandbox credentials rejected", retryability: "requires_action",
} } })).toBe(false);
});
it.each(["user_secret_missing", "secret_inactive"])("offers Claude setup for %s without adopting another provider", errorCode => {
const run = failure([{ ...missingClaudeKey, errorCode }]);
expect(isAiAuthenticationRepairable(run)).toBe(true);
+16 -4
View File
@@ -1716,9 +1716,10 @@ console.log(JSON.stringify({ type: "result", subtype: "success", result: "hello"
});
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}`;
["anthropic", false, false], ["openai", false, false], ["anthropic", true, false], ["openai", true, false],
["anthropic", false, true], ["openai", false, true],
] as const)("turns a %s auth failure into one card and resumes after repair (switch method: %s, typed: %s)", async (provider, switchMethod, typed) => {
const userId = `auth-recovery-${provider}-${switchMethod}-${typed}`;
const id = randomUUID();
const issueId = randomUUID();
const runId = randomUUID();
@@ -1729,10 +1730,21 @@ console.log(JSON.stringify({ type: "result", subtype: "success", result: "hello"
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,
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId: id, status: "failed", errorCode: typed ? "native_session_interrupted" : "acpx_auth_required", responsibleUserId: userId,
...(typed ? { resultJson: { providerFailure: { schema: "paperclip.provider-failure.v1", provider, phase: "turn",
category: "authentication", message: "Invalid API key", retryability: "requires_action" } } } : {}),
contextSnapshot: { issueId, aiConnection: { ...runtime.attribution, identity: runtime.identity } } });
await runtime.cleanup();
const intents = connectionIntentService(db);
if (typed) {
const [failed] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
await db.update(heartbeatRuns).set({ contextSnapshot: { ...failed.contextSnapshot, aiConnection: {
...runtime.attribution, identity: runtime.identity, provider: provider === "openai" ? "anthropic" : "openai",
} } }).where(eq(heartbeatRuns.id, runId));
expect(await intents.requestForRunAuthFailure(runId)).toBeNull();
expect((await db.select().from(connectionGrants).where(eq(connectionGrants.id, account.grantId)))[0].status).toBe("active");
await db.update(heartbeatRuns).set({ contextSnapshot: failed.contextSnapshot }).where(eq(heartbeatRuns.id, runId));
}
const card = await intents.requestForRunAuthFailure(runId);
expect(card).toMatchObject({ state: "needs_user_action", service: provider });
expect((await intents.requestForRunAuthFailure(runId))?.interactionId).toBe(card!.interactionId);
+1 -1
View File
@@ -3,7 +3,7 @@ import { aiConnectionMetadataSchema, aiRoutingHarness, isAiConnectionCompatible
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) => {
it.each(["acpx_auth_required", "claude_auth_required", "codex_auth_required", "grok_auth_required", "adapter_auth_missing", "provider_invalid_credentials", "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) => {
+20 -4
View File
@@ -1,4 +1,4 @@
import { AI_PROVIDERS, AI_CONNECTION_CAPABILITIES, isAiConnectionCompatible, type AiConnectionBinding, type AiProvider } from "@paperclipai/shared";
import { AI_PROVIDERS, AI_CONNECTION_CAPABILITIES, isAiConnectionCompatible, readProviderFailure, type AiConnectionBinding, type AiProvider } from "@paperclipai/shared";
type AuthenticationFailure = {
errorCode?: string | null;
@@ -39,15 +39,29 @@ export function isAiConnectionConfigurationFailure(run: AuthenticationFailure):
);
}
export function isAiAuthenticationRepairable(run: AuthenticationFailure): boolean {
return isAiAuthenticationFailure(run.errorCode) || isAiConnectionConfigurationFailure(run);
/** Driver names that identify the same account as the Connections provider. */
const AUTHENTICATION_PROVIDERS = new Map<string, AiProvider>([
["claude", "anthropic"], ["codex", "openai"], ["grok", "xai"],
["gemini", "google"], ["antigravity", "google"], ["copilot", "github"],
]);
function authenticationProvider(run: AuthenticationFailure): AiProvider | undefined {
const failure = readProviderFailure(record(run.resultJson)?.providerFailure);
if (failure?.category !== "authentication") return undefined;
return AI_PROVIDERS.find(provider => provider === failure.provider) ?? AUTHENTICATION_PROVIDERS.get(failure.provider);
}
export function isAiAuthenticationRepairable(run: AuthenticationFailure, provider?: AiProvider): boolean {
const failedProvider = authenticationProvider(run);
if (provider && failedProvider && provider !== failedProvider) return false;
return Boolean(failedProvider) || isAiAuthenticationFailure(run.errorCode) || isAiConnectionConfigurationFailure(run);
}
/** 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|copilot)_auth_required$/i.test(code)
|| ["adapter_auth_missing", "authentication_required", "auth_required", "refresh_token_reused", "refresh_token_expired", "refresh_token_invalidated"].includes(code)
|| ["adapter_auth_missing", "provider_invalid_credentials", "authentication_required", "auth_required", "refresh_token_reused", "refresh_token_expired", "refresh_token_invalidated"].includes(code)
));
}
@@ -63,8 +77,10 @@ export function aiBindingForAuthRecovery(
): AiConnectionBinding | undefined {
if (failure?.errorCode === "configuration_incomplete" && !isAiConnectionConfigurationFailure(failure)) return undefined;
const missingProvider = failure ? missingPersonalAiCredentialProvider(failure) : undefined;
const failedProvider = failure ? authenticationProvider(failure) : undefined;
for (const provider of AI_PROVIDERS) {
if (missingProvider && missingProvider !== provider) continue;
if (failedProvider && failedProvider !== provider) continue;
for (const method of ["subscription", "api_key"] as const) {
if (!AI_CONNECTION_CAPABILITIES[provider].methods[method]) continue;
// Recovery presents a concrete sign-in method. A responsible-user binding
+5 -2
View File
@@ -13,7 +13,7 @@ import { isDeepStrictEqual } from "node:util";
import { logActivity } from "./activity-log.js";
import { aiConnectionService } from "./ai-connections.js";
import { aiConnectionBindingSchema, aiConnectionCatalogSlug, aiConnectionRouterBindingSchema, aiConnectionSourceSlug } from "@paperclipai/shared";
import { aiBindingForAuthRecovery, isAiAuthenticationFailure, isAiAuthenticationRepairable } from "./ai-auth-failure.js";
import { aiBindingForAuthRecovery, isAiAuthenticationRepairable } from "./ai-auth-failure.js";
import { and, eq, desc, isNull, notInArray, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
@@ -343,7 +343,7 @@ export function connectionIntentService(db: Db) {
const [source] = await client.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.agentId, agentId), eq(heartbeatRuns.id, options.sourceRunId)));
const taskKey = text(source?.contextSnapshot?.aiRouterTaskKey);
const evidence = record(source?.contextSnapshot?.aiRouterSelection);
if (!source || !isAiAuthenticationFailure(source.errorCode) || source.status !== "failed" || evidence?.poolId !== router.connectionId || !taskKey) return null;
if (!source || !isAiAuthenticationRepairable(source) || source.status !== "failed" || evidence?.poolId !== router.connectionId || !taskKey) return null;
const [pin] = await client.select().from(aiConnectionTaskPins).where(and(eq(aiConnectionTaskPins.companyId, companyId), eq(aiConnectionTaskPins.poolId, router.connectionId), eq(aiConnectionTaskPins.agentId, agentId), eq(aiConnectionTaskPins.taskKey, taskKey)));
const binding = pin?.selection.binding;
if (!pin || !binding || !aiBindingMatchesService(binding.provider, serviceSlug) || JSON.stringify(evidence.binding) !== JSON.stringify(binding)) return null;
@@ -1537,6 +1537,9 @@ export function connectionIntentService(db: Db) {
const binding = router ? managed?.binding : saved ?? aiBindingForAuthRecovery(agent.adapterType, agent.adapterConfig, run);
if (!binding) return null;
const attribution = record(run.contextSnapshot?.aiConnection);
// The recorded account is authoritative for routed/proxy connections:
// a driver's provider name can identify the upstream protocol instead.
if (!attribution && !isAiAuthenticationRepairable(run, binding.provider)) return null;
if (attribution && attribution.provider !== binding.provider) return null;
if ((saved || managed) && 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,
@@ -86,6 +86,18 @@ describe("heartbeat retry module callbacks", () => {
for (const callback of Object.values(deps.runDispatch)) expect(callback).not.toHaveBeenCalled();
});
it("does not schedule provider work for a quota that needs account repair", async () => {
const database = guardedDatabase();
const deps = callbacks();
const run = { ...unitRun(), errorCode: "provider_quota", resultJson: { errorFamily: "provider_quota",
providerFailure: { schema: "paperclip.provider-failure.v1", provider: "openai", phase: "turn",
category: "quota_exhausted", message: "Check billing", retryability: "requires_action" } } } as Run;
const result = await extracted.createHeartbeatRetries(database.db, deps).scheduleBoundedRetryForRun(run, {} as Agent);
expect(result).toMatchObject({ outcome: "not_scheduled", issueId: "issue" });
expect(database.access).not.toHaveBeenCalled();
expect(deps.appendRunEvent).not.toHaveBeenCalled();
});
it.each(["missing_run", "missing_agent"] as const)("keeps %s lookup behavior and requests the full source result", async (outcome) => {
const database = guardedDatabase();
const deps = callbacks();
+4
View File
@@ -9,6 +9,7 @@ import { notifyStatusCardIssueChange } from "../status-card-notifications.js";
import { notifyScheduledRetryDispatch } from "../run-dispatch-notifications.js";
import { deriveTaskKeyWithHeartbeatFallback } from "./run-state.js";
import { infrastructureRetryDelayMs } from "../system-recovery-state.js";
import { isProviderQuotaActionRequired } from "../provider-quota-reset.js";
import {
WORKSPACE_VALIDATION_FAILURE_CODE,
isWorkspaceValidationFailedRun,
@@ -510,6 +511,9 @@ export function createHeartbeatRetries(db: Db, dependencies: HeartbeatRetryDepen
preserveWakeContext?: boolean;
},
) {
if (isProviderQuotaActionRequired(run, opts?.now)) return { outcome: "not_scheduled" as const,
reason: "Review the provider account's billing and usage allowance before retrying.",
issueId: readNonEmptyString(run.contextSnapshot?.issueId) };
const preparation = parseObject(run.resultJson?.executionRecovery);
if (typeof preparation.preparationSettledAt === "string" && await isInterruptedNativePreparation(db, run)) {
const children = await db.select().from(heartbeatRuns).where(and(
@@ -1,8 +1,9 @@
import { randomUUID } from "node:crypto";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { agents, companies, createDb, heartbeatRuns } from "@paperclipai/db";
import { eq } from "drizzle-orm";
import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
import { agentProviderLimitCooldown } from "./native-startup-retry.js";
import { agentProviderLimitCooldown, planNativeStartupRetry } from "./native-startup-retry.js";
const HOUR_MS = 60 * 60_000;
const DAY_MS = 24 * HOUR_MS;
@@ -74,6 +75,39 @@ describe("native provider limit cooldown", () => {
.toMatchObject({ resetAt, resetReported: true, category: "quota_exhausted" });
});
it("does not invent a reset for an account quota that needs billing action", async () => {
const agentId = await limitedAgent(new Date(Date.now() + HOUR_MS));
const [prior] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId));
// A prior weekly reset must not resurrect a wait after a newer billing refusal.
await db.insert(heartbeatRuns).values({ ...prior, id: randomUUID(), startedAt: new Date(), finishedAt: new Date(),
resultJson: { providerFailure: {
schema: "paperclip.provider-failure.v1", provider: "openai", phase: "turn",
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();
});
it("keeps the default cooldown for a rate limit without a reset", async () => {
const agentId = await limitedAgent(new Date(Date.now() + HOUR_MS));
await db.update(heartbeatRuns).set({ resultJson: { providerFailure: {
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() }))
.toMatchObject({ resetReported: false, category: "rate_limit" });
});
it("never plans a startup retry for a billing refusal even when the caller allows retries", async () => {
const agentId = await limitedAgent(new Date(Date.now() + HOUR_MS));
const plan = await planNativeStartupRetry({ db, binding: { companyId, agentId, runId: randomUUID() },
attempt: 1, retryable: true, now: new Date(), failure: {
schema: "paperclip.provider-failure.v1", provider: "openai", phase: "startup",
category: "quota_exhausted", message: "Check your billing details.", retryability: "requires_action",
} });
expect(plan).toEqual({ nextAttemptAt: null, providerCooldownAt: null });
});
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();
@@ -16056,6 +16056,16 @@ describe("native session bounded recovery", () => {
});
});
it.each([false, true])("stops a billing refusal on its first attempt even with a confirmed runner exit (remote: %s)", remote => {
const failure = Object.defineProperty(sessionOpenFailure(startupFailure({
category: "quota_exhausted", retryability: "requires_action", message: "Check billing and usage.",
})), "runnerExitConfirmed", { value: true });
const code = nativeSessionFailureSourceCode(failure);
expect(nativeRemoteStartupRejectionCode(code, failure, remote)).toBe(NATIVE_PROVIDER_STARTUP_REJECTED);
expect(nativeSessionFailureDisposition(1, new Date(), code))
.toMatchObject({ phase: "terminal_failure", nextAttemptAt: null });
});
it("keeps bounded same-run retries for a local startup failure without a definite permanent cause", () => {
for (const fields of [
{},
@@ -16063,7 +16073,8 @@ describe("native session bounded recovery", () => {
{ category: "overloaded", retryability: "transient", httpStatus: 503 },
{ category: "timeout", retryability: "transient", httpStatus: 504 },
{ category: "rate_limit", httpStatus: 429 },
{ category: "quota_exhausted", retryability: "requires_action", providerCode: "usageLimitExceeded" },
{ category: "quota_exhausted", retryability: "requires_action", providerCode: "usageLimitExceeded",
retryAt: new Date(Date.now() + 60_000).toISOString() },
{ category: "model_unavailable", retryability: "requires_action" },
{ phase: "turn", category: "authentication", retryability: "requires_action" },
]) {
@@ -16139,7 +16150,8 @@ describe("native session bounded recovery", () => {
...fields });
const confirmed = (fields: Record<string, unknown>) =>
Object.defineProperty(sessionOpenFailure(limit(fields)), "runnerExitConfirmed", { value: true, enumerable: false });
for (const fields of [{ category: "rate_limit" }, { category: "quota_exhausted", retryability: "requires_action" }]) {
for (const fields of [{ category: "rate_limit" }, { category: "quota_exhausted", retryability: "requires_action",
retryAt: new Date(Date.now() + 60_000).toISOString() }]) {
const first = confirmed(fields);
expect(nativeSessionFailureSourceCode(first)).toBe("provider_session_open_rejected");
// The first refusal still retries the same run after the cooldown.
@@ -19,6 +19,7 @@ import { NATIVE_CLEANUP_SETTLING_MESSAGE, NATIVE_COMPLETED_TURN_CLEANUP_MESSAGE,
import { prepareCursorCloudRuntime } from "./cursor-cloud-runtime.js";
import { LocalRuntimeApiListenerClosedError, resolveLocalRuntimeApiUrl } from "../../runtime-api.js";
import { providerFailureFromError } from "../../vendor/paperclip-runner/index.js";
import { isProviderQuotaActionRequired } from "../provider-quota-reset.js";
import { readProviderFailure } from "@paperclipai/shared";
import { nativeCancellationHasUnsettledOwner, notifyNativeCancellation, waitForNativeCancellation } from "./native-cancellation-delivery.js";
import { readClaimedNativeStopRecovery } from "./native-cancellation-request.js";
@@ -9163,8 +9164,10 @@ export const NATIVE_PROVIDER_STARTUP_REJECTED_ACTION =
function deterministicProviderStartupFailure(error: unknown): boolean {
const failure = providerFailureFromError(error);
return failure?.phase === "startup" && failure.retryability === "requires_action"
&& ["authentication", "permission", "invalid_request"].includes(failure.category);
return failure?.phase === "startup" && (
isProviderQuotaActionRequired({ resultJson: { providerFailure: failure } })
|| failure.retryability === "requires_action" && ["authentication", "permission", "invalid_request"].includes(failure.category)
);
}
/** The Runner transport proved the failed runner settled and its process exited. */
@@ -9214,9 +9217,9 @@ export function nativeStartupFailureSignature(failure: unknown): string | null {
* startup error. Otherwise it ends at once with Retry. A deterministic
* rejection never reaches here: it is already NATIVE_PROVIDER_STARTUP_REJECTED.
*
* An exhausted provider allowance (a rate limit or quota) ends as a usage-limit
* hold instead: it passes by itself, so the hold retries the task at the reset
* like a limit reported on a turn, rather than waiting for a person's Retry.
* A rate limit or an allowance with a reported reset can end as a usage-limit
* hold, which retries the task at the reset like a limit reported on a turn.
* A quota with no reset is already classified as an action-required refusal.
*/
export function nativeRemoteStartupRejectionCode<Code extends string>(
sourceFailureCode: Code,
@@ -41,6 +41,7 @@ import { environmentRunnerIngressErrorData, JsonRpcCallError, PluginEnvironmentR
import { accountRunCost } from "../run-cost-accounting.js";
import { settleUnrecoverableExecutions } from "../execution-recovery-resolution.js";
import { agentProviderLimitCooldown } from "./native-startup-retry.js";
import { projectTaskInterruption } from "../task-interruption-presentation.js";
import { resolveLocalRuntimeApiUrl, runtimeApiInternals } from "../../runtime-api.js";
type SessionOpenStatus = "failed" | "rejected" | "indeterminate";
@@ -901,6 +902,24 @@ describe("native provider startup retry", () => {
})).toEqual([]);
});
it("settles a startup billing refusal without scheduling another provider attempt", async () => {
const seeded = await seedRun(await createAgent());
const failure = Object.defineProperty(sessionOpenFailure({ providerFailure: limitFailure({
phase: "startup", category: "quota_exhausted", retryability: "requires_action",
message: "Check your plan and billing details.",
}) }), "runnerExitConfirmed", { value: true });
await failStartup(seeded, failure);
const state = await read(seeded);
expect(state.coordinator).toMatchObject({ phase: "terminal_failure", recoveryState: "blocked", nextAttemptAt: null });
expect(state.run.status).toBe("failed");
expect(state.issue).toMatchObject({ status: "blocked", executionRunId: null });
expect(projectTaskInterruption(state.issue, { run: state.run, action: state.action ?? undefined,
agent: { status: "idle", pauseReason: null }, paused: false, approval: false }))
.toMatchObject({ state: "waiting_for_user", userAction: "provider_billing", nextRetryAt: null });
expect(await claimNativeSessionResumptions({ db, runnerInstanceId: "startup-retry-test", runIds: [seeded.runId],
now: new Date(Date.now() + 10 * 60_000), deferIneligible: false })).toEqual([]);
});
it("waits for the cooldown of a recent provider usage limit before retrying", async () => {
const agentId = await createAgent();
const limitedAt = new Date(Date.now() - 5 * 60_000);
@@ -4,7 +4,7 @@ import { 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";
import { parseProviderQuotaClockReset } from "../provider-quota-reset.js";
import { isProviderQuotaActionRequired, parseProviderQuotaClockReset } from "../provider-quota-reset.js";
/** Categories that report an exhausted account or request allowance. */
const PROVIDER_LIMIT_CATEGORIES = ["rate_limit", "quota_exhausted"];
@@ -18,6 +18,7 @@ type ProviderLimitEvidence = { resetAt: number; resetReported: boolean; category
function limitEvidence(failure: ProviderFailure | null, observedAt: Date, sourceRunId: string | null): ProviderLimitEvidence | null {
if (!failure || !PROVIDER_LIMIT_CATEGORIES.includes(failure.category)) return null;
if (isProviderQuotaActionRequired({ resultJson: { providerFailure: failure } }, observedAt)) return null;
const retryAt = failure.retryAt ? Date.parse(failure.retryAt) : Number.NaN;
if (Number.isFinite(retryAt)) return { resetAt: retryAt, resetReported: true, category: failure.category, sourceRunId };
// ACP harnesses report the reset only in the provider's own wording.
@@ -49,6 +50,7 @@ export async function agentProviderLimitCooldown(db: Db, input: {
failure?: ProviderFailure | null;
now: Date;
}): Promise<AgentProviderLimitCooldown | null> {
if (isProviderQuotaActionRequired({ resultJson: { providerFailure: input.failure } }, input.now)) return null;
const now = input.now.getTime();
let latest = limitEvidence(input.failure ?? null, input.now, input.runId ?? null);
const rows = await db
@@ -77,7 +79,10 @@ export async function agentProviderLimitCooldown(db: Db, input: {
for (const row of rows) {
// The provider accepted work after this point, so its allowance was restored.
if (row.status === "succeeded") break;
let recorded = limitEvidence(readProviderFailure(row.providerFailure), row.observedAt, row.id);
const failure = readProviderFailure(row.providerFailure);
// A newer billing refusal supersedes an older estimate or reported reset.
if (isProviderQuotaActionRequired({ resultJson: { providerFailure: failure } }, row.observedAt)) break;
let recorded = limitEvidence(failure, row.observedAt, row.id);
if (recorded === null && PROVIDER_LIMIT_ERROR_CODES.includes(row.errorCode ?? "")) {
const reset = row.retryNotBefore ? Date.parse(row.retryNotBefore) : Number.NaN;
recorded = Number.isFinite(reset)
@@ -108,6 +113,8 @@ export async function planNativeStartupRetry(input: {
failure: ProviderFailure | null;
now: Date;
}): Promise<{ nextAttemptAt: Date | null; providerCooldownAt: Date | null }> {
if (isProviderQuotaActionRequired({ resultJson: { providerFailure: input.failure } }, input.now))
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, {
@@ -1,5 +1,20 @@
import { describe, expect, it } from "vitest";
import { parseProviderQuotaClockReset } from "./provider-quota-reset.js";
import { isProviderQuotaActionRequired, parseProviderQuotaClockReset } from "./provider-quota-reset.js";
describe("provider account action", () => {
const failure = { schema: "paperclip.provider-failure.v1", provider: "openai", phase: "turn",
category: "quota_exhausted", message: "Check billing and usage.", retryability: "requires_action" };
it("requires account repair for typed quota exhaustion even if an old recovery estimated a retry", () => {
expect(isProviderQuotaActionRequired({ resultJson: { providerFailure: failure, retryNotBefore: "2099-01-01T00:00:00Z" } })).toBe(true);
});
it.each([
{ ...failure, category: "authentication" }, { ...failure, category: "rate_limit" },
{ ...failure, message: "You've hit your weekly limit · resets Nov 12, 6pm (UTC)" },
{ ...failure, retryAt: "2026-11-12T18:00:00.000Z" }, { ...failure, schema: "invalid" }, undefined,
])("preserves other recovery and reported resets for %j", providerFailure => {
expect(isProviderQuotaActionRequired({ resultJson: { providerFailure } }, new Date("2026-11-10T20:00:00Z"))).toBe(false);
});
});
describe("parseProviderQuotaClockReset", () => {
it("reads a weekly limit's calendar reset, as Claude's ACP agent reports it", () => {
@@ -1,3 +1,14 @@
import { readProviderFailure } from "@paperclipai/shared";
/** An exhausted account with no reported reset needs an account/billing repair. */
export function isProviderQuotaActionRequired(run: { resultJson?: unknown } | null | undefined, observedAt = new Date()): boolean {
const result = run?.resultJson;
const failure = readProviderFailure(result && typeof result === "object" && !Array.isArray(result)
? (result as Record<string, unknown>).providerFailure : undefined);
return failure?.category === "quota_exhausted" && !failure.retryAt
&& !parseProviderQuotaClockReset(failure.message, observedAt);
}
const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
const MONTH_NAMES = "jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?";
const MAX_DATED_RESET_AHEAD_MS = 45 * 24 * 60 * 60_000;
@@ -10,6 +10,15 @@ import { legacyExecutionNeedsReconciliation } from "../legacy-execution-recovery
import { isConfigurationIncompleteFailedRun } from "../../modules/wake-queue/domain/values.js";
describe("classifyAdapterFailureForRecovery", () => {
it("keeps a typed billing quota out of continuation and provider-quota retry loops", () => {
const run = { errorCode: "provider_quota", error: "Provider quota exceeded", resultJson: {
errorFamily: "provider_quota", retryNotBefore: new Date(Date.now() + 60_000).toISOString(),
providerFailure: { schema: "paperclip.provider-failure.v1", provider: "openai", phase: "turn",
category: "quota_exhausted", message: "Check your plan and billing details.", retryability: "requires_action" },
} };
expect(classifyAdapterFailureForRecovery(run)).toBeNull();
expect(classifyContinuationFailure(run as never)).toMatchObject({ kind: "non_retryable", maxAttempts: 0 });
});
it("does not retry a permanently refused agent interaction delivery", () => {
expect(classifyContinuationFailure({ errorCode: "agent_interaction_delivery_denied", resultJson: null } as never))
.toMatchObject({ kind: "non_retryable", maxAttempts: 0 });
@@ -45,6 +45,17 @@ describe.skipIf(!support.supported)("recovery result PostgreSQL projection", ()
expect(stored).toEqual(run);
});
it.each(["authentication", "quota_exhausted"])("retains typed %s evidence for native recovery", async category => {
const providerFailure = { schema: "paperclip.provider-failure.v1", provider: "openai", phase: "turn",
category, message: "Account needs attention", retryability: "requires_action" };
const { run, selected } = await read({ providerFailure, output: "private execution output" }, "native_session_interrupted");
expect(selected.resultJson).toEqual({ providerFailure });
const complete = { ...run, livenessState: "blocked" };
const projected = { ...complete, resultJson: selected.resultJson };
expect(isAiAuthenticationBlocked(projected)).toBe(isAiAuthenticationBlocked(complete));
expect(classifyContinuationFailure(projected)).toMatchObject({ kind: "non_retryable", maxAttempts: 0 });
});
it.each(["adapter_failed", "provider_quota", "configuration_incomplete"])("retains arbitrary provider evidence for %s classification", async errorCode => {
const now = new Date("2020-01-01T00:00:00Z");
const result = { providerSpecificField: { nestedResponse: "Rate limit exceeded. Try again after 2099-01-01T00:00:00Z" },
@@ -4,7 +4,7 @@ import { sql } from "drizzle-orm";
const recoveryResultKeys = [
"errorFamily", "workspaceValidation", "configurationIncomplete",
"cancelledByActorType", "retryNotBefore", "transientRetryNotBefore",
"providerQuotaRetryNotBefore", "finalizationReasonCode",
"providerQuotaRetryNotBefore", "finalizationReasonCode", "providerFailure",
] as const;
export const recoveryRunResultColumn = sql<Record<string, unknown> | null>`
+5 -2
View File
@@ -131,7 +131,7 @@ import { isBoardOwnedBudgetBlock } from "../budget-block-ownership.js";
import { unadmittedChatWakeupCondition } from "../durable-chat-wakeup.js";
import { issueRecoveryActionService, SOURCE_TERMINAL_RESOLUTION } from "../issue-recovery-actions.js";
import { PROVIDER_LIMIT_DEFAULT_COOLDOWN_MS } from "../system-recovery-state.js";
import { parseProviderQuotaClockReset } from "../provider-quota-reset.js";
import { isProviderQuotaActionRequired, parseProviderQuotaClockReset } from "../provider-quota-reset.js";
import { hasUnverifiedNativeWorkspaceFinalizationOwner } from "../native-runtime/native-workspace-finalization-recovery-state.js";
import {
legacyExecutionNeedsReconciliationWithEvidence,
@@ -476,6 +476,7 @@ function readRecoveryRunErrorFamily(latestRun: LatestIssueRun) {
}
function isProviderQuotaRecovery(latestRun: LatestIssueRun) {
if (isProviderQuotaActionRequired(latestRun)) return false;
if (latestRun?.errorCode === "provider_quota") return true;
if (readRecoveryRunErrorFamily(latestRun) === "provider_quota") return true;
if (latestRun?.errorCode !== "adapter_failed") return false;
@@ -688,6 +689,7 @@ export function classifyAdapterFailureForRecovery(
>,
now = new Date(),
): AdapterFailureRecoveryClassification {
if (isProviderQuotaActionRequired(latestRun, now)) return null;
// An engine prerequisite cannot be repaired by asking the same unavailable
// engine to retry. Use the existing configuration-blocker path.
if (latestRun.errorCode === "adapter_engine_unavailable" || latestRun.errorCode === "provider_tool_definition_invalid" || latestRun.errorCode === "native_provider_model_rejected") {
@@ -781,7 +783,8 @@ export function classifyContinuationFailure(
errorCode,
};
}
if (isAiAuthenticationBlocked(latestRun) || (errorCode && NON_RETRYABLE_CONTINUATION_ERROR_CODES.has(errorCode))) {
if (isAiAuthenticationBlocked(latestRun) || isProviderQuotaActionRequired(latestRun)
|| (errorCode && NON_RETRYABLE_CONTINUATION_ERROR_CODES.has(errorCode))) {
return {
kind: "non_retryable",
maxAttempts: 0,
@@ -367,6 +367,22 @@ it("preserves a provider explanation on a failed task without changing retry aut
.not.toHaveProperty("providerFailure");
});
it("asks for billing action for an exhausted provider quota without inventing a retry time", () => {
const failed = { ...run, errorCode: "native_provider_usage_limit", resultJson: { providerFailure: {
schema: "paperclip.provider-failure.v1", provider: "openai", phase: "turn",
category: "quota_exhausted", providerCode: "insufficient_quota", message: "Check your plan and billing details.",
retryability: "requires_action",
} } };
const input = { run: failed, agent, paused: false, approval: false };
expect(projectTaskInterruption(issue, input)).toMatchObject({ state: "waiting_for_user", responsibility: "user",
userAction: "provider_billing", nextRetryAt: null });
expect(projectTaskInterruption(issue, { ...input, paused: true })).toMatchObject({ userAction: "resume" });
expect(projectTaskInterruption(issue, { ...input, approval: true })).toMatchObject({ userAction: "approval" });
expect(projectTaskInterruption(issue, { ...input, run: { ...failed, resultJson: { providerFailure: {
...failed.resultJson.providerFailure, retryAt: new Date(Date.now() + 60_000).toISOString(),
} } } })).not.toMatchObject({ userAction: "provider_billing" });
});
describe("task project-access interruption", () => {
it("explains a project denial without offering a futile retry", () => {
expect(projectTaskInterruption(issue, { run, agent, paused: false, approval: false })).toMatchObject({
@@ -12,6 +12,7 @@ import { unionAll } from "drizzle-orm/pg-core";
import { EXECUTION_RECONCILIATION_CAUSES, HEARTBEAT_RUN_STATUSES, readProviderFailure, type TaskInterruptionPresentation } from "@paperclipai/shared";
import { captureTaskInterruptionFailure } from "../sentry.js";
import { isAiAuthenticationBlocked } from "./ai-auth-failure.js";
import { isProviderQuotaActionRequired } from "./provider-quota-reset.js";
import { readSystemRecovery } from "./system-recovery-state.js";
import { PROJECT_ACCESS_DENIED } from "./project-access-denial.js";
import { authorizationService } from "./authorization.js";
@@ -421,6 +422,8 @@ function projectTaskInterruptionState(issue: ProjectionIssue, input: ProjectionS
return { ...base, state: "failed", canRetry: false,
retryWait: { reason: "cleanup_quarantined", message: NATIVE_CLEANUP_SETTLING_MESSAGE } };
}
if (run.status === "failed" && isProviderQuotaActionRequired(run, new Date(now)))
return { ...base, responsibility: "user", state: "waiting_for_user", userAction: "provider_billing", canRetry: true };
return { ...base, state: "failed", canRetry: true, ...(projectAccess ? { projectAccess } : {}) };
}
@@ -424,7 +424,7 @@
"packages/shared/src/types/email.ts": "556ff6a0dcefa01eb704d6d00d3b191de81ff4dc",
"packages/shared/src/types/environment.ts": "62e62afcb3d5b7f246db1e8910a34fb0091f54db",
"packages/shared/src/types/execution-continuation.ts": "5afe62afd227efa03ff847d8f73291c14707ab5b",
"packages/shared/src/types/execution-projection.ts": "75ae5e1312160fd9cec79e5234004221ef296ee6",
"packages/shared/src/types/execution-projection.ts": "88d5b54e05556a6e9482633f6d67786b20f98be4",
"packages/shared/src/types/external-object.ts": "7a225e0f5a6777d449019a30530c858b753eb4c1",
"packages/shared/src/types/feedback.ts": "c5eb31545c7f67c04ad9afd9db45a6b4774bcb35",
"packages/shared/src/types/finance.ts": "5c2208c7950020f1005aa0dd86a1680c54dd4354",
@@ -38,6 +38,15 @@ describe("ordinary task interruption", () => {
expect(container.querySelector("a, details, input, textarea")).toBeNull();
expect(container.textContent).not.toMatch(/service attention|process|receipt|workspace/i);
});
it("offers account and billing repair instead of a quota countdown", async () => {
await render({ ...failed, state: "waiting_for_user", responsibility: "user", userAction: "provider_billing",
providerFailure: { schema: "paperclip.provider-failure.v1", provider: "openai", phase: "turn",
category: "quota_exhausted", message: "Check your plan and billing details.", retryability: "requires_action" } });
expect(container.textContent).toContain("Check your provider account’s billing and usage allowance, then retry.");
expect(container.querySelector('a[href="/apps"]')?.textContent).toBe("Review AI account");
expect(container.textContent).not.toMatch(/Trying again|retry automatically/);
});
it("does not report a failed attempt for a task the agent handed to a person", async () => {
await render({ ...failed, responsibility: "user", state: "waiting_for_user", userAction: "unblock" });
expect(container.textContent).toBe("");
+5 -1
View File
@@ -69,8 +69,12 @@ export function ExecutionBlockerNotice({ presentation, canRetry, onRetry, optimi
// Saved-work recovery is what the task waits for, so name it over the
// generic automatic-retry line while keeping the provider explanation.
return <ProviderFailureNotice failure={presentation.providerFailure} className={className}
actions={canRetry && presentation.canRetry ? <Button variant="outline" size="sm" onClick={onRetry} data-testid="task-execution-retry">Retry</Button> : undefined}>
actions={<>
{presentation.userAction === "provider_billing" && <Button variant="outline" size="sm" asChild><Link to="/apps">Review AI account</Link></Button>}
{canRetry && presentation.canRetry && <Button variant="outline" size="sm" onClick={onRetry} data-testid="task-execution-retry">Retry</Button>}
</>}>
{presentation.state === "retry_scheduled" && <p>{step ? `${step}. ${retryIn}` : "Paperclip will retry automatically."}</p>}
{presentation.userAction === "provider_billing" && <p>Check your provider account’s billing and usage allowance, then retry.</p>}
{isBudgetWait(presentation) && <p data-testid="task-execution-waiting">It is waiting for the budget to allow new work. Raise the budget in Costs.</p>}
</ProviderFailureNotice>;
}
+1 -1
View File
@@ -415,7 +415,7 @@ export function FailedRunInboxRow({
: interruption?.state === "retry_scheduled" ? `Trying again in ${retrySeconds}s…`
: interruption?.state === "failed" ? "Couldn’t finish this attempt. Your message is saved."
: interruption?.state === "waiting_for_user" ? ({
approval: "Approval required", question: "Respond to the pending question", reconnect: "Reconnect account", assign_agent: "Assign an agent", choose_model: "Choose a supported model",
approval: "Approval required", question: "Respond to the pending question", reconnect: "Reconnect account", provider_billing: "Review provider billing and usage", assign_agent: "Assign an agent", choose_model: "Choose a supported model",
resume: "Work is paused", budget: "Budget limit reached",
project_access: "Agent needs project access",
confirm_owner_stop: "Confirm the previous server stopped",