fix(inbox): group repeated provider failures and clear recovered tasks (#22846)

## Thinking Path

> - Paperclip helps people manage work that agents do.
> - The inbox tells a person which tasks need a decision.
> - A provider usage limit can stop several attempts on one task or
affect several tasks.
> - Separate failure cards made it hard to tell which tasks still needed
attention.
> - This change groups failures using the account, reset time, or retry
links that Paperclip can verify.
> - A person can now see which task to retry, which tasks are waiting,
and which ones recovered.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

It improves the Coordinator inbox when a provider limits usage.

**Current behavior**

Repeated run failures can fill the inbox. Resolved failures can still
appear beside open decisions.

**Proposed behavior**

Show personal actions in Needs you, automatic retries and snoozes in
Waiting, and past events in History. Keep an archived retry chain hidden
during automatic attempts. Return it to Needs you when a person must
act.

**Additional context**

Related work includes #18020 on completed tasks, #9704 on archive
behavior, and #21570 on usage limits in chat.

## What Changed

- Group verified account and reset windows. When that evidence is
missing, count linked attempts per task and show the tasks in a
collapsible group.
- Separate the reported reset time from each task’s retry schedule. Keep
unresolved ownership recoveries visible after task closure. Use
persisted native retry requests to preserve the original archive and
increment the attempt count.
- Keep personal archive in the card menu. Put decision receipts and run
logs in History.
- Align inbox filters, tabs, and history. Share empty-state artwork and
placement across Inbox, Goals, Routines, and Secrets.
- Index run-history pages and resumed-work lookups, and rate-limit
history requests per company and viewer. Add synthetic fixtures for both
grouping paths and a manual walkthrough.

## Verification

- The author and a human tester completed the synthetic retry-chain
walkthrough. Chromium also verified archive, repeat failure, exhaustion,
and recovery.
- The 64 focused server tests and the UI and server typechecks passed
before rebasing. See `doc/testing/coordinator-inbox-test-drive.md` to
repeat the manual checks.
- The shared SDK input check and all 64 focused server tests passed
after rebasing. The OpenAPI suite (59 tests), API catalog suite (2,309
tests), and both demo seed paths passed locally after the CI fixes.
- The affected inbox and native-runtime suites passed locally after
merging the upstream conformance test fix in #22854. The browser
access-denial scenarios passed three runs each for 403 and 404.
- The migration checks and 79 focused tests passed, including an
index-plan regression with 5,000 unrelated runs. The migration and query
plan were reverified after renumbering. [Full CI on
`cf52b80161`](https://github.com/paperclipai/paperclip/actions/runs/45529834793)
passed after rerunning a timed-out server shard.

## Risks

The attention feed reads retry ancestry. Long chains can increase query
cost. Task and company checks bound the traversal, and cycle detection
stops repeated visits. Providers that omit the reset time leave the card
with an unknown reset. Migration 0508 adds two indexes concurrently.
Each run-history page returns at most 100 records.

## Model Used

OpenAI Codex, GPT-6 family, with repository editing, local test
execution, and browser verification.

## 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: Scott Tong <scott@scotts-mbp-m5-max.local>
Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
authored and GitHub committed 2026-11-24 18:33:27 -08:00
1 parent f961287949
commit 627d59c5aa
50 files changed
+1759 -234

No files matched your search

@@ -1,16 +1,21 @@
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
import { randomUUID } from "node:crypto";
import { createHash, randomUUID } from "node:crypto";
import { and, eq, inArray, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import {
activityLog,
agents,
agentWakeupRequests,
agentRuntimeState,
heartbeatRunEvents,
heartbeatRuns,
approvals,
companies,
companyMemberships,
createDb,
issueApprovals,
issueComments,
issueRecoveryActions,
issueThreadInteractions,
issues,
} from "@paperclipai/db";
@@ -28,6 +33,7 @@ import {
} from "../services/attention.js";
import { expirePendingInteractionsOnClosedIssues } from "../services/closed-issue-interaction-sweep.js";
import { inboxDismissalService } from "../services/inbox-dismissals.js";
import { attentionRunHistory, attentionRunHistoryQuery } from "../services/attention-provider-limits.js";
import { pendingUserRequestRowCondition } from "../services/issue-participation.js";
const TOOL_ACTION = {
@@ -229,6 +235,206 @@ describeEmbeddedPostgres("attention current cards (PAP-749 task 2a)", () => {
return (await attentionService(db).list(companyId, { userId, view })).items;
}
it.each(["done", "cancelled"])("keeps unresolved ownership recovery visible when a task is %s", async (status) => {
const { companyId } = await seedCompany();
const task = await insertIssue({ companyId, status, createdByUserId: SCOTT });
const limitedTask = await insertIssue({ companyId, status, createdByUserId: SCOTT });
const [ownership] = await db.insert(issueRecoveryActions).values([
{ companyId, sourceIssueId: task, kind: "active_run_watchdog", ownerType: "board",
cause: "ownership_owner_unprovable", fingerprint: "owner", nextAction: "Confirm the previous server stopped." },
{ companyId, sourceIssueId: limitedTask, kind: "active_run_watchdog", ownerType: "board",
cause: "native_provider_usage_limit", fingerprint: "limit", nextAction: "Retry after restoring capacity." },
]).returning();
const cards = (await list(companyId, SCOTT, "company")).filter(item => item.sourceKind === "recovery_action");
expect(cards.map(item => item.subject.id)).toEqual([ownership!.id]);
const summary = await attentionService(db).summary(companyId, { userId: SCOTT });
expect(summary.countsBySourceKind.recovery_action).toBe(1);
});
it("clears an agent's last provider error when the task finishes without another run", async () => {
const { companyId, workerId } = await seedCompany();
const issueId = await insertIssue({ companyId });
const error = "Provider usage limit reached";
const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId: workerId, issueId, scopeKind: "issue",
error, errorCode: "native_provider_usage_limit", status: "failed" }).returning();
await db.insert(agentRuntimeState).values({ agentId: workerId, companyId, lastRunId: run!.id, lastError: error, adapterType: "process" });
await db.update(agents).set({ status: "error", errorReason: error }).where(eq(agents.id, workerId));
const errors = async () => (await list(companyId, SCOTT, "company")).filter(item => item.sourceKind === "agent_error_alert");
expect(await errors()).toHaveLength(1);
await db.update(issues).set({ status: "done" }).where(eq(issues.id, issueId));
expect(await errors()).toHaveLength(0);
await db.update(agents).set({ errorReason: "Different failure" }).where(eq(agents.id, workerId));
expect(await errors()).toHaveLength(1);
});
it("keeps unverified quota retries task-scoped through archive, exhaustion, and recovery", async () => {
const { companyId, workerId } = await seedCompany();
const makeTask = () => insertIssue({ companyId, createdByUserId: SCOTT, assigneeAgentId: workerId });
const [first, second, third] = await Promise.all([makeTask(), makeTask(), makeTask()]);
const due = new Date(Date.now() + 60_000);
const base = { companyId, agentId: workerId, scopeKind: "issue" } as const;
async function start(issueId: string) {
const [run] = await db.insert(heartbeatRuns).values({ ...base, issueId, status: "failed",
errorCode: "native_provider_usage_limit" }).returning();
return queue(issueId, run!.id);
}
async function queue(issueId: string, parent: string) {
const [retry] = await db.insert(heartbeatRuns).values({ ...base, issueId, status: "scheduled_retry",
retryOfRunId: parent, scheduledRetryAt: due }).returning();
return retry!.id;
}
let retry = await start(first);
const secondRetry = await start(second);
await start(third);
const cards = async (view: AttentionFeedView) => (await list(companyId, SCOTT, view)).filter(item => item.providerLimit);
const waiting = await cards("waiting");
expect(waiting).toHaveLength(3);
expect(new Set(waiting.map(item => item.dismissalKey)).size).toBe(3);
const original = waiting.find(item => item.relatedIssue?.id === first)!;
expect(original.providerLimit).toMatchObject({ grouping: "retry_chain", attempts: 1, resetAt: null,
retryAt: due.toISOString(), state: "scheduled" });
await inboxDismissalService(db).dismiss(companyId, SCOTT, original.dismissalKey, new Date(), original.changeFingerprint);
for (let count = 2; count <= 4; count++) {
await db.update(heartbeatRuns).set({ status: "failed", errorCode: "native_provider_usage_limit" }).where(eq(heartbeatRuns.id, retry));
retry = await queue(first, retry);
}
expect((await cards("waiting")).map(item => item.relatedIssue?.id).sort()).toEqual([second, third].sort());
const archived = await cards("archived");
expect(archived).toHaveLength(1);
expect(archived[0]).toMatchObject({ dismissalKey: original.dismissalKey, providerLimit: { attempts: 4 } });
await db.update(heartbeatRuns).set({ status: "failed", errorCode: "native_provider_usage_limit" }).where(eq(heartbeatRuns.id, retry));
await db.insert(heartbeatRunEvents).values({ companyId, agentId: workerId, runId: retry, seq: 1,
eventType: "lifecycle", message: "Bounded retry exhausted" });
const manual = await cards("mine");
expect(manual).toHaveLength(1);
expect(manual[0]).toMatchObject({ relatedIssue: { id: first }, providerLimit: { attempts: 5, state: "needs_retry" } });
expect(await cards("archived")).toHaveLength(0);
expect(await cards("waiting")).toHaveLength(2);
await db.update(heartbeatRuns).set({ status: "queued", scheduledRetryAt: null }).where(eq(heartbeatRuns.id, secondRetry));
const queued = (await cards("waiting")).find(item => item.relatedIssue?.id === second);
expect(queued?.providerLimit).toMatchObject({ attempts: 1, state: "retry_requested", resetAt: null });
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, secondRetry));
await db.update(issues).set({ status: "done" }).where(eq(issues.id, first));
expect((await cards("waiting")).map(item => item.relatedIssue?.id)).toEqual([third]);
expect(await cards("mine")).toHaveLength(0);
});
it("honors an older per-run archive without folding unrelated retries on the same task", async () => {
const { companyId, workerId } = await seedCompany();
const task = await insertIssue({ companyId, createdByUserId: SCOTT, assigneeAgentId: workerId });
const other = await insertIssue({ companyId, createdByUserId: SCOTT, assigneeAgentId: workerId });
const base = { companyId, agentId: workerId, scopeKind: "issue" } as const;
async function failed(issueId: string, parent: string | null, code = "provider_limit_wait") {
const [run] = await db.insert(heartbeatRuns).values({ ...base, issueId, retryOfRunId: parent,
status: "failed", errorCode: code }).returning();
return run!.id;
}
const otherRoot = await failed(other, null);
const root = await failed(task, otherRoot); // A cross-task pointer cannot establish a shared chain.
const middle = await failed(task, root);
const transient = await failed(task, middle, "transient_error");
const tip = await failed(task, transient);
const separate = await failed(task, null);
for (const parent of [tip, separate]) {
await db.insert(heartbeatRuns).values({ ...base, issueId: task, retryOfRunId: parent,
status: "scheduled_retry", scheduledRetryAt: new Date(Date.now() + 60_000) });
}
const waiting = await list(companyId, SCOTT, "waiting");
const before = waiting.find(item => item.providerLimit?.runId === tip)!;
expect(before.providerLimit?.attempts).toBe(3);
const oldEpisode = createHash("sha256").update(middle).digest("hex");
const oldKey = before.dismissalKey.replace(before.providerLimit!.episode, oldEpisode);
await inboxDismissalService(db).dismiss(companyId, SCOTT, oldKey, new Date(), before.changeFingerprint);
expect((await list(companyId, SCOTT, "archived")).map(item => item.dismissalKey)).toEqual([oldKey]);
expect((await list(companyId, SCOTT, "waiting")).map(item => item.providerLimit?.runId)).toEqual([separate]);
});
it("keeps a native retry linked to an archived provider limit through its saved retry request", async () => {
const { companyId, workerId } = await seedCompany();
const issueId = await insertIssue({ companyId, createdByUserId: SCOTT, assigneeAgentId: workerId });
const [initialRun] = await db.insert(heartbeatRuns).values({
companyId, agentId: workerId, issueId, scopeKind: "issue", runtimeMode: "native",
status: "failed", errorCode: "native_provider_usage_limit",
}).returning();
const evidence = { runId: initialRun!.id, providerLimitAutomatic: true, providerLimitEstimated: true };
const [hold] = await db.insert(issueRecoveryActions).values({
companyId, sourceIssueId: issueId, kind: "active_run_watchdog", ownerType: "board",
cause: "native_provider_usage_limit", fingerprint: "limit", nextAction: "Retry when capacity returns.", evidence,
}).returning();
const [original] = await list(companyId, SCOTT, "waiting");
expect(original?.providerLimit).toMatchObject({ grouping: "retry_chain", attempts: 1 });
await inboxDismissalService(db).dismiss(companyId, SCOTT, original!.dismissalKey, new Date(), original!.changeFingerprint);
const requestId = randomUUID();
const [retry] = await db.insert(heartbeatRuns).values({
companyId, agentId: workerId, issueId, scopeKind: "issue", runtimeMode: "native",
status: "failed", errorCode: "native_provider_usage_limit",
contextSnapshot: { issueId, previousRunId: initialRun!.id, taskRetryRequestId: requestId },
}).returning();
const taskRetry = {
schema: "paperclip.task-retry.v1", generationId: requestId, sourceRunId: initialRun!.id,
actorId: SCOTT, strategy: "evaluate", initiatedBy: "provider_limit_reset",
};
await db.insert(agentWakeupRequests).values({
id: requestId, companyId, agentId: workerId, source: "on_demand", reason: "task_retry",
requestedByActorType: "user", requestedByActorId: SCOTT, runId: retry!.id,
payload: { issueId, taskRetry },
});
await db.update(issueRecoveryActions).set({ evidence: { ...evidence, runId: retry!.id } })
.where(eq(issueRecoveryActions.id, hold!.id));
expect(await list(companyId, SCOTT, "waiting")).toHaveLength(0);
expect(await list(companyId, SCOTT, "archived")).toEqual([expect.objectContaining({
dismissalKey: original!.dismissalKey,
providerLimit: expect.objectContaining({ attempts: 2, runId: retry!.id }),
})]);
await db.update(agentWakeupRequests).set({ payload: { issueId: randomUUID(), taskRetry } })
.where(eq(agentWakeupRequests.id, requestId));
expect(await list(companyId, SCOTT, "archived")).toHaveLength(0);
expect(await list(companyId, SCOTT, "waiting")).toEqual([expect.objectContaining({
providerLimit: expect.objectContaining({ attempts: 1, runId: retry!.id }),
})]);
});
it("uses indexed history pages and recovery probes as unrelated runs accumulate", async () => {
const { companyId, workerId } = await seedCompany();
const task = await insertIssue({ companyId, createdByUserId: SCOTT });
const unrelated = await insertIssue({ companyId, createdByUserId: SCOTT });
await db.execute(sql`
insert into ${heartbeatRuns} (company_id, agent_id, issue_id, scope_kind, status, created_at)
select ${companyId}::uuid, ${workerId}::uuid, ${unrelated}::uuid, 'issue', 'succeeded',
now() - n * interval '1 second'
from generate_series(1, 5000) n
`);
await db.execute(sql`
insert into ${heartbeatRuns} (company_id, agent_id, issue_id, scope_kind, status, created_at)
select ${companyId}::uuid, ${workerId}::uuid, ${task}::uuid, 'issue', 'failed',
now() - interval '1 day' - n * interval '1 microsecond'
from generate_series(1, 101) n
`);
await db.insert(heartbeatRuns).values({
companyId, agentId: workerId, scopeKind: "issue", status: "succeeded", contextSnapshot: { taskId: task },
});
await db.execute(sql`analyze ${heartbeatRuns}`);
const allowed = sql`true`;
const first = await attentionRunHistory(db, companyId, allowed);
expect(first).toHaveLength(100);
expect(new Set(first.map(row => row.outcome))).toEqual(new Set(["Work resumed"]));
const before = { at: first.at(-1)!.recordedAt, id: first.at(-1)!.runId };
const second = await attentionRunHistory(db, companyId, allowed, before);
expect(second).toEqual([expect.objectContaining({ taskId: task, outcome: "Work resumed" })]);
expect(first.some(row => row.runId === second[0]?.runId)).toBe(false);
const query = attentionRunHistoryQuery(db, companyId, allowed, before);
const plan = JSON.stringify(await db.execute(sql`explain (format json) ${query}`));
expect(plan).toContain("heartbeat_runs_attention_history_idx");
expect(plan).toContain("heartbeat_runs_attention_resumed_idx");
});
function find(items: AttentionItem[], sourceId: string) {
return items.find((item) => item.subject.id === sourceId) ?? null;
}
+24 -1
View File
@@ -1,3 +1,5 @@
import { attentionRunHistory } from "../services/attention-provider-limits.js";
import { issueReadSqlCondition } from "../services/authorization.js";
import { Router, type Request } from "express";
import type { Db } from "@paperclipai/db";
import {
@@ -12,6 +14,7 @@ import {
type AttentionTransferResult,
} from "@paperclipai/shared";
import { attentionService } from "../services/attention.js";
import { createCompanySearchRateLimiter } from "../services/company-search-rate-limit.js";
import {
attentionHandledDetails,
attentionHandledFor,
@@ -31,7 +34,7 @@ import { assertBoard, assertCompanyAccess, getActorInfo } from "./authz.js";
import { cancelApprovalAndNotify } from "./approvals.js";
import { withdrawIssueThreadInteractionAndNotify } from "./issues.js";
const ATTENTION_FEED_VIEWS: readonly AttentionFeedView[] = ["mine", "unassigned", "company", "archived", "all"];
const ATTENTION_FEED_VIEWS: readonly AttentionFeedView[] = ["mine", "unassigned", "company", "archived", "all", "waiting"];
function optionalQueryString(value: unknown, field: string) {
if (value === undefined) return undefined;
@@ -45,6 +48,7 @@ export function attentionRoutes(
) {
const router = Router();
const svc = attentionService(db);
const runHistoryRateLimiter = createCompanySearchRateLimiter();
const heartbeat = heartbeatService(db, { pluginWorkerManager: options.pluginWorkerManager });
const decisions = decisionService(db, options.decisionServiceOptions ?? {
wakeOriginAgent: createDecisionWakeOriginAgent(heartbeat.wakeup),
@@ -81,6 +85,25 @@ export function attentionRoutes(
res.json(await svc.taskIndex(companyId, { userId: req.actor.userId, actor: req.actor }));
});
router.get("/companies/:companyId/attention/run-history", async (req, res) => {
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
assertBoard(req);
if (!req.actor.userId) { res.status(403).json({ error: "Board user context required" }); return; }
const cursor = z.object({ at: z.string().datetime(), id: z.string().uuid() }).strict();
const before = Object.keys(req.query).length ? cursor.safeParse(req.query) : null;
if (before && !before.success) throw badRequest("Invalid run history cursor");
const rate = runHistoryRateLimiter.consume({ companyId, actorType: "board", actorId: req.actor.userId });
res.setHeader("X-RateLimit-Limit", String(rate.limit));
res.setHeader("X-RateLimit-Remaining", String(rate.remaining));
if (!rate.allowed) {
res.setHeader("Retry-After", String(rate.retryAfterSeconds));
res.status(429).json({ error: "Run history rate limit exceeded", retryAfterSeconds: rate.retryAfterSeconds });
return;
}
res.json(await attentionRunHistory(db, companyId, await issueReadSqlCondition(db, req.actor), before?.data));
});
router.get("/companies/:companyId/attention/history", async (req, res) => {
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
+28 -2
View File
@@ -1506,6 +1506,7 @@ const BOARD_ONLY_OPERATIONS = new Set([
"GET /api/issues/{id}/decision-receipts",
"GET /api/issues/{id}/chat-handoffs",
"GET /api/companies/{companyId}/attention/history",
"GET /api/companies/{companyId}/attention/run-history",
"GET /api/companies/{companyId}/attention/summary",
"GET /api/companies/{companyId}/attention/tasks",
"POST /api/companies/{companyId}/attention/{sourceKind}/{sourceId}/claim",
@@ -6640,8 +6641,8 @@ registry.registerPath({
includeDismissed: z.enum(["true", "false"]).optional(),
archived: z.enum(["true", "false"]).optional(),
all: z.enum(["true", "false"]).optional(),
view: z.enum(["mine", "unassigned", "company", "archived", "all"]).optional()
.describe("Audience slice (PAP-749). `all` (default) keeps the full feed; `viewCounts` and the For you badge `deskBadgeCount` ignore it. `mine` also returns `receipts`: what a different person did with your cards in the last 7 days. `archived` returns only the open cards you archived or snoozed for yourself, whatever their audience; `viewCounts.archived` counts them and is never in the badge. `viewCounts.all` counts the Everyone tab (every person's open cards, board members only) and is never in the badge."),
view: z.enum(["mine", "unassigned", "company", "archived", "all", "waiting"]).optional()
.describe("Audience slice (PAP-749). `waiting` lists snoozed requests and automatic retries visible to the caller. `all` (default) keeps the full feed; `viewCounts` and the For you badge `deskBadgeCount` ignore it. `mine` also returns `receipts`: what a different person did with your cards in the last 7 days. `archived` returns only the open cards you archived or snoozed for yourself, whatever their audience; `viewCounts.archived` counts them and is never in the badge. `viewCounts.all` counts the Everyone tab (every person's open cards, board members only) and is never in the badge."),
activitySince: z.string().datetime().optional(),
activityUntil: z.string().datetime().optional(),
queue: z.string().min(1).optional(),
@@ -6654,6 +6655,8 @@ registry.registerPath({
});
const attentionSummaryResponseSchema = z.object({
waitingCount: z.number().int().nonnegative().optional(),
nextSnoozeAt: z.string().datetime().optional(),
companyId: z.string().uuid(),
generatedAt: z.string().datetime(),
totalCount: z.number().int().nonnegative(),
@@ -6747,6 +6750,29 @@ registry.registerPath({
// ─── Decisions ──────────────────────────────────────────────────────────────
registry.registerPath({
method: "get",
path: "/api/companies/{companyId}/attention/run-history",
tags: ["inbox"],
summary: "List recent failures in inbox run history",
description: "Requires a board user. Returns up to 100 recent failed runs on tasks visible to the caller, newest first. For the next page, pass the last row’s recordedAt and runId as at and id together. Limited to 60 requests per minute per board user and company.",
request: {
params: z.object({ companyId: z.string() }),
query: z.object({ at: z.string().datetime().optional(), id: z.string().uuid().optional() }).strict(),
},
responses: {
200: r.ok(z.array(z.object({
runId: z.string().uuid(), agentId: z.string().uuid(), agentName: z.string(),
taskId: z.string().uuid(), taskTitle: z.string(), identifier: z.string().nullable(),
recordedAt: z.string().datetime(), reason: z.string(), outcome: z.string(),
}))),
400: r.badRequest,
401: r.unauthorized,
403: r.forbidden,
429: r.tooManyRequests,
},
});
registry.registerPath({
method: "get",
path: "/api/companies/{companyId}/attention/history",
@@ -1,5 +1,7 @@
import { and, asc, desc, eq, inArray, notInArray, sql } from "drizzle-orm";
import { agents, heartbeatRunEvents, heartbeatRuns, type Db } from "@paperclipai/db";
import { agents, heartbeatRunEvents, heartbeatRuns, issueRecoveryActions, type Db } from "@paperclipai/db";
import { providerWorkResumed, usageLimitFailure } from "./attention-provider-limits.js";
export function listAttentionExhaustedRuns(db: Db, companyId: string) {
// Recovery can revisit an exhausted run. Deduplicate its historical events
@@ -31,6 +33,17 @@ export function listAttentionExhaustedRuns(db: Db, companyId: string) {
status: heartbeatRuns.status,
error: heartbeatRuns.error,
errorCode: heartbeatRuns.errorCode,
providerLimited: sql<boolean>`${usageLimitFailure} is true`,
providerResumed: sql<boolean>`case when ${usageLimitFailure} then ${providerWorkResumed} else false end`,
providerRetryAt: sql<string | null>`${heartbeatRuns.resultJson}#>>'{providerFailure,retryAt}'`,
account: sql<string | null>`coalesce(nullif(${heartbeatRuns.contextSnapshot}#>>'{aiConnection,subscriptionId}', ''),
nullif(${heartbeatRuns.contextSnapshot}#>>'{aiConnection,connectionId}', ''))`,
settledProviderHold: sql<boolean>`${heartbeatRuns.errorCode} = 'native_provider_usage_limit' and exists(
select 1 from ${issueRecoveryActions} hold where hold.company_id = ${heartbeatRuns.companyId}
and hold.source_issue_id = coalesce(${heartbeatRuns.issueId}, ${heartbeatRuns.nativeIssueId})
and hold.evidence->>'runId' = ${heartbeatRuns.id}::text and hold.cause = 'native_provider_usage_limit'
and hold.status in ('resolved','cancelled'))`,
boundTaskId: sql<string | null>`coalesce(${heartbeatRuns.issueId}, ${heartbeatRuns.nativeIssueId})`,
// Preserve JSON types and issueId/taskId fallback semantics without
// transferring prompts, transcripts, or the rest of the run context.
contextSnapshot: sql<Record<string, unknown>>`jsonb_build_object(
@@ -0,0 +1,52 @@
import { describe, expect, it } from "vitest";
import type { AttentionItem } from "@paperclipai/shared";
import { groupProviderLimits, providerLimitForHold } from "./attention-provider-limits.js";
const run = { runId: "run-1", taskId: "task-1", agentId: "agent-1", agentName: "Editor", account: "account-1" };
const reset = "2026-11-24T21:00:00Z";
const scheduled = { providerLimitResetAt: reset, providerLimitAutomatic: true };
describe("provider usage limits in the inbox", () => {
it("uses the same known account and reset across agents, keeping unverified or estimated windows separate", () => {
const episode = providerLimitForHold(run, scheduled, "").episode;
const other = { ...run, runId: "run-2", taskId: "task-2", agentId: "agent-2" };
expect(providerLimitForHold(other, scheduled, "").episode).toBe(episode);
expect(providerLimitForHold({ ...other, account: "account-2" }, scheduled, "").episode).not.toBe(episode);
expect(providerLimitForHold(other, { ...scheduled, providerLimitEstimated: true }, "").episode).not.toBe(episode);
expect(providerLimitForHold({ ...other, account: null }, scheduled, "").episode).not.toBe(episode);
});
it("labels a scheduled recheck independently of what the provider reported", () => {
const retryAt = new Date(reset).toISOString();
expect(providerLimitForHold(run, { ...scheduled, providerLimitEstimated: true }, ""))
.toMatchObject({ grouping: "retry_chain", resetAt: null, retryAt, state: "scheduled" });
expect(providerLimitForHold({ ...run, account: null }, scheduled, ""))
.toMatchObject({ grouping: "retry_chain", resetAt: retryAt, state: "scheduled" });
expect(providerLimitForHold(run, scheduled, ""))
.toMatchObject({ grouping: "account_window", resetAt: retryAt });
});
it("keeps the dismissal stable across lead changes and isolates different recipients", () => {
const member = (id: string, userId: string, manual = false) => ({
id, audience: { kind: "user", userId },
providerLimit: providerLimitForHold({ ...run, runId: id },
{ ...scheduled, ...(manual && { providerLimitResume: { state: "not_requested" } }) }, ""),
} as AttentionItem);
const first = member("first", "me");
groupProviderLimits([first]);
const key = first.dismissalKey;
const manual = member("second", "me", true);
const other = member("third", "someone-else");
groupProviderLimits([first, manual, other]);
expect(first.obligationLeadId).toBe(manual.id);
expect(manual.dismissalKey).toBe(key);
expect(other.obligationLeadId).toBe(other.id);
expect(other.dismissalKey).not.toBe(key);
});
it("keeps a queued retry waiting, and a known reset without an automatic retry actionable", () => {
expect(providerLimitForHold(run, { ...scheduled, providerLimitResume: { state: "requested" } }, "").state).toBe("retry_requested");
expect(providerLimitForHold(run, { providerLimitResetAt: reset }, "Retry this task.").state).toBe("needs_retry");
expect(providerLimitForHold(run, { providerLimitResetAt: reset }, "Paperclip will retry this task then.").state).toBe("scheduled");
});
});
@@ -0,0 +1,200 @@
import { and, eq, inArray, or, sql, type SQL } from "drizzle-orm";
import { agentWakeupRequests, agents, heartbeatRuns, issueRecoveryActions, issues, type Db } from "@paperclipai/db";
import type { AttentionItem, AttentionProviderLimit, AttentionRunHistoryEntry } from "@paperclipai/shared";
import { alias } from "drizzle-orm/pg-core";
import { createHash } from "node:crypto";
import { attentionIssueCondition } from "./issue-visibility.js";
const taskId = sql<string>`coalesce(${heartbeatRuns.issueId}::text, ${heartbeatRuns.nativeIssueId}::text,
${heartbeatRuns.contextSnapshot}->>'issueId', ${heartbeatRuns.contextSnapshot}->>'taskId')`;
const account = sql<string | null>`coalesce(nullif(${heartbeatRuns.contextSnapshot}#>>'{aiConnection,subscriptionId}', ''),
nullif(${heartbeatRuns.contextSnapshot}#>>'{aiConnection,connectionId}', ''))`;
/** A reset or queued retry does not establish recovery. Keep this probe aligned with the attention resumed index. */
export const providerWorkResumed = sql<boolean>`exists(select 1 from heartbeat_runs later where later.company_id = ${heartbeatRuns.companyId}
and later.created_at > ${heartbeatRuns.createdAt} and later.status in ('running','succeeded')
and coalesce(later.issue_id::text,later.native_issue_id::text,later.context_snapshot->>'issueId',later.context_snapshot->>'taskId') = ${taskId})`;
export const usageLimitFailure = sql`(${heartbeatRuns.errorCode} in ('provider_limit_wait','native_provider_usage_limit')
or ${heartbeatRuns.resultJson}#>>'{providerFailure,category}' in ('rate_limit','quota_exhausted'))`;
export async function scheduledProviderWaits(db: Db, companyId: string) {
const retry = alias(heartbeatRuns, "scheduled_provider_retry");
const rows = await db.select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, agentId: agents.id, agentName: agents.name,
status: heartbeatRuns.status, error: heartbeatRuns.error, errorCode: heartbeatRuns.errorCode, account, taskId,
createdAt: heartbeatRuns.createdAt, updatedAt: heartbeatRuns.updatedAt, finishedAt: heartbeatRuns.finishedAt,
resetAt: sql<string | null>`coalesce(${heartbeatRuns.resultJson}#>>'{providerLimitWait,resetAt}', ${heartbeatRuns.resultJson}#>>'{providerFailure,retryAt}')`,
reported: sql<boolean>`case when ${heartbeatRuns.errorCode} = 'provider_limit_wait' then
${heartbeatRuns.resultJson}#>>'{providerLimitWait,resetReported}' = 'true' else true end`,
retryStatus: retry.status, due: retry.scheduledRetryAt }).from(retry)
.innerJoin(heartbeatRuns, and(eq(heartbeatRuns.id, retry.retryOfRunId), eq(heartbeatRuns.companyId, companyId)))
.innerJoin(agents, and(eq(agents.id, heartbeatRuns.agentId), eq(agents.companyId, companyId)))
.where(and(eq(retry.companyId, companyId), inArray(retry.status, ["scheduled_retry", "queued"]), usageLimitFailure,
sql`coalesce(${retry.issueId}::text, ${retry.nativeIssueId}::text, ${retry.contextSnapshot}->>'issueId',
${retry.contextSnapshot}->>'taskId', ${taskId}) = ${taskId}`,
sql`not ${providerWorkResumed}`));
return rows.filter(row => row.taskId).map(row => {
const limit = providerLimitForHold({ ...row, runId: row.id },
{ providerLimitResetAt: row.resetAt, providerLimitAutomatic: true, providerLimitEstimated: !row.reported }, "");
limit.retryAt = row.due?.toISOString() ?? null;
if (row.retryStatus === "queued") limit.state = "retry_requested";
return { ...row, boundTaskId: row.taskId, contextSnapshot: { issueId: row.taskId }, exhaustionMessage: null, limit };
});
}
/** Some native limit failures never emit a bounded-retry exhaustion receipt. */
export async function recoveredProviderRuns(db: Db, companyId: string, runIds: string[], readCondition: SQL) {
if (!runIds.length) return [];
return db.select({ id: heartbeatRuns.id }).from(heartbeatRuns)
.innerJoin(issues, and(eq(issues.companyId, companyId), sql`${issues.id}::text = ${taskId}`))
.where(and(eq(heartbeatRuns.companyId, companyId), inArray(heartbeatRuns.id, runIds),
eq(heartbeatRuns.errorCode, "native_provider_usage_limit"), readCondition,
or(inArray(issues.status, ["done", "cancelled"]), providerWorkResumed, sql`exists(
select 1 from ${issueRecoveryActions} hold where hold.company_id = ${heartbeatRuns.companyId}
and hold.source_issue_id = ${issues.id} and hold.evidence->>'runId' = ${heartbeatRuns.id}::text
and hold.cause = 'native_provider_usage_limit' and hold.status in ('resolved','cancelled'))`)));
}
export async function providerHoldRuns(db: Db, companyId: string, runIds: string[]) {
if (!runIds.length) return new Map<string, ProviderRun>();
const rows = await db.select({ runId: heartbeatRuns.id, agentId: agents.id, agentName: agents.name,
taskId, account, resumed: providerWorkResumed }).from(heartbeatRuns)
.innerJoin(agents, and(eq(agents.id, heartbeatRuns.agentId), eq(agents.companyId, companyId)))
.where(and(eq(heartbeatRuns.companyId, companyId), inArray(heartbeatRuns.id, runIds)));
return new Map(rows.map(row => [row.runId, row]));
}
type ProviderRun = { runId: string; agentId: string; agentName: string; account: string | null; taskId: string; resumed?: boolean };
export function providerLimitForHold(run: ProviderRun, evidence: Record<string, unknown>, nextAction: string): AttentionProviderLimit {
const reset = evidence.providerLimitResetAt;
const resetAt = typeof reset === "string" && Number.isFinite(Date.parse(reset)) ? new Date(reset).toISOString() : null;
const resume = evidence.providerLimitResume as { state?: string } | undefined;
// Older holds persisted the scheduler's promise only in its canonical next action.
const automatic = evidence.providerLimitAutomatic ?? nextAction.includes("Paperclip will retry this task");
const state = resume?.state === "requested" ? "retry_requested"
: !resume && automatic === true ? "scheduled" : "needs_retry";
const reportedReset = evidence.providerLimitEstimated || nextAction.includes("did not report") ? null : resetAt;
const sharedWindow = run.account && reportedReset;
const episode = sharedWindow ? createHash("sha256").update(JSON.stringify([run.account, resetAt])).digest("hex") : episodeForRun(run.runId);
return { episode, grouping: sharedWindow ? "account_window" : "retry_chain", attempts: 1,
resetAt: reportedReset, retryAt: state === "scheduled" ? resetAt : null, state, runId: run.runId, agentId: run.agentId, agentName: run.agentName };
}
function episodeForRun(id: string) {
return createHash("sha256").update(id).digest("hex");
}
function obligationKey(episode: string, audience: AttentionItem["audience"]) {
return `provider-limit:${episode}:${audience.kind}:${audience.userId ?? ""}`;
}
/** A retry has to link to the same task. A cooldown's source run can belong to a different task. */
export async function attachProviderRetryChains(db: Db, companyId: string, items: AttentionItem[],
dismissals: ReadonlyMap<string, unknown>) {
const members = items.filter(item => item.providerLimit?.grouping === "retry_chain");
const legacyDismissals = new Map<string, string>();
if (!members.length) return legacyDismissals;
const ids = [...new Set(members.map(item => item.providerLimit!.runId))];
// A native retry may bind a durable task retry request without setting retry_of_run_id.
const rows = await db.execute<{ run_id: string; attempts: string[] }>(sql`
with recursive chain(run_id, task_id, id, agent_id, parent_id, retry_request_id, path, limited) as (
select id, ${taskId}, id, agent_id, retry_of_run_id, context_snapshot->>'taskRetryRequestId', array[id], true
from ${heartbeatRuns}
where company_id = ${companyId} and ${inArray(heartbeatRuns.id, ids)}
union all
select c.run_id, c.task_id, r.id, r.agent_id, r.retry_of_run_id, r.context_snapshot->>'taskRetryRequestId',
c.path || r.id,
r.error_code in ('provider_limit_wait','native_provider_usage_limit')
or r.result_json#>>'{providerFailure,category}' in ('rate_limit','quota_exhausted')
from chain c
left join ${agentWakeupRequests} wake on c.parent_id is null
and wake.company_id = ${companyId} and wake.run_id = c.id and wake.agent_id = c.agent_id
and wake.id::text = c.retry_request_id and wake.reason = 'task_retry'
and wake.payload->>'issueId' = c.task_id
and wake.payload#>>'{taskRetry,schema}' = 'paperclip.task-retry.v1'
and wake.payload#>>'{taskRetry,generationId}' = c.retry_request_id
join ${heartbeatRuns} r on r.company_id = ${companyId} and r.id = coalesce(c.parent_id,
case when wake.payload#>>'{taskRetry,sourceRunId}' ~* '^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$'
then (wake.payload#>>'{taskRetry,sourceRunId}')::uuid end)
where coalesce(r.issue_id::text, r.native_issue_id::text, r.context_snapshot->>'issueId', r.context_snapshot->>'taskId') = c.task_id
and r.status in ('failed','timed_out','cancelled')
and not r.id = any(c.path)
)
select run_id, array_agg(id order by cardinality(path) desc) as attempts
from chain where limited group by run_id
`);
const byRun = new Map(rows.map(row => [row.run_id, row.attempts]));
for (const item of members) {
const limit = item.providerLimit!;
const attempts = byRun.get(limit.runId);
if (!attempts?.length) continue;
limit.episode = episodeForRun(attempts[0]!);
limit.attempts = attempts.length;
// Honor a personal archive written for an individual attempt before chain grouping.
if (!dismissals.size) continue;
const key = obligationKey(limit.episode, item.audience);
for (const runId of attempts) {
const oldKey = `attention:${obligationKey(episodeForRun(runId), item.audience)}`;
if (dismissals.has(oldKey)) {
legacyDismissals.set(key, oldKey);
break;
}
}
}
return legacyDismissals;
}
/** Group only after task access and personal routing, keeping the dismissal stable as membership changes. */
export function groupProviderLimits(items: AttentionItem[], legacyDismissals?: ReadonlyMap<string, string>) {
const groups = new Map<string, AttentionItem[]>();
for (const item of items) {
if (!item.providerLimit) continue;
const key = obligationKey(item.providerLimit.episode, item.audience);
const members = groups.get(key) ?? [];
members.push(item);
groups.set(key, members);
}
for (const [key, members] of groups) {
let lead = members.find(item => item.providerLimit?.state === "needs_retry") ?? members[0]!;
if (lead.providerLimit!.grouping === "retry_chain") {
// Old hold receipts can still be active when the next attempt records its own state.
for (const item of members) {
const difference = item.providerLimit!.attempts - lead.providerLimit!.attempts;
if (difference > 0 || (difference === 0 && item.activityAt > lead.activityAt)) lead = item;
}
}
for (const member of members) {
member.dismissalKey = legacyDismissals?.get(key) ?? `attention:${key}`;
member.obligationKey = key;
member.obligationLeadId = lead.id;
}
}
}
/** Only load diagnostic history when opened. Every run must join a task the board actor may read. */
export function attentionRunHistoryQuery(db: Db, companyId: string, readCondition: SQL, before?: { at: string; id: string }) {
return db.select({ runId: heartbeatRuns.id, agentId: agents.id, agentName: agents.name,
taskId: issues.id, taskTitle: issues.title, identifier: issues.identifier, status: issues.status,
holdStatus: issueRecoveryActions.status, recordedAt: sql<string>`to_char(${heartbeatRuns.createdAt} at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`, code: heartbeatRuns.errorCode,
resumed: providerWorkResumed })
.from(heartbeatRuns).innerJoin(issues, and(eq(issues.companyId,companyId), sql`${issues.id}::text = ${taskId}`))
.innerJoin(agents, and(eq(agents.id, heartbeatRuns.agentId), eq(agents.companyId, companyId)))
.leftJoin(issueRecoveryActions, and(eq(issueRecoveryActions.companyId, companyId), eq(issueRecoveryActions.sourceIssueId, issues.id),
sql`${issueRecoveryActions.evidence}->>'runId' = ${heartbeatRuns.id}::text`, eq(issueRecoveryActions.cause, "native_provider_usage_limit")))
.where(and(eq(heartbeatRuns.companyId,companyId),
sql`(${heartbeatRuns.status} in ('failed', 'timed_out') or ${heartbeatRuns.errorCode} = 'provider_limit_wait')`,
attentionIssueCondition(), readCondition,
before ? sql`(${heartbeatRuns.createdAt}, ${heartbeatRuns.id}) < (${before.at}::timestamptz, ${before.id}::uuid)` : undefined))
.orderBy(sql`${heartbeatRuns.createdAt} desc nulls last`, sql`${heartbeatRuns.id} desc nulls last`).limit(100);
}
export async function attentionRunHistory(db: Db, companyId: string, readCondition: SQL,
before?: { at: string; id: string }): Promise<AttentionRunHistoryEntry[]> {
const rows = await attentionRunHistoryQuery(db, companyId, readCondition, before);
return rows.map(({ status, holdStatus, recordedAt, code, resumed, ...row }) => ({ ...row, recordedAt,
reason: ["native_provider_usage_limit", "provider_limit_wait"].includes(code ?? "") ? "Provider usage limit" : "Failed run",
outcome: status === "done" ? "Task completed" : status === "cancelled" ? "Task cancelled" : resumed ? "Work resumed"
: holdStatus === "resolved" ? "Recovery resolved" : "Run recorded" }));
}
+73 -20
View File
@@ -1,9 +1,11 @@
import { attachProviderRetryChains, groupProviderLimits, recoveredProviderRuns, scheduledProviderWaits, providerHoldRuns, providerLimitForHold } from "./attention-provider-limits.js";
import { recoveryActionAttentionCondition, ATTENTION_BUDGET_WARNING_PERCENT, ATTENTION_AGENT_ERROR_STATUS, collapsePendingConfirmationsToNewest, loadNewestSettledConfirmationAt, readRunIssueId, listFailedRunsWithNewerRun, requiresReviewAttention, terminalBlockerRequiresAttention } from "./attention-source-eligibility.js";
import { approvalExecutionIssueCondition, firstApprovalIssueId } from "./approval-visibility.js";
import { and, asc, desc, eq, inArray, isNull, ne, notInArray, or, sql, type SQL } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
activityLog,
agentRuntimeState,
agents,
approvals,
assets,
@@ -1358,7 +1360,7 @@ export function resolveAttentionAudience(
/** Whether a resolved audience belongs in the requested view (PAP-749 plan §1, Rule 3). */
export function audienceMatchesView(
audience: AttentionAudience,
view: AttentionFeedView,
view: Exclude<AttentionFeedView, "waiting">,
userId: string | null | undefined,
): boolean {
switch (view) {
@@ -2105,19 +2107,36 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
recoveryActionAttentionCondition(),
))
.orderBy(desc(issueRecoveryActions.updatedAt), desc(issueRecoveryActions.id));
const [recoveryIssueMap, recoveryImageMap] = await Promise.all([
const [recoveryIssueMap, recoveryImageMap, holdRuns, scheduled] = await Promise.all([
loadIssues(recoveryRows.flatMap((row) => [row.sourceIssueId, row.recoveryIssueId])),
loadImages(db, companyId, recoveryRows.map((row) => row.sourceIssueId), readCondition),
providerHoldRuns(db, companyId, recoveryRows.flatMap(row =>
row.cause === "native_provider_usage_limit" && typeof row.evidence?.runId === "string"
&& /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(row.evidence.runId) ? [row.evidence.runId] : [])),
scheduledProviderWaits(db, companyId),
]);
const scheduledByRun = new Map(scheduled.map(run => [run.id, run.limit]));
for (const recovery of recoveryRows) {
const sourceIssue = recoveryIssueMap.get(recovery.sourceIssueId) ?? null;
if (!sourceIssue) continue;
const isProviderLimit = recovery.cause === "native_provider_usage_limit";
if (isProviderLimit && ["done", "cancelled"].includes(sourceIssue.status)) continue;
const run = isProviderLimit ? holdRuns.get(String(recovery.evidence?.runId)) : undefined;
if (run?.taskId === sourceIssue.id && run.resumed) continue;
const providerLimit = run?.taskId === sourceIssue.id
? providerLimitForHold(run, recovery.evidence, recovery.nextAction) : undefined;
const queuedRetry = run && scheduledByRun.get(run.runId);
if (providerLimit && queuedRetry) {
providerLimit.state = queuedRetry.state;
providerLimit.retryAt = queuedRetry.retryAt;
}
const recoveryIssue = recovery.recoveryIssueId ? recoveryIssueMap.get(recovery.recoveryIssueId) ?? null : null;
const dedupKey = `recovery:${recovery.kind}:${recovery.sourceIssueId}:${recovery.cause}:${recovery.fingerprint}`;
add(createItem({
companyId,
sourceKind: "recovery_action",
providerLimit,
subject: {
kind: "recovery_action",
id: recovery.id,
@@ -2158,7 +2177,7 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
}), {
issueId: recovery.sourceIssueId,
ownerUserId: recovery.ownerType === "user" ? recovery.ownerUserId : null,
companyScoped: recovery.ownerType === "board",
companyScoped: recovery.ownerType === "board" && !providerLimit,
}, {
// Escalation and a new next action are important; retry attempts
// that only move `updatedAt` are not.
@@ -2448,8 +2467,9 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
: null);
}
const failedRows = await listAttentionExhaustedRuns(db, companyId);
const failedIssueIds = failedRows.map((row) => readRunIssueId(row.contextSnapshot));
const exhausted = await listAttentionExhaustedRuns(db, companyId);
const failedRows = [...exhausted, ...scheduled];
const failedIssueIds = failedRows.map((row) => row.boundTaskId ?? readRunIssueId(row.contextSnapshot));
const [failedIssueMap, failedImageMap, failedRunsWithNewerRun] = await Promise.all([
loadIssues(failedIssueIds),
loadImages(db, companyId, failedIssueIds, readCondition),
@@ -2461,15 +2481,21 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
}))),
]);
for (const run of failedRows) {
const issueId = readRunIssueId(run.contextSnapshot);
if (failedRunsWithNewerRun.has(run.id)) continue;
const issueId = run.boundTaskId ?? readRunIssueId(run.contextSnapshot);
const scheduledLimit = scheduledByRun.get(run.id);
if (!scheduledLimit && (failedRunsWithNewerRun.has(run.id) || ("providerResumed" in run && run.providerLimited && run.providerResumed))) continue;
const issue = issueId ? failedIssueMap.get(issueId) ?? null : null;
if (issueId && !issue) continue;
if (issueId && (!issue || ["done", "cancelled"].includes(issue.status))) continue;
if (holdRuns.has(run.id) || ("settledProviderHold" in run && run.settledProviderHold)) continue;
const providerLimit = scheduledLimit ?? ("providerRetryAt" in run && issueId && run.providerLimited
? providerLimitForHold({ runId: run.id, agentId: run.agentId, agentName: run.agentName, account: run.account, taskId: issueId },
{ providerLimitResetAt: run.providerRetryAt }, "") : undefined);
const dedupKey = `run:${run.id}`;
add(createItem({
companyId,
sourceKind: "failed_run",
providerLimit,
subject: {
kind: "run",
id: run.id,
@@ -2516,12 +2542,12 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
failureReasonExcerpt: excerpt((run.error ? withoutSqlStatementText(run.error) : null) ?? run.exhaustionMessage ?? run.errorCode),
images: issueImages(failedImageMap, issueId),
},
}), { issueId, companyScoped: true }, {
}), { issueId, companyScoped: !providerLimit }, {
// Each failed run is its own card; nothing about it changes later.
content: null,
since: run.finishedAt ?? run.updatedAt ?? run.createdAt,
// Rule 11: a failed run joins the card for the task it blocks, if any.
}, issueId ? { key: `blocked:${issueId}`, anchor: false } : null);
}, issueId && !providerLimit ? { key: `blocked:${issueId}`, anchor: false } : null);
}
// A count reads the open incidents of the budget overview without the
@@ -2604,14 +2630,23 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
role: agents.role,
status: agents.status,
errorReason: agents.errorReason,
lastRunId: agentRuntimeState.lastRunId,
lastError: agentRuntimeState.lastError,
createdAt: agents.createdAt,
updatedAt: agents.updatedAt,
})
.from(agents)
.leftJoin(agentRuntimeState, and(eq(agentRuntimeState.agentId, agents.id), eq(agentRuntimeState.companyId, companyId)))
.where(and(eq(agents.companyId, companyId), eq(agents.status, ATTENTION_AGENT_ERROR_STATUS)))
.orderBy(desc(agents.updatedAt), desc(agents.id));
const knownLimitRuns = new Set(collected.flatMap(item => item.providerLimit ? [item.providerLimit.runId] : []));
const unresolvedErrors = erroredAgents.flatMap(agent => agent.lastRunId && !knownLimitRuns.has(agent.lastRunId)
? [agent.lastRunId] : []);
for (const run of await recoveredProviderRuns(db, companyId, unresolvedErrors, readCondition)) knownLimitRuns.add(run.id);
for (const agent of erroredAgents) {
if (agent.lastRunId && knownLimitRuns.has(agent.lastRunId) && agent.lastError && agent.errorReason
&& (agent.errorReason === agent.lastError || agent.errorReason === agent.lastError.slice(0, 499) + "…")) continue;
const dedupKey = `agent_error:${agent.id}`;
add(createItem({
companyId,
@@ -2655,8 +2690,13 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
}
const providerTasks = new Set(collected.flatMap(item => item.providerLimit && item.relatedIssue ? [item.relatedIssue.id] : []));
const deduped = new Map<string, AttentionItem>();
for (const item of collected) {
// The active hold already explains this terminal task's stalled path. An
// explicit unblock request has its own key and stays independently actionable.
if (item.sourceKind === "blocker_attention" && item.dedupKey === `blocker:${item.subject.id}`
&& providerTasks.has(item.subject.id)) continue;
const current = deduped.get(item.dedupKey);
deduped.set(item.dedupKey, current ? betterDuplicate(current, item) : item);
}
@@ -2710,13 +2750,15 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
// Rule 11: one card for each obligation. Members share one placement, so
// the fingerprint below reads the obligation's audience.
assignAttentionObligations(currentItems, obligationHintByDedupKey);
const legacyLimitDismissals = await attachProviderRetryChains(db, companyId, currentItems, dismissals);
groupProviderLimits(currentItems, legacyLimitDismissals);
for (const item of currentItems) {
// A count reads a fingerprint only to compare it with a dismissal.
if (summaryOnly && !dismissals.has(item.dismissalKey)) continue;
const change = changeBasisByDedupKey.get(item.dedupKey) ?? { content: null, since: item.createdAt };
item.changeFingerprint = attentionChangeFingerprint({
sourceKind: item.sourceKind,
content: change.content,
sourceKind: item.providerLimit ? "recovery_action" : item.sourceKind,
content: item.providerLimit ? { needsRetry: item.providerLimit.state === "needs_retry" } : change.content,
forViewer: item.audience.kind === "user" && item.audience.userId != null
&& item.audience.userId === options.userId,
});
@@ -2749,17 +2791,19 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
const enrichedById = new Map(enrichedItems.map((item) => [item.id, item]));
const obligationLeadOf = (item: AttentionItem) =>
isObligationEvidence(item) ? enrichedById.get(item.obligationLeadId!) ?? item : item;
const automatic = (item: AttentionItem) => Boolean(item.providerLimit && item.providerLimit.state !== "needs_retry");
const waitingForViewer = (item: AttentionItem) => hiddenForViewer(item)
? item.dismissal?.kind === "snooze"
: automatic(item) && (item.audience.kind !== "user" || item.audience.userId === options.userId);
const visibleItems = enrichedItems.filter((member) => {
const item = obligationLeadOf(member);
if (view === "archived") {
// The person's own Archived view (PAP-749 plan §3): open cards they
// archived or snoozed, and nothing else.
if (view === "waiting") {
if (!waitingForViewer(item)) return false;
} else if (view === "archived") {
if (!hiddenForViewer(item)) return false;
} else {
// `all` (the default) keeps the pre-PAP-749 superset; the other views
// partition by resolved audience (PAP-749 plan §1, Rule 3).
if (view !== "all" && !audienceMatchesView(item.audience, view, options.userId)) return false;
if (!includeDismissed && hiddenForViewer(item)) return false;
if (!includeDismissed && (hiddenForViewer(item) || automatic(item))) return false;
}
if (options.archived === true ? !item.archivedAt : Boolean(item.archivedAt)) return false;
if (!includeDismissed && item.snoozedUntil && timestamp(item.snoozedUntil) > now) return false;
@@ -2778,22 +2822,29 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
// three audience views and Everyone skip the cards this person archived
// or snoozed; the Archived tab counts exactly those (plan §3). Only For
// you is the badge. Each obligation counts once, as its lead (Rule 11).
let waitingCount = 0;
let nextSnoozeAt: string | null = null;
const viewCounts: AttentionViewCounts = { mine: 0, unassigned: 0, company: 0, archived: 0, all: 0 };
for (const item of enrichedItems) {
if (obligationLeadOf(item) !== item) continue;
if (item.archivedAt) continue;
if (item.snoozedUntil && timestamp(item.snoozedUntil) > now) continue;
if (waitingForViewer(item)) waitingCount++;
if (hiddenForViewer(item)) {
viewCounts.archived += 1;
const until = item.dismissal?.snoozedUntil;
if (until && (!nextSnoozeAt || until < nextSnoozeAt)) nextSnoozeAt = until;
continue;
}
if (automatic(item)) continue;
for (const countedView of ATTENTION_PERSONAL_VIEWS) {
if (countedView === "archived") continue;
if (audienceMatchesView(item.audience, countedView, options.userId)) viewCounts[countedView] += 1;
}
}
const summary: AttentionSummary = { companyId, generatedAt: new Date().toISOString(), totalCount: visibleItems.length, deskBadgeCount: viewCounts.mine, viewCounts, countsBySourceKind };
const waiting = { ...(waitingCount ? { waitingCount } : {}), ...(nextSnoozeAt ? { nextSnoozeAt } : {}) };
const summary: AttentionSummary = { companyId, ...waiting, generatedAt: new Date().toISOString(), totalCount: visibleItems.length, deskBadgeCount: viewCounts.mine, viewCounts, countsBySourceKind };
if (summaryOnly) return { ...summary, nextCursor: null, items: visibleItems };
const sort = options.sort ?? "activity";
@@ -2871,6 +2922,7 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
companyId,
generatedAt: new Date().toISOString(),
totalCount: rankedItems.length,
...waiting,
// The badge is the "For you" count. It has no day boundary: an open
// card stays in it until a person answers it.
deskBadgeCount: viewCounts.mine,
@@ -3019,7 +3071,8 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
throw unprocessable("This card cannot be hidden.", { code: "attention_close_mode_unsupported", closeModes: item.closeModes });
}
// The version the person saw; the card returns when its content differs.
const fingerprint = item.id === requested?.id ? input.fingerprint ?? item.changeFingerprint : item.changeFingerprint;
const fingerprint = item.providerLimit || item.id === requested?.id
? input.fingerprint ?? item.changeFingerprint : item.changeFingerprint;
const dismissals = inboxDismissalService(db);
const dismissal = input.mode === "snooze"
? await dismissals.snooze(companyId, input.userId, item.dismissalKey, new Date(input.until!), new Date(), fingerprint)
@@ -13903,6 +13903,8 @@ async function executePaperclipNativeSessionAttempt(
recoveryEvidence.providerSessionEstablished,
...(providerCooldownAt ? { providerCooldownAt: providerCooldownAt.toISOString() } : {}),
...(providerLimit?.plan.resetAt ? { providerLimitResetAt: providerLimit.plan.resetAt.toISOString() } : {}),
...(providerLimit ? { providerLimitAutomatic: providerLimit.plan.automatic,
providerLimitEstimated: providerLimit.plan.estimated === true } : {}),
...(providerLimit && startupProviderLimit ? { providerLimitStartup: {
failure: outputRedactor.redact(startupProviderLimit.failure),
observedAt: startupProviderLimit.observedAt.toISOString(),
@@ -9,6 +9,7 @@ import {
} from "@paperclipai/db";
import { readProviderFailure, type ProviderFailure } from "@paperclipai/shared";
import { HttpError } from "../../errors.js";
import { persistActivity, publishActivity } from "../activity-log.js";
import { logger } from "../../middleware/logger.js";
import type { createDeliveryWorkCoordinator } from "../delivery-work-coordinator.js";
import { DELIVERY_QUEUES } from "../delivery-work-notifications.js";
@@ -165,11 +166,20 @@ type Outcome =
| { requested: false; reason: string };
async function settle(db: Db, actionId: string, state: Record<string, unknown>, nextAction?: string) {
await db.update(issueRecoveryActions).set({
evidence: sql`coalesce(${issueRecoveryActions.evidence}, '{}'::jsonb) || jsonb_build_object('providerLimitResume', ${JSON.stringify(state)}::jsonb)`,
...(nextAction ? { nextAction } : {}),
updatedAt: new Date(),
}).where(and(eq(issueRecoveryActions.id, actionId), sql`${issueRecoveryActions.evidence}->'providerLimitResume' is null`));
const publication = await db.transaction(async tx => {
const [changed] = await tx.update(issueRecoveryActions).set({
evidence: sql`coalesce(${issueRecoveryActions.evidence}, '{}'::jsonb) || jsonb_build_object('providerLimitResume', ${JSON.stringify(state)}::jsonb)`,
...(nextAction ? { nextAction } : {}),
updatedAt: new Date(),
}).where(and(eq(issueRecoveryActions.id, actionId), sql`${issueRecoveryActions.evidence}->'providerLimitResume' is null`))
.returning({ companyId: issueRecoveryActions.companyId, taskId: issueRecoveryActions.sourceIssueId });
if (!changed) return null;
const result = await persistActivity(tx as unknown as Db, { companyId: changed.companyId, actorType: "system",
actorId: "recovery", action: "issue.provider_limit_retry_settled", entityType: "issue", entityId: changed.taskId,
details: { state: state.state, reason: state.reason ?? null } });
return result.publication;
});
if (publication) publishActivity(publication);
}
/** Why Paperclip did not retry after a reset it announced; the Retry stays.
@@ -220,7 +230,7 @@ export async function requestProviderLimitResumeRetry(db: Db, input: {
// Retry to the user; it never promised an automatic one.
await db.update(issueRecoveryActions).set({
nextAction: providerLimitNextAction({ automatic: false, resetAt: reset.resetAt }),
evidence: sql`coalesce(${issueRecoveryActions.evidence}, '{}'::jsonb) || jsonb_build_object('providerLimitResetAt', ${reset.resetAt.toISOString()}::text)`,
evidence: sql`coalesce(${issueRecoveryActions.evidence}, '{}'::jsonb) || jsonb_build_object('providerLimitResetAt', ${reset.resetAt.toISOString()}::text, 'providerLimitAutomatic', false)`,
updatedAt: now,
}).where(and(eq(issueRecoveryActions.id, action.id), eq(issueRecoveryActions.status, "active")));
await settle(db, action.id, { state: "not_requested", reason: "reset_beyond_wait", resetAt: reset.resetAt.toISOString(),
@@ -235,7 +245,7 @@ export async function requestProviderLimitResumeRetry(db: Db, input: {
nextAction: providerLimitNextAction(actorId
? { automatic: true, resetAt: reset.resetAt, actorId, estimated: reset.estimated }
: { automatic: false, resetAt: reset.resetAt, estimated: reset.estimated }),
evidence: sql`coalesce(${issueRecoveryActions.evidence}, '{}'::jsonb) || jsonb_build_object('providerLimitResetAt', ${reset.resetAt.toISOString()}::text)`,
evidence: sql`coalesce(${issueRecoveryActions.evidence}, '{}'::jsonb) || jsonb_build_object('providerLimitResetAt', ${reset.resetAt.toISOString()}::text, 'providerLimitAutomatic', ${!!actorId}::boolean, 'providerLimitEstimated', ${!!reset.estimated}::boolean)`,
updatedAt: now,
}).where(and(eq(issueRecoveryActions.id, action.id), eq(issueRecoveryActions.status, "active")));
}