mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +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>
153 lines
11 KiB
TypeScript
153 lines
11 KiB
TypeScript
import { describeError } from "../api/errors";
|
||
import type { IssueRelationIssueSummary, TaskInterruptionPresentation } from "@paperclipai/shared";
|
||
import { AlertCircle } from "lucide-react";
|
||
import { Link } from "@/lib/router";
|
||
import { createIssueDetailPath } from "../lib/issueDetailBreadcrumb";
|
||
import { Button } from "./ui/button";
|
||
import { cn } from "../lib/utils";
|
||
import { useSecondTick } from "../hooks/useSecondTick";
|
||
import { TaskProjectAccessNotice } from "./TaskProjectAccessNotice";
|
||
import { ProviderFailureNotice } from "./ProviderFailureNotice";
|
||
import { LockedIssueChip, isLockedIssueStub } from "./LockedIssueChip";
|
||
import { PreviousServerStopConfirmation } from "./WorkspaceExportRecovery";
|
||
import { issuesApi } from "../api/issues";
|
||
|
||
const recoveryStepText: Record<NonNullable<TaskInterruptionPresentation["recoveryStep"]>, string> = {
|
||
checking_previous_run: "Checking that the previous attempt stopped",
|
||
saving_previous_files: "Saving files from the previous attempt",
|
||
finishing_recovery: "Finishing recovery of saved work",
|
||
};
|
||
|
||
/** A budget hard stop holds saved work. Only a task that already ran has an
|
||
* attempt to report; a task refused before its first run just waits. */
|
||
function budgetWaitText(presentation: TaskInterruptionPresentation) {
|
||
const wait = "It is waiting for the budget to allow new work. Raise the budget in Costs.";
|
||
return presentation.observedRunId || presentation.sourceRunIds.length
|
||
? `Couldn’t finish this attempt. Your message is saved. ${wait}`
|
||
: `This task has not started. ${wait}`;
|
||
}
|
||
const isBudgetWait = (presentation: TaskInterruptionPresentation | null | undefined) =>
|
||
presentation?.state === "waiting_for_user" && presentation.userAction === "budget";
|
||
|
||
const blockerAction: Record<string, string> = {
|
||
blocked: "Blocked: open it to Retry",
|
||
cancelled: "Cancelled: remove or replace it",
|
||
done: "Saving its files",
|
||
};
|
||
|
||
/** One ordinary interruption surface. Technical records remain in diagnostics. */
|
||
export function ExecutionBlockerNotice({ presentation, canRetry, onRetry, optimistic, takingLonger, error, className, issueId, companyId, agentName, projectName, blockers }: {
|
||
presentation: TaskInterruptionPresentation | null | undefined;
|
||
companyId?: string;
|
||
blockers?: IssueRelationIssueSummary[];
|
||
canRetry: boolean;
|
||
onRetry: () => void;
|
||
optimistic?: boolean;
|
||
takingLonger?: boolean;
|
||
error?: Error | null;
|
||
className?: string;
|
||
issueId?: string;
|
||
agentName?: string;
|
||
projectName?: string;
|
||
}) {
|
||
useSecondTick(presentation?.state === "retry_scheduled");
|
||
if (presentation?.projectAccess && !optimistic && !takingLonger) return <TaskProjectAccessNotice
|
||
access={presentation.projectAccess} issueId={issueId} agentName={agentName} projectName={projectName}
|
||
canRetry={canRetry && presentation.canRetry} onRetry={onRetry} error={error} className={className} />;
|
||
if (error && !optimistic && !takingLonger) return <div role="alert" className={cn("flex items-center justify-between gap-2 text-sm text-destructive", className)}><span>{describeError(error).body}</span>{canRetry && <Button variant="outline" size="sm" onClick={onRetry} data-testid="task-execution-retry">Retry</Button>}</div>;
|
||
if (takingLonger) return <div role="status" className={cn("flex items-center justify-between gap-2 text-sm text-muted-foreground", className)}><span>Taking longer than usual…</span>{canRetry && <Button variant="outline" size="sm" onClick={onRetry} data-testid="task-execution-retry">Retry</Button>}</div>;
|
||
const step = !optimistic && presentation?.responsibility === "system" && presentation.recoveryStep
|
||
&& ["working", "retry_scheduled"].includes(presentation.state) ? recoveryStepText[presentation.recoveryStep] : null;
|
||
const seconds = Math.max(0, Math.ceil((Date.parse(presentation?.nextRetryAt ?? "") - Date.now()) / 1000));
|
||
const retryIn = `Trying again in ${seconds > 60 ? `${Math.ceil(seconds / 60)}m` : `${seconds}s`}…`;
|
||
if (!optimistic && presentation?.state === "waiting_for_user" && presentation.userAction === "question")
|
||
return <div role="status" data-testid="task-execution-waiting" className={cn("flex items-center justify-between gap-2 text-sm text-muted-foreground", className)}>
|
||
<span>Respond to the pending question to continue.</span>
|
||
{canRetry && presentation.canRetry && <Button variant="outline" size="sm" onClick={onRetry} data-testid="task-execution-retry">Retry</Button>}
|
||
</div>;
|
||
if (!optimistic && !presentation?.retryWait && presentation?.providerFailure && ["failed", "retry_scheduled", "waiting_for_user"].includes(presentation.state)) {
|
||
// 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={<>
|
||
{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>;
|
||
}
|
||
if (step && presentation?.state === "working") return <div role="status" aria-label="Task status"
|
||
className={cn("text-sm text-muted-foreground", className)}>{`${step}…`}</div>;
|
||
if (!optimistic && presentation?.state === "working" && presentation.retryAction === "move_forward" && presentation.canRetry)
|
||
return <div role="status" aria-label="Task status" className={cn("flex items-center justify-between gap-3 text-sm text-muted-foreground", className)}>
|
||
<span className="min-w-0 flex-1">Waiting for the agent to finish other work. Paperclip continues this task by itself.</span>
|
||
{canRetry && <Button variant="outline" size="sm" className="shrink-0" onClick={onRetry} data-testid="task-execution-move-forward">Move it forward now</Button>}
|
||
</div>;
|
||
// A task that has not started yet names the admission hold it waits for.
|
||
if (!optimistic && presentation?.state === "working" && presentation.retryWait) {
|
||
const dependencies = presentation.retryWait.reason === "dependency_blocked" ? blockers ?? [] : [];
|
||
const unfinished = dependencies.filter(blocker => isLockedIssueStub(blocker) || blocker.status !== "done");
|
||
const waitingOn = unfinished.length ? unfinished : dependencies;
|
||
return <div role="status" aria-label="Task status" className={cn("text-sm text-muted-foreground", className)}>
|
||
<p>{presentation.retryWait.message}</p>
|
||
{waitingOn.length ? <ul className="mt-1 space-y-0.5" data-testid="retry-waiting-on">
|
||
{waitingOn.map(blocker => isLockedIssueStub(blocker)
|
||
? <li key={blocker.id} className="flex min-w-0 items-center gap-2"><LockedIssueChip identifier={blocker.identifier} /></li>
|
||
: <li key={blocker.id} className="flex min-w-0 items-center gap-2">
|
||
<Link to={createIssueDetailPath(blocker.identifier ?? blocker.id)}
|
||
className="font-mono text-xs text-foreground underline-offset-2 hover:underline">
|
||
{blocker.identifier ?? "Task"}
|
||
</Link>
|
||
<span className="min-w-0 truncate">{blocker.title}</span>
|
||
<span className="shrink-0 text-xs">{blockerAction[blocker.status] ?? blocker.status.replace(/_/g, " ")}</span>
|
||
</li>)}
|
||
</ul> : null}
|
||
</div>;
|
||
}
|
||
if (!optimistic && presentation?.userAction === "confirm_run_stopped" && presentation.observedRunId && issueId && companyId) {
|
||
const runId = presentation.observedRunId;
|
||
return <PreviousServerStopConfirmation key={`${issueId}:${runId}`} runId={runId} formId={runId} issueId={issueId} companyId={companyId}
|
||
className={className} confirmStop={stopEvidence => issuesApi.confirmRunStopped(issueId, { runId, stopEvidence })}
|
||
copy={{ waiting: presentation.retryWait?.message ?? "Paperclip can't confirm that the previous run stopped. Your message is saved.",
|
||
question: "How did you confirm that no agent is still working on this task?",
|
||
placeholder: "For example: no codex or claude process for this task is running on the server host.",
|
||
resuming: "Starting your Retry…", confirm: "Confirm it stopped" }} />;
|
||
}
|
||
// Other person-owned decisions have their own card on the task (approval,
|
||
// project access, ...). A budget hold has none, so name it here and keep the
|
||
// failure visible. The saved attempt starts by itself once the budget allows.
|
||
if (!optimistic && presentation && isBudgetWait(presentation)) return (
|
||
<div className={cn("pt-4", className)}>
|
||
<div role="status" aria-label="Task status" data-testid="task-execution-waiting"
|
||
className="flex items-center gap-3 rounded-lg bg-destructive/10 p-4 text-sm text-foreground">
|
||
<AlertCircle className="size-5 shrink-0 text-destructive" aria-hidden="true" />
|
||
<span className="min-w-0 flex-1">{budgetWaitText(presentation)}</span>
|
||
</div>
|
||
</div>
|
||
);
|
||
if (optimistic || !presentation || presentation.responsibility !== "system" ||
|
||
!["failed", "retry_scheduled"].includes(presentation.state)) return null;
|
||
return (
|
||
<div className={cn(presentation.state === "failed" && "pt-4", className)}>
|
||
<div role="status" aria-label="Task status" className={cn(
|
||
"flex items-center justify-between gap-3 text-sm",
|
||
presentation.state === "failed" ? "rounded-lg bg-destructive/10 p-4 text-foreground" : "text-muted-foreground",
|
||
)}>
|
||
{presentation.state === "failed" && <AlertCircle className="size-5 shrink-0 text-destructive" aria-hidden="true" />}
|
||
<span className="min-w-0 flex-1">{presentation.state === "retry_scheduled"
|
||
? step ? `${step}. ${retryIn}`
|
||
: presentation.setupFailure ? `${presentation.setupFailure.message}. ${retryIn}` : retryIn
|
||
: presentation.retryWait ? presentation.retryWait.message
|
||
: presentation.workspaceFailure
|
||
? <>Couldn’t prepare the task folders. {presentation.workspaceFailure.message}</>
|
||
: presentation.setupFailure
|
||
? <>Couldn’t set up the task workspace. {presentation.setupFailure.message}. Fix the command in the project’s workspace settings, then retry.</>
|
||
: "Couldn’t finish this attempt. Your message is saved."}</span>
|
||
{canRetry && presentation.canRetry && <Button variant="outline" size="sm" className="shrink-0" onClick={onRetry} data-testid="task-execution-retry">Retry</Button>}
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|