diff --git a/DESIGN.md b/DESIGN.md index 80a019d05f3..23cb31ff750 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1105,6 +1105,13 @@ Further consolidation proposals, pending visual review: ### Collection empty states and roster selection +Center the empty-state artwork, labels and actions together in the space below +the page controls. The default artwork is the 200px square Paperclip mark in +the muted surface color. Collections with dedicated illustrations use their +own artwork in the same position. In Goals, Routines, Secrets and Inbox, center +the group horizontally and place its midpoint 35% down the available space. +On short screens, keep the full group and its action accessible. + Projects uses the large artifact stack with a dark grey Paperclip mark on an off-white image front. The empty-state action is “Create project”. Artwork, message and primary action have 20px gaps (`gap-5`). Hovering or keyboard-focusing the action diff --git a/doc/PRODUCT.md b/doc/PRODUCT.md index f1c7c3ff82f..b7d28e23681 100644 --- a/doc/PRODUCT.md +++ b/doc/PRODUCT.md @@ -534,7 +534,20 @@ Coordinator navigation uses **Chat**, **Tasks**, and **Inbox**. Inbox uses the inbox icon and keeps the existing decision feed, its count, and decision history at `/decisions`. The previous Inbox destination under More is removed. -Inbox opens with **Assigned to you**. Its assignee filter can show all accessible +Inbox opens to **Needs you** with **Assigned to you** selected. Its badge counts +personal actions. **Waiting** shows scheduled provider retries and personal +snoozes. A provider limit with a known account and reset appears once per +recipient, with the affected tasks, agents and run logs inside. When the account or +reported reset is unknown, each task’s linked retry attempts share one card. +Automatic retries update its attempt count and preserve a personal archive. +A collapsible group brings these task cards together. Each card shows its own +retry state and distinguishes a scheduled recheck from a reported reset. Exhausted retries +return to Needs you when someone must act. Resumed or closed tasks leave the +group. **History** includes decision receipts and failed or +provider-held runs on accessible tasks. Open a card’s ellipsis menu to choose +**Archive for me**. The confirmation offers **Undo**. Archiving a provider episode covers later failures in the same +window until the required action changes. Personal archive leaves approvals pending. +The assignee filter can show all accessible assignees, a particular person, ownerless requests, or company alerts. Cards for someone else prepend that person's name to the action label; your own cards omit your name. Routing validates who may reassign a request and whether its recipient diff --git a/doc/testing/coordinator-inbox-test-drive.md b/doc/testing/coordinator-inbox-test-drive.md new file mode 100644 index 00000000000..edac3286903 --- /dev/null +++ b/doc/testing/coordinator-inbox-test-drive.md @@ -0,0 +1,48 @@ +# Coordinator Inbox manual test + +Open [Inbox Test Drive](http://127.0.0.1:3917/IBX/decisions). The local board user has one launch approval. Two synthetic agents have hit the same provider account’s five-hour limit on four tasks, three failed attempts per task. The fixture uses recorded provider outcomes. No model account is needed. + +Open a terminal at the root of this checkout. Paste the function below, press Return, and keep that terminal open for the walkthrough. Run each `inbox_demo` command there, then switch back to the browser and refresh. + +```sh +inbox_demo() { + node --import ./server/node_modules/tsx/dist/loader.mjs server/scripts/inbox-test-drive.ts "$1" +} +``` + +| Step | Action | Expected result | +| --- | --- | --- | +| 1 | Run `inbox_demo reset` and reload **Needs you**. | One launch approval, sidebar badge **1**, and **Waiting · 1**. | +| 2 | Open **Waiting** and expand **View 4 tasks**. Follow a run log, then go back. | One usage-limit row, a retry time, four task links, agent names, and individual run links. **History** contains the twelve failed runs. | +| 3 | In **Needs you**, open the approval’s **⋯** menu and choose **Archive for me**. Reload. Open **View → Archived** and restore it from its menu. Archive it again and click **Undo** in the toast. | Archiving clears the badge and survives reload. Restore and Undo each bring back the pending approval. | +| 4 | On the approval, choose **⋯ → Snooze for me → Tomorrow morning**. | **Needs you** is empty, the badge clears, and **Waiting** contains the snoozed approval and the provider limit. | +| 5 | Open [Waiting](http://127.0.0.1:3917/IBX/decisions?folder=waiting). On the card with **View 4 tasks**, choose **⋯ → Archive for me**. Once the card disappears, run `inbox_demo repeat` in the terminal. Open [Archived](http://127.0.0.1:3917/IBX/decisions?view=archived) and click **View 5 tasks**. | **IBX-5 Summarize test results** appears in the archived group. The repeat failure leaves the group archived. Waiting shows the approval if you snoozed it in step 4. | +| 6 | Run `inbox_demo one-left`, open **Needs you**, and refresh. | The episode returns as **1 task needs a retry after the usage limit**. The badge is **1**. **Open task to retry** leads to IBX-4. | +| 7 | Run `inbox_demo all-recovered` and refresh **Needs you**. | The retry row clears automatically. The badge clears. In **History**, IBX-1 shows **Work resumed** because its retry succeeded. Opening IBX-1 shows **Todo** because the task is still open and no run is active. IBX-4 shows **Task completed** in History. | +| 8 | In **Waiting**, open the snoozed approval’s menu and choose **Restore now**. Go to **Needs you** and approve the launch plan. | The approval leaves the inbox, the badge clears, and the decision appears in **History**. | +| 9 | Run `inbox_demo reset` and refresh. | The original approval and four-task waiting group are ready for another pass. | + +The fixture commands write synthetic outcomes directly into the isolated embedded database, so refresh after running one. Actions taken in the UI update the inbox immediately. Reset targets the fixture company in this checkout’s `tmp/inbox-drive` database and clears the local board user’s dismissals for that company. + +## Test retries with an unknown reset + +These commands use a separate synthetic company. Refresh the page after each command. + +1. Run `inbox_demo chains` and open [Retry Chain Test Drive → Waiting](http://127.0.0.1:3917/RCH/decisions?folder=waiting). Expand **3 tasks hit usage limits**. Each task has its own retry time and says **Reset time unknown**. +2. Archive **RCH-1** using its ellipsis menu. Run `inbox_demo chains-repeat`. Waiting still has two tasks. In **View → Archived**, RCH-1 now shows **4 attempts**. +3. Run `inbox_demo chains-exhausted`. Only RCH-1 appears in **Needs you**. The two other tasks remain in **Waiting**. +4. Run `inbox_demo chains-recovered`. RCH-2 leaves Waiting automatically. RCH-3 is the only waiting card. Run `inbox_demo chains` to reset this example. + +## Restart the local server + +From this checkout, with port 3917 free, run the following in a terminal and leave it open. + +```sh +env -u DATABASE_URL -u DATABASE_MIGRATION_URL -u PAPERCLIP_CONFIG \ + PAPERCLIP_HOME="$PWD/tmp/inbox-drive" PAPERCLIP_INSTANCE_ID=default \ + PAPERCLIP_DISABLE_CWD_ENV_FILE=true PAPERCLIP_UI_DEV_MIDDLEWARE=true \ + PAPERCLIP_MIGRATION_AUTO_APPLY=true PAPERCLIP_OPEN_ON_LISTEN=false \ + PAPERCLIP_TELEMETRY_DISABLED=1 PAPERCLIP_DEPLOYMENT_MODE=local_trusted \ + HOST=127.0.0.1 PAPERCLIP_BIND=loopback HEARTBEAT_SCHEDULER_ENABLED=false PORT=3917 \ + pnpm --filter @paperclipai/server exec tsx watch src/index.ts +``` diff --git a/docs/api/attention.md b/docs/api/attention.md index 3fda0cd3926..99756b0581b 100644 --- a/docs/api/attention.md +++ b/docs/api/attention.md @@ -20,7 +20,7 @@ The feed accepts these query parameters: | Parameter | Meaning | | --- | --- | -| `view` | `mine`, `unassigned`, `company`, `archived`, or `all`. The API default is `all`. | +| `view` | `mine`, `unassigned`, `company`, `waiting`, `archived`, or `all`. The API default is `all`. | | `includeDismissed` | Include personally hidden cards. Default: `false`. | | `archived` | Read retained source archives instead of current sources. This differs from personal `view=archived`. | | `all` | Return a complete snapshot instead of a page. | @@ -35,6 +35,15 @@ and counts once. `deskBadgeCount` counts requests assigned to the viewer. Summary returns the same current counts without card bodies. Tasks also returns unique `taskIds` for visible requests. Neither endpoint returns card bodies. +`view=waiting` returns automatic provider retries visible to the caller and +cards the caller has snoozed. The optional `waitingCount` counts waiting cards. +The optional `nextSnoozeAt` gives the earliest active snooze expiry. +A provider-limit card carries `providerLimit`. Its `grouping` is +`account_window` for a verified account and reset, or `retry_chain` for +linked attempts on one task. Its `state` is `scheduled`, `retry_requested`, +or `needs_retry`. The provider's `resetAt` and Paperclip's scheduled +`retryAt` can each be null. + Routing uses explicit recipients, chat ownership, review participants, task assignees, human instigators, and configured decision owners. A card with no owner enters Unassigned. After seven days it moves to Company. A required @@ -113,6 +122,25 @@ for the caller. Filters include `search`, `outcome`, `agentId`, `projectId`, Withdrawn requests, expired requests, and requests closed with their task have separate outcomes. Personal archive and snooze do not record consent. +## Recent run history + +```text +GET /api/companies/{companyId}/attention/run-history +``` + +Returns a JSON array of up to 100 failed, timed-out, or provider-held runs +on tasks the board user can read. Each entry includes `runId`, `agentId`, +`agentName`, `taskId`, `taskTitle`, `identifier`, `recordedAt`, `reason`, +and `outcome`. Rows are ordered by run creation time, newest first, then by +run ID descending when times match. + +Omit query parameters for the first page. For the next page, pass the last +row’s exact `recordedAt` string as `at` and its `runId` as `id`. Keep the +timestamp’s fractional seconds. The next page starts after that row. A page +with fewer than 100 rows is the last page. A partial or invalid cursor returns +HTTP 400. Each company and board user can make up to 60 run-history +requests per minute. HTTP 429 includes a `Retry-After` header in seconds. + ## Errors | Status | Meaning | diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index 0eb26a89333..71d713489dd 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -921,6 +921,7 @@ const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set([ "0384_funny_adam_warlock.sql", "0383_tool_review_company_expiry.sql", "0505_nice_rawhide_kid.sql", + "0508_normal_riptide.sql", "0507_special_kang.sql", ]); diff --git a/packages/db/src/migrations/0508_normal_riptide.sql b/packages/db/src/migrations/0508_normal_riptide.sql new file mode 100644 index 00000000000..aa05b678209 --- /dev/null +++ b/packages/db/src/migrations/0508_normal_riptide.sql @@ -0,0 +1,3 @@ +CREATE INDEX CONCURRENTLY IF NOT EXISTS "heartbeat_runs_attention_resumed_idx" ON "heartbeat_runs" USING btree ("company_id",coalesce("issue_id"::text, "native_issue_id"::text, + "context_snapshot"->>'issueId', "context_snapshot"->>'taskId'),"created_at") WHERE "heartbeat_runs"."status" in ('running', 'succeeded');--> statement-breakpoint +CREATE INDEX CONCURRENTLY IF NOT EXISTS "heartbeat_runs_attention_history_idx" ON "heartbeat_runs" USING btree ("company_id","created_at" DESC NULLS LAST,"id" DESC NULLS LAST) WHERE "heartbeat_runs"."status" in ('failed', 'timed_out') or "heartbeat_runs"."error_code" = 'provider_limit_wait'; diff --git a/packages/db/src/migrations/meta/0503_snapshot.json b/packages/db/src/migrations/meta/0508_snapshot.json similarity index 99% rename from packages/db/src/migrations/meta/0503_snapshot.json rename to packages/db/src/migrations/meta/0508_snapshot.json index f4e1db1e606..b63b08c8692 100644 --- a/packages/db/src/migrations/meta/0503_snapshot.json +++ b/packages/db/src/migrations/meta/0508_snapshot.json @@ -1,6 +1,6 @@ { - "id": "6d216ee0-8a1e-45e1-a71a-38c1e51b0ec1", - "prevId": "e7daf0b9-3e4a-42d7-b72a-4d7d413d9686", + "id": "8ddb0345-f9e8-4dde-8156-391f71d858b1", + "prevId": "2f88a046-845e-47f5-ad81-b3b338c79fb5", "version": "7", "dialect": "postgresql", "tables": { @@ -3313,6 +3313,153 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.agent_setup_progress": { + "name": "agent_setup_progress", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "purpose": { + "name": "purpose", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_id": { + "name": "subject_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'waiting'" + }, + "items": { + "name": "items", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "update_count": { + "name": "update_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "agent_setup_progress_company_idx": { + "name": "agent_setup_progress_company_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "agent_setup_progress_expires_idx": { + "name": "agent_setup_progress_expires_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "agent_setup_progress_company_id_companies_id_fk": { + "name": "agent_setup_progress_company_id_companies_id_fk", + "tableFrom": "agent_setup_progress", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "agent_setup_progress_status_check": { + "name": "agent_setup_progress_status_check", + "value": "\"agent_setup_progress\".\"status\" in ('waiting', 'in_progress', 'done', 'failed')" + } + }, + "isRLSEnabled": false + }, "public.agent_session_goal_actions": { "name": "agent_session_goal_actions", "schema": "", @@ -10448,6 +10595,40 @@ "method": "btree", "with": {} }, + "chat_actions_github_task_publications_idx": { + "name": "chat_actions_github_task_publications_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "endpoint_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "(\"payload\"->'session'->>'issueId')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"chat_actions\".\"kind\" = 'github_review_publication' and \"chat_actions\".\"status\" = 'processed'", + "concurrently": true, + "method": "btree", + "with": {} + }, "chat_actions_github_terminal_work_idx": { "name": "chat_actions_github_terminal_work_idx", "columns": [ @@ -36558,6 +36739,62 @@ "method": "btree", "with": {} }, + "heartbeat_runs_attention_resumed_idx": { + "name": "heartbeat_runs_attention_resumed_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"issue_id\"::text, \"native_issue_id\"::text,\n \"context_snapshot\"->>'issueId', \"context_snapshot\"->>'taskId')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"heartbeat_runs\".\"status\" in ('running', 'succeeded')", + "concurrently": true, + "method": "btree", + "with": {} + }, + "heartbeat_runs_attention_history_idx": { + "name": "heartbeat_runs_attention_history_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": false, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"heartbeat_runs\".\"status\" in ('failed', 'timed_out') or \"heartbeat_runs\".\"error_code\" = 'provider_limit_wait'", + "concurrently": true, + "method": "btree", + "with": {} + }, "heartbeat_runs_company_ctx_issue_created_idx": { "name": "heartbeat_runs_company_ctx_issue_created_idx", "columns": [ @@ -59978,6 +60215,28 @@ "concurrently": false, "method": "btree", "with": {} + }, + "tool_call_events_connection_error_idx": { + "name": "tool_call_events_connection_error_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"tool_call_events\".\"error_message\" is not null", + "concurrently": false, + "method": "btree", + "with": {} } }, "foreignKeys": { @@ -60819,6 +61078,13 @@ "notNull": true, "default": "'pending'" }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'requested'" + }, "requested_by_actor_type": { "name": "requested_by_actor_type", "type": "text", @@ -60858,6 +61124,12 @@ "primaryKey": false, "notNull": false }, + "not_before": { + "name": "not_before", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, "completed_at": { "name": "completed_at", "type": "timestamp with time zone", @@ -62417,6 +62689,28 @@ "method": "btree", "with": {} }, + "tool_invocations_connection_error_idx": { + "name": "tool_invocations_connection_error_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"tool_invocations\".\"error_message\" is not null", + "concurrently": false, + "method": "btree", + "with": {} + }, "tool_invocations_company_idempotency_uq": { "name": "tool_invocations_company_idempotency_uq", "columns": [ diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index 52378cb2cad..a07a97e8f92 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -3543,6 +3543,13 @@ "when": 1795561452000, "tag": "0507_special_kang", "breakpoints": true + }, + { + "idx": 508, + "version": "7", + "when": 1795572002132, + "tag": "0508_normal_riptide", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/heartbeat_runs.ts b/packages/db/src/schema/heartbeat_runs.ts index 72ce4e56c22..3cea7549134 100644 --- a/packages/db/src/schema/heartbeat_runs.ts +++ b/packages/db/src/schema/heartbeat_runs.ts @@ -264,6 +264,16 @@ export const heartbeatRuns = pgTable( table.companyId, table.createdAt.desc(), ), + // Inbox recovery checks look for a newer successful or running attempt on the same task. + attentionResumedIdx: index("heartbeat_runs_attention_resumed_idx") + .on(table.companyId, sql`coalesce(${table.issueId}::text, ${table.nativeIssueId}::text, + ${table.contextSnapshot}->>'issueId', ${table.contextSnapshot}->>'taskId')`, table.createdAt) + .where(sql`${table.status} in ('running', 'succeeded')`) + .concurrently(), + attentionHistoryIdx: index("heartbeat_runs_attention_history_idx") + .on(table.companyId, table.createdAt.desc(), table.id.desc()) + .where(sql`${table.status} in ('failed', 'timed_out') or ${table.errorCode} = 'provider_limit_wait'`) + .concurrently(), companyCtxIssueCreatedIdx: index("heartbeat_runs_company_ctx_issue_created_idx").on( table.companyId, sql`(${table.contextSnapshot} ->> 'issueId')`, diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index afbe3d16f13..4be2761402a 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -201,6 +201,8 @@ export type { AttentionTaskIndex, AttentionFeedView, AttentionItem, + AttentionProviderLimit, + AttentionRunHistoryEntry, AttentionItemDetail, AttentionItemDismissal, AttentionFeedQuery, diff --git a/packages/shared/src/types/attention.ts b/packages/shared/src/types/attention.ts index bd6fdf6938c..ac112c8e57d 100644 --- a/packages/shared/src/types/attention.ts +++ b/packages/shared/src/types/attention.ts @@ -278,7 +278,7 @@ export interface AttentionAudience { * cards (PAP-749 plan §3): open cards they archived or snoozed, read from * their `inbox_dismissals`, whatever the card's audience. */ -export type AttentionFeedView = "mine" | "unassigned" | "company" | "archived" | "all"; +export type AttentionFeedView = "waiting" | "mine" | "unassigned" | "company" | "archived" | "all"; /** * The views the Decisions pages switch between (PAP-749 plan §1, Rule 3; §3): @@ -561,7 +561,33 @@ export function attentionCardType(item: Pick 65535) throw new Error("Start the isolated dev server first"); +const url = `postgres://paperclip:paperclip@127.0.0.1:${port}/paperclip`; +if (realpathSync((await getPostgresDataDirectory(url))!) !== dir) throw new Error("Unexpected database directory"); +const db = createDb(url); +const id = (n: number) => `1b0a0000-0000-4000-8000-${String(n).padStart(12, "0")}`; +const companyId = id(1); +const userId = "local-board"; +const titles = ["Review the launch checklist", "Draft release notes", "Check help links", "Prepare the handoff", "Summarize test results"]; +try { + await db.transaction(async tx => { + async function ensurePausedAgent(ownerId: string, agentId: string, name: string) { + const [existing] = await tx.select({ companyId: agents.companyId }).from(agents).where(eq(agents.id, agentId)); + if (existing) { + if (existing.companyId !== ownerId) throw new Error("Fixture agent belongs to another company"); + return; + } + await requestAgentHireInTransaction(tx as unknown as Db, [], ownerId, { + id: agentId, name, status: "paused", adapterType: "process", adapterConfig: { command: "echo" }, + runtimeConfig: { heartbeat: { enabled: false } }, + }, { createdByUserId: userId }); + } + if (chainPhases.includes(phase)) { + const demoId = id(1000); + const [demo] = await tx.select().from(companies).where(eq(companies.id, demoId)); + if (demo && (demo.name !== "Retry Chain Test Drive" || demo.issuePrefix !== "RCH")) throw new Error("Fixture identity mismatch"); + if (!demo && phase !== "chains") throw new Error("Run chains first"); + await tx.insert(companies).values({ id: demoId, name: "Retry Chain Test Drive", issuePrefix: "RCH", + issueCounter: 3, defaultDecisionOwnerUserId: userId }).onConflictDoNothing(); + await tx.insert(companyMemberships).values({ companyId: demoId, principalType: "user", principalId: userId, + membershipRole: "owner" }).onConflictDoNothing(); + const agentId = id(1001); + await ensurePausedAgent(demoId, agentId, "Reviewer"); + if (phase === "chains") await tx.delete(inboxDismissals).where(and(eq(inboxDismissals.companyId, demoId), eq(inboxDismissals.userId, userId))); + for (let n = 1; n <= 3; n++) { + const issueId = id(1010 + n); + const recovered = phase === "chains-recovered" && n === 2; + const manual = phase === "chains-exhausted" || phase === "chains-recovered"; + const status = recovered ? "done" : "blocked"; + await tx.insert(issues).values({ id: issueId, companyId: demoId, issueNumber: n, identifier: `RCH-${n}`, + title: titles[n-1]!, createdByUserId: userId, responsibleUserId: userId, assigneeAgentId: agentId, status }) + .onConflictDoUpdate({ target: issues.id, set: { status } }); + const attempts = n === 1 ? (phase === "chains" ? 3 : 4) : 1; + let parent: string | null = null; + for (let attempt = 1; attempt <= attempts; attempt++) { + const runId = id(1100 + 10 * n + attempt); + await tx.insert(heartbeatRuns).values({ id: runId, companyId: demoId, agentId, issueId, scopeKind: "issue", + status: "failed", errorCode: "native_provider_usage_limit", retryOfRunId: parent }).onConflictDoNothing(); + parent = runId; + } + const evidence = { runId: parent, providerLimitAutomatic: true, providerLimitEstimated: true, + providerLimitResetAt: new Date(Date.now() + n * 3600_000).toISOString(), + ...(manual && n === 1 && { providerLimitResume: { state: "not_requested", reason: "automatic_retry_budget_used" } }) }; + const holdStatus = recovered ? "resolved" : "active"; + await tx.insert(issueRecoveryActions).values({ id: id(1200+n), companyId: demoId, sourceIssueId: issueId, + kind: "active_run_watchdog", ownerType: "board", cause: "native_provider_usage_limit", fingerprint: issueId, + evidence, status: holdStatus, nextAction: "Check the provider limit on this task." }) + .onConflictDoUpdate({ target: issueRecoveryActions.id, set: { evidence, status: holdStatus, updatedAt: new Date() } }); + } + return; + } + const [existing] = await tx.select().from(companies).where(eq(companies.id,companyId)); + if (existing && (existing.name !== "Inbox Test Drive" || existing.issuePrefix !== "IBX")) throw new Error("Fixture identity mismatch"); + if (phase !== "reset" && !existing) throw new Error("Run reset first"); + const now = new Date(); + if (phase === "reset") { + await tx.insert(companies).values({ id: companyId, name: "Inbox Test Drive", issuePrefix: "IBX", issueCounter: 5, + defaultDecisionOwnerUserId: userId }).onConflictDoNothing(); + await tx.insert(companyMemberships).values({ companyId, principalType: "user", principalId: userId, membershipRole: "owner" }).onConflictDoNothing(); + await tx.insert(approvals).values({ id: id(2), companyId, requestedByUserId: userId, type: "approve_ceo_strategy", + payload: { title: "Approve the launch plan", plan: "Release the synthetic inbox after review." } }) + .onConflictDoUpdate({ target: approvals.id, set: { status: "pending", decidedAt: null, decidedByUserId: null, updatedAt: now } }); + await tx.delete(inboxDismissals).where(and(eq(inboxDismissals.companyId, companyId), eq(inboxDismissals.userId,userId))); + await tx.delete(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId,companyId), eq(issueRecoveryActions.id,id(405)))); + await tx.update(issues).set({ status: "done", hiddenAt: now }).where(and(eq(issues.companyId, companyId),eq(issues.id,id(105)))); + } + const [first] = await tx.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id,id(401))); + const resetAt = phase === "reset" ? new Date(+now + 5 * 3600_000).toISOString() : String(first?.evidence.providerLimitResetAt); + for (let n = 1; n <= (phase === "repeat" ? 5 : 4); n++) { + if (phase === "repeat" && n < 5) continue; + const agentId = id(10 + ((n-1) % 2)); + const issueId = id(100+n); + const runId = id(350+n); + const recovered = phase === "all-recovered" || (phase === "one-left" && n < 4); + const manual = phase === "one-left" && n === 4; + const resumed = recovered && n === 1; + const taskStatus = resumed ? "in_progress" : recovered ? "done" : "blocked"; + await ensurePausedAgent(companyId, agentId, n % 2 ? "Editor" : "Reviewer"); + await tx.insert(issues).values({ id: issueId, companyId, issueNumber:n, identifier:`IBX-${n}`, title: titles[n-1]!, + createdByUserId: userId, responsibleUserId: userId, assigneeAgentId: agentId, status: taskStatus }) + .onConflictDoUpdate({ target: issues.id, set: { status: taskStatus, hiddenAt: null, updatedAt: now } }); + const failure = { schema:"paperclip.provider-failure.v1", provider:"openai", phase:"startup", category:"quota_exhausted", + retryability:"requires_action", message:"Five-hour usage limit reached", retryAt:resetAt }; + for (let attempt = phase === "repeat" ? 2 : 0; attempt < 3; attempt++) { + const attemptId = attempt === 2 ? runId : id(200 + n*10 + attempt); + const at = new Date(+now - (3-attempt)*60_000); + await tx.insert(heartbeatRuns).values({ id:attemptId, companyId, agentId, issueId, scopeKind:"issue", nativeIssueId:issueId, + responsibleUserId:userId, status:"failed", runtimeMode:"native", invocationSource:"on_demand", + errorCode:"native_provider_usage_limit", error:failure.message, finishedAt:at, createdAt:at, updatedAt:at, + resultJson:{ providerFailure:failure }, contextSnapshot:{ issueId, aiConnection:{subscriptionId:id(90),provider:"openai"} } }) + .onConflictDoUpdate({ target:heartbeatRuns.id, set:{ resultJson:{providerFailure:failure} } }); + await tx.insert(heartbeatRunEvents).values({ companyId,agentId,runId:attemptId,seq:1,eventType:"lifecycle", + message:"Bounded retry exhausted: five-hour provider usage limit" }).onConflictDoNothing(); + } + if (resumed) { + await tx.insert(heartbeatRuns).values({ id: id(500+n), companyId, agentId, issueId, scopeKind:"issue", + status:"succeeded", invocationSource:"on_demand", finishedAt:now, createdAt:now, contextSnapshot:{issueId} }) + .onConflictDoUpdate({target:heartbeatRuns.id,set:{createdAt:now,finishedAt:now}}); + } else if (phase === "reset") { + await tx.delete(heartbeatRuns).where(and(eq(heartbeatRuns.companyId,companyId),eq(heartbeatRuns.id,id(500+n)))); + } + const evidence = { runId, providerLimitResetAt:resetAt, providerLimitAutomatic:true, + ...(manual ? {providerLimitResume:{state:"not_requested",reason:"automatic_retry_budget_used"}} : {}) }; + const status = recovered ? "resolved" : "active"; + const nextAction = manual ? "Retry this task after restoring capacity." : "Paperclip will retry this task at the reported reset."; + await tx.insert(issueRecoveryActions).values({ id:id(400+n), companyId, sourceIssueId:issueId, kind:"active_run_watchdog", + ownerType:"board", cause:"native_provider_usage_limit", fingerprint:runId, evidence, status, nextAction }) + .onConflictDoUpdate({ target:issueRecoveryActions.id, set:{ evidence,status,nextAction, resolvedAt:recovered ? now : null, updatedAt:now } }); + } + if (phase === "reset") { + // The agent status and its last failed run describe the same incident. + const agentId = id(10); + const error = "Five-hour usage limit reached"; + await tx.update(agents).set({ status: "error", errorReason: error }).where(and( + eq(agents.companyId, companyId), eq(agents.id, agentId), eq(agents.lifecycleState, "ready"), + )); + await tx.insert(agentRuntimeState).values({ agentId, companyId, adapterType:"process", lastRunId:id(353), + lastRunStatus:"failed", lastError:error }).onConflictDoUpdate({target:agentRuntimeState.agentId, + set:{lastRunId:id(353),lastRunStatus:"failed",lastError:error}}); + } + if (phase === "one-left" || phase === "all-recovered") { + await tx.update(issues).set({status:"done"}).where(and(eq(issues.companyId,companyId),eq(issues.id,id(105)))); + await tx.update(issueRecoveryActions).set({status:"resolved", resolvedAt:now}).where(and(eq(issueRecoveryActions.companyId,companyId),eq(issueRecoveryActions.id,id(405)))); + } + }); + console.log(`Inbox Test Drive: ${phase}. Refresh the inbox.`); +} finally { + await closeRegisteredClients(url, { scope: "database" }); +} diff --git a/server/src/__tests__/attention-current-cards.test.ts b/server/src/__tests__/attention-current-cards.test.ts index 11c0aceecd5..e32290602b3 100644 --- a/server/src/__tests__/attention-current-cards.test.ts +++ b/server/src/__tests__/attention-current-cards.test.ts @@ -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; } diff --git a/server/src/routes/attention.ts b/server/src/routes/attention.ts index f0a890885ae..77f896a1c95 100644 --- a/server/src/routes/attention.ts +++ b/server/src/routes/attention.ts @@ -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); diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index be80e892eda..33b8193b8c6 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -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", diff --git a/server/src/services/attention-exhausted-runs.ts b/server/src/services/attention-exhausted-runs.ts index fee63d1a25a..73693f8a247 100644 --- a/server/src/services/attention-exhausted-runs.ts +++ b/server/src/services/attention-exhausted-runs.ts @@ -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`${usageLimitFailure} is true`, + providerResumed: sql`case when ${usageLimitFailure} then ${providerWorkResumed} else false end`, + providerRetryAt: sql`${heartbeatRuns.resultJson}#>>'{providerFailure,retryAt}'`, + account: sql`coalesce(nullif(${heartbeatRuns.contextSnapshot}#>>'{aiConnection,subscriptionId}', ''), + nullif(${heartbeatRuns.contextSnapshot}#>>'{aiConnection,connectionId}', ''))`, + settledProviderHold: sql`${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`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>`jsonb_build_object( diff --git a/server/src/services/attention-provider-limits.test.ts b/server/src/services/attention-provider-limits.test.ts new file mode 100644 index 00000000000..7385f6ca0b5 --- /dev/null +++ b/server/src/services/attention-provider-limits.test.ts @@ -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"); + }); +}); diff --git a/server/src/services/attention-provider-limits.ts b/server/src/services/attention-provider-limits.ts new file mode 100644 index 00000000000..16ae2097ea0 --- /dev/null +++ b/server/src/services/attention-provider-limits.ts @@ -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`coalesce(${heartbeatRuns.issueId}::text, ${heartbeatRuns.nativeIssueId}::text, + ${heartbeatRuns.contextSnapshot}->>'issueId', ${heartbeatRuns.contextSnapshot}->>'taskId')`; +const account = sql`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`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`coalesce(${heartbeatRuns.resultJson}#>>'{providerLimitWait,resetAt}', ${heartbeatRuns.resultJson}#>>'{providerFailure,retryAt}')`, + reported: sql`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(); + 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, 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) { + const members = items.filter(item => item.providerLimit?.grouping === "retry_chain"); + const legacyDismissals = new Map(); + 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) { + const groups = new Map(); + 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`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 { + 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" })); +} diff --git a/server/src/services/attention.ts b/server/src/services/attention.ts index 96313a84e3d..e5ce678848f 100644 --- a/server/src/services/attention.ts +++ b/server/src/services/attention.ts @@ -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, 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(); 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) diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 6263aebc1a0..cd514fa6230 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -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(), diff --git a/server/src/services/native-runtime/provider-limit-resume.ts b/server/src/services/native-runtime/provider-limit-resume.ts index 97b3959946d..6a61da53c3b 100644 --- a/server/src/services/native-runtime/provider-limit-resume.ts +++ b/server/src/services/native-runtime/provider-limit-resume.ts @@ -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, 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"))); } diff --git a/tests/e2e/coordinator-inbox-views.spec.ts b/tests/e2e/coordinator-inbox-views.spec.ts index d4405ddccf5..23b34093849 100644 --- a/tests/e2e/coordinator-inbox-views.spec.ts +++ b/tests/e2e/coordinator-inbox-views.spec.ts @@ -92,7 +92,7 @@ for (const mobile of [false, true]) test(`Mine retains Inbox behavior inside Tas await page.keyboard.press("u"); await expect(unreadRow).toBeVisible(); await page.getByRole("link", { name: "Inbox", exact: true }).click(); - const inbox = page.getByRole("region", { name: "Needs You", exact: true }); + const inbox = page.getByRole("region", { name: "Inbox", exact: true }); await expect(inbox.getByRole("toolbar", { name: "Decisions controls" })).toBeVisible(); await expect(inbox.getByRole("button", { name: "Filter decisions by assignee, Assigned to you", exact: true })).toBeVisible(); await page.setViewportSize({ width: 1024, height: 720 }); diff --git a/tests/e2e/disconnect-resilience.spec.ts b/tests/e2e/disconnect-resilience.spec.ts index 758d34a2821..6d978f992f1 100644 --- a/tests/e2e/disconnect-resilience.spec.ts +++ b/tests/e2e/disconnect-resilience.spec.ts @@ -314,7 +314,13 @@ for (const status of [403, 404]) test(`a genuine ${status} replaces cached task await page.goto(data.route); await expect(page.getByTestId("task-chat-history-content")).toBeVisible({ timeout: 30_000 }); await expectCachedTask(page, data.issue); - await page.route("**/api/issues/*?view=core", route => route.fulfill({ status, json: { error: status === 403 ? "forbidden" : "not_found" } })); + // The bootstrap omits inaccessible tasks. Mirror that alongside both + // detail endpoints so either cache revalidation path observes the denial. + await page.route(url => url.pathname === `/api/companies/${data.company.id}/issues/chat-bootstrap`, + route => route.fulfill({ json: { items: [] } })); + const taskPaths = new Set([`/api/issues/${data.issue.id}`, `/api/issues/${data.issue.identifier}`]); + await page.route(url => taskPaths.has(url.pathname), + route => route.fulfill({ status, json: { error: status === 403 ? "forbidden" : "not_found" } })); await page.reload(); await expect(page.getByText(status === 403 ? "You don’t have permission to do that." : "This item doesn’t exist or was moved.", { exact: true })).toBeVisible(); await expect(page.getByTestId("issue-detail-header")).toHaveCount(0); diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 8e838418752..d45726dfff7 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -278,7 +278,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "afbe3d16f138f9c0d8d38041cb1190050b6ba9c6", + "packages/shared/src/index.ts": "4be2761402a84946e28007115841a01ba52ee0db", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", @@ -407,7 +407,7 @@ "packages/shared/src/types/approval.ts": "4554d36f804cb74b825b29711ed4c622df07ff6d", "packages/shared/src/types/artifact.ts": "6d022d34a718196df5c109a6164e7a70ede287e8", "packages/shared/src/types/asset.ts": "d148d6cba0e9a8d2e3aa6cb9182df6f59f909fba", - "packages/shared/src/types/attention.ts": "bd6fdf6938c23f6f6e86c496a7f17d376647d9f9", + "packages/shared/src/types/attention.ts": "ac112c8e57d853ebdb739e459b7acb41313947ad", "packages/shared/src/types/board-bootstrap.ts": "8eb0e0ec4c91369d12b268b9411ed512c8d1e8b1", "packages/shared/src/types/budget.ts": "7b3fe924d571008d67093c051a13d2c7e67f3ebe", "packages/shared/src/types/chat-channels.ts": "103eb76c5c517102e999b49b4bb726e0ea228902", @@ -436,7 +436,7 @@ "packages/shared/src/types/inbox-agent-policy.ts": "cb9d41d9681e80b834889268ad96015a39df92f6", "packages/shared/src/types/inbox-dismissal.ts": "58fb7013847396ac9971eb5799dd0bf0486e0371", "packages/shared/src/types/inbox-mine.ts": "1d302b531d34842189704abd2f75f8743d09490d", - "packages/shared/src/types/index.ts": "eed3bf088f545e1ad2f1d6f25bafc8a325b649d9", + "packages/shared/src/types/index.ts": "60366f789182ba3a4fb6895f91454ec386988496", "packages/shared/src/types/instance.ts": "ddfef2455723757a5ecffaf3bab56ec47c287267", "packages/shared/src/types/issue-tree-control.ts": "75489fffd491b8350b05caf57d7796419797d9df", "packages/shared/src/types/issue.ts": "849b293fb2263ed41d9a0a74276534ad5c2ff7b8", diff --git a/ui/src/api/attention.ts b/ui/src/api/attention.ts index 5ccb8c68ccb..591a25ce35b 100644 --- a/ui/src/api/attention.ts +++ b/ui/src/api/attention.ts @@ -4,6 +4,7 @@ import type { AttentionCloseResult, AttentionFeed, AttentionSummary, + AttentionRunHistoryEntry, AttentionTaskIndex, AttentionFeedQuery, AttentionSourceKind, @@ -21,6 +22,10 @@ function cardPath(companyId: string, sourceKind: AttentionSourceKind, sourceId: export const attentionApi = { summary: (companyId: string) => api.get(`/companies/${companyId}/attention/summary`), taskIndex: (companyId: string) => api.get(`/companies/${companyId}/attention/tasks`), + runHistory: (companyId: string, before?: { at: string; id: string }) => { + const query = before ? `?${new URLSearchParams(before)}` : ""; + return api.get(`/companies/${companyId}/attention/run-history${query}`); + }, history: (companyId: string, options: DecisionHistoryQuery = {}) => { const params = new URLSearchParams(); for (const [key, value] of Object.entries(options)) if (value !== undefined && value !== "") params.set(key, String(value)); diff --git a/ui/src/components/DecisionHistoryPanel.tsx b/ui/src/components/DecisionHistoryPanel.tsx index f8557f26dda..b7e0da9f610 100644 --- a/ui/src/components/DecisionHistoryPanel.tsx +++ b/ui/src/components/DecisionHistoryPanel.tsx @@ -10,7 +10,8 @@ import { DECISION_HISTORY_OUTCOME_OPTIONS, DECISION_HISTORY_SCOPE_OPTIONS, DEFAU import { CoordinatorDecisionReceipt as Receipt } from "@/components/coordinator/CoordinatorDecisionReceipt"; import { ToolbarSearch } from "@/components/ToolbarSearch"; import { Button } from "@/components/ui/button"; -import { NativeSelect } from "@/components/ui/select"; +import { EmptyState } from "@/components/EmptyState"; +import { InboxFilter } from "@/components/InboxFilter"; type Group = "none" | "task" | "agent" | "project"; @@ -28,12 +29,12 @@ export function DecisionHistoryPanel({ companyId, agents, userLabelMap, - header, + afterControls, }: { companyId: string; agents: Agent[]; userLabelMap?: ReadonlyMap; - header?: ReactNode; + afterControls?: ReactNode; }) { const navigate = useNavigate(); const [search, setSearch] = useState(""); @@ -62,29 +63,36 @@ export function DecisionHistoryPanel({ groups.set(label, [...(groups.get(label) ?? []), item]); } return
- {header} - -
- setScope(event.target.value as DecisionHistoryScope)} className="col-span-2"> - {DECISION_HISTORY_SCOPE_OPTIONS.map((option) => )} - - setOutcome(event.target.value)}> - - {DECISION_HISTORY_OUTCOME_OPTIONS.map((option) => )} - - - setSort(event.target.value as typeof sort)}> - setAgentId(event.target.value)} className="col-span-2">{agents.map((agent) => )} - setProjectId(event.target.value)} className="col-span-2">{(projects.data ?? []).map((project) => )} - setGroupBy(event.target.value as Group)} className="col-span-2"> +
+ +
+ label="Whose decision history" heading="Whose decisions" value={scope} + options={DECISION_HISTORY_SCOPE_OPTIONS} onChange={setScope} /> + + label="Sort decision history" heading="Sort by" value={sort} onChange={setSort} + options={[{ value: "newest", label: "Newest first" }, { value: "oldest", label: "Oldest first" }]} /> + ({ value: agent.id, label: agent.name }))]} /> + ({ value: project.id, label: project.name }))]} /> + label="Group decision history" heading="Group by" value={groupBy} onChange={setGroupBy} + options={[{ value: "none", label: "No grouping" }, { value: "task", label: "By task" }, { value: "agent", label: "By agent" }, { value: "project", label: "By project" }]} /> +
+ {afterControls} {waiting ?

Loading decisions…

: null} {historyView.kind === "error" ? : null} - {!waiting && historyView.kind !== "error" && !items.length ?
-

{scope === "mine" && !search && !outcome && !agentId && !projectId ? "No decisions handled by you or for you yet." : "No decisions match these filters."}

- {scope === "mine" ? : null} -
: null} -
{[...groups].map(([label, entries]) =>
{label ?

{label}

: null}{entries.map((item) =>

)}
)}
+ {!waiting && historyView.kind !== "error" && !items.length && setScope("all")} + hideActionIcon + />} +
{[...groups].map(([label, entries]) =>
+ {label &&

{label}

} + {entries.map(item => )} +
)}
{history.hasNextPage ? : null}
; } diff --git a/ui/src/components/EmptyState.tsx b/ui/src/components/EmptyState.tsx index 1b23884f89f..fc35b6e08ec 100644 --- a/ui/src/components/EmptyState.tsx +++ b/ui/src/components/EmptyState.tsx @@ -2,11 +2,14 @@ import { Plus } from "lucide-react"; import type { LucideIcon } from "lucide-react"; import type { ReactNode } from "react"; import { Button } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; interface EmptyStateProps { - icon: LucideIcon; + /** Retained for callers that supplied a section icon before the shared brand artwork. */ + icon?: LucideIcon; /** Large decorative artwork; shares hover/focus with the action below. */ graphic?: ReactNode; + placement?: "center" | "upper"; /** Optional bold heading rendered above the message. */ title?: string; message: string; @@ -19,8 +22,8 @@ interface EmptyStateProps { } export function EmptyState({ - icon: Icon, graphic, + placement = "center", title, message, description, @@ -29,27 +32,23 @@ export function EmptyState({ hideActionIcon = false, }: EmptyStateProps) { return ( -
- {graphic ? :
- -
} - {title ? ( - <> -

{title}

-

{message}

- - ) : ( - <> -

{message}

- {description &&

{description}

} - - )} - {action && onAction && ( - - )} +
+
+ +
+ {title &&

{title}

} +

{message}

+ {description &&

{description}

} +
+ {action && onAction && ( + + )} +
); } diff --git a/ui/src/components/InboxFilter.tsx b/ui/src/components/InboxFilter.tsx new file mode 100644 index 00000000000..389021bf285 --- /dev/null +++ b/ui/src/components/InboxFilter.tsx @@ -0,0 +1,31 @@ +import { Check, ChevronDown } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; +import { cn } from "@/lib/utils"; + +export function InboxFilter({ label, heading, value, options, onChange, defaultLabel }: { + label: string; + heading: string; + value: T; + options: readonly { value: T; label: string }[]; + onChange: (value: T) => void; + defaultLabel?: string; +}) { + const selected = options.find(option => option.value === value); + return + + + + + {heading} + {options.map(option => onChange(option.value)}> + + {option.label} + )} + + ; +} diff --git a/ui/src/components/coordinator/CoordinatorDecisionReceipt.tsx b/ui/src/components/coordinator/CoordinatorDecisionReceipt.tsx index c86d0e14a28..b726fb627f0 100644 --- a/ui/src/components/coordinator/CoordinatorDecisionReceipt.tsx +++ b/ui/src/components/coordinator/CoordinatorDecisionReceipt.tsx @@ -5,9 +5,10 @@ import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; import { cn } from "@/lib/utils"; /** A recorded decision links to its context; it is not a second approval form. */ -export function CoordinatorDecisionReceipt({ item, onOpen, userLabelMap }: { +export function CoordinatorDecisionReceipt({ item, onOpen, userLabelMap, showTimestamp = false }: { item: DecisionHistoryItem; onOpen: (href: string) => void; + showTimestamp?: boolean; /** Names the person a different person answered for ("for @dotta"; PAP-749 plan §6). */ userLabelMap?: ReadonlyMap | null; }) { @@ -19,6 +20,7 @@ export function CoordinatorDecisionReceipt({ item, onOpen, userLabelMap }: { {decisionHistoryContext(item)} {/* Who withdrew it is in the headline; the reason they gave is here (PAP-749 plan §3). */} {item.reason ? Reason: {item.reason} : null} + {showTimestamp && } ; diff --git a/ui/src/components/coordinator/CoordinatorNeedsYou.tsx b/ui/src/components/coordinator/CoordinatorNeedsYou.tsx index 77cdf7ca4d1..6dd21067b0d 100644 --- a/ui/src/components/coordinator/CoordinatorNeedsYou.tsx +++ b/ui/src/components/coordinator/CoordinatorNeedsYou.tsx @@ -1,7 +1,9 @@ +import { InboxLimitCards, InboxProviderLimit } from "./InboxProviderLimit"; +import { InboxRunHistory } from "./InboxRunHistory"; import { QueryErrorState, useQueryView } from "@/components/QueryView"; import { useCallback, useEffect, useMemo, useState, type MouseEvent as ReactMouseEvent } from "react"; import { useQuery } from "@tanstack/react-query"; -import { ArrowLeft, ArrowUpRight, Check, ChevronDown, FileText, Image as ImageIcon, Loader2 } from "lucide-react"; +import { ArrowLeft, ArrowUpRight, ChevronDown, FileText, Image as ImageIcon, Loader2 } from "lucide-react"; import { LayoutGroup, motion, useReducedMotion } from "motion/react"; import { attentionCardType, type AttentionCloseMode, type AttentionItem, type AttentionPersonalView } from "@paperclipai/shared"; import { accessApi } from "@/api/access"; @@ -19,7 +21,7 @@ import { COORDINATOR_ASSIGNEE_PARAM, COORDINATOR_RECENT_DECISION_MS, DEFAULT_DEC import { attentionDetailLine, isInlineResolvable } from "@/lib/attention"; import { ATTENTION_VIEW_PARAM, attentionAudienceLineNamesResponders, parseAttentionView } from "@/lib/attention-views"; import { splitArchivedAttentionItems, splitStaleAttentionItems } from "@/lib/attention-close"; -import { attentionObligationEvidence, foldAttentionObligations } from "@/lib/attention-obligations"; +import { attentionObligationEvidence, foldAttentionObligations, inboxCardMatchesFilters, inboxProjectOptions } from "@/lib/attention-obligations"; import { buildCompanyUserLabelMap } from "@/lib/company-members"; import { AttentionCloseMenu, AttentionForOtherGate, AttentionHiddenChip, AttentionSnoozedGroup, AttentionStaleChip, AttentionStaleGroup } from "@/components/AttentionCloseMenu"; import { BudgetAlertActions, FailedRunActions } from "@/components/AttentionInlineVerbs"; @@ -30,6 +32,8 @@ import { DecisionHistoryPanel } from "@/components/DecisionHistoryPanel"; import { DecisionResolver } from "@/components/DecisionResolver"; import { DecisionCardFooter } from "@/components/DecisionCardFooter"; import { useSidePanelTabs } from "@/components/side-panel"; +import { EmptyState } from "@/components/EmptyState"; +import { InboxFilter } from "@/components/InboxFilter"; import { ToolbarSearch } from "@/components/ToolbarSearch"; import { Button } from "@/components/ui/button"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; @@ -47,32 +51,11 @@ import { cn } from "@/lib/utils"; type Group = "type" | "none" | "task" | "agent" | "project"; -function InboxFilter({ label, heading, value, options, onChange, defaultLabel }: { - label: string; - heading: string; - value: T; - options: readonly { value: T; label: string }[]; - onChange: (value: T) => void; - defaultLabel?: string; -}) { - const selected = options.find(option => option.value === value); - return - - - - - {heading} - {options.map(option => onChange(option.value)}> - - {option.label} - )} - - ; -} +const inboxFolders = [ + { value: "needs", label: "Needs you", description: "Review open requests and decide what happens next." }, + { value: "waiting", label: "Waiting", description: "See what you’ve snoozed and which tasks are waiting for an automatic retry." }, + { value: "history", label: "History", description: "Look back at past decisions and see what happened to failed runs." }, +] as const; /** Rule 7: a card that cannot answer inline links to the exact control, named by its verb. */ function openLabel(item: AttentionItem) { @@ -118,6 +101,7 @@ export function CoordinatorNeedsYou() { const forUserId = view === "all" ? searchParams.get(COORDINATOR_ASSIGNEE_PARAM) : null; const setView = useCallback((next: typeof view, person: string | null = null) => setSearchParams(current => { const params = new URLSearchParams(current); + params.delete("folder"); if (next === "mine") params.delete(ATTENTION_VIEW_PARAM); else params.set(ATTENTION_VIEW_PARAM, next); if (person) params.set(COORDINATOR_ASSIGNEE_PARAM, person); else params.delete(COORDINATOR_ASSIGNEE_PARAM); return params; @@ -128,7 +112,18 @@ export function CoordinatorNeedsYou() { const [agentFilter, setAgentFilter] = useState(""); const [projectFilter, setProjectFilter] = useState(""); const [groupBy, setGroupBy] = useState("type"); - const [historyOpen, setHistoryOpen] = useState(false); + const folder = searchParams.get("folder"); + const historyOpen = folder === "history"; + const waitingOpen = folder === "waiting"; + const changeFolder = (next: "needs" | "waiting" | "history") => { + setQuery(""); setAgentFilter(""); setProjectFilter(""); + setSearchParams(current => { + const params = new URLSearchParams(current); + params.delete(ATTENTION_VIEW_PARAM); params.delete(COORDINATOR_ASSIGNEE_PARAM); + if (next === "needs") params.delete("folder"); else params.set("folder", next); + return params; + }); + }; // Focus (PAP-770): documents a card asks about open as side-panel tabs, the // same chrome as task detail. Decision history is a main-pane view instead. const reviewTabs = useSidePanelTabs({ initialState: { tabs: [], activeTabId: null } }); @@ -140,11 +135,11 @@ export function CoordinatorNeedsYou() { // Snoozed group starts open (PAP-749 plan §3). const [staleOpen, setStaleOpen] = useState(false); const [snoozedOpen, setSnoozedOpen] = useState(true); - useEffect(() => { setSettling([]); setSavedIds(new Map()); setStaleOpen(false); setSnoozedOpen(true); }, [selectedCompanyId, userId, view]); + useEffect(() => { setSettling([]); setSavedIds(new Map()); setStaleOpen(false); setSnoozedOpen(true); }, [selectedCompanyId, userId, view, folder]); const archivedView = view === "archived"; const [renderLimit, setRenderLimit] = useState(40); // Keyed by person and view; the For you key is the one the badge reads. - const feed = useAttentionViewFeed(selectedCompanyId, view); + const feed = useAttentionViewFeed(selectedCompanyId, waitingOpen ? "waiting" : view); useEffect(() => { setSavedIds(current => { const pending = new Map([...current].filter(([, hidden]) => hidden.closed || hidden.version === feed.dataUpdatedAt)); @@ -198,12 +193,9 @@ export function CoordinatorNeedsYou() { }).map(([, item]) => item); }, [obligations, settling, settlingIds, recentItems, savedIds, feed.dataUpdatedAt]); const filtered = useMemo(() => pendingItems.filter((item) => { - const agentId = String(item.subject.metadata?.createdByAgentId ?? item.subject.metadata?.originAgentId ?? ""); - if (agentFilter && agentId !== agentFilter && item.originAgentName !== agentMap.get(agentFilter)?.name) return false; - if (projectFilter && item.project?.id !== projectFilter) return false; if (forUserId && coordinatorAudienceKey(item) !== `user:${forUserId}`) return false; - return [item.subject.title, item.relatedIssue?.title, item.relatedIssue?.identifier, item.originAgentName, item.project?.name, attentionDetailLine(item)].join(" ").toLocaleLowerCase().includes(query.trim().toLocaleLowerCase()); - }).sort((a, b) => Date.parse(b.activityAt) - Date.parse(a.activityAt)), [pendingItems, agentFilter, projectFilter, forUserId, query, agentMap]); + return inboxCardMatchesFilters(obligations, item, { query, agentId: agentFilter, agentName: agentMap.get(agentFilter)?.name, projectId: projectFilter }); + }).sort((a, b) => Date.parse(b.activityAt) - Date.parse(a.activityAt)), [pendingItems, obligations, agentFilter, projectFilter, forUserId, query, agentMap]); // Stale cards go to the collapsed group at the bottom of each view (Rule 10). // The Archived view keeps stale cards in place with their chip, and puts // snoozed cards in their own group (plan §3). @@ -243,10 +235,8 @@ export function CoordinatorNeedsYou() { card.scrollIntoView({ block: "center", behavior: reducedMotion ? "auto" : "smooth" }); setSearchParams(current => { const next = new URLSearchParams(current); next.delete("decisionId"); return next; }, { replace: true }); }, [deepLinkDecisionId, selectedCompanyId, pendingItems, currentItems, staleItems, feedWaiting, everyone, view, query, agentFilter, projectFilter, forUserId, setView, renderLimit, reducedMotion, setSearchParams]); - const projects = useMemo(() => [...new Map([ - ...pendingItems.flatMap((item) => item.project ? [[item.project.id, item.project.name] as const] : []), - ...recentItems.flatMap((item) => item.projectId ? [[item.projectId, item.projectName ?? "Unnamed project"] as const] : []), - ]).entries()], [pendingItems, recentItems]); + const projects = useMemo(() => inboxProjectOptions(obligations, pendingItems, recentItems), + [obligations, pendingItems, recentItems]); // Assigned to you, everyone the viewer may see, one person, no owner yet, or company alerts. const assigneeOptions = useMemo(() => { const people = [...userLabelMap].filter(([id]) => id !== userId).sort(([, a], [, b]) => a.localeCompare(b)); @@ -258,8 +248,7 @@ export function CoordinatorNeedsYou() { ]; }, [userLabelMap, userId, everyone]); const chooseAssignee = (value: CoordinatorAssignee) => { const target = coordinatorAssigneeTarget(value, userId); setView(target.view, target.forUserId); }; - const closeHistory = useCallback(() => setHistoryOpen(false), []); - const showHistory = () => setHistoryOpen(true); + const showHistory = () => changeFolder("history"); // Cards whose artifact can open beside them: the + launcher lists these. const reviewable = useMemo(() => pendingItems.filter(item => !!needsYouArtifact(item)), [pendingItems]); const { openTab: openReviewTab, closeTab: closeReviewTab, selectTab: selectReviewTab, reorderTabs: reorderReviewTabs, resetTabs: resetReviewTabs } = reviewTabs; @@ -275,9 +264,9 @@ export function CoordinatorNeedsYou() { const open = new Set(pendingItems.map(item => item.id)); for (const tab of reviewTabs.tabs) if (!open.has(tab.payload.itemId)) closeReviewTab(tab.id); }, [pendingItems, reviewTabs.tabs, closeReviewTab]); - useEffect(() => { setBreadcrumbs([{ label: "Needs You" }]); }, [setBreadcrumbs]); + useEffect(() => { setBreadcrumbs([{ label: "Inbox" }]); }, [setBreadcrumbs]); useEffect(() => { - setSettling([]); setHistoryOpen(false); setReviewPanelOpen(false); resetReviewTabs({ tabs: [], activeTabId: null }); setNow(Date.now()); closePanel(); + setSettling([]); setReviewPanelOpen(false); resetReviewTabs({ tabs: [], activeTabId: null }); setNow(Date.now()); closePanel(); return closePanel; }, [selectedCompanyId, closePanel, resetReviewTabs]); useEffect(() => { @@ -358,13 +347,13 @@ export function CoordinatorNeedsYou() { className="coordinator-decision-card space-y-3" data-attention-card={item.id} data-card-type={type} data-card-kind={needsYouSection(item) === "problems" ? "problem" : "decision"} data-reviewing={reviewing || undefined}> {/* What to do (with whose card it is) on the left; who asked, when, and ⋯ on the right (Paper "A · Compact cards"). */} -
+
- + {item.providerLimit ? Provider usage limit : }
-
+
claim.mutate(entry)} claiming={claim.isPending && claim.variables?.id === item.id} /> @@ -374,11 +363,12 @@ export function CoordinatorNeedsYou() { onArchive={entry => closeActions.close({ item: entry, mode: "archive" })} onSnooze={(entry, until) => closeActions.close({ item: entry, mode: "snooze", until })} onTransfer={(entry, target) => closeActions.transfer({ item: entry, userId: target })} - onRestore={archivedView ? entry => void closeActions.restore(entry) : undefined} /> + onRestore={archivedView || item.dismissal?.isActive ? entry => void closeActions.restore(entry) : undefined} />
- {interaction ? { + {item.providerLimit ? + : interaction ? { if (!resolved || resolved.status === "pending") { refetchAll(); return; } onResolved(item); }} /> @@ -400,19 +390,35 @@ export function CoordinatorNeedsYou() { if (!selectedCompanyId) return

Choose a company to see its decisions.

; // Decision history is a view of the main pane (PAP-770), not a side panel // that repeats Recent Decisions beside them. + const activeFolder = inboxFolders.find(({ value }) => + value === "needs" ? !waitingOpen && !historyOpen && !archivedView : value === folder); + const folders =
+ + {activeFolder &&

{activeFolder.description}

} +
; + const receipts = feed.data?.receipts ?? []; if (historyOpen) return
- - Decision history} /> + + {folders} + {receipts.length > 0 &&

Updates

{receipts.map(entry => )}
} +

Decision history

+ } /> +
; - const receipts = view === "mine" ? feed.data?.receipts ?? [] : []; - const counts = { decisions: 0, problems: 0, updates: receipts.length }; + const counts = { decisions: 0, problems: 0, updates: 0 }; for (const item of currentItems) counts[needsYouSection(item)]++; const summarySections = (Object.keys(counts) as NeedsYouSection[]).filter(section => counts[section] > 0); - if (!summarySections.length) summarySections.push("decisions"); + const sectionHeading = (section: NeedsYouSection) =>

{NEEDS_YOU_SECTIONS[section].title}

; - return
+ return
{archivedView ?

Archived

: null} {/* Assigned to you by default (PAP-775); the assignee filter widens to all assignees, one person, no owner yet or company alerts. Archived and @@ -426,7 +432,7 @@ export function CoordinatorNeedsYou() { ({ value, label }))]} /> - {assignee && option.value === assignee) ? [...assigneeOptions, { value: assignee, label: "Someone else" }] : assigneeOptions} />} @@ -443,7 +449,8 @@ export function CoordinatorNeedsYou() {
- {feed.data ?

+ {folders} + {feed.data && !waitingOpen && summarySections.length > 0 ?

{summarySections.map((section, index) => { const label = NEEDS_YOU_SECTIONS[section].title.toLocaleLowerCase(); return {index ? " · " : ""}{counts[section]} {counts[section] === 1 ? label.slice(0, -1) : label}; @@ -451,25 +458,23 @@ export function CoordinatorNeedsYou() {

: null} {feedWaiting ?

Loading decisions…

: null} {feedView.kind === "error" ? : null} - {!feedWaiting && feedView.kind !== "error" && currentItems.length === 0 && !receipts.length ?

{staleItems.length ? "No current cards. Stale cards are below." : snoozedItems.length ? "No archived cards. Snoozed cards are below." : pendingItems.length ? "No open decisions match these filters." : EMPTY_VIEW_TEXT[view]}

: null} + {!feedWaiting && feedView.kind !== "error" && currentItems.length === 0 && ( + staleItems.length || snoozedItems.length + ?

{staleItems.length ? "No current cards. Stale cards are below." : "No archived cards. Snoozed cards are below."}

+ : + )} {groups.map(([label, items], index) =>
{groupBy === "type" ? index > 0 ? sectionHeading(label as NeedsYouSection) : null : label ?

{label}

: null} - {items.map(renderCard)} +
)} {currentItems.length > renderLimit ? : null} setStaleOpen(open => !open)} onWithdrawAll={closeActions.withdrawAll} busy={closeActions.bulkPending} currentUserId={userId} userLabelMap={userLabelMap} titleOf={coordinatorCardTitle}> - {staleItems.map(renderCard)} + {/* Snoozed by you: each card says when it comes back (PAP-749 plan §3). */} setSnoozedOpen(open => !open)}> - {snoozedItems.map(renderCard)} + - {/* What other people did with your requests (PAP-749 plan §6): not in the badge. */} - {receipts.length ?
- {currentItems.length || staleItems.length || snoozedItems.length ? sectionHeading("updates") : null} - {receipts.map(entry => )} -
: null} ; } diff --git a/ui/src/components/coordinator/InboxProviderLimit.test.tsx b/ui/src/components/coordinator/InboxProviderLimit.test.tsx new file mode 100644 index 00000000000..787413d1a40 --- /dev/null +++ b/ui/src/components/coordinator/InboxProviderLimit.test.tsx @@ -0,0 +1,38 @@ +// @vitest-environment jsdom + +import type { AttentionItem, AttentionProviderLimit } from "@paperclipai/shared"; +import { renderToStaticMarkup } from "react-dom/server"; +import { MemoryRouter } from "react-router-dom"; +import { describe, expect, it, vi } from "vitest"; +import { InboxProviderLimit } from "./InboxProviderLimit"; + +vi.mock("@/lib/router", async () => ({ Link: (await import("react-router-dom")).Link })); + +const resetAt = "2026-11-24T20:00:00Z"; +const firstRetry = "2026-11-24T18:00:00Z"; +const secondRetry = "2026-11-24T19:00:00Z"; + +function task(id: string, retryAt: string): AttentionItem { + const providerLimit: AttentionProviderLimit = { + episode: "account-window", grouping: "account_window", attempts: 1, state: "scheduled", resetAt, retryAt, + runId: id, agentId: "editor", agentName: "Editor", + }; + return { + relatedIssue: { id, identifier: id, title: "Review the launch", href: `/issues/${id}` }, + providerLimit, + } as AttentionItem; +} + +describe("InboxProviderLimit", () => { + it("distinguishes the reported reset and each task's scheduled retry time", () => { + const html = renderToStaticMarkup( + + ); + const container = document.createElement("div"); + container.innerHTML = html; + const reset = Array.from(container.querySelectorAll("p")).find(row => row.textContent?.includes("Provider reset")); + expect(reset?.querySelector("time")?.dateTime).toBe(resetAt); + expect(Array.from(container.querySelectorAll("li"), row => row.querySelector("time")?.dateTime)) + .toEqual([firstRetry, secondRetry]); + }); +}); diff --git a/ui/src/components/coordinator/InboxProviderLimit.tsx b/ui/src/components/coordinator/InboxProviderLimit.tsx new file mode 100644 index 00000000000..6220804fbd1 --- /dev/null +++ b/ui/src/components/coordinator/InboxProviderLimit.tsx @@ -0,0 +1,81 @@ +import type { ReactNode } from "react"; +import type { AttentionItem, AttentionProviderLimit } from "@paperclipai/shared"; +import { Link } from "@/lib/router"; +import { Button } from "@/components/ui/button"; +import { formatDateTime } from "@/lib/utils"; + +function RetryStatus({ limit }: { limit: AttentionProviderLimit }) { + if (limit.state === "needs_retry") return "Needs retry"; + if (limit.state === "retry_requested") return "Retry requested"; + return <>Retry scheduled + {limit.retryAt && <> for } + ; +} + +/** This disclosure has no dismissal or retry action. Both belong to the child cards. */ +export function InboxLimitCards({ items, renderCard }: { + items: readonly AttentionItem[]; + renderCard: (item: AttentionItem) => ReactNode; +}) { + const chains = items.filter(item => item.providerLimit?.grouping === "retry_chain" && item.relatedIssue); + const taskCount = new Set(chains.map(item => item.relatedIssue!.id)).size; + if (taskCount < 2) return items.map(renderCard); + const grouped = new Set(chains); + return items.map(item => { + if (!grouped.has(item)) return renderCard(item); + if (item !== chains[0]) return null; + return
+ {taskCount} tasks hit usage limits +
{chains.map(renderCard)}
+
; + }); +} + +export function InboxProviderLimit({ item, evidence }: { item: AttentionItem; evidence: readonly AttentionItem[] }) { + const state = item.providerLimit!; + if (state.grouping === "retry_chain" && item.relatedIssue) { + const task = item.relatedIssue; + return
+

{task.identifier} {task.title}

+

+

{state.attempts} {state.attempts === 1 ? "attempt" : "attempts"} · {state.resetAt + ? <>Provider reset at + : "Reset time unknown"}

+
+ {state.state === "needs_retry" && } + {state.agentName} run log +
+
; + } + const members = [item, ...evidence].filter(member => member.providerLimit && member.relatedIssue); + const tasks = [...new Map(members.map(member => [member.relatedIssue!.id, member])).values()]; + const manual = tasks.filter(task => task.providerLimit!.state === "needs_retry"); + const title = manual.length + ? `${manual.length} ${manual.length === 1 ? "task needs" : "tasks need"} a retry after the usage limit` + : `${tasks.length} ${tasks.length === 1 ? "task paused" : "tasks paused"} by the provider usage limit`; + const taskLabel = (count: number) => count === 1 ? "task" : "tasks"; + const scheduled = tasks.filter(task => task.providerLimit!.state === "scheduled"); + const firstRetry = scheduled[0]?.providerLimit?.retryAt; + const sharedRetryAt = firstRetry && scheduled.every(task => task.providerLimit!.retryAt === firstRetry) ? firstRetry : null; + return
+

{title}

+ {state.resetAt &&

Provider reset at .

} + {scheduled.length > 0 &&

Retry scheduled for {scheduled.length} {taskLabel(scheduled.length)} + {sharedRetryAt && <> at }. +

} + {!scheduled.length && !manual.length &&

Retry requested. Waiting for work to resume.

} + {manual.length > 0 &&

Open the affected task to retry it when capacity is available.

} +
View {tasks.length} {taskLabel(tasks.length)} +
    {tasks.map(member => { + const task = member.relatedIssue!; + const limit = member.providerLimit!; + return
  • + {task.identifier} {task.title} + {limit.agentName} · + Run log +
  • ; + })}
+
+ {manual.length === 1 && } +
; +} diff --git a/ui/src/components/coordinator/InboxRunHistory.tsx b/ui/src/components/coordinator/InboxRunHistory.tsx new file mode 100644 index 00000000000..cb4f6760526 --- /dev/null +++ b/ui/src/components/coordinator/InboxRunHistory.tsx @@ -0,0 +1,46 @@ +import { EmptyState } from "@/components/EmptyState"; +import { Button } from "@/components/ui/button"; +import { useInfiniteQuery } from "@tanstack/react-query"; +import { attentionApi } from "@/api/attention"; +import { queryKeys } from "@/lib/queryKeys"; +import { Link } from "@/lib/router"; +import { QueryErrorState, useQueryView } from "@/components/QueryView"; +import { HorizontalScrollViewport } from "@/components/HorizontalScrollViewport"; +import { FileText } from "lucide-react"; + +const recordedTime = new Intl.DateTimeFormat(undefined, { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" }); + +export function InboxRunHistory({ companyId, userId }: { companyId: string; userId: string | null }) { + const query = useInfiniteQuery({ queryKey: [...queryKeys.attention(companyId), userId, "run-history"], + initialPageParam: undefined as { at: string; id: string } | undefined, + queryFn: ({ pageParam }) => attentionApi.runHistory(companyId, pageParam), + getNextPageParam: (rows) => { + const last = rows.at(-1); + return rows.length === 100 && last ? { at: last.recordedAt, id: last.runId } : undefined; + } }); + const runs = query.data?.pages.flat(); + const view = useQueryView(query); + return

Recent run history

+ {view.kind === "error" && } + {query.isLoading &&

Loading runs…

} + {view.kind !== "error" && runs?.length === 0 && } + {runs && runs.length > 0 && + + {["Task", "Task ID", "Outcome", "Run log", "Recorded"].map(label => )} + {runs.map(run => { + const recordedAt = new Date(run.recordedAt); + return + + + + + + ; + })} +
{label}
{run.taskTitle}{run.identifier ?? "—"}
{run.outcome}
{run.reason}
+ {run.agentName} +
+
} + {query.hasNextPage && } +
; +} diff --git a/ui/src/context/LiveUpdatesProvider.tsx b/ui/src/context/LiveUpdatesProvider.tsx index abfef4a92de..07227750798 100644 --- a/ui/src/context/LiveUpdatesProvider.tsx +++ b/ui/src/context/LiveUpdatesProvider.tsx @@ -1594,6 +1594,9 @@ function invalidateActivityQueries( typeof details?.handledForUserId === "string" || action?.startsWith("issue.thread_interaction_") || action === "issue.status_decision_recorded" || + action === "issue.provider_limit_retry_settled" || + action === "issue.recovery_action_resolved" || + action === "issue.retry_requested" || action === "issue.conversation_session_started" || (entityType === "issue" && ["issue.created", "issue.updated", "issue.deleted"].includes(action ?? "")); const decisionAudienceChanged = action?.startsWith("issue_access_grant.") || @@ -2181,6 +2184,9 @@ function handleLiveEvent( } invalidateVisibleIssueRunQueries(queryClient, pathname, payload); if (event.type === "heartbeat.run.status") { + if (["scheduled_retry", "running", "succeeded", "failed", "timed_out", "cancelled"].includes(String(payload.status))) { + void queryClient.invalidateQueries({ queryKey: queryKeys.attention(expectedCompanyId) }, { cancelRefetch: false }); + } const toast = buildRunStatusToast(payload, nameOf); if (toast && event.toastEligible === true && !suppressRunToast) { gatedPushToast(gate, pushToast, "run-status", toast); diff --git a/ui/src/hooks/useAttentionViews.ts b/ui/src/hooks/useAttentionViews.ts index 7f9bb6fa1bc..5086e1296bc 100644 --- a/ui/src/hooks/useAttentionViews.ts +++ b/ui/src/hooks/useAttentionViews.ts @@ -1,6 +1,6 @@ import { useCallback, useState } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import type { AttentionCloseMode, AttentionItem, AttentionPersonalView, AttentionReceipt } from "@paperclipai/shared"; +import type { AttentionCloseMode, AttentionItem, AttentionFeedView, AttentionReceipt } from "@paperclipai/shared"; import { accessApi } from "@/api/access"; import { attentionApi } from "@/api/attention"; import { inboxDismissalsApi } from "@/api/inboxDismissals"; @@ -24,7 +24,7 @@ interface AttentionViewFeedOptions { */ export function useAttentionViewFeed( companyId: string | null | undefined, - view: AttentionPersonalView, + view: AttentionFeedView, options: AttentionViewFeedOptions = {}, ) { const { userId } = useCoordinatorWorkspaceEnabled(); diff --git a/ui/src/hooks/useCoordinatorAttentionCount.ts b/ui/src/hooks/useCoordinatorAttentionCount.ts index ee64663d1d0..901813f86d3 100644 --- a/ui/src/hooks/useCoordinatorAttentionCount.ts +++ b/ui/src/hooks/useCoordinatorAttentionCount.ts @@ -1,4 +1,6 @@ -import { useQuery } from "@tanstack/react-query"; +import { useEffect } from "react"; +import { queryKeys } from "@/lib/queryKeys"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; import { attentionApi } from "@/api/attention"; import { useCoordinatorWorkspaceEnabled } from "./useCoordinatorWorkspaceEnabled"; import { coordinatorAttentionQueryKey, coordinatorAttentionSummaryQueryKey, coordinatorAttentionTasksQueryKey } from "@/lib/coordinator-attention"; @@ -21,9 +23,24 @@ export function useCoordinatorAttentionCount(companyId: string | null | undefine // These are three projections of the same company/person count. Keep the // newest known count during route changes, including an explicit fresh zero. // Server generation time wins over a delayed older response arriving later. - if (!canRead) return 0; + const queryClient = useQueryClient(); const snapshots = feedPage ? [attention, tasks, summary] : taskPage ? [tasks, attention, summary] : [summary, attention, tasks]; - return snapshots.filter(snapshot => snapshot.data !== undefined) + const latest = snapshots.filter(snapshot => snapshot.data !== undefined) .sort((a, b) => ((Date.parse(b.data?.generatedAt ?? "") || 0) - (Date.parse(a.data?.generatedAt ?? "") || 0)) - || b.dataUpdatedAt - a.dataUpdatedAt)[0]?.data?.deskBadgeCount ?? 0; + || b.dataUpdatedAt - a.dataUpdatedAt)[0]?.data; + const nextSnoozeAt = latest?.nextSnoozeAt; + useEffect(() => { + if (!canRead || !companyId || !nextSnoozeAt) return; + // One deadline per viewer. A hidden tab catches up on focus. + const due = Date.parse(nextSnoozeAt); + let timer: number; + const schedule = () => { + const remaining = due - Date.now(); + if (remaining <= 0) void queryClient.invalidateQueries({ queryKey: queryKeys.attention(companyId) }); + else timer = window.setTimeout(schedule, Math.min(remaining, 2_147_483_647)); + }; + schedule(); + return () => window.clearTimeout(timer); + }, [canRead, companyId, nextSnoozeAt, queryClient]); + return canRead ? latest?.deskBadgeCount ?? 0 : 0; } diff --git a/ui/src/index.css b/ui/src/index.css index c09115915dc..c732cca63af 100644 --- a/ui/src/index.css +++ b/ui/src/index.css @@ -5278,8 +5278,27 @@ html:not(.dark) .coordinator-sidebar { /* The Needs You toolbar fits one row: the search takes what the filters leave. */ [data-canonical-toolbar="inbox"] { justify-content: space-between; } [data-canonical-toolbar="inbox"] .design-toolbar-actions { margin-inline-start: 0; } -.coordinator-needs-you > :not([role="toolbar"]) { max-width: var(--container-4xl); margin-inline: auto; } +.coordinator-needs-you:not([data-coordinator-decision-history]) > :not([role="toolbar"], [data-inbox-folders]) { max-width: var(--container-4xl); margin-inline: auto; } +[data-coordinator-decision-history] > :not([data-decision-history]), +[data-coordinator-decision-history] > [data-decision-history] > :not([role="toolbar"], [data-inbox-folders]) { max-width: var(--container-4xl); } .coordinator-needs-you [data-toolbar-search] input { flex: 1; width: auto; } +.inbox-run-table { + width: 100%; + border-collapse: collapse; + text-align: start; + font-size: var(--task-row-title-size); + line-height: var(--task-row-title-leading); +} +.inbox-run-table :is(th, td) { + height: var(--task-row-height-comfortable); + padding-inline: var(--task-row-gap); + border-bottom: var(--task-row-rule-width) solid var(--task-row-rule-color); + white-space: nowrap; +} +.inbox-run-table :is(th, td):first-child { padding-inline-start: var(--task-row-padding-inline); } +.inbox-run-table :is(th, td):last-child { text-align: end; padding-inline-end: var(--task-row-padding-inline); } +.inbox-run-table th { color: var(--muted-foreground); font-weight: var(--font-weight-medium); text-align: start; } +.inbox-run-table tbody tr:is(:hover, :focus-within) { background: var(--task-row-surface-hover); } .coordinator-decision-card [data-needs-you-panel] :is(p, label) { font-size: var(--text-compact); line-height: calc(var(--spacing) * 5); } .coordinator-decision-card [data-needs-you-panel] :is(p, label, span).text-xs { font-size: var(--text-xs); line-height: calc(var(--spacing) * 4.5); } .coordinator-decision-card [data-decision-actions] :is(button, a):is([data-slot="button"], [data-variant]) { height: calc(var(--spacing) * 8); padding-inline: calc(var(--spacing) * 2.5); font-size: var(--text-compact); } @@ -5450,7 +5469,31 @@ html:not(.dark) .coordinator-sidebar { } /* Large collection empty states share the artifact fan, with 20px rhythm. */ -.empty-state-artwork > p { margin-block: 0; } +.empty-state[data-placement="upper"] { + /* Center the group in the upper 70%, allowing its contents to fit on short screens. */ + grid-template-rows: minmax(max-content, 70%) 1fr; +} +.empty-state-logo { + display: block; + inline-size: var(--sz-200px); + block-size: var(--sz-200px); + background: var(--muted); + mask: url("/favicon.svg") center / contain no-repeat; +} +/* Let a page-level empty state take the space left by its own toolbar and labels. */ +#main-content:has(> .empty-state, > .empty-state-page, > :only-child > .empty-state), +#main-content > :is(.empty-state-page, :only-child:has(> .empty-state)) { + display: flex; + flex-direction: column; +} +#main-content > :is(.empty-state-page, :only-child:has(> .empty-state)) { flex: 1; } +.paperclip-app-shell[data-mobile="true"] .app-content-column:has(#main-content > .empty-state, #main-content > .empty-state-page, #main-content > :only-child > .empty-state) { + min-height: calc(100dvh - var(--sz-safe-top)); +} +.paperclip-app-shell[data-mobile="true"] .app-content-row:has(#main-content > .empty-state, #main-content > .empty-state-page, #main-content > :only-child > .empty-state) { + display: flex; + flex: 1; +} .empty-state-graphic { display: flex; align-items: flex-end; justify-content: center; max-width: 100%; } [data-canonical-toolbar] input:not([type="checkbox"], [type="radio"]) { height: var(--collection-toolbar-height); diff --git a/ui/src/lib/attention-obligations.test.ts b/ui/src/lib/attention-obligations.test.ts index 9617b117ef1..16c0e87259d 100644 --- a/ui/src/lib/attention-obligations.test.ts +++ b/ui/src/lib/attention-obligations.test.ts @@ -5,6 +5,8 @@ import { attentionEvidenceText, attentionObligationEvidence, foldAttentionObligations, + inboxCardMatchesFilters, + inboxProjectOptions, isAttentionObligationEvidence, } from "./attention-obligations"; @@ -48,6 +50,52 @@ describe("one card for each obligation (PAP-749 task 2d)", () => { expect(folded.evidenceByLeadId.size).toBe(0); }); + it("finds a non-lead task in a shared window when the same task matches all filters", () => { + const member = (id: string, agent: string, project: string) => item(id, { + providerLimit: { episode: "window", grouping: "account_window", attempts: 1, retryAt: null, resetAt: null, + state: "scheduled", runId: id, agentId: agent, agentName: agent }, + relatedIssue: { ...review.subject, identifier: id }, + project: { id: project, name: project, urlKey: project, color: null, icon: null }, + obligationLeadId: "ONE-1", + }); + const lead = member("ONE-1", "Editor", "Design"); + const folded = foldAttentionObligations([lead, member("TWO-2", "Reviewer", "Launch")]); + const matches = (query: string, agentId: string, projectId: string) => + inboxCardMatchesFilters(folded, lead, { query, agentId, projectId }); + expect(matches("two-2", "Reviewer", "Launch")).toBe(true); + expect(matches("reviewer", "", "")).toBe(true); + expect(matches("two-2", "Editor", "Design")).toBe(false); + }); + + it("bounds project and search work for a large inbox with a shared quota window", () => { + const size = 800; + const grouped = size / 2; + let reads = 0; + const items = Array.from({ length: size }, (_, index) => { + const id = `TASK-${index}`; + const projectId = `project-${index % 4}`; + const member = item(id, { + relatedIssue: { ...review.subject, identifier: id }, + project: { id: projectId, name: projectId, urlKey: projectId, color: null, icon: null }, + obligationLeadId: index < grouped ? "TASK-0" : id, + providerLimit: { episode: index < grouped ? "shared" : id, grouping: "account_window", attempts: 1, + retryAt: null, resetAt: null, state: "scheduled", runId: id, agentId: "agent", agentName: "Editor" }, + }); + return new Proxy(member, { get(target, property, receiver) { + if (++reads > size * 36) throw Error("Inbox toolbar exceeded its linear property-read budget"); + return Reflect.get(target, property, receiver); + } }); + }); + const folded = foldAttentionObligations(items); + const projects = inboxProjectOptions(folded, folded.cards, []); + expect(projects).toHaveLength(4); + const matches = folded.cards.filter(card => inboxCardMatchesFilters(folded, card, { + query: "task-399", agentId: "agent", projectId: "project-3", + })); + expect(matches.map(card => card.id)).toEqual(["TASK-0"]); + expect(reads).toBeGreaterThan(size); + }); + it("names what each evidence card is to its lead", () => { const run = item("failed_run:run:r1", { sourceKind: "failed_run" }); const blocked = item("blocker_attention:blocker:t2", { sourceKind: "blocker_attention" }); diff --git a/ui/src/lib/attention-obligations.ts b/ui/src/lib/attention-obligations.ts index f225b89d817..7d1dbbcf4a4 100644 --- a/ui/src/lib/attention-obligations.ts +++ b/ui/src/lib/attention-obligations.ts @@ -30,7 +30,9 @@ export function foldAttentionObligations(items: readonly AttentionItem[]): Folde const evidenceByLeadId = new Map(); for (const item of items) { if (isAttentionObligationEvidence(item) && ids.has(item.obligationLeadId!)) { - evidenceByLeadId.set(item.obligationLeadId!, [...(evidenceByLeadId.get(item.obligationLeadId!) ?? []), item]); + const evidence = evidenceByLeadId.get(item.obligationLeadId!); + if (evidence) evidence.push(item); + else evidenceByLeadId.set(item.obligationLeadId!, [item]); } else { cards.push(item); } @@ -45,6 +47,40 @@ export function attentionObligationEvidence( return folded.evidenceByLeadId.get(item.id) ?? NO_EVIDENCE; } +/** The task rows a provider-limit card represents in the inbox toolbar. */ +function inboxCardMembers(folded: FoldedAttentionObligations, item: AttentionItem) { + return item.providerLimit ? [item, ...attentionObligationEvidence(folded, item)] : [item]; +} + +export function inboxProjectOptions(folded: FoldedAttentionObligations, cards: readonly AttentionItem[], + receipts: readonly { projectId: string | null; projectName: string | null }[]) { + const projects = new Map(); + for (const card of cards) { + for (const member of inboxCardMembers(folded, card)) { + const project = member.project; + if (project) projects.set(project.id, project.name); + } + } + for (const receipt of receipts) { + if (receipt.projectId) projects.set(receipt.projectId, receipt.projectName ?? "Unnamed project"); + } + return [...projects.entries()]; +} + +export function inboxCardMatchesFilters(folded: FoldedAttentionObligations, item: AttentionItem, + filters: { query: string; agentId: string; agentName?: string; projectId: string }) { + const query = filters.query.trim().toLocaleLowerCase(); + return inboxCardMembers(folded, item).some(member => { + if (filters.projectId && member.project?.id !== filters.projectId) return false; + const agentId = member.providerLimit?.agentId ?? member.subject.metadata?.createdByAgentId ?? member.subject.metadata?.originAgentId; + if (filters.agentId && agentId !== filters.agentId + && (agentId || !filters.agentName || member.originAgentName !== filters.agentName)) return false; + if (!query) return true; + return [member.subject.title, member.relatedIssue?.title, member.relatedIssue?.identifier, member.originAgentName, + member.providerLimit?.agentName, member.project?.name, attentionDetailLine(member)].join(" ").toLocaleLowerCase().includes(query); + }); +} + /** * What an evidence card is to its lead: the task that waits on the approval, * the work a failed run blocks, or another cause. diff --git a/ui/src/lib/coordinator-attention.ts b/ui/src/lib/coordinator-attention.ts index aa74b1befaa..02a0622d639 100644 --- a/ui/src/lib/coordinator-attention.ts +++ b/ui/src/lib/coordinator-attention.ts @@ -1,4 +1,4 @@ -import { attentionReceiptText, type AttentionItem, type AttentionPersonalView, type DecisionHistoryItem, type DecisionHistoryOutcomeFilter, type DecisionHistoryScope } from "@paperclipai/shared"; +import { attentionReceiptText, type AttentionItem, type AttentionFeedView, type AttentionPersonalView, type DecisionHistoryItem, type DecisionHistoryOutcomeFilter, type DecisionHistoryScope } from "@paperclipai/shared"; import { queryKeys } from "./queryKeys"; import { isInlineResolvable } from "./attention"; @@ -8,7 +8,7 @@ import { isInlineResolvable } from "./attention"; * cached list. The "For you" key is shared by the page, the sidebar, the mobile * navigation and the Tasks filter, so the badge always agrees with the list. */ -export const coordinatorAttentionQueryKey = (companyId: string, userId?: string | null, view?: AttentionPersonalView) => +export const coordinatorAttentionQueryKey = (companyId: string, userId?: string | null, view?: AttentionFeedView) => userId === undefined && view === undefined ? [...queryKeys.attention(companyId), "coordinator", "pending"] as const : [...queryKeys.attention(companyId), userId, view, "coordinator", "pending"] as const; diff --git a/ui/src/pages/Goals.tsx b/ui/src/pages/Goals.tsx index e079e157646..8ab614975df 100644 --- a/ui/src/pages/Goals.tsx +++ b/ui/src/pages/Goals.tsx @@ -30,7 +30,7 @@ export function Goals() { const goalsView = useQueryView(goalsQuery); if (!selectedCompanyId) { - return ; + return ; } // Keep a loaded list on screen through a failed refetch; only a real @@ -53,7 +53,7 @@ export function Goals() { return (
{goals && goals.length === 0 && ( - ; + return ; } const markAllReadIssues = (tab === "mine" ? visibleMineIssues : unreadTouchedIssues) @@ -3101,7 +3101,7 @@ function StreamlinedInbox({ )} {tab !== "blocked" && allLoaded && !listError && !optionalSourceError && visibleSections.length === 0 && ( - 0); if (!selectedCompanyId) { - return ; + return ; } const hasRunFailures = failedRuns.length > 0; @@ -2631,7 +2631,7 @@ export function Inbox() { )} {tab !== "blocked" && allLoaded && visibleSections.length === 0 && ( - ; + return ; } // Keep loaded routines on screen through a failed refetch; only a real @@ -564,8 +564,9 @@ export function Routines() { return ; } + const emptyList = activeTab === "routines" && sortedRoutines.length === 0; return ( -
+

Routines

+
{showFolderRail ? ( ) : null} -
+
{routineViewState.groupBy === "folder" && hasRoutineFolders ? (
{folderSelection === "all" ? : ( @@ -695,27 +696,13 @@ export function Routines() { /> ) : null} {visibleRoutines.length === 0 && !routineViewState.statuses.length ? ( -
- -
+ ) : sortedRoutines.length === 0 ? ( -
- routineViewState[key].length) || folderSelection === "all" ? "No routines match this view." : "This folder is empty."} - /> - {folderSelection !== "all" ? ( -
- -
- ) : null} -
+ routineViewState[key].length) || folderSelection === "all" ? "No routines match this view." : "This folder is empty."} + action={folderSelection !== "all" ? "New routine in this folder" : undefined} + onAction={openCreateRoutine} + /> ) : (
{routineSections.map((group) => { diff --git a/ui/src/pages/Routines.tsx b/ui/src/pages/Routines.tsx index 71ad91140df..ecbed667126 100644 --- a/ui/src/pages/Routines.tsx +++ b/ui/src/pages/Routines.tsx @@ -527,7 +527,7 @@ export function Routines() { } if (!selectedCompanyId) { - return ; + return ; } if (streamlinedUiEnabled && legacyRunsRequested) { @@ -585,8 +585,9 @@ export function Routines() { ); } + const emptyList = sortedRoutines.length === 0; return ( -
+

Routines

updateRoutineView({ query })} @@ -653,7 +654,7 @@ export function Routines() { onRetry={foldersView.retry} retrying={foldersView.isFetching} /> ) : null} -
+
{showFolderRail ? ( ) : null} -
+
{routineViewState.groupBy === "folder" && routineFolders && !hasRoutineFolders && !foldersLoading && visibleRoutines.length > 0 ? ( ) : null} {visibleRoutines.length === 0 && !routineViewState.statuses.length ? ( -
- -
+ ) : sortedRoutines.length === 0 ? ( -
- routineViewState[key].length) || folderSelection === "all" ? "No routines match this view." : "This folder is empty."} - /> - {folderSelection !== "all" ? ( -
- -
- ) : null} -
+ routineViewState[key].length) || folderSelection === "all" ? "No routines match this view." : "This folder is empty."} + action={folderSelection !== "all" ? "New routine in this folder" : undefined} + onAction={openCreateRoutine} + /> ) : (
{routineSections.map((group) => { diff --git a/ui/src/pages/Secrets.tsx b/ui/src/pages/Secrets.tsx index c04a399d4e7..30f818e4859 100644 --- a/ui/src/pages/Secrets.tsx +++ b/ui/src/pages/Secrets.tsx @@ -2197,7 +2197,7 @@ export function Secrets() { return ( -
+
@@ -2241,7 +2241,7 @@ export function Secrets() { setActiveTab(value as SecretsTab)} - className="flex flex-col gap-4" + className="flex flex-1 flex-col gap-4" >
) : null} -
+
{secretsView.kind === "error" || userDefinitionsView.kind === "error" ? (
) : ( -
+
{showFolderView && folderPath ? (
{renderSecretsBreadcrumb()} @@ -2387,7 +2387,7 @@ export function Secrets() { ))}
) : showFolderView && folderPath && activeSecretFilterCount === 0 ? ( - ) : ( - @@ -2528,7 +2528,7 @@ export function Secrets() { )} {!hideProposalsTab && ( - + {selectedCompanyId ? ( ) : null} diff --git a/ui/src/pages/secrets/MyUserSecretsTab.tsx b/ui/src/pages/secrets/MyUserSecretsTab.tsx index a7cc9a3bd19..19cc9042a5e 100644 --- a/ui/src/pages/secrets/MyUserSecretsTab.tsx +++ b/ui/src/pages/secrets/MyUserSecretsTab.tsx @@ -60,7 +60,7 @@ export function MyUserSecretsTab({ companyId }: { companyId: string }) { ); return ( -
+

Values only you provide. Agents use them when they work for you. {missingCount > 0 ? ( @@ -79,7 +79,7 @@ export function MyUserSecretsTab({ companyId }: { companyId: string }) { retrying={mySecretsView.isFetching} /> ) : entries.length === 0 && !mySecretsQuery.isPending && mySecretsView.kind !== "reconnecting" ? ( - diff --git a/ui/src/pages/secrets/ProposalsTab.tsx b/ui/src/pages/secrets/ProposalsTab.tsx index de54b4ed59a..7b4713170af 100644 --- a/ui/src/pages/secrets/ProposalsTab.tsx +++ b/ui/src/pages/secrets/ProposalsTab.tsx @@ -461,7 +461,7 @@ export function ProposalsTab({ if (pending.length === 0 && decided.length === 0 && !decidedFailed) { return ( -

) : definitions.length === 0 && !definitionsQuery.isPending && definitionsView.kind !== "reconnecting" ? ( -