mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +01:00
fix(inbox): group repeated provider failures and clear recovered tasks (#22846)
## Thinking Path > - Paperclip helps people manage work that agents do. > - The inbox tells a person which tasks need a decision. > - A provider usage limit can stop several attempts on one task or affect several tasks. > - Separate failure cards made it hard to tell which tasks still needed attention. > - This change groups failures using the account, reset time, or retry links that Paperclip can verify. > - A person can now see which task to retry, which tasks are waiting, and which ones recovered. ## Linked Issues or Issue Description **What existing behavior does this improve?** It improves the Coordinator inbox when a provider limits usage. **Current behavior** Repeated run failures can fill the inbox. Resolved failures can still appear beside open decisions. **Proposed behavior** Show personal actions in Needs you, automatic retries and snoozes in Waiting, and past events in History. Keep an archived retry chain hidden during automatic attempts. Return it to Needs you when a person must act. **Additional context** Related work includes #18020 on completed tasks, #9704 on archive behavior, and #21570 on usage limits in chat. ## What Changed - Group verified account and reset windows. When that evidence is missing, count linked attempts per task and show the tasks in a collapsible group. - Separate the reported reset time from each task’s retry schedule. Keep unresolved ownership recoveries visible after task closure. Use persisted native retry requests to preserve the original archive and increment the attempt count. - Keep personal archive in the card menu. Put decision receipts and run logs in History. - Align inbox filters, tabs, and history. Share empty-state artwork and placement across Inbox, Goals, Routines, and Secrets. - Index run-history pages and resumed-work lookups, and rate-limit history requests per company and viewer. Add synthetic fixtures for both grouping paths and a manual walkthrough. ## Verification - The author and a human tester completed the synthetic retry-chain walkthrough. Chromium also verified archive, repeat failure, exhaustion, and recovery. - The 64 focused server tests and the UI and server typechecks passed before rebasing. See `doc/testing/coordinator-inbox-test-drive.md` to repeat the manual checks. - The shared SDK input check and all 64 focused server tests passed after rebasing. The OpenAPI suite (59 tests), API catalog suite (2,309 tests), and both demo seed paths passed locally after the CI fixes. - The affected inbox and native-runtime suites passed locally after merging the upstream conformance test fix in #22854. The browser access-denial scenarios passed three runs each for 403 and 404. - The migration checks and 79 focused tests passed, including an index-plan regression with 5,000 unrelated runs. The migration and query plan were reverified after renumbering. [Full CI on `cf52b80161`](https://github.com/paperclipai/paperclip/actions/runs/45529834793) passed after rerunning a timed-out server shard. ## Risks The attention feed reads retry ancestry. Long chains can increase query cost. Task and company checks bound the traversal, and cycle detection stops repeated visits. Providers that omit the reset time leave the card with an unknown reset. Migration 0508 adds two indexes concurrently. Each run-history page returns at most 100 records. ## Model Used OpenAI Codex, GPT-6 family, with repository editing, local test execution, and browser verification. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Scott Tong <scott@scotts-mbp-m5-max.local> Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
50 files changed
+1759
-234
No files matched your search
@@ -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
|
||||
|
||||
+14
-1
@@ -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
|
||||
|
||||
@@ -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
|
||||
```
|
||||
+29
-1
@@ -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 |
|
||||
|
||||
@@ -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",
|
||||
]);
|
||||
|
||||
|
||||
@@ -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';
|
||||
+296
-2
@@ -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": [
|
||||
+7
@@ -3543,6 +3543,13 @@
|
||||
"when": 1795561452000,
|
||||
"tag": "0507_special_kang",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 508,
|
||||
"version": "7",
|
||||
"when": 1795572002132,
|
||||
"tag": "0508_normal_riptide",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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')`,
|
||||
|
||||
@@ -201,6 +201,8 @@ export type {
|
||||
AttentionTaskIndex,
|
||||
AttentionFeedView,
|
||||
AttentionItem,
|
||||
AttentionProviderLimit,
|
||||
AttentionRunHistoryEntry,
|
||||
AttentionItemDetail,
|
||||
AttentionItemDismissal,
|
||||
AttentionFeedQuery,
|
||||
|
||||
@@ -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<AttentionItem, "sourceKind" | "subj
|
||||
}
|
||||
}
|
||||
|
||||
export interface AttentionProviderLimit {
|
||||
episode: string;
|
||||
grouping: "account_window" | "retry_chain";
|
||||
attempts: number;
|
||||
retryAt: string | null;
|
||||
/** A reset reported by the provider. Scheduled rechecks have their own timestamp. */
|
||||
resetAt: string | null;
|
||||
state: "scheduled" | "retry_requested" | "needs_retry";
|
||||
runId: string;
|
||||
agentId: string;
|
||||
agentName: string;
|
||||
}
|
||||
|
||||
export interface AttentionRunHistoryEntry {
|
||||
runId: string;
|
||||
agentId: string;
|
||||
agentName: string;
|
||||
taskId: string;
|
||||
taskTitle: string;
|
||||
identifier: string | null;
|
||||
recordedAt: string;
|
||||
reason: string;
|
||||
outcome: string;
|
||||
}
|
||||
|
||||
export interface AttentionItem {
|
||||
providerLimit?: AttentionProviderLimit;
|
||||
id: string;
|
||||
companyId: string;
|
||||
sourceKind: AttentionSourceKind;
|
||||
@@ -650,6 +676,9 @@ export interface AttentionItem {
|
||||
}
|
||||
|
||||
export interface AttentionFeed {
|
||||
/** Personal automatic retries and snoozed obligations. */
|
||||
waitingCount?: number;
|
||||
nextSnoozeAt?: string | null;
|
||||
companyId: string;
|
||||
generatedAt: string;
|
||||
totalCount: number;
|
||||
|
||||
@@ -64,6 +64,8 @@ export type {
|
||||
AttentionTaskIndex,
|
||||
AttentionFeedView,
|
||||
AttentionItem,
|
||||
AttentionProviderLimit,
|
||||
AttentionRunHistoryEntry,
|
||||
AttentionItemDetail,
|
||||
AttentionItemDismissal,
|
||||
AttentionFeedQuery,
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
// Simulate provider outcomes inside the isolated local inbox dev database.
|
||||
import { readFileSync, realpathSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { requestAgentHireInTransaction } from "../src/services/agent-lifecycle.js";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { agents, agentRuntimeState, approvals, closeRegisteredClients, companies, companyMemberships, createDb, getPostgresDataDirectory,
|
||||
type Db, heartbeatRunEvents, heartbeatRuns, inboxDismissals, issueRecoveryActions, issues } from "@paperclipai/db";
|
||||
|
||||
const phase = process.argv[2] ?? "reset";
|
||||
const chainPhases = ["chains", "chains-repeat", "chains-exhausted", "chains-recovered"];
|
||||
if (!["reset", "one-left", "all-recovered", "repeat", ...chainPhases].includes(phase)) throw new Error("Unknown inbox demo phase");
|
||||
const dir = realpathSync(fileURLToPath(new URL("../../tmp/inbox-drive/instances/default/db", import.meta.url)));
|
||||
const port = Number(readFileSync(dir + "/postmaster.pid", "utf8").split("\n")[3]);
|
||||
if (!Number.isInteger(port) || port < 1 || port > 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" });
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -1506,6 +1506,7 @@ const BOARD_ONLY_OPERATIONS = new Set([
|
||||
"GET /api/issues/{id}/decision-receipts",
|
||||
"GET /api/issues/{id}/chat-handoffs",
|
||||
"GET /api/companies/{companyId}/attention/history",
|
||||
"GET /api/companies/{companyId}/attention/run-history",
|
||||
"GET /api/companies/{companyId}/attention/summary",
|
||||
"GET /api/companies/{companyId}/attention/tasks",
|
||||
"POST /api/companies/{companyId}/attention/{sourceKind}/{sourceId}/claim",
|
||||
@@ -6640,8 +6641,8 @@ registry.registerPath({
|
||||
includeDismissed: z.enum(["true", "false"]).optional(),
|
||||
archived: z.enum(["true", "false"]).optional(),
|
||||
all: z.enum(["true", "false"]).optional(),
|
||||
view: z.enum(["mine", "unassigned", "company", "archived", "all"]).optional()
|
||||
.describe("Audience slice (PAP-749). `all` (default) keeps the full feed; `viewCounts` and the For you badge `deskBadgeCount` ignore it. `mine` also returns `receipts`: what a different person did with your cards in the last 7 days. `archived` returns only the open cards you archived or snoozed for yourself, whatever their audience; `viewCounts.archived` counts them and is never in the badge. `viewCounts.all` counts the Everyone tab (every person's open cards, board members only) and is never in the badge."),
|
||||
view: z.enum(["mine", "unassigned", "company", "archived", "all", "waiting"]).optional()
|
||||
.describe("Audience slice (PAP-749). `waiting` lists snoozed requests and automatic retries visible to the caller. `all` (default) keeps the full feed; `viewCounts` and the For you badge `deskBadgeCount` ignore it. `mine` also returns `receipts`: what a different person did with your cards in the last 7 days. `archived` returns only the open cards you archived or snoozed for yourself, whatever their audience; `viewCounts.archived` counts them and is never in the badge. `viewCounts.all` counts the Everyone tab (every person's open cards, board members only) and is never in the badge."),
|
||||
activitySince: z.string().datetime().optional(),
|
||||
activityUntil: z.string().datetime().optional(),
|
||||
queue: z.string().min(1).optional(),
|
||||
@@ -6654,6 +6655,8 @@ registry.registerPath({
|
||||
});
|
||||
|
||||
const attentionSummaryResponseSchema = z.object({
|
||||
waitingCount: z.number().int().nonnegative().optional(),
|
||||
nextSnoozeAt: z.string().datetime().optional(),
|
||||
companyId: z.string().uuid(),
|
||||
generatedAt: z.string().datetime(),
|
||||
totalCount: z.number().int().nonnegative(),
|
||||
@@ -6747,6 +6750,29 @@ registry.registerPath({
|
||||
|
||||
// ─── Decisions ──────────────────────────────────────────────────────────────
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/api/companies/{companyId}/attention/run-history",
|
||||
tags: ["inbox"],
|
||||
summary: "List recent failures in inbox run history",
|
||||
description: "Requires a board user. Returns up to 100 recent failed runs on tasks visible to the caller, newest first. For the next page, pass the last row’s recordedAt and runId as at and id together. Limited to 60 requests per minute per board user and company.",
|
||||
request: {
|
||||
params: z.object({ companyId: z.string() }),
|
||||
query: z.object({ at: z.string().datetime().optional(), id: z.string().uuid().optional() }).strict(),
|
||||
},
|
||||
responses: {
|
||||
200: r.ok(z.array(z.object({
|
||||
runId: z.string().uuid(), agentId: z.string().uuid(), agentName: z.string(),
|
||||
taskId: z.string().uuid(), taskTitle: z.string(), identifier: z.string().nullable(),
|
||||
recordedAt: z.string().datetime(), reason: z.string(), outcome: z.string(),
|
||||
}))),
|
||||
400: r.badRequest,
|
||||
401: r.unauthorized,
|
||||
403: r.forbidden,
|
||||
429: r.tooManyRequests,
|
||||
},
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/api/companies/{companyId}/attention/history",
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { and, asc, desc, eq, inArray, notInArray, sql } from "drizzle-orm";
|
||||
import { agents, heartbeatRunEvents, heartbeatRuns, type Db } from "@paperclipai/db";
|
||||
import { agents, heartbeatRunEvents, heartbeatRuns, issueRecoveryActions, type Db } from "@paperclipai/db";
|
||||
|
||||
import { providerWorkResumed, usageLimitFailure } from "./attention-provider-limits.js";
|
||||
|
||||
export function listAttentionExhaustedRuns(db: Db, companyId: string) {
|
||||
// Recovery can revisit an exhausted run. Deduplicate its historical events
|
||||
@@ -31,6 +33,17 @@ export function listAttentionExhaustedRuns(db: Db, companyId: string) {
|
||||
status: heartbeatRuns.status,
|
||||
error: heartbeatRuns.error,
|
||||
errorCode: heartbeatRuns.errorCode,
|
||||
providerLimited: sql<boolean>`${usageLimitFailure} is true`,
|
||||
providerResumed: sql<boolean>`case when ${usageLimitFailure} then ${providerWorkResumed} else false end`,
|
||||
providerRetryAt: sql<string | null>`${heartbeatRuns.resultJson}#>>'{providerFailure,retryAt}'`,
|
||||
account: sql<string | null>`coalesce(nullif(${heartbeatRuns.contextSnapshot}#>>'{aiConnection,subscriptionId}', ''),
|
||||
nullif(${heartbeatRuns.contextSnapshot}#>>'{aiConnection,connectionId}', ''))`,
|
||||
settledProviderHold: sql<boolean>`${heartbeatRuns.errorCode} = 'native_provider_usage_limit' and exists(
|
||||
select 1 from ${issueRecoveryActions} hold where hold.company_id = ${heartbeatRuns.companyId}
|
||||
and hold.source_issue_id = coalesce(${heartbeatRuns.issueId}, ${heartbeatRuns.nativeIssueId})
|
||||
and hold.evidence->>'runId' = ${heartbeatRuns.id}::text and hold.cause = 'native_provider_usage_limit'
|
||||
and hold.status in ('resolved','cancelled'))`,
|
||||
boundTaskId: sql<string | null>`coalesce(${heartbeatRuns.issueId}, ${heartbeatRuns.nativeIssueId})`,
|
||||
// Preserve JSON types and issueId/taskId fallback semantics without
|
||||
// transferring prompts, transcripts, or the rest of the run context.
|
||||
contextSnapshot: sql<Record<string, unknown>>`jsonb_build_object(
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { AttentionItem } from "@paperclipai/shared";
|
||||
import { groupProviderLimits, providerLimitForHold } from "./attention-provider-limits.js";
|
||||
|
||||
const run = { runId: "run-1", taskId: "task-1", agentId: "agent-1", agentName: "Editor", account: "account-1" };
|
||||
const reset = "2026-11-24T21:00:00Z";
|
||||
const scheduled = { providerLimitResetAt: reset, providerLimitAutomatic: true };
|
||||
|
||||
describe("provider usage limits in the inbox", () => {
|
||||
it("uses the same known account and reset across agents, keeping unverified or estimated windows separate", () => {
|
||||
const episode = providerLimitForHold(run, scheduled, "").episode;
|
||||
const other = { ...run, runId: "run-2", taskId: "task-2", agentId: "agent-2" };
|
||||
expect(providerLimitForHold(other, scheduled, "").episode).toBe(episode);
|
||||
expect(providerLimitForHold({ ...other, account: "account-2" }, scheduled, "").episode).not.toBe(episode);
|
||||
expect(providerLimitForHold(other, { ...scheduled, providerLimitEstimated: true }, "").episode).not.toBe(episode);
|
||||
expect(providerLimitForHold({ ...other, account: null }, scheduled, "").episode).not.toBe(episode);
|
||||
});
|
||||
|
||||
it("labels a scheduled recheck independently of what the provider reported", () => {
|
||||
const retryAt = new Date(reset).toISOString();
|
||||
expect(providerLimitForHold(run, { ...scheduled, providerLimitEstimated: true }, ""))
|
||||
.toMatchObject({ grouping: "retry_chain", resetAt: null, retryAt, state: "scheduled" });
|
||||
expect(providerLimitForHold({ ...run, account: null }, scheduled, ""))
|
||||
.toMatchObject({ grouping: "retry_chain", resetAt: retryAt, state: "scheduled" });
|
||||
expect(providerLimitForHold(run, scheduled, ""))
|
||||
.toMatchObject({ grouping: "account_window", resetAt: retryAt });
|
||||
});
|
||||
|
||||
it("keeps the dismissal stable across lead changes and isolates different recipients", () => {
|
||||
const member = (id: string, userId: string, manual = false) => ({
|
||||
id, audience: { kind: "user", userId },
|
||||
providerLimit: providerLimitForHold({ ...run, runId: id },
|
||||
{ ...scheduled, ...(manual && { providerLimitResume: { state: "not_requested" } }) }, ""),
|
||||
} as AttentionItem);
|
||||
const first = member("first", "me");
|
||||
groupProviderLimits([first]);
|
||||
const key = first.dismissalKey;
|
||||
const manual = member("second", "me", true);
|
||||
const other = member("third", "someone-else");
|
||||
groupProviderLimits([first, manual, other]);
|
||||
expect(first.obligationLeadId).toBe(manual.id);
|
||||
expect(manual.dismissalKey).toBe(key);
|
||||
expect(other.obligationLeadId).toBe(other.id);
|
||||
expect(other.dismissalKey).not.toBe(key);
|
||||
});
|
||||
|
||||
it("keeps a queued retry waiting, and a known reset without an automatic retry actionable", () => {
|
||||
expect(providerLimitForHold(run, { ...scheduled, providerLimitResume: { state: "requested" } }, "").state).toBe("retry_requested");
|
||||
expect(providerLimitForHold(run, { providerLimitResetAt: reset }, "Retry this task.").state).toBe("needs_retry");
|
||||
expect(providerLimitForHold(run, { providerLimitResetAt: reset }, "Paperclip will retry this task then.").state).toBe("scheduled");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,200 @@
|
||||
import { and, eq, inArray, or, sql, type SQL } from "drizzle-orm";
|
||||
import { agentWakeupRequests, agents, heartbeatRuns, issueRecoveryActions, issues, type Db } from "@paperclipai/db";
|
||||
import type { AttentionItem, AttentionProviderLimit, AttentionRunHistoryEntry } from "@paperclipai/shared";
|
||||
import { alias } from "drizzle-orm/pg-core";
|
||||
import { createHash } from "node:crypto";
|
||||
import { attentionIssueCondition } from "./issue-visibility.js";
|
||||
|
||||
const taskId = sql<string>`coalesce(${heartbeatRuns.issueId}::text, ${heartbeatRuns.nativeIssueId}::text,
|
||||
${heartbeatRuns.contextSnapshot}->>'issueId', ${heartbeatRuns.contextSnapshot}->>'taskId')`;
|
||||
const account = sql<string | null>`coalesce(nullif(${heartbeatRuns.contextSnapshot}#>>'{aiConnection,subscriptionId}', ''),
|
||||
nullif(${heartbeatRuns.contextSnapshot}#>>'{aiConnection,connectionId}', ''))`;
|
||||
|
||||
/** A reset or queued retry does not establish recovery. Keep this probe aligned with the attention resumed index. */
|
||||
export const providerWorkResumed = sql<boolean>`exists(select 1 from heartbeat_runs later where later.company_id = ${heartbeatRuns.companyId}
|
||||
and later.created_at > ${heartbeatRuns.createdAt} and later.status in ('running','succeeded')
|
||||
and coalesce(later.issue_id::text,later.native_issue_id::text,later.context_snapshot->>'issueId',later.context_snapshot->>'taskId') = ${taskId})`;
|
||||
|
||||
export const usageLimitFailure = sql`(${heartbeatRuns.errorCode} in ('provider_limit_wait','native_provider_usage_limit')
|
||||
or ${heartbeatRuns.resultJson}#>>'{providerFailure,category}' in ('rate_limit','quota_exhausted'))`;
|
||||
|
||||
export async function scheduledProviderWaits(db: Db, companyId: string) {
|
||||
const retry = alias(heartbeatRuns, "scheduled_provider_retry");
|
||||
const rows = await db.select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, agentId: agents.id, agentName: agents.name,
|
||||
status: heartbeatRuns.status, error: heartbeatRuns.error, errorCode: heartbeatRuns.errorCode, account, taskId,
|
||||
createdAt: heartbeatRuns.createdAt, updatedAt: heartbeatRuns.updatedAt, finishedAt: heartbeatRuns.finishedAt,
|
||||
resetAt: sql<string | null>`coalesce(${heartbeatRuns.resultJson}#>>'{providerLimitWait,resetAt}', ${heartbeatRuns.resultJson}#>>'{providerFailure,retryAt}')`,
|
||||
reported: sql<boolean>`case when ${heartbeatRuns.errorCode} = 'provider_limit_wait' then
|
||||
${heartbeatRuns.resultJson}#>>'{providerLimitWait,resetReported}' = 'true' else true end`,
|
||||
retryStatus: retry.status, due: retry.scheduledRetryAt }).from(retry)
|
||||
.innerJoin(heartbeatRuns, and(eq(heartbeatRuns.id, retry.retryOfRunId), eq(heartbeatRuns.companyId, companyId)))
|
||||
.innerJoin(agents, and(eq(agents.id, heartbeatRuns.agentId), eq(agents.companyId, companyId)))
|
||||
.where(and(eq(retry.companyId, companyId), inArray(retry.status, ["scheduled_retry", "queued"]), usageLimitFailure,
|
||||
sql`coalesce(${retry.issueId}::text, ${retry.nativeIssueId}::text, ${retry.contextSnapshot}->>'issueId',
|
||||
${retry.contextSnapshot}->>'taskId', ${taskId}) = ${taskId}`,
|
||||
sql`not ${providerWorkResumed}`));
|
||||
return rows.filter(row => row.taskId).map(row => {
|
||||
const limit = providerLimitForHold({ ...row, runId: row.id },
|
||||
{ providerLimitResetAt: row.resetAt, providerLimitAutomatic: true, providerLimitEstimated: !row.reported }, "");
|
||||
limit.retryAt = row.due?.toISOString() ?? null;
|
||||
if (row.retryStatus === "queued") limit.state = "retry_requested";
|
||||
return { ...row, boundTaskId: row.taskId, contextSnapshot: { issueId: row.taskId }, exhaustionMessage: null, limit };
|
||||
});
|
||||
}
|
||||
|
||||
/** Some native limit failures never emit a bounded-retry exhaustion receipt. */
|
||||
export async function recoveredProviderRuns(db: Db, companyId: string, runIds: string[], readCondition: SQL) {
|
||||
if (!runIds.length) return [];
|
||||
return db.select({ id: heartbeatRuns.id }).from(heartbeatRuns)
|
||||
.innerJoin(issues, and(eq(issues.companyId, companyId), sql`${issues.id}::text = ${taskId}`))
|
||||
.where(and(eq(heartbeatRuns.companyId, companyId), inArray(heartbeatRuns.id, runIds),
|
||||
eq(heartbeatRuns.errorCode, "native_provider_usage_limit"), readCondition,
|
||||
or(inArray(issues.status, ["done", "cancelled"]), providerWorkResumed, sql`exists(
|
||||
select 1 from ${issueRecoveryActions} hold where hold.company_id = ${heartbeatRuns.companyId}
|
||||
and hold.source_issue_id = ${issues.id} and hold.evidence->>'runId' = ${heartbeatRuns.id}::text
|
||||
and hold.cause = 'native_provider_usage_limit' and hold.status in ('resolved','cancelled'))`)));
|
||||
}
|
||||
|
||||
export async function providerHoldRuns(db: Db, companyId: string, runIds: string[]) {
|
||||
if (!runIds.length) return new Map<string, ProviderRun>();
|
||||
const rows = await db.select({ runId: heartbeatRuns.id, agentId: agents.id, agentName: agents.name,
|
||||
taskId, account, resumed: providerWorkResumed }).from(heartbeatRuns)
|
||||
.innerJoin(agents, and(eq(agents.id, heartbeatRuns.agentId), eq(agents.companyId, companyId)))
|
||||
.where(and(eq(heartbeatRuns.companyId, companyId), inArray(heartbeatRuns.id, runIds)));
|
||||
return new Map(rows.map(row => [row.runId, row]));
|
||||
}
|
||||
|
||||
type ProviderRun = { runId: string; agentId: string; agentName: string; account: string | null; taskId: string; resumed?: boolean };
|
||||
|
||||
export function providerLimitForHold(run: ProviderRun, evidence: Record<string, unknown>, nextAction: string): AttentionProviderLimit {
|
||||
const reset = evidence.providerLimitResetAt;
|
||||
const resetAt = typeof reset === "string" && Number.isFinite(Date.parse(reset)) ? new Date(reset).toISOString() : null;
|
||||
const resume = evidence.providerLimitResume as { state?: string } | undefined;
|
||||
// Older holds persisted the scheduler's promise only in its canonical next action.
|
||||
const automatic = evidence.providerLimitAutomatic ?? nextAction.includes("Paperclip will retry this task");
|
||||
const state = resume?.state === "requested" ? "retry_requested"
|
||||
: !resume && automatic === true ? "scheduled" : "needs_retry";
|
||||
const reportedReset = evidence.providerLimitEstimated || nextAction.includes("did not report") ? null : resetAt;
|
||||
const sharedWindow = run.account && reportedReset;
|
||||
const episode = sharedWindow ? createHash("sha256").update(JSON.stringify([run.account, resetAt])).digest("hex") : episodeForRun(run.runId);
|
||||
return { episode, grouping: sharedWindow ? "account_window" : "retry_chain", attempts: 1,
|
||||
resetAt: reportedReset, retryAt: state === "scheduled" ? resetAt : null, state, runId: run.runId, agentId: run.agentId, agentName: run.agentName };
|
||||
}
|
||||
|
||||
function episodeForRun(id: string) {
|
||||
return createHash("sha256").update(id).digest("hex");
|
||||
}
|
||||
|
||||
function obligationKey(episode: string, audience: AttentionItem["audience"]) {
|
||||
return `provider-limit:${episode}:${audience.kind}:${audience.userId ?? ""}`;
|
||||
}
|
||||
|
||||
/** A retry has to link to the same task. A cooldown's source run can belong to a different task. */
|
||||
export async function attachProviderRetryChains(db: Db, companyId: string, items: AttentionItem[],
|
||||
dismissals: ReadonlyMap<string, unknown>) {
|
||||
const members = items.filter(item => item.providerLimit?.grouping === "retry_chain");
|
||||
const legacyDismissals = new Map<string, string>();
|
||||
if (!members.length) return legacyDismissals;
|
||||
const ids = [...new Set(members.map(item => item.providerLimit!.runId))];
|
||||
// A native retry may bind a durable task retry request without setting retry_of_run_id.
|
||||
const rows = await db.execute<{ run_id: string; attempts: string[] }>(sql`
|
||||
with recursive chain(run_id, task_id, id, agent_id, parent_id, retry_request_id, path, limited) as (
|
||||
select id, ${taskId}, id, agent_id, retry_of_run_id, context_snapshot->>'taskRetryRequestId', array[id], true
|
||||
from ${heartbeatRuns}
|
||||
where company_id = ${companyId} and ${inArray(heartbeatRuns.id, ids)}
|
||||
union all
|
||||
select c.run_id, c.task_id, r.id, r.agent_id, r.retry_of_run_id, r.context_snapshot->>'taskRetryRequestId',
|
||||
c.path || r.id,
|
||||
r.error_code in ('provider_limit_wait','native_provider_usage_limit')
|
||||
or r.result_json#>>'{providerFailure,category}' in ('rate_limit','quota_exhausted')
|
||||
from chain c
|
||||
left join ${agentWakeupRequests} wake on c.parent_id is null
|
||||
and wake.company_id = ${companyId} and wake.run_id = c.id and wake.agent_id = c.agent_id
|
||||
and wake.id::text = c.retry_request_id and wake.reason = 'task_retry'
|
||||
and wake.payload->>'issueId' = c.task_id
|
||||
and wake.payload#>>'{taskRetry,schema}' = 'paperclip.task-retry.v1'
|
||||
and wake.payload#>>'{taskRetry,generationId}' = c.retry_request_id
|
||||
join ${heartbeatRuns} r on r.company_id = ${companyId} and r.id = coalesce(c.parent_id,
|
||||
case when wake.payload#>>'{taskRetry,sourceRunId}' ~* '^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$'
|
||||
then (wake.payload#>>'{taskRetry,sourceRunId}')::uuid end)
|
||||
where coalesce(r.issue_id::text, r.native_issue_id::text, r.context_snapshot->>'issueId', r.context_snapshot->>'taskId') = c.task_id
|
||||
and r.status in ('failed','timed_out','cancelled')
|
||||
and not r.id = any(c.path)
|
||||
)
|
||||
select run_id, array_agg(id order by cardinality(path) desc) as attempts
|
||||
from chain where limited group by run_id
|
||||
`);
|
||||
const byRun = new Map(rows.map(row => [row.run_id, row.attempts]));
|
||||
for (const item of members) {
|
||||
const limit = item.providerLimit!;
|
||||
const attempts = byRun.get(limit.runId);
|
||||
if (!attempts?.length) continue;
|
||||
limit.episode = episodeForRun(attempts[0]!);
|
||||
limit.attempts = attempts.length;
|
||||
|
||||
// Honor a personal archive written for an individual attempt before chain grouping.
|
||||
if (!dismissals.size) continue;
|
||||
const key = obligationKey(limit.episode, item.audience);
|
||||
for (const runId of attempts) {
|
||||
const oldKey = `attention:${obligationKey(episodeForRun(runId), item.audience)}`;
|
||||
if (dismissals.has(oldKey)) {
|
||||
legacyDismissals.set(key, oldKey);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return legacyDismissals;
|
||||
}
|
||||
|
||||
/** Group only after task access and personal routing, keeping the dismissal stable as membership changes. */
|
||||
export function groupProviderLimits(items: AttentionItem[], legacyDismissals?: ReadonlyMap<string, string>) {
|
||||
const groups = new Map<string, AttentionItem[]>();
|
||||
for (const item of items) {
|
||||
if (!item.providerLimit) continue;
|
||||
const key = obligationKey(item.providerLimit.episode, item.audience);
|
||||
const members = groups.get(key) ?? [];
|
||||
members.push(item);
|
||||
groups.set(key, members);
|
||||
}
|
||||
for (const [key, members] of groups) {
|
||||
let lead = members.find(item => item.providerLimit?.state === "needs_retry") ?? members[0]!;
|
||||
if (lead.providerLimit!.grouping === "retry_chain") {
|
||||
// Old hold receipts can still be active when the next attempt records its own state.
|
||||
for (const item of members) {
|
||||
const difference = item.providerLimit!.attempts - lead.providerLimit!.attempts;
|
||||
if (difference > 0 || (difference === 0 && item.activityAt > lead.activityAt)) lead = item;
|
||||
}
|
||||
}
|
||||
for (const member of members) {
|
||||
member.dismissalKey = legacyDismissals?.get(key) ?? `attention:${key}`;
|
||||
member.obligationKey = key;
|
||||
member.obligationLeadId = lead.id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Only load diagnostic history when opened. Every run must join a task the board actor may read. */
|
||||
export function attentionRunHistoryQuery(db: Db, companyId: string, readCondition: SQL, before?: { at: string; id: string }) {
|
||||
return db.select({ runId: heartbeatRuns.id, agentId: agents.id, agentName: agents.name,
|
||||
taskId: issues.id, taskTitle: issues.title, identifier: issues.identifier, status: issues.status,
|
||||
holdStatus: issueRecoveryActions.status, recordedAt: sql<string>`to_char(${heartbeatRuns.createdAt} at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`, code: heartbeatRuns.errorCode,
|
||||
resumed: providerWorkResumed })
|
||||
.from(heartbeatRuns).innerJoin(issues, and(eq(issues.companyId,companyId), sql`${issues.id}::text = ${taskId}`))
|
||||
.innerJoin(agents, and(eq(agents.id, heartbeatRuns.agentId), eq(agents.companyId, companyId)))
|
||||
.leftJoin(issueRecoveryActions, and(eq(issueRecoveryActions.companyId, companyId), eq(issueRecoveryActions.sourceIssueId, issues.id),
|
||||
sql`${issueRecoveryActions.evidence}->>'runId' = ${heartbeatRuns.id}::text`, eq(issueRecoveryActions.cause, "native_provider_usage_limit")))
|
||||
.where(and(eq(heartbeatRuns.companyId,companyId),
|
||||
sql`(${heartbeatRuns.status} in ('failed', 'timed_out') or ${heartbeatRuns.errorCode} = 'provider_limit_wait')`,
|
||||
attentionIssueCondition(), readCondition,
|
||||
before ? sql`(${heartbeatRuns.createdAt}, ${heartbeatRuns.id}) < (${before.at}::timestamptz, ${before.id}::uuid)` : undefined))
|
||||
.orderBy(sql`${heartbeatRuns.createdAt} desc nulls last`, sql`${heartbeatRuns.id} desc nulls last`).limit(100);
|
||||
}
|
||||
|
||||
export async function attentionRunHistory(db: Db, companyId: string, readCondition: SQL,
|
||||
before?: { at: string; id: string }): Promise<AttentionRunHistoryEntry[]> {
|
||||
const rows = await attentionRunHistoryQuery(db, companyId, readCondition, before);
|
||||
return rows.map(({ status, holdStatus, recordedAt, code, resumed, ...row }) => ({ ...row, recordedAt,
|
||||
reason: ["native_provider_usage_limit", "provider_limit_wait"].includes(code ?? "") ? "Provider usage limit" : "Failed run",
|
||||
outcome: status === "done" ? "Task completed" : status === "cancelled" ? "Task cancelled" : resumed ? "Work resumed"
|
||||
: holdStatus === "resolved" ? "Recovery resolved" : "Run recorded" }));
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { attachProviderRetryChains, groupProviderLimits, recoveredProviderRuns, scheduledProviderWaits, providerHoldRuns, providerLimitForHold } from "./attention-provider-limits.js";
|
||||
import { recoveryActionAttentionCondition, ATTENTION_BUDGET_WARNING_PERCENT, ATTENTION_AGENT_ERROR_STATUS, collapsePendingConfirmationsToNewest, loadNewestSettledConfirmationAt, readRunIssueId, listFailedRunsWithNewerRun, requiresReviewAttention, terminalBlockerRequiresAttention } from "./attention-source-eligibility.js";
|
||||
import { approvalExecutionIssueCondition, firstApprovalIssueId } from "./approval-visibility.js";
|
||||
import { and, asc, desc, eq, inArray, isNull, ne, notInArray, or, sql, type SQL } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
activityLog,
|
||||
agentRuntimeState,
|
||||
agents,
|
||||
approvals,
|
||||
assets,
|
||||
@@ -1358,7 +1360,7 @@ export function resolveAttentionAudience(
|
||||
/** Whether a resolved audience belongs in the requested view (PAP-749 plan §1, Rule 3). */
|
||||
export function audienceMatchesView(
|
||||
audience: AttentionAudience,
|
||||
view: AttentionFeedView,
|
||||
view: Exclude<AttentionFeedView, "waiting">,
|
||||
userId: string | null | undefined,
|
||||
): boolean {
|
||||
switch (view) {
|
||||
@@ -2105,19 +2107,36 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
|
||||
recoveryActionAttentionCondition(),
|
||||
))
|
||||
.orderBy(desc(issueRecoveryActions.updatedAt), desc(issueRecoveryActions.id));
|
||||
const [recoveryIssueMap, recoveryImageMap] = await Promise.all([
|
||||
const [recoveryIssueMap, recoveryImageMap, holdRuns, scheduled] = await Promise.all([
|
||||
loadIssues(recoveryRows.flatMap((row) => [row.sourceIssueId, row.recoveryIssueId])),
|
||||
loadImages(db, companyId, recoveryRows.map((row) => row.sourceIssueId), readCondition),
|
||||
providerHoldRuns(db, companyId, recoveryRows.flatMap(row =>
|
||||
row.cause === "native_provider_usage_limit" && typeof row.evidence?.runId === "string"
|
||||
&& /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(row.evidence.runId) ? [row.evidence.runId] : [])),
|
||||
scheduledProviderWaits(db, companyId),
|
||||
]);
|
||||
const scheduledByRun = new Map(scheduled.map(run => [run.id, run.limit]));
|
||||
|
||||
for (const recovery of recoveryRows) {
|
||||
const sourceIssue = recoveryIssueMap.get(recovery.sourceIssueId) ?? null;
|
||||
if (!sourceIssue) continue;
|
||||
const isProviderLimit = recovery.cause === "native_provider_usage_limit";
|
||||
if (isProviderLimit && ["done", "cancelled"].includes(sourceIssue.status)) continue;
|
||||
const run = isProviderLimit ? holdRuns.get(String(recovery.evidence?.runId)) : undefined;
|
||||
if (run?.taskId === sourceIssue.id && run.resumed) continue;
|
||||
const providerLimit = run?.taskId === sourceIssue.id
|
||||
? providerLimitForHold(run, recovery.evidence, recovery.nextAction) : undefined;
|
||||
const queuedRetry = run && scheduledByRun.get(run.runId);
|
||||
if (providerLimit && queuedRetry) {
|
||||
providerLimit.state = queuedRetry.state;
|
||||
providerLimit.retryAt = queuedRetry.retryAt;
|
||||
}
|
||||
const recoveryIssue = recovery.recoveryIssueId ? recoveryIssueMap.get(recovery.recoveryIssueId) ?? null : null;
|
||||
const dedupKey = `recovery:${recovery.kind}:${recovery.sourceIssueId}:${recovery.cause}:${recovery.fingerprint}`;
|
||||
add(createItem({
|
||||
companyId,
|
||||
sourceKind: "recovery_action",
|
||||
providerLimit,
|
||||
subject: {
|
||||
kind: "recovery_action",
|
||||
id: recovery.id,
|
||||
@@ -2158,7 +2177,7 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
|
||||
}), {
|
||||
issueId: recovery.sourceIssueId,
|
||||
ownerUserId: recovery.ownerType === "user" ? recovery.ownerUserId : null,
|
||||
companyScoped: recovery.ownerType === "board",
|
||||
companyScoped: recovery.ownerType === "board" && !providerLimit,
|
||||
}, {
|
||||
// Escalation and a new next action are important; retry attempts
|
||||
// that only move `updatedAt` are not.
|
||||
@@ -2448,8 +2467,9 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
|
||||
: null);
|
||||
}
|
||||
|
||||
const failedRows = await listAttentionExhaustedRuns(db, companyId);
|
||||
const failedIssueIds = failedRows.map((row) => readRunIssueId(row.contextSnapshot));
|
||||
const exhausted = await listAttentionExhaustedRuns(db, companyId);
|
||||
const failedRows = [...exhausted, ...scheduled];
|
||||
const failedIssueIds = failedRows.map((row) => row.boundTaskId ?? readRunIssueId(row.contextSnapshot));
|
||||
const [failedIssueMap, failedImageMap, failedRunsWithNewerRun] = await Promise.all([
|
||||
loadIssues(failedIssueIds),
|
||||
loadImages(db, companyId, failedIssueIds, readCondition),
|
||||
@@ -2461,15 +2481,21 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
|
||||
}))),
|
||||
]);
|
||||
for (const run of failedRows) {
|
||||
const issueId = readRunIssueId(run.contextSnapshot);
|
||||
if (failedRunsWithNewerRun.has(run.id)) continue;
|
||||
const issueId = run.boundTaskId ?? readRunIssueId(run.contextSnapshot);
|
||||
const scheduledLimit = scheduledByRun.get(run.id);
|
||||
if (!scheduledLimit && (failedRunsWithNewerRun.has(run.id) || ("providerResumed" in run && run.providerLimited && run.providerResumed))) continue;
|
||||
|
||||
const issue = issueId ? failedIssueMap.get(issueId) ?? null : null;
|
||||
if (issueId && !issue) continue;
|
||||
if (issueId && (!issue || ["done", "cancelled"].includes(issue.status))) continue;
|
||||
if (holdRuns.has(run.id) || ("settledProviderHold" in run && run.settledProviderHold)) continue;
|
||||
const providerLimit = scheduledLimit ?? ("providerRetryAt" in run && issueId && run.providerLimited
|
||||
? providerLimitForHold({ runId: run.id, agentId: run.agentId, agentName: run.agentName, account: run.account, taskId: issueId },
|
||||
{ providerLimitResetAt: run.providerRetryAt }, "") : undefined);
|
||||
const dedupKey = `run:${run.id}`;
|
||||
add(createItem({
|
||||
companyId,
|
||||
sourceKind: "failed_run",
|
||||
providerLimit,
|
||||
subject: {
|
||||
kind: "run",
|
||||
id: run.id,
|
||||
@@ -2516,12 +2542,12 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
|
||||
failureReasonExcerpt: excerpt((run.error ? withoutSqlStatementText(run.error) : null) ?? run.exhaustionMessage ?? run.errorCode),
|
||||
images: issueImages(failedImageMap, issueId),
|
||||
},
|
||||
}), { issueId, companyScoped: true }, {
|
||||
}), { issueId, companyScoped: !providerLimit }, {
|
||||
// Each failed run is its own card; nothing about it changes later.
|
||||
content: null,
|
||||
since: run.finishedAt ?? run.updatedAt ?? run.createdAt,
|
||||
// Rule 11: a failed run joins the card for the task it blocks, if any.
|
||||
}, issueId ? { key: `blocked:${issueId}`, anchor: false } : null);
|
||||
}, issueId && !providerLimit ? { key: `blocked:${issueId}`, anchor: false } : null);
|
||||
}
|
||||
|
||||
// A count reads the open incidents of the budget overview without the
|
||||
@@ -2604,14 +2630,23 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
|
||||
role: agents.role,
|
||||
status: agents.status,
|
||||
errorReason: agents.errorReason,
|
||||
lastRunId: agentRuntimeState.lastRunId,
|
||||
lastError: agentRuntimeState.lastError,
|
||||
createdAt: agents.createdAt,
|
||||
updatedAt: agents.updatedAt,
|
||||
})
|
||||
.from(agents)
|
||||
.leftJoin(agentRuntimeState, and(eq(agentRuntimeState.agentId, agents.id), eq(agentRuntimeState.companyId, companyId)))
|
||||
.where(and(eq(agents.companyId, companyId), eq(agents.status, ATTENTION_AGENT_ERROR_STATUS)))
|
||||
.orderBy(desc(agents.updatedAt), desc(agents.id));
|
||||
|
||||
const knownLimitRuns = new Set(collected.flatMap(item => item.providerLimit ? [item.providerLimit.runId] : []));
|
||||
const unresolvedErrors = erroredAgents.flatMap(agent => agent.lastRunId && !knownLimitRuns.has(agent.lastRunId)
|
||||
? [agent.lastRunId] : []);
|
||||
for (const run of await recoveredProviderRuns(db, companyId, unresolvedErrors, readCondition)) knownLimitRuns.add(run.id);
|
||||
for (const agent of erroredAgents) {
|
||||
if (agent.lastRunId && knownLimitRuns.has(agent.lastRunId) && agent.lastError && agent.errorReason
|
||||
&& (agent.errorReason === agent.lastError || agent.errorReason === agent.lastError.slice(0, 499) + "…")) continue;
|
||||
const dedupKey = `agent_error:${agent.id}`;
|
||||
add(createItem({
|
||||
companyId,
|
||||
@@ -2655,8 +2690,13 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
|
||||
|
||||
}
|
||||
|
||||
const providerTasks = new Set(collected.flatMap(item => item.providerLimit && item.relatedIssue ? [item.relatedIssue.id] : []));
|
||||
const deduped = new Map<string, AttentionItem>();
|
||||
for (const item of collected) {
|
||||
// The active hold already explains this terminal task's stalled path. An
|
||||
// explicit unblock request has its own key and stays independently actionable.
|
||||
if (item.sourceKind === "blocker_attention" && item.dedupKey === `blocker:${item.subject.id}`
|
||||
&& providerTasks.has(item.subject.id)) continue;
|
||||
const current = deduped.get(item.dedupKey);
|
||||
deduped.set(item.dedupKey, current ? betterDuplicate(current, item) : item);
|
||||
}
|
||||
@@ -2710,13 +2750,15 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
|
||||
// Rule 11: one card for each obligation. Members share one placement, so
|
||||
// the fingerprint below reads the obligation's audience.
|
||||
assignAttentionObligations(currentItems, obligationHintByDedupKey);
|
||||
const legacyLimitDismissals = await attachProviderRetryChains(db, companyId, currentItems, dismissals);
|
||||
groupProviderLimits(currentItems, legacyLimitDismissals);
|
||||
for (const item of currentItems) {
|
||||
// A count reads a fingerprint only to compare it with a dismissal.
|
||||
if (summaryOnly && !dismissals.has(item.dismissalKey)) continue;
|
||||
const change = changeBasisByDedupKey.get(item.dedupKey) ?? { content: null, since: item.createdAt };
|
||||
item.changeFingerprint = attentionChangeFingerprint({
|
||||
sourceKind: item.sourceKind,
|
||||
content: change.content,
|
||||
sourceKind: item.providerLimit ? "recovery_action" : item.sourceKind,
|
||||
content: item.providerLimit ? { needsRetry: item.providerLimit.state === "needs_retry" } : change.content,
|
||||
forViewer: item.audience.kind === "user" && item.audience.userId != null
|
||||
&& item.audience.userId === options.userId,
|
||||
});
|
||||
@@ -2749,17 +2791,19 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
|
||||
const enrichedById = new Map(enrichedItems.map((item) => [item.id, item]));
|
||||
const obligationLeadOf = (item: AttentionItem) =>
|
||||
isObligationEvidence(item) ? enrichedById.get(item.obligationLeadId!) ?? item : item;
|
||||
const automatic = (item: AttentionItem) => Boolean(item.providerLimit && item.providerLimit.state !== "needs_retry");
|
||||
const waitingForViewer = (item: AttentionItem) => hiddenForViewer(item)
|
||||
? item.dismissal?.kind === "snooze"
|
||||
: automatic(item) && (item.audience.kind !== "user" || item.audience.userId === options.userId);
|
||||
const visibleItems = enrichedItems.filter((member) => {
|
||||
const item = obligationLeadOf(member);
|
||||
if (view === "archived") {
|
||||
// The person's own Archived view (PAP-749 plan §3): open cards they
|
||||
// archived or snoozed, and nothing else.
|
||||
if (view === "waiting") {
|
||||
if (!waitingForViewer(item)) return false;
|
||||
} else if (view === "archived") {
|
||||
if (!hiddenForViewer(item)) return false;
|
||||
} else {
|
||||
// `all` (the default) keeps the pre-PAP-749 superset; the other views
|
||||
// partition by resolved audience (PAP-749 plan §1, Rule 3).
|
||||
if (view !== "all" && !audienceMatchesView(item.audience, view, options.userId)) return false;
|
||||
if (!includeDismissed && hiddenForViewer(item)) return false;
|
||||
if (!includeDismissed && (hiddenForViewer(item) || automatic(item))) return false;
|
||||
}
|
||||
if (options.archived === true ? !item.archivedAt : Boolean(item.archivedAt)) return false;
|
||||
if (!includeDismissed && item.snoozedUntil && timestamp(item.snoozedUntil) > now) return false;
|
||||
@@ -2778,22 +2822,29 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
|
||||
// three audience views and Everyone skip the cards this person archived
|
||||
// or snoozed; the Archived tab counts exactly those (plan §3). Only For
|
||||
// you is the badge. Each obligation counts once, as its lead (Rule 11).
|
||||
let waitingCount = 0;
|
||||
let nextSnoozeAt: string | null = null;
|
||||
const viewCounts: AttentionViewCounts = { mine: 0, unassigned: 0, company: 0, archived: 0, all: 0 };
|
||||
for (const item of enrichedItems) {
|
||||
if (obligationLeadOf(item) !== item) continue;
|
||||
if (item.archivedAt) continue;
|
||||
if (item.snoozedUntil && timestamp(item.snoozedUntil) > now) continue;
|
||||
if (waitingForViewer(item)) waitingCount++;
|
||||
if (hiddenForViewer(item)) {
|
||||
viewCounts.archived += 1;
|
||||
const until = item.dismissal?.snoozedUntil;
|
||||
if (until && (!nextSnoozeAt || until < nextSnoozeAt)) nextSnoozeAt = until;
|
||||
continue;
|
||||
}
|
||||
if (automatic(item)) continue;
|
||||
for (const countedView of ATTENTION_PERSONAL_VIEWS) {
|
||||
if (countedView === "archived") continue;
|
||||
if (audienceMatchesView(item.audience, countedView, options.userId)) viewCounts[countedView] += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const summary: AttentionSummary = { companyId, generatedAt: new Date().toISOString(), totalCount: visibleItems.length, deskBadgeCount: viewCounts.mine, viewCounts, countsBySourceKind };
|
||||
const waiting = { ...(waitingCount ? { waitingCount } : {}), ...(nextSnoozeAt ? { nextSnoozeAt } : {}) };
|
||||
const summary: AttentionSummary = { companyId, ...waiting, generatedAt: new Date().toISOString(), totalCount: visibleItems.length, deskBadgeCount: viewCounts.mine, viewCounts, countsBySourceKind };
|
||||
if (summaryOnly) return { ...summary, nextCursor: null, items: visibleItems };
|
||||
|
||||
const sort = options.sort ?? "activity";
|
||||
@@ -2871,6 +2922,7 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
|
||||
companyId,
|
||||
generatedAt: new Date().toISOString(),
|
||||
totalCount: rankedItems.length,
|
||||
...waiting,
|
||||
// The badge is the "For you" count. It has no day boundary: an open
|
||||
// card stays in it until a person answers it.
|
||||
deskBadgeCount: viewCounts.mine,
|
||||
@@ -3019,7 +3071,8 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
|
||||
throw unprocessable("This card cannot be hidden.", { code: "attention_close_mode_unsupported", closeModes: item.closeModes });
|
||||
}
|
||||
// The version the person saw; the card returns when its content differs.
|
||||
const fingerprint = item.id === requested?.id ? input.fingerprint ?? item.changeFingerprint : item.changeFingerprint;
|
||||
const fingerprint = item.providerLimit || item.id === requested?.id
|
||||
? input.fingerprint ?? item.changeFingerprint : item.changeFingerprint;
|
||||
const dismissals = inboxDismissalService(db);
|
||||
const dismissal = input.mode === "snooze"
|
||||
? await dismissals.snooze(companyId, input.userId, item.dismissalKey, new Date(input.until!), new Date(), fingerprint)
|
||||
|
||||
@@ -13903,6 +13903,8 @@ async function executePaperclipNativeSessionAttempt(
|
||||
recoveryEvidence.providerSessionEstablished,
|
||||
...(providerCooldownAt ? { providerCooldownAt: providerCooldownAt.toISOString() } : {}),
|
||||
...(providerLimit?.plan.resetAt ? { providerLimitResetAt: providerLimit.plan.resetAt.toISOString() } : {}),
|
||||
...(providerLimit ? { providerLimitAutomatic: providerLimit.plan.automatic,
|
||||
providerLimitEstimated: providerLimit.plan.estimated === true } : {}),
|
||||
...(providerLimit && startupProviderLimit ? { providerLimitStartup: {
|
||||
failure: outputRedactor.redact(startupProviderLimit.failure),
|
||||
observedAt: startupProviderLimit.observedAt.toISOString(),
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
} from "@paperclipai/db";
|
||||
import { readProviderFailure, type ProviderFailure } from "@paperclipai/shared";
|
||||
import { HttpError } from "../../errors.js";
|
||||
import { persistActivity, publishActivity } from "../activity-log.js";
|
||||
import { logger } from "../../middleware/logger.js";
|
||||
import type { createDeliveryWorkCoordinator } from "../delivery-work-coordinator.js";
|
||||
import { DELIVERY_QUEUES } from "../delivery-work-notifications.js";
|
||||
@@ -165,11 +166,20 @@ type Outcome =
|
||||
| { requested: false; reason: string };
|
||||
|
||||
async function settle(db: Db, actionId: string, state: Record<string, unknown>, nextAction?: string) {
|
||||
await db.update(issueRecoveryActions).set({
|
||||
evidence: sql`coalesce(${issueRecoveryActions.evidence}, '{}'::jsonb) || jsonb_build_object('providerLimitResume', ${JSON.stringify(state)}::jsonb)`,
|
||||
...(nextAction ? { nextAction } : {}),
|
||||
updatedAt: new Date(),
|
||||
}).where(and(eq(issueRecoveryActions.id, actionId), sql`${issueRecoveryActions.evidence}->'providerLimitResume' is null`));
|
||||
const publication = await db.transaction(async tx => {
|
||||
const [changed] = await tx.update(issueRecoveryActions).set({
|
||||
evidence: sql`coalesce(${issueRecoveryActions.evidence}, '{}'::jsonb) || jsonb_build_object('providerLimitResume', ${JSON.stringify(state)}::jsonb)`,
|
||||
...(nextAction ? { nextAction } : {}),
|
||||
updatedAt: new Date(),
|
||||
}).where(and(eq(issueRecoveryActions.id, actionId), sql`${issueRecoveryActions.evidence}->'providerLimitResume' is null`))
|
||||
.returning({ companyId: issueRecoveryActions.companyId, taskId: issueRecoveryActions.sourceIssueId });
|
||||
if (!changed) return null;
|
||||
const result = await persistActivity(tx as unknown as Db, { companyId: changed.companyId, actorType: "system",
|
||||
actorId: "recovery", action: "issue.provider_limit_retry_settled", entityType: "issue", entityId: changed.taskId,
|
||||
details: { state: state.state, reason: state.reason ?? null } });
|
||||
return result.publication;
|
||||
});
|
||||
if (publication) publishActivity(publication);
|
||||
}
|
||||
|
||||
/** Why Paperclip did not retry after a reset it announced; the Retry stays.
|
||||
@@ -220,7 +230,7 @@ export async function requestProviderLimitResumeRetry(db: Db, input: {
|
||||
// Retry to the user; it never promised an automatic one.
|
||||
await db.update(issueRecoveryActions).set({
|
||||
nextAction: providerLimitNextAction({ automatic: false, resetAt: reset.resetAt }),
|
||||
evidence: sql`coalesce(${issueRecoveryActions.evidence}, '{}'::jsonb) || jsonb_build_object('providerLimitResetAt', ${reset.resetAt.toISOString()}::text)`,
|
||||
evidence: sql`coalesce(${issueRecoveryActions.evidence}, '{}'::jsonb) || jsonb_build_object('providerLimitResetAt', ${reset.resetAt.toISOString()}::text, 'providerLimitAutomatic', false)`,
|
||||
updatedAt: now,
|
||||
}).where(and(eq(issueRecoveryActions.id, action.id), eq(issueRecoveryActions.status, "active")));
|
||||
await settle(db, action.id, { state: "not_requested", reason: "reset_beyond_wait", resetAt: reset.resetAt.toISOString(),
|
||||
@@ -235,7 +245,7 @@ export async function requestProviderLimitResumeRetry(db: Db, input: {
|
||||
nextAction: providerLimitNextAction(actorId
|
||||
? { automatic: true, resetAt: reset.resetAt, actorId, estimated: reset.estimated }
|
||||
: { automatic: false, resetAt: reset.resetAt, estimated: reset.estimated }),
|
||||
evidence: sql`coalesce(${issueRecoveryActions.evidence}, '{}'::jsonb) || jsonb_build_object('providerLimitResetAt', ${reset.resetAt.toISOString()}::text)`,
|
||||
evidence: sql`coalesce(${issueRecoveryActions.evidence}, '{}'::jsonb) || jsonb_build_object('providerLimitResetAt', ${reset.resetAt.toISOString()}::text, 'providerLimitAutomatic', ${!!actorId}::boolean, 'providerLimitEstimated', ${!!reset.estimated}::boolean)`,
|
||||
updatedAt: now,
|
||||
}).where(and(eq(issueRecoveryActions.id, action.id), eq(issueRecoveryActions.status, "active")));
|
||||
}
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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<AttentionSummary>(`/companies/${companyId}/attention/summary`),
|
||||
taskIndex: (companyId: string) => api.get<AttentionTaskIndex>(`/companies/${companyId}/attention/tasks`),
|
||||
runHistory: (companyId: string, before?: { at: string; id: string }) => {
|
||||
const query = before ? `?${new URLSearchParams(before)}` : "";
|
||||
return api.get<AttentionRunHistoryEntry[]>(`/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));
|
||||
|
||||
@@ -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<string, string>;
|
||||
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 <div className="space-y-5" data-decision-history>
|
||||
{header}
|
||||
<ToolbarSearch query={search} onQueryChange={setSearch} label="Search decision history" placeholder="Search decisions or task IDs…" />
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<NativeSelect aria-label="Whose decision history" value={scope} onChange={(event) => setScope(event.target.value as DecisionHistoryScope)} className="col-span-2">
|
||||
{DECISION_HISTORY_SCOPE_OPTIONS.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
|
||||
</NativeSelect>
|
||||
<NativeSelect aria-label="Filter decision outcomes" value={outcome} onChange={(event) => setOutcome(event.target.value)}>
|
||||
<option value="">All outcomes</option>
|
||||
{DECISION_HISTORY_OUTCOME_OPTIONS.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
|
||||
<option value={HANDLED_FOR_ME}>Handled for me</option>
|
||||
</NativeSelect>
|
||||
<NativeSelect aria-label="Sort decision history" value={sort} onChange={(event) => setSort(event.target.value as typeof sort)}><option value="newest">Newest first</option><option value="oldest">Oldest first</option></NativeSelect>
|
||||
<NativeSelect aria-label="Filter decision history by agent" value={agentId} onChange={(event) => setAgentId(event.target.value)} className="col-span-2"><option value="">All agents</option>{agents.map((agent) => <option key={agent.id} value={agent.id}>{agent.name}</option>)}</NativeSelect>
|
||||
<NativeSelect aria-label="Filter decision history by project" value={projectId} onChange={(event) => setProjectId(event.target.value)} className="col-span-2"><option value="">All projects</option>{(projects.data ?? []).map((project) => <option key={project.id} value={project.id}>{project.name}</option>)}</NativeSelect>
|
||||
<NativeSelect aria-label="Group decision history" value={groupBy} onChange={(event) => setGroupBy(event.target.value as Group)} className="col-span-2"><option value="none">No grouping</option><option value="task">By task</option><option value="agent">By agent</option><option value="project">By project</option></NativeSelect>
|
||||
<div role="toolbar" aria-label="Decision history controls" className="space-y-5">
|
||||
<ToolbarSearch query={search} onQueryChange={setSearch} label="Search decision history" placeholder="Search decisions or task IDs…" />
|
||||
<div data-canonical-toolbar="history">
|
||||
<InboxFilter<DecisionHistoryScope> label="Whose decision history" heading="Whose decisions" value={scope}
|
||||
options={DECISION_HISTORY_SCOPE_OPTIONS} onChange={setScope} />
|
||||
<InboxFilter label="Filter decision outcomes" heading="Outcome" value={outcome} onChange={setOutcome}
|
||||
options={[{ value: "", label: "All outcomes" }, ...DECISION_HISTORY_OUTCOME_OPTIONS, { value: HANDLED_FOR_ME, label: "Handled for me" }]} />
|
||||
<InboxFilter<typeof sort> label="Sort decision history" heading="Sort by" value={sort} onChange={setSort}
|
||||
options={[{ value: "newest", label: "Newest first" }, { value: "oldest", label: "Oldest first" }]} />
|
||||
<InboxFilter label="Filter decision history by agent" heading="Agents" value={agentId} onChange={setAgentId}
|
||||
options={[{ value: "", label: "All agents" }, ...agents.map(agent => ({ value: agent.id, label: agent.name }))]} />
|
||||
<InboxFilter label="Filter decision history by project" heading="Projects" value={projectId} onChange={setProjectId}
|
||||
options={[{ value: "", label: "All projects" }, ...(projects.data ?? []).map(project => ({ value: project.id, label: project.name }))]} />
|
||||
<InboxFilter<Group> 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" }]} />
|
||||
</div>
|
||||
</div>
|
||||
{afterControls}
|
||||
{waiting ? <p role="status" className="text-sm text-muted-foreground">Loading decisions…</p> : null}
|
||||
{historyView.kind === "error" ? <QueryErrorState error={historyView.error} onRetry={historyView.retry} /> : null}
|
||||
{!waiting && historyView.kind !== "error" && !items.length ? <div className="space-y-2 text-sm text-muted-foreground">
|
||||
<p>{scope === "mine" && !search && !outcome && !agentId && !projectId ? "No decisions handled by you or for you yet." : "No decisions match these filters."}</p>
|
||||
{scope === "mine" ? <Button variant="outline" size="sm" onClick={() => setScope("all")}>Show everyone's decisions</Button> : null}
|
||||
</div> : null}
|
||||
<div className="space-y-4">{[...groups].map(([label, entries]) => <section key={label} className="space-y-3">{label ? <h3 className="text-sm font-medium text-muted-foreground">{label}</h3> : null}{entries.map((item) => <div key={item.id} className="space-y-1"><Receipt item={item} onOpen={navigate} userLabelMap={userLabelMap} /><p className="px-1 text-xs text-muted-foreground"><time dateTime={item.resolvedAt}>{new Date(item.resolvedAt).toLocaleString()}</time></p></div>)}</section>)}</div>
|
||||
{!waiting && historyView.kind !== "error" && !items.length && <EmptyState placement="upper"
|
||||
message={scope === "mine" && !search && !outcome && !agentId && !projectId ? "No decisions handled by you or for you yet." : "No decisions match these filters."}
|
||||
action={scope === "mine" ? "Show everyone's decisions" : undefined}
|
||||
onAction={() => setScope("all")}
|
||||
hideActionIcon
|
||||
/>}
|
||||
<div className="space-y-4">{[...groups].map(([label, entries]) => <section key={label} className="space-y-3">
|
||||
{label && <h3 className="text-sm font-medium text-muted-foreground">{label}</h3>}
|
||||
{entries.map(item => <Receipt key={item.id} item={item} onOpen={navigate} userLabelMap={userLabelMap} showTimestamp />)}
|
||||
</section>)}</div>
|
||||
{history.hasNextPage ? <Button variant="outline" disabled={history.isFetchingNextPage} onClick={() => void history.fetchNextPage()}>{history.isFetchingNextPage ? "Loading…" : "Load more decisions"}</Button> : null}
|
||||
</div>;
|
||||
}
|
||||
@@ -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 (
|
||||
<div className={graphic ? "empty-state-artwork flex flex-col items-center justify-center gap-5 py-16 text-center" : "flex flex-col items-center justify-center py-16 text-center"}>
|
||||
{graphic ? <div className="empty-state-graphic" aria-hidden="true">{graphic}</div> : <div className="bg-muted/50 p-4 mb-4">
|
||||
<Icon className="h-10 w-10 text-muted-foreground/50" />
|
||||
</div>}
|
||||
{title ? (
|
||||
<>
|
||||
<p className="text-base font-semibold text-foreground mb-1.5">{title}</p>
|
||||
<p className="text-sm text-muted-foreground mb-4 max-w-md">{message}</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-sm font-medium text-foreground mb-1">{message}</p>
|
||||
{description && <p className="max-w-md text-sm text-muted-foreground mb-4">{description}</p>}
|
||||
</>
|
||||
)}
|
||||
{action && onAction && (
|
||||
<Button onClick={onAction}>
|
||||
{!hideActionIcon && <Plus className="h-4 w-4 mr-1.5" />}
|
||||
{action}
|
||||
</Button>
|
||||
)}
|
||||
<div className="empty-state empty-state-artwork grid w-full flex-1 justify-items-center text-center" data-placement={placement}>
|
||||
<div className={cn("flex flex-col items-center justify-center gap-5", placement === "center" && "py-6")}>
|
||||
<div className="empty-state-graphic" aria-hidden="true">
|
||||
{graphic ?? <span className="empty-state-logo" />}
|
||||
</div>
|
||||
<div className="max-w-md space-y-1.5">
|
||||
{title && <p className="text-base font-semibold text-foreground">{title}</p>}
|
||||
<p className="whitespace-pre-line text-sm text-muted-foreground">{message}</p>
|
||||
{description && <p className="text-sm text-muted-foreground">{description}</p>}
|
||||
</div>
|
||||
{action && onAction && (
|
||||
<Button onClick={onAction}>
|
||||
{!hideActionIcon && <Plus className="h-4 w-4 mr-1.5" />}
|
||||
{action}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<T extends string>({ 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 <DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="sm" value={value} aria-label={selected ? `${label}, ${selected.label}` : label}>
|
||||
<span className="max-w-(--sz-160px) truncate font-medium">{defaultLabel ?? selected?.label}</span>
|
||||
<ChevronDown aria-hidden className="size-3.5 text-muted-foreground" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" collisionPadding={8} className="w-(--sz-260px)" aria-label={heading}>
|
||||
<DropdownMenuLabel>{heading}</DropdownMenuLabel>
|
||||
{options.map(option => <DropdownMenuItem key={option.value} aria-current={option.value === value || undefined}
|
||||
className="items-start gap-2" onSelect={() => onChange(option.value)}>
|
||||
<Check aria-hidden className={cn("mt-0.5 size-3.5 shrink-0", value !== option.value && "opacity-0")} />
|
||||
<span className={cn("truncate", value === option.value && "font-medium")}>{option.label}</span>
|
||||
</DropdownMenuItem>)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>;
|
||||
}
|
||||
@@ -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<string, string> | null;
|
||||
}) {
|
||||
@@ -19,6 +20,7 @@ export function CoordinatorDecisionReceipt({ item, onOpen, userLabelMap }: {
|
||||
<span className="block truncate text-sm text-muted-foreground">{decisionHistoryContext(item)}</span>
|
||||
{/* Who withdrew it is in the headline; the reason they gave is here (PAP-749 plan §3). */}
|
||||
{item.reason ? <span className="block text-sm text-muted-foreground" data-decision-history-reason>Reason: {item.reason}</span> : null}
|
||||
{showTimestamp && <time className="block text-xs tabular-nums text-muted-foreground" dateTime={item.resolvedAt}>{new Date(item.resolvedAt).toLocaleString()}</time>}
|
||||
</span>
|
||||
<ArrowUpRight className="size-4 shrink-0 text-muted-foreground" aria-hidden />
|
||||
</button>;
|
||||
|
||||
@@ -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<T extends string>({ 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 <DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="sm" value={value} aria-label={selected ? `${label}, ${selected.label}` : label}>
|
||||
<span className="max-w-(--sz-160px) truncate font-medium">{defaultLabel ?? selected?.label}</span>
|
||||
<ChevronDown aria-hidden className="size-3.5 text-muted-foreground" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" collisionPadding={8} className="w-(--sz-260px)" aria-label={heading}>
|
||||
<DropdownMenuLabel>{heading}</DropdownMenuLabel>
|
||||
{options.map(option => <DropdownMenuItem key={option.value} aria-current={option.value === value || undefined}
|
||||
className="items-start gap-2" onSelect={() => onChange(option.value)}>
|
||||
<Check aria-hidden className={cn("mt-0.5 size-3.5 shrink-0", value !== option.value && "opacity-0")} />
|
||||
<span className={cn("truncate", value === option.value && "font-medium")}>{option.label}</span>
|
||||
</DropdownMenuItem>)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>;
|
||||
}
|
||||
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<Group>("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<NeedsYouReviewPayload>({ 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"). */}
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<NeedsYouTypeLabel item={item} currentUserId={userId} userLabelMap={userLabelMap} />
|
||||
{item.providerLimit ? <span className="text-sm font-medium">Provider usage limit</span> : <NeedsYouTypeLabel item={item} currentUserId={userId} userLabelMap={userLabelMap} />}
|
||||
<AttentionHiddenChip item={item} />
|
||||
<AttentionStaleChip item={item} />
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-3" data-attention-context>
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-3" data-attention-context>
|
||||
<NeedsYouAudience item={item} currentUserId={userId} userLabelMap={userLabelMap} onClaim={entry => claim.mutate(entry)} claiming={claim.isPending && claim.variables?.id === item.id} />
|
||||
<NeedsYouRequester item={item} agentMap={agentMap} userLabelMap={userLabelMap} currentUserId={userId} />
|
||||
<time dateTime={item.activityAt} title={new Date(item.activityAt).toLocaleString()} className="shrink-0 text-xs leading-4.5 text-muted-foreground">{timeAgo(item.activityAt)}</time>
|
||||
@@ -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} />
|
||||
</div>
|
||||
</div>
|
||||
<AttentionForOtherGate item={item} currentUserId={userId} userLabelMap={userLabelMap}>
|
||||
{interaction ? <AttentionInteractionResolver footerSlot={taskLink} artifactRow={artifactRow} presentation="coordinator-decision" audienceStated={attentionAudienceLineNamesResponders(item, userId)} companyId={selectedCompanyId!} issueId={issueId} interactionId={item.subject.id} shareReviseDraft agentMap={agentMap} currentUserId={userId} onResolved={resolved => {
|
||||
{item.providerLimit ? <InboxProviderLimit item={item} evidence={attentionObligationEvidence(obligations, item)} />
|
||||
: interaction ? <AttentionInteractionResolver footerSlot={taskLink} artifactRow={artifactRow} presentation="coordinator-decision" audienceStated={attentionAudienceLineNamesResponders(item, userId)} companyId={selectedCompanyId!} issueId={issueId} interactionId={item.subject.id} shareReviseDraft agentMap={agentMap} currentUserId={userId} onResolved={resolved => {
|
||||
if (!resolved || resolved.status === "pending") { refetchAll(); return; }
|
||||
onResolved(item);
|
||||
}} />
|
||||
@@ -400,19 +390,35 @@ export function CoordinatorNeedsYou() {
|
||||
if (!selectedCompanyId) return <p className="text-sm text-muted-foreground">Choose a company to see its decisions.</p>;
|
||||
// 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 = <div className="space-y-2" data-inbox-folders>
|
||||
<nav className="flex gap-1" aria-label="Inbox views">{inboxFolders.map(({ value, label }) => {
|
||||
const selected = value === activeFolder?.value;
|
||||
const waitingCount = feed.data?.waitingCount;
|
||||
return <Button key={value} size="sm" variant={selected ? "secondary" : "ghost"} aria-current={selected ? "page" : undefined}
|
||||
onClick={() => changeFolder(value)}>{label}{value === "waiting" && waitingCount ? ` · ${waitingCount}` : ""}</Button>;
|
||||
})}</nav>
|
||||
{activeFolder && <p className="text-sm text-muted-foreground">{activeFolder.description}</p>}
|
||||
</div>;
|
||||
const receipts = feed.data?.receipts ?? [];
|
||||
if (historyOpen) return <section className="coordinator-needs-you w-full space-y-6" aria-label="Decision history" data-coordinator-decision-history>
|
||||
<Button variant="ghost" size="sm" onClick={closeHistory}><ArrowLeft className="size-4" />Needs You</Button>
|
||||
<DecisionHistoryPanel companyId={selectedCompanyId} agents={agentQuery.data ?? []} userLabelMap={userLabelMap} header={<h1 className="text-2xl font-medium">Decision history</h1>} />
|
||||
<DecisionHistoryPanel companyId={selectedCompanyId} agents={agentQuery.data ?? []} userLabelMap={userLabelMap} afterControls={<>
|
||||
{folders}
|
||||
{receipts.length > 0 && <section className="space-y-3"><h2>Updates</h2>{receipts.map(entry => <NeedsYouReceiptCard key={entry.id} receipt={entry} userLabelMap={userLabelMap} onOpen={navigate}
|
||||
onDismiss={receiptActions.dismiss} dismissing={receiptActions.dismissingId === entry.id} />)}</section>}
|
||||
<h1 className="text-2xl font-medium">Decision history</h1>
|
||||
</>} />
|
||||
<InboxRunHistory companyId={selectedCompanyId} userId={userId} />
|
||||
</section>;
|
||||
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) => <h2 className="text-base font-medium" data-needs-you-section={section}>
|
||||
{NEEDS_YOU_SECTIONS[section].title}
|
||||
</h2>;
|
||||
return <LayoutGroup id="coordinator-decisions"><section className="coordinator-needs-you w-full space-y-6" aria-label="Needs You">
|
||||
return <LayoutGroup id="coordinator-decisions"><section className="coordinator-needs-you w-full space-y-6" aria-label="Inbox">
|
||||
{archivedView ? <div className="flex items-center gap-2"><Button variant="ghost" size="icon-sm" aria-label="Back to Needs You" onClick={() => setView("mine")}><ArrowLeft className="size-4" /></Button><h1 className="text-2xl font-medium">Archived</h1></div> : 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() {
|
||||
<InboxFilter label="Filter decisions by project" heading="Projects" value={projectFilter} onChange={setProjectFilter}
|
||||
defaultLabel={projectFilter ? undefined : "By projects"}
|
||||
options={[{ value: "", label: "All projects" }, ...projects.map(([value, label]) => ({ value, label }))]} />
|
||||
{assignee && <InboxFilter label="Filter decisions by assignee" heading="Assigned to" value={assignee} onChange={chooseAssignee}
|
||||
{!waitingOpen && assignee && <InboxFilter label="Filter decisions by assignee" heading="Assigned to" value={assignee} onChange={chooseAssignee}
|
||||
defaultLabel={assignee === "me" ? "By assigned" : undefined}
|
||||
options={assignee.startsWith("user:") && !assigneeOptions.some(option => option.value === assignee)
|
||||
? [...assigneeOptions, { value: assignee, label: "Someone else" }] : assigneeOptions} />}
|
||||
@@ -443,7 +449,8 @@ export function CoordinatorNeedsYou() {
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
{feed.data ? <p className="text-sm text-muted-foreground" data-needs-you-summary>
|
||||
{folders}
|
||||
{feed.data && !waitingOpen && summarySections.length > 0 ? <p className="text-sm text-muted-foreground" data-needs-you-summary>
|
||||
{summarySections.map((section, index) => {
|
||||
const label = NEEDS_YOU_SECTIONS[section].title.toLocaleLowerCase();
|
||||
return <span key={section}>{index ? " · " : ""}{counts[section]} {counts[section] === 1 ? label.slice(0, -1) : label}</span>;
|
||||
@@ -451,25 +458,23 @@ export function CoordinatorNeedsYou() {
|
||||
</p> : null}
|
||||
{feedWaiting ? <p role="status" className="flex items-center gap-2 text-sm text-muted-foreground"><Loader2 className="size-4 animate-spin" />Loading decisions…</p> : null}
|
||||
{feedView.kind === "error" ? <QueryErrorState error={feedView.error} onRetry={feedView.retry} /> : null}
|
||||
{!feedWaiting && feedView.kind !== "error" && currentItems.length === 0 && !receipts.length ? <div className="space-y-3 py-8 text-center"><p className="text-sm text-muted-foreground">{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]}</p></div> : null}
|
||||
{!feedWaiting && feedView.kind !== "error" && currentItems.length === 0 && (
|
||||
staleItems.length || snoozedItems.length
|
||||
? <p className="py-8 text-center text-sm text-muted-foreground">{staleItems.length ? "No current cards. Stale cards are below." : "No archived cards. Snoozed cards are below."}</p>
|
||||
: <EmptyState placement="upper" message={pendingItems.length ? "No open decisions match these filters." : waitingOpen ? "Nothing is waiting." : view === "mine" && feed.data?.waitingCount ? `You’re caught up. ${feed.data.waitingCount} ${feed.data.waitingCount === 1 ? "item is" : "items are"} waiting.` : EMPTY_VIEW_TEXT[view]} />
|
||||
)}
|
||||
{groups.map(([label, items], index) => <div key={label} className="space-y-3" role={groupBy === "type" ? "group" : undefined} aria-label={groupBy === "type" ? NEEDS_YOU_SECTIONS[label as NeedsYouSection].title : undefined}>
|
||||
{groupBy === "type" ? index > 0 ? sectionHeading(label as NeedsYouSection) : null : label ? <h2 className="text-sm font-medium text-muted-foreground">{label}</h2> : null}
|
||||
{items.map(renderCard)}
|
||||
<InboxLimitCards items={items} renderCard={renderCard} />
|
||||
</div>)}
|
||||
{currentItems.length > renderLimit ? <Button variant="outline" onClick={() => setRenderLimit((value) => value + 40)}>Show more decisions</Button> : null}
|
||||
<AttentionStaleGroup items={staleItems} open={staleOpen} onToggle={() => setStaleOpen(open => !open)} onWithdrawAll={closeActions.withdrawAll}
|
||||
busy={closeActions.bulkPending} currentUserId={userId} userLabelMap={userLabelMap} titleOf={coordinatorCardTitle}>
|
||||
{staleItems.map(renderCard)}
|
||||
<InboxLimitCards items={staleItems} renderCard={renderCard} />
|
||||
</AttentionStaleGroup>
|
||||
{/* Snoozed by you: each card says when it comes back (PAP-749 plan §3). */}
|
||||
<AttentionSnoozedGroup count={snoozedItems.length} open={snoozedOpen} onToggle={() => setSnoozedOpen(open => !open)}>
|
||||
{snoozedItems.map(renderCard)}
|
||||
<InboxLimitCards items={snoozedItems} renderCard={renderCard} />
|
||||
</AttentionSnoozedGroup>
|
||||
{/* What other people did with your requests (PAP-749 plan §6): not in the badge. */}
|
||||
{receipts.length ? <div className="space-y-3" aria-label="Updates">
|
||||
{currentItems.length || staleItems.length || snoozedItems.length ? sectionHeading("updates") : null}
|
||||
{receipts.map(entry => <NeedsYouReceiptCard key={entry.id} receipt={entry} userLabelMap={userLabelMap} onOpen={navigate}
|
||||
onDismiss={receiptActions.dismiss} dismissing={receiptActions.dismissingId === entry.id} />)}
|
||||
</div> : null}
|
||||
</section></LayoutGroup>;
|
||||
}
|
||||
@@ -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(<MemoryRouter>
|
||||
<InboxProviderLimit item={task("IBX-1", firstRetry)} evidence={[task("IBX-2", secondRetry)]} />
|
||||
</MemoryRouter>);
|
||||
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]);
|
||||
});
|
||||
});
|
||||
@@ -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 <time dateTime={limit.retryAt}>{formatDateTime(limit.retryAt)}</time></>}
|
||||
</>;
|
||||
}
|
||||
|
||||
/** 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 <details key="usage-limits" className="coordinator-decision-card">
|
||||
<summary className="cursor-pointer font-medium">{taskCount} tasks hit usage limits</summary>
|
||||
<div className="mt-3 space-y-3">{chains.map(renderCard)}</div>
|
||||
</details>;
|
||||
});
|
||||
}
|
||||
|
||||
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 <div className="space-y-2">
|
||||
<h2><Link to={task.href!}>{task.identifier} {task.title}</Link></h2>
|
||||
<p className="text-sm"><RetryStatus limit={state} /></p>
|
||||
<p className="text-sm text-muted-foreground">{state.attempts} {state.attempts === 1 ? "attempt" : "attempts"} · {state.resetAt
|
||||
? <>Provider reset at <time dateTime={state.resetAt}>{formatDateTime(state.resetAt)}</time></>
|
||||
: "Reset time unknown"}</p>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
{state.state === "needs_retry" && <Button size="sm" asChild><Link to={task.href!}>Open task to retry</Link></Button>}
|
||||
<Link to={`/agents/${state.agentId}/runs/${state.runId}`} className="text-sm underline">{state.agentName} run log</Link>
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
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 <div className="space-y-3">
|
||||
<h2>{title}</h2>
|
||||
{state.resetAt && <p className="text-sm text-muted-foreground">Provider reset at <time dateTime={state.resetAt}>{formatDateTime(state.resetAt)}</time>.</p>}
|
||||
{scheduled.length > 0 && <p className="text-sm text-muted-foreground">Retry scheduled for {scheduled.length} {taskLabel(scheduled.length)}
|
||||
{sharedRetryAt && <> at <time dateTime={sharedRetryAt}>{formatDateTime(sharedRetryAt)}</time></>}.
|
||||
</p>}
|
||||
{!scheduled.length && !manual.length && <p className="text-sm text-muted-foreground">Retry requested. Waiting for work to resume.</p>}
|
||||
{manual.length > 0 && <p className="text-sm text-muted-foreground">Open the affected task to retry it when capacity is available.</p>}
|
||||
<details><summary className="cursor-pointer text-sm">View {tasks.length} {taskLabel(tasks.length)}</summary>
|
||||
<ul className="mt-2 space-y-2">{tasks.map(member => {
|
||||
const task = member.relatedIssue!;
|
||||
const limit = member.providerLimit!;
|
||||
return <li key={task.id} className="flex flex-wrap items-center gap-2 text-sm">
|
||||
<Link to={task.href!} className="underline">{task.identifier} {task.title}</Link>
|
||||
<span>{limit.agentName} · <RetryStatus limit={limit} /></span>
|
||||
<Link to={`/agents/${limit.agentId}/runs/${limit.runId}`} className="underline">Run log</Link>
|
||||
</li>;
|
||||
})}</ul>
|
||||
</details>
|
||||
{manual.length === 1 && <Button size="sm" asChild><Link to={manual[0]!.relatedIssue!.href!}>Open task to retry</Link></Button>}
|
||||
</div>;
|
||||
}
|
||||
@@ -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 <section className="min-w-0 space-y-3"><h2 className="text-2xl font-medium" id="recent-run-history">Recent run history</h2>
|
||||
{view.kind === "error" && <QueryErrorState error={view.error} onRetry={view.retry} />}
|
||||
{query.isLoading && <p role="status">Loading runs…</p>}
|
||||
{view.kind !== "error" && runs?.length === 0 && <EmptyState placement="upper" message="No failed runs on visible tasks." />}
|
||||
{runs && runs.length > 0 && <HorizontalScrollViewport label="Run history columns">
|
||||
<table className="inbox-run-table" aria-labelledby="recent-run-history">
|
||||
<thead><tr>{["Task", "Task ID", "Outcome", "Run log", "Recorded"].map(label => <th key={label} scope="col">{label}</th>)}</tr></thead>
|
||||
<tbody>{runs.map(run => {
|
||||
const recordedAt = new Date(run.recordedAt);
|
||||
return <tr key={run.runId}>
|
||||
<td><Link to={`/issues/${run.identifier ?? run.taskId}`} className="block max-w-xs truncate hover:underline" title={run.taskTitle}>{run.taskTitle}</Link></td>
|
||||
<td className="font-mono text-muted-foreground">{run.identifier ?? "—"}</td>
|
||||
<td><div>{run.outcome}</div><div className="text-xs text-muted-foreground">{run.reason}</div></td>
|
||||
<td><Link to={`/agents/${run.agentId}/runs/${run.runId}`} className="inline-flex items-center gap-1.5 hover:underline" aria-label={`${run.agentName} run log for ${run.identifier ?? run.taskTitle}`}>
|
||||
<FileText aria-hidden className="size-3.5 shrink-0 text-muted-foreground" /><span className="max-w-40 truncate">{run.agentName}</span>
|
||||
</Link></td>
|
||||
<td><time className="tabular-nums text-muted-foreground" dateTime={run.recordedAt} title={recordedAt.toLocaleString()}>{recordedTime.format(recordedAt)}</time></td>
|
||||
</tr>;
|
||||
})}</tbody>
|
||||
</table>
|
||||
</HorizontalScrollViewport>}
|
||||
{query.hasNextPage && <Button variant="outline" disabled={query.isFetchingNextPage} onClick={() => void query.fetchNextPage()}>Show older runs</Button>}
|
||||
</section>;
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
+45
-2
@@ -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);
|
||||
|
||||
@@ -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" });
|
||||
|
||||
@@ -30,7 +30,9 @@ export function foldAttentionObligations(items: readonly AttentionItem[]): Folde
|
||||
const evidenceByLeadId = new Map<string, AttentionItem[]>();
|
||||
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<string, string>();
|
||||
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.
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -30,7 +30,7 @@ export function Goals() {
|
||||
const goalsView = useQueryView(goalsQuery);
|
||||
|
||||
if (!selectedCompanyId) {
|
||||
return <EmptyState icon={Target} message="Select an organization to view goals." />;
|
||||
return <EmptyState placement="upper" icon={Target} message="Select an organization to view goals." />;
|
||||
}
|
||||
|
||||
// Keep a loaded list on screen through a failed refetch; only a real
|
||||
@@ -53,7 +53,7 @@ export function Goals() {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{goals && goals.length === 0 && (
|
||||
<EmptyState
|
||||
<EmptyState placement="upper"
|
||||
icon={Target}
|
||||
message="No goals yet."
|
||||
action="Add Goal"
|
||||
|
||||
@@ -2747,7 +2747,7 @@ function StreamlinedInbox({
|
||||
);
|
||||
|
||||
if (!selectedCompanyId) {
|
||||
return <EmptyState icon={InboxIcon} message={`Select an organization to view ${surfaceLabel.toLowerCase()}.`} />;
|
||||
return <EmptyState placement={surfaceLabel === "Inbox" ? "upper" : "center"} icon={InboxIcon} message={`Select an organization to view ${surfaceLabel.toLowerCase()}.`} />;
|
||||
}
|
||||
|
||||
const markAllReadIssues = (tab === "mine" ? visibleMineIssues : unreadTouchedIssues)
|
||||
@@ -3101,7 +3101,7 @@ function StreamlinedInbox({
|
||||
)}
|
||||
|
||||
{tab !== "blocked" && allLoaded && !listError && !optionalSourceError && visibleSections.length === 0 && (
|
||||
<EmptyState
|
||||
<EmptyState placement={surfaceLabel === "Inbox" ? "upper" : "center"}
|
||||
icon={searchQuery.trim() ? Search : InboxIcon}
|
||||
message={
|
||||
searchQuery.trim()
|
||||
|
||||
@@ -2239,7 +2239,7 @@ export function Inbox() {
|
||||
useWarmTaskDetailCode(Boolean(selectedCompanyId) && allLoaded && tab !== "blocked" && totalVisibleWorkItems > 0);
|
||||
|
||||
if (!selectedCompanyId) {
|
||||
return <EmptyState icon={InboxIcon} message="Select a company to view inbox." />;
|
||||
return <EmptyState placement="upper" icon={InboxIcon} message="Select a company to view inbox." />;
|
||||
}
|
||||
|
||||
const hasRunFailures = failedRuns.length > 0;
|
||||
@@ -2631,7 +2631,7 @@ export function Inbox() {
|
||||
)}
|
||||
|
||||
{tab !== "blocked" && allLoaded && visibleSections.length === 0 && (
|
||||
<EmptyState
|
||||
<EmptyState placement="upper"
|
||||
icon={searchQuery.trim() ? Search : InboxIcon}
|
||||
message={
|
||||
searchQuery.trim()
|
||||
|
||||
@@ -555,7 +555,7 @@ export function Routines() {
|
||||
}
|
||||
|
||||
if (!selectedCompanyId) {
|
||||
return <EmptyState icon={Repeat} message="Select a company to view routines." />;
|
||||
return <EmptyState placement="upper" icon={Repeat} message="Select a company to view routines." />;
|
||||
}
|
||||
|
||||
// Keep loaded routines on screen through a failed refetch; only a real
|
||||
@@ -564,8 +564,9 @@ export function Routines() {
|
||||
return <PageSkeleton variant="issues-list" />;
|
||||
}
|
||||
|
||||
const emptyList = activeTab === "routines" && sortedRoutines.length === 0;
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className={cn("space-y-6", emptyList && "empty-state-page")}>
|
||||
<h1 className="sr-only">Routines</h1>
|
||||
<RoutinesToolbar
|
||||
showListControls={activeTab === "routines"}
|
||||
@@ -643,7 +644,7 @@ export function Routines() {
|
||||
) : null}
|
||||
|
||||
{activeTab === "routines" ? (
|
||||
<div className={cn(showFolderRail && "flex gap-4")}>
|
||||
<div className={cn(showFolderRail && "flex gap-4", emptyList && "flex flex-1")}>
|
||||
{showFolderRail ? (
|
||||
<FolderRail
|
||||
result={railFolderResult}
|
||||
@@ -661,7 +662,7 @@ export function Routines() {
|
||||
onDelete={setDeleteFolderTarget}
|
||||
/>
|
||||
) : null}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className={cn("min-w-0 flex-1", emptyList && "flex flex-col")}>
|
||||
{routineViewState.groupBy === "folder" && hasRoutineFolders ? (
|
||||
<div className="mb-3 flex flex-wrap items-center gap-2">
|
||||
{folderSelection === "all" ? <FolderIconHeader label="All routines" count={sortedRoutines.length} /> : (
|
||||
@@ -695,27 +696,13 @@ export function Routines() {
|
||||
/>
|
||||
) : null}
|
||||
{visibleRoutines.length === 0 && !routineViewState.statuses.length ? (
|
||||
<div className="py-12">
|
||||
<EmptyState
|
||||
icon={Repeat}
|
||||
message="No active routines. Use New routine to define the first recurring workflow."
|
||||
/>
|
||||
</div>
|
||||
<EmptyState placement="upper" message="No active routines." action="New routine" onAction={openCreateRoutine} />
|
||||
) : sortedRoutines.length === 0 ? (
|
||||
<div className="py-12">
|
||||
<EmptyState
|
||||
icon={Repeat}
|
||||
message={query.trim() ? "No routines match your search." : routineFilterKeys.some(key => routineViewState[key].length) || folderSelection === "all" ? "No routines match this view." : "This folder is empty."}
|
||||
/>
|
||||
{folderSelection !== "all" ? (
|
||||
<div className="mt-3 flex justify-center">
|
||||
<Button size="sm" onClick={openCreateRoutine}>
|
||||
<Plus className="mr-2 h-3.5 w-3.5" />
|
||||
New routine in this folder
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<EmptyState placement="upper"
|
||||
message={query.trim() ? "No routines match your search." : routineFilterKeys.some(key => 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}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex flex-col gap-3">
|
||||
{routineSections.map((group) => {
|
||||
|
||||
+11
-24
@@ -527,7 +527,7 @@ export function Routines() {
|
||||
}
|
||||
|
||||
if (!selectedCompanyId) {
|
||||
return <EmptyState icon={Repeat} message="Select an organization to view routines." />;
|
||||
return <EmptyState placement="upper" icon={Repeat} message="Select an organization to view routines." />;
|
||||
}
|
||||
|
||||
if (streamlinedUiEnabled && legacyRunsRequested) {
|
||||
@@ -585,8 +585,9 @@ export function Routines() {
|
||||
);
|
||||
}
|
||||
|
||||
const emptyList = sortedRoutines.length === 0;
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className={cn("space-y-6", emptyList && "empty-state-page")}>
|
||||
<h1 className="sr-only">Routines</h1>
|
||||
<RoutinesToolbar
|
||||
query={query} onQueryChange={query => updateRoutineView({ query })}
|
||||
@@ -653,7 +654,7 @@ export function Routines() {
|
||||
onRetry={foldersView.retry} retrying={foldersView.isFetching} />
|
||||
) : null}
|
||||
|
||||
<div className={cn(showFolderRail && "flex gap-4")}>
|
||||
<div className={cn(showFolderRail && "flex gap-4", emptyList && "flex flex-1")}>
|
||||
{showFolderRail ? (
|
||||
<FolderRail
|
||||
result={railFolderResult}
|
||||
@@ -671,7 +672,7 @@ export function Routines() {
|
||||
onDelete={setDeleteFolderTarget}
|
||||
/>
|
||||
) : null}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className={cn("min-w-0 flex-1", emptyList && "flex flex-col")}>
|
||||
{routineViewState.groupBy === "folder" && routineFolders && !hasRoutineFolders && !foldersLoading && visibleRoutines.length > 0 ? (
|
||||
<AllUnfiledBanner
|
||||
storageKey={`paperclip:routines-folder-nudge:${selectedCompanyId ?? "none"}`}
|
||||
@@ -680,27 +681,13 @@ export function Routines() {
|
||||
/>
|
||||
) : null}
|
||||
{visibleRoutines.length === 0 && !routineViewState.statuses.length ? (
|
||||
<div className="py-12">
|
||||
<EmptyState
|
||||
icon={Repeat}
|
||||
message="No active routines. Use New routine to define the first recurring workflow."
|
||||
/>
|
||||
</div>
|
||||
<EmptyState placement="upper" message="No active routines." action="New routine" onAction={openCreateRoutine} />
|
||||
) : sortedRoutines.length === 0 ? (
|
||||
<div className="py-12">
|
||||
<EmptyState
|
||||
icon={Repeat}
|
||||
message={query.trim() ? "No routines match your search." : routineFilterKeys.some(key => routineViewState[key].length) || folderSelection === "all" ? "No routines match this view." : "This folder is empty."}
|
||||
/>
|
||||
{folderSelection !== "all" ? (
|
||||
<div className="mt-3 flex justify-center">
|
||||
<Button size="sm" onClick={openCreateRoutine}>
|
||||
<Plus className="mr-2 h-3.5 w-3.5" />
|
||||
New routine in this folder
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<EmptyState placement="upper"
|
||||
message={query.trim() ? "No routines match your search." : routineFilterKeys.some(key => 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}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex flex-col gap-3">
|
||||
{routineSections.map((group) => {
|
||||
|
||||
@@ -2197,7 +2197,7 @@ export function Secrets() {
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<div className="flex max-w-6xl flex-col gap-4">
|
||||
<div className="empty-state-page flex max-w-6xl flex-col gap-4 has-[.empty-state]:max-w-none">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -2241,7 +2241,7 @@ export function Secrets() {
|
||||
<Tabs
|
||||
value={activeTab}
|
||||
onValueChange={(value) => setActiveTab(value as SecretsTab)}
|
||||
className="flex flex-col gap-4"
|
||||
className="flex flex-1 flex-col gap-4"
|
||||
>
|
||||
<PageTabBar
|
||||
items={[
|
||||
@@ -2342,7 +2342,7 @@ export function Secrets() {
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
<div>
|
||||
<div className="flex flex-1 flex-col">
|
||||
{secretsView.kind === "error" || userDefinitionsView.kind === "error" ? (
|
||||
<div className="py-4">
|
||||
<QueryErrorState
|
||||
@@ -2358,15 +2358,15 @@ export function Secrets() {
|
||||
) : unifiedRows.length === 0 &&
|
||||
!secretsListLoading &&
|
||||
!(showFolderView && folderPath) ? (
|
||||
<EmptyState
|
||||
<EmptyState placement="upper"
|
||||
icon={KeyRound}
|
||||
title="No secrets yet"
|
||||
message="Add an API key or token once, then choose which agents can use it."
|
||||
message={"Add an API key or token once,\nthen choose which agents can use it."}
|
||||
action="New secret"
|
||||
onAction={openCreateSecret}
|
||||
/>
|
||||
) : (
|
||||
<div className="@container min-w-0 overflow-x-hidden text-sm" data-testid="secrets-list-container">
|
||||
<div className="@container min-w-0 overflow-x-hidden text-sm has-[.empty-state]:flex has-[.empty-state]:flex-1 has-[.empty-state]:flex-col" data-testid="secrets-list-container">
|
||||
{showFolderView && folderPath ? (
|
||||
<div className="mb-3 flex flex-wrap items-center justify-between gap-x-3 gap-y-1">
|
||||
{renderSecretsBreadcrumb()}
|
||||
@@ -2387,7 +2387,7 @@ export function Secrets() {
|
||||
))}
|
||||
</div>
|
||||
) : showFolderView && folderPath && activeSecretFilterCount === 0 ? (
|
||||
<EmptyState
|
||||
<EmptyState placement="upper"
|
||||
icon={FolderOpen}
|
||||
message="No secrets in this folder yet."
|
||||
action="New secret here"
|
||||
@@ -2400,7 +2400,7 @@ export function Secrets() {
|
||||
: "Your team hasn't added a secret yet."}
|
||||
</p>
|
||||
) : (
|
||||
<EmptyState
|
||||
<EmptyState placement="upper"
|
||||
icon={Search}
|
||||
message={searching ? "No secrets match your search." : "No secrets match your filters."}
|
||||
/>
|
||||
@@ -2528,7 +2528,7 @@ export function Secrets() {
|
||||
</TabsContent>
|
||||
)}
|
||||
{!hideProposalsTab && (
|
||||
<TabsContent value="proposals">
|
||||
<TabsContent value="proposals" className="flex flex-col">
|
||||
{selectedCompanyId ? (
|
||||
<ProposalsTab companyId={selectedCompanyId} providerConfigs={providerConfigs} />
|
||||
) : null}
|
||||
|
||||
@@ -60,7 +60,7 @@ export function MyUserSecretsTab({ companyId }: { companyId: string }) {
|
||||
);
|
||||
|
||||
return (
|
||||
<section aria-label="My secrets" className="flex flex-col gap-4">
|
||||
<section aria-label="My secrets" className="flex flex-1 flex-col gap-4">
|
||||
<p className="max-w-xl text-sm text-muted-foreground">
|
||||
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" ? (
|
||||
<EmptyState
|
||||
<EmptyState placement="upper"
|
||||
icon={KeyRound}
|
||||
message="Nothing is asked of you yet. An admin decides which secrets each member provides."
|
||||
/>
|
||||
|
||||
@@ -461,7 +461,7 @@ export function ProposalsTab({
|
||||
|
||||
if (pending.length === 0 && decided.length === 0 && !decidedFailed) {
|
||||
return (
|
||||
<EmptyState
|
||||
<EmptyState placement="upper"
|
||||
icon={Inbox}
|
||||
title="Nothing to review"
|
||||
message="When an agent asks to save a secret or to use one, the request appears here."
|
||||
|
||||
@@ -181,7 +181,7 @@ export function UserSecretDefinitionsTab({ companyId }: { companyId: string }) {
|
||||
/>
|
||||
</div>
|
||||
) : definitions.length === 0 && !definitionsQuery.isPending && definitionsView.kind !== "reconnecting" ? (
|
||||
<EmptyState
|
||||
<EmptyState placement="upper"
|
||||
icon={UserRound}
|
||||
message="No user secret definitions yet. Create one to require each member to supply their own credential."
|
||||
action="New user secret"
|
||||
|
||||
Reference in new issue
Block a user