diff --git a/.github/workflows/ci-incremental-qualification.yml b/.github/workflows/ci-incremental-qualification.yml
index 43ea66b942d..3b9f8b1f33e 100644
--- a/.github/workflows/ci-incremental-qualification.yml
+++ b/.github/workflows/ci-incremental-qualification.yml
@@ -56,7 +56,7 @@ jobs:
const lanes = JSON.parse(readFileSync('.github/ci-task-matrix.json', 'utf8'));
const head = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
for (const [file, project, related] of [
- ['ui/src/pages/Inbox.tsx', '@paperclipai/ui', 'ui/src/pages/Inbox.test.tsx'],
+ ['ui/src/pages/Auth.tsx', '@paperclipai/ui', 'ui/src/pages/Auth.test.tsx'],
['server/src/middleware/auth.ts', '@paperclipai/server', 'server/src/__tests__/agent-auth-middleware.test.ts'],
['server/src/storage/config.test.ts', '@paperclipai/server', 'server/src/storage/config.test.ts'],
]) {
diff --git a/docs/api/costs.md b/docs/api/costs.md
index 1d99df02913..00efd4bbc38 100644
--- a/docs/api/costs.md
+++ b/docs/api/costs.md
@@ -75,7 +75,7 @@ Both are board-only. Both are separate from budgets.
A budget is a budget policy on one scope: `company`, `agent`, or `project`. Only board users can change budgets.
-Budgets count billed cost in cents (`billed_cents`). Usage with the billing type `subscription_included` has a cost of 0 cents, so a budget does not stop an agent that runs on a subscription.
+Budgets count billed cost in cents (`billed_cents`). Usage with the billing type `subscription_included` has a cost of 0 cents, so it never moves a budget toward its limit. A hard stop and `reservationCents` still apply to runs on a subscription.
### Budget Overview
@@ -125,7 +125,7 @@ POST /api/companies/{companyId}/budgets/policies
| `notifyEnabled` | `true` | Whether the warning opens |
| `hardStopEnabled` | `true` | Whether work stops when spend reaches the limit |
| `reservationCents` | `0` | An estimate held against the budget before each run starts |
-| `unpricedUsagePolicy` | `block` | `block` or `allow`. What to do when usage has no reliable price |
+| `unpricedUsagePolicy` | `block` | `block` or `allow`. What to do when a complete usage receipt has no reliable price |
| `isActive` | `true` | Set `false` to turn the policy off and keep its amount |
A scope has one policy for each window kind. A second call with the same scope and window updates the policy. Fields you leave out keep their value.
diff --git a/docs/guides/agent-developer/cost-reporting.md b/docs/guides/agent-developer/cost-reporting.md
index be58fe8b2d5..7cf06c71328 100644
--- a/docs/guides/agent-developer/cost-reporting.md
+++ b/docs/guides/agent-developer/cost-reporting.md
@@ -86,7 +86,7 @@ POST /api/companies/{companyId}/cost-events
Each cost event has a billing type. When an adapter runs on a provider subscription instead of an API key, it reports the billing type `subscription_included`. Paperclip keeps the token counts and records the cost as 0 cents.
-Budgets count billed cents only. Subscription usage therefore never moves an agent toward its budget, and a budget does not stop an agent that runs on a subscription.
+Budgets count billed cents only. Subscription usage therefore never moves an agent toward its budget. A hard stop on a company or project budget, and the reserve per run, still apply to an agent that runs on a subscription.
## Budget Awareness
diff --git a/docs/guides/board-operator/costs-and-budgets.md b/docs/guides/board-operator/costs-and-budgets.md
index 1b74c642452..4e7b7ef9faa 100644
--- a/docs/guides/board-operator/costs-and-budgets.md
+++ b/docs/guides/board-operator/costs-and-budgets.md
@@ -6,7 +6,7 @@ summary: Cost tracking, budget limits, hard stops, and budget incidents
Paperclip records the usage and cost of every agent run. You can set a budget for the company, for one agent, or for one project. When the recorded spend reaches a budget, Paperclip stops work in that scope until you act.
-A budget counts dollars only. Usage on a Claude, ChatGPT, or other provider subscription is recorded at $0, so **a budget does not stop an agent that runs on a subscription**. See [What a Budget Counts](#what-a-budget-counts).
+A budget counts dollars only. Usage on a Claude, ChatGPT, or other provider subscription is recorded at $0, so **subscription usage never moves a budget toward its limit**. A budget does not limit how much of a subscription an agent uses. A hard stop and the reserve per run still apply to subscription agents. See [What a Budget Counts](#what-a-budget-counts).
## What a Budget Counts
@@ -18,7 +18,7 @@ Every cost event has a billing type. The billing type decides whether the event
| Billing type | Recorded cost | Counts toward a budget |
|--------------|---------------|------------------------|
| `metered_api` | The cost the provider or Paperclip's price list reports | Yes |
-| `subscription_included` | Always $0. Tokens are still recorded | No |
+| `subscription_included` | Always $0. Tokens are still recorded | No. It adds $0 |
| `subscription_overage`, `credits`, `fixed` | The reported cost, if there is one | Yes, for the reported cost |
| `unknown` | The reported cost, if there is one | Yes, for the reported cost |
@@ -26,9 +26,17 @@ An agent runs on a subscription when its adapter signs in with a subscription ac
For these agents:
-- The spend stays at $0, so the warning and the hard stop never trigger.
-- The budget card shows $0 observed, even when the agent uses many tokens.
-- To stop the agent, pause it. See [Managing Agents](/guides/board-operator/managing-agents).
+- Their usage adds $0 to the spend. Subscription usage alone never triggers the warning or the hard stop.
+- The budget card shows $0 observed for their runs, even when they use many tokens.
+
+A budget can still stop an agent that runs on a subscription:
+
+- A hard stop stops all work in its scope. If API-billed work reaches the company budget or a project budget, the subscription agents in that company or project stop too.
+- The reserve per run is held for every run, whatever its billing type. If the reserve does not fit under the limit, the run is refused. See [Reserve per Run](#reserve-per-run).
+
+To limit how much of a subscription an agent uses:
+
+- Pause the agent. See [Managing Agents](/guides/board-operator/managing-agents).
- To see how much of the subscription is used, open the **Providers** tab. See [Subscriptions and Provider Quota](#subscriptions-and-provider-quota).
## How Cost Tracking Works
@@ -181,23 +189,33 @@ If the recorded spend plus the amounts held for unfinished runs would go above t
- The default is `0`, which turns the estimate off.
- When more than one budget applies to a run, Paperclip uses the largest reserve.
- The reserve is an estimate. The real cost of a run can be higher.
+- The reserve applies to every run, including a run on a subscription that records $0.
Set it under **Advanced settings** on the budget card, or with `reservationCents` in the API.
## Usage With No Reliable Price
-Sometimes Paperclip records usage but cannot give it a price. `unpricedUsagePolicy` controls what a budget with a hard stop does in that case:
+Sometimes Paperclip has a complete usage receipt for a run but cannot give it a price. `unpricedUsagePolicy` controls what a budget with a hard stop does with that usage:
- `block` (default) — a hard stop opens, even when the known spend is under the limit. To resume, resolve the unpriced usage or change the setting to `allow`. You cannot raise the budget past this stop.
- `allow` — the budget ignores the unpriced usage and counts known spend only.
-Subscription usage is not unpriced usage. It has a price of $0 and never triggers this setting.
+The budget card shows the usage that counts for this setting as **usage events are unpriced**. Hosted browser work with a cost that is not known yet also counts.
-In the UI, this is the **Block new work when usage has no reliable price** checkbox under **Advanced settings**. To see which runs have no price, expand **run costs unavailable** on the Costs overview. See [Cost Reporting](/guides/agent-developer/cost-reporting).
+This setting does not cover every entry that the Costs overview lists under **run costs unavailable**. These entries do not trigger `block`:
+
+- A run whose final usage receipt is missing or could not be captured
+- An entry that has a known partial cost
+- A metered API or subscription entry with no tokens
+- Subscription usage. It has a price of $0
+
+Work continues for those entries. For what each label on the Costs overview means, see [Cost Reporting](/guides/agent-developer/cost-reporting).
+
+In the UI, this setting is the **Block new work when usage has no reliable price** checkbox under **Advanced settings**.
## Subscriptions and Provider Quota
-Budgets do not cover subscriptions. Paperclip shows subscription information in two other places.
+Budgets do not measure subscription usage. Paperclip shows subscription information in two other places.
### Subscriptions
@@ -234,7 +252,7 @@ See the [Costs API](/api/costs) for the full list.
## Best Practices
-- Check how each agent is billed before you rely on a budget. A budget protects API-key usage. It does not limit a subscription
+- Check how each agent is billed before you rely on a budget. A budget measures API-billed spend. Subscription usage adds $0 to it
- Set conservative budgets initially and increase as you see results
- Use per-agent budgets to limit exposure from any single agent
- Use a project budget to cap the total cost of one piece of work
diff --git a/docs/guides/board-operator/creating-a-company.md b/docs/guides/board-operator/creating-a-company.md
index 5ebf0298f4c..1b94b45e5fc 100644
--- a/docs/guides/board-operator/creating-a-company.md
+++ b/docs/guides/board-operator/creating-a-company.md
@@ -50,9 +50,9 @@ Set monthly budgets at the company and per-agent level. You can also set a budge
- **Warning** at 80% of the budget. Work continues
- **Hard stop** at 100% — the company, agent, or project is paused, new work is refused, and a budget incident opens
-Both thresholds are settings on the budget.
+You can change the warning percentage and turn the hard stop on or off. The hard stop always uses 100% of the budget.
-Budgets count dollars only. Usage on a provider subscription is recorded at $0, so a budget does not stop an agent that runs on a subscription. See [Costs and Budgets](/guides/board-operator/costs-and-budgets).
+Budgets count dollars only. Usage on a provider subscription is recorded at $0, so subscription usage never moves a budget toward its limit. A hard stop still stops every agent in its scope. See [Costs and Budgets](/guides/board-operator/costs-and-budgets).
## Step 6: Launch
diff --git a/docs/guides/board-operator/managing-agents.md b/docs/guides/board-operator/managing-agents.md
index 59ebb440e2b..16bda7b8dcb 100644
--- a/docs/guides/board-operator/managing-agents.md
+++ b/docs/guides/board-operator/managing-agents.md
@@ -70,7 +70,7 @@ Edit an agent's configuration from the agent detail page:
- **Adapter config** — change model, prompt template, working directory, environment variables
- **Heartbeat settings** — interval, cooldown, max concurrent runs, wake triggers
-- **Budget** — monthly spend limit. It counts billed cost, so it does not limit an agent that runs on a subscription
+- **Budget** — monthly spend limit. It counts billed cost. Usage on a provider subscription adds $0 to it
Use the "Test Environment" button to validate that the agent's adapter config is correct before running.
@@ -90,7 +90,7 @@ POST /api/agents/{agentId}/resume
An agent is also paused when its recorded spend reaches its monthly budget, unless the hard stop is turned off for that budget. A budget pause opens a budget incident. Resolve it from the incident: raise the budget, or keep the agent paused. A budget pause on a monthly budget also ends when the next UTC month starts.
-Budgets count dollars only. Usage on a provider subscription is recorded at $0, so a budget does not pause an agent that runs on a subscription. See [Costs and Budgets](/guides/board-operator/costs-and-budgets).
+Budgets count dollars only. Usage on a provider subscription is recorded at $0, so an agent's subscription usage never reaches its budget. A hard stop on the company budget or on a project budget still stops the agent. See [Costs and Budgets](/guides/board-operator/costs-and-budgets).
## Terminating Agents
diff --git a/docs/start/core-concepts.md b/docs/start/core-concepts.md
index 27cfecb1af2..998dc77c431 100644
--- a/docs/start/core-concepts.md
+++ b/docs/start/core-concepts.md
@@ -24,7 +24,7 @@ Every employee is an AI agent. Each agent has:
- **Adapter type + config** — how the agent runs (Claude Code, Codex, shell process, HTTP webhook)
- **Role and reporting** — title, who they report to, who reports to them
- **Capabilities** — a short description of what the agent does
-- **Budget** — per-agent monthly spend limit. It counts billed cost, so it does not limit usage on a provider subscription
+- **Budget** — per-agent monthly spend limit. It counts billed cost. Usage on a provider subscription adds $0 to it
- **Status** — active, idle, running, error, paused, or terminated
Agents are organized in a strict tree hierarchy. Every agent reports to exactly one manager (except the CEO). This chain of command is used for escalation and delegation.
diff --git a/maps/agent-access-map/chat-channels.md b/maps/agent-access-map/chat-channels.md
index 3a61ad6c461..6a56ae72364 100644
--- a/maps/agent-access-map/chat-channels.md
+++ b/maps/agent-access-map/chat-channels.md
@@ -216,8 +216,8 @@ Gaps: This individual operation has source review but no recorded HTTP verificat
API: `present` — `POST /api/chat-endpoints/{endpointId}/github/app`; JSON REST.
Agent access: `available` — agent REST and default native `search_api` / `call_api` return a saved human credential-entry handoff; agents may send an empty body.
Policy: `tools:manage_connections`; [shared management policy](../../doc/plans/2026-10-13-connection-api-parity.md#authorization-contract). A human session imports the App credentials and signing key. Delegated service import is rejected, and agent requests persist no caller-chosen key.
-Evidence: `verified` — [route](../../server/src/routes/chat-channels.ts), [provider service](../../server/src/services/chat-channels/github/app-setup.ts), and [actual-auth fixture](../../server/src/__tests__/connection-management.integration.test.ts). Agent key/JWT handoffs leave vault refs unchanged. Fresh drafts open the saved import form without the reconnect flag; its component test submits App import with the required webhook secret. Human import persists credentials, then agent repository discovery and verification continue.
-Verification: `passed` — deterministic provider fixtures, assembled server and [saved-screen tests](../../ui/src/pages/apps/chat/GitHubChatSetup.test.tsx).
+Evidence: `verified` — [route](../../server/src/routes/chat-channels.ts), [provider service](../../server/src/services/chat-channels/github/app-setup.ts), and [actual-auth fixture](../../server/src/__tests__/connection-management.integration.test.ts). Agent key/JWT handoffs leave vault refs unchanged. Fresh drafts open the saved import form without the reconnect flag; browser E2E submits App import with the required webhook secret. Human import persists credentials, then agent repository discovery and verification continue.
+Verification: `passed` — deterministic provider fixtures, assembled server, and [browser chat-provider E2E](../../tests/e2e/chat-adapters-ui-providers-catalog.spec.ts).
Gaps: Human credential entry is intentional; no live provider qualification.
### `post-chat-endpoints-github-repositories-refresh`
diff --git a/maps/feature-map/agents.md b/maps/feature-map/agents.md
index 949ddfa48e3..d4f35e3ed0e 100644
--- a/maps/feature-map/agents.md
+++ b/maps/feature-map/agents.md
@@ -173,7 +173,7 @@ Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Use
### `hire-agent`
-Automated: [configuration form](../../ui/src/components/AgentConfigForm.render.test.tsx) covers mocked configuration-form UI behavior (mocked `NewAgent` page tests were removed; verify the new-agent page flow manually).
+Automated: [agent configuration E2E](../../tests/e2e/agent-configuration.spec.ts) and [configuration helpers](../../ui/src/components/AgentConfigForm.test.ts) cover configuration persistence (verify the new-agent page flow manually).
For an agent-owned plugin environment, verify preparation before connecting,
same-agent probes, account preservation after an environment change, failed
@@ -223,9 +223,9 @@ from the hiring picker; API fixture creation does not prove this UI journey.
Automated: [instruction service](../../server/src/__tests__/agent-instructions-service.test.ts) and [instruction revisions](../../server/src/__tests__/agent-instruction-revisions.test.ts) cover file/revision contracts.
-The [AI account field regression](../../ui/src/components/ai-connections/AiConnectionField.test.tsx)
-checks duplicate provider names, account identity in choices and adoption confirmation,
-the exact selected grant, and disabled unavailable accounts with authorized metadata fixtures.
+The [AI connection model tests](../../ui/src/components/ai-connections/model.test.ts)
+and [AI personal connection recovery E2E](../../tests/e2e/ai-personal-connection-recovery.spec.ts)
+cover provider/account compatibility and recovery.
Manually compare a personal API key and shared subscription with the same name in
Harness / Runtime. Confirm their method, scope and available identity before saving.
Reload the saved choice and verify the next eligible task uses it; labels alone
@@ -261,7 +261,7 @@ The notice must stay absent for native agents, other harnesses, and unsupported
targets. Discovery failure must not imply that an upgrade is available.
Navigate to another agent while an upgrade is pending. Its result must stay with
the original agent, without showing success on the new page or redirecting back.
-Focused coverage: [configuration form](../../ui/src/components/AgentConfigForm.render.test.tsx) (mocked upgrade save-receipt UI tests were removed; verify upgrade save receipts manually).
+Focused coverage: [agent configuration E2E](../../tests/e2e/agent-configuration.spec.ts) (verify upgrade save receipts manually).
For an existing native agent on a Daytona snapshot or immutable sandbox image,
use **Test** in its saved Harness or Runtime configuration after a managed
@@ -281,7 +281,7 @@ or provider execution.
### `organization`
-Automated: none (mocked org-chart and built-in agent configuration modal UI tests were removed; verify manually).
+Automated: none (verify manually).
Manual: Inspect a manager and report, change the relationship through the offered controls, and reload both views. Exercise a rejected invalid relationship. Configure a built-in agent and verify it retains its required identity and restrictions.
diff --git a/maps/feature-map/connection-setup.md b/maps/feature-map/connection-setup.md
index 446fd0223b5..eb3a9eb2216 100644
--- a/maps/feature-map/connection-setup.md
+++ b/maps/feature-map/connection-setup.md
@@ -101,14 +101,12 @@ do not establish OAuth registration, public callbacks, or production provider ac
### `apps-catalog`
-Automated: [Browse](../../ui/src/pages/apps/Browse.test.tsx) covers catalog entry
-with mocked APIs (mocked `AppNotConnected` and `AppsConnect` component tests were
-removed; coverage for access selection, method choices, and setup failures now relies
-on browser/manual checks). [Connection intents](../../tests/e2e/connection-intents.spec.ts)
-drives store and task setup against one fake provider through a useful continuation:
+Automated: [Connection intents](../../tests/e2e/connection-intents.spec.ts)
+and [chat provider catalog E2E](../../tests/e2e/chat-adapters-ui-providers-catalog.spec.ts)
+drive catalog entry and setup against fake providers through a useful continuation
+(Tailscale admin gating is covered by [TailscaleConnector](../../ui/src/pages/apps/TailscaleConnector.test.tsx)):
```sh
-pnpm exec vitest run ui/src/pages/apps/Browse.test.tsx
pnpm exec playwright test -c tests/e2e/playwright.config.ts tests/e2e/connection-intents.spec.ts
```
@@ -242,8 +240,7 @@ Slack setup does not qualify Discord, Telegram, GitHub, email, or iMessage.
Automated: [agent-authenticated integration](../../server/src/__tests__/connection-management.integration.test.ts)
uses production agent creation, persistent keys, run JWTs, native tool bindings,
human sessions, PostgreSQL and deterministic provider fixtures. It covers saved
-setup, ownership, attribution, scope, trust, work modes and revocation. (Mocked
-`GoogleWorkspaceServices` UI service-picker tests were removed; verify pending
+setup, ownership, attribution, scope, trust, work modes and revocation. (verify pending
choices and consent-picker UI manually.) These are separate from live provider
setup and model success.
diff --git a/maps/feature-map/inbox-search.md b/maps/feature-map/inbox-search.md
index 112f5178910..9776acc8069 100644
--- a/maps/feature-map/inbox-search.md
+++ b/maps/feature-map/inbox-search.md
@@ -149,8 +149,9 @@ approvals resolve. Only the stable list placeholder should appear until the
initial sources settle; a failed-run row must not jump when tasks arrive. Release
visible-row details separately and compare row/title bounds. Mine reads its own
100-row snapshot with parent/run context; sidebar badges use the count endpoint.
-The [Inbox component checks](../../ui/src/pages/Inbox.test.tsx) cover the source
-barrier and selected-source query; [badge tests](../../server/src/__tests__/inbox-dismissals.test.ts)
+The [inbox helpers](../../ui/src/lib/inbox.test.ts) and [coordinator inbox E2E](../../tests/e2e/coordinator-inbox-views.spec.ts)
+cover inbox projection and view transitions ;
+[badge tests](../../server/src/__tests__/inbox-dismissals.test.ts)
cover unread counts. Browser timing and layout proof remain separate from these tests.
### `decisions`
@@ -165,9 +166,7 @@ company/private-task isolation, and private v1 targets.
[Attention service regressions](../../server/src/__tests__/attention-service.test.ts)
cover pending question forms and confirmations in persistent agent chats, removal
after an answer with retained history, and company/task-visibility/addressee checks.
-Idle chats without structured requests remain absent. (Mocked
-`CoordinatorNeedsYou` UI component tests for chat-sourced canonical question
-routing were removed; verify Inbox card routing manually alongside the server
+Idle chats without structured requests remain absent. (verify Inbox card routing manually alongside the server
tests above.)
[Audience, badge and claim tests](../../server/src/__tests__/attention-audience-service.test.ts)
cover the view partition, the For you badge with per-view counts, the personal
@@ -195,9 +194,7 @@ route tests cover the active-member 422 and board-only writes.
[Obligation tests](../../server/src/__tests__/attention-obligations.test.ts)
cover the approval/review, budget-stop/override-approval and blocked-task/failed-run joins, the separate human
review gate, placement with the blocked task's person, one count per obligation,
-evidence that hides and restores with its lead, and the split after an answer.
-(Mocked UI component tests for `CoordinatorNeedsYou`, `WhatNeedsMe`, and
-`CoordinatorTaskCommitment` were removed; UI view switching, Archived/Restore,
+evidence that hides and restores with its lead, and the split after an answer. (UI view switching, Archived/Restore,
and reduced-motion card behavior are demonstrated in the Storybook stories below
and should be verified manually.)
The [Decisions views stories](../../ui/storybook/stories/inbox-search/needs-you-views.stories.tsx)
@@ -212,7 +209,7 @@ task context on receipt click. Turning the setting off restores the classic surf
### `search`
-Automated: [company search service](../../server/src/__tests__/company-search-service.test.ts) covers server search contracts (mocked `Search` page UI tests were removed; verify search page UI manually).
+Automated: [company search service](../../server/src/__tests__/company-search-service.test.ts) covers server search contracts (verify search page UI manually).
Manual: Search a unique task title and content phrase, open the result, and compare the actual record. Test filters, no results, and a second company. Verify stale results do not expose inaccessible data.
@@ -250,8 +247,8 @@ after switching company/account to verify suppression and isolation.
- A feature-map recipe and mocked UI tests do not prove live multiplayer behavior.
- Combined Inbox/Tasks requires both `enableCombinedInboxTasks` and
- `enableStreamlinedUi`. [Standalone Inbox tests](../../ui/src/pages/Inbox.test.tsx)
- render archive/read controls and toolbars; this is not live multi-user evidence.
+ `enableStreamlinedUi`. [Coordinator inbox E2E](../../tests/e2e/coordinator-inbox-views.spec.ts)
+ exercises combined and standalone inbox views; live multi-user evidence remains separate.
- Personal archival is not task cancellation or completion.
- Legacy Inbox routes can redirect to the combined task view; record which host actually rendered.
@@ -266,7 +263,7 @@ Capability ID: `inbox-search/views`.
Scope: ui
Storybook: Mine/Recent/Unread/Blocked and broader task views; combined versus standalone host; loading/empty/error/filter states.
Production: Use persisted personal participation/read data; verify scoped counts and list navigation/reload; automatic read cleanup must not create Mine membership.
-Sources: Source: [Inbox.tsx](../../ui/src/pages/Inbox.tsx), [Issues.tsx](../../ui/src/pages/Issues.tsx). Tests: [Inbox.test.tsx](../../ui/src/pages/Inbox.test.tsx), [Issues.test.tsx](../../ui/src/pages/Issues.test.tsx), [issues-service.test.ts](../../server/src/__tests__/issues-service.test.ts)
+Sources: Source: [Inbox.tsx](../../ui/src/pages/Inbox.tsx), [Issues.tsx](../../ui/src/pages/Issues.tsx). Tests: [inbox.test.ts](../../ui/src/lib/inbox.test.ts), [Issues.test.tsx](../../ui/src/pages/Issues.test.tsx), [issues-service.test.ts](../../server/src/__tests__/issues-service.test.ts), [coordinator-inbox-views.spec.ts](../../tests/e2e/coordinator-inbox-views.spec.ts)
#### `toasts`
diff --git a/maps/feature-map/questions-and-approvals.md b/maps/feature-map/questions-and-approvals.md
index 3648347be4a..dd92dade821 100644
--- a/maps/feature-map/questions-and-approvals.md
+++ b/maps/feature-map/questions-and-approvals.md
@@ -101,8 +101,7 @@ Use these checks alongside the entry-point recipes below and the operation recor
### `task-thread`
-Automated: [interaction cards](../../ui/src/components/IssueThreadInteractionCard.test.tsx),
-[paged task cards](../../ui/src/components/task-chat/TaskChatInteractionCard.test.tsx),
+Automated: [interaction cards](../../ui/src/components/IssueThreadInteractionCard.test.tsx)
and [task thread](../../ui/src/components/TaskChatThread.test.tsx) cover form,
receipt, and dismissal behavior. [Resolution routes](../../server/src/__tests__/issue-thread-interaction-routes.test.ts)
and [response delivery](../../server/src/__tests__/question-response-delivery.test.ts)
@@ -132,8 +131,7 @@ history remains and the conversation does not close as a completed task.
### `attention`
-Automated: the resolution-route tests above cover the API (mocked
-`AttentionInteractionResolver` UI component tests were removed; verify
+Automated: the resolution-route tests above cover the API (verify
preparing-request refresh and Decisions/Inbox navigation manually).
Manual: open the same pending request in an attention row and task tab. Resolve
diff --git a/maps/feature-map/routines.md b/maps/feature-map/routines.md
index d4292dfc660..5b899f019c9 100644
--- a/maps/feature-map/routines.md
+++ b/maps/feature-map/routines.md
@@ -42,7 +42,7 @@ Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Use
### `routine-editor`
-Automated: [routine form tests](../../ui/src/components/routine-page/routine-form.test.ts) cover schedule and responsibility sync, and [Routine service](../../server/src/__tests__/routines-service.test.ts) covers server contracts (mocked `RoutineDetail` page tests were removed; verify page redirects, History paging, status switch, save conflicts, and running a routine manually).
+Automated: [routine form tests](../../ui/src/components/routine-page/routine-form.test.ts) cover schedule and responsibility sync, and [Routine service](../../server/src/__tests__/routines-service.test.ts) covers server contracts (verify page redirects, History paging, status switch, save conflicts, and running a routine manually).
Manual: Save an agent, request, project, and a required variable. Reload and inspect the saved definition. Run now with a distinguishable input, follow the resulting task, and verify its output and history entry. Check a missing required input.
@@ -53,7 +53,7 @@ complete the generated task or establish a useful task output.
### `trigger-history`
-Automated: [webhook instructions](../../ui/src/components/routine-triggers/webhook-instructions.test.ts) and [webhook fields](../../ui/src/components/routine-triggers/WebhookFields.test.tsx) are component coverage; [routine integration](../../server/src/__tests__/routines-e2e.test.ts) is server integration rather than a provider-wide browser proof.
+Automated: [webhook instructions](../../ui/src/components/routine-triggers/webhook-instructions.test.ts) and [replay masking](../../ui/src/lib/analytics/replay-masking.test.tsx) cover webhook instructions and secret-field replay blocking; [routine integration](../../server/src/__tests__/routines-e2e.test.ts) is server integration rather than a provider-wide browser proof.
Manual: Set a near-term disposable schedule or authorized test webhook, verify one eligible execution and its source trigger, then disable it and confirm further invocations stop. Inspect a failed execution without losing its history. Remove the temporary trigger after testing.
diff --git a/packages/db/src/better-auth-account-issuer-migration.test.ts b/packages/db/src/better-auth-account-issuer-migration.test.ts
deleted file mode 100644
index 47466f37076..00000000000
--- a/packages/db/src/better-auth-account-issuer-migration.test.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { getTableConfig } from "drizzle-orm/pg-core";
-import { describe, expect, it } from "vitest";
-import { authAccounts } from "./schema/auth.js";
-
-describe("account issuer schema", () => {
- it("keeps issuer nullable and identifies accounts by provider and account ID", () => {
- const config = getTableConfig(authAccounts);
- const issuer = config.columns.find((column) => column.name === "issuer");
- expect(issuer).toBeDefined();
- expect(issuer?.notNull).toBe(false);
-
- const unique = config.indexes.find((index) => index.config.name === "account_provider_account_id_uq");
- expect(unique?.config.unique).toBe(true);
- expect(unique?.config.columns.map((column) => (column as { name: string }).name)).toEqual([
- "provider_id",
- "account_id",
- ]);
- });
-});
diff --git a/packages/shared/src/connection-intent-guidance.test.ts b/packages/shared/src/connection-intent-guidance.test.ts
deleted file mode 100644
index ae89f72dff4..00000000000
--- a/packages/shared/src/connection-intent-guidance.test.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { CONNECTION_INTENT_AGENT_GUIDANCE, CONNECTION_REQUEST_TOOL_DESCRIPTION, CONNECTION_RUNTIME_TOOL_NAMES, CONNECTIONS_SEARCH_TOOL_DESCRIPTION } from "./connection-intent-guidance.js";
-describe("connection result guidance", () => {
- it("delegates route decisions to trusted tool output instead of a provider decision tree", () => {
- expect(CONNECTION_INTENT_AGENT_GUIDANCE).toContain("follow the returned `instruction`");
- expect(CONNECTION_INTENT_AGENT_GUIDANCE).toContain("Respect recorded declines and provider choices");
- expect(CONNECTION_INTENT_AGENT_GUIDANCE).not.toMatch(/Composio|Arcade|Executor|Zapier/);
- expect(CONNECTION_INTENT_AGENT_GUIDANCE).not.toMatch(/https?:\/\/|bearer/);
- });
- it("retains waiting, credential, and arbitrary URL boundaries", () => {
- expect(CONNECTION_INTENT_AGENT_GUIDANCE).toContain("yield without retrying or polling");
- expect(CONNECTION_INTENT_AGENT_GUIDANCE).toContain("never ask for credentials in comments");
- expect(CONNECTION_INTENT_AGENT_GUIDANCE).toContain("arbitrary MCP URLs");
- });
- it("binds a request card to the person it is addressed to", () => {
- expect(CONNECTION_INTENT_AGENT_GUIDANCE).toContain("Only that person can complete or decline it");
- });
- it("describes exact questions and saved selection proof", () => {
- expect(CONNECTIONS_SEARCH_TOOL_DESCRIPTION).toContain("exact providerQuestion");
- expect(CONNECTION_REQUEST_TOOL_DESCRIPTION).toContain("saved provider-selection interaction ID");
- expect(CONNECTION_RUNTIME_TOOL_NAMES).toEqual(["connections_search","connection_request"]);
- });
-});
diff --git a/packages/shared/src/telemetry/readme-contract.test.ts b/packages/shared/src/telemetry/readme-contract.test.ts
deleted file mode 100644
index eec9d4511dd..00000000000
--- a/packages/shared/src/telemetry/readme-contract.test.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { describe, expect, it } from "vitest";
-import * as generatedTelemetry from "./generated/paperclip-telemetry.js";
-
-const readmePath = fileURLToPath(new URL("./README.md", import.meta.url));
-
-describe("telemetry README contract", () => {
- it("documents generated event helper exports that exist", () => {
- const readme = readFileSync(readmePath, "utf8");
-
- expect(generatedTelemetry.SCHEMA_VERSION).toBeDefined();
- expect(generatedTelemetry.makeEvent).toBeTypeOf("function");
- expect(generatedTelemetry.makeBatch).toBeTypeOf("function");
- expect(readme).toContain("`SCHEMA_VERSION`, `makeEvent()`, and `makeBatch()`");
- expect(readme).not.toContain("createPaperclipTelemetryEvent");
- expect(readme).not.toContain("createPaperclipTelemetryEnvelope");
- });
-});
diff --git a/packages/shared/src/validators/chat-channels.test.ts b/packages/shared/src/validators/chat-channels.test.ts
index eb157fcb001..4f58b4abfbc 100644
--- a/packages/shared/src/validators/chat-channels.test.ts
+++ b/packages/shared/src/validators/chat-channels.test.ts
@@ -5,6 +5,7 @@ import {
resolveChatActionSchema,
resolveChatPublicationSchema,
chatPublicationStateSchema,
+ updateChatEndpointSchema,
} from "./chat-channels.js";
describe("Microsoft Teams chat credential validation", () => {
@@ -111,3 +112,14 @@ describe("chat provider-action resolution validation", () => {
);
});
});
+
+describe("chat endpoint communicationInstructions validation", () => {
+ it("accepts clearing instructions and rejects oversized instructions and unsupported controls", () => {
+ expect(updateChatEndpointSchema.parse({ communicationInstructions: " " })).toEqual({
+ communicationInstructions: "",
+ });
+ expect(updateChatEndpointSchema.safeParse({ communicationInstructions: "a".repeat(4001) }).success).toBe(false);
+ expect(updateChatEndpointSchema.safeParse({ replyDetail: "brief" }).success).toBe(false);
+ expect(updateChatEndpointSchema.safeParse({ progressUpdates: false }).success).toBe(false);
+ });
+});
diff --git a/packages/skills-catalog/src/release-content-cases-contract.test.ts b/packages/skills-catalog/src/release-content-cases-contract.test.ts
deleted file mode 100644
index 64bd29a3372..00000000000
--- a/packages/skills-catalog/src/release-content-cases-contract.test.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-function readRepoFile(path: string) {
- return readFileSync(new URL(`../../../${path}`, import.meta.url), "utf8");
-}
-
-describe("release-content Cases contract", () => {
- it("keeps release-content skills wired to emit the required case tree", () => {
- const release = readRepoFile(".agents/skills/release/SKILL.md");
- const changelog = readRepoFile(".agents/skills/release-changelog/SKILL.md");
- const discord = readRepoFile(".agents/skills/release-changelog-discord-message/SKILL.md");
- const announcement = readRepoFile("packages/skills-catalog/catalog/optional/content/release-announcement/SKILL.md");
- const combined = [release, changelog, discord, announcement].join("\n");
-
- for (const required of [
- "\"caseType\": \"release\"",
- "\"caseType\": \"blog_post\"",
- "\"caseType\": \"tweet_storm\"",
- "\"parentCaseId\"",
- "PUT /api/cases/:caseId/documents/body",
- "paperclip-release:vYYYY.MDD.P",
- "X-Paperclip-Run-Id",
- ]) {
- expect(combined).toContain(required);
- }
-
- expect(release).toContain("same three cases instead of duplicating them");
- expect(changelog).toContain("\"release_patch\": 0");
- expect(changelog).toContain("\"stable\": true");
- expect(changelog).toContain("\"channels\": [\"changelog\", \"blog_post\", \"tweet_storm\"]");
- expect(changelog).toContain("\"artifacts\"");
- expect(changelog).toContain("\"verification\"");
- expect(changelog).toContain("\"notes\": null");
- expect(announcement).toContain("\"word_count_target\": 650");
- expect(announcement).toContain("\"requires_screenshot\": false");
- expect(discord).toContain("\"needs_human_copy_paste\": true");
- expect(discord).toContain("\"approved_by\": null");
- });
-});
diff --git a/scripts/general-server-shard-durations.json b/scripts/general-server-shard-durations.json
index e9b11bcf4fd..e5cf2d3d0ba 100644
--- a/scripts/general-server-shard-durations.json
+++ b/scripts/general-server-shard-durations.json
@@ -10,9 +10,9 @@
}
],
"coverage": {
- "measured": 1577,
- "withSetup": 1577,
- "inventory": 2142
+ "measured": 1573,
+ "withSetup": 1573,
+ "inventory": 2138
},
"durations": {
"server/scripts/build-config.test.mjs": 10828,
@@ -900,7 +900,6 @@
"server/src/__tests__/prepared-chat-authorization.integration.test.ts": 7209,
"server/src/__tests__/prepared-statements-driver.test.ts": 6901,
"server/src/__tests__/prepared-statements.test.ts": 803,
- "server/src/__tests__/primary-agent-guidance.test.ts": 4326,
"server/src/__tests__/primary-agent.test.ts": 10405,
"server/src/__tests__/principal-access-compatibility.test.ts": 3032,
"server/src/__tests__/privacy-production-review.test.ts": 12611,
@@ -1032,7 +1031,6 @@
"server/src/__tests__/scoped-deadline-work-notifications.test.ts": 2950,
"server/src/__tests__/scoped-deadline-work.test.ts": 2998,
"server/src/__tests__/secret-binding-discovery.test.ts": 2921,
- "server/src/__tests__/secret-entry-guidance.test.ts": 3727,
"server/src/__tests__/secret-provider-registry.test.ts": 917,
"server/src/__tests__/secret-sensitive-request-error.test.ts": 6884,
"server/src/__tests__/secrets-service-dangling-user-secret.test.ts": 8396,
@@ -1453,7 +1451,6 @@
"server/src/services/chat-channels/slack/receipt-timing.test.ts": 940,
"server/src/services/chat-channels/slack/signing-secret-preflight.test.ts": 7167,
"server/src/services/chat-channels/slack/wake-authority.test.ts": 908,
- "server/src/services/chat-communication-guidance.test.ts": 1886,
"server/src/services/chat-control-admission-retry.test.ts": 5391,
"server/src/services/chat-discord-adapter-patch.test.ts": 4770,
"server/src/services/chat-discord-command-registration-store.test.ts": 7446,
@@ -1969,7 +1966,6 @@
"server/src/services/object-run-log-store.test.ts": 9158,
"server/src/services/offline-workspace-operation-reconciliation.test.ts": 8220,
"server/src/services/onboarding-first-task-assets.test.ts": 2668,
- "server/src/services/onboarding-greeting.test.ts": 1943,
"server/src/services/online-durable-data-migration-postgres.test.ts": 9418,
"server/src/services/online-durable-data-migration.test.ts": 8010,
"server/src/services/online-legacy-workspace-recovery.test.ts": 6018,
diff --git a/scripts/storybook-button-usage.test.mjs b/scripts/storybook-button-usage.test.mjs
deleted file mode 100644
index d63699351be..00000000000
--- a/scripts/storybook-button-usage.test.mjs
+++ /dev/null
@@ -1,25 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-import { buttonReferences } from "./storybook-button-usage.mjs";
-
-test("button usage follows canonical imports and aliases, excluding native and unrelated buttons", () => {
- const entries = buttonReferences(`
- import { Button as Action } from '@/components/ui/button';
- import * as UI from './ui/button';
- import { Button } from './OtherButton';
- export const View = () => <>>;
- `, "ui/src/components/Example.tsx", "app");
- assert.equal(entries.length, 2);
- assert.deepEqual(entries.map(({ variant, size, scope }) => ({ variant, size, scope })), [
- { variant: "outline", size: "sm", scope: "app" }, { variant: "default", size: "default", scope: "app" },
- ]);
-});
-
-test("dynamic props and spread precedence are not reported as known defaults", () => {
- const entries = buttonReferences(`
- import { Button } from '@/components/ui/button';
- export const View = () => <>>;
- `, "ui/src/pages/Example.tsx", "app");
- assert.deepEqual(entries.map(entry => entry.variant), ["dynamic / spread", "dynamic", "dynamic / spread", "ghost"]);
- assert.deepEqual(entries.map(entry => entry.size), ["dynamic / spread", "default", "dynamic / spread", "dynamic / spread"]);
-});
diff --git a/scripts/storybook-muse-catalog.test.mjs b/scripts/storybook-muse-catalog.test.mjs
deleted file mode 100644
index ad6041003b2..00000000000
--- a/scripts/storybook-muse-catalog.test.mjs
+++ /dev/null
@@ -1,68 +0,0 @@
-import assert from "node:assert/strict";
-import { existsSync, readFileSync } from "node:fs";
-import path from "node:path";
-import { test } from "node:test";
-import { fileURLToPath } from "node:url";
-import { catalogFromStories, renderIndex, scanStories, validateCatalog } from "./storybook-catalog.mjs";
-import { featureIndex } from "./feature-map.mjs";
-
-const root = fileURLToPath(new URL("../", import.meta.url));
-const file = "ui/storybook/stories/agents/external-agent-invite/muse.stories.tsx";
-const stableId = "onboarding-external-agent-invitation-muse-personal-agent";
-const index = featureIndex(root);
-const stories = scanStories(root);
-const catalog = catalogFromStories(stories, index);
-const muse = stories.find(story => story.file === file);
-
-// These IDs predate the move; existing links must survive the feature title change.
-test("real Muse suite preserves all existing journey IDs and resolves relocated imports", () => {
- assert.ok(muse, "Muse suite must be discovered in its agent feature home");
- assert.equal(muse.metaId, stableId);
- assert.deepEqual(muse.ids, [
- "start-here", "name-and-role", "copy-setup", "paired", "receiver-detected",
- "finishing-setup", "ready", "approval", "loading-invitation",
- "authenticated-instance-required", "missing-public-host", "no-recent-response",
- "replaced-prompt", "mobile", "mobile-details", "light", "copy-and-verify",
- "settings", "stop-boundary", "expired-connection",
- ].map(suffix => `${stableId}--${suffix}`));
- assert.equal(muse.plays, 1);
- assert.equal(existsSync(path.join(root, "ui/storybook/stories/external-agent-invite/muse.stories.tsx")), false);
- const source = readFileSync(path.join(root, file), "utf8");
- for (const [, relative] of source.matchAll(/from "(\.[^"]+)"/g)) {
- assert.ok(existsSync(path.resolve(root, path.dirname(file), `${relative}.tsx`))
- || existsSync(path.resolve(root, path.dirname(file), `${relative}.ts`)), `Unresolved moved import: ${relative}`);
- }
-});
-
-test("Muse registration validates actual production subjects with honest fixture limits", () => {
- const entries = catalog.entries.filter(entry => entry.file === file);
- assert.equal(entries.length, 1);
- const entry = entries[0];
- assert.equal(entry.stableId, stableId);
- assert.equal(entry.sidebarTitle, muse.title);
- assert.deepEqual(entry.capabilities, ["agents/hire", "agents/lifecycle", "access/invitations"]);
- assert.equal(entry.status, "unreviewed");
- assert.equal(entry.implementation, "production");
- assert.equal(entry.boundary, "fixtures");
- const source = readFileSync(path.join(root, file), "utf8");
- assert.ok(source.includes("component: ExternalAgentInvitePreview"));
- for (const subject of [
- "../../../support/external-agent-invite/ExternalAgentInvitePreview",
- "@/components/MuseRunnerConnection",
- "../../../support/external-agent-invite/muse-fixtures",
- ]) assert.ok(source.includes(`from "${subject}"`), `Missing rendered subject or fixture import: ${subject}`);
- assert.match(entry.notes, /simulated API state/);
- assert.match(entry.notes, /Does not establish live provider/);
- const errors = validateCatalog(catalog, stories, index);
- // Other suites retain their outstanding reviews; this assertion covers Muse only.
- assert.deepEqual(errors.filter(error => error.startsWith(file)), []);
- assert.ok(!errors.includes("Duplicate story IDs"));
-});
-
-test("generated catalog navigation links the one Muse suite from every registered capability", () => {
- const generated = renderIndex(catalog, stories, index);
- for (const capability of ["agents/hire", "agents/lifecycle", "access/invitations"]) {
- const line = generated.split("\n").find(text => text.startsWith(`- \`${capability}\`:`));
- assert.ok(line?.includes(`../../${file}`), `Missing Muse lookup: ${capability}`);
- }
-});
diff --git a/server/src/__tests__/primary-agent-guidance.test.ts b/server/src/__tests__/primary-agent-guidance.test.ts
deleted file mode 100644
index 7d44bff4249..00000000000
--- a/server/src/__tests__/primary-agent-guidance.test.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { expect, it, vi } from "vitest";
-import { searchRunnerApi } from "../services/native-runtime/runner-api-catalog.js";
-import { executeRunnerApi } from "../services/native-runtime/runner-api-client.js";
-import { startOpenCodeMcpBridge } from "../../../packages/paperclip-runner/src/drivers/opencode/mcp-bridge.js";
-import { searchApiAction } from "../../../packages/paperclip-runner/src/protocol-actions/search-api.js";
-
-it("delivers personal primary profile guidance through actual API discovery and bounded OpenCode MCP output", async () => {
- const descriptor = searchApiAction.live.descriptor;
- let calls = 0;
- const bridge = await startOpenCodeMcpBridge({
- tools: [{ name: descriptor.operationId, description: descriptor.description, inputSchema: descriptor.inputSchema }],
- handler: async call => {
- expect(call.tool).toBe("search_api"); calls++;
- return { type: "inputText", text: JSON.stringify(searchRunnerApi(call.arguments)) };
- },
- });
- try {
- const response = await fetch(bridge.url, { method: "POST", headers: {
- Authorization: `Bearer ${bridge.secret}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream",
- }, body: JSON.stringify({ jsonrpc: "2.0", id: "primary-guidance", method: "tools/call",
- params: { name: "paperclip_search_api", arguments: { query: "set primary agent", limit: 2 } } }) });
- expect(response.status).toBe(200);
- const wire = await response.json() as { result: { isError?: boolean; content: Array<{ type: string; text: string }> } };
- expect(wire.result.isError).not.toBe(true);
- const controller = JSON.parse(wire.result.content[0]!.text) as { type: string; text: string };
- expect(controller.type).toBe("inputText");
- expect(Buffer.byteLength(JSON.stringify(controller))).toBeLessThan(500_000);
- const discovered = JSON.parse(controller.text) as ReturnType;
- const operation = discovered.results.find(row => row.operationId === "PUT /api/companies/{companyId}/primary-agent/me");
- expect(operation).toBeDefined();
- expect(operation!.description).toMatch(/agent.{0,12}profile/i);
- expect(operation!.description).toContain("Set as my primary");
- expect(operation!.description).toMatch(/confirm.{0,30}replac/i);
- expect(operation!.description).toMatch(/chat picker.{0,70}does not change/i);
- expect(operation!.authorization.actor).toBe("board");
- expect(operation!.description).toContain("Agent credentials cannot access it");
- expect(operation!.requestBody?.content["application/json"].schema.properties.primaryAgentId).toMatchObject({ type: "string", format: "uuid" });
- expect(calls).toBe(1);
- } finally { await bridge.close(); }
-});
-
-it("keeps personal preference calls on the agent identity and preserves the board-only denial", async () => {
- const companyId = "00000000-0000-4000-8000-000000000111", runId = "00000000-0000-4000-8000-000000000112";
- const request = vi.fn(async () => Response.json({ error: "Board access required" }, { status: 403 }));
- const result = await executeRunnerApi({ operationId: "PUT /api/companies/{companyId}/primary-agent/me",
- body: { primaryAgentId: "00000000-0000-4000-8000-000000000113" } },
- { companyId, runId, issueId: "00000000-0000-4000-8000-000000000114", workMode: "standard" },
- { apiUrl: "https://paperclip.test", token: "synthetic-agent-only", fetch: request,
- readFile: async () => { throw new Error("No file read required"); },
- saveResponse: async () => { throw new Error("No capture required"); } });
- expect(result).toMatchObject({ ok: false, status: 403, data: { error: "Board access required" } });
- expect(request).toHaveBeenCalledOnce();
- const headers = new Headers(request.mock.calls[0]![1]?.headers);
- expect(headers.get("Authorization")).toBe("Bearer synthetic-agent-only");
- expect(headers.get("X-Paperclip-Run-Id")).toBe(runId);
-});
diff --git a/server/src/__tests__/secret-entry-guidance.test.ts b/server/src/__tests__/secret-entry-guidance.test.ts
deleted file mode 100644
index 8b242ee68cd..00000000000
--- a/server/src/__tests__/secret-entry-guidance.test.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { expect, it } from "vitest";
-import { searchRunnerApi } from "../services/native-runtime/runner-api-catalog.js";
-import { startOpenCodeMcpBridge } from "../../../packages/paperclip-runner/src/drivers/opencode/mcp-bridge.js";
-import { searchApiAction } from "../../../packages/paperclip-runner/src/protocol-actions/search-api.js";
-
-it("discovers the existing secure human entry surface through native API search", async () => {
- const descriptor = searchApiAction.live.descriptor;
- const bridge = await startOpenCodeMcpBridge({
- tools: [{ name: descriptor.operationId, description: descriptor.description, inputSchema: descriptor.inputSchema }],
- handler: async call => ({ type: "inputText", text: JSON.stringify(searchRunnerApi(call.arguments)) }),
- });
- try {
- for (const query of ["company credential secret", "personal publishing credential"]) {
- const response = await fetch(bridge.url, { method: "POST", headers: {
- Authorization: `Bearer ${bridge.secret}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream",
- }, body: JSON.stringify({ jsonrpc: "2.0", id: query, method: "tools/call",
- params: { name: "paperclip_search_api", arguments: { query } } }) });
- expect(response.status).toBe(200);
- const wire = await response.json() as { result: { isError?: boolean; content: Array<{ text: string }> } };
- expect(wire.result.isError).not.toBe(true);
- const controller = JSON.parse(wire.result.content[0]!.text) as { text: string };
- const discovered = JSON.parse(controller.text) as ReturnType;
- const operations = discovered.results.filter(operation => operation.description.includes("/company/settings/secrets"));
- expect(operations.length, query).toBeGreaterThan(0);
- expect(operations.some(operation => /human|signed-in person/.test(operation.description))).toBe(true);
- expect(operations.some(operation => /never.*chat/i.test(operation.description))).toBe(true);
- if (query.startsWith("personal")) {
- const definitions = operations.find(operation => operation.path.endsWith("user-secret-definitions"));
- expect(definitions?.description).toContain("Set my value");
- expect(definitions?.description).toContain("current person");
- expect(definitions?.description).toContain("Company admins can also open definition details");
- expect(definitions?.description).toContain("other members use My secrets and Set my value");
- expect(definitions?.authorization.actor).toBe("board");
- }
- }
- } finally { await bridge.close(); }
-});
diff --git a/server/src/services/chat-communication-guidance.test.ts b/server/src/services/chat-communication-guidance.test.ts
deleted file mode 100644
index 23f65cec3e1..00000000000
--- a/server/src/services/chat-communication-guidance.test.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { CHAT_PROVIDERS, updateChatEndpointSchema } from "@paperclipai/shared";
-import { buildChatCommunicationGuidance } from "./chat-communication-guidance.js";
-
-describe("initial medium communication guidance", () => {
- it.each([true, false])("requires result and review updates in Slack (direct=%s)", (isDirectMessage) => {
- const guidance = buildChatCommunicationGuidance({ provider: "slack", isDirectMessage });
- expect(guidance).toContain("When you have results, update the user in the originating Slack");
- expect(guidance).toContain("Put this update in your final response");
- expect(guidance).toContain("When the user needs to review a plan, approve an action, or review a result");
- expect(guidance).toContain("create the required human-input or approval interaction before you yield");
- expect(guidance).toContain("do not continue gated work until the required approval is recorded");
- });
-
- it("guides Slack presentation while retaining ordinary agent tools and explicit output requests", () => {
- const guidance = buildChatCommunicationGuidance({ provider: "slack", isDirectMessage: false, communicationInstructions: "Use customer-facing names." });
- expect(guidance).toContain("shared channel thread");
- expect(guidance).toContain("document or artifact tools");
- expect(guidance).toContain("exact output");
- expect(guidance).toContain("grant no additional authority");
- expect(guidance).toContain('"Use customer-facing names."');
- expect(buildChatCommunicationGuidance({ provider: "slack", isDirectMessage: true })).toContain("direct conversation");
- });
-
- it("keeps voice presentation concise without cancelling work on hangup or granting approvals", () => {
- const guidance = buildChatCommunicationGuidance({ provider: "speko", isDirectMessage: true });
- expect(guidance).toContain("Communication by voice");
- expect(guidance).toContain("Keep your existing identity, runtime, tools, and task assignment");
- expect(guidance).toContain("one focused clarification");
- expect(guidance).toContain("durable Paperclip continuation");
- expect(guidance).toContain("Delivery to Speko does not prove an answer was spoken");
- expect(guidance).toContain("does not cancel work");
- expect(guidance).toContain("Protected approvals must be completed in Paperclip");
- });
-
- it.each([false, true])("requires public links for created Slack tasks (DM: %s)", (isDirectMessage) => {
- const guidance = buildChatCommunicationGuidance({ provider: "slack", isDirectMessage });
- expect(guidance).toContain("include a clickable link to each created task");
- expect(guidance).toContain("task identifier or title as the link text");
- expect(guidance).toContain("public task URL returned by Paperclip tools or supplied in task context");
- expect(guidance).toContain("never guess a URL");
- expect(guidance).toContain("If no public task URL is available, say that the link is unavailable");
- });
-
- it.each(CHAT_PROVIDERS.filter((provider) => provider !== "slack" && provider !== "speko"))("leaves %s unchanged", (provider) => {
- expect(buildChatCommunicationGuidance({ provider, isDirectMessage: false, communicationInstructions: "Ignored" })).toBeNull();
- });
-
- it("accepts clearing instructions and rejects oversized instructions and unsupported controls", () => {
- expect(updateChatEndpointSchema.parse({ communicationInstructions: " " })).toEqual({ communicationInstructions: "" });
- expect(updateChatEndpointSchema.safeParse({ communicationInstructions: "a".repeat(4001) }).success).toBe(false);
- expect(updateChatEndpointSchema.safeParse({ replyDetail: "brief" }).success).toBe(false);
- expect(updateChatEndpointSchema.safeParse({ progressUpdates: false }).success).toBe(false);
- });
-});
diff --git a/server/src/services/onboarding-greeting.test.ts b/server/src/services/onboarding-greeting.test.ts
deleted file mode 100644
index a3a1ff5289d..00000000000
--- a/server/src/services/onboarding-greeting.test.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { renderOnboardingGreeting } from "./onboarding-greeting.js";
-
-describe("renderOnboardingGreeting", () => {
- it("introduces the agent by name as the user's first teammate", async () => {
- const greeting = await renderOnboardingGreeting({
- agentName: "Nova",
- organizationName: "Acme",
- });
-
- expect(greeting).toContain(
- "Welcome to Paperclip! I'm Nova, your first agent teammate.",
- );
- // No goal quote and no "give me one moment" — the agent is not about to run.
- expect(greeting).not.toContain("aiming for");
- expect(greeting).not.toContain("one moment");
- // The "what would you like to do" ask moved to the opening card; the
- // greeting only points at it.
- expect(greeting).toContain("Pick how you'd like to start");
- });
-
- it("drops the name gracefully when no agent name is set", async () => {
- const greeting = await renderOnboardingGreeting({
- agentName: null,
- organizationName: "Acme",
- });
-
- expect(greeting).toContain(
- "Welcome to Paperclip! I'm your first agent teammate.",
- );
- expect(greeting).not.toContain("{{agentName}}");
- });
-
- it("trims whitespace/blank names to the no-name phrasing", async () => {
- const greeting = await renderOnboardingGreeting({ agentName: " " });
-
- expect(greeting).toContain("I'm your first agent teammate.");
- });
-});
diff --git a/tests/runner-e2e/PRODUCT-JOURNEYS.md b/tests/runner-e2e/PRODUCT-JOURNEYS.md
index 6eec3cd43b6..30858434c29 100644
--- a/tests/runner-e2e/PRODUCT-JOURNEYS.md
+++ b/tests/runner-e2e/PRODUCT-JOURNEYS.md
@@ -557,3 +557,17 @@ retains the five allowlisted task observations. The adjacent
Valid, wrong and missing evidence
controls calibrate the independent oracle. Registration and local checks do not
claim a Cloud staging pass or admission to a daily plan.
+
+
+Agent task journeys keep observing an exact native-session retry when the API
+reports a retryable failure, agent-owned recovery, remaining attempts and a retry
+time inside the original campaign deadline. Older projections can omit the
+optional successor field when there is no successor. The same run must later
+succeed; the temporary failed state never counts as completion. Terminal,
+unbound, exhausted and out-of-deadline failures still fail immediately. The
+original run limit, budgets, deadline and artifact checks stay in effect.
+
+The recovery wait gates the shared task snapshot before it reaches any journey
+consumer. Plan revision, Plan approval and protected-action decisions cannot use
+a pending card while its producing run is still recovering. A recovery that
+outlives the original campaign deadline fails without making a decision.
diff --git a/tests/runner-e2e/product-journeys/agent-flows.ts b/tests/runner-e2e/product-journeys/agent-flows.ts
index c1883704e67..48487f4b78c 100644
--- a/tests/runner-e2e/product-journeys/agent-flows.ts
+++ b/tests/runner-e2e/product-journeys/agent-flows.ts
@@ -19,6 +19,8 @@ import { createTaskThroughUi, submitTaskReply } from "../user-actions.js";
import { agentJourneyRuns } from "./catalog.js";
import { JourneyError, type JourneyContext, type JourneyEvidence, type TargetSession } from "./types.js";
+import { isPendingNativeRecovery } from "./workspace-deferral.js";
+
type Row = Record;
type AgentJourney = Exclude;
interface TaskState { currentIssue: Row & { id: string; status: string }; taskRuns: Array; comments: Row[]; interactions: Array; attachments: StoryDelivery[] }
interface Options { deadlineAt: number; directory: string; capture(id: string, label: string, file: string): Promise }
-const active = (run: Row) => ["queued", "running"].includes(run.status);
+const ACTIVE_RUN_STATUSES = ["queued", "running"];
+const SETTLED_RUN_STATUSES = ["succeeded", "cancelled"];
+const active = (run: Row) => ACTIVE_RUN_STATUSES.includes(run.status);
+const settledRun = (run: Row) => SETTLED_RUN_STATUSES.includes(run.status);
/** These fixture replies are plain text. The rich editor escapes underscores in
* its persisted Markdown; compare the intended text while retaining exact count
@@ -59,14 +64,15 @@ export function startedTaskRuns(state: Pick) {
return state.taskRuns.filter(run => !retiredBeforeProviderStart(run));
}
-/** The task is done after exactly `count` started runs, with nothing active or pending. */
+/** The task is done after exactly `count` started runs, and every run finished as succeeded or cancelled:
+ * an active run, or a failed run still waiting for its scheduled same-run retry, is not settled. */
export function agentTaskSettled(state: TaskState, count: number) {
- return state.currentIssue.status === "done" && startedTaskRuns(state).length === count && state.taskRuns.every(run => !active(run))
+ return state.currentIssue.status === "done" && startedTaskRuns(state).length === count && state.taskRuns.every(settledRun)
&& state.interactions.every(row => row.status !== "pending");
}
/** Owned-task observations only: other work in a persistent QA company cannot affect this grade. */
-export function validateAgentTaskState(context: JourneyContext, issueId: string, state: TaskState, maxRuns: number, allowedCancelled: string[] = []) {
+export function validateAgentTaskState(context: JourneyContext, issueId: string, state: TaskState, maxRuns: number, allowedCancelled: string[] = [], deadlineAt?: number) {
const agent = context.agent!;
if (state.currentIssue.id !== issueId || state.currentIssue.companyId !== context.company.id
|| state.currentIssue.assigneeAgentId !== agent.id || state.taskRuns.length > maxRuns) throw new JourneyError("failed", "agent_task_binding_mismatch");
@@ -78,7 +84,10 @@ export function validateAgentTaskState(context: JourneyContext, issueId: string,
if (retiredBeforeProviderStart(run)) continue;
if (!active(run) && (run.runtimeMode !== "native" || run.contextSnapshot?.paperclipEnvironment?.id !== context.environmentId
|| provider?.kind !== agent.provider || provider?.model !== agent.model)) throw new JourneyError("failed", "agent_run_binding_mismatch");
- if (!["queued", "running", "succeeded"].includes(run.status) && !(run.status === "cancelled" && allowedCancelled.includes(run.id))) throw new JourneyError("failed", "agent_run_failed");
+ // A projected exact-session retry is still work in progress. Keep observing
+ // the same run under the original campaign deadline and run limit.
+ if (deadlineAt !== undefined && isPendingNativeRecovery(run, deadlineAt)) continue;
+ if (!active(run) && run.status !== "succeeded" && !(run.status === "cancelled" && allowedCancelled.includes(run.id))) throw new JourneyError("failed", "agent_run_failed");
}
}
@@ -114,7 +123,7 @@ export async function runAgentJourney(id: AgentJourney, context: JourneyContext,
await session.own({ kind: "issue", name: title, id: created.issueId, journeyId: id });
return context.api.get(`/api/issues/${created.issueId}`);
};
- const read = async (issue: Row): Promise => {
+ const read = async (issue: Row): Promise => waitFor(options.deadlineAt, async () => {
const route = `/api/issues/${issue.id}`;
const [currentIssue, summaries, comments, interactions, attachments] = await Promise.all([
context.api.get(route), context.api.get(`${route}/runs`), context.api.get(`${route}/comments?order=asc`),
@@ -124,9 +133,11 @@ export async function runAgentJourney(id: AgentJourney, context: JourneyContext,
const taskRuns = await Promise.all(summaries.map(summary => context.api.get(`/api/heartbeat-runs/${summary.runId}`)));
const state = { currentIssue, taskRuns, comments, interactions, attachments };
await retain(`${issue.id}-latest.json`, state);
- validateAgentTaskState(context, issue.id, state, maxRuns, cancelled);
+ validateAgentTaskState(context, issue.id, state, maxRuns, cancelled, options.deadlineAt);
return state;
- };
+ // No consumer may act on a card, reply or artifact produced by an unsettled
+ // retry. Gate the shared read so Plan and protected-action waits stay safe too.
+ }, state => !state.taskRuns.some(run => isPendingNativeRecovery(run, options.deadlineAt)), "agent_recovery_not_completed");
const settled = (issue: Row, count: number) => waitFor(options.deadlineAt, () => read(issue), state =>
agentTaskSettled(state, count), "agent_task_not_completed");
const finalReply = async (issue: Row, state: TaskState, marker?: string) => {
diff --git a/tests/runner-e2e/product-journeys/agent-recovery-decisions.test.ts b/tests/runner-e2e/product-journeys/agent-recovery-decisions.test.ts
new file mode 100644
index 00000000000..205aed74ada
--- /dev/null
+++ b/tests/runner-e2e/product-journeys/agent-recovery-decisions.test.ts
@@ -0,0 +1,96 @@
+import { mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, expect, it, vi } from "vitest";
+import { runAgentJourney } from "./agent-flows.js";
+import { runnerTasks } from "../catalog.js";
+import { createTaskThroughUi } from "../user-actions.js";
+import { decideProtectedActionThroughUi } from "../protected-action-flow.js";
+import type { JourneyContext, JourneyEvidence, TargetSession } from "./types.js";
+
+vi.mock("../user-actions.js", async importOriginal => ({ ...await importOriginal(), createTaskThroughUi: vi.fn() }));
+vi.mock("../protected-action-flow.js", async importOriginal => ({ ...await importOriginal(), decideProtectedActionThroughUi: vi.fn() }));
+vi.mock("@playwright/test", () => ({ expect: () => ({ toBeVisible: async () => {}, toHaveAttribute: async () => {} }) }));
+type Row = Record;
+const directories: string[] = [];
+afterEach(async () => {
+ vi.clearAllMocks();
+ await Promise.all(directories.splice(0).map(directory => rm(directory, { recursive: true, force: true })));
+});
+
+async function fixture(journey: "plan-revise-accept" | "protected-actions", neverRecovers = false) {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "agent-recovery-decision-")); directories.push(directory);
+ const campaign = "journey-fixture", deadlineAt = Date.now() + (neverRecovers ? 1_500 : 15_000);
+ const markers = runnerTasks.find(row => row.id === "plan-revise-accept")!.buildPlanMarkers!(campaign.replaceAll("-", "_"));
+ const now = Date.now();
+ let stage = 1, rejects = 0;
+ const reads = new Map(), decisions: number[] = [];
+ const stop = new Error("stop-after-proven-decision");
+ const issue = { id: "task", identifier: "QA-1", companyId: "company", assigneeAgentId: "agent", status: "in_progress" };
+ const recovering = () => neverRecovers || (reads.get(stage) ?? 0) < 3;
+ const pending = () => ({ id: `card-${stage}`, status: "pending", kind: "request_confirmation",
+ payload: { target: { type: "issue_document", key: "plan", revisionId: `revision-${stage}` } } });
+ const run = (n: number) => ({ id: `run-${n}`, issueId: "task", nativeIssueId: "task", companyId: "company", agentId: "agent",
+ runtimeMode: "native", status: n === stage && recovering() ? "failed" : "succeeded",
+ nativePhase: n === stage && recovering() ? "retryable_failure" : "committed", errorCode: "native_session_interrupted",
+ finishedAt: new Date(now - 1_000).toISOString(), contextSnapshot: { issueId: "task", paperclipEnvironment: { id: "environment" } },
+ runnerProfileJson: { nativeExecutionInput: { provider: { kind: "opencode", model: "model" } } },
+ execution: { phase: "retry_scheduled", cause: "native_session_interrupted", attempt: 1, maxAttempts: 3,
+ recoveryOwner: "agent", retryAt: new Date(now + 1_000).toISOString() } });
+ const api = { origin: "https://qa.example.test", get: vi.fn(async (route: string) => {
+ if (route === "/api/issues/task") return { ...issue };
+ if (route === "/api/issues/task/runs") return Array.from({ length: stage }, (_, i) => ({ runId: `run-${i + 1}` }));
+ const match = /^\/api\/heartbeat-runs\/run-(\d+)$/.exec(route);
+ if (match) {
+ const n = Number(match[1]);
+ if (n === stage) reads.set(stage, (reads.get(stage) ?? 0) + 1);
+ return run(n);
+ }
+ if (route === "/api/issues/task/interactions") return [pending()];
+ if (route === "/api/issues/task/comments?order=asc" || route === "/api/issues/task/attachments") return [];
+ if (route === "/api/tool-connections/service") return { id: "service", enabled: true };
+ if (route === "/api/issues/task/documents/plan") {
+ expect(recovering(), "must not read the decision's Plan while its producing turn recovers").toBe(false);
+ return { id: "plan", key: "plan", latestRevisionId: `revision-${stage}`, latestRevisionNumber: stage,
+ body: stage === 1 ? `1. ${markers.draft}\n2. Check it` : `1. ${markers.revised}\n2. Check it\n3. Finish` };
+ }
+ throw new Error(`Unexpected read ${route}`);
+ }) };
+ const locator: Row = { last() { return this; }, first() { return this; }, getByTestId() { return this; }, locator() { return this; }, fill: async () => {} };
+ const page = { goto: async () => {}, reload: async () => {}, locator: () => locator, getByTestId: () => locator,
+ getByRole: (_role: string, options: { name: string }) => ({ last() { return this; }, click: async () => {
+ expect(recovering(), "a human decision must wait for the producing native turn").toBe(false);
+ if (options.name === "Reject") { if (++rejects === 2) stage = 2; }
+ else { decisions.push(stage); throw stop; }
+ } }) };
+ vi.mocked(createTaskThroughUi).mockResolvedValue({ issueId: "task" } as any);
+ vi.mocked(decideProtectedActionThroughUi).mockImplementation(async () => {
+ expect(recovering(), "protected approval must wait for the producing turn").toBe(false);
+ decisions.push(stage); throw stop;
+ });
+ const context = { api, page, company: { id: "company", issuePrefix: "QA" }, user: { id: "user" }, environmentId: "environment",
+ agent: { id: "agent", name: "QA agent", provider: "opencode", model: "model", runtimeMode: "native" },
+ fixtures: { reviewService: { id: "service", name: "Review", connectionId: "service", invocationCount: () => 0 } } } as unknown as JourneyContext;
+ return { api, reads, decisions, stop, execute: () => runAgentJourney(journey, context, { own: async () => {} } as unknown as TargetSession,
+ campaign, { checks: [] } as unknown as JourneyEvidence, { directory, deadlineAt, capture: async () => {} }) };
+}
+
+it("waits through both draft and revised Plan recovery before requesting changes or approving", async () => {
+ const f = await fixture("plan-revise-accept");
+ await expect(f.execute()).rejects.toBe(f.stop);
+ expect([...f.reads.entries()]).toEqual([[1, 3], [2, 3]]);
+ expect(f.decisions).toEqual([2]);
+});
+it("waits through pending protected-action recovery before making its first decision", async () => {
+ const f = await fixture("protected-actions");
+ await expect(f.execute()).rejects.toBe(f.stop);
+ expect(f.reads.get(1)).toBe(3);
+ expect(f.decisions).toEqual([1]);
+});
+it.each(["plan-revise-accept", "protected-actions"] as const)("does not decide %s when recovery outlives the original deadline", async journey => {
+ const f = await fixture(journey, true);
+ await expect(f.execute()).rejects.toMatchObject({ code: "agent_recovery_not_completed" });
+ expect(f.decisions).toEqual([]);
+ expect(f.api.get.mock.calls.some(([route]) => route.endsWith("/documents/plan"))).toBe(false);
+ expect(decideProtectedActionThroughUi).not.toHaveBeenCalled();
+});
diff --git a/tests/runner-e2e/product-journeys/agent-recovery.test.ts b/tests/runner-e2e/product-journeys/agent-recovery.test.ts
new file mode 100644
index 00000000000..634f3361e13
--- /dev/null
+++ b/tests/runner-e2e/product-journeys/agent-recovery.test.ts
@@ -0,0 +1,75 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { agentTaskSettled, validateAgentTaskState, waitFor } from "./agent-flows.js";
+import type { JourneyContext } from "./types.js";
+
+type Row = Record;
+const context = { company: { id: "company" }, environmentId: "environment",
+ agent: { id: "agent", provider: "opencode", model: "model", runtimeMode: "native" } } as JourneyContext;
+function snapshot() {
+ const now = Date.now();
+ const run: Row & { status: string } = { id: "run", companyId: "company", agentId: "agent", issueId: "task", nativeIssueId: "task",
+ runtimeMode: "native", status: "failed", nativePhase: "retryable_failure", errorCode: "native_session_interrupted",
+ finishedAt: new Date(now - 1_000).toISOString(), contextSnapshot: { issueId: "task", paperclipEnvironment: { id: "environment" } },
+ runnerProfileJson: { nativeExecutionInput: { provider: { kind: "opencode", model: "model" } } },
+ execution: { phase: "retry_scheduled", cause: "native_session_interrupted", attempt: 1, maxAttempts: 3,
+ recoveryOwner: "agent", retryAt: new Date(now + 1_000).toISOString() } };
+ return { currentIssue: { id: "task", companyId: "company", assigneeAgentId: "agent", status: "in_progress" },
+ taskRuns: [run], comments: [], interactions: [], attachments: [] };
+}
+afterEach(() => vi.useRealTimers());
+
+it("observes a scheduled exact-run recovery through success within the original deadline and run limit", async () => {
+ vi.useFakeTimers();
+ const state = snapshot(), deadline = Date.now() + 5_000;
+ const pending = waitFor(deadline, async () => {
+ validateAgentTaskState(context, "task", state, 1, [], deadline);
+ return state;
+ }, value => agentTaskSettled(value, 1), "agent_task_not_completed");
+ const assertion = expect(pending).resolves.toBe(state);
+ await vi.advanceTimersByTimeAsync(1_000);
+ state.taskRuns[0]!.status = "succeeded";
+ state.taskRuns[0]!.nativePhase = "committed";
+ state.currentIssue.status = "done";
+ await vi.advanceTimersByTimeAsync(1_000);
+ await assertion;
+ expect(state.taskRuns.map(run => run.id)).toEqual(["run"]);
+});
+
+it.each([
+ ["terminal phase", (run: Row) => { run.nativePhase = "terminal_failure"; }],
+ ["terminal cause", (run: Row) => { run.errorCode = run.execution.cause = "native_provider_terminal_failed"; }],
+ ["no retry owner", (run: Row) => { run.execution.recoveryOwner = "board"; }],
+ ["exhausted retry", (run: Row) => { run.execution.attempt = 3; }],
+ ["late retry", (run: Row) => { run.execution.retryAt = new Date(Date.now() + 6_000).toISOString(); }],
+ ["different successor", (run: Row) => { run.execution.successorRunId = "other-run"; }],
+ ["foreign model", (run: Row) => { run.runnerProfileJson.nativeExecutionInput.provider.model = "other"; }],
+ ["foreign task", (run: Row) => { run.nativeIssueId = "other"; }],
+] as const)("keeps %s fatal", (_label, change) => {
+ const state = snapshot(); change(state.taskRuns[0]!);
+ expect(() => validateAgentTaskState(context, "task", state, 1, [], Date.now() + 5_000)).toThrow();
+});
+
+it("never counts a pending recovery as settled even if the task snapshot says done", () => {
+ const state = snapshot(); state.currentIssue.status = "done";
+ expect(agentTaskSettled(state, 1)).toBe(false);
+});
+
+it("keeps the original campaign deadline when recovery never completes", async () => {
+ vi.useFakeTimers();
+ const state = snapshot(), deadline = Date.now() + 2_000;
+ const pending = waitFor(deadline, async () => {
+ validateAgentTaskState(context, "task", state, 1, [], deadline);
+ return state;
+ }, value => agentTaskSettled(value, 1), "agent_task_not_completed");
+ const assertion = expect(pending).rejects.toMatchObject({ code: "agent_task_not_completed" });
+ await vi.advanceTimersByTimeAsync(2_000);
+ await assertion;
+});
+
+
+it.each([null, undefined])("accepts an explicitly scheduled same-run retry with successor %s", successor => {
+ const state = snapshot(); state.taskRuns[0]!.execution.successorRunId = successor;
+ expect(() => validateAgentTaskState(context, "task", state, 1, [], Date.now() + 5_000)).not.toThrow();
+ expect(() => validateAgentTaskState(context, "task", state, 1)).toThrow("agent_run_failed");
+ expect(() => validateAgentTaskState(context, "task", state, 0, [], Date.now() + 5_000)).toThrow("agent_task_binding_mismatch");
+});
diff --git a/tests/runner-e2e/product-journeys/onboarding-first-task.test.ts b/tests/runner-e2e/product-journeys/onboarding-first-task.test.ts
index 15b9f30007e..a5917bb3f21 100644
--- a/tests/runner-e2e/product-journeys/onboarding-first-task.test.ts
+++ b/tests/runner-e2e/product-journeys/onboarding-first-task.test.ts
@@ -292,7 +292,7 @@ describe("Cloud canonical onboarding first task", () => {
await expect(onboardingFirstTask(f.input)).resolves.toMatchObject({ artifact: { originatingRunId: "child-run" } });
expect(connectionDelay).toHaveBeenCalledOnce();
});
- it.each(["active", "native-recovery", "workspace-replacement"])("waits past an old child blocker while %s remains pending", async mode => {
+ it.each(["active", "native-recovery", "native-recovery-without-successor-field", "workspace-replacement"])("waits past an old child blocker while %s remains pending", async mode => {
let waiting = true;
const now = Date.now();
vi.mocked(connectionDelay).mockImplementation(async () => { waiting = false; });
@@ -306,6 +306,10 @@ describe("Cloud canonical onboarding first task", () => {
withBoardBlockedChild(state);
if (mode === "active") Object.assign(state.runs[1]!, { status: "running", finishedAt: null });
if (mode === "native-recovery") withPendingNativeRecovery(state.runs[1]!, now - 1000, now + 30_000);
+ if (mode === "native-recovery-without-successor-field") {
+ withPendingNativeRecovery(state.runs[1]!, now - 1000, now + 30_000);
+ delete state.runs[1]!.execution.successorRunId;
+ }
} });
await expect(onboardingFirstTask(f.input)).resolves.toMatchObject({ artifact: { originatingRunId: "child-run" } });
expect(connectionDelay).toHaveBeenCalledOnce();
@@ -448,7 +452,6 @@ describe("Cloud canonical onboarding first task", () => {
["noninteger attempt", (run: Row) => { run.execution.attempt = 1.5; }],
["unexpected ceiling", (run: Row) => { run.execution.maxAttempts = 4; }],
["different successor", (run: Row) => { run.execution.successorRunId = "other-run"; }],
- ["missing successor state", (run: Row) => { delete run.execution.successorRunId; }],
] as const)("keeps a failed native run fatal with %s", async (_label, change) => {
const now = Date.now();
vi.spyOn(Date, "now").mockReturnValue(now);
diff --git a/tests/runner-e2e/product-journeys/workspace-deferral.ts b/tests/runner-e2e/product-journeys/workspace-deferral.ts
index 9146cb87e17..ea925d4fa9e 100644
--- a/tests/runner-e2e/product-journeys/workspace-deferral.ts
+++ b/tests/runner-e2e/product-journeys/workspace-deferral.ts
@@ -27,6 +27,8 @@ export function isPendingNativeRecovery(run: RecordValue, deadlineAt: number): b
const execution = object(run.execution);
const finishedAt = typeof run.finishedAt === "string" ? Date.parse(run.finishedAt) : NaN;
const retryAt = typeof execution.retryAt === "string" ? Date.parse(execution.retryAt) : NaN;
+ // Older deployed projections omit the optional successor field when there
+ // is no successor. Both forms preserve the exact same-run retry contract.
return run.runtimeMode === "native" && run.status === "failed" && run.nativePhase === "retryable_failure" &&
typeof run.errorCode === "string" && run.errorCode.trim().length > 0 && execution.cause === run.errorCode &&
!nativeRecoveryTerminalCauses.has(run.errorCode) &&
@@ -34,7 +36,7 @@ export function isPendingNativeRecovery(run: RecordValue, deadlineAt: number): b
(run.issueId == null || run.issueId === run.nativeIssueId) &&
(execution.phase === "retry_scheduled" || execution.phase === "reconnecting") && execution.recoveryOwner === "agent" &&
Number.isInteger(execution.attempt) && Number(execution.attempt) >= 1 &&
- execution.maxAttempts === 3 && Number(execution.attempt) < execution.maxAttempts && execution.successorRunId === null &&
+ execution.maxAttempts === 3 && Number(execution.attempt) < execution.maxAttempts && execution.successorRunId == null &&
Number.isFinite(finishedAt) && Number.isFinite(retryAt) && Number.isFinite(deadlineAt) &&
retryAt > finishedAt && retryAt <= deadlineAt;
}
diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json
index 1cfd8f7404f..8e91f9b30bf 100644
--- a/tests/runner-e2e/source-sdk-public-inputs.json
+++ b/tests/runner-e2e/source-sdk-public-inputs.json
@@ -225,7 +225,6 @@
"packages/shared/src/config-schema.ts": "f9c8d41cb09fbc51c3e7a038089b54376cc9150c",
"packages/shared/src/connection-instructions.test.ts": "5095a9eeaa378b8d881feafa699c1705f207717f",
"packages/shared/src/connection-instructions.ts": "61b3e102838bd8bcab20eb9d0497a182f86eaac0",
- "packages/shared/src/connection-intent-guidance.test.ts": "ae89f72dff415181d07c29a75d005c229d5c61b8",
"packages/shared/src/connection-intent-guidance.ts": "c121d7e31f3c44c7b0879db3929c23be20ef7987",
"packages/shared/src/connection-routing.test.ts": "95f6d30b790a2ef69f409fb72e4ba83256d7771e",
"packages/shared/src/connection-routing.ts": "6c506acd09b75d4f70ecde6cc5b652a244a7eb8a",
@@ -390,7 +389,6 @@
"packages/shared/src/telemetry/generated/paperclip-telemetry.ts": "c1a5e4e7679d9a4a1d2e420a1c65be608874b518",
"packages/shared/src/telemetry/index.ts": "6e609229bc9e37feb231fb13d8bc39fc3697d35f",
"packages/shared/src/telemetry/product-events.test.ts": "d3182c7e18fbe9c2915497fc1e2048fb2a250a04",
- "packages/shared/src/telemetry/readme-contract.test.ts": "eec9d4511ddc3085a9af1a2dab6bf8487e49dfd7",
"packages/shared/src/telemetry/retention.test.ts": "9d54db1371bf20f22b8d2f8373f84433107a7408",
"packages/shared/src/telemetry/retention.ts": "838957cb8f9812d7d75680fbf42173d425d12006",
"packages/shared/src/telemetry/server-started-event.test.ts": "3d0e0e2289badb41c92ba0d69e3668d00b3b5fdb",
@@ -490,7 +488,7 @@
"packages/shared/src/validators/asset.ts": "93b9a747b0e7a2bce216db4ac3ab82ee42eb5cc3",
"packages/shared/src/validators/attention.ts": "137f6ca363e2c9b81961de5621c69a87a8c3d461",
"packages/shared/src/validators/budget.ts": "76ad91791c89d5be0f64cb23dd5587c493a7ead5",
- "packages/shared/src/validators/chat-channels.test.ts": "eb157fcb00128a62d381e3e06630ed38c9a80314",
+ "packages/shared/src/validators/chat-channels.test.ts": "4f58b4abfbc76bd29fbe3ee321fa664c9eb0a86c",
"packages/shared/src/validators/chat-channels.ts": "9d0adf5ce89655d22071061d5e085d2ed84625d6",
"packages/shared/src/validators/chat-github.ts": "828c560fdad771389928f18c01e1eb14d4caeed5",
"packages/shared/src/validators/claude-setup-token-session.test.ts": "9eca823f24a9f85a20bddc6e61867b73362017e0",
diff --git a/tests/speko-voice-proof/cleanup.test.mjs b/tests/speko-voice-proof/cleanup.test.mjs
deleted file mode 100644
index 24345ca2901..00000000000
--- a/tests/speko-voice-proof/cleanup.test.mjs
+++ /dev/null
@@ -1,149 +0,0 @@
-import test from 'node:test';
-import assert from 'node:assert/strict';
-import { createCleanup, createAudioSave, createReportSaver } from './cleanup.mjs';
-
-test('failed hangup preserves evidence and retries only the unconfirmed provider operation', async () => {
- let locals = 0, ends = 0;
- const failures = [], reports = [];
- const cleanup = createCleanup({
- local: async () => { locals++; },
- provider: async () => { if (++ends === 1) throw new Error('private failure'); },
- report: async () => { reports.push([...failures]); },
- failed: (operation) => failures.push(operation),
- });
- assert.equal(await cleanup.end(), false);
- assert.equal(cleanup.complete, false);
- assert.deepEqual(reports, [['session.end']]);
- assert.equal(await cleanup.end(), true);
- assert.equal(cleanup.complete, true);
- assert.equal(locals, 1);
- assert.equal(ends, 2);
- assert.equal(reports.length, 2);
-});
-
-test('media failures do not prevent hangup or final evidence; concurrent cleanup coalesces', async () => {
- let ends = 0, reports = 0;
- const failures = [];
- const cleanup = createCleanup({
- local: async (attempt) => {
- await attempt('sdk.end', async () => { throw new Error('sdk failure'); });
- await attempt('tracks.stop', async () => { throw new Error('media failure'); });
- },
- provider: async () => { ends++; },
- report: async () => { reports++; },
- failed: (operation) => failures.push(operation),
- });
- assert.deepEqual(await Promise.all([cleanup.end(), cleanup.end()]), [false, false]);
- assert.equal(ends, 1);
- assert.equal(reports, 1);
- assert.deepEqual(failures, ['sdk.end', 'tracks.stop']);
-});
-
-test('failed report can be retried without redialing or repeating a confirmed hangup', async () => {
- let ends = 0, reports = 0;
- const cleanup = createCleanup({ local: async () => {}, provider: async () => { ends++; },
- report: async () => { if (++reports === 1) throw new Error('disk failure'); }, failed: () => {} });
- assert.equal(await cleanup.end(), false);
- assert.equal(cleanup.complete, false);
- assert.equal(await cleanup.end(), true);
- assert.equal(ends, 1);
- assert.equal(reports, 2);
-});
-
-
-test('retries failed local operations and keeps End available until all media cleanup succeeds', async () => {
- let tracks = 0, sdk = 0, ends = 0, reports = 0;
- const cleanup = createCleanup({
- local: async attempt => {
- await attempt('tracks.stop', async () => { tracks++; });
- await attempt('sdk.end', async () => { if (++sdk === 1) throw new Error('temporary failure'); });
- },
- provider: async () => { ends++; }, report: async () => { reports++; }, failed: () => {},
- });
- assert.equal(await cleanup.end(), false);
- assert.equal(cleanup.complete, false);
- assert.equal(await cleanup.end(), true);
- assert.equal(cleanup.complete, true);
- assert.deepEqual({tracks, sdk, ends, reports}, {tracks: 1, sdk: 2, ends: 1, reports: 2});
-});
-
-
-test('failed audio upload is retryable with the same finalized recording and blocks cleanup completion', async () => {
- const blob = new Blob(['synthetic-audio']);
- let stops = 0, uploads = 0, ends = 0;
- const evidence = createAudioSave({stop: async () => { stops++; return blob; }, upload: async value => {
- assert.equal(value, blob); if (++uploads === 1) throw new Error('HTTP failure');
- }});
- const failures = [];
- const cleanup = createCleanup({local: async attempt => { await attempt('recording.save', () => evidence.save()); },
- provider: async () => { ends++; }, report: async () => {}, failed: operation => failures.push(operation)});
- assert.equal(await cleanup.end(), false);
- assert.equal(cleanup.complete, false);
- assert.deepEqual(failures, ['recording.save']);
- assert.equal(await cleanup.end(), true);
- assert.equal(cleanup.complete, true);
- assert.deepEqual({stops, uploads, ends}, {stops: 1, uploads: 2, ends: 1});
-});
-
-test('audio evidence waits for final recording data before upload and coalesces concurrent saves', async () => {
- let finish, uploads = 0;
- const stopped = new Promise(resolve => { finish = resolve; });
- const evidence = createAudioSave({stop: () => stopped, upload: async () => { uploads++; }});
- const first = evidence.save(), second = evidence.save();
- assert.equal(first, second);
- await Promise.resolve(); assert.equal(uploads, 0);
- finish(new Blob(['synthetic-audio']));
- await first; await evidence.save();
- assert.equal(uploads, 1);
-});
-
-test('final report waits for an older write and preserves its cleanup failures', async () => {
- let release;
- const writes = [], stored = [];
- const save = createReportSaver(async report => {
- writes.push(report);
- if (writes.length === 1) await new Promise(resolve => { release = resolve; });
- stored.push(report);
- });
- const earlier = {events: ['working'], cleanupFailures: []};
- const oldSave = save(earlier);
- await Promise.resolve();
- earlier.events.push('mutated after enqueue');
- const finalSave = save({events: ['ended'], cleanupFailures: ['session.end']});
- await Promise.resolve();
- assert.equal(writes.length, 1);
- release();
- await Promise.all([oldSave, finalSave]);
- assert.deepEqual(stored, [{events: ['working'], cleanupFailures: []}, {events: ['ended'], cleanupFailures: ['session.end']}]);
-});
-
-test('a failed periodic write does not prevent storing final cleanup evidence', async () => {
- let writes = 0;
- const save = createReportSaver(async report => { if (++writes === 1) throw new Error('failed'); return report; });
- await assert.rejects(save({events: []}));
- assert.deepEqual(await save({events: ['ended']}), {events: ['ended']});
-});
-
-
-test('stalled periodic transport is aborted and final evidence advances behind its late server write', async () => {
- let release, calls = 0;
- const stored = [];
- const serverSave = createReportSaver(async report => {
- if (!stored.length && report.phase === 'periodic') await new Promise(resolve => { release = resolve; });
- stored.push(report);
- return report;
- });
- const clientSave = createReportSaver((report, signal) => {
- const response = serverSave(report);
- if (++calls !== 1) { release(); return response; }
- return new Promise((resolve, reject) => {
- signal.addEventListener('abort', () => reject(signal.reason), {once: true});
- response.then(resolve, reject);
- });
- }, {timeoutMs: 20});
- const first = clientSave({phase: 'periodic'});
- const final = clientSave({phase: 'ended', cleanupFailures: ['session.end']});
- await assert.rejects(first, /Report save timed out/);
- assert.deepEqual(await final, {phase: 'ended', cleanupFailures: ['session.end']});
- assert.deepEqual(stored, [{phase: 'periodic'}, {phase: 'ended', cleanupFailures: ['session.end']}]);
-});
diff --git a/tests/speko-voice-proof/media-failure.test.mjs b/tests/speko-voice-proof/media-failure.test.mjs
deleted file mode 100644
index 20b122a0073..00000000000
--- a/tests/speko-voice-proof/media-failure.test.mjs
+++ /dev/null
@@ -1,27 +0,0 @@
-import test from 'node:test';
-import assert from 'node:assert/strict';
-import {createMediaFailure} from './media-failure.mjs';
-
-for (const operation of ['captureFrame', 'waitForPlayout']) {
- test(`${operation} failure releases pending input and runs hangup and evidence cleanup`, async () => {
- let fail, hungUp = false, reportSaved = false, observed;
- const media = createMediaFailure(error => { observed = error; });
- const sourceFailure = new Error(`${operation} failed`);
- const source = {captureFrame: async () => {}, waitForPlayout: async () => {}};
- source[operation] = () => new Promise((_, reject) => { fail = reject; });
- const pump = media.observe((async () => { await source.captureFrame(); await source.waitForPlayout(); })());
- const input = media.waitFor(() => new Promise(() => {}));
- while (!fail) await Promise.resolve();
- fail(sourceFailure);
- let failure;
- try { await input; }
- catch (error) { failure = error; }
- finally { hungUp = true; reportSaved = true; }
- await pump;
- assert.equal(failure, sourceFailure);
- assert.equal(observed, sourceFailure);
- assert.equal(media.error, sourceFailure);
- assert.equal(hungUp && reportSaved, true);
- await assert.rejects(media.waitFor(() => new Promise(() => {})), sourceFailure);
- });
-}
diff --git a/tests/speko-voice-proof/proof.test.mjs b/tests/speko-voice-proof/proof.test.mjs
deleted file mode 100644
index df95544573f..00000000000
--- a/tests/speko-voice-proof/proof.test.mjs
+++ /dev/null
@@ -1,124 +0,0 @@
-import assert from "node:assert/strict";
-import { randomBytes } from "node:crypto";
-import { once } from "node:events";
-import test from "node:test";
-import { Webhook } from "standardwebhooks";
-import { BODY_LIMIT, createProof, createProofServer, TOOL_PATH, toolDefinitions, WAIT_MS } from "./proof.mjs";
-
-const secret = () => `whsec_${randomBytes(32).toString("base64")}`;
-function fixture(options = {}) {
- const signingSecret = secret();
- const proof = createProof({ signingSecret, ...options });
- const signer = new Webhook(signingSecret);
- let sequence = 0;
- function request(tool, args, { session = "session_1", call = `call_${++sequence}`, timestamp = new Date(), signing = signer } = {}) {
- const body = JSON.stringify({ tool, args, session_id: session, tool_call_id: call, idempotency_key: `${session}:${call}` });
- const id = `${session}:${call}`;
- const headers = { "webhook-id": id, "webhook-timestamp": String(Math.floor(timestamp.getTime() / 1000)), "webhook-signature": signing.sign(id, timestamp, body) };
- return { body, headers, send: () => proof.handle(body, headers) };
- }
- return { proof, request };
-}
-
-test("requires HTTPS and keeps each fetch below the four-second provider limit", () => {
- for (const origin of ["http://example.com", "https://user:secret@example.com", "https://example.com/path", "https://example.com?key=secret"]) {
- assert.throws(() => toolDefinitions(origin));
- }
- const tools = toolDefinitions("https://example.com");
- assert.equal(tools.length, 2);
- assert.ok(tools.every(({ source }) => source.timeoutMs < 4000 && source.timeoutMs > WAIT_MS && !source.secret));
-});
-
-test("rejects missing, wrong, stale, future and tampered signatures", async () => {
- const { proof, request } = fixture();
- const valid = request("submit_request", { text: "synthetic request" });
- assert.equal((await proof.handle(valid.body, {})).status, 401);
- assert.equal((await proof.handle(valid.body + " ", valid.headers)).status, 401);
- for (const options of [{ signing: new Webhook(secret()) }, { timestamp: new Date(Date.now() - 360_000) }, { timestamp: new Date(Date.now() + 360_000) }]) {
- assert.equal((await request("submit_request", { text: "test" }, options).send()).status, 401);
- }
- assert.equal(proof.evidence().acceptedRequests, 0);
-});
-
-test("deduplicates concurrent retries and rejects changed arguments and session substitution", async () => {
- const { proof, request } = fixture();
- const original = request("submit_request", { text: "private phrase" }, { call: "same" });
- const responses = await Promise.all([original.send(), original.send(), original.send()]);
- assert.ok(responses.every((response) => response.body.requestCount === 1));
- assert.equal((await request("submit_request", { text: "changed" }, { call: "same" }).send()).status, 409);
- assert.equal((await request("submit_request", { text: "test" }, { session: "other" }).send()).status, 403);
- assert.equal(proof.evidence().acceptedRequests, 1);
- assert.ok(!JSON.stringify(proof.evidence()).includes("private phrase"));
-});
-
-test("waits 60 seconds, admits follow-ups to one job and distinguishes result retrieval from speech", async () => {
- let clock = 0;
- const waits = [];
- const { proof, request } = fixture({ now: () => clock, wait: async (duration) => { waits.push(duration); clock += duration; } });
- assert.equal((await request("get_updates", { cursor: 0 }).send()).status, 409);
- assert.equal((await request("submit_request", { text: "start" }).send()).body.status, "pending");
- assert.equal((await request("get_updates", { cursor: 1 }).send()).status, 400);
- let response;
- for (let i = 0; i < 24; i++) {
- if (i === 6) assert.equal((await request("submit_request", { text: "followup" }).send()).body.requestCount, 2);
- response = await request("get_updates", { cursor: 0 }).send();
- if (i < 23) assert.equal(response.body.status, "pending");
- }
- assert.equal(clock, 60_000);
- assert.ok(waits.every((duration) => duration <= 2500));
- assert.equal(response.body.status, "completed");
- assert.match(response.body.updates[0].text, /Verification number \d{4}\. Follow-up count 1/);
- assert.deepEqual((await request("get_updates", { cursor: 1 }).send()).body.updates, []);
- assert.equal(proof.evidence().liveQualification, "not_established");
- assert.equal(proof.evidence().resultReturned, true);
-});
-
-test("close during a bounded wait prevents further result delivery", async () => {
- let release;
- const { proof, request } = fixture({ wait: () => new Promise((resolve) => { release = resolve; }) });
- await request("submit_request", { text: "start" }).send();
- const polling = request("get_updates", { cursor: 0 }).send();
- await Promise.resolve();
- proof.close();
- release();
- assert.equal((await polling).status, 410);
- assert.equal((await request("submit_request", { text: "late" }).send()).status, 410);
-});
-
-test("expires the single-run receiver and caps authenticated deliveries", async () => {
- let clock = 0;
- const { proof, request } = fixture({ now: () => clock });
- for (let i = 0; i < 500; i++) {
- assert.equal((await request("submit_request", { text: "synthetic" }).send()).status, 200);
- }
- assert.equal((await request("submit_request", { text: "over limit" }).send()).status, 429);
- clock = 15 * 60_000;
- assert.equal((await request("submit_request", { text: "expired" }).send()).status, 410);
- assert.equal(proof.evidence().acceptedRequests, 500);
-});
-
-test("rejects invalid args and bodies before accepting work", async () => {
- const { proof, request } = fixture();
- for (const [tool, args] of [["unknown", {}], ["submit_request", { text: "" }], ["submit_request", { text: "ok", authority: "admin" }], ["get_updates", { cursor: -1 }], ["get_updates", { cursor: 0.5 }]]) {
- assert.equal((await request(tool, args).send()).status, 400);
- }
- assert.equal((await proof.handle("x".repeat(BODY_LIMIT + 1), {})).status, 413);
- assert.equal(proof.evidence().acceptedRequests, 0);
-});
-
-test("HTTP surface only accepts JSON on the signed tool route", async (t) => {
- const { proof, request } = fixture();
- const server = createProofServer(proof);
- t.after(() => { server.closeAllConnections(); server.close(); });
- server.listen(0, "127.0.0.1");
- await once(server, "listening");
- const base = `http://127.0.0.1:${server.address().port}`;
- assert.equal((await fetch(`${base}/health`)).status, 200);
- assert.equal((await fetch(`${base}/api/companies`)).status, 404);
- assert.equal((await fetch(`${base}${TOOL_PATH}`, { method: "POST", body: "{}" })).status, 415);
- const signed = request("submit_request", { text: "start" });
- const response = await fetch(`${base}${TOOL_PATH}`, { method: "POST", headers: { ...signed.headers, "content-type": "application/json" }, body: signed.body });
- assert.equal(response.status, 200);
- assert.equal(response.headers.get("cache-control"), "no-store");
- assert.equal((await response.json()).requestCount, 1);
-});
diff --git a/tests/speko-voice-proof/summarize-run.test.mjs b/tests/speko-voice-proof/summarize-run.test.mjs
deleted file mode 100644
index 00a1232de8d..00000000000
--- a/tests/speko-voice-proof/summarize-run.test.mjs
+++ /dev/null
@@ -1,54 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-import { mkdtemp, readFile, writeFile, rm } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { spawnSync } from "node:child_process";
-
-test("shared reports exclude private content and never promote transport to playback proof", async () => {
- const dir = await mkdtemp(join(tmpdir(), "speko-redaction-"));
- try {
- const input = join(dir, "private.json");
- const output = join(dir, "public.json");
- await writeFile(input, JSON.stringify({
- sessionId: "11111111-1111-4111-8111-111111111111", mode: "text", provider: "openai:gpt-4.1",
- failure: null, audioFrames: 42, transportToken: "never-publish-token",
- syntheticTranscript: [{ text: "never-publish-transcript" }],
- sourceDigests: { "proof.mjs": "a".repeat(64), "media-failure.mjs": "b".repeat(64), accidentalKey: "never-publish-key" },
- proof: { acceptedRequests: 2, resultReturned: true, expectedSyntheticResult: "never-publish-phrase" },
- events: [
- { kind: "request_accepted", elapsedMs: 10, requestCount: 1, text: "never-publish-caller" },
- { kind: "script_failed", elapsedMs: 20, reason: "never-publish-error-detail" },
- { kind: "unknown_future_event", elapsedMs: 30, text: "never-publish-future" },
- ],
- }));
- const script = new URL("./summarize-run.mjs", import.meta.url);
- const run = () => spawnSync(process.execPath, [script.pathname, input, output], { encoding: "utf8" });
- assert.equal(run().status, 0);
- const text = await readFile(output, "utf8");
- assert.equal(text.includes("never-publish"), false);
- const report = JSON.parse(text);
- assert.equal(report.status, "requires_audio_review");
- assert.equal(report.confirmedResultPlayback, false);
- assert.equal(report.resultReturned, true);
- assert.equal(report.events.length, 2);
- assert.deepEqual(report.sourceDigests, { "proof.mjs": "a".repeat(64), "media-failure.mjs": "b".repeat(64) });
- assert.notEqual(run().status, 0, "must refuse to overwrite evidence");
- assert.equal(await readFile(output, "utf8"), text);
- } finally {
- await rm(dir, { recursive: true, force: true });
- }
-});
-
-test("shared reports mark cleanup failures without leaking private diagnostics", async () => {
- const dir = await mkdtemp(join(tmpdir(), "speko-cleanup-redaction-"));
- try {
- const input = join(dir, "private.json"), output = join(dir, "public.json");
- await writeFile(input, JSON.stringify({failure: null, audioFrames: 1, proof: {acceptedRequests: 1, resultReturned: true}, cleanupFailures: [{operation: "source.close", reason: "secret detail"}], events: [{kind: "cleanup_failed", elapsedMs: 25, operation: "private operation"}]}));
- assert.equal(spawnSync(process.execPath, [new URL("./summarize-run.mjs", import.meta.url).pathname, input, output]).status, 0);
- const text = await readFile(output, "utf8"), report = JSON.parse(text);
- assert.equal(report.status, "failed"); assert.equal(report.cleanupFailureCount, 1);
- assert.equal(report.events[0].kind, "cleanup_failed");
- assert.equal(text.includes("secret detail"), false); assert.equal(text.includes("private operation"), false);
- } finally {await rm(dir, {recursive: true, force: true});}
-});
diff --git a/ui/src/components/AccountQuotaPanels.test.tsx b/ui/src/components/AccountQuotaPanels.test.tsx
deleted file mode 100644
index b3b77d33fb1..00000000000
--- a/ui/src/components/AccountQuotaPanels.test.tsx
+++ /dev/null
@@ -1,16 +0,0 @@
-// @vitest-environment jsdom
-import { renderToStaticMarkup } from "react-dom/server";
-import { afterEach, expect, it } from "vitest";
-import { AccountQuotaPanels } from "./AccountQuotaPanels";
-import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils";
-
-afterEach(() => { document.body.innerHTML = ""; });
-
-it("masks the subscription account label in session replay", () => {
- document.body.innerHTML = renderToStaticMarkup();
- expect(replayLeaks("fenwick.oriel@example.test")).toEqual({ rendered: true, recorded: false });
- expect(replayLeaks("Weekly limit")).toEqual({ rendered: true, recorded: true });
-});
diff --git a/ui/src/components/AgentSetupPrompt.test.tsx b/ui/src/components/AgentSetupPrompt.test.tsx
deleted file mode 100644
index 66327160a0a..00000000000
--- a/ui/src/components/AgentSetupPrompt.test.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-// @vitest-environment jsdom
-import { act } from "react";
-import { createRoot, type Root } from "react-dom/client";
-import { afterEach, beforeEach, expect, it, vi } from "vitest";
-import { AgentSetupPrompt } from "./AgentSetupPrompt";
-import { isBlockedFromReplay } from "@/lib/analytics/replay-recording.test-utils";
-
-(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-
-let root: Root;
-let container: HTMLDivElement;
-beforeEach(() => {
- vi.stubGlobal("matchMedia", (query: string) => ({ matches: query.includes("reduce"), media: query, addEventListener: vi.fn(), removeEventListener: vi.fn(), addListener: vi.fn(), removeListener: vi.fn() }));
- Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText: vi.fn(async () => {}) } });
- container = document.createElement("div");
- document.body.append(container);
- root = createRoot(container);
-});
-afterEach(async () => {
- await act(async () => root.unmount());
- container.remove();
- vi.unstubAllGlobals();
- Reflect.deleteProperty(navigator, "clipboard");
-});
-
-it("blocks the setup prompt preview, which carries pairing tokens, from session replay", async () => {
- const prompt = "Run: paperclipai pair --token pcp_pair_8f3kQz2LmWv";
- await act(async () => root.render());
- await act(async () => container.querySelector("button")!.click());
- expect(document.querySelector("pre[aria-label='Setup prompt']")).not.toBeNull();
- expect(isBlockedFromReplay("pcp_pair_8f3kQz2LmWv", document.body)).toBe(true);
-});
diff --git a/ui/src/components/ApprovalPayload.test.tsx b/ui/src/components/ApprovalPayload.test.tsx
deleted file mode 100644
index 95339474730..00000000000
--- a/ui/src/components/ApprovalPayload.test.tsx
+++ /dev/null
@@ -1,212 +0,0 @@
-// @vitest-environment jsdom
-
-import { act } from "react";
-import { createRoot } from "react-dom/client";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import { ApprovalPayloadRenderer, approvalLabel } from "./ApprovalPayload";
-import { ThemeProvider } from "../context/ThemeContext";
-
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
-
-describe("approvalLabel", () => {
- it("uses payload titles for generic board approvals", () => {
- expect(
- approvalLabel("request_board_approval", {
- title: "Reply with an ASCII frog",
- }),
- ).toBe("Board Approval: Reply with an ASCII frog");
- });
-});
-
-describe("ApprovalPayloadRenderer", () => {
- let container: HTMLDivElement;
-
- beforeEach(() => {
- container = document.createElement("div");
- document.body.appendChild(container);
- });
-
- afterEach(() => {
- container.remove();
- });
-
- it("renders request_board_approval payload fields without falling back to raw JSON", () => {
- const root = createRoot(container);
-
- act(() => {
- root.render(
-
-
- ,
- );
- });
-
- expect(container.textContent).toContain("Reply with an ASCII frog");
- expect(container.textContent).toContain("Board asked for approval before posting the frog.");
- expect(container.textContent).toContain("Approve the frog reply.");
- expect(container.textContent).toContain("Post the frog comment on the issue.");
- expect(container.textContent).toContain("The frog might be too powerful.");
- expect(container.textContent).toContain("(o)<");
- expect(container.textContent).not.toContain("\"recommendedAction\"");
-
- act(() => {
- root.unmount();
- });
- });
-
- it("renders markdown in board approval prose fields", () => {
- const root = createRoot(container);
-
- act(() => {
- root.render(
-
-
- ,
- );
- });
-
- const bodies = container.querySelectorAll(".paperclip-markdown");
- expect(bodies.length).toBe(4);
-
- const summary = bodies[0];
- expect(summary.querySelector("strong")?.textContent).toBe("Bold");
- expect(summary.querySelector("code")?.textContent).toBe("code");
- const link = summary.querySelector("a");
- expect(link?.getAttribute("href")).toBe("https://example.com");
- expect(link?.textContent).toBe("a link");
-
- // The raw markdown characters must not survive into the rendered text.
- expect(container.textContent).not.toContain("**Bold**");
- expect(container.textContent).not.toContain("[a link](https://example.com)");
-
- expect(bodies[1].querySelector("strong")?.textContent).toBe("frog");
- expect(bodies[2].querySelector("code")?.textContent).toBe("frog");
- expect(bodies[3].querySelector("strong")?.textContent).toBe("frog");
-
- act(() => {
- root.unmount();
- });
- });
-
- it("does not nest a second bullet when a risk is authored as a markdown list item", () => {
- const root = createRoot(container);
-
- act(() => {
- root.render(
-
-
- ,
- );
- });
-
- const bodies = container.querySelectorAll(".paperclip-markdown");
- expect(bodies.length).toBe(5);
- for (const body of bodies) {
- expect(body.querySelector("ul")).toBeNull();
- expect(body.querySelector("ol")).toBeNull();
- expect(body.querySelector("li")).toBeNull();
- }
-
- expect(bodies[0].querySelector("strong")?.textContent).toBe("Leading dash");
- expect(container.textContent).toContain("Leading star risk.");
- expect(container.textContent).toContain("Leading dot risk.");
- expect(container.textContent).toContain("Leading number risk.");
- expect(container.textContent).toContain("Leading paren risk.");
- expect(container.textContent).not.toContain("- **Leading dash**");
-
- act(() => {
- root.unmount();
- });
- });
-
- it("renders every risk when two entries collapse to the same text after marker stripping", () => {
- const root = createRoot(container);
- const errors: unknown[] = [];
- const originalError = console.error;
- console.error = (...args: unknown[]) => {
- errors.push(args);
- };
-
- try {
- act(() => {
- root.render(
-
-
- ,
- );
- });
-
- expect(container.querySelectorAll(".paperclip-markdown").length).toBe(2);
- expect(errors).toEqual([]);
- } finally {
- console.error = originalError;
- act(() => {
- root.unmount();
- });
- }
- });
-
- it("can hide the repeated title when the card header already shows it", () => {
- const root = createRoot(container);
-
- act(() => {
- root.render(
-
-
- ,
- );
- });
-
- expect(container.textContent).toContain("Board asked for approval before posting the frog.");
- expect(container.textContent).not.toContain("TitleReply with an ASCII frog");
-
- act(() => {
- root.unmount();
- });
- });
-});
diff --git a/ui/src/components/BudgetIncidentCard.test.tsx b/ui/src/components/BudgetIncidentCard.test.tsx
deleted file mode 100644
index 2bde9f13b7f..00000000000
--- a/ui/src/components/BudgetIncidentCard.test.tsx
+++ /dev/null
@@ -1,91 +0,0 @@
-// @vitest-environment jsdom
-import { act } from "react";
-import { createRoot } from "react-dom/client";
-import type { BudgetIncident } from "@paperclipai/shared";
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { BudgetIncidentCard } from "./BudgetIncidentCard";
-
-(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-
-function incident(overrides: Partial = {}): BudgetIncident {
- return {
- id: "incident-1",
- companyId: "company-1",
- policyId: "policy-1",
- scopeType: "agent",
- scopeId: "agent-1",
- scopeName: "Budget Demo",
- metric: "billed_cents",
- windowKind: "calendar_month_utc",
- windowStart: new Date("2026-10-01T00:00:00Z"),
- windowEnd: new Date("2026-11-01T00:00:00Z"),
- thresholdType: "hard",
- amountLimit: 100_000,
- amountObserved: 100_000,
- status: "open",
- approvalId: null,
- approvalStatus: null,
- resolvedAt: null,
- createdAt: new Date("2026-10-12T00:00:00Z"),
- updatedAt: new Date("2026-10-12T00:00:00Z"),
- ...overrides,
- };
-}
-
-async function renderCard(value: BudgetIncident) {
- const div = document.createElement("div");
- document.body.append(div);
- const root = createRoot(div);
- const onKeepPaused = vi.fn();
- const onRaiseAndResume = vi.fn();
- await act(async () => root.render(
- ,
- ));
- const buttons = () => Array.from(div.querySelectorAll("button"), (button) => button.textContent?.trim());
- return {
- div,
- buttons,
- onKeepPaused,
- cleanup: async () => {
- await act(async () => root.unmount());
- div.remove();
- },
- };
-}
-
-describe("BudgetIncidentCard", () => {
- afterEach(() => vi.restoreAllMocks());
-
- it("labels a hard-stop incident as paused", async () => {
- const { div, buttons, cleanup } = await renderCard(incident());
- expect(div.textContent).toContain("agent hard stop");
- expect(div.textContent).toContain("This scope is paused.");
- expect(buttons()).toEqual(["Raise budget & resume", "Keep paused"]);
- expect(div.querySelector("input")?.value).toBe("1010.00");
- await cleanup();
- });
-
- it("labels a soft-threshold incident as a warning that does not pause the scope", async () => {
- const { div, buttons, onKeepPaused, cleanup } = await renderCard(
- incident({ thresholdType: "soft", amountObserved: 80_000 }),
- );
- expect(div.textContent).toContain("agent budget warning");
- expect(div.textContent).not.toContain("hard stop");
- expect(div.textContent).not.toContain("paused");
- expect(div.textContent).toContain("This warning does not pause work.");
- expect(div.textContent).toContain("Spending reached $800.00 against a limit of $1,000.00.");
- expect(buttons()).toEqual(["Raise budget", "Dismiss warning"]);
- expect(div.querySelector("input")?.value).toBe("1010.00");
- const dismiss = Array.from(div.querySelectorAll("button")).find((button) => button.textContent?.trim() === "Dismiss warning")!;
- await act(async () => dismiss.click());
- expect(onKeepPaused).toHaveBeenCalledTimes(1);
- await cleanup();
- });
-
- it("describes a paused project for a project hard stop", async () => {
- const { div, cleanup } = await renderCard(incident({ scopeType: "project", scopeName: "Website" }));
- expect(div.textContent).toContain("project hard stop");
- expect(div.textContent).toContain("Project execution is paused.");
- await cleanup();
- });
-});
diff --git a/ui/src/components/CaseRevisionRail.test.tsx b/ui/src/components/CaseRevisionRail.test.tsx
deleted file mode 100644
index 20cd3735556..00000000000
--- a/ui/src/components/CaseRevisionRail.test.tsx
+++ /dev/null
@@ -1,140 +0,0 @@
-// @vitest-environment jsdom
-
-import { flushSync } from "react-dom";
-import { createRoot } from "react-dom/client";
-import type { AnchorHTMLAttributes } from "react";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import type { CaseDocumentRevisions } from "@/api/cases";
-import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils";
-import { CaseRevisionRail } from "./CaseRevisionRail";
-
-function act(callback: () => void) {
- flushSync(callback);
-}
-
-const mockCasesApi = vi.hoisted(() => ({ listRevisions: vi.fn() }));
-
-vi.mock("@/api/cases", async (importOriginal) => ({
- ...(await importOriginal()),
- casesApi: mockCasesApi,
-}));
-vi.mock("@/components/MarkdownBody", () => ({
- MarkdownBody: ({ children }: { children: string }) => {children}
,
-}));
-vi.mock("@/lib/router", () => ({
- Link: ({ children, to, ...props }: AnchorHTMLAttributes & { to: string }) => (
- {children}
- ),
-}));
-
-(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-
-async function flush() {
- for (let i = 0; i < 5; i += 1) {
- await Promise.resolve();
- await new Promise((r) => setTimeout(r, 0));
- }
- flushSync(() => {});
-}
-
-const revisions: CaseDocumentRevisions = {
- key: "body",
- document: { id: "doc-1", title: "body", format: "markdown", latestRevisionId: "r2", latestRevisionNumber: 2 },
- revisions: [
- {
- id: "r2",
- revisionNumber: 2,
- title: "body",
- format: "markdown",
- body: "# Second version",
- changeSummary: "polish wording",
- createdAt: "2026-07-07T02:00:00.000Z",
- createdByAgentId: "agent-1",
- createdByUserId: null,
- createdByRunId: "run-2",
- actorAgentName: "Cases Agent",
- issue: { id: "i1", identifier: "PAP-42", title: "Task", status: "in_progress" },
- },
- {
- id: "r1",
- revisionNumber: 1,
- title: "body",
- format: "markdown",
- body: "# First version",
- changeSummary: null,
- createdAt: "2026-07-07T01:00:00.000Z",
- createdByAgentId: "agent-1",
- createdByUserId: null,
- createdByRunId: "run-1",
- actorAgentName: "Cases Agent",
- issue: null,
- },
- ],
-};
-
-describe("CaseRevisionRail", () => {
- let container: HTMLDivElement;
- beforeEach(() => {
- container = document.createElement("div");
- document.body.appendChild(container);
- mockCasesApi.listRevisions.mockReset();
- });
- afterEach(() => container.remove());
-
- async function render() {
- const root = createRoot(container);
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
- act(() => {
- root.render(
-
-
- ,
- );
- });
- await flush();
- return root;
- }
-
- it("renders both revisions and shows the latest body by default", async () => {
- mockCasesApi.listRevisions.mockResolvedValue(revisions);
- const root = await render();
- const text = container.textContent ?? "";
- expect(text).toContain("rev 2");
- expect(text).toContain("rev 1");
- expect(text).toContain("latest");
- expect(text).toContain("polish wording");
- expect(text).toContain("Cases Agent");
- // Latest (rev 2) selected → its body renders; via-issue attribution shown.
- expect(container.querySelector('[data-testid="md"]')?.textContent).toBe("# Second version");
- expect(container.querySelector('a[href="/issues/PAP-42"]')).not.toBeNull();
- act(() => root.unmount());
- });
-
- it("switches the rendered body when an older revision is picked", async () => {
- mockCasesApi.listRevisions.mockResolvedValue(revisions);
- const root = await render();
- const rev1Button = Array.from(container.querySelectorAll("button")).find((b) =>
- b.textContent?.includes("rev 1"),
- );
- expect(rev1Button).toBeTruthy();
- act(() => rev1Button!.dispatchEvent(new MouseEvent("click", { bubbles: true })));
- await flush();
- expect(container.querySelector('[data-testid="md"]')?.textContent).toBe("# First version");
- act(() => root.unmount());
- });
-
- it("keeps revision diff lines out of session replay", async () => {
- mockCasesApi.listRevisions.mockResolvedValue(revisions);
- const root = await render();
- const compare = Array.from(container.querySelectorAll("button")).find((b) => /compare|diff/i.test(b.textContent ?? "") || /compare|diff/i.test(b.getAttribute("aria-label") ?? ""));
- expect(compare).toBeTruthy();
- act(() => compare!.dispatchEvent(new MouseEvent("click", { bubbles: true })));
- await flush();
- const dialog = document.querySelector('[role="dialog"]');
- expect(dialog).not.toBeNull();
- expect(replayLeaks("Second version", dialog!)).toEqual({ rendered: true, recorded: false });
- expect(replayLeaks("First version", dialog!)).toEqual({ rendered: true, recorded: false });
- act(() => root.unmount());
- });
-});
diff --git a/ui/src/components/DeferredOverlay.test.tsx b/ui/src/components/DeferredOverlay.test.tsx
deleted file mode 100644
index eee19620a81..00000000000
--- a/ui/src/components/DeferredOverlay.test.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-// @vitest-environment jsdom
-import { act, lazy, useState } from "react";
-import { createRoot } from "react-dom/client";
-import { afterEach, beforeEach, expect, it, vi } from "vitest";
-import { DeferredOverlay } from "./DeferredOverlay";
-
-const capture = vi.hoisted(() => vi.fn());
-vi.mock("../lib/sentry", () => ({ captureBrowserException: capture }));
-let container: HTMLDivElement;
-let root: ReturnType;
-beforeEach(() => {
- container = document.createElement("div");
- document.body.appendChild(container);
- root = createRoot(container);
- vi.spyOn(console, "error").mockImplementation(() => {});
-});
-afterEach(async () => {
- await act(async () => root.unmount());
- container.remove();
- vi.restoreAllMocks();
- capture.mockClear();
-});
-it("dismisses a failed chunk without replacing the board or its draft", async () => {
- const Failed = lazy(async () => { throw new Error("Chunk download failed"); });
- function Board() {
- const [requested, setRequested] = useState(true);
- return <> setRequested(false)}>>;
- }
- await act(async () => root.render());
- const draft = container.querySelector("textarea")!;
- expect(document.body.textContent).toContain("Couldn't open new task");
- const close = [...document.querySelectorAll("button")].find((button) => button.textContent === "Close")!;
- await act(async () => close.click());
- expect(document.querySelector('[role="dialog"]')).toBeNull();
- expect(container.querySelector("textarea")).toBe(draft);
- expect(draft.value).toBe("Keep my unsent reply");
- expect(capture).toHaveBeenCalledWith(expect.any(Error));
-});
-it("removes a pending overlay on navigation and contains a later rejection", async () => {
- let reject!: (error: Error) => void;
- const Pending = lazy(() => new Promise((_, rejectImport) => { reject = rejectImport; }));
- function render(requested: boolean) {
- return <> {}}>>;
- }
- await act(async () => root.render(render(true)));
- expect(document.body.textContent).toContain("Loading setup");
- const draft = container.querySelector("textarea");
- await act(async () => root.render(render(false)));
- expect(document.querySelector('[role="dialog"]')).toBeNull();
- await act(async () => reject(new Error("Late chunk failure")));
- expect(document.querySelector('[role="dialog"]')).toBeNull();
- expect(container.querySelector("textarea")).toBe(draft);
-});
-it("allows cancelling an in-flight download", async () => {
- const Pending = lazy(() => new Promise(() => {}));
- function Board() {
- const [requested, setRequested] = useState(true);
- return setRequested(false)}>;
- }
- await act(async () => root.render());
- const cancel = [...document.querySelectorAll("button")].find((button) => button.textContent === "Cancel")!;
- await act(async () => cancel.click());
- expect(document.querySelector('[role="dialog"]')).toBeNull();
-});
diff --git a/ui/src/components/EmailConnectionAccess.test.tsx b/ui/src/components/EmailConnectionAccess.test.tsx
deleted file mode 100644
index 9175630f5d1..00000000000
--- a/ui/src/components/EmailConnectionAccess.test.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-// @vitest-environment jsdom
-import { act } from "react";
-import { createRoot, type Root } from "react-dom/client";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { afterEach, beforeEach, expect, it, vi } from "vitest";
-import { ApiError } from "@/api/client";
-import { EmailConnectionAccess } from "./EmailConnectionAccess";
-
-const mocks = vi.hoisted(() => ({ grants: vi.fn(), installs: vi.fn(), save: vi.fn() }));
-vi.mock("@/api/tools", () => ({ toolsApi: { listConnectionGrants: mocks.grants, getConnectionInstalls: mocks.installs, putConnectionInstalls: mocks.save } }));
-(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-let root: Root, host: HTMLDivElement, client: QueryClient;
-let finishInstalls: () => void;
-beforeEach(() => {
- vi.clearAllMocks();
- host = document.createElement("div"); document.body.append(host); root = createRoot(host);
- client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
- mocks.installs.mockReturnValue(new Promise(resolve => { finishInstalls = () => resolve({ installs: [] }); }));
-});
-afterEach(async () => {
- await act(async () => root.unmount()); finishInstalls(); client.clear(); host.remove();
-});
-it.each([403, 500])("shows a known %s before the other access read finishes", async status => {
- mocks.grants.mockRejectedValue(new ApiError("Access lookup failed", status, {}));
- await act(async () => root.render());
- await vi.waitFor(() => expect(host.querySelector('[data-query-view="error"]')).not.toBeNull());
- expect(host.textContent).not.toContain("Loading access");
- const retry = [...host.querySelectorAll("button")].find(button => button.textContent?.trim() === "Retry");
- if (status === 403) expect(retry).toBeUndefined();
- else {
- expect(retry).toBeDefined();
- mocks.grants.mockResolvedValue({ grants: [], capabilities: { canConfigure: false } });
- await act(async () => retry!.click());
- await vi.waitFor(() => expect(mocks.grants).toHaveBeenCalledTimes(2));
- await vi.waitFor(() => expect(host.textContent).toContain("Loading access"));
- }
-});
diff --git a/ui/src/components/IssueDocumentAnnotations.test.tsx b/ui/src/components/IssueDocumentAnnotations.test.tsx
deleted file mode 100644
index 357341e38fe..00000000000
--- a/ui/src/components/IssueDocumentAnnotations.test.tsx
+++ /dev/null
@@ -1,1071 +0,0 @@
-// @vitest-environment jsdom
-
-import { useState } from "react";
-import { createRoot as createReactRoot } from "react-dom/client";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import type {
- DocumentAnnotationThreadWithComments,
- IssueDocument,
-} from "@paperclipai/shared";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import {
- DocumentAnnotationsCountChip,
- IssueDocumentAnnotations,
-} from "./IssueDocumentAnnotations";
-
-const mockAnnotationsApi = vi.hoisted(() => {
- const api = {
- list: vi.fn(),
- listForTarget: vi.fn(),
- get: vi.fn(),
- getForTarget: vi.fn(),
- create: vi.fn(),
- createForTarget: vi.fn(),
- addComment: vi.fn(),
- addCommentForTarget: vi.fn(),
- updateStatus: vi.fn(),
- updateStatusForTarget: vi.fn(),
- };
- api.listForTarget.mockImplementation((target, options) =>
- target.kind === "issue"
- ? api.list(target.issueId, target.documentKey, options)
- : target.kind === "case"
- ? api.list(target.caseId, target.documentKey, options)
- : api.list(target.routineId, target.documentKey, options));
- api.getForTarget.mockImplementation((target, threadId) =>
- target.kind === "issue"
- ? api.get(target.issueId, target.documentKey, threadId)
- : target.kind === "case"
- ? api.get(target.caseId, target.documentKey, threadId)
- : api.get(target.routineId, target.documentKey, threadId));
- api.createForTarget.mockImplementation((target, data) =>
- target.kind === "issue"
- ? api.create(target.issueId, target.documentKey, data)
- : target.kind === "case"
- ? api.create(target.caseId, target.documentKey, data)
- : api.create(target.routineId, target.documentKey, data));
- api.addCommentForTarget.mockImplementation((target, threadId, data) =>
- target.kind === "issue"
- ? api.addComment(target.issueId, target.documentKey, threadId, data)
- : target.kind === "case"
- ? api.addComment(target.caseId, target.documentKey, threadId, data)
- : api.addComment(target.routineId, target.documentKey, threadId, data));
- api.updateStatusForTarget.mockImplementation((target, threadId, status) =>
- target.kind === "issue"
- ? api.updateStatus(target.issueId, target.documentKey, threadId, status)
- : target.kind === "case"
- ? api.updateStatus(target.caseId, target.documentKey, threadId, status)
- : api.updateStatus(target.routineId, target.documentKey, threadId, status));
- return api;
-});
-
-const mockPendingAnchor = vi.hoisted(() => ({
- selector: {
- quote: { exact: "should keep the editor", prefix: "We ", suffix: "." },
- position: { normalizedStart: 10, normalizedEnd: 32, markdownStart: 10, markdownEnd: 32 },
- },
- selectedText: "should keep the editor",
-}));
-
-vi.mock("@/api/document-annotations", () => ({
- documentAnnotationsApi: mockAnnotationsApi,
-}));
-
-vi.mock("./MarkdownBody", () => ({
- MarkdownBody: ({ children }: { children: string }) => {children}
,
-}));
-
-vi.mock("@/components/ui/sheet", () => ({
- Sheet: ({ open, children }: { open: boolean; children: React.ReactNode }) =>
- open ? {children}
: null,
- SheetContent: ({
- children,
- className,
- side,
- }: {
- children: React.ReactNode;
- className?: string;
- side?: string;
- }) => (
-
- {children}
-
- ),
- SheetTitle: ({ children, className }: { children: React.ReactNode; className?: string }) => (
- {children}
- ),
-}));
-
-vi.mock("./DocumentAnnotationLayer", () => ({
- DocumentAnnotationLayer: (props: {
- newCommentDisabled?: boolean;
- onPendingAnchorChange: (anchor: typeof mockPendingAnchor | null) => void;
- onRequestComment: (anchor: typeof mockPendingAnchor, rect: { top: number; left: number; width: number; height: number }) => void;
- onThreadFocus: (threadId: string, rect: { top: number; left: number; width: number; height: number }) => void;
- }) => (
- <>
-
-
-
- >
- ),
-}));
-
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
-
-async function act(callback: () => void | Promise) {
- await callback();
- await Promise.resolve();
- await new Promise((resolve) => setTimeout(resolve, 0));
-}
-
-// Track every root so afterEach can unmount it. Tests mount into a throwaway
-// container but never unmount, so without this the panel's window scroll/resize
-// listeners and react-query subscriptions from earlier tests stay live and can
-// recompute positioning against a detached host — an order-dependent flake that
-// only surfaced under CI's fuller suite run.
-const activeRoots: Array> = [];
-function createRoot(node: Parameters[0]) {
- const root = createReactRoot(node);
- activeRoots.push(root);
- return root;
-}
-
-async function unmountActiveRoots() {
- if (activeRoots.length === 0) return;
- const roots = activeRoots.splice(0);
- await act(() => {
- for (const root of roots) root.unmount();
- });
-}
-
-async function flush() {
- await act(() => {});
-}
-
-// Poll an assertion across React flushes until it passes or times out. The panel
-// positions itself and loads threads through effects + react-query, so a fixed
-// number of flushes can race on a loaded machine (CI). Waiting on the assertion
-// itself is deterministic regardless of how many turns the settle takes.
-async function waitFor(assertion: () => void, { timeout = 2000 }: { timeout?: number } = {}) {
- const start = Date.now();
- for (;;) {
- try {
- assertion();
- return;
- } catch (error) {
- if (Date.now() - start > timeout) throw error;
- await flush();
- }
- }
-}
-
-function setTextareaValue(textarea: HTMLTextAreaElement, value: string) {
- const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")?.set;
- setter?.call(textarea, value);
- textarea.dispatchEvent(new Event("input", { bubbles: true }));
-}
-
-function dispatchSubmitShortcut(textarea: HTMLTextAreaElement) {
- textarea.dispatchEvent(
- new KeyboardEvent("keydown", { key: "Enter", metaKey: true, bubbles: true }),
- );
-}
-
-function makeQueryClient() {
- return new QueryClient({
- defaultOptions: {
- queries: { retry: false },
- mutations: { retry: false },
- },
- });
-}
-
-function makeDoc(overrides: Partial = {}): IssueDocument {
- return {
- id: "doc-1",
- companyId: "co-1",
- issueId: "issue-1",
- key: "plan",
- title: "Plan",
- format: "markdown",
- body: "# Plan\n\nWe should keep the editor.",
- latestRevisionId: "rev-4",
- latestRevisionNumber: 4,
- createdByAgentId: null,
- createdByUserId: "user-1",
- updatedByAgentId: null,
- updatedByUserId: "user-1",
- lockedAt: null,
- lockedByAgentId: null,
- lockedByUserId: null,
- createdAt: new Date("2026-04-01T00:00:00Z"),
- updatedAt: new Date("2026-04-01T00:01:00Z"),
- ...overrides,
- };
-}
-
-function makeThread(
- overrides: Partial = {},
-): DocumentAnnotationThreadWithComments {
- const id = overrides.id ?? "thread-1";
- return {
- id,
- companyId: "co-1",
- issueId: "issue-1",
- documentId: "doc-1",
- documentKey: "plan",
- status: "open",
- anchorState: "active",
- anchorConfidence: "exact",
- originalRevisionId: "rev-4",
- originalRevisionNumber: 4,
- currentRevisionId: "rev-4",
- currentRevisionNumber: 4,
- selectedText: "should keep the editor",
- prefixText: "We ",
- suffixText: ".",
- normalizedStart: 0,
- normalizedEnd: 22,
- markdownStart: 0,
- markdownEnd: 22,
- anchorSelector: {
- quote: { exact: "should keep the editor", prefix: "We ", suffix: "." },
- position: { normalizedStart: 0, normalizedEnd: 22, markdownStart: 0, markdownEnd: 22 },
- },
- createdByAgentId: null,
- createdByUserId: "user-1",
- resolvedByAgentId: null,
- resolvedByUserId: null,
- resolvedAt: null,
- createdAt: new Date("2026-04-01T00:01:00Z"),
- updatedAt: new Date("2026-04-01T00:02:00Z"),
- comments: [
- {
- id: "comment-1",
- companyId: "co-1",
- threadId: id,
- issueId: "issue-1",
- documentId: "doc-1",
- body: "Please clarify this assumption.",
- authorType: "user",
- authorAgentId: null,
- authorUserId: "user-1",
- createdByRunId: null,
- createdAt: new Date("2026-04-01T00:01:00Z"),
- updatedAt: new Date("2026-04-01T00:01:00Z"),
- },
- ],
- ...overrides,
- };
-}
-
-function Harness({
- doc,
- draftDirty = false,
- draftConflicted = false,
- historicalPreview = false,
- locationHash = "",
- initialPanelOpen = false,
- panelPlacement,
-}: {
- doc: IssueDocument;
- draftDirty?: boolean;
- draftConflicted?: boolean;
- historicalPreview?: boolean;
- locationHash?: string;
- initialPanelOpen?: boolean;
- panelPlacement?: "floating" | "inline" | "popover";
-}) {
- const [open, setOpen] = useState(initialPanelOpen);
- return (
- <>
- setOpen((current) => !current)}
- />
-
- Body content
-
- >
- );
-}
-
-describe("IssueDocumentAnnotations", () => {
- let container: HTMLDivElement;
-
- beforeEach(() => {
- container = document.createElement("div");
- document.body.appendChild(container);
- vi.clearAllMocks();
- });
-
- afterEach(async () => {
- await unmountActiveRoots();
- container.remove();
- });
-
- it("renders the open count chip and opens the panel on click", async () => {
- mockAnnotationsApi.list.mockResolvedValue([makeThread()]);
- const root = createRoot(container);
- const queryClient = makeQueryClient();
- const doc = makeDoc();
-
- await act(async () => {
- root.render(
-
-
- ,
- );
- });
- await flush();
- await flush();
-
- const chip = container.querySelector('[data-testid="document-annotation-count-plan"]');
- expect(chip).not.toBeNull();
- expect(chip!.textContent).toContain("1");
- expect(mockAnnotationsApi.list).toHaveBeenCalledTimes(1);
-
- await act(async () => {
- (chip as HTMLButtonElement).click();
- });
- await flush();
- const panel = container.querySelector('[data-testid="document-annotation-panel"]');
- expect(panel).not.toBeNull();
- const anchor = container.querySelector('[data-testid="document-annotation-panel-anchor"]');
- expect(anchor).not.toBeNull();
- // The desktop panel docks into an in-flow gutter column beside the doc; it no
- // longer floats over the viewport with position: fixed (PAP-504).
- expect(anchor?.className).not.toContain("fixed");
- expect(anchor?.className).toContain("lg:block");
- expect(anchor?.querySelector(".sticky")).not.toBeNull();
- });
-
- it("stacks an inline panel below the document instead of floating over its host", async () => {
- mockAnnotationsApi.list.mockResolvedValue([makeThread()]);
- const root = createRoot(container);
- const queryClient = makeQueryClient();
- const doc = makeDoc();
-
- await act(async () => {
- root.render(
-
-
- ,
- );
- });
- await flush();
- await flush();
-
- const inlinePanel = container.querySelector('[data-testid="document-annotation-panel-inline"]');
- const floatingAnchor = container.querySelector('[data-testid="document-annotation-panel-anchor"]');
- const panel = container.querySelector('[data-testid="document-annotation-panel"]');
- expect(inlinePanel).not.toBeNull();
- expect(floatingAnchor).toBeNull();
- expect(panel?.className).toContain("w-full");
- });
-
- it("opens anchored compose and thread popovers in popover placement", async () => {
- mockAnnotationsApi.list.mockResolvedValue([makeThread()]);
- const root = createRoot(container);
- const queryClient = makeQueryClient();
- await act(async () => {
- root.render(
-
-
- ,
- );
- });
- await waitFor(() => expect(container.querySelector('[data-testid="mock-annotation-selection"]')).not.toBeNull());
- await act(async () => (container.querySelector('[data-testid="mock-annotation-selection"]') as HTMLButtonElement).click());
- await waitFor(() => {
- expect(container.querySelector('[data-testid="document-annotation-popover"]')).not.toBeNull();
- expect(container.querySelector('[data-testid="document-annotation-popover-composer"]')).not.toBeNull();
- expect(container.querySelector('[data-testid="document-annotation-panel-inline"]')).toBeNull();
- });
- await act(async () => (container.querySelector('[aria-label="Add annotation comment"] button') as HTMLButtonElement).click());
- await act(async () => (container.querySelector('[data-testid="mock-annotation-thread"]') as HTMLButtonElement).click());
- await waitFor(() => {
- expect(container.querySelector('[data-testid="document-annotation-popover"] [data-thread-id="thread-1"]')).not.toBeNull();
- });
- });
-
- it("docks the desktop annotation panel into an in-flow gutter column beside the document", async () => {
- mockAnnotationsApi.list.mockResolvedValue([makeThread()]);
- const root = createRoot(container);
- const queryClient = makeQueryClient();
- const doc = makeDoc();
-
- await act(async () => {
- root.render(
-
-
-
-
- ,
- );
- });
- await waitFor(() => {
- const anchor = container.querySelector('[data-testid="document-annotation-panel-anchor"]') as HTMLElement | null;
- const panel = container.querySelector('[data-testid="document-annotation-panel"]') as HTMLElement | null;
- expect(anchor).not.toBeNull();
- expect(panel).not.toBeNull();
- // Gutter column: fixed width, in normal flow (no absolute/fixed positioning),
- // and its host row is a flex layout so the doc sits to its left.
- expect(anchor!.style.width).toBe("360px");
- expect(anchor!.className).not.toContain("fixed");
- expect(anchor!.style.left).toBe("");
- const host = container.querySelector(".paperclip-doc-annotation-host") as HTMLElement | null;
- expect(host!.className).toContain("lg:flex");
- // The panel is sticky inside the gutter so it stays beside the doc while scrolling.
- expect(anchor!.querySelector(".sticky")).not.toBeNull();
- expect(panel!.style.width).toBe("360px");
- });
- });
-
- it("auto-opens the panel and focuses the thread when deep-linked", async () => {
- mockAnnotationsApi.list.mockResolvedValue([makeThread({ id: "thread-99" })]);
- const root = createRoot(container);
- const queryClient = makeQueryClient();
- const doc = makeDoc();
-
- await act(async () => {
- root.render(
-
-
- ,
- );
- });
- await waitFor(() => {
- const panel = container.querySelector('[data-testid="document-annotation-panel"]');
- expect(panel).not.toBeNull();
- const focusedThread = container.querySelector('[data-thread-id="thread-99"][data-focused]');
- expect(focusedThread).not.toBeNull();
- });
- });
-
- it("opens a resolved orphaned deep-link target after revision and fresh reload without changing history", async () => {
- const originalBody = "Original review detail that must remain readable after its selection was removed. ".repeat(5)
- + "The complete first comment ends here.";
- const target = makeThread({ id: "orphan-target", status: "resolved", anchorState: "orphaned",
- currentRevisionId: "rev-5", currentRevisionNumber: 5, resolvedByUserId: "user-1", resolvedAt: new Date() });
- target.comments = [{ ...target.comments[0]!, body: originalBody },
- { ...target.comments[0]!, id: "resolution-note", body: "The saved policy addresses this review." }];
- mockAnnotationsApi.list.mockResolvedValue([target,
- makeThread({ id: "unrelated-orphan", status: "resolved", anchorState: "orphaned" }),
- makeThread({ id: "remaining-thread", anchorState: "stale" })]);
- const doc = makeDoc({ latestRevisionId: "rev-5", latestRevisionNumber: 5, body: "# Updated policy\n\nThe original selection is gone." });
- for (let mount = 0; mount < 2; mount++) {
- const root = createRoot(container);
- const queryClient = makeQueryClient();
- const render = (locationHash: string) => root.render(
- ,
- );
- await act(() => render("#document-plan&thread=orphan-target&comment=comment-1"));
- await waitFor(() => {
- const card = container.querySelector('[data-thread-id="orphan-target"][data-focused]');
- expect(card).not.toBeNull();
- expect(card!.getAttribute("data-anchor-state")).toBe("orphaned");
- expect(card!.getAttribute("data-status")).toBe("resolved");
- expect(card!.textContent).toContain(originalBody);
- expect(card!.textContent).toContain("The saved policy addresses this review.");
- });
- expect(container.querySelector('[data-thread-id="unrelated-orphan"]')).toBeNull();
- expect(mockAnnotationsApi.create).not.toHaveBeenCalled();
- expect(mockAnnotationsApi.addComment).not.toHaveBeenCalled();
- expect(mockAnnotationsApi.updateStatus).not.toHaveBeenCalled();
- await act(() => render("#document-plan&thread=remaining-thread"));
- await waitFor(() => {
- expect(container.querySelector('[data-thread-id="remaining-thread"][data-focused]')).not.toBeNull();
- expect(container.querySelector('[data-thread-id="orphan-target"]')).toBeNull();
- });
- await unmountActiveRoots();
- queryClient.clear();
- }
- });
-
- it("shows a disabled reason in the panel when the draft is dirty", async () => {
- mockAnnotationsApi.list.mockResolvedValue([makeThread()]);
- const root = createRoot(container);
- const queryClient = makeQueryClient();
- const doc = makeDoc();
-
- await act(async () => {
- root.render(
-
-
- ,
- );
- });
- await waitFor(() => {
- const reason = container.querySelector(
- '[data-testid="document-annotation-disabled-reason"]',
- );
- expect(reason).not.toBeNull();
- expect(reason!.textContent).toMatch(/draft/i);
- });
- });
-
- it("shows open and resolved threads together in a single list (no filter tabs)", async () => {
- mockAnnotationsApi.list.mockResolvedValue([
- makeThread({ id: "open-1" }),
- makeThread({ id: "resolved-1", status: "resolved" }),
- makeThread({ id: "orphan-1", anchorState: "orphaned" }),
- ]);
- const root = createRoot(container);
- const queryClient = makeQueryClient();
- const doc = makeDoc();
-
- await act(async () => {
- root.render(
-
-
- ,
- );
- });
- // Open + resolved both render without any filter interaction.
- await waitFor(() => {
- expect(container.querySelector('[data-thread-id="open-1"]')).not.toBeNull();
- expect(container.querySelector('[data-thread-id="resolved-1"]')).not.toBeNull();
- });
- // Orphaned threads can't be anchored in the doc, so they stay hidden.
- expect(container.querySelector('[data-thread-id="orphan-1"]')).toBeNull();
-
- // The Open/Resolved/Stale/Orphaned filter chips are gone.
- const filterChip = Array.from(container.querySelectorAll("button")).find((button) =>
- ["Open", "Resolved", "Stale", "Orphaned"].includes((button.textContent ?? "").trim()),
- );
- expect(filterChip).toBeUndefined();
- });
-
- it("orders threads by document position, not API/recency order", async () => {
- // Returned out of document order: later-in-doc first, earlier-in-doc last.
- mockAnnotationsApi.list.mockResolvedValue([
- makeThread({ id: "thread-late", normalizedStart: 900, markdownStart: 900 }),
- makeThread({ id: "thread-early", normalizedStart: 10, markdownStart: 10 }),
- makeThread({ id: "thread-mid", normalizedStart: 400, markdownStart: 400 }),
- ]);
- const root = createRoot(container);
- const queryClient = makeQueryClient();
- const doc = makeDoc();
-
- await act(async () => {
- root.render(
-
-
- ,
- );
- });
- await waitFor(() => {
- const order = Array.from(container.querySelectorAll("[data-thread-id]"))
- .map((el) => el.getAttribute("data-thread-id"));
- expect(order).toEqual(["thread-early", "thread-mid", "thread-late"]);
- });
- });
-
- it("renders author name + role from agent and user maps", async () => {
- mockAnnotationsApi.list.mockResolvedValue([
- makeThread({
- id: "open-1",
- comments: [
- {
- id: "comment-board",
- companyId: "co-1",
- threadId: "open-1",
- issueId: "issue-1",
- documentId: "doc-1",
- body: "From the board.",
- authorType: "user",
- authorAgentId: null,
- authorUserId: "user-1",
- createdByRunId: null,
- createdAt: new Date("2026-04-01T00:01:00Z"),
- updatedAt: new Date("2026-04-01T00:01:00Z"),
- },
- {
- id: "comment-agent",
- companyId: "co-1",
- threadId: "open-1",
- issueId: "issue-1",
- documentId: "doc-1",
- body: "From the agent.",
- authorType: "agent",
- authorAgentId: "agent-uxdesigner",
- authorUserId: null,
- createdByRunId: "run-1",
- createdAt: new Date("2026-04-01T00:02:00Z"),
- updatedAt: new Date("2026-04-01T00:02:00Z"),
- },
- ],
- }),
- ]);
- const root = createRoot(container);
- const queryClient = makeQueryClient();
- const doc = makeDoc();
-
- const agentMap = new Map([["agent-uxdesigner", { id: "agent-uxdesigner", name: "UXDesigner" }]]);
- const userProfileMap = new Map([["user-1", { label: "Dotta", image: null }]]);
-
- await act(async () => {
- root.render(
-
- {}}
- />
- {}}
- agentMap={agentMap}
- userProfileMap={userProfileMap}
- >
- Body
-
- ,
- );
- });
- // Click the open thread to expand it.
- await waitFor(() => {
- expect(container.querySelector('[data-thread-id="open-1"]')).not.toBeNull();
- });
- const threadCard = container.querySelector('[data-thread-id="open-1"]') as HTMLElement | null;
- await act(async () => threadCard!.click());
- await flush();
-
- const expandedThread = container.querySelector('[data-thread-id="open-1"]');
- const expandedText = expandedThread?.textContent ?? "";
- expect(expandedText).toContain("Dotta");
- expect(expandedText).not.toContain("· board");
- expect(expandedText).toContain("UXDesigner");
- expect(expandedText).toContain("· agent");
- // Each rendered comment shows an author avatar.
- const avatars = expandedThread?.querySelectorAll('[data-slot="avatar"], [data-slot="agent-avatar"]') ?? [];
- expect(avatars.length).toBe(2);
- });
-
- it("does not render a persistent New comment on selection hint when panel is open", async () => {
- mockAnnotationsApi.list.mockResolvedValue([]);
- const root = createRoot(container);
- const queryClient = makeQueryClient();
- const doc = makeDoc();
-
- await act(async () => {
- root.render(
-
-
- ,
- );
- });
- await flush();
- await flush();
-
- const cta = container.querySelector('[data-testid="document-annotation-new-comment-cta"]');
- expect(cta).toBeNull();
- expect(container.textContent).not.toMatch(/New comment on selection/i);
- expect(container.textContent).not.toMatch(/⌘⇧M/);
- });
-
- it("keeps a captured selection from opening the composer until the layer requests a comment", async () => {
- mockAnnotationsApi.list.mockResolvedValue([]);
- const root = createRoot(container);
- const queryClient = makeQueryClient();
- const doc = makeDoc();
-
- await act(async () => {
- root.render(
-
-
- ,
- );
- });
- await flush();
- await flush();
-
- const selectOnlyButton = container.querySelector(
- '[data-testid="mock-annotation-selection-only"]',
- ) as HTMLButtonElement | null;
- expect(selectOnlyButton).not.toBeNull();
- await act(async () => {
- selectOnlyButton!.click();
- });
- await flush();
-
- expect(container.querySelector('[data-testid="document-annotation-composer"]')).toBeNull();
-
- expect(container.querySelector('[data-testid="document-annotation-new-comment-cta"]')).toBeNull();
- const directRequestButton = container.querySelector(
- '[data-testid="mock-annotation-selection"]',
- ) as HTMLButtonElement | null;
- expect(directRequestButton).not.toBeNull();
- await act(async () => {
- directRequestButton!.click();
- });
- await flush();
-
- const composer = container.querySelector(
- '[data-testid="document-annotation-composer"]',
- ) as HTMLTextAreaElement | null;
- expect(composer).not.toBeNull();
- expect(container.textContent).toContain(mockPendingAnchor.selectedText);
- });
-
- it("creates a thread from a captured selection and refreshes the shared annotations query", async () => {
- mockAnnotationsApi.list.mockResolvedValue([]);
- mockAnnotationsApi.create.mockResolvedValue(makeThread({ id: "created-1" }));
- const root = createRoot(container);
- const queryClient = makeQueryClient();
- const doc = makeDoc();
-
- await act(async () => {
- root.render(
-
-
- ,
- );
- });
- await flush();
- await flush();
- expect(mockAnnotationsApi.list).toHaveBeenCalledTimes(1);
-
- const selectButton = container.querySelector('[data-testid="mock-annotation-selection"]') as HTMLButtonElement | null;
- expect(selectButton).not.toBeNull();
- await act(async () => {
- selectButton!.click();
- });
- await flush();
-
- const composer = container.querySelector('[data-testid="document-annotation-composer"]') as HTMLTextAreaElement | null;
- expect(composer).not.toBeNull();
- await act(async () => {
- setTextareaValue(composer!, "New anchored comment");
- });
- await flush();
-
- const submit = Array.from(container.querySelectorAll("button")).find(
- (button) => button.textContent === "Comment",
- );
- expect(submit).not.toBeUndefined();
- await act(async () => {
- submit!.click();
- });
- await flush();
- await flush();
-
- expect(mockAnnotationsApi.create).toHaveBeenCalledWith("issue-1", "plan", {
- baseRevisionId: "rev-4",
- baseRevisionNumber: 4,
- selector: mockPendingAnchor.selector,
- body: "New anchored comment",
- });
- expect(mockAnnotationsApi.list.mock.calls.length).toBeGreaterThan(1);
- });
-
- it("keeps the composer visible with the draft when creating a thread fails", async () => {
- mockAnnotationsApi.list.mockResolvedValue([]);
- mockAnnotationsApi.create.mockRejectedValue(new Error("Annotation anchor does not match the current document revision"));
- const root = createRoot(container);
- const queryClient = makeQueryClient();
- const doc = makeDoc();
-
- await act(async () => {
- root.render(
-
-
- ,
- );
- });
- await flush();
- await flush();
-
- const selectButton = container.querySelector('[data-testid="mock-annotation-selection"]') as HTMLButtonElement | null;
- expect(selectButton).not.toBeNull();
- await act(async () => {
- selectButton!.click();
- });
- await flush();
-
- const composer = container.querySelector('[data-testid="document-annotation-composer"]') as HTMLTextAreaElement | null;
- expect(composer).not.toBeNull();
- await act(async () => {
- setTextareaValue(composer!, "New anchored comment");
- });
- await flush();
-
- const submit = Array.from(container.querySelectorAll("button")).find(
- (button) => button.textContent === "Comment",
- );
- expect(submit).not.toBeUndefined();
- await act(async () => {
- submit!.click();
- });
- await flush();
- await flush();
-
- const composerAfterFailure = container.querySelector('[data-testid="document-annotation-composer"]') as HTMLTextAreaElement | null;
- expect(composerAfterFailure).not.toBeNull();
- expect(composerAfterFailure!.value).toBe("New anchored comment");
- expect(container.querySelector('[data-testid="document-annotation-error"]')?.textContent)
- .toContain("Annotation anchor does not match the current document revision");
- });
-
- it("submits a new anchored comment with ⌘↵", async () => {
- mockAnnotationsApi.list.mockResolvedValue([]);
- mockAnnotationsApi.create.mockResolvedValue(makeThread({ id: "created-1" }));
- const root = createRoot(container);
- const queryClient = makeQueryClient();
- const doc = makeDoc();
-
- await act(async () => {
- root.render(
-
-
- ,
- );
- });
- await flush();
- await flush();
-
- const selectButton = container.querySelector('[data-testid="mock-annotation-selection"]') as HTMLButtonElement | null;
- await act(async () => selectButton!.click());
- await flush();
-
- const composer = container.querySelector('[data-testid="document-annotation-composer"]') as HTMLTextAreaElement | null;
- expect(composer).not.toBeNull();
- await act(async () => setTextareaValue(composer!, "Submitted via shortcut"));
- await flush();
- await act(async () => dispatchSubmitShortcut(composer!));
- await flush();
- await flush();
-
- expect(mockAnnotationsApi.create).toHaveBeenCalledWith("issue-1", "plan", {
- baseRevisionId: "rev-4",
- baseRevisionNumber: 4,
- selector: mockPendingAnchor.selector,
- body: "Submitted via shortcut",
- });
- });
-
- it("submits a reply with ⌘↵", async () => {
- mockAnnotationsApi.list.mockResolvedValue([makeThread({ id: "open-1" })]);
- mockAnnotationsApi.addComment.mockResolvedValue(makeThread({ id: "open-1" }).comments[0]);
- const root = createRoot(container);
- const queryClient = makeQueryClient();
- const doc = makeDoc();
-
- await act(async () => {
- root.render(
-
-
- ,
- );
- });
- await flush();
- await flush();
-
- const openThread = container.querySelector('[data-thread-id="open-1"]') as HTMLElement | null;
- await act(async () => openThread!.click());
- await flush();
-
- const reply = container.querySelector(
- '[data-testid="document-annotation-reply-open-1"]',
- ) as HTMLTextAreaElement | null;
- expect(reply).not.toBeNull();
- await act(async () => setTextareaValue(reply!, "Replying via shortcut"));
- await flush();
- await act(async () => dispatchSubmitShortcut(reply!));
- await flush();
- await flush();
-
- expect(mockAnnotationsApi.addComment).toHaveBeenCalledWith("issue-1", "plan", "open-1", {
- body: "Replying via shortcut",
- });
- });
-
- it("keeps a reply draft visible when submitting the reply fails", async () => {
- mockAnnotationsApi.list.mockResolvedValue([makeThread({ id: "open-1" })]);
- mockAnnotationsApi.addComment.mockRejectedValue(new Error("Failed to add reply"));
- const root = createRoot(container);
- const queryClient = makeQueryClient();
- const doc = makeDoc();
-
- await act(async () => {
- root.render(
-
-
- ,
- );
- });
- await flush();
- await flush();
-
- const openThread = container.querySelector('[data-thread-id="open-1"]') as HTMLElement | null;
- expect(openThread).not.toBeNull();
- await act(async () => openThread!.click());
- await flush();
-
- const reply = container.querySelector(
- '[data-testid="document-annotation-reply-open-1"]',
- ) as HTMLTextAreaElement | null;
- expect(reply).not.toBeNull();
- await act(async () => setTextareaValue(reply!, "Reply should stay visible"));
- await flush();
-
- const replyButton = Array.from(container.querySelectorAll("button")).find(
- (button) => button.textContent === "Reply",
- );
- expect(replyButton).not.toBeUndefined();
- await act(async () => replyButton!.click());
- await flush();
- await flush();
-
- const replyAfterFailure = container.querySelector(
- '[data-testid="document-annotation-reply-open-1"]',
- ) as HTMLTextAreaElement | null;
- expect(replyAfterFailure).not.toBeNull();
- expect(replyAfterFailure!.value).toBe("Reply should stay visible");
- expect(container.querySelector('[data-testid="document-annotation-error"]')?.textContent)
- .toContain("Failed to add reply");
- });
-
- it("shows resolve and reopen actions and updates thread status", async () => {
- mockAnnotationsApi.list.mockResolvedValue([
- makeThread({ id: "open-1" }),
- makeThread({ id: "resolved-1", status: "resolved" }),
- ]);
- mockAnnotationsApi.updateStatus.mockResolvedValue(makeThread({ id: "open-1", status: "resolved" }));
- const root = createRoot(container);
- const queryClient = makeQueryClient();
- const doc = makeDoc();
-
- await act(async () => {
- root.render(
-
-
- ,
- );
- });
- await flush();
- await flush();
-
- const openThread = container.querySelector('[data-thread-id="open-1"]') as HTMLElement | null;
- expect(openThread).not.toBeNull();
- await act(async () => openThread!.click());
- await flush();
-
- const resolveButton = Array.from(container.querySelectorAll("button")).find(
- (button) => /\bResolve\b/.test(button.textContent ?? ""),
- );
- expect(resolveButton).not.toBeUndefined();
- await act(async () => resolveButton!.click());
- await flush();
- expect(mockAnnotationsApi.updateStatus).toHaveBeenCalledWith("issue-1", "plan", "open-1", "resolved");
-
- // Resolved threads stay in the same list (filter tabs were removed).
- const resolvedThread = container.querySelector('[data-thread-id="resolved-1"]') as HTMLElement | null;
- expect(resolvedThread).not.toBeNull();
- await act(async () => resolvedThread!.click());
- await flush();
-
- const reopenButton = Array.from(container.querySelectorAll("button")).find(
- (button) => button.textContent?.includes("Reopen"),
- );
- expect(reopenButton).not.toBeUndefined();
- await act(async () => reopenButton!.click());
- await flush();
- expect(mockAnnotationsApi.updateStatus).toHaveBeenCalledWith("issue-1", "plan", "resolved-1", "open");
- });
-
- it("renders the mobile annotation panel through the sheet path", async () => {
- const originalMatchMedia = window.matchMedia;
- Object.defineProperty(window, "matchMedia", {
- configurable: true,
- value: vi.fn().mockImplementation((query: string) => ({
- matches: true,
- media: query,
- onchange: null,
- addEventListener: vi.fn(),
- removeEventListener: vi.fn(),
- addListener: vi.fn(),
- removeListener: vi.fn(),
- dispatchEvent: vi.fn(),
- })),
- });
- mockAnnotationsApi.list.mockResolvedValue([makeThread()]);
- const root = createRoot(container);
- const queryClient = makeQueryClient();
- const doc = makeDoc();
-
- try {
- await act(async () => {
- root.render(
-
-
- ,
- );
- });
- await flush();
- await flush();
-
- const sheet = container.querySelector('[data-slot="sheet-content"]');
- expect(sheet).not.toBeNull();
- expect(sheet?.getAttribute("data-side")).toBe("bottom");
- expect(sheet?.className).toContain("paperclip-doc-annotation-sheet");
- expect(sheet?.className).toContain("z-(--z-60)");
- expect(sheet?.className).toContain("bg-popover");
- } finally {
- Object.defineProperty(window, "matchMedia", {
- configurable: true,
- value: originalMatchMedia,
- });
- }
- });
-});
diff --git a/ui/src/components/IssueRunLedger.test.tsx b/ui/src/components/IssueRunLedger.test.tsx
deleted file mode 100644
index d194e6d6d4d..00000000000
--- a/ui/src/components/IssueRunLedger.test.tsx
+++ /dev/null
@@ -1,683 +0,0 @@
-// @vitest-environment jsdom
-
-import { act } from "react";
-import type { ComponentProps, ReactNode } from "react";
-import { createRoot, type Root } from "react-dom/client";
-import type { ActivityEvent, Issue, RunLivenessState } from "@paperclipai/shared";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import type { RunForIssue } from "../api/activity";
-import type { ActiveRunForIssue } from "../api/heartbeats";
-import { IssueRunLedgerContent } from "./IssueRunLedger";
-import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils";
-
-vi.mock("@/lib/router", () => ({
- Link: ({ children, to, ...props }: { children: ReactNode; to: string } & ComponentProps<"a">) => (
- {children}
- ),
-}));
-
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
-
-let container: HTMLDivElement;
-let root: Root;
-
-beforeEach(() => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date("2026-04-18T20:00:00.000Z"));
- container = document.createElement("div");
- document.body.appendChild(container);
- root = createRoot(container);
-});
-
-afterEach(() => {
- act(() => root.unmount());
- container.remove();
- vi.useRealTimers();
-});
-
-function render(ui: ReactNode) {
- act(() => {
- root.render(ui);
- });
-}
-
-function createRun(overrides: Partial = {}): RunForIssue {
- return {
- runId: "run-00000000",
- status: "succeeded",
- agentId: "agent-1",
- adapterType: "codex_local",
- startedAt: "2026-04-18T19:58:00.000Z",
- finishedAt: "2026-04-18T19:59:00.000Z",
- createdAt: "2026-04-18T19:58:00.000Z",
- invocationSource: "assignment",
- usageJson: null,
- resultJson: null,
- livenessState: "advanced",
- livenessReason: "Run produced concrete action evidence: 2 activity event(s)",
- continuationAttempt: 0,
- lastUsefulActionAt: "2026-04-18T19:59:00.000Z",
- nextAction: null,
- ...overrides,
- };
-}
-
-function createActivity(overrides: Partial = {}): ActivityEvent {
- return {
- id: "activity-1",
- companyId: "company-1",
- actorType: "system",
- actorId: "system",
- action: "issue.updated",
- entityType: "issue",
- entityId: "issue-1",
- agentId: null,
- runId: null,
- details: null,
- createdAt: new Date("2026-04-18T19:57:00.000Z"),
- ...overrides,
- };
-}
-
-function createIssue(overrides: Partial = {}): Issue {
- return {
- id: "issue-1",
- companyId: "company-1",
- projectId: null,
- projectWorkspaceId: null,
- goalId: null,
- parentId: null,
- title: "Child issue",
- description: null,
- status: "todo",
- priority: "medium",
- reviewPolicy: null,
- assigneeAgentId: null,
- assigneeUserId: null,
- responsibleUserId: null,
- checkoutRunId: null,
- executionRunId: null,
- executionAgentNameKey: null,
- executionLockedAt: null,
- createdByAgentId: null,
- createdByUserId: null,
- issueNumber: null,
- identifier: "PAP-1",
- requestDepth: 0,
- billingCode: null,
- assigneeAdapterOverrides: null,
- executionWorkspaceId: null,
- executionWorkspacePreference: null,
- executionWorkspaceSettings: null,
- startedAt: null,
- completedAt: null,
- cancelledAt: null,
- hiddenAt: null,
- createdAt: new Date("2026-04-18T19:00:00.000Z"),
- updatedAt: new Date("2026-04-18T19:00:00.000Z"),
- ...overrides,
- workMode: overrides.workMode ?? "standard",
- };
-}
-
-function createActiveRun(overrides: Partial = {}): ActiveRunForIssue {
- return {
- id: "run-live-1",
- status: "running",
- invocationSource: "assignment",
- triggerDetail: null,
- startedAt: "2026-04-18T19:58:00.000Z",
- finishedAt: null,
- createdAt: "2026-04-18T19:58:00.000Z",
- agentId: "agent-1",
- agentName: "CodexCoder",
- adapterType: "codex_local",
- outputSilence: {
- lastOutputAt: "2026-04-18T19:00:00.000Z",
- lastOutputSeq: 4,
- lastOutputStream: "stdout",
- silenceStartedAt: "2026-04-18T19:30:00.000Z",
- silenceAgeMs: 45 * 60 * 1000,
- level: "critical",
- suspicionThresholdMs: 10 * 60 * 1000,
- criticalThresholdMs: 30 * 60 * 1000,
- snoozedUntil: null,
- evaluationIssueId: "issue-eval-1",
- evaluationIssueIdentifier: "PAP-404",
- evaluationIssueAssigneeAgentId: "agent-owner",
- },
- ...overrides,
- };
-}
-
-function renderLedger(props: Partial> = {}) {
- render(
- ,
- );
-}
-
-describe("IssueRunLedger", () => {
- it("renders every liveness state with exhausted continuation context", () => {
- const states: RunLivenessState[] = [
- "advanced",
- "plan_only",
- "empty_response",
- "blocked",
- "failed",
- "completed",
- "needs_followup",
- ];
-
- renderLedger({
- runs: states.map((state, index) =>
- createRun({
- runId: `run-${index}0000000`,
- createdAt: `2026-04-18T19:5${index}:00.000Z`,
- livenessState: state,
- livenessReason: state === "needs_followup"
- ? "Run produced useful output but no concrete action evidence; continuation attempts exhausted"
- : `state ${state}`,
- continuationAttempt: state === "needs_followup" ? 3 : 0,
- }),
- ),
- });
-
- expect(container.textContent).toContain("Advanced");
- expect(container.textContent).toContain("Plan only");
- expect(container.textContent).toContain("Empty response");
- expect(container.textContent).toContain("Blocked");
- expect(container.textContent).toContain("Failed");
- expect(container.textContent).toContain("Completed");
- expect(container.textContent).toContain("Needs follow-up");
- expect(container.textContent).toContain("Exhausted");
- expect(container.textContent).toContain("Continuation attempt 3");
- });
-
- it("renders historical runs without liveness metadata as unavailable", () => {
- renderLedger({
- runs: [
- createRun({
- livenessState: null,
- livenessReason: null,
- continuationAttempt: undefined,
- lastUsefulActionAt: null,
- nextAction: null,
- resultJson: null,
- }),
- ],
- });
-
- expect(container.textContent).toContain("No liveness data");
- expect(container.textContent).toContain("Stop Unavailable");
- expect(container.textContent).toContain("Last useful action Unavailable");
- });
-
- it("interleaves run rows and activity rows by timestamp", () => {
- renderLedger({
- runs: [
- createRun({
- runId: "run-oldest",
- startedAt: "2026-04-18T19:55:00.000Z",
- createdAt: "2026-04-18T19:55:00.000Z",
- }),
- createRun({
- runId: "run-newest",
- startedAt: "2026-04-18T19:59:00.000Z",
- createdAt: "2026-04-18T19:59:00.000Z",
- }),
- ],
- activityEvents: [
- createActivity({
- id: "activity-middle",
- action: "activity-middle",
- createdAt: new Date("2026-04-18T19:57:00.000Z"),
- }),
- ],
- renderActivityEvent: (event) => (
- {event.action}
- ),
- });
-
- const text = container.textContent ?? "";
- const newestIndex = text.indexOf("run-newe");
- const activityIndex = text.indexOf("activity-middle");
- const oldestIndex = text.indexOf("run-olde");
-
- expect(newestIndex).toBeGreaterThanOrEqual(0);
- expect(activityIndex).toBeGreaterThan(newestIndex);
- expect(oldestIndex).toBeGreaterThan(activityIndex);
- });
-
- it("shows live runs as pending final checks without missing-data language", () => {
- renderLedger({
- runs: [
- createRun({
- status: "running",
- finishedAt: null,
- livenessState: null,
- livenessReason: null,
- continuationAttempt: 0,
- lastUsefulActionAt: null,
- nextAction: null,
- resultJson: null,
- }),
- ],
- });
-
- expect(container.textContent).toContain("Running now by CodexCoder");
- expect(container.textContent).toContain("Checks after finish");
- expect(container.textContent).toContain("Last useful action No action recorded yet");
- expect(container.textContent).toContain("Stop Still running");
- expect(container.textContent).not.toContain("Liveness pending");
- expect(container.textContent).not.toContain("initial attempt");
- });
-
- it("surfaces scheduled retry timing and exhaustion state without opening logs", () => {
- renderLedger({
- runs: [
- createRun({
- runId: "run-scheduled",
- status: "scheduled_retry",
- finishedAt: null,
- livenessState: null,
- livenessReason: null,
- retryOfRunId: "run-root",
- scheduledRetryAt: "2026-04-18T20:15:00.000Z",
- scheduledRetryAttempt: 2,
- scheduledRetryReason: "transient_failure",
- }),
- createRun({
- runId: "run-exhausted",
- status: "failed",
- createdAt: "2026-04-18T19:57:00.000Z",
- retryOfRunId: "run-root",
- scheduledRetryAttempt: 4,
- scheduledRetryReason: "transient_failure",
- retryExhaustedReason: "Bounded retry exhausted after 4 scheduled attempts; no further automatic retry will be queued",
- }),
- ],
- });
-
- expect(container.textContent).toContain("Retry scheduled");
- expect(container.textContent).toContain("Attempt 2");
- expect(container.textContent).toContain("Transient failure");
- expect(container.textContent).toContain("Next retry");
- expect(container.textContent).toContain("Retry exhausted");
- expect(container.textContent).toContain("no further automatic retry will be queued");
- expect(container.textContent).toContain("Manual intervention required");
- expect(replayLeaks("Bounded retry exhausted after 4 scheduled attempts", container)).toEqual({ rendered: true, recorded: false });
- });
-
- it("labels max-turn stops and continuation retries without confusing them with per-run turns", () => {
- renderLedger({
- runs: [
- createRun({
- runId: "run-scheduled-continuation",
- status: "scheduled_retry",
- finishedAt: null,
- livenessState: null,
- livenessReason: null,
- retryOfRunId: "run-max-turns",
- scheduledRetryAt: "2026-04-18T20:15:00.000Z",
- scheduledRetryAttempt: 1,
- scheduledRetryReason: "max_turns_continuation",
- }),
- createRun({
- runId: "run-max-turns",
- resultJson: { stopReason: "max_turns_exhausted" },
- createdAt: "2026-04-18T19:57:00.000Z",
- }),
- createRun({
- runId: "run-continuation-exhausted",
- status: "failed",
- createdAt: "2026-04-18T19:56:00.000Z",
- retryOfRunId: "run-max-turns",
- scheduledRetryAttempt: 3,
- scheduledRetryReason: "max_turns_continuation",
- retryExhaustedReason: "Bounded retry exhausted after 3 scheduled attempts; no further automatic retry will be queued",
- }),
- ],
- });
-
- expect(container.textContent).toContain("Continuation scheduled");
- expect(container.textContent).toContain("Max-turn continuation");
- expect(container.textContent).toContain("Next continuation");
- expect(container.textContent).toContain("Stop max turns exhausted");
- expect(container.textContent).toContain("Continuation exhausted");
- });
-
- it("shows timeout, cancel, and budget stop reasons without raw logs", () => {
- renderLedger({
- runs: [
- createRun({
- runId: "run-timeout",
- resultJson: { stopReason: "timeout", timeoutFired: true, effectiveTimeoutSec: 30 },
- }),
- createRun({
- runId: "run-cancel",
- resultJson: { stopReason: "cancelled" },
- createdAt: "2026-04-18T19:57:00.000Z",
- }),
- createRun({
- runId: "run-budget",
- resultJson: { stopReason: "budget_paused" },
- createdAt: "2026-04-18T19:56:00.000Z",
- }),
- createRun({
- runId: "run-background-task",
- resultJson: { stopReason: "unmanaged_background_task_stopped" },
- createdAt: "2026-04-18T19:55:30.000Z",
- }),
- createRun({
- runId: "run-paused",
- resultJson: { stopReason: "paused" },
- createdAt: "2026-04-18T19:55:00.000Z",
- }),
- ],
- });
-
- expect(container.textContent).toContain("timeout (30s timeout)");
- expect(container.textContent).toContain("cancelled");
- expect(container.textContent).toContain("budget paused");
- expect(container.textContent).toContain("unmanaged background task stopped");
- expect(container.textContent).toContain("paused by board");
- });
-
- it("names the recorded cause of an adapter failure and keeps the plain label for older runs", () => {
- renderLedger({
- runs: [
- createRun({
- runId: "run-adapter-cause",
- status: "failed",
- errorCode: "adapter_failed",
- failureCause: "40001",
- resultJson: { stopReason: "adapter_failed" },
- }),
- createRun({
- runId: "run-adapter-legacy",
- status: "failed",
- errorCode: "adapter_failed",
- resultJson: { stopReason: "adapter_failed" },
- createdAt: "2026-04-18T19:57:00.000Z",
- }),
- createRun({
- runId: "run-adapter-malformed",
- status: "failed",
- errorCode: "adapter_failed",
- failureCause: "select * from secrets",
- resultJson: { stopReason: "adapter_failed" },
- createdAt: "2026-04-18T19:56:00.000Z",
- }),
- ],
- });
-
- expect(container.textContent).toContain("adapter failed (40001)");
- expect(container.textContent?.match(/adapter failed(?! \()/g)).toHaveLength(2);
- expect(container.textContent).not.toContain("secrets");
- });
-
- it("surfaces active and completed child issue summaries", () => {
- renderLedger({
- childIssues: [
- createIssue({ id: "child-1", identifier: "PAP-2", title: "Implement worker handoff", status: "in_progress" }),
- createIssue({ id: "child-2", identifier: "PAP-3", title: "Verify final report", status: "done" }),
- createIssue({ id: "child-3", identifier: "PAP-4", title: "Cancelled experiment", status: "cancelled" }),
- ],
- });
-
- expect(container.textContent).toContain("Child work");
- expect(container.textContent).toContain("1 active, 1 done, 1 cancelled");
- expect(container.textContent).toContain("PAP-2");
- expect(container.textContent).toContain("Implement worker handoff");
-
- renderLedger({
- childIssues: [
- createIssue({ id: "child-2", identifier: "PAP-3", title: "Verify final report", status: "done" }),
- createIssue({ id: "child-3", identifier: "PAP-4", title: "Cancelled experiment", status: "cancelled" }),
- ],
- });
-
- expect(container.textContent).toContain("all 2 terminal (1 done, 1 cancelled)");
- });
-
- it("shows the current execution instruction and clears stale instructions after a recorded successor", () => {
- const execution = {
- phase: "recovery_needed" as const, label: "Stopped", cause: "native_continuation_requires_reconciliation",
- lastConfirmedActivityAt: null, retryAt: null, attempt: 1, maxAttempts: 3,
- recoveryOwner: null, nextAction: "Saved work recovered. Send a message to continue.",
- permittedActions: ["inspect_run"] as const, predecessorRunId: null, successorRunId: null,
- };
- const stopped = createRun({ status: "failed", nextAction: "Repair the retained sandbox.",
- execution: { ...execution, permittedActions: ["inspect_run"] } });
- renderLedger({ runs: [stopped] });
- expect(container.textContent).toContain(execution.nextAction);
- expect(container.textContent).not.toContain("Repair the retained sandbox.");
- renderLedger({ runs: [{ ...stopped, execution: { ...stopped.execution!, phase: "completed",
- label: "Continued in another run", nextAction: null, successorRunId: "successor" } }] });
- expect(container.textContent).not.toContain("Next action:");
- });
-
- it("uses wrapping-friendly markup for long next action text", () => {
- renderLedger({
- runs: [
- createRun({
- nextAction: "Continue investigating this intentionally-long-next-action-token-that-needs-to-wrap-cleanly-on-mobile-and-desktop-without-overlapping-controls.",
- }),
- ],
- });
-
- const nextAction = [...container.querySelectorAll("span")]
- .find((node) => node.textContent?.includes("intentionally-long-next-action-token"));
- expect(nextAction?.className).toContain("break-words");
- expect(container.textContent).toContain("Next action:");
- });
-
- it("shows when older runs are clipped from the ledger", () => {
- renderLedger({
- runs: Array.from({ length: 22 }, (_, index) =>
- createRun({
- runId: `run-${index.toString().padStart(8, "0")}`,
- createdAt: `2026-04-18T19:${String(index).padStart(2, "0")}:00.000Z`,
- }),
- ),
- });
-
- expect(container.textContent).toContain("2 older items not shown");
- });
-
- it("renders legacy evaluation context with watchdog actions and a silence badge", () => {
- const onWatchdogDecision = vi.fn();
- renderLedger({
- runs: [createRun({ runId: "run-live-1", status: "running", finishedAt: null })],
- activeRun: createActiveRun(),
- onWatchdogDecision,
- });
-
- expect(container.textContent).toContain("Critical output silence");
- expect(container.textContent).toContain("PAP-404");
- expect(container.textContent).toContain("Critical silence");
- expect(container.textContent).toContain("Paperclip did not create new delegated recovery work");
- const watchdogBanner = Array.from(container.querySelectorAll("p"))
- .find((node) => node.textContent?.includes("Critical output silence"))
- ?.closest("div");
- expect(watchdogBanner?.className).toContain("border-red-500/30");
- expect(watchdogBanner?.className).toContain("bg-red-500/10");
-
- const continueButton = Array.from(container.querySelectorAll("button")).find(
- (button) => button.textContent?.includes("Continue monitoring"),
- );
- expect(continueButton).not.toBeUndefined();
- act(() => {
- continueButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
- });
- expect(onWatchdogDecision).toHaveBeenCalledWith({
- runId: "run-live-1",
- decision: "continue",
- evaluationIssueId: "issue-eval-1",
- });
- });
-
- it.each([
- {
- level: "suspicious" as const,
- heading: "Output silence watchdog warning",
- badge: "Output silence",
- },
- {
- level: "critical" as const,
- heading: "Critical output silence",
- badge: "Critical silence",
- },
- ])("renders a $level UI-only signal without an evaluation-task link", ({ level, heading, badge }) => {
- const onWatchdogDecision = vi.fn();
- const activeRun = createActiveRun();
- renderLedger({
- runs: [createRun({ runId: activeRun.id, status: "running", finishedAt: null })],
- activeRun: createActiveRun({
- outputSilence: {
- ...activeRun.outputSilence!,
- level,
- evaluationIssueId: null,
- evaluationIssueIdentifier: null,
- evaluationIssueAssigneeAgentId: null,
- },
- }),
- onWatchdogDecision,
- });
-
- expect(container.textContent).toContain(heading);
- expect(container.textContent).toContain(badge);
- expect(container.textContent).toContain("Paperclip did not create or assign a recovery task");
- expect(container.textContent).not.toContain("PAP-404");
- expect(container.querySelector('a[href^="/issues/"]')).toBeNull();
- expect(container.textContent).toContain("Continue monitoring");
- expect(container.textContent).toContain("Snooze 1h");
- expect(container.textContent).toContain("Mark false positive");
-
- const continueButton = Array.from(container.querySelectorAll("button")).find(
- (button) => button.textContent?.includes("Continue monitoring"),
- );
- act(() => {
- continueButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
- });
- expect(onWatchdogDecision).toHaveBeenCalledWith({
- runId: "run-live-1",
- decision: "continue",
- evaluationIssueId: null,
- });
- });
-
- it("hides watchdog decision actions for known non-owner viewers", () => {
- const onWatchdogDecision = vi.fn();
- renderLedger({
- runs: [createRun({ runId: "run-live-1", status: "running", finishedAt: null })],
- activeRun: createActiveRun(),
- canRecordWatchdogDecisions: false,
- onWatchdogDecision,
- });
-
- expect(container.textContent).toContain("Critical output silence");
- expect(container.textContent).toContain("PAP-404");
- expect(container.textContent).not.toContain("Continue monitoring");
- expect(container.textContent).not.toContain("Snooze 1h");
- expect(container.textContent).not.toContain("Mark false positive");
- expect(
- Array.from(container.querySelectorAll("button")).filter((button) =>
- /continue|snooze|false positive/i.test(button.textContent ?? ""),
- ),
- ).toHaveLength(0);
- expect(onWatchdogDecision).not.toHaveBeenCalled();
- });
-
- it("surfaces the responsible user a run acts on behalf of", () => {
- renderLedger({
- runs: [createRun({ runId: "run-obo-1", responsibleUserId: "user-2" })],
- resolveUserLabel: (userId) => (userId === "user-2" ? "Ada Lovelace" : null),
- });
-
- const chip = container.querySelector('[data-testid="run-on-behalf-of"]');
- expect(chip).not.toBeNull();
- expect(chip?.textContent).toContain("on behalf of");
- expect(chip?.textContent).toContain("Ada Lovelace");
- });
-
- it("omits the on-behalf-of chip when the run has no responsible user", () => {
- renderLedger({
- runs: [createRun({ runId: "run-obo-2", responsibleUserId: null })],
- resolveUserLabel: () => "Ada Lovelace",
- });
-
- expect(container.querySelector('[data-testid="run-on-behalf-of"]')).toBeNull();
- });
-
- it("renders actionable copy for a responsible-user-unauthorized run failure", () => {
- renderLedger({
- runs: [
- createRun({
- runId: "run-denied-1",
- status: "failed",
- livenessState: "failed",
- responsibleUserId: "user-2",
- errorCode: "RESPONSIBLE_USER_UNAUTHORIZED",
- }),
- ],
- resolveUserLabel: () => "Ada Lovelace",
- });
-
- const notice = container.querySelector('[data-testid="responsible-user-denial-notice"]');
- expect(notice).not.toBeNull();
- expect(notice?.getAttribute("data-denial-tone")).toBe("unauthorized");
- expect(notice?.textContent).toContain("Ada Lovelace");
- expect(notice?.textContent).toContain("Responsible user not authorized");
- });
-
- it("steers the responsible-user-unavailable failure toward marking work blocked", () => {
- renderLedger({
- runs: [
- createRun({
- runId: "run-denied-2",
- status: "failed",
- livenessState: "failed",
- responsibleUserId: "user-3",
- errorCode: "RESPONSIBLE_USER_UNAVAILABLE",
- }),
- ],
- resolveUserLabel: () => "Grace Hopper",
- });
-
- const notice = container.querySelector('[data-testid="responsible-user-denial-notice"]');
- expect(notice).not.toBeNull();
- expect(notice?.getAttribute("data-denial-tone")).toBe("unavailable");
- expect(notice?.textContent?.toLowerCase()).toContain("blocked");
- });
-
- it("does not render a denial notice for a generic agent failure", () => {
- renderLedger({
- runs: [
- createRun({
- runId: "run-denied-3",
- status: "failed",
- livenessState: "failed",
- errorCode: "budget_blocked",
- }),
- ],
- });
-
- expect(container.querySelector('[data-testid="responsible-user-denial-notice"]')).toBeNull();
- });
-});
diff --git a/ui/src/components/KanbanBoard.test.tsx b/ui/src/components/KanbanBoard.test.tsx
deleted file mode 100644
index a6b456222d4..00000000000
--- a/ui/src/components/KanbanBoard.test.tsx
+++ /dev/null
@@ -1,250 +0,0 @@
-// @vitest-environment jsdom
-
-import { createRoot, type Root } from "react-dom/client";
-import { flushSync } from "react-dom";
-import type { Issue, IssueStatus } from "@paperclipai/shared";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { getKanbanColumnTone, KanbanBoard, resolveKanbanTargetStatus } from "./KanbanBoard";
-import { applyOptimisticIssueFieldUpdate } from "../lib/optimistic-issue-comments";
-
-vi.mock("@/lib/router", () => ({
- Link: ({
- children,
- to,
- disableIssueQuicklook: _disableIssueQuicklook,
- ...props
- }: React.AnchorHTMLAttributes & {
- to: string;
- disableIssueQuicklook?: boolean;
- }) => (
- {children}
- ),
-}));
-
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
-
-const mountedRoots: Root[] = [];
-
-function act(callback: () => void): void {
- flushSync(callback);
-}
-
-function createIssue(index: number, status: IssueStatus): Issue {
- return {
- id: `issue-${status}-${index}`,
- identifier: `PAP-${index}`,
- companyId: "company-1",
- projectId: null,
- projectWorkspaceId: null,
- goalId: null,
- parentId: null,
- title: `Issue ${index}`,
- description: null,
- status,
- workMode: "standard",
- priority: "medium",
- reviewPolicy: null,
- assigneeAgentId: index === 1 ? "agent-1" : null,
- assigneeUserId: null,
- responsibleUserId: null,
- createdByAgentId: null,
- createdByUserId: null,
- issueNumber: index,
- requestDepth: 0,
- billingCode: null,
- assigneeAdapterOverrides: null,
- executionWorkspaceId: null,
- executionWorkspacePreference: null,
- executionWorkspaceSettings: null,
- checkoutRunId: null,
- executionRunId: null,
- executionAgentNameKey: null,
- executionLockedAt: null,
- startedAt: null,
- completedAt: null,
- cancelledAt: null,
- hiddenAt: null,
- createdAt: new Date("2026-05-05T00:00:00.000Z"),
- updatedAt: new Date("2026-05-05T00:00:00.000Z"),
- labels: [],
- labelIds: [],
- myLastTouchAt: null,
- lastExternalCommentAt: null,
- lastActivityAt: null,
- isUnreadForMe: false,
- };
-}
-
-function createIssues(count: number, status: IssueStatus): Issue[] {
- return Array.from({ length: count }, (_, index) => createIssue(index + 1, status));
-}
-
-function renderBoard(
- props: Partial> & { issues: Issue[] },
-) {
- const container = document.createElement("div");
- document.body.appendChild(container);
- const root = createRoot(container);
- mountedRoots.push(root);
-
- const render = (nextProps: Partial> & { issues: Issue[] }) => {
- act(() => {
- root.render(
- ,
- );
- });
- };
-
- render(props);
-
- return { container, root, render };
-}
-
-describe("KanbanBoard", () => {
- beforeEach(() => {
- document.body.innerHTML = "";
- });
-
- afterEach(() => {
- while (mountedRoots.length > 0) {
- const root = mountedRoots.pop();
- if (root) {
- act(() => root.unmount());
- }
- }
- document.body.innerHTML = "";
- });
-
- it("limits visible cards and reveals more cards per column", () => {
- const { container } = renderBoard({
- issues: createIssues(60, "todo"),
- compactCards: true,
- initialVisibleCount: 50,
- revealIncrement: 50,
- });
-
- expect(container.textContent).toContain("Showing 50 of 60");
- expect(container.textContent).toContain("Show 10 more");
- expect(container.textContent).toContain("Issue 50");
- expect(container.textContent).not.toContain("Issue 51");
-
- const showMoreButton = Array.from(container.querySelectorAll("button")).find((button) =>
- button.textContent?.includes("Show 10 more"),
- );
- expect(showMoreButton).toBeTruthy();
-
- act(() => {
- showMoreButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
- });
-
- expect(container.textContent).toContain("Issue 60");
- expect(container.textContent).not.toContain("Show 10 more");
- });
-
- it("resets visible counts when the column page size changes", () => {
- const issues = createIssues(60, "todo");
- const { container, render } = renderBoard({
- issues,
- initialVisibleCount: 50,
- revealIncrement: 50,
- });
-
- const showMoreButton = Array.from(container.querySelectorAll("button")).find((button) =>
- button.textContent?.includes("Show 10 more"),
- );
- expect(showMoreButton).toBeTruthy();
-
- act(() => {
- showMoreButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
- });
-
- expect(container.textContent).toContain("Issue 60");
-
- render({
- issues,
- initialVisibleCount: 10,
- revealIncrement: 10,
- });
-
- expect(container.textContent).toContain("Showing 10 of 60");
- expect(container.textContent).toContain("Show 10 more");
- expect(container.textContent).toContain("Issue 10");
- expect(container.textContent).not.toContain("Issue 11");
- });
-
- it("renders collapsed statuses as rails without cards", () => {
- const { container } = renderBoard({
- issues: createIssues(3, "done"),
- collapsedStatuses: ["done"],
- });
-
- expect(container.textContent).toContain("Done");
- expect(container.textContent).toContain("3");
- expect(container.textContent).not.toContain("Issue 1");
- });
-
- it("gives every column a status-hued tone", () => {
- expect(getKanbanColumnTone("backlog").body).toContain("bg-muted/30");
- expect(getKanbanColumnTone("todo").body).toContain("amber");
- expect(getKanbanColumnTone("in_progress").body).toContain("blue");
- expect(getKanbanColumnTone("in_review").body).toContain("violet");
- expect(getKanbanColumnTone("blocked").body).toContain("red");
- expect(getKanbanColumnTone("done").body).toContain("green");
- expect(getKanbanColumnTone("cancelled").body).toContain("bg-muted/25");
- expect(getKanbanColumnTone("cancelled").card).toContain("opacity-80");
- });
-
- it("ghosts cancelled lane cards", () => {
- const { container } = renderBoard({
- issues: createIssues(1, "cancelled"),
- });
-
- const card = container.querySelector('a[href="/issues/PAP-1"]')?.parentElement;
-
- expect(card?.className).toContain("bg-muted/35");
- expect(card?.className).toContain("opacity-80");
- });
-
- it("keeps core issue signals in compact cards", () => {
- const { container } = renderBoard({
- issues: createIssues(1, "todo"),
- compactCards: true,
- });
-
- expect(container.textContent).toContain("PAP-1");
- expect(container.textContent).toContain("Issue 1");
- expect(container.textContent).toContain("Codex");
- expect(container.textContent).toContain("Live");
- });
-
- it("resolves drop targets from status rails and cards", () => {
- const issues = [
- createIssue(1, "todo"),
- createIssue(2, "blocked"),
- ];
-
- expect(resolveKanbanTargetStatus("done", issues)).toBe("done");
- expect(resolveKanbanTargetStatus("issue-blocked-2", issues)).toBe("blocked");
- expect(resolveKanbanTargetStatus("missing", issues)).toBeNull();
- });
-
- it("moves a cached card into its new column before the server responds", () => {
- const issue = { ...createIssue(1, "todo"), displayStatus: "todo" as const };
- const { container, render } = renderBoard({ issues: [issue] });
- const column = () => container.querySelector('a[href="/issues/PAP-1"]')?.closest('[data-issue-row-details]')?.parentElement?.parentElement;
- expect(column()?.textContent).toContain("Todo");
- render({ issues: [applyOptimisticIssueFieldUpdate(issue, { status: "done" })!] });
- expect(column()?.textContent).toContain("Done");
- });
-});
-
-
-it("keeps Monitoring derived rather than allowing a drag to manufacture it", () => {
- expect(resolveKanbanTargetStatus("monitoring", [])).toBeNull();
-});
diff --git a/ui/src/components/WorkspaceAccessCard.test.tsx b/ui/src/components/WorkspaceAccessCard.test.tsx
deleted file mode 100644
index f822d3e6555..00000000000
--- a/ui/src/components/WorkspaceAccessCard.test.tsx
+++ /dev/null
@@ -1,211 +0,0 @@
-// @vitest-environment jsdom
-
-import { flushSync } from "react-dom";
-import { createRoot } from "react-dom/client";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { WorkspaceAccessCard } from "./WorkspaceAccessCard";
-import type { WorkspaceAccessState } from "../lib/workspace-access-state";
-
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
-
-function act(callback: () => void) {
- flushSync(callback);
-}
-
-function accessState(overrides: Partial = {}): WorkspaceAccessState {
- return {
- state: "ready",
- title: "Ready",
- description: "Opening the workspace signs you in to the cloned board without a password.",
- action: { kind: "open", label: "Open workspace" },
- handoffAvailable: true,
- ...overrides,
- };
-}
-
-describe("WorkspaceAccessCard", () => {
- let container: HTMLDivElement;
-
- beforeEach(() => {
- container = document.createElement("div");
- document.body.appendChild(container);
- });
-
- afterEach(() => {
- document.body.innerHTML = "";
- });
-
- function renderCard(props: Partial[0]> = {}) {
- const handlers = {
- onOpen: vi.fn(),
- onStart: vi.fn(),
- onRepair: vi.fn(),
- onViewLogs: vi.fn(),
- };
- const root = createRoot(container);
- act(() => {
- root.render();
- });
- const button = container.querySelector("button");
- return { ...handlers, root, button };
- }
-
- function findButton(label: string) {
- return Array.from(container.querySelectorAll("button")).find(
- (candidate) => candidate.textContent?.trim() === label,
- );
- }
-
- it("renders the ready state and opens without asking for a password", () => {
- const { onOpen, root } = renderCard();
- const card = container.querySelector("[data-testid='workspace-access-card']");
- expect(card?.getAttribute("data-state")).toBe("ready");
- expect(container.textContent).toContain("Ready");
- expect(container.textContent).toContain("single-use login handoff");
-
- const button = findButton("Open workspace");
- expect(button).toBeDefined();
- act(() => button!.click());
- expect(onOpen).toHaveBeenCalledTimes(1);
-
- act(() => root.unmount());
- });
-
- it("keeps a superseded repair failure visible without hiding the open action", () => {
- const { onOpen, onViewLogs, root } = renderCard({
- access: accessState({
- secondaryNotice: {
- title: "Repair failed",
- description: "The repair stopped during managed_restart. The pre-repair backup was kept.",
- action: { kind: "view_logs", label: "View repair log" },
- },
- }),
- });
-
- const openButton = findButton("Open workspace");
- const logButton = findButton("View repair log");
- expect(openButton).toBeDefined();
- expect(logButton).toBeDefined();
- expect(container.querySelector("[data-testid='workspace-access-secondary-notice']")?.textContent)
- .toContain("pre-repair backup was kept");
-
- act(() => openButton!.click());
- act(() => logButton!.click());
- expect(onOpen).toHaveBeenCalledTimes(1);
- expect(onViewLogs).toHaveBeenCalledTimes(1);
- act(() => root.unmount());
- });
-
- it("labels the credential fallback accurately when no handoff is available", () => {
- const { root } = renderCard({
- access: accessState({
- handoffAvailable: false,
- description: "Opening the board will ask for the credentials captured in this snapshot.",
- }),
- });
- expect(container.textContent).toContain("snapshot-local credentials captured");
- expect(container.textContent).not.toContain("single-use login handoff");
- act(() => root.unmount());
- });
-
- it("gives provisioning, degraded, and failed states their own safe action", () => {
- const cases = [
- {
- access: accessState({
- state: "provisioning" as const,
- title: "Provisioning database",
- action: { kind: "start" as const, label: "Start workspace" },
- }),
- label: "Start workspace",
- handlerKey: "onStart" as const,
- },
- {
- access: accessState({
- state: "degraded" as const,
- title: "Workspace is degraded",
- action: { kind: "repair" as const, label: "Repair workspace" },
- }),
- label: "Repair workspace",
- handlerKey: "onRepair" as const,
- },
- {
- access: accessState({
- state: "failed" as const,
- title: "Repair failed",
- action: { kind: "view_logs" as const, label: "View repair log" },
- }),
- label: "View repair log",
- handlerKey: "onViewLogs" as const,
- },
- ];
-
- for (const testCase of cases) {
- const rendered = renderCard({ access: testCase.access });
- expect(container.textContent).toContain(testCase.access.title);
- const button = findButton(testCase.label);
- expect(button).toBeDefined();
- expect(button!.disabled).toBe(false);
- act(() => button!.click());
- expect(rendered[testCase.handlerKey]).toHaveBeenCalledTimes(1);
- act(() => rendered.root.unmount());
- container.innerHTML = "";
- }
- });
-
- it("offers nothing clickable while a repair is already running", () => {
- const { root } = renderCard({
- access: accessState({
- state: "repairing",
- title: "Repairing workspace database",
- action: { kind: "wait", label: "Repair in progress" },
- }),
- });
- expect(findButton("Repair in progress")?.disabled).toBe(true);
- expect(
- container.querySelector("[data-testid='workspace-access-badge']")?.textContent,
- ).toContain("Repairing");
- act(() => root.unmount());
- });
-
- it("does not show a provisioning badge or spinner when the workspace can be started", () => {
- const { root } = renderCard({
- access: accessState({
- state: "stopped",
- title: "Workspace is not running",
- description: "Start the workspace runtime to publish its board.",
- action: { kind: "start", label: "Start workspace" },
- }),
- });
-
- const badge = container.querySelector("[data-testid='workspace-access-badge']");
- expect(badge).toBeNull();
- expect(container.querySelector(".animate-spin")).toBeNull();
- expect(findButton("Start workspace")).toBeDefined();
- act(() => root.unmount());
- });
-
- it("always names the state and the cause instead of a bare failure", () => {
- const { root } = renderCard({
- access: accessState({
- state: "failed",
- title: "Database provisioning failed",
- description: "The clone failed during restore. Repairing replaces only the isolated database.",
- action: { kind: "repair", label: "Repair workspace" },
- }),
- errorMessage: "Failed to open the workspace.",
- });
- expect(container.textContent).toContain("Database provisioning failed");
- expect(container.textContent).toContain("failed during restore");
- expect(
- container.querySelector("[data-testid='workspace-access-error']")?.textContent,
- ).toContain("Failed to open the workspace.");
- act(() => root.unmount());
- });
-
- it("disables the action while the caller reports it busy", () => {
- const { root } = renderCard({ isBusy: true });
- expect(findButton("Open workspace")?.disabled).toBe(true);
- act(() => root.unmount());
- });
-});
diff --git a/ui/src/components/WorkspaceFileBrowser.test.tsx b/ui/src/components/WorkspaceFileBrowser.test.tsx
deleted file mode 100644
index 375ac365a59..00000000000
--- a/ui/src/components/WorkspaceFileBrowser.test.tsx
+++ /dev/null
@@ -1,1014 +0,0 @@
-// @vitest-environment jsdom
-
-import { useState, type ComponentProps } from "react";
-import { flushSync } from "react-dom";
-import { createRoot } from "react-dom/client";
-import type { Root } from "react-dom/client";
-import type { Project, ProjectWorkspace, WorkspaceFileListDirectoryItem, WorkspaceFileListFileItem, WorkspaceFileListItem, WorkspaceFileListResponse } from "@paperclipai/shared";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { WorkspaceFileBrowser, describeUnavailable } from "./WorkspaceFileBrowser";
-import { ApiError } from "@/api/client";
-
-function act(callback: () => void | Promise) {
- let result: void | Promise | undefined;
- flushSync(() => {
- result = callback();
- });
- return result;
-}
-
-/**
- * Waits on the condition, not on a fixed number of turns. A hand-rolled retry
- * loop is ample on an idle machine and not when the suite runs many workers in
- * parallel: it gives up after N turns and reports a failure on behaviour that
- * works. `vi.waitFor` retries against a time budget, so a loaded worker gets
- * more turns instead.
- *
- * Same replacement as #11499 and #11521, which fixed the shorter-budget
- * instances of this in the routing tests.
- *
- * This was a reimplementation of `vi.waitFor` down to rethrowing the last
- * error, differing only in bounding on turns rather than on time.
- */
-async function waitForExpectation(assertion: () => void) {
- await vi.waitFor(assertion);
-}
-
-const useQueryMock = vi.fn();
-const cancelQueriesMock = vi.fn(() => Promise.resolve());
-const LIST_LIMIT = 100;
-
-vi.mock("@tanstack/react-query", async () => {
- const actual = await vi.importActual("@tanstack/react-query");
- return {
- ...actual,
- useQuery: (options: unknown) => useQueryMock(options),
- useQueries: ({ queries }: { queries: unknown[] }) => queries.map((options) => useQueryMock(options)),
- useQueryClient: () => ({ cancelQueries: cancelQueriesMock }),
- };
-});
-
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
-
-function createItem(overrides: Partial = {}): WorkspaceFileListFileItem {
- return {
- kind: "file",
- provider: "git_worktree",
- title: "IssueDetail.tsx",
- relativePath: "ui/src/pages/IssueDetail.tsx",
- displayPath: "ui/src/pages/IssueDetail.tsx",
- workspaceLabel: "Isolated workspace",
- workspaceKind: "execution_workspace",
- workspaceId: "ws-1",
- contentType: "text/plain; charset=utf-8",
- byteSize: 2048,
- modifiedAt: new Date(Date.now() - 120_000).toISOString(),
- previewKind: "text",
- capabilities: { preview: true, download: true, listChildren: false },
- ...overrides,
- };
-}
-
-function createDirectoryItem(overrides: Partial = {}): WorkspaceFileListDirectoryItem {
- return {
- kind: "directory",
- provider: "git_worktree",
- title: "src",
- relativePath: "ui/src",
- displayPath: "ui/src/",
- workspaceLabel: "Isolated workspace",
- workspaceKind: "execution_workspace",
- workspaceId: "ws-1",
- contentType: null,
- byteSize: null,
- modifiedAt: null,
- previewKind: "unsupported",
- capabilities: { preview: false, download: false, listChildren: true },
- ...overrides,
- };
-}
-
-function availableResponse(items: WorkspaceFileListItem[], truncated = false): WorkspaceFileListResponse {
- return {
- kind: "workspace_file_list",
- state: "available",
- workspace: {
- provider: "git_worktree",
- workspaceLabel: "Isolated workspace",
- workspaceKind: "execution_workspace",
- workspaceId: "ws-1",
- },
- query: { workspace: "auto", mode: "changed", q: null, limit: 100, offset: 0 },
- items,
- scannedCount: items.length,
- truncated,
- };
-}
-
-function availableAllResponse(
- items: WorkspaceFileListItem[],
- path: string | null,
- truncated = false,
- offset = 0,
-): WorkspaceFileListResponse {
- const response = availableResponse(items, truncated);
- response.query = { ...response.query, mode: "all", path, offset };
- return response;
-}
-
-function createWorkspace(overrides: Partial = {}): ProjectWorkspace {
- return {
- id: "workspace-content",
- companyId: "company-1",
- projectId: "project-content",
- name: "Paperclip Content",
- sourceType: "local_path",
- cwd: "/srv/paperclip/home/paperclipai/paperclip-content",
- repoUrl: null,
- repoRef: null,
- defaultRef: null,
- visibility: "default",
- setupCommand: null,
- cleanupCommand: null,
- remoteProvider: null,
- remoteWorkspaceRef: null,
- sharedWorkspaceKey: null,
- metadata: null,
- runtimeConfig: null,
- isPrimary: true,
- createdAt: new Date("2026-06-08T00:00:00.000Z"),
- updatedAt: new Date("2026-06-08T00:00:00.000Z"),
- ...overrides,
- };
-}
-
-function createProject(overrides: Partial = {}): Project {
- const workspace = createWorkspace();
- return {
- id: "project-content",
- companyId: "company-1",
- urlKey: "paperclip-content",
- goalId: null,
- goalIds: [],
- goals: [],
- name: "Paperclip Content",
- description: null,
- status: "in_progress",
- leadAgentId: null,
- targetDate: null,
- color: null,
- icon: null,
- env: null,
- pauseReason: null,
- pausedAt: null,
- executionWorkspacePolicy: null,
- codebase: {
- workspaceId: workspace.id,
- repoUrl: null,
- repoRef: null,
- defaultRef: null,
- repoName: null,
- localFolder: workspace.cwd,
- managedFolder: "",
- effectiveLocalFolder: workspace.cwd ?? "",
- origin: "local_folder",
- },
- workspaces: [workspace],
- primaryWorkspace: workspace,
- archivedAt: null,
- createdAt: new Date("2026-06-08T00:00:00.000Z"),
- updatedAt: new Date("2026-06-08T00:00:00.000Z"),
- ...overrides,
- };
-}
-
-function unavailableResponse(reason: string): WorkspaceFileListResponse {
- return {
- kind: "workspace_file_list",
- state: "unavailable",
- unavailableReason: reason,
- workspace: null,
- query: { workspace: "auto", mode: "changed", q: null, limit: 100, offset: 0 },
- items: [],
- scannedCount: 0,
- truncated: false,
- };
-}
-
-function ok(data: T) {
- return { data, isFetching: false, isError: false, error: null, refetch: vi.fn() };
-}
-
-describe("WorkspaceFileBrowser", () => {
- let container: HTMLDivElement;
- const roots: Root[] = [];
-
- beforeEach(() => {
- container = document.createElement("div");
- document.body.appendChild(container);
- useQueryMock.mockReset();
- cancelQueriesMock.mockClear();
- Object.defineProperty(document, "visibilityState", {
- configurable: true,
- value: "visible",
- });
- Object.defineProperty(Element.prototype, "scrollIntoView", {
- configurable: true,
- value: vi.fn(),
- });
- });
-
- afterEach(() => {
- for (const root of roots.splice(0)) {
- act(() => {
- root.unmount();
- });
- }
- container.remove();
- vi.restoreAllMocks();
- });
-
- function renderBrowser(onOpen = vi.fn(), props: Partial> = {}) {
- const root = createRoot(container);
- roots.push(root);
- act(() => {
- root.render();
- });
- return { root, onOpen };
- }
-
- function changedListQueryOptions() {
- return useQueryMock.mock.calls
- .map(([options]) => options as {
- queryKey?: readonly unknown[];
- enabled?: boolean;
- refetchOnWindowFocus?: boolean;
- refetchOnReconnect?: boolean;
- })
- .filter((options) => options.queryKey?.[0] === "issues" && options.queryKey?.[3] === "list")
- .at(-1);
- }
-
- it("does not enable changed-file enumeration before the Files panel opens", () => {
- useQueryMock.mockReturnValue(ok(availableResponse([])));
-
- renderBrowser(vi.fn(), { active: false });
-
- expect(changedListQueryOptions()).toMatchObject({
- enabled: false,
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- });
- expect(cancelQueriesMock).toHaveBeenCalledWith({
- queryKey: ["issues", "file-resources", "issue-1", "list"],
- });
- });
-
- it("disables and cancels changed-file enumeration while the page is hidden", () => {
- Object.defineProperty(document, "visibilityState", {
- configurable: true,
- value: "hidden",
- });
- useQueryMock.mockReturnValue(ok(availableResponse([])));
-
- renderBrowser();
-
- expect(changedListQueryOptions()?.enabled).toBe(false);
- expect(cancelQueriesMock).toHaveBeenCalledTimes(1);
- });
-
- it("cancels an active changed-file query when the page becomes hidden", () => {
- useQueryMock.mockReturnValue(ok(availableResponse([])));
- renderBrowser();
- expect(changedListQueryOptions()?.enabled).toBe(true);
-
- Object.defineProperty(document, "visibilityState", {
- configurable: true,
- value: "hidden",
- });
- act(() => {
- document.dispatchEvent(new Event("visibilitychange"));
- });
-
- expect(changedListQueryOptions()?.enabled).toBe(false);
- expect(cancelQueriesMock).toHaveBeenCalledWith({
- queryKey: ["issues", "file-resources", "issue-1", "list"],
- });
- });
-
- it("runs one explicit refresh without enabling focus or reconnect bursts", () => {
- const refetch = vi.fn();
- useQueryMock.mockReturnValue({
- ...ok(availableResponse([createItem()])),
- refetch,
- });
-
- renderBrowser();
- const refresh = container.querySelector('button[aria-label="Refresh workspace files"]');
- expect(refresh).not.toBeNull();
- act(() => refresh!.click());
-
- expect(refetch).toHaveBeenCalledTimes(1);
- expect(changedListQueryOptions()).toMatchObject({
- enabled: true,
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- });
- });
-
- it.each([
- [503, "workspace_git_scan_saturated"],
- [504, "workspace_git_scan_timeout"],
- ] as const)("renders %s changed-file failures as a retryable state", (status, code) => {
- const refetch = vi.fn();
- useQueryMock.mockReturnValue({
- data: undefined,
- isFetching: false,
- isError: true,
- error: new ApiError("temporarily unavailable", status, { code }),
- refetch,
- });
-
- renderBrowser();
-
- expect(container.textContent).toContain("Changed files temporarily unavailable");
- const retry = Array.from(container.querySelectorAll("button")).find((button) => button.textContent?.includes("Retry"));
- expect(retry).not.toBeUndefined();
- act(() => retry!.click());
- expect(refetch).toHaveBeenCalledTimes(1);
- });
-
- it("renders the Recently changed files as a tree and opens a row with its relative path", () => {
- useQueryMock.mockReturnValue(
- ok(availableResponse([createItem(), createItem({ relativePath: "README.md", displayPath: "README.md" })])),
- );
-
- const { onOpen } = renderBrowser();
-
- expect(container.querySelector('[role="tree"]')).not.toBeNull();
- expect(container.textContent).toContain("Isolated workspace");
- expect(container.textContent).not.toContain("Recently changed");
- expect(container.textContent).not.toContain("From Isolated workspace");
-
- const option = Array.from(container.querySelectorAll('[role="treeitem"]')).find(
- (el) => el.getAttribute("title") === "ui/src/pages/IssueDetail.tsx",
- );
- expect(option).not.toBeUndefined();
- const download = option!.querySelector('a[aria-label="Download IssueDetail.tsx"]');
- expect(download?.getAttribute("href")).toBe(
- "/api/issues/issue-1/file-resources/content?path=ui%2Fsrc%2Fpages%2FIssueDetail.tsx&download=1",
- );
-
- act(() => {
- option!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
- });
- expect(onOpen).toHaveBeenCalledWith({
- path: "ui/src/pages/IssueDetail.tsx",
- workspace: "auto",
- browseFolderPath: null,
- browseQuery: null,
- });
- });
-
- it.each(["live", "saved"] as const)("identifies %s workspace files without presenting saved bytes as live", kind => {
- const response = availableResponse([createItem()]);
- response.workspace!.source = { kind, savedAt: kind === "saved" ? "2026-10-30T12:00:00.000Z" : null,
- snapshotId: kind === "saved" ? "f6d9bb44-e06d-45bb-a7c3-72a5ac6f6ef5" : null };
- useQueryMock.mockReturnValue(ok(response));
- renderBrowser();
- const source = container.querySelector('[aria-label="Workspace file source"]');
- expect(source?.textContent).toContain(kind === "live" ? "Live workspace" : "Saved copy from");
- expect(source?.querySelector("time")?.getAttribute("datetime") ?? null).toBe(response.workspace!.source.savedAt);
- if (kind === "saved") expect(source?.textContent).not.toContain("Live workspace");
- });
-
- it("groups nested paths into collapsible folder rows instead of repeating full paths", () => {
- useQueryMock.mockReturnValue(
- ok(availableResponse([
- createItem({
- title: "tweet.md",
- relativePath: "videos/90-days-paperclip/tweet.md",
- displayPath: "videos/90-days-paperclip/tweet.md",
- }),
- createItem({
- title: "90-days-paperclip-1x1.mp4",
- relativePath: "videos/90-days-paperclip/out/90-days-paperclip-1x1.mp4",
- displayPath: "videos/90-days-paperclip/out/90-days-paperclip-1x1.mp4",
- previewKind: "video",
- }),
- ])),
- );
-
- renderBrowser();
-
- expect(container.querySelector('[role="tree"]')).not.toBeNull();
- expect(container.textContent).toContain("videos");
- expect(container.textContent).toContain("90-days-paperclip");
- expect(container.textContent).toContain("tweet.md");
- expect(container.textContent).toContain("90-days-paperclip-1x1.mp4");
- expect(container.textContent).not.toContain("videos/90-days-paperclip/tweet.md");
-
- const videosFolder = Array.from(container.querySelectorAll('button[role="treeitem"]')).find(
- (el) => el.getAttribute("title") === "videos",
- );
- expect(videosFolder).not.toBeUndefined();
- act(() => {
- videosFolder!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
- });
- expect(container.textContent).not.toContain("tweet.md");
- });
-
- it("can render without autofocus when embedded beside a preview", () => {
- useQueryMock.mockReturnValue(ok(availableResponse([createItem()])));
- renderBrowser(vi.fn(), { autoFocusSearch: false });
- expect(container.querySelector("input")?.hasAttribute("autofocus")).toBe(false);
- expect(container.querySelector("input")?.className).toContain("max-w-full");
- });
-
- it("hides source controls, folder headings, workspace labels, and timestamps", () => {
- useQueryMock.mockReturnValue(ok(availableResponse([
- createItem({
- relativePath: "videos/90-days-paperclip/tweet.md",
- displayPath: "videos/90-days-paperclip/tweet.md",
- }),
- ])));
-
- renderBrowser(vi.fn(), { compact: true, autoFocusSearch: false });
-
- expect(container.textContent).not.toContain("Source");
- expect(container.textContent).not.toContain("Workspace");
- expect(container.textContent).not.toContain("Recently changed");
- expect(container.textContent).not.toContain("Files in folder");
- expect(container.textContent).not.toContain("From Isolated workspace");
- expect(container.querySelector(".tabular-nums")).toBeNull();
- expect(container.textContent).toContain("videos");
- expect(container.textContent).toContain("tweet.md");
- });
-
- it("marks the selected file in the tree", () => {
- useQueryMock.mockReturnValue(ok(availableResponse([createItem()])));
- renderBrowser(vi.fn(), { selectedPath: "ui/src/pages/IssueDetail.tsx" });
- const selected = Array.from(container.querySelectorAll('[role="treeitem"]')).find(
- (el) => el.getAttribute("title") === "ui/src/pages/IssueDetail.tsx",
- );
- expect(selected?.getAttribute("aria-selected")).toBe("true");
- });
-
- it("lists the selected file's parent folder so deep-linked files appear selected", () => {
- const commandsItem = createItem({
- title: "commands.md",
- relativePath: "docs/reference/cli/commands.md",
- displayPath: "docs/reference/cli/commands.md",
- byteSize: 8192,
- });
- useQueryMock.mockReturnValue(ok(availableResponse([commandsItem])));
-
- renderBrowser(vi.fn(), {
- compact: true,
- autoFocusSearch: false,
- selectedPath: "docs/reference/cli/commands.md",
- });
-
- const listCall = useQueryMock.mock.calls.find(([options]) => options.queryKey?.[3] === "list");
- expect(listCall?.[0].queryKey[4]).toMatchObject({
- mode: "all",
- path: "docs/reference/cli",
- });
- const selected = Array.from(container.querySelectorAll('[role="treeitem"]')).find(
- (el) => el.getAttribute("title") === "docs/reference/cli/commands.md",
- );
- expect(selected?.getAttribute("aria-selected")).toBe("true");
- expect(container.textContent).toContain("commands.md");
- });
-
- it("treats an explicit null initial folder as the workspace root", () => {
- useQueryMock.mockReturnValue(ok(availableResponse([createItem({
- title: "README.md",
- relativePath: "README.md",
- displayPath: "README.md",
- })])));
-
- renderBrowser(vi.fn(), {
- compact: true,
- autoFocusSearch: false,
- initialFolderPath: null,
- selectedPath: "docs/reference/cli/commands.md",
- });
-
- const listCall = useQueryMock.mock.calls.find(([options]) => options.queryKey?.[3] === "list");
- expect(listCall?.[0].queryKey[4]).toMatchObject({
- mode: "all",
- path: null,
- });
- });
-
- it("preserves an initial search instead of narrowing to the selected file's parent folder", () => {
- useQueryMock.mockReturnValue(ok(availableResponse([createItem({
- title: "FileViewerSheet.tsx",
- relativePath: "ui/src/components/FileViewerSheet.tsx",
- displayPath: "ui/src/components/FileViewerSheet.tsx",
- })])));
-
- renderBrowser(vi.fn(), {
- compact: true,
- autoFocusSearch: false,
- initialQuery: "FileViewerSheet",
- selectedPath: "ui/src/components/FileViewerSheet.tsx",
- });
-
- const listCall = useQueryMock.mock.calls.find(([options]) => options.queryKey?.[3] === "list");
- expect(listCall?.[0].queryKey[4]).toMatchObject({
- mode: "all",
- q: "FileViewerSheet",
- path: null,
- });
- });
-
- it("does not mark an unrelated highlighted row as selected", () => {
- useQueryMock.mockReturnValue(ok(availableResponse([
- createItem({
- title: "vite.config.ts",
- relativePath: "ui/vite.config.ts",
- displayPath: "ui/vite.config.ts",
- }),
- ])));
-
- renderBrowser(vi.fn(), {
- compact: true,
- autoFocusSearch: false,
- selectedPath: "docs/reference/cli/commands.md",
- });
-
- const unrelated = Array.from(container.querySelectorAll('[role="treeitem"]')).find(
- (el) => el.getAttribute("title") === "ui/vite.config.ts",
- );
- expect(unrelated?.getAttribute("aria-selected")).toBe("false");
- });
-
- it("does not render a Recent/All toggle", () => {
- useQueryMock.mockReturnValue(ok(availableResponse([createItem()])));
- renderBrowser();
- expect(container.textContent).not.toContain("All files");
- expect(container.textContent).not.toContain("Recent changes / All");
- });
-
- it("discloses truncation in the footer", () => {
- useQueryMock.mockReturnValue(ok(availableResponse([createItem()], true)));
- renderBrowser();
- expect(container.textContent).toContain("refine the search to narrow");
- });
-
- it("renders newly loaded current-folder rows after Load more", () => {
- const folderPath = "ui/src/components";
- const pageZero = availableAllResponse([
- createItem({
- title: "IssueLinkQuicklook.tsx",
- relativePath: `${folderPath}/IssueLinkQuicklook.tsx`,
- displayPath: `${folderPath}/IssueLinkQuicklook.tsx`,
- }),
- ], folderPath, true, 0);
- const pageOne = availableAllResponse([
- createItem({
- title: "SourceTrustBadge.tsx",
- relativePath: `${folderPath}/SourceTrustBadge.tsx`,
- displayPath: `${folderPath}/SourceTrustBadge.tsx`,
- }),
- ], folderPath, true, LIST_LIMIT);
- useQueryMock.mockImplementation((options: { queryKey: readonly unknown[] }) => {
- const query = options.queryKey[4] as { path?: string | null; offset?: number } | undefined;
- if (query?.path === folderPath && query.offset === LIST_LIMIT) return ok(pageOne);
- return ok(pageZero);
- });
-
- renderBrowser(vi.fn(), {
- compact: true,
- autoFocusSearch: false,
- initialFolderPath: folderPath,
- });
-
- expect(container.textContent).toContain("IssueLinkQuicklook.tsx");
- expect(container.textContent).not.toContain("SourceTrustBadge.tsx");
- const loadMore = Array.from(container.querySelectorAll("button")).find(
- (el) => el.textContent === "Load more from this folder",
- );
- act(() => {
- loadMore!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
- });
-
- expect(container.textContent).toContain("SourceTrustBadge.tsx");
- });
-
- it("opens the highlighted row when Enter is pressed in the search field", () => {
- useQueryMock.mockReturnValue(ok(availableResponse([createItem()])));
- const { onOpen } = renderBrowser();
- const input = container.querySelector("input")!;
- act(() => {
- input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true, cancelable: true }));
- });
- act(() => {
- input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
- });
- expect(onOpen).toHaveBeenCalledWith({
- path: "ui/src/pages/IssueDetail.tsx",
- workspace: "auto",
- browseFolderPath: null,
- browseQuery: null,
- });
- });
-
- it("reports live search state for URL-backed browse preservation", async () => {
- useQueryMock.mockReturnValue(ok(availableResponse([createItem()])));
- const onBrowseStateChange = vi.fn();
- renderBrowser(vi.fn(), {
- initialFolderPath: "ui/src/components",
- onBrowseStateChange,
- });
- onBrowseStateChange.mockClear();
-
- const input = container.querySelector("input")!;
- const nativeSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
- act(() => {
- nativeSetter?.call(input, "FileViewerSheet");
- input.dispatchEvent(new Event("input", { bubbles: true, cancelable: true }));
- });
- await new Promise((resolve) => window.setTimeout(resolve, 0));
-
- expect(onBrowseStateChange).toHaveBeenLastCalledWith({
- q: "FileViewerSheet",
- folderPath: "ui/src/components",
- projectId: null,
- workspaceId: null,
- });
- });
-
- it("settles a controlled parent with an inline browse-state handler and reports child search changes", async () => {
- useQueryMock.mockReturnValue(ok(availableResponse([createItem()])));
- const notifications = vi.fn();
- type BrowseState = Parameters["onBrowseStateChange"]>>[0];
- function ControlledBrowser() {
- const [browse, setBrowse] = useState({ q: null, folderPath: null, projectId: null, workspaceId: null });
- return <>
-
- {
- notifications(next);
- // Bound the broken feedback loop so the regression fails without
- // exhausting React's nested-update limit or hanging the worker.
- if (notifications.mock.calls.length < 10) setBrowse(next);
- }} />
- >;
- }
- const root = createRoot(container);
- roots.push(root);
- act(() => root.render());
- await waitForExpectation(() => expect(notifications).toHaveBeenCalledTimes(1));
-
- const input = container.querySelector("input")!;
- const nativeSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
- act(() => {
- nativeSetter?.call(input, "workspace-proof");
- input.dispatchEvent(new Event("input", { bubbles: true, cancelable: true }));
- });
- await waitForExpectation(() => {
- expect(container.querySelector('[data-testid="parent-query"]')?.textContent).toBe("workspace-proof");
- expect(notifications).toHaveBeenCalledTimes(2);
- });
- });
-
- it("uses the replaced browse callback for the next actual state change without reporting callback-only changes", async () => {
- useQueryMock.mockReturnValue(ok(availableResponse([createItem()])));
- const first = vi.fn(), latest = vi.fn(), onOpen = vi.fn();
- const { root } = renderBrowser(onOpen, { onBrowseStateChange: first });
- expect(first).toHaveBeenCalledTimes(1);
- act(() => root.render());
- expect(latest).not.toHaveBeenCalled();
-
- const input = container.querySelector("input")!;
- const nativeSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
- act(() => {
- nativeSetter?.call(input, " next-file ");
- input.dispatchEvent(new Event("input", { bubbles: true, cancelable: true }));
- });
- await waitForExpectation(() => expect(latest).toHaveBeenCalledWith({
- q: "next-file", folderPath: null, projectId: null, workspaceId: null,
- }));
- act(() => {
- nativeSetter?.call(input, "next-file");
- input.dispatchEvent(new Event("input", { bubbles: true, cancelable: true }));
- });
- await new Promise(resolve => window.setTimeout(resolve, 0));
- expect(latest).toHaveBeenCalledTimes(1);
- expect(first).toHaveBeenCalledTimes(1);
- });
-
- it("shows the remote-workspace state without file rows", () => {
- useQueryMock.mockReturnValue(ok(unavailableResponse("remote_workspace")));
- renderBrowser();
- expect(container.textContent).toContain("Remote workspace preview not supported");
- expect(container.querySelector('[role="tree"]')).toBeNull();
- });
-
- it("shows the no-workspace state when the issue has no workspace", () => {
- useQueryMock.mockReturnValue(ok(unavailableResponse("no_workspace")));
- renderBrowser();
- expect(container.textContent).toContain("No workspace yet");
- });
-
- it("opens a result from a selected other project workspace", () => {
- const contentItem = createItem({
- relativePath: "content-os/cases/active/2026-06-06-pap-10199-bundled-skills/README.md",
- displayPath: "Paperclip Content / content-os/cases/active/2026-06-06-pap-10199-bundled-skills/README.md",
- workspaceLabel: "Paperclip Content",
- workspaceKind: "project_workspace",
- workspaceId: "workspace-content",
- projectId: "project-content",
- projectName: "Paperclip Content",
- });
- useQueryMock.mockImplementation((options: { queryKey: readonly unknown[] }) => {
- if (options.queryKey[0] === "projects") return ok([createProject()]);
- return ok(availableResponse([contentItem]));
- });
-
- const { onOpen } = renderBrowser(vi.fn(), {
- companyId: "company-1",
- initialProjectId: "project-content",
- initialWorkspaceId: "workspace-content",
- });
-
- expect(container.textContent).not.toContain("Other project");
- expect(container.textContent).toContain("Paperclip Content / Paperclip Content");
- const listCall = useQueryMock.mock.calls.find(([options]) => options.queryKey?.[3] === "list");
- expect(listCall?.[0].queryKey[4]).toMatchObject({
- workspace: "project",
- projectId: "project-content",
- workspaceId: "workspace-content",
- });
-
- const option = Array.from(container.querySelectorAll('[role="treeitem"]')).find(
- (el) => el.getAttribute("title") === contentItem.displayPath,
- )!;
- act(() => {
- option.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
- });
- expect(onOpen).toHaveBeenCalledWith({
- path: "content-os/cases/active/2026-06-06-pap-10199-bundled-skills/README.md",
- workspace: "project",
- projectId: "project-content",
- workspaceId: "workspace-content",
- browseFolderPath: null,
- browseQuery: null,
- });
- });
-
- it("focuses an initial folder in a selected other project workspace", () => {
- const folderPath = "content-os/cases/active/2026-06-06-pap-10199-bundled-skills/";
- const contentItem = createItem({
- relativePath: `${folderPath}README.md`,
- displayPath: `Paperclip Content / ${folderPath}README.md`,
- workspaceLabel: "Paperclip Content",
- workspaceKind: "project_workspace",
- workspaceId: "workspace-content",
- projectId: "project-content",
- projectName: "Paperclip Content",
- });
- useQueryMock.mockImplementation((options: { queryKey: readonly unknown[] }) => {
- if (options.queryKey[0] === "projects") return ok([createProject()]);
- return ok(availableResponse([contentItem]));
- });
-
- const { onOpen } = renderBrowser(vi.fn(), {
- companyId: "company-1",
- initialProjectId: "project-content",
- initialWorkspaceId: "workspace-content",
- initialFolderPath: folderPath,
- });
-
- expect(container.textContent).toContain("bundled-skills");
- expect(container.textContent).not.toContain(folderPath);
- expect(container.textContent).not.toContain("Files in folder");
- const listCall = useQueryMock.mock.calls.find(([options]) => options.queryKey?.[3] === "list");
- expect(listCall?.[0].queryKey[4]).toMatchObject({
- workspace: "project",
- projectId: "project-content",
- workspaceId: "workspace-content",
- path: folderPath,
- });
-
- const option = Array.from(container.querySelectorAll('[role="treeitem"]')).find(
- (el) => el.getAttribute("title") === contentItem.displayPath,
- )!;
- act(() => {
- option.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
- });
- expect(onOpen).toHaveBeenCalledWith({
- path: `${folderPath}README.md`,
- workspace: "project",
- projectId: "project-content",
- workspaceId: "workspace-content",
- browseFolderPath: folderPath,
- browseQuery: null,
- });
- });
-
- it("opens sibling files with the current folder scope", () => {
- const folderPath = "docs/cli";
- const controlPlane = createItem({
- title: "control-plane-commands.md",
- relativePath: `${folderPath}/control-plane-commands.md`,
- displayPath: `${folderPath}/control-plane-commands.md`,
- });
- useQueryMock.mockReturnValue(ok(availableResponse([
- createItem({
- title: "setup-commands.md",
- relativePath: `${folderPath}/setup-commands.md`,
- displayPath: `${folderPath}/setup-commands.md`,
- }),
- controlPlane,
- ])));
-
- const { onOpen } = renderBrowser(vi.fn(), {
- compact: true,
- autoFocusSearch: false,
- initialFolderPath: folderPath,
- selectedPath: `${folderPath}/setup-commands.md`,
- });
-
- const option = Array.from(container.querySelectorAll('[role="treeitem"]')).find(
- (el) => el.getAttribute("title") === controlPlane.displayPath,
- )!;
- act(() => {
- option.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
- });
-
- expect(onOpen).toHaveBeenCalledWith({
- path: `${folderPath}/control-plane-commands.md`,
- workspace: "auto",
- browseFolderPath: folderPath,
- browseQuery: null,
- });
- });
-
- it("scrolls the selected file into view after breadcrumb-scoped listings", () => {
- const folderPath = "docs";
- const selectedPath = "docs/cli/setup-commands.md";
- const scrollIntoView = vi.fn();
- Object.defineProperty(Element.prototype, "scrollIntoView", {
- configurable: true,
- value: scrollIntoView,
- });
- vi.spyOn(Element.prototype, "getBoundingClientRect").mockImplementation(function getBoundingClientRect(this: Element) {
- if (this.getAttribute("aria-selected") === "true") {
- return { top: 1086, bottom: 1114, left: 0, right: 100, width: 100, height: 28, x: 0, y: 1086, toJSON: () => ({}) };
- }
- if (typeof this.className === "string" && this.className.includes("overflow-y-auto")) {
- return { top: 188, bottom: 546, left: 0, right: 320, width: 320, height: 358, x: 0, y: 188, toJSON: () => ({}) };
- }
- return { top: 0, bottom: 0, left: 0, right: 0, width: 0, height: 0, x: 0, y: 0, toJSON: () => ({}) };
- });
- useQueryMock.mockReturnValue(ok(availableResponse([createItem({
- title: "setup-commands.md",
- relativePath: selectedPath,
- displayPath: selectedPath,
- })])));
-
- renderBrowser(vi.fn(), {
- compact: true,
- autoFocusSearch: false,
- initialFolderPath: folderPath,
- selectedPath,
- });
-
- expect(scrollIntoView).toHaveBeenCalledWith({ block: "nearest" });
- });
-
- it("loads the selected file's ancestor folders when a parent breadcrumb is open", () => {
- const selectedPath = "docs/cli/setup-commands.md";
- const docsResponse = availableResponse([
- createDirectoryItem({
- title: "cli",
- relativePath: "docs/cli",
- displayPath: "docs/cli/",
- }),
- ]);
- docsResponse.query = { ...docsResponse.query, mode: "all", path: "docs" };
- const cliResponse = availableResponse([
- createItem({
- title: "setup-commands.md",
- relativePath: selectedPath,
- displayPath: selectedPath,
- }),
- ]);
- cliResponse.query = { ...cliResponse.query, mode: "all", path: "docs/cli" };
- useQueryMock.mockImplementation((options: { queryKey: readonly unknown[] }) => {
- const query = options.queryKey[4] as { path?: string | null } | undefined;
- if (query?.path === "docs/cli") return ok(cliResponse);
- return ok(docsResponse);
- });
-
- renderBrowser(vi.fn(), {
- compact: true,
- autoFocusSearch: false,
- initialFolderPath: "docs",
- selectedPath,
- });
-
- const childListCall = useQueryMock.mock.calls.find(([options]) => options.queryKey?.[4]?.path === "docs/cli");
- expect(childListCall?.[0].queryKey[4]).toMatchObject({ path: "docs/cli", offset: 0 });
- const selected = Array.from(container.querySelectorAll('[role="treeitem"]')).find(
- (el) => el.getAttribute("title") === selectedPath,
- );
- expect(selected?.getAttribute("aria-selected")).toBe("true");
- expect(container.textContent).toContain("setup-commands.md");
- });
-
- it("auto-pages the selected file's current folder until the selected row is loaded", async () => {
- const folderPath = "ui/src/components";
- const selectedPath = `${folderPath}/WorkspaceFileBrowser.tsx`;
- const pageZero = availableAllResponse([
- createItem({
- title: "ActivityCharts.tsx",
- relativePath: `${folderPath}/ActivityCharts.tsx`,
- displayPath: `${folderPath}/ActivityCharts.tsx`,
- }),
- ], folderPath, true, 0);
- const pageOne = availableAllResponse([
- createItem({
- title: "SourceTrustBadge.tsx",
- relativePath: `${folderPath}/SourceTrustBadge.tsx`,
- displayPath: `${folderPath}/SourceTrustBadge.tsx`,
- }),
- ], folderPath, true, LIST_LIMIT);
- const pageTwo = availableAllResponse([
- createItem({
- title: "WorkspaceFileBrowser.tsx",
- relativePath: selectedPath,
- displayPath: selectedPath,
- }),
- ], folderPath, false, LIST_LIMIT * 2);
- useQueryMock.mockImplementation((options: { queryKey: readonly unknown[] }) => {
- const query = options.queryKey[4] as { path?: string | null; offset?: number } | undefined;
- if (query?.path === folderPath && query.offset === LIST_LIMIT) return ok(pageOne);
- if (query?.path === folderPath && query.offset === LIST_LIMIT * 2) return ok(pageTwo);
- return ok(pageZero);
- });
-
- renderBrowser(vi.fn(), {
- compact: true,
- autoFocusSearch: false,
- initialFolderPath: folderPath,
- selectedPath,
- });
-
- await waitForExpectation(() => {
- const pageTwoCall = useQueryMock.mock.calls.find(
- ([options]) => options.queryKey?.[4]?.path === folderPath && options.queryKey[4].offset === LIST_LIMIT * 2,
- );
- expect(pageTwoCall?.[0].queryKey[4]).toMatchObject({ path: folderPath, offset: LIST_LIMIT * 2 });
- });
- await waitForExpectation(() => {
- const selected = Array.from(container.querySelectorAll('[role="treeitem"]')).find(
- (el) => el.getAttribute("title") === selectedPath,
- );
- expect(selected?.getAttribute("aria-selected")).toBe("true");
- expect(container.textContent).toContain("WorkspaceFileBrowser.tsx");
- });
- });
-
- it("lets breadcrumb folders navigate to parent directories", () => {
- const folderPath = "content-os/cases/active/";
- useQueryMock.mockReturnValue(ok(availableResponse([createItem({
- relativePath: `${folderPath}README.md`,
- displayPath: `${folderPath}README.md`,
- })])));
-
- renderBrowser(vi.fn(), { initialFolderPath: folderPath });
- const contentOsCrumb = Array.from(container.querySelectorAll("button")).find(
- (el) => el.getAttribute("title") === "content-os",
- );
- expect(contentOsCrumb).not.toBeUndefined();
- act(() => {
- contentOsCrumb!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
- });
- const latestListCall = useQueryMock.mock.calls.filter(([options]) => options.queryKey?.[3] === "list").at(-1);
- expect(latestListCall?.[0].queryKey[4]).toMatchObject({ path: "content-os" });
- });
-});
-
-describe("describeUnavailable", () => {
- it("maps reasons to copy that matches the viewer's denial voice", () => {
- expect(describeUnavailable("remote_workspace").title).toBe("Remote workspace preview not supported");
- expect(describeUnavailable("no_workspace").title).toBe("No workspace yet");
- expect(describeUnavailable("no_local_workspace").title).toBe("No workspace yet");
- expect(describeUnavailable("workspace_unavailable").title).toBe("Workspace is no longer available");
- expect(describeUnavailable("archived").title).toBe("Workspace is no longer available");
- });
-
- it("never leaks the raw reason code as the body", () => {
- for (const reason of ["remote_workspace", "no_workspace", "workspace_unavailable", "weird_unknown"]) {
- const { body } = describeUnavailable(reason);
- expect(body).not.toBe(reason);
- expect(body).not.toMatch(/^[a-z_]+$/);
- }
- });
-});
diff --git a/ui/src/components/WorkspaceRuntimeControls.test.tsx b/ui/src/components/WorkspaceRuntimeControls.test.tsx
deleted file mode 100644
index 6e560fca96e..00000000000
--- a/ui/src/components/WorkspaceRuntimeControls.test.tsx
+++ /dev/null
@@ -1,804 +0,0 @@
-// @vitest-environment jsdom
-
-import type { ReactNode } from "react";
-import { flushSync } from "react-dom";
-import { createRoot } from "react-dom/client";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import type { WorkspaceRuntimeService } from "@paperclipai/shared";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import {
- buildWorkspaceRuntimeControlSections,
- buildWorkspaceServiceControlEntries,
- resolveWorkspaceServiceControlRequests,
- WorkspaceRuntimeQuickControls,
- WorkspaceRuntimeControls,
-} from "./WorkspaceRuntimeControls";
-import { queryKeys } from "@/lib/queryKeys";
-
-const mockInstanceSettingsApi = vi.hoisted(() => ({
- getExperimental: vi.fn(),
-}));
-
-vi.mock("@/api/instanceSettings", () => ({
- instanceSettingsApi: mockInstanceSettingsApi,
-}));
-
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
-
-function act(callback: () => void) {
- flushSync(callback);
-}
-
-/**
- * The command rows read the managed-sandbox-only policy through the shared
- * instance-settings query, so every render needs a query client. Renders here
- * are synchronous and the guard fails closed until the policy resolves, so the
- * cache is primed by default. Pass `null` to render with the policy unresolved.
- */
-function withQueryClient(node: ReactNode, experimentalSettings: Record | null = {}) {
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
- if (experimentalSettings) {
- queryClient.setQueryData(queryKeys.instance.experimentalSettings, experimentalSettings);
- }
- return {node};
-}
-
-function createRuntimeService(overrides: Partial = {}): WorkspaceRuntimeService {
- return {
- id: overrides.id ?? "service-1",
- companyId: overrides.companyId ?? "company-1",
- projectId: overrides.projectId ?? "project-1",
- projectWorkspaceId: overrides.projectWorkspaceId ?? "workspace-1",
- executionWorkspaceId: overrides.executionWorkspaceId ?? null,
- issueId: overrides.issueId ?? null,
- scopeType: overrides.scopeType ?? "project_workspace",
- scopeId: overrides.scopeId ?? "workspace-1",
- serviceName: overrides.serviceName ?? "web",
- status: overrides.status ?? "stopped",
- lifecycle: overrides.lifecycle ?? "shared",
- reuseKey: overrides.reuseKey ?? null,
- command: overrides.command ?? "pnpm dev",
- cwd: overrides.cwd ?? "/repo",
- port: overrides.port ?? null,
- url: overrides.url ?? null,
- provider: overrides.provider ?? "local_process",
- providerRef: overrides.providerRef ?? null,
- ownerAgentId: overrides.ownerAgentId ?? null,
- startedByRunId: overrides.startedByRunId ?? null,
- lastUsedAt: overrides.lastUsedAt ?? new Date("2026-04-12T00:00:00.000Z"),
- startedAt: overrides.startedAt ?? new Date("2026-04-12T00:00:00.000Z"),
- stoppedAt: overrides.stoppedAt ?? null,
- stopPolicy: overrides.stopPolicy ?? null,
- healthStatus: overrides.healthStatus ?? "unknown",
- exposure: overrides.exposure ?? null,
- configIndex: overrides.configIndex ?? null,
- createdAt: overrides.createdAt ?? new Date("2026-04-12T00:00:00.000Z"),
- updatedAt: overrides.updatedAt ?? new Date("2026-04-12T00:00:00.000Z"),
- };
-}
-
-describe("buildWorkspaceRuntimeControlSections", () => {
- it("separates service and job commands while matching running services", () => {
- const sections = buildWorkspaceRuntimeControlSections({
- runtimeConfig: {
- commands: [
- { id: "web", name: "web", kind: "service", command: "pnpm dev" },
- { id: "db-migrate", name: "db:migrate", kind: "job", command: "pnpm db:migrate" },
- ],
- },
- runtimeServices: [
- createRuntimeService({ id: "service-web", serviceName: "web", status: "running" }),
- ],
- canStartServices: true,
- canRunJobs: true,
- });
-
- expect(sections.services).toHaveLength(1);
- expect(sections.jobs).toHaveLength(1);
- expect(sections.services[0]).toMatchObject({
- title: "web",
- statusLabel: "running",
- workspaceCommandId: "web",
- runtimeServiceId: "service-web",
- });
- expect(sections.jobs[0]).toMatchObject({
- title: "db:migrate",
- statusLabel: "run once",
- workspaceCommandId: "db-migrate",
- });
- });
-
- it("keeps stopped stale runtime services from masking updated inherited commands", () => {
- const sections = buildWorkspaceRuntimeControlSections({
- runtimeConfig: {
- commands: [
- { id: "web", name: "web", kind: "service", command: "pnpm dev:once --tailscale-auth" },
- ],
- },
- runtimeServices: [
- createRuntimeService({
- id: "service-web",
- serviceName: "web",
- status: "stopped",
- command: "pnpm dev",
- }),
- ],
- canStartServices: true,
- canRunJobs: true,
- });
-
- expect(sections.services).toEqual([
- expect.objectContaining({
- title: "web",
- statusLabel: "stopped",
- command: "pnpm dev:once --tailscale-auth",
- runtimeServiceId: null,
- }),
- ]);
- expect(sections.otherServices).toEqual([]);
- });
-
- it("surfaces running stale runtime services separately from updated commands", () => {
- const sections = buildWorkspaceRuntimeControlSections({
- runtimeConfig: {
- commands: [
- { id: "web", name: "web", kind: "service", command: "pnpm dev:once --tailscale-auth" },
- ],
- },
- runtimeServices: [
- createRuntimeService({
- id: "service-web",
- serviceName: "web",
- status: "running",
- command: "pnpm dev",
- }),
- ],
- canStartServices: true,
- canRunJobs: true,
- });
-
- expect(sections.services).toEqual([
- expect.objectContaining({
- title: "web",
- statusLabel: "stopped",
- command: "pnpm dev:once --tailscale-auth",
- runtimeServiceId: null,
- }),
- ]);
- expect(sections.otherServices).toEqual([
- expect.objectContaining({
- title: "web",
- statusLabel: "running",
- command: "pnpm dev",
- runtimeServiceId: "service-web",
- disabledReason: "This runtime service no longer matches a configured workspace command.",
- }),
- ]);
- });
-});
-
-describe("WorkspaceRuntimeControls", () => {
- let container: HTMLDivElement;
-
- beforeEach(() => {
- container = document.createElement("div");
- document.body.appendChild(container);
- mockInstanceSettingsApi.getExperimental.mockResolvedValue({});
- });
-
- afterEach(() => {
- document.body.innerHTML = "";
- vi.clearAllMocks();
- });
-
- it("shows the service working directory when the managed-sandbox-only policy is off", () => {
- const sections = buildWorkspaceRuntimeControlSections({
- runtimeConfig: {
- commands: [{ id: "web", name: "web", kind: "service", command: "pnpm dev", cwd: "." }],
- },
- runtimeServices: [
- createRuntimeService({ id: "service-web", serviceName: "web", status: "running", cwd: "/srv/repo" }),
- ],
- canStartServices: true,
- });
-
- const root = createRoot(container);
- act(() => {
- root.render(withQueryClient(
- ,
- {},
- ));
- });
-
- expect(container.textContent).toContain("/srv/repo");
- expect(container.textContent).toContain("pnpm dev");
-
- act(() => root.unmount());
- });
-
- it("keeps the service working directory hidden while the policy is still loading", () => {
- // A cold cache resolves the policy to false on the first render. The guard
- // fails closed so a managed instance never flashes the execution-host path.
- const sections = buildWorkspaceRuntimeControlSections({
- runtimeConfig: {
- commands: [{ id: "web", name: "web", kind: "service", command: "pnpm dev", cwd: "." }],
- },
- runtimeServices: [
- createRuntimeService({ id: "service-web", serviceName: "web", status: "running", cwd: "/srv/repo" }),
- ],
- canStartServices: true,
- });
-
- const root = createRoot(container);
- act(() => {
- root.render(withQueryClient(
- ,
- null,
- ));
- });
-
- expect(container.textContent).not.toContain("/srv/repo");
- expect(container.textContent).toContain("pnpm dev");
-
- act(() => root.unmount());
- });
-
- it("drops the service working directory when the managed-sandbox-only policy is on", () => {
- const sections = buildWorkspaceRuntimeControlSections({
- runtimeConfig: {
- commands: [{ id: "web", name: "web", kind: "service", command: "pnpm dev", cwd: "." }],
- },
- runtimeServices: [
- createRuntimeService({
- id: "service-web",
- serviceName: "web",
- status: "running",
- cwd: "/srv/repo",
- url: "http://127.0.0.1:5173",
- port: 5173,
- }),
- ],
- canStartServices: true,
- });
-
- const root = createRoot(container);
- act(() => {
- root.render(withQueryClient(
- ,
- { enableManagedSandboxOnly: true },
- ));
- });
-
- expect(container.textContent).not.toContain("/srv/repo");
- // The URL, the port, and the command describe the service, not the host.
- expect(container.textContent).toContain("http://127.0.0.1:5173");
- expect(container.textContent).toContain("Port 5173");
- expect(container.textContent).toContain("pnpm dev");
-
- act(() => root.unmount());
- });
-
- it("renders service and job actions distinctly", () => {
- const sections = buildWorkspaceRuntimeControlSections({
- runtimeConfig: {
- commands: [
- { id: "web", name: "web", kind: "service", command: "pnpm dev" },
- { id: "db-migrate", name: "db:migrate", kind: "job", command: "pnpm db:migrate" },
- ],
- },
- runtimeServices: [
- createRuntimeService({ id: "service-web", serviceName: "web", status: "running" }),
- ],
- canStartServices: true,
- canRunJobs: true,
- });
-
- const root = createRoot(container);
- act(() => {
- root.render(withQueryClient(
- ,
- ));
- });
-
- const buttons = Array.from(container.querySelectorAll("button")).map((button) => button.textContent?.trim());
- expect(buttons).toEqual(["Stop", "Restart", "Run"]);
- expect(container.textContent).toContain("Services");
- expect(container.textContent).toContain("Jobs");
-
- act(() => root.unmount());
- });
-
- it("lets quick action buttons inherit the shared button shape tokens", () => {
- const sections = buildWorkspaceRuntimeControlSections({
- runtimeConfig: {
- commands: [
- { id: "web", name: "web", kind: "service", command: "pnpm dev" },
- ],
- },
- runtimeServices: [
- createRuntimeService({ id: "service-web", serviceName: "web", status: "running" }),
- ],
- canStartServices: true,
- });
-
- const root = createRoot(container);
- act(() => {
- root.render(withQueryClient(
- ,
- ));
- });
-
- const buttons = Array.from(container.querySelectorAll("button"));
- expect(buttons).toHaveLength(2);
- for (const button of buttons) {
- expect(button.className).toContain("rounded-md");
- expect(button.className).not.toContain("rounded-none");
- expect(button.className).not.toContain("rounded-xl");
- expect(button.className).not.toContain("shadow-none");
- }
-
- act(() => root.unmount());
- });
-
- it("shows disabled actions when local command prerequisites are missing", () => {
- const sections = buildWorkspaceRuntimeControlSections({
- runtimeConfig: {
- commands: [
- { id: "web", name: "web", kind: "service", command: "pnpm dev" },
- { id: "db-migrate", name: "db:migrate", kind: "job", command: "pnpm db:migrate" },
- ],
- },
- runtimeServices: [],
- canStartServices: false,
- canRunJobs: false,
- });
-
- const root = createRoot(container);
- act(() => {
- root.render(withQueryClient(
- ,
- ));
- });
-
- const buttons = Array.from(container.querySelectorAll("button"));
- expect(buttons.every((button) => button.hasAttribute("disabled"))).toBe(true);
- expect(container.textContent).toContain("Add a workspace path first.");
-
- act(() => root.unmount());
- });
-
- it("hides the disabled hint once services can already run", () => {
- const sections = buildWorkspaceRuntimeControlSections({
- runtimeConfig: {
- commands: [
- { id: "web", name: "web", kind: "service", command: "pnpm dev" },
- ],
- },
- runtimeServices: [
- createRuntimeService({ id: "service-web", serviceName: "web", status: "running" }),
- ],
- canStartServices: true,
- });
-
- const root = createRoot(container);
- act(() => {
- root.render(withQueryClient(
- ,
- ));
- });
-
- expect(container.textContent).not.toContain("Add runtime settings first.");
-
- act(() => root.unmount());
- });
-
- it("hides the health badge for stopped services", () => {
- const sections = buildWorkspaceRuntimeControlSections({
- runtimeConfig: {
- commands: [
- { id: "web", name: "web", kind: "service", command: "pnpm dev" },
- ],
- },
- runtimeServices: [
- createRuntimeService({ id: "service-web", serviceName: "web", status: "stopped", healthStatus: "unknown" }),
- ],
- canStartServices: true,
- });
-
- const root = createRoot(container);
- act(() => {
- root.render(withQueryClient(
- ,
- ));
- });
-
- expect(container.textContent).not.toContain("unknown");
-
- act(() => root.unmount());
- });
-
- it.each([
- ["failed", "external HTTPS health probe did not validate", "HTTPS unavailable", "Check the Tailscale broker and node HTTPS configuration."],
- ["cleanup_pending", "host broker cleanup confirmation timed out", "HTTPS cleanup pending", "Restart the host broker before reusing this port."],
- ] as const)(
- "shows %s exposure state, last error, and remediation on service cards",
- (state, lastError, label, remediation) => {
- const sections = buildWorkspaceRuntimeControlSections({
- runtimeConfig: {
- commands: [
- { id: "web", name: "web", kind: "service", command: "pnpm dev" },
- ],
- },
- runtimeServices: [
- createRuntimeService({
- id: "service-web",
- serviceName: "web",
- status: "stopped",
- exposure: {
- provider: "tailscale_https",
- state,
- publicUrl: null,
- hostname: "paperclip-dev.tail29c1aa.ts.net",
- listeners: [{ purpose: "app", publicPort: 42002, targetPort: 42002 }],
- brokerRef: "service-web",
- lastError,
- updatedAt: "2026-08-12T00:00:00.000Z",
- },
- }),
- ],
- canStartServices: true,
- });
-
- const root = createRoot(container);
- act(() => {
- root.render(withQueryClient(
- ,
- ));
- });
-
- const alert = container.querySelector('[role="alert"]');
- const summary = alert?.firstElementChild;
- expect(alert?.classList.contains("text-destructive")).toBe(true);
- expect(summary?.classList.contains("line-clamp-3")).toBe(true);
- expect(summary?.getAttribute("title")).toBe(lastError);
- expect(alert?.textContent).toContain(label);
- expect(alert?.textContent).toContain(lastError);
- expect(alert?.textContent).toContain(remediation);
-
- act(() => root.unmount());
- },
- );
-
- it("can render square plain surfaces for embedded configuration pages", () => {
- const sections = buildWorkspaceRuntimeControlSections({
- runtimeConfig: {
- commands: [
- { id: "web", name: "web", kind: "service", command: "pnpm dev" },
- ],
- },
- runtimeServices: [],
- canStartServices: true,
- });
-
- const root = createRoot(container);
- act(() => {
- root.render(withQueryClient(
- ,
- ));
- });
-
- const summaryPanel = container.querySelector(".border.border-border\\/70");
- const servicePanel = Array.from(container.querySelectorAll(".border.border-border\\/80"))
- .find((element) => element.textContent?.includes("web"));
- const startButton = Array.from(container.querySelectorAll("button"))
- .find((button) => button.textContent?.trim() === "Start");
-
- expect(summaryPanel?.className).toContain("rounded-none");
- expect(summaryPanel?.className).not.toContain("bg-background/60");
- expect(servicePanel?.className).toContain("rounded-none");
- expect(startButton?.className).toContain("rounded-none");
-
- act(() => root.unmount());
- });
-});
-
-describe("buildWorkspaceServiceControlEntries", () => {
- const sections = () => buildWorkspaceRuntimeControlSections({
- runtimeConfig: {
- commands: [
- { id: "web", name: "web", kind: "service", command: "pnpm dev" },
- { id: "db-migrate", name: "db:migrate", kind: "job", command: "pnpm db:migrate" },
- ],
- },
- runtimeServices: [
- createRuntimeService({
- id: "service-web",
- serviceName: "web",
- status: "running",
- url: "http://localhost:3100",
- port: 3100,
- healthStatus: "healthy",
- }),
- ],
- canStartServices: true,
- canRunJobs: true,
- });
-
- it("maps service items to control bar entries and excludes jobs", () => {
- const entries = buildWorkspaceServiceControlEntries({ sections: sections() });
-
- expect(entries).toEqual([
- expect.objectContaining({
- name: "web",
- state: "running",
- url: "http://localhost:3100",
- port: 3100,
- healthStatus: "healthy",
- failureDetail: null,
- }),
- ]);
- });
-
- it("overlays transitional states from the pending mutation", () => {
- const built = sections();
- const entries = buildWorkspaceServiceControlEntries({
- sections: built,
- isPending: true,
- pendingRequest: {
- action: "stop",
- workspaceCommandId: built.services[0].workspaceCommandId ?? null,
- runtimeServiceId: built.services[0].runtimeServiceId ?? null,
- serviceIndex: built.services[0].serviceIndex ?? null,
- },
- });
-
- expect(entries[0].state).toBe("stopping");
- });
-
- it("overlays every service targeted by a bulk mutation", () => {
- const built = buildWorkspaceRuntimeControlSections({
- runtimeConfig: {
- commands: [
- { id: "web", name: "web", kind: "service", command: "pnpm dev" },
- { id: "api", name: "api", kind: "service", command: "pnpm api" },
- ],
- },
- runtimeServices: [
- createRuntimeService({ id: "service-web", serviceName: "web", status: "running" }),
- createRuntimeService({
- id: "service-api",
- serviceName: "api",
- status: "running",
- command: "pnpm api",
- }),
- ],
- canStartServices: true,
- });
- const pendingRequests = resolveWorkspaceServiceControlRequests(built, "stop", null);
-
- const entries = buildWorkspaceServiceControlEntries({ sections: built, pendingRequests });
-
- expect(entries.map((entry) => entry.state)).toEqual(["stopping", "stopping"]);
- });
-
- it("maps a provisioning runtime service to the provisioning control state", () => {
- const provisioning = createRuntimeService({
- id: "service-web",
- serviceName: "web",
- status: "provisioning",
- });
- const built = buildWorkspaceRuntimeControlSections({
- runtimeConfig: { commands: [{ id: "web", name: "web", kind: "service", command: "pnpm dev" }] },
- runtimeServices: [provisioning],
- canStartServices: true,
- });
-
- expect(built.services[0]).toMatchObject({ statusLabel: "provisioning", runtimeServiceId: "service-web" });
-
- const entries = buildWorkspaceServiceControlEntries({ sections: built, runtimeServices: [provisioning] });
- expect(entries[0].state).toBe("provisioning");
- });
-
- it("surfaces a provisioning stale runtime service in otherServices", () => {
- const provisioning = createRuntimeService({
- id: "service-web",
- serviceName: "web",
- status: "provisioning",
- command: "pnpm dev",
- });
- const built = buildWorkspaceRuntimeControlSections({
- runtimeConfig: {
- commands: [{ id: "web", name: "web", kind: "service", command: "pnpm dev:once --tailscale-auth" }],
- },
- runtimeServices: [provisioning],
- canStartServices: true,
- });
-
- expect(built.otherServices).toEqual([
- expect.objectContaining({ title: "web", statusLabel: "provisioning", runtimeServiceId: "service-web" }),
- ]);
- });
-
- it("builds a failure detail line from the stopped runtime service", () => {
- const failed = createRuntimeService({
- id: "service-web",
- serviceName: "web",
- status: "failed",
- stoppedAt: new Date(Date.now() - 60_000),
- });
- const built = buildWorkspaceRuntimeControlSections({
- runtimeConfig: { commands: [{ id: "web", name: "web", kind: "service", command: "pnpm dev" }] },
- runtimeServices: [failed],
- canStartServices: true,
- });
- const entries = buildWorkspaceServiceControlEntries({
- sections: built,
- runtimeServices: [failed],
- });
-
- expect(entries[0].state).toBe("failed");
- expect(entries[0].failureDetail).toMatch(/^Service failed · /);
- });
-
- it("surfaces HTTPS failure independently while the backend remains running", () => {
- const running = createRuntimeService({
- status: "running",
- healthStatus: "healthy",
- port: 42000,
- url: null,
- exposure: {
- provider: "tailscale_https",
- state: "failed",
- publicUrl: null,
- hostname: "runner.tail123.ts.net",
- listeners: [{ purpose: "app", publicPort: 42000, targetPort: 42000 }],
- brokerRef: "service-1",
- lastError: "cli_error",
- updatedAt: "2026-08-11T00:00:00.000Z",
- },
- });
- const built = buildWorkspaceRuntimeControlSections({
- runtimeConfig: { commands: [{ id: "web", name: "web", kind: "service", command: "pnpm dev" }] },
- runtimeServices: [running],
- canStartServices: true,
- });
- const [entry] = buildWorkspaceServiceControlEntries({ sections: built, runtimeServices: [running] });
-
- expect(entry.state).toBe("running");
- expect(entry.exposureState).toBe("failed");
- expect(entry.exposureDetail).toMatch(/^HTTPS unavailable/);
- expect(entry.exposureDetail).not.toContain("cli_error");
- });
-
- it("carries the verified HTTPS URL into the launch entry, and no HTTP fallback while pending", () => {
- // PAP-17158: the workspace/project/issue launch links are rendered from these
- // entries, so the tailnet HTTPS URL has to survive the mapping intact — and a
- // service whose exposure is not yet verified must offer no URL at all rather
- // than the loopback backend it is really listening on.
- const httpsUrl = "https://paperclip-dev.tail29c1aa.ts.net:42010";
- const buildEntry = (service: ReturnType) => {
- const sections = buildWorkspaceRuntimeControlSections({
- runtimeConfig: { commands: [{ id: "web", name: "web", kind: "service", command: "pnpm dev" }] },
- runtimeServices: [service],
- canStartServices: true,
- });
- return buildWorkspaceServiceControlEntries({ sections, runtimeServices: [service] })[0];
- };
-
- const ready = buildEntry(createRuntimeService({
- status: "running",
- healthStatus: "healthy",
- port: 42_010,
- url: httpsUrl,
- exposure: {
- provider: "tailscale_https",
- state: "ready",
- publicUrl: httpsUrl,
- hostname: "paperclip-dev.tail29c1aa.ts.net",
- listeners: [
- { purpose: "app", publicPort: 42_010, targetPort: 42_010 },
- { purpose: "vite_hmr", publicPort: 52_010, targetPort: 52_010 },
- ],
- brokerRef: "service-1",
- lastError: null,
- updatedAt: "2026-08-12T00:00:00.000Z",
- },
- }));
- expect(ready.state).toBe("running");
- expect(ready.url).toBe(httpsUrl);
- expect(ready.exposureState).toBe("ready");
- // A ready exposure reports plainly and never as a remediation prompt.
- expect(ready.exposureDetail).toBe("HTTPS ready");
- expect(ready.exposureDetail).not.toMatch(/unavailable|cleanup|Check the/i);
-
- const pending = buildEntry(createRuntimeService({
- status: "running",
- healthStatus: "healthy",
- port: 42_020,
- url: null,
- exposure: {
- provider: "tailscale_https",
- state: "pending",
- publicUrl: null,
- hostname: "paperclip-dev.tail29c1aa.ts.net",
- listeners: [],
- brokerRef: null,
- lastError: null,
- updatedAt: "2026-08-12T00:00:00.000Z",
- },
- }));
- expect(pending.url ?? null).toBeNull();
- expect(pending.exposureDetail).toBe("Provisioning HTTPS…");
- expect(JSON.stringify(pending)).not.toContain("http://");
- });
-});
-
-describe("resolveWorkspaceServiceControlRequests", () => {
- const mixedSections = () => buildWorkspaceRuntimeControlSections({
- runtimeConfig: {
- commands: [
- { id: "web", name: "web", kind: "service", command: "pnpm dev" },
- { id: "api", name: "api", kind: "service", command: "pnpm api" },
- ],
- },
- runtimeServices: [
- createRuntimeService({ id: "service-web", serviceName: "web", status: "running" }),
- ],
- canStartServices: true,
- });
-
- it("targets a single service by key", () => {
- const built = mixedSections();
- const requests = resolveWorkspaceServiceControlRequests(built, "stop", built.services[0].key);
-
- expect(requests).toEqual([
- expect.objectContaining({ action: "stop", workspaceCommandId: "web", runtimeServiceId: "service-web" }),
- ]);
- });
-
- it("stops only active services for the aggregate stop", () => {
- const requests = resolveWorkspaceServiceControlRequests(mixedSections(), "stop", null);
-
- expect(requests).toEqual([expect.objectContaining({ action: "stop", workspaceCommandId: "web" })]);
- });
-
- it("starts only inactive services for the aggregate start", () => {
- const requests = resolveWorkspaceServiceControlRequests(mixedSections(), "start", null);
-
- expect(requests).toEqual([expect.objectContaining({ action: "start", workspaceCommandId: "api" })]);
- });
-
- it("restarts active services and starts stopped ones for the aggregate restart", () => {
- const requests = resolveWorkspaceServiceControlRequests(mixedSections(), "restart", null);
-
- expect(requests).toEqual([
- expect.objectContaining({ action: "restart", workspaceCommandId: "web" }),
- expect.objectContaining({ action: "start", workspaceCommandId: "api" }),
- ]);
- });
-});
diff --git a/ui/src/components/ai-connections/AiConnectionAccountControls.test.tsx b/ui/src/components/ai-connections/AiConnectionAccountControls.test.tsx
deleted file mode 100644
index 762d3ca2bbd..00000000000
--- a/ui/src/components/ai-connections/AiConnectionAccountControls.test.tsx
+++ /dev/null
@@ -1,18 +0,0 @@
-// @vitest-environment jsdom
-import { renderToStaticMarkup } from "react-dom/server";
-import { afterEach, expect, it, vi } from "vitest";
-import type { ConnectionGrant } from "@paperclipai/shared";
-import { AiConnectionAccountControls } from "./AiConnectionAccountControls";
-import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils";
-
-afterEach(() => { document.body.innerHTML = ""; });
-
-it("masks the account label line in session replay", () => {
- document.body.innerHTML = renderToStaticMarkup();
- expect(replayLeaks("tamsin.vale@example.test")).toEqual({ rendered: true, recorded: false });
- expect(replayLeaks("Reconnect")).toEqual({ rendered: true, recorded: true });
-});
diff --git a/ui/src/components/ai-connections/AiConnectionAccountDetails.test.tsx b/ui/src/components/ai-connections/AiConnectionAccountDetails.test.tsx
deleted file mode 100644
index c6178f4a05f..00000000000
--- a/ui/src/components/ai-connections/AiConnectionAccountDetails.test.tsx
+++ /dev/null
@@ -1,166 +0,0 @@
-// @vitest-environment jsdom
-import { act } from "react";
-import { createRoot } from "react-dom/client";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { afterEach, beforeEach, expect, it, vi } from "vitest";
-import type { AiConnectionAccountIdentity, AiManagedConnectionSummary, ConnectionGrant, ToolConnection } from "@paperclipai/shared";
-import { AiConnectionAccountDetails } from "./AiConnectionAccountDetails";
-import { ManagedAiConnectionDetails } from "./ManagedAiConnectionDetails";
-import { TooltipProvider } from "@/components/ui/tooltip";
-import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils";
-
-vi.mock("@/lib/router", () => ({ useNavigate: () => vi.fn() }));
-vi.mock("@/api/auth", () => ({ authApi: { getSession: vi.fn(async () => ({ user: { id: "user" } })) } }));
-
-const account: AiManagedConnectionSummary = {
- id: "connection", grantId: "grant", companyId: "company", provider: "anthropic", method: "subscription",
- name: "Saved Claude", ownership: "personal", ownerName: "Sam", ownerUserId: "user", isDefault: true, status: "connected",
-};
-const grant = { id: account.grantId, updatedAt: new Date("2020-01-01T00:00:00.000Z"), capabilities: { canRevoke: true, canEditAudience: false } } as ConnectionGrant;
-const known: AiConnectionAccountIdentity = { connectionId: account.id, grantId: grant.id, status: "available", accountLabel: "avery@example.test", organizationLabel: "Example team", checkedAt: "2020-01-01T00:00:00.000Z" };
-let root: ReturnType;
-let host: HTMLDivElement;
-let client: QueryClient;
-let observation: AiConnectionAccountIdentity;
-let blocked: boolean;
-let signals: AbortSignal[];
-const fetchMock = vi.fn();
-
-beforeEach(() => {
- vi.useFakeTimers();
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- vi.stubGlobal("fetch", fetchMock);
- observation = known;
- blocked = false;
- signals = [];
- fetchMock.mockReset().mockImplementation((url: string, init: RequestInit) => {
- if (url.includes("/identity?")) {
- if (blocked) {
- const signal = init.signal as AbortSignal;
- signals.push(signal);
- return new Promise((_resolve, reject) => signal.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")), { once: true }));
- }
- return Promise.resolve(Response.json(observation));
- }
- if (url.endsWith("/active-runs")) return Promise.resolve(Response.json([]));
- if (url.endsWith("/grants")) return Promise.resolve(Response.json({ currentUserId: "user", grants: [grant] }));
- return Promise.resolve(Response.json({ currentUserId: "user", connections: [account], pools: [], canManageConnections: true }));
- });
- client = new QueryClient({ defaultOptions: { queries: { staleTime: 30_000, gcTime: Infinity } } });
- host = document.createElement("div");
- document.body.append(host);
- root = createRoot(host);
-});
-
-afterEach(async () => {
- await act(async () => root.unmount());
- client.clear();
- host.remove();
- vi.unstubAllGlobals();
- vi.useRealTimers();
-});
-
-async function render(value = account, selectedGrant = grant, completePanel = false) {
- await act(async () => {
- root.render({completePanel
- ?
- : });
- });
- await act(async () => { await vi.advanceTimersByTimeAsync(10); });
- await act(async () => { await vi.advanceTimersByTimeAsync(10); });
-}
-const identityCalls = () => fetchMock.mock.calls.filter(([url]) => url.includes("/identity?"));
-
-it("shows the provider email and organization separately from the Paperclip owner", async () => {
- await render();
- expect(host.textContent).toContain("avery@example.test");
- expect(host.textContent).toContain("Example team");
- expect(host.textContent).toContain("Personal · Sam");
- expect(identityCalls()[0][0]).toBe("/api/companies/company/ai-connections/connection/identity?grantId=grant");
-});
-
-it.each(["Example business", "Personal workspace"])("shows the selected OpenAI workspace %s with the saved email", async workspace => {
- observation = { ...known, accountLabel: null, organizationLabel: workspace };
- await render({ ...account, provider: "openai", accountLabel: "avery@example.test" });
- expect(host.textContent).toContain("avery@example.test");
- expect(host.textContent).toContain(workspace);
- expect(host.textContent).toContain("ChatGPT workspace");
- expect(host.textContent).toContain("Personal · Sam");
- expect(identityCalls()).toHaveLength(1);
-});
-
-it("explains an unavailable OpenAI workspace without guessing from the email or Paperclip access", async () => {
- observation = { ...known, status: "unavailable", accountLabel: null, organizationLabel: null,
- errorCode: "invalid_response", message: "OpenAI did not return the selected workspace name." };
- await render({ ...account, provider: "openai", accountLabel: "avery@example.test" });
- expect(host.textContent).toContain("avery@example.test");
- expect(host.textContent).toContain("ChatGPT workspaceNot available");
- expect(host.textContent).toContain("OpenAI did not return the selected workspace name.");
-});
-
-it("explains profile permission denial while preserving connected account controls", async () => {
- observation = { ...known, status: "unavailable", accountLabel: null, organizationLabel: null, errorCode: "permission_denied", message: "Anthropic did not permit this connection to read the account email." };
- await render(account, grant, true);
- expect(host.textContent).toContain("Default for Claude");
- expect(host.textContent).toContain("Reconnect");
- expect(host.textContent).toContain("did not permit");
- expect(host.textContent).not.toContain("avery@example.test");
- expect(host.textContent).not.toContain("Retry account check");
- await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });
- expect(identityCalls()).toHaveLength(1);
-});
-
-it("keeps maintenance controls visible during a stalled lookup and recovers only the identity request", async () => {
- blocked = true;
- await render(account, grant, true);
- expect(host.textContent).toContain("Default for Claude");
- expect(host.textContent).toContain("Reconnect");
- expect(host.textContent).toContain("Checking account details…");
- await act(async () => { await vi.advanceTimersByTimeAsync(20_001); });
- expect(signals[0].aborted).toBe(true);
- expect(host.textContent).toContain("Default for Claude");
- expect(host.textContent).not.toContain("Checking account details…");
- const ordinaryCalls = fetchMock.mock.calls.length - identityCalls().length;
- blocked = false;
- await act(async () => {
- [...host.querySelectorAll("button")].find(button => button.textContent === "Retry account check")!.click();
- await vi.advanceTimersByTimeAsync(0);
- });
- expect(host.textContent).toContain("avery@example.test");
- expect(fetchMock.mock.calls.length - identityCalls().length).toBe(ordinaryCalls);
-});
-
-it.each(["anthropic", "openai"] as const)("does not show the previous %s credential's identity after the selected grant changes", async provider => {
- await render({ ...account, provider });
- expect(host.textContent).toContain("avery@example.test");
- blocked = true;
- await render({ ...account, provider, grantId: "other-grant" }, { ...grant, id: "other-grant" });
- expect(host.textContent).not.toContain("avery@example.test");
- expect(host.textContent).toContain("Checking account details…");
-});
-
-it.each(["anthropic", "openai"] as const)("uses saved labels for %s API keys without opening an identity request", async provider => {
- await render({ ...account, provider, method: "api_key", accountLabel: "billing@example.test", ownership: "shared" });
- expect(host.textContent).toContain("billing@example.test");
- expect(host.textContent).toContain("Company shared");
- expect(identityCalls()).toHaveLength(0);
-});
-
-it("reuses recent identity observations and invalidates them after reconnect", async () => {
- await render();
- await act(async () => { root.render(null); });
- await render();
- expect(identityCalls()).toHaveLength(1);
- observation = { ...known, accountLabel: "new-account@example.test" };
- await render(account, { ...grant, updatedAt: new Date("2020-01-02T00:00:00.000Z") });
- expect(identityCalls()).toHaveLength(2);
- expect(host.textContent).toContain("new-account@example.test");
- expect(host.textContent).not.toContain("avery@example.test");
-});
-
-it("masks the provider account and organization labels in session replay", async () => {
- observation = { ...known, accountLabel: "perrin.ashdown@example.test", organizationLabel: "Brackenridge Analytics" };
- await render();
- expect(replayLeaks("perrin.ashdown@example.test", document.body)).toEqual({ rendered: true, recorded: false });
- expect(replayLeaks("Brackenridge Analytics", document.body)).toEqual({ rendered: true, recorded: false });
-});
diff --git a/ui/src/components/ai-connections/AiConnectionField.test.tsx b/ui/src/components/ai-connections/AiConnectionField.test.tsx
deleted file mode 100644
index a2a6a43dc88..00000000000
--- a/ui/src/components/ai-connections/AiConnectionField.test.tsx
+++ /dev/null
@@ -1,271 +0,0 @@
-// @vitest-environment jsdom
-import { flushSync } from "react-dom";
-import { createRoot, type Root } from "react-dom/client";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { afterEach, beforeEach, expect, it, vi } from "vitest";
-import type { ComponentProps } from "react";
-import type { AiManagedConnectionSummary } from "@paperclipai/shared";
-import { AiConnectionField, aiProviderForAdapter } from "./AiConnectionField";
-import { ApiError } from "@/api/client";
-import type { AiConnectionCredentialStep } from "./AiConnectionCredentialStep";
-import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils";
-
-const mocks = vi.hoisted(() => ({ list: vi.fn(), setDefault: vi.fn() }));
-let credentialProps: ComponentProps | undefined;
-vi.mock("@/api/ai-connections", () => ({ aiConnectionsApi: mocks }));
-vi.mock("./AiConnectionCredentialStep", () => ({
- AiConnectionCredentialStep: (props: ComponentProps) => {
- credentialProps = props;
- return Provider sign-in
;
- },
-}));
-vi.mock("./AiProviderSetup", () => ({ AiProviderSetup: () => Advanced provider setup
}));
-vi.mock("@/pages/apps/AppLogo", () => ({ AppLogo: () => null }));
-
-let root: Root;
-let container: HTMLDivElement;
-let client: QueryClient;
-const onChange = vi.fn();
-const account = (overrides: Partial = {}): AiManagedConnectionSummary => ({
- id: "old-connection", grantId: "old-grant", companyId: "company",
- provider: "anthropic", method: "subscription", name: "My Claude",
- ownership: "personal", ownerUserId: "owner", isDefault: true,
- status: "needs_attention", ...overrides,
-});
-async function settle() {
- for (let i = 0; i < 5; i++) {
- await new Promise(resolve => setTimeout(resolve, 0));
- flushSync(() => {});
- }
-}
-async function mount(connections: AiManagedConnectionSummary[], canManageConnections = true, preferAdvanced = false, props: Partial> = {}) {
- mocks.list.mockResolvedValue({ currentUserId: "owner", connections, canManageConnections });
- flushSync(() => root.render(
-
- ));
- await settle();
-}
-async function click(label: string) {
- if (label === "Connect another account") {
- const trigger = document.querySelector('[role="combobox"][aria-label="Connection"]')!;
- flushSync(() => trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })));
- await settle();
- const option = Array.from(document.querySelectorAll('[role="option"]')).find(item => item.textContent?.includes("Connect an account"));
- expect(option).toBeDefined();
- flushSync(() => option!.click());
- await settle();
- return;
- }
- const button = Array.from(document.querySelectorAll("button")).find(item => item.textContent === label);
- expect(button, `Missing button: ${label}`).toBeDefined();
- flushSync(() => button!.click());
-}
-beforeEach(() => {
- vi.clearAllMocks();
- credentialProps = undefined;
- mocks.setDefault.mockResolvedValue({});
- container = document.createElement("div");
- document.body.append(container);
- root = createRoot(container);
- client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
-});
-
-it("disables a saved Claude subscription after the harness changes to Codex", async () => {
- const value = { provider: "anthropic" as const, method: "subscription" as const, mode: "shared" as const,
- connectionId: "11111111-1111-4111-8111-111111111111", grantId: "22222222-2222-4222-8222-222222222222" };
- const connections = [account({ id: value.connectionId, grantId: value.grantId, ownership: "shared", status: "connected" })];
- await mount(connections, true, false, { value });
- await mount(connections, true, false, { value, adapterType: "codex_local" });
- const trigger = container.querySelector('[role="combobox"][aria-label="Connection"]')!;
- flushSync(() => trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })));
- await settle();
- const option = [...document.querySelectorAll('[role="option"]')].find(option => option.textContent?.includes("My Claude"));
- expect(option?.getAttribute("aria-disabled")).toBe("true");
- expect(option?.textContent).toContain("Incompatible with this harness and model");
- expect(onChange).not.toHaveBeenCalled();
-});
-afterEach(() => { flushSync(() => root.unmount()); client.clear(); container.remove(); });
-
-it("reconnects the unavailable personal default in place", async () => {
- await mount([account()]);
- await click("Reconnect account");
- expect(credentialProps).toMatchObject({ connectionId: "old-connection", initialMethod: "subscription", fixedMethod: true });
- credentialProps!.onComplete({ connectionId: "old-connection", grantId: "old-grant", method: "subscription" });
- await settle();
- expect(mocks.setDefault).not.toHaveBeenCalled();
- expect(onChange).toHaveBeenCalledWith({ provider: "anthropic", method: "subscription", mode: "responsible_user" });
-});
-
-it("identifies duplicate-named accounts before adopting the exact personal grant", async () => {
- const personal = account({ id: "00000000-0000-4000-8000-000000000001", grantId: "00000000-0000-4000-8000-000000000002", provider: "openai", method: "api_key", name: "OpenAI", ownerName: "Avery", status: "connected", isDefault: false });
- const shared = account({ id: "00000000-0000-4000-8000-000000000003", grantId: "00000000-0000-4000-8000-000000000004", provider: "openai", method: "subscription", name: "OpenAI", accountLabel: "engineering@example.test", ownership: "shared", ownerUserId: undefined, status: "connected", isDefault: false });
- const sharedKey = account({ id: "00000000-0000-4000-8000-000000000005", grantId: "00000000-0000-4000-8000-000000000006", provider: "openai", method: "api_key", name: "OpenAI", ownerName: "Engineering", ownership: "shared", ownerUserId: undefined, status: "connected", isDefault: false });
- const unavailable = account({ id: "expired-account", grantId: "expired-grant", provider: "openai", method: "api_key", name: "Expired account", ownerName: "Avery" });
- mocks.list.mockResolvedValue({ currentUserId: "owner", connections: [shared, personal, sharedKey, unavailable], canManageConnections: true });
- flushSync(() => root.render(
-
- ));
- await settle();
- await click("Choose a managed connection");
- const trigger = container.querySelector('[role="combobox"][aria-label="Connection"]')!;
- flushSync(() => trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })));
- await settle();
- const choices = [...document.querySelectorAll('[role="option"]')];
- expect(choices.map(choice => choice.textContent)).toContain("OpenAI · API key · Personal · Avery");
- expect(choices.map(choice => choice.textContent)).toContain("OpenAI · ChatGPT subscription · Company shared · engineering@example.test");
- expect(choices.map(choice => choice.textContent)).toContain("OpenAI · API key · Company shared · Engineering");
- expect(choices.find(choice => choice.textContent?.includes("Expired account"))?.getAttribute("aria-disabled")).toBe("true");
- flushSync(() => choices.find(choice => choice.textContent === "OpenAI · API key · Personal · Avery")!.click());
- await settle();
- expect(document.querySelector('[role="dialog"]')?.textContent).toContain("OpenAI · API key · Personal · Avery");
- expect(onChange).not.toHaveBeenCalled();
- await click("Use this binding when saved");
- expect(onChange).toHaveBeenCalledExactlyOnceWith({ provider: "openai", method: "api_key", mode: "delegated", connectionId: personal.id, grantId: personal.grantId });
-});
-
-it("opens provider setup directly when connecting from the advanced mode", async () => {
- await mount([], true, true);
- await click("Connect another account");
- expect(document.body.textContent).toContain("Advanced provider setup");
- expect(credentialProps).toBeUndefined();
-});
-
-it("selects the returned new grant and actual method before adopting the personal default", async () => {
- await mount([account()]);
- await click("Connect another account");
- expect(document.body.textContent).toContain("default");
- expect(credentialProps).toMatchObject({ connectionId: undefined, allAgents: true });
- let resolveDefault!: () => void;
- mocks.setDefault.mockImplementation(() => new Promise(resolve => { resolveDefault = resolve; }));
- credentialProps!.onComplete({ connectionId: "new-connection", grantId: "new-grant", method: "api_key" });
- await settle();
- expect(mocks.setDefault).toHaveBeenCalledWith("company", "new-grant");
- expect(onChange).not.toHaveBeenCalled();
- resolveDefault();
- await settle();
- expect(onChange).toHaveBeenCalledWith({ provider: "anthropic", method: "api_key", mode: "responsible_user" });
-});
-
-it("lets the owner limit a new personal connection to this agent", async () => {
- await mount([]);
- await click("Connect another account");
- const checkbox = document.querySelector('[role="checkbox"]')!;
- expect(checkbox).not.toBeNull();
- expect(checkbox.getAttribute("aria-checked")).toBe("true");
- flushSync(() => checkbox.click());
- expect(credentialProps).toMatchObject({ allAgents: false, agentIds: ["agent"] });
-});
-
-it("keeps default-update failures visible and retries without another provider login", async () => {
- await mount([account()]);
- await click("Connect another account");
- mocks.setDefault.mockRejectedValueOnce(new Error("Default update failed"));
- credentialProps!.onComplete({ connectionId: "new-connection", grantId: "new-grant", method: "api_key" });
- await settle();
- expect(document.body.textContent).toContain("Default update failed");
- expect(onChange).not.toHaveBeenCalled();
- await click("Retry default selection");
- await settle();
- expect(mocks.setDefault).toHaveBeenCalledTimes(2);
- expect(onChange).toHaveBeenCalledWith({ provider: "anthropic", method: "api_key", mode: "responsible_user" });
-});
-
-it("does not offer reconnection for a healthy default or another owner's account", async () => {
- await mount([account({ status: "connected" }), account({ id: "someone-else", ownerUserId: "other" })]);
- expect(document.body.textContent).not.toContain("Reconnect account");
-});
-
-it("keeps an ordinary member's new connection scoped to the current agent by default", async () => {
- await mount([], false);
- expect(document.body.textContent).toContain("You have no default account");
- await click("Connect another account");
- expect(document.querySelector('[role="checkbox"]')!.disabled).toBe(true);
- expect(credentialProps).toMatchObject({ allAgents: false, agentIds: ["agent"] });
-});
-
-it("uses the server's connection-manager permission for company-wide access", async () => {
- await mount([], true);
- await click("Connect another account");
- expect(credentialProps).toMatchObject({ allAgents: true });
-});
-
-it("offers Pi account selection before choosing its required model", async () => {
- mocks.list.mockResolvedValue({ currentUserId: "owner", connections: [], canManageConnections: true });
- expect(aiProviderForAdapter("pi_local")).toBe("openrouter");
- flushSync(() => root.render(
-
- ));
- await settle();
- expect(document.querySelector('[role="combobox"][aria-label="Connection"]')).not.toBeNull();
- expect(container.textContent).not.toContain("does not support the current harness");
- await click("Connect another account");
- expect(document.body.textContent).toContain("Advanced provider setup");
-});
-
-it.each(["openai", "anthropic", "google", "openrouter"] as const)("keeps a matching saved Pi %s API-key account selectable", async provider => {
- const saved = account({ provider, method: "api_key", name: "Pi provider account", accountLabel: "avery@example.test", status: "connected" });
- mocks.list.mockResolvedValue({ currentUserId: "owner", connections: [saved], canManageConnections: true });
- flushSync(() => root.render(
-
- ));
- await settle();
- expect(container.textContent).toContain("Pi provider account");
- expect(container.textContent).not.toContain("incompatible");
- expect(container.textContent).not.toContain("does not support");
- const trigger = container.querySelector('[role="combobox"][aria-label="Connection"]')!;
- expect(trigger.getAttribute("title")).toBe("Pi provider account · API key · Personal · avery@example.test");
- flushSync(() => trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })));
- await settle();
- const choice = [...document.querySelectorAll('[role="option"]')].find(node => node.textContent?.includes("Pi provider account"));
- expect(choice).toBeDefined();
- expect(choice?.getAttribute("aria-disabled")).not.toBe("true");
-});
-
-it("keeps loaded connections usable when a refetch fails during an outage", async () => {
- await mount([account()]);
- expect(document.body.textContent).toContain("Reconnect account");
- mocks.list.mockRejectedValue(new ApiError("Paperclip is restarting.", 503, { error: "tenant_app_unavailable" }));
- await client.invalidateQueries();
- await settle();
- expect(document.body.textContent).toContain("Reconnect account");
- expect(document.body.textContent).not.toContain("Retry connections");
- expect(document.body.textContent).not.toContain("Paperclip is restarting.");
- expect(document.querySelector('[data-query-view="error"]')).toBeNull();
-});
-
-it("shows readable copy with a retry when connections cannot be loaded", async () => {
- mocks.list.mockRejectedValueOnce(new ApiError("Request failed: 500", 500, { error: "internal_error" }));
- await mount([account()]);
- const alerts = Array.from(document.querySelectorAll('[role="alert"]')).map(node => node.textContent).join(" ");
- expect(alerts).toContain("An unexpected error occurred");
- expect(document.body.textContent).not.toContain("internal_error");
- expect(document.body.textContent).not.toContain("Request failed: 500");
- expect(document.body.textContent).not.toContain("Reconnect account");
- await click("Retry connections");
- await settle();
- expect(mocks.list).toHaveBeenCalledTimes(2);
- expect(document.body.textContent).toContain("Reconnect account");
- expect(document.body.textContent).not.toContain("Retry connections");
-});
-
-it("masks the adoption dialog's account label in session replay", async () => {
- const personal = account({ id: "00000000-0000-4000-8000-000000000011", grantId: "00000000-0000-4000-8000-000000000012", provider: "openai", method: "api_key", name: "OpenAI", accountLabel: "solenne.drake@example.test", status: "connected", isDefault: false });
- mocks.list.mockResolvedValue({ currentUserId: "owner", connections: [personal], canManageConnections: true });
- flushSync(() => root.render(
-
- ));
- await settle();
- await click("Choose a managed connection");
- const trigger = container.querySelector('[role="combobox"][aria-label="Connection"]')!;
- flushSync(() => trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })));
- await settle();
- flushSync(() => [...document.querySelectorAll('[role="option"]')].find(choice => choice.textContent?.includes("solenne.drake@example.test"))!.click());
- await settle();
- const dialog = document.querySelector('[role="dialog"]')!;
- expect(replayLeaks("solenne.drake@example.test", dialog)).toEqual({ rendered: true, recorded: false });
- expect(replayLeaks("Adopt Connections for Nova", dialog)).toEqual({ rendered: true, recorded: false });
-});
diff --git a/ui/src/components/ai-connections/AiConnectionIdentity.test.tsx b/ui/src/components/ai-connections/AiConnectionIdentity.test.tsx
deleted file mode 100644
index 995b589ec25..00000000000
--- a/ui/src/components/ai-connections/AiConnectionIdentity.test.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-// @vitest-environment jsdom
-import { renderToStaticMarkup } from "react-dom/server";
-import { afterEach, expect, it } from "vitest";
-import { AiConnectionIdentity } from "./AiConnectionIdentity";
-import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils";
-
-afterEach(() => { document.body.innerHTML = ""; });
-
-it("masks the connection name and account label in session replay", () => {
- document.body.innerHTML = renderToStaticMarkup();
- expect(replayLeaks("Zephyr Labs Claude")).toEqual({ rendered: true, recorded: false });
- expect(replayLeaks("quill.marten@example.test")).toEqual({ rendered: true, recorded: false });
- expect(replayLeaks("Company shared")).toEqual({ rendered: true, recorded: true });
-});
diff --git a/ui/src/components/ai-connections/AiConnectionPicker.test.tsx b/ui/src/components/ai-connections/AiConnectionPicker.test.tsx
deleted file mode 100644
index 4c96aac1866..00000000000
--- a/ui/src/components/ai-connections/AiConnectionPicker.test.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-// @vitest-environment jsdom
-import { renderToStaticMarkup } from "react-dom/server";
-import { afterEach, expect, it, vi } from "vitest";
-import { AiConnectionPicker } from "./AiConnectionPicker";
-import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils";
-
-afterEach(() => { document.body.innerHTML = ""; });
-
-it("does not offer an OpenRouter connection for an incompatible OpenCode model", () => {
- document.body.innerHTML = renderToStaticMarkup();
- expect(document.body.textContent).not.toContain("Shared router");
- expect(document.querySelector('[aria-label="Responsible user’s connection"]')!.disabled).toBe(true);
- expect(document.body.textContent).toContain("Incompatible with this harness and model");
-});
-
-it("masks a shared connection's account label in session replay", () => {
- document.body.innerHTML = renderToStaticMarkup();
- expect(replayLeaks("orla.brisk@example.test")).toEqual({ rendered: true, recorded: false });
-});
-
-it("masks the responsible user's default connection name in session replay", () => {
- document.body.innerHTML = renderToStaticMarkup();
- expect(replayLeaks("Orla's Claude Max")).toEqual({ rendered: true, recorded: false });
-});
diff --git a/ui/src/components/ai-connections/AiConnectionPoolRunDetails.test.tsx b/ui/src/components/ai-connections/AiConnectionPoolRunDetails.test.tsx
deleted file mode 100644
index 1994e2088a5..00000000000
--- a/ui/src/components/ai-connections/AiConnectionPoolRunDetails.test.tsx
+++ /dev/null
@@ -1,16 +0,0 @@
-// @vitest-environment jsdom
-import { renderToStaticMarkup } from "react-dom/server";
-import { afterEach, expect, it } from "vitest";
-import { AiConnectionPoolRunDetails } from "./AiConnectionPoolRunDetails";
-import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils";
-
-afterEach(() => { document.body.innerHTML = ""; });
-
-it("masks the pinned pool account name in session replay", () => {
- document.body.innerHTML = renderToStaticMarkup();
- expect(replayLeaks("Juniper Ops Pool Account")).toEqual({ rendered: true, recorded: false });
- expect(replayLeaks("claude-sonnet")).toEqual({ rendered: true, recorded: true });
-});
diff --git a/ui/src/components/composer-recovery.test.tsx b/ui/src/components/composer-recovery.test.tsx
deleted file mode 100644
index bdb243114ad..00000000000
--- a/ui/src/components/composer-recovery.test.tsx
+++ /dev/null
@@ -1,106 +0,0 @@
-// @vitest-environment jsdom
-
-import { act, type ReactElement } from "react";
-import { createRoot, type Root } from "react-dom/client";
-import { MemoryRouter } from "react-router-dom";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { IssueChatThread } from "./IssueChatThread";
-import { TaskChatComposer } from "./task-chat/TaskChatComposer";
-import { queryKeys } from "../lib/queryKeys";
-import {
- loadDraftSubmission,
- saveDraft,
- saveDraftAttachments,
- saveDraftSubmission,
-} from "../lib/composer-draft";
-
-vi.mock("./MarkdownEditor", async () => {
- const { forwardRef, useImperativeHandle, useRef } = await import("react");
- return {
- MarkdownEditor: forwardRef(function Editor(
- { value, onChange, readOnly }: { value: string; onChange: (value: string) => void; readOnly?: boolean },
- ref,
- ) {
- const input = useRef(null);
- useImperativeHandle(ref, () => ({ focus: () => input.current?.focus(), clear: () => onChange("") }));
- return