mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 07:27:13 +01:00
## 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>
247 lines
17 KiB
TypeScript
247 lines
17 KiB
TypeScript
// @vitest-environment jsdom
|
||
import { act } from "react";
|
||
import { createRoot, type Root } from "react-dom/client";
|
||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||
import type { TaskInterruptionPresentation } from "@paperclipai/shared";
|
||
import type { AnchorHTMLAttributes } from "react";
|
||
import { ExecutionBlockerNotice } from "./ExecutionBlockerNotice";
|
||
|
||
vi.mock("@/lib/router", () => ({
|
||
Link: ({ children, to, ...props }: AnchorHTMLAttributes<HTMLAnchorElement> & { to: string }) => <a href={to} {...props}>{children}</a>,
|
||
}));
|
||
|
||
const failed: TaskInterruptionPresentation = {
|
||
intentId: "intent", responsibility: "system", state: "failed", nextRetryAt: null,
|
||
canRetry: true, userAction: null, sourceRunIds: ["source"], observedRunId: "source",
|
||
};
|
||
describe("ordinary task interruption", () => {
|
||
let root: Root;
|
||
let container: HTMLDivElement;
|
||
const retry = vi.fn();
|
||
beforeEach(() => {
|
||
retry.mockReset(); container = document.createElement("div"); document.body.append(container);
|
||
root = createRoot(container);
|
||
});
|
||
afterEach(async () => { await act(async () => root.unmount()); container.remove(); vi.useRealTimers(); });
|
||
const render = async (presentation = failed, options: { canRetry?: boolean; optimistic?: boolean; takingLonger?: boolean; error?: Error } = {}) => {
|
||
await act(async () => root.render(<ExecutionBlockerNotice presentation={presentation} canRetry onRetry={retry} {...options} />));
|
||
};
|
||
it("offers one Retry without delegating infrastructure chores", async () => {
|
||
await render();
|
||
expect(container.textContent).toContain("Couldn’t finish this attempt. Your message is saved.");
|
||
expect(container.querySelectorAll("button")).toHaveLength(1);
|
||
// A stable handle for the task's own Retry, the supported path after
|
||
// automatic recovery stops.
|
||
expect(container.querySelector('[data-testid="task-execution-retry"]')?.textContent).toBe("Retry");
|
||
await act(async () => container.querySelector<HTMLButtonElement>("button")!.click());
|
||
expect(retry).toHaveBeenCalledOnce();
|
||
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("");
|
||
});
|
||
|
||
it.each([false, true])("names the question without repeating a historical failure (manual Retry=%s)", async canRetry => {
|
||
const presentation = { ...failed, responsibility: "user" as const, state: "waiting_for_user" as const, userAction: "question" as const, canRetry,
|
||
providerFailure: { schema: "paperclip.provider-failure.v1", provider: "anthropic", phase: "startup",
|
||
category: "rate_limit", httpStatus: 429, retryability: "unknown", message: "API error: 429" } } satisfies TaskInterruptionPresentation;
|
||
await render(presentation);
|
||
expect(container.textContent).toContain("Respond to the pending question to continue.");
|
||
expect(container.textContent).not.toMatch(/429|rate limit|failed/i);
|
||
expect(Boolean(container.querySelector("button"))).toBe(canRetry);
|
||
if (canRetry) {
|
||
await act(async () => container.querySelector<HTMLButtonElement>("button")!.click());
|
||
expect(retry).toHaveBeenCalledOnce();
|
||
}
|
||
await render(presentation, { canRetry: false });
|
||
expect(container.querySelector("button")).toBeNull();
|
||
});
|
||
|
||
it("keeps the failure visible and names the gate while a saved Retry waits on the budget", async () => {
|
||
await render({ ...failed, responsibility: "user", state: "waiting_for_user", userAction: "budget", canRetry: false });
|
||
const notice = container.querySelector('[data-testid="task-execution-waiting"]');
|
||
expect(notice?.textContent).toContain("Couldn’t finish this attempt. Your message is saved.");
|
||
expect(notice?.textContent).toContain("waiting for the budget to allow new work");
|
||
// The saved Retry starts by itself; a second Retry would only duplicate it.
|
||
expect(container.querySelector("button")).toBeNull();
|
||
});
|
||
|
||
it("does not report a failed attempt for a task the budget held before its first run", async () => {
|
||
await render({ ...failed, responsibility: "user", state: "waiting_for_user", userAction: "budget", canRetry: false,
|
||
sourceRunIds: [], observedRunId: null });
|
||
const notice = container.querySelector('[data-testid="task-execution-waiting"]');
|
||
expect(notice?.textContent).toContain("This task has not started.");
|
||
expect(notice?.textContent).not.toContain("Couldn’t finish this attempt");
|
||
});
|
||
|
||
it("shows persisted backoff with a usable Retry", async () => {
|
||
vi.useFakeTimers(); vi.setSystemTime(new Date("2026-10-20T00:00:00Z"));
|
||
await render({ ...failed, state: "retry_scheduled", nextRetryAt: "2026-10-20T00:00:30Z" });
|
||
expect(container.textContent).toContain("Trying again in 30s");
|
||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||
expect(container.textContent).toContain("Trying again in 25s");
|
||
expect(container.querySelector("button")?.textContent).toBe("Retry");
|
||
});
|
||
it.each(["working", "resolved"] as const)("does not duplicate the thread indicator for %s", async state => {
|
||
await render({ ...failed, state }); expect(container.textContent).toBe("");
|
||
});
|
||
it("offers to move a waiting continuation forward in plain words, without reporting a failure", async () => {
|
||
await render({ ...failed, state: "working", retryAction: "move_forward" });
|
||
expect(container.textContent).toContain("Paperclip continues this task by itself.");
|
||
expect(container.textContent).not.toMatch(/Couldn’t finish|failed|continuation|queue|run\b/i);
|
||
const button = container.querySelector<HTMLButtonElement>('[data-testid="task-execution-move-forward"]');
|
||
expect(button?.textContent).toBe("Move it forward now");
|
||
expect(container.querySelectorAll("button")).toHaveLength(1);
|
||
await act(async () => button!.click());
|
||
expect(retry).toHaveBeenCalledOnce();
|
||
});
|
||
|
||
it("shows a waiting continuation without the button to a read-only user, or once the move was requested", async () => {
|
||
await act(async () => root.render(<ExecutionBlockerNotice presentation={{ ...failed, state: "working", retryAction: "move_forward" }}
|
||
canRetry={false} onRetry={retry} />));
|
||
expect(container.textContent).toContain("Paperclip continues this task by itself.");
|
||
expect(container.querySelector("button")).toBeNull();
|
||
await render({ ...failed, state: "working", canRetry: false });
|
||
expect(container.textContent).toBe("");
|
||
});
|
||
|
||
it("names the admission hold a task that has not started waits for", async () => {
|
||
await render({ ...failed, state: "working", canRetry: false, sourceRunIds: [], observedRunId: null,
|
||
retryWait: { reason: "budget.blocked", message: "Waiting for the budget to allow new work. The task starts automatically when it does." } });
|
||
expect(container.textContent).toBe("Waiting for the budget to allow new work. The task starts automatically when it does.");
|
||
expect(container.querySelector("button")).toBeNull();
|
||
});
|
||
it("names and links the readable blockers a saved Retry waits on, with no second Retry (restart chaos t05)", async () => {
|
||
const message = "Retry is waiting on a blocked task this one depends on. Retry or unblock it; this task continues when it is done. Your Retry is saved.";
|
||
const summary = (id: string, identifier: string, title: string, status: string) =>
|
||
({ id, identifier, title, status, priority: "medium", assigneeAgentId: null, assigneeUserId: null }) as never;
|
||
await act(async () => root.render(<ExecutionBlockerNotice presentation={{ ...failed, state: "working", canRetry: false,
|
||
retryWait: { reason: "dependency_blocked", message } }} canRetry onRetry={retry}
|
||
blockers={[summary("child", "CHA-10", "Part 2", "blocked"), summary("gone", "CHA-11", "Part 3", "cancelled"),
|
||
summary("done", "CHA-9", "Part 1", "done")]} />));
|
||
expect(container.textContent).toContain(message);
|
||
const links = [...container.querySelectorAll<HTMLAnchorElement>("[data-testid='retry-waiting-on'] a")].map(link => link.getAttribute("href"));
|
||
expect(links).toHaveLength(2);
|
||
expect(links[0]).toContain("CHA-10");
|
||
expect(container.textContent).toContain("Blocked: open it to Retry");
|
||
expect(container.textContent).toContain("Cancelled: remove or replace it");
|
||
expect(container.textContent).not.toContain("Part 1");
|
||
expect(container.querySelector("button")).toBeNull();
|
||
});
|
||
it("shows a locked blocker without reading its status, and a finished blocker still saving files", async () => {
|
||
const message = "Retry is waiting for a finished task this one depends on to save its files. Your Retry is saved.";
|
||
await act(async () => root.render(<ExecutionBlockerNotice presentation={{ ...failed, state: "working", canRetry: false,
|
||
retryWait: { reason: "dependency_blocked", message } }} canRetry onRetry={retry}
|
||
blockers={[{ id: "secret", identifier: "CHA-12", locked: true } as never]} />));
|
||
expect(container.querySelector("[data-testid='locked-issue-chip']")?.textContent).toContain("CHA-12");
|
||
await act(async () => root.render(<ExecutionBlockerNotice presentation={{ ...failed, state: "working", canRetry: false,
|
||
retryWait: { reason: "dependency_blocked", message } }} canRetry onRetry={retry}
|
||
blockers={[{ id: "done", identifier: "CHA-9", title: "Part 1", status: "done", priority: "medium",
|
||
assigneeAgentId: null, assigneeUserId: null } as never]} />));
|
||
expect(container.querySelector("[data-testid='retry-waiting-on'] a")?.getAttribute("href")).toContain("CHA-9");
|
||
expect(container.textContent).toContain("Saving its files");
|
||
});
|
||
it("names the saved-work recovery step instead of a bare queue", async () => {
|
||
await render({ ...failed, state: "working", canRetry: false, recoveryStep: "saving_previous_files" });
|
||
expect(container.textContent).toBe("Saving files from the previous attempt…");
|
||
expect(container.querySelector("button")).toBeNull();
|
||
});
|
||
it("names the step a scheduled recovery will retry", async () => {
|
||
vi.useFakeTimers(); vi.setSystemTime(new Date("2026-10-20T00:00:00Z"));
|
||
await render({ ...failed, state: "retry_scheduled", nextRetryAt: "2026-10-20T00:00:30Z", recoveryStep: "checking_previous_run" });
|
||
expect(container.textContent).toContain("Checking that the previous attempt stopped. Trying again in 30s…");
|
||
expect(container.querySelector("button")?.textContent).toBe("Retry");
|
||
});
|
||
it("names the recovery step inside a provider failure notice", async () => {
|
||
vi.useFakeTimers(); vi.setSystemTime(new Date("2026-10-20T00:00:00Z"));
|
||
await render({ ...failed, state: "retry_scheduled", nextRetryAt: "2026-10-20T00:00:30Z", recoveryStep: "checking_previous_run",
|
||
providerFailure: { schema: "paperclip.provider-failure.v1", provider: "openai", phase: "startup", category: "overloaded",
|
||
retryability: "unknown", message: "Try later." } });
|
||
expect(container.textContent).toContain("Checking that the previous attempt stopped. Trying again in 30s…");
|
||
expect(container.textContent).not.toContain("Paperclip will retry automatically.");
|
||
});
|
||
it("leaves genuine user decisions to their specific action surface", async () => {
|
||
await render({ ...failed, responsibility: "user", state: "waiting_for_user", userAction: "approval", canRetry: false });
|
||
expect(container.textContent).toBe("");
|
||
});
|
||
it("does not give read-only users a mutation", async () => {
|
||
await render(failed, { canRetry: false }); expect(container.querySelector("button")).toBeNull();
|
||
});
|
||
it("removes the stale failure immediately while admission is pending", async () => {
|
||
await render(failed, { optimistic: true }); expect(container.textContent).toBe("");
|
||
await render(failed, { optimistic: true, takingLonger: true });
|
||
expect(container.textContent).toContain("Taking longer than usual…");
|
||
});
|
||
it("shows a definitive admission rejection instead of silently dropping Retry", async () => {
|
||
await render(failed, { error: new Error("Your task access changed. Refresh the task.") });
|
||
expect(container.querySelector('[role="alert"]')?.textContent).toContain("Your task access changed.");
|
||
expect(container.querySelectorAll("button")).toHaveLength(1);
|
||
});
|
||
it("shows workspace preparation failures as plain text while keeping retry permissions", async () => {
|
||
const workspaceFailure = { message: 'Could not prepare the project folder <img src=x onerror=alert(1)>.' };
|
||
await render({ ...failed, workspaceFailure }, { canRetry: false });
|
||
expect(container.textContent).toContain("Couldn’t prepare the task folders.");
|
||
expect(container.textContent).toContain(workspaceFailure.message);
|
||
expect(container.querySelector("img, button")).toBeNull();
|
||
await render({ ...failed, workspaceFailure });
|
||
await act(async () => container.querySelector<HTMLButtonElement>("button")!.click());
|
||
expect(retry).toHaveBeenCalledOnce();
|
||
await render({ ...failed, workspaceFailure, state: "working" });
|
||
expect(container.textContent).toBe("");
|
||
});
|
||
it("names a failed workspace setup command and what to change, keeping Retry", async () => {
|
||
const setupFailure = { step: "workspace_provision" as const, command: "bash ./scripts/provision-worktree.sh", exitCode: 127,
|
||
output: "bash: ./scripts/provision-worktree.sh: No such file or directory",
|
||
message: "The project's workspace provision command \"bash ./scripts/provision-worktree.sh\" failed with exit code 127: bash: ./scripts/provision-worktree.sh: No such file or directory" };
|
||
await render({ ...failed, setupFailure });
|
||
expect(container.textContent).toContain("Couldn’t set up the task workspace.");
|
||
expect(container.textContent).toContain(setupFailure.message);
|
||
expect(container.textContent).toContain("Fix the command in the project’s workspace settings");
|
||
expect(container.textContent).not.toContain("Couldn’t finish this attempt.");
|
||
await act(async () => container.querySelector<HTMLButtonElement>("button")!.click());
|
||
expect(retry).toHaveBeenCalledOnce();
|
||
});
|
||
it("shows why an accepted Retry is waiting and keeps another attempt available", async () => {
|
||
const retryWait = { reason: "remote_cleanup", message: "Retry is waiting for the previous environment to stop. Your message is saved." };
|
||
await render({ ...failed, retryWait });
|
||
expect(container.textContent).toContain(retryWait.message);
|
||
expect(container.textContent).not.toContain("Couldn’t finish this attempt.");
|
||
await act(async () => container.querySelector<HTMLButtonElement>("button")!.click());
|
||
expect(retry).toHaveBeenCalledOnce();
|
||
await render({ ...failed, retryWait }, { canRetry: false });
|
||
expect(container.textContent).toContain(retryWait.message);
|
||
expect(container.querySelector("button")).toBeNull();
|
||
});
|
||
it("names the budget wait alongside a provider failure while a saved Retry is held", async () => {
|
||
const providerFailure = { schema: "paperclip.provider-failure.v1" as const, provider: "openai", phase: "startup" as const,
|
||
category: "overloaded" as const, retryability: "transient" as const, message: "Provider overloaded" };
|
||
await render({ ...failed, providerFailure, responsibility: "user", state: "waiting_for_user", userAction: "budget", canRetry: false });
|
||
expect(container.textContent).toContain("Provider overloaded");
|
||
expect(container.querySelector('[data-testid="task-execution-waiting"]')?.textContent).toContain("waiting for the budget to allow new work");
|
||
expect(container.querySelector("button")).toBeNull();
|
||
});
|
||
it("shows an unknown provider's original explanation as text and preserves read-only access", async () => {
|
||
const providerFailure = { schema: "paperclip.provider-failure.v1" as const, provider: "new-provider", phase: "startup" as const,
|
||
category: "unknown" as const, retryability: "unknown" as const, httpStatus: 429,
|
||
message: "Upstream failure <img src=x onerror=alert(1)>" };
|
||
await render({ ...failed, providerFailure }, { canRetry: false });
|
||
expect(container.textContent).toContain(providerFailure.message);
|
||
expect(container.textContent).toContain("Failed before work started");
|
||
expect(container.textContent).toContain("HTTP 429");
|
||
expect(container.querySelector("img, button")).toBeNull();
|
||
await render({ ...failed, providerFailure, state: "resolved" });
|
||
expect(container.textContent).toBe("");
|
||
});
|
||
});
|