mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +01:00
Merge remote-tracking branch 'origin/master' into swarm-neon-tmp
* origin/master: refactor(ui): prune 36 thin mocked jsdom UI tests and consolidate replay masking checks (#22834) docs: correct three budget claims from the review of the budget docs (#22833) refactor(test): prune 28 completed migration, prose-grep, and Storybook fixture tests (#22832) fix(e2e): observe scheduled native retries before grading tasks (#22826)
This commit is contained in:
commit
83bf07cac4
85 files changed
+397
-15059
No files matched your search
@@ -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'],
|
||||
]) {
|
||||
|
||||
+2
-2
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
<Warning>
|
||||
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).
|
||||
</Warning>
|
||||
|
||||
## 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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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`
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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`
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -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"]);
|
||||
});
|
||||
});
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
@@ -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 = () => <><Action variant="outline" size="sm" /><UI.Button /><Button /><button /></>;
|
||||
`, "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 = () => <><Button {...props} /><Button variant={style} /><Button variant="cta" {...props} /><Button {...props} variant="ghost" /></>;
|
||||
`, "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"]);
|
||||
});
|
||||
@@ -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}`);
|
||||
}
|
||||
});
|
||||
@@ -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<typeof searchRunnerApi>;
|
||||
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<typeof fetch>(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);
|
||||
});
|
||||
@@ -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<typeof searchRunnerApi>;
|
||||
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(); }
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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.");
|
||||
});
|
||||
});
|
||||
@@ -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.
|
||||
@@ -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<string, any>;
|
||||
type AgentJourney = Exclude<keyof typeof agentJourneyRuns,
|
||||
"ask-question"
|
||||
@@ -32,7 +34,10 @@ type AgentJourney = Exclude<keyof typeof agentJourneyRuns,
|
||||
| "saved-skill-use">;
|
||||
interface TaskState { currentIssue: Row & { id: string; status: string }; taskRuns: Array<Row & { status: string }>; comments: Row[]; interactions: Array<Row & { id: string; status: string }>; attachments: StoryDelivery[] }
|
||||
interface Options { deadlineAt: number; directory: string; capture(id: string, label: string, file: string): Promise<void> }
|
||||
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<TaskState, "taskRuns">) {
|
||||
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<Row>(`/api/issues/${created.issueId}`);
|
||||
};
|
||||
const read = async (issue: Row): Promise<TaskState> => {
|
||||
const read = async (issue: Row): Promise<TaskState> => waitFor(options.deadlineAt, async () => {
|
||||
const route = `/api/issues/${issue.id}`;
|
||||
const [currentIssue, summaries, comments, interactions, attachments] = await Promise.all([
|
||||
context.api.get<TaskState["currentIssue"]>(route), context.api.get<Row[]>(`${route}/runs`), context.api.get<Row[]>(`${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<TaskState["taskRuns"][number]>(`/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) => {
|
||||
|
||||
@@ -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<typeof import("../user-actions.js")>(), createTaskThroughUi: vi.fn() }));
|
||||
vi.mock("../protected-action-flow.js", async importOriginal => ({ ...await importOriginal<typeof import("../protected-action-flow.js")>(), decideProtectedActionThroughUi: vi.fn() }));
|
||||
vi.mock("@playwright/test", () => ({ expect: () => ({ toBeVisible: async () => {}, toHaveAttribute: async () => {} }) }));
|
||||
type Row = Record<string, any>;
|
||||
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<number, number>(), 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();
|
||||
});
|
||||
@@ -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<string, any>;
|
||||
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");
|
||||
});
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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']}]);
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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});}
|
||||
});
|
||||
@@ -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(<AccountQuotaPanels accounts={[{
|
||||
provider: "anthropic", accountKey: "key", accountLabel: "fenwick.oriel@example.test", ok: true,
|
||||
windows: [{ label: "Weekly limit", usedPercent: 40, valueLabel: null, resetsAt: null, detail: null }],
|
||||
}]} />);
|
||||
expect(replayLeaks("fenwick.oriel@example.test")).toEqual({ rendered: true, recorded: false });
|
||||
expect(replayLeaks("Weekly limit")).toEqual({ rendered: true, recorded: true });
|
||||
});
|
||||
@@ -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(<AgentSetupPrompt prompt={prompt} />));
|
||||
await act(async () => container.querySelector<HTMLButtonElement>("button")!.click());
|
||||
expect(document.querySelector("pre[aria-label='Setup prompt']")).not.toBeNull();
|
||||
expect(isBlockedFromReplay("pcp_pair_8f3kQz2LmWv", document.body)).toBe(true);
|
||||
});
|
||||
@@ -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(
|
||||
<ThemeProvider>
|
||||
<ApprovalPayloadRenderer
|
||||
type="request_board_approval"
|
||||
payload={{
|
||||
title: "Reply with an ASCII frog",
|
||||
summary: "Board asked for approval before posting the frog.",
|
||||
recommendedAction: "Approve the frog reply.",
|
||||
nextActionOnApproval: "Post the frog comment on the issue.",
|
||||
risks: ["The frog might be too powerful."],
|
||||
proposedComment: "(o)<",
|
||||
}}
|
||||
/>
|
||||
</ThemeProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
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(
|
||||
<ThemeProvider>
|
||||
<ApprovalPayloadRenderer
|
||||
type="request_board_approval"
|
||||
payload={{
|
||||
title: "Reply with an ASCII frog",
|
||||
summary: "**Bold** and `code` and [a link](https://example.com).",
|
||||
recommendedAction: "Approve the **frog** reply.",
|
||||
nextActionOnApproval: "Post the `frog` comment.",
|
||||
risks: ["The **frog** might be too powerful."],
|
||||
}}
|
||||
/>
|
||||
</ThemeProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
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(
|
||||
<ThemeProvider>
|
||||
<ApprovalPayloadRenderer
|
||||
type="request_board_approval"
|
||||
payload={{
|
||||
title: "Reply with an ASCII frog",
|
||||
risks: [
|
||||
"- **Leading dash** risk.",
|
||||
"* Leading star risk.",
|
||||
"• Leading dot risk.",
|
||||
"1. Leading number risk.",
|
||||
"2) Leading paren risk.",
|
||||
],
|
||||
}}
|
||||
/>
|
||||
</ThemeProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
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(
|
||||
<ThemeProvider>
|
||||
<ApprovalPayloadRenderer
|
||||
type="request_board_approval"
|
||||
payload={{
|
||||
title: "Reply with an ASCII frog",
|
||||
risks: ["- Low probability", "* Low probability"],
|
||||
}}
|
||||
/>
|
||||
</ThemeProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
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(
|
||||
<ThemeProvider>
|
||||
<ApprovalPayloadRenderer
|
||||
type="request_board_approval"
|
||||
hidePrimaryTitle
|
||||
payload={{
|
||||
title: "Reply with an ASCII frog",
|
||||
summary: "Board asked for approval before posting the frog.",
|
||||
}}
|
||||
/>
|
||||
</ThemeProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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> = {}): 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(
|
||||
<BudgetIncidentCard incident={value} onKeepPaused={onKeepPaused} onRaiseAndResume={onRaiseAndResume} />,
|
||||
));
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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<typeof import("@/api/cases")>()),
|
||||
casesApi: mockCasesApi,
|
||||
}));
|
||||
vi.mock("@/components/MarkdownBody", () => ({
|
||||
MarkdownBody: ({ children }: { children: string }) => <div data-testid="md">{children}</div>,
|
||||
}));
|
||||
vi.mock("@/lib/router", () => ({
|
||||
Link: ({ children, to, ...props }: AnchorHTMLAttributes<HTMLAnchorElement> & { to: string }) => (
|
||||
<a href={to} {...props}>{children}</a>
|
||||
),
|
||||
}));
|
||||
|
||||
(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(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<CaseRevisionRail caseIdentifier="PAP-C7" documentKey="body" />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
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());
|
||||
});
|
||||
});
|
||||
@@ -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<typeof createRoot>;
|
||||
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 <><textarea defaultValue="Keep my unsent reply" /><DeferredOverlay requested={requested} title="New task" onClose={() => setRequested(false)}><Failed /></DeferredOverlay></>;
|
||||
}
|
||||
await act(async () => root.render(<Board />));
|
||||
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<never>((_, rejectImport) => { reject = rejectImport; }));
|
||||
function render(requested: boolean) {
|
||||
return <><textarea defaultValue="Saved draft" /><DeferredOverlay requested={requested} title="Setup" onClose={() => {}}><Pending /></DeferredOverlay></>;
|
||||
}
|
||||
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<never>(() => {}));
|
||||
function Board() {
|
||||
const [requested, setRequested] = useState(true);
|
||||
return <DeferredOverlay requested={requested} title="New project" onClose={() => setRequested(false)}><Pending /></DeferredOverlay>;
|
||||
}
|
||||
await act(async () => root.render(<Board />));
|
||||
const cancel = [...document.querySelectorAll("button")].find((button) => button.textContent === "Cancel")!;
|
||||
await act(async () => cancel.click());
|
||||
expect(document.querySelector('[role="dialog"]')).toBeNull();
|
||||
});
|
||||
@@ -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(<QueryClientProvider client={client}><EmailConnectionAccess companyId="company" connectionId="connection" agents={[]} /></QueryClientProvider>));
|
||||
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"));
|
||||
}
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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">) => (
|
||||
<a href={to} {...props}>{children}</a>
|
||||
),
|
||||
}));
|
||||
|
||||
// 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> = {}): 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> = {}): 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> = {}): 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> = {}): 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<ComponentProps<typeof IssueRunLedgerContent>> = {}) {
|
||||
render(
|
||||
<IssueRunLedgerContent
|
||||
runs={props.runs ?? []}
|
||||
liveRuns={props.liveRuns}
|
||||
activeRun={props.activeRun}
|
||||
issueStatus={props.issueStatus ?? "in_progress"}
|
||||
childIssues={props.childIssues ?? []}
|
||||
agentMap={props.agentMap ?? new Map([["agent-1", { name: "CodexCoder" }]])}
|
||||
activityEvents={props.activityEvents}
|
||||
renderActivityEvent={props.renderActivityEvent}
|
||||
resolveUserLabel={props.resolveUserLabel}
|
||||
pendingWatchdogDecision={props.pendingWatchdogDecision}
|
||||
canRecordWatchdogDecisions={props.canRecordWatchdogDecisions}
|
||||
watchdogDecisionError={props.watchdogDecisionError}
|
||||
onWatchdogDecision={props.onWatchdogDecision}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
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) => (
|
||||
<div data-testid={`activity-${event.id}`}>{event.action}</div>
|
||||
),
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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<HTMLAnchorElement> & {
|
||||
to: string;
|
||||
disableIssueQuicklook?: boolean;
|
||||
}) => (
|
||||
<a href={to} {...props}>{children}</a>
|
||||
),
|
||||
}));
|
||||
|
||||
// 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<React.ComponentProps<typeof KanbanBoard>> & { issues: Issue[] },
|
||||
) {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
mountedRoots.push(root);
|
||||
|
||||
const render = (nextProps: Partial<React.ComponentProps<typeof KanbanBoard>> & { issues: Issue[] }) => {
|
||||
act(() => {
|
||||
root.render(
|
||||
<KanbanBoard
|
||||
agents={[{ id: "agent-1", name: "Codex" }]}
|
||||
liveIssueIds={new Set(["issue-todo-1"])}
|
||||
onUpdateIssue={vi.fn()}
|
||||
{...nextProps}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
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();
|
||||
});
|
||||
@@ -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> = {}): 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<Parameters<typeof WorkspaceAccessCard>[0]> = {}) {
|
||||
const handlers = {
|
||||
onOpen: vi.fn(),
|
||||
onStart: vi.fn(),
|
||||
onRepair: vi.fn(),
|
||||
onViewLogs: vi.fn(),
|
||||
};
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(<WorkspaceAccessCard access={accessState()} {...handlers} {...props} />);
|
||||
});
|
||||
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());
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<string, unknown> | null = {}) {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
if (experimentalSettings) {
|
||||
queryClient.setQueryData(queryKeys.instance.experimentalSettings, experimentalSettings);
|
||||
}
|
||||
return <QueryClientProvider client={queryClient}>{node}</QueryClientProvider>;
|
||||
}
|
||||
|
||||
function createRuntimeService(overrides: Partial<WorkspaceRuntimeService> = {}): 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(
|
||||
<WorkspaceRuntimeControls sections={sections} onAction={vi.fn()} />,
|
||||
{},
|
||||
));
|
||||
});
|
||||
|
||||
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(
|
||||
<WorkspaceRuntimeControls sections={sections} onAction={vi.fn()} />,
|
||||
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(
|
||||
<WorkspaceRuntimeControls sections={sections} onAction={vi.fn()} />,
|
||||
{ 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(
|
||||
<WorkspaceRuntimeControls
|
||||
sections={sections}
|
||||
onAction={vi.fn()}
|
||||
/>,
|
||||
));
|
||||
});
|
||||
|
||||
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(
|
||||
<WorkspaceRuntimeQuickControls
|
||||
sections={sections}
|
||||
onAction={vi.fn()}
|
||||
/>,
|
||||
));
|
||||
});
|
||||
|
||||
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(
|
||||
<WorkspaceRuntimeControls
|
||||
sections={sections}
|
||||
disabledHint="Add a workspace path first."
|
||||
onAction={vi.fn()}
|
||||
/>,
|
||||
));
|
||||
});
|
||||
|
||||
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(
|
||||
<WorkspaceRuntimeControls
|
||||
sections={sections}
|
||||
disabledHint="Add runtime settings first."
|
||||
onAction={vi.fn()}
|
||||
/>,
|
||||
));
|
||||
});
|
||||
|
||||
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(
|
||||
<WorkspaceRuntimeControls
|
||||
sections={sections}
|
||||
onAction={vi.fn()}
|
||||
/>,
|
||||
));
|
||||
});
|
||||
|
||||
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(
|
||||
<WorkspaceRuntimeControls
|
||||
sections={sections}
|
||||
onAction={vi.fn()}
|
||||
/>,
|
||||
));
|
||||
});
|
||||
|
||||
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(
|
||||
<WorkspaceRuntimeControls
|
||||
sections={sections}
|
||||
square
|
||||
onAction={vi.fn()}
|
||||
/>,
|
||||
));
|
||||
});
|
||||
|
||||
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<typeof createRuntimeService>) => {
|
||||
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" }),
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -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(<AiConnectionAccountControls
|
||||
account={{ id: "connection", grantId: "grant", companyId: "company", provider: "openai", method: "subscription",
|
||||
name: "Team ChatGPT", accountLabel: "tamsin.vale@example.test", ownership: "shared", status: "connected" }}
|
||||
grant={{ id: "grant", capabilities: { canRevoke: true, canEditAudience: false } } as ConnectionGrant}
|
||||
currentUserId="user" onMakeDefault={vi.fn()} onReconnect={vi.fn()} onRevoke={vi.fn()} />);
|
||||
expect(replayLeaks("tamsin.vale@example.test")).toEqual({ rendered: true, recorded: false });
|
||||
expect(replayLeaks("Reconnect")).toEqual({ rendered: true, recorded: true });
|
||||
});
|
||||
@@ -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<typeof createRoot>;
|
||||
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(<QueryClientProvider client={client}><TooltipProvider>{completePanel
|
||||
? <ManagedAiConnectionDetails connection={{ id: value.id, companyId: value.companyId } as ToolConnection} />
|
||||
: <AiConnectionAccountDetails account={value} grant={selectedGrant} />}</TooltipProvider></QueryClientProvider>);
|
||||
});
|
||||
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 });
|
||||
});
|
||||
@@ -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<typeof AiConnectionCredentialStep> | undefined;
|
||||
vi.mock("@/api/ai-connections", () => ({ aiConnectionsApi: mocks }));
|
||||
vi.mock("./AiConnectionCredentialStep", () => ({
|
||||
AiConnectionCredentialStep: (props: ComponentProps<typeof AiConnectionCredentialStep>) => {
|
||||
credentialProps = props;
|
||||
return <div>Provider sign-in</div>;
|
||||
},
|
||||
}));
|
||||
vi.mock("./AiProviderSetup", () => ({ AiProviderSetup: () => <div>Advanced provider setup</div> }));
|
||||
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> = {}): 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<ComponentProps<typeof AiConnectionField>> = {}) {
|
||||
mocks.list.mockResolvedValue({ currentUserId: "owner", connections, canManageConnections });
|
||||
flushSync(() => root.render(<QueryClientProvider client={client}>
|
||||
<AiConnectionField companyId="company" agentId="agent" agentName="Nova" adapterType="claude_local"
|
||||
preferAdvanced={preferAdvanced}
|
||||
value={{ provider: "anthropic", method: "subscription", mode: "responsible_user" }} onChange={onChange} {...props} />
|
||||
</QueryClientProvider>));
|
||||
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<HTMLElement>('[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<HTMLElement>('[role="combobox"][aria-label="Connection"]')!;
|
||||
flushSync(() => trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })));
|
||||
await settle();
|
||||
const option = [...document.querySelectorAll<HTMLElement>('[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(<QueryClientProvider client={client}>
|
||||
<AiConnectionField companyId="company" agentId="agent" agentName="Nova" adapterType="codex_local" legacy onChange={onChange} />
|
||||
</QueryClientProvider>));
|
||||
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<HTMLElement>('[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<void>(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<HTMLButtonElement>('[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<HTMLButtonElement>('[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(<QueryClientProvider client={client}>
|
||||
<AiConnectionField companyId="company" agentId="agent" agentName="Pi" adapterType="pi_local" model=""
|
||||
value={{ provider: "openrouter", method: "api_key", mode: "responsible_user" }} onChange={onChange} />
|
||||
</QueryClientProvider>));
|
||||
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(<QueryClientProvider client={client}>
|
||||
<AiConnectionField companyId="company" agentId="agent" agentName="Pi" adapterType="pi_local" model={`${provider}/provider-model`}
|
||||
value={{ provider, method: "api_key", mode: "delegated", connectionId: saved.id, grantId: saved.grantId }} onChange={onChange} />
|
||||
</QueryClientProvider>));
|
||||
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<HTMLElement>('[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(<QueryClientProvider client={client}>
|
||||
<AiConnectionField companyId="company" agentId="agent" agentName="Nova" adapterType="codex_local" legacy onChange={onChange} />
|
||||
</QueryClientProvider>));
|
||||
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<HTMLElement>('[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 });
|
||||
});
|
||||
@@ -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(<AiConnectionIdentity connection={{
|
||||
id: "connection", grantId: "grant", companyId: "company", provider: "anthropic", method: "subscription",
|
||||
name: "Zephyr Labs Claude", accountLabel: "quill.marten@example.test", ownership: "shared", status: "connected",
|
||||
}} />);
|
||||
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 });
|
||||
});
|
||||
@@ -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(<AiConnectionPicker
|
||||
adapterType="opencode_local" model="zai/glm-5" requirement={{ companyId: "company", provider: "openrouter" }}
|
||||
connections={[{ id: "router", grantId: "grant", companyId: "company", provider: "openrouter", method: "api_key",
|
||||
name: "Shared router", ownership: "shared", status: "connected" }]}
|
||||
currentUserId="user" agentId="agent" agentName="Nova" onChange={vi.fn()} onConnect={vi.fn()} />);
|
||||
expect(document.body.textContent).not.toContain("Shared router");
|
||||
expect(document.querySelector<HTMLButtonElement>('[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(<AiConnectionPicker
|
||||
requirement={{ companyId: "company", provider: "anthropic" }}
|
||||
connections={[{ id: "connection", grantId: "grant", companyId: "company", provider: "anthropic", method: "api_key",
|
||||
name: "Shared Claude key", accountLabel: "orla.brisk@example.test", ownership: "shared", status: "connected" }]}
|
||||
currentUserId="user" agentId="agent" agentName="Nova" onChange={vi.fn()} onConnect={vi.fn()} />);
|
||||
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(<AiConnectionPicker
|
||||
requirement={{ companyId: "company", provider: "anthropic" }}
|
||||
connections={[{ id: "mine", grantId: "grant", companyId: "company", provider: "anthropic", method: "subscription",
|
||||
name: "Orla's Claude Max", ownership: "personal", ownerUserId: "user", isDefault: true, status: "connected" }]}
|
||||
currentUserId="user" agentId="agent" agentName="Nova" onChange={vi.fn()} onConnect={vi.fn()} />);
|
||||
expect(replayLeaks("Orla's Claude Max")).toEqual({ rendered: true, recorded: false });
|
||||
});
|
||||
@@ -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(<AiConnectionPoolRunDetails context={{
|
||||
aiRouterSelection: { binding: { provider: "anthropic" }, runtimeConfig: { model: "claude-sonnet" }, notes: [] },
|
||||
aiConnection: { accountName: "Juniper Ops Pool Account", connectionId: "connection" },
|
||||
}} />);
|
||||
expect(replayLeaks("Juniper Ops Pool Account")).toEqual({ rendered: true, recorded: false });
|
||||
expect(replayLeaks("claude-sonnet")).toEqual({ rendered: true, recorded: true });
|
||||
});
|
||||
@@ -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<HTMLTextAreaElement>(null);
|
||||
useImperativeHandle(ref, () => ({ focus: () => input.current?.focus(), clear: () => onChange("") }));
|
||||
return <textarea ref={input} aria-label="Recovery draft" value={value} readOnly={readOnly}
|
||||
onChange={event => onChange(event.target.value)} />;
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
let client: QueryClient;
|
||||
beforeEach(() => {
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
client = new QueryClient({ defaultOptions: { queries: { enabled: false, retry: false } } });
|
||||
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
|
||||
});
|
||||
afterEach(async () => {
|
||||
await act(async () => root.unmount());
|
||||
container.remove();
|
||||
client.clear();
|
||||
});
|
||||
|
||||
describe.each(["task chat", "legacy thread"] as const)("%s composer recovery", surface => {
|
||||
it.each([false, true])("can send the retained draft after an already-reviewed unknown save (reload=%s)", async reload => {
|
||||
const key = "reviewed-unknown-save";
|
||||
const originalAttemptId = "9af8228f-0be7-45ae-a104-6fbe0af6f1d3";
|
||||
const attachmentId = "5e5f9946-c706-4785-8988-d4d6f0f499ab";
|
||||
const body = "I enabled the connection. Please try again.";
|
||||
const contentPath = `/api/attachments/${attachmentId}/content`;
|
||||
saveDraft(key, body);
|
||||
saveDraftAttachments(key, [{ attachmentId, name: "notes.txt", inline: false, contentPath }]);
|
||||
// This is the old persisted state shown after Review conversation. It has
|
||||
// no replayable request snapshot, so recovery must not blindly resend it.
|
||||
saveDraftSubmission(key, { attemptId: originalAttemptId, reviewed: true });
|
||||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||||
const composer: ReactElement = surface === "task chat"
|
||||
? <TaskChatComposer onAdd={onAdd} draftKey={key} workMode="standard" />
|
||||
: <MemoryRouter><IssueChatThread onAdd={onAdd} draftKey={key}
|
||||
comments={[]} linkedRuns={[]} timelineEvents={[]} liveRuns={[]}
|
||||
enableLiveTranscriptPolling={false} /></MemoryRouter>;
|
||||
const element = <QueryClientProvider client={client}>{composer}</QueryClientProvider>;
|
||||
await act(async () => root.render(element));
|
||||
if (reload) {
|
||||
await act(async () => root.unmount());
|
||||
root = createRoot(container);
|
||||
await act(async () => root.render(element));
|
||||
}
|
||||
const editor = () => container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Recovery draft"]')!;
|
||||
const send = () => container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-send"]')
|
||||
?? Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Send")!;
|
||||
expect(editor().value).toBe(body);
|
||||
expect(onAdd).not.toHaveBeenCalled();
|
||||
const recover = Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Cancel");
|
||||
expect(recover, "An unknown save must offer a non-destructive way back to the composer").toBeDefined();
|
||||
await act(async () => recover!.click());
|
||||
expect(editor().readOnly).toBe(false);
|
||||
expect(editor().value).toBe(body);
|
||||
expect(container.textContent).toContain("notes.txt");
|
||||
expect(loadDraftSubmission(key)).toBeNull();
|
||||
expect(send().disabled).toBe(false);
|
||||
await act(async () => send().click());
|
||||
expect(onAdd).toHaveBeenCalledExactlyOnceWith(`${body}\n\n[notes.txt](${contentPath})`,
|
||||
undefined, undefined, [attachmentId], expect.any(String));
|
||||
expect(onAdd.mock.calls[0]![4]).not.toBe(originalAttemptId);
|
||||
expect(editor().value).toBe("");
|
||||
expect(container.textContent).not.toContain("notes.txt");
|
||||
// Recovery must leave ordinary sending usable, including after a reload.
|
||||
await act(async () => {
|
||||
Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value")!.set!.call(editor(), "One more message");
|
||||
editor().dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
expect(send().disabled).toBe(false);
|
||||
await act(async () => send().click());
|
||||
expect(onAdd.mock.calls[1]![0]).toBe("One more message");
|
||||
expect(onAdd.mock.calls[1]![4]).not.toBe(onAdd.mock.calls[0]![4]);
|
||||
});
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { CopyField } from "./WebhookFields";
|
||||
import { isBlockedFromReplay } from "@/lib/analytics/replay-recording.test-utils";
|
||||
|
||||
afterEach(() => { document.body.innerHTML = ""; });
|
||||
|
||||
it("blocks the webhook URL and secret from session replay", () => {
|
||||
document.body.innerHTML = renderToStaticMarkup(<>
|
||||
<CopyField label="Webhook URL" value="https://paperclip.example.test/api/routine-triggers/hook_k4Zr9Qe1" />
|
||||
<CopyField label="Authentication key" value="whsec_Tq8vLm2Rz7Np" />
|
||||
</>);
|
||||
expect(isBlockedFromReplay("hook_k4Zr9Qe1", document.body)).toBe(true);
|
||||
expect(isBlockedFromReplay("whsec_Tq8vLm2Rz7Np", document.body)).toBe(true);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,514 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { flushSync } from "react-dom";
|
||||
import type { ComponentProps } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import type { WorkTimelineResult } from "@paperclipai/shared";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { WorkTimelineChart } from "./WorkTimelineChart";
|
||||
import { computeLayout } from "@/lib/timeline/layout";
|
||||
|
||||
vi.mock("@/lib/router", () => ({
|
||||
useLocation: () => ({ pathname: "/PAP/timeline" }),
|
||||
}));
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
flushSync(() => root.unmount());
|
||||
container.remove();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function renderChart(
|
||||
data: WorkTimelineResult,
|
||||
props: Partial<ComponentProps<typeof WorkTimelineChart>> = {},
|
||||
) {
|
||||
flushSync(() => {
|
||||
root.render(
|
||||
<WorkTimelineChart
|
||||
data={data}
|
||||
zoom="hour"
|
||||
nowMs={new Date("2026-07-02T12:00:00.000Z").getTime()}
|
||||
{...props}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async function flushTimelineEffects(count = 5) {
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
}
|
||||
|
||||
function timelineSample(): WorkTimelineResult {
|
||||
return {
|
||||
actors: [
|
||||
{ id: "agent:codex", type: "agent", name: "CodexCoder", avatar: "code" },
|
||||
{ id: "agent:qa", type: "agent", name: "QA", avatar: "shield" },
|
||||
],
|
||||
spans: [
|
||||
{
|
||||
actorId: "agent:codex",
|
||||
laneHint: null,
|
||||
runId: "run-1",
|
||||
issueId: "issue-1",
|
||||
issueIdentifier: "PAP-12443",
|
||||
issueTitle: "Work Timeline sticky gutter",
|
||||
start: "2026-07-02T09:00:00.000Z",
|
||||
end: "2026-07-02T10:00:00.000Z",
|
||||
status: "completed",
|
||||
retryOfRunId: null,
|
||||
},
|
||||
{
|
||||
actorId: "agent:qa",
|
||||
laneHint: null,
|
||||
runId: "run-2",
|
||||
issueId: "issue-2",
|
||||
issueIdentifier: "PAP-12426",
|
||||
issueTitle: "QA validation",
|
||||
start: "2026-07-02T11:00:00.000Z",
|
||||
end: "2026-07-02T11:30:00.000Z",
|
||||
status: "completed",
|
||||
retryOfRunId: null,
|
||||
},
|
||||
],
|
||||
events: [],
|
||||
edges: [],
|
||||
pagination: { limit: 200, offset: 0, totalIssues: 2, hasMore: false },
|
||||
window: {
|
||||
from: "2026-07-02T00:00:00.000Z",
|
||||
to: "2026-07-03T00:00:00.000Z",
|
||||
capped: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("WorkTimelineChart", () => {
|
||||
it("renders date-aware AM/PM labels on the header axis", () => {
|
||||
renderChart(timelineSample());
|
||||
|
||||
const timeAxis = container.querySelector<HTMLElement>("[data-testid='work-timeline-time-axis']");
|
||||
|
||||
expect(timeAxis?.textContent).toContain("Jul 2");
|
||||
expect(timeAxis?.textContent).toContain("AM");
|
||||
expect(timeAxis?.textContent).not.toContain("09:00");
|
||||
});
|
||||
|
||||
it("freezes the time axis over vertical scrolling while preserving horizontal alignment", async () => {
|
||||
renderChart(timelineSample());
|
||||
|
||||
const scroller = container.querySelector<HTMLElement>("[data-testid='work-timeline-scroll']")!;
|
||||
const timeAxis = container.querySelector<HTMLElement>("[data-testid='work-timeline-time-axis']")!;
|
||||
const axisSvg = timeAxis.querySelector<SVGSVGElement>("svg")!;
|
||||
|
||||
expect(timeAxis.getAttribute("class")).toContain("absolute");
|
||||
expect(timeAxis.getAttribute("class")).toContain("top-0");
|
||||
expect(timeAxis.style.height).toBe("32px");
|
||||
expect(axisSvg.style.transform).toBe("translateX(0px)");
|
||||
|
||||
flushSync(() => {
|
||||
Object.defineProperty(scroller, "scrollTop", { configurable: true, value: 400 });
|
||||
Object.defineProperty(scroller, "scrollLeft", { configurable: true, value: 240 });
|
||||
scroller.dispatchEvent(new Event("scroll", { bubbles: true }));
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
expect(timeAxis.textContent).toContain("Jul 2");
|
||||
expect(axisSvg.style.transform).toBe("translateX(-240px)");
|
||||
});
|
||||
|
||||
it("renders actor labels in a sticky gutter outside the horizontally scrolling SVG", () => {
|
||||
renderChart(timelineSample());
|
||||
|
||||
const scroller = container.querySelector<HTMLElement>("[data-testid='work-timeline-scroll']");
|
||||
const gutter = container.querySelector<SVGSVGElement>("[data-testid='work-timeline-actor-gutter']");
|
||||
const chartSvg = container.querySelector<SVGSVGElement>("svg.absolute");
|
||||
|
||||
expect(scroller).not.toBeNull();
|
||||
expect(gutter).not.toBeNull();
|
||||
expect(chartSvg).not.toBeNull();
|
||||
expect(gutter?.getAttribute("class")).toContain("sticky");
|
||||
expect(gutter?.getAttribute("class")).toContain("left-0");
|
||||
expect(gutter?.getAttribute("class")).not.toContain("top-0");
|
||||
expect(gutter?.getAttribute("width")).toBe("176");
|
||||
expect(chartSvg?.getAttribute("width")).not.toBe(gutter?.getAttribute("width"));
|
||||
expect(gutter?.textContent).toContain("CodexCoder");
|
||||
expect(gutter?.textContent).not.toContain("agent");
|
||||
expect(gutter?.textContent).not.toContain("×");
|
||||
|
||||
flushSync(() => {
|
||||
scroller!.scrollLeft = 10_000;
|
||||
scroller!.dispatchEvent(new Event("scroll", { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(container.querySelector("[data-testid='work-timeline-actor-gutter']")?.textContent).toContain("CodexCoder");
|
||||
});
|
||||
|
||||
it("reports the currently visible time window when the chart scrolls", async () => {
|
||||
vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockReturnValue(640);
|
||||
const onVisibleWindowChange = vi.fn();
|
||||
const data = timelineSample();
|
||||
renderChart(data, { onVisibleWindowChange });
|
||||
|
||||
await flushTimelineEffects();
|
||||
|
||||
const scroller = container.querySelector<HTMLElement>("[data-testid='work-timeline-scroll']")!;
|
||||
expect(onVisibleWindowChange).toHaveBeenCalled();
|
||||
|
||||
flushSync(() => {
|
||||
scroller.scrollLeft = 0;
|
||||
scroller.dispatchEvent(new Event("scroll", { bubbles: true }));
|
||||
});
|
||||
await flushTimelineEffects();
|
||||
|
||||
const lastCall = onVisibleWindowChange.mock.calls.at(-1)?.[0];
|
||||
expect(lastCall?.fromMs).toBe(new Date(data.window.from).getTime());
|
||||
expect(lastCall?.toMs).toBeCloseTo(new Date("2026-07-02T01:00:00.000Z").getTime(), -3);
|
||||
});
|
||||
|
||||
it("renders cached persona images in the actor gutter", () => {
|
||||
renderChart(timelineSample());
|
||||
|
||||
const gutter = container.querySelector<SVGSVGElement>("[data-testid='work-timeline-actor-gutter']");
|
||||
|
||||
const portraits = gutter?.querySelectorAll('image[data-testid="timeline-agent-icon"]');
|
||||
expect(portraits?.length).toBe(2);
|
||||
expect(portraits?.[0].getAttribute("href")).toContain("/api/agent-avatars/cap-v1/");
|
||||
expect(portraits?.[1].getAttribute("href")).toContain("/api/agent-avatars/cap-v1/");
|
||||
expect(gutter?.textContent).not.toContain("CC");
|
||||
});
|
||||
|
||||
it("does not render created diamonds or comment bubbles from instant events", () => {
|
||||
const data = timelineSample();
|
||||
data.actors.push({ id: "user:dotta", type: "user", name: "Dotta" });
|
||||
data.events = [
|
||||
{ actorId: "user:dotta", kind: "created", issueId: "issue-1", at: "2026-07-02T08:30:00.000Z" },
|
||||
{ actorId: "user:dotta", kind: "commented", issueId: "issue-2", at: "2026-07-02T09:15:00.000Z" },
|
||||
{ actorId: "user:dotta", kind: "approved", issueId: "issue-1", at: "2026-07-02T10:05:00.000Z" },
|
||||
];
|
||||
renderChart(data);
|
||||
|
||||
const gutter = container.querySelector<SVGSVGElement>("[data-testid='work-timeline-actor-gutter']");
|
||||
expect(gutter?.textContent).not.toContain("Dotta");
|
||||
expect(container.querySelectorAll("[data-testid='timeline-event-marker']")).toHaveLength(0);
|
||||
expect(container.querySelectorAll("[data-testid='timeline-comment-marker']")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("keeps connectors hidden until hover, renders them orthogonally, and highlights the connected graph", async () => {
|
||||
const data = timelineSample();
|
||||
data.actors.push({ id: "agent:cto", type: "agent", name: "CTO" });
|
||||
data.spans.push(
|
||||
{
|
||||
actorId: "agent:cto",
|
||||
laneHint: null,
|
||||
runId: "run-3",
|
||||
issueId: "issue-3",
|
||||
issueIdentifier: "PAP-12427",
|
||||
issueTitle: "Follow-up validation",
|
||||
start: "2026-07-02T11:45:00.000Z",
|
||||
end: "2026-07-02T12:00:00.000Z",
|
||||
status: "completed",
|
||||
retryOfRunId: null,
|
||||
},
|
||||
{
|
||||
actorId: "agent:codex",
|
||||
laneHint: null,
|
||||
runId: "run-4",
|
||||
issueId: "issue-4",
|
||||
issueIdentifier: "PAP-12428",
|
||||
issueTitle: "Unrelated work",
|
||||
start: "2026-07-02T13:00:00.000Z",
|
||||
end: "2026-07-02T14:00:00.000Z",
|
||||
status: "completed",
|
||||
retryOfRunId: null,
|
||||
},
|
||||
);
|
||||
data.edges = [
|
||||
{
|
||||
fromActorId: "agent:codex",
|
||||
toActorId: "agent:qa",
|
||||
issueId: "issue-2",
|
||||
at: "2026-07-02T10:45:00.000Z",
|
||||
kind: "delegation",
|
||||
},
|
||||
{
|
||||
fromActorId: "agent:qa",
|
||||
toActorId: "agent:cto",
|
||||
issueId: "issue-3",
|
||||
at: "2026-07-02T11:35:00.000Z",
|
||||
kind: "delegation",
|
||||
},
|
||||
];
|
||||
renderChart(data);
|
||||
|
||||
expect(container.querySelectorAll("[data-testid='timeline-connector']")).toHaveLength(0);
|
||||
|
||||
const hovered = container.querySelector<SVGGElement>("[data-run-id='run-2']")!;
|
||||
flushSync(() => {
|
||||
hovered.dispatchEvent(new MouseEvent("mouseover", { bubbles: true, clientX: 100, clientY: 100 }));
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
expect(container.querySelectorAll("[data-testid='timeline-connector']")).toHaveLength(2);
|
||||
const connectorStrokePaths = Array.from(
|
||||
container.querySelectorAll<SVGPathElement>("[data-testid='timeline-connector'] path[fill='none']"),
|
||||
);
|
||||
expect(connectorStrokePaths.map((path) => path.getAttribute("d"))).toEqual(
|
||||
expect.arrayContaining([expect.stringMatching(/ V.+ H/)]),
|
||||
);
|
||||
expect(container.querySelector("[data-run-id='run-1']")?.getAttribute("data-connected-state")).toBe("connected");
|
||||
expect(container.querySelector("[data-run-id='run-2']")?.getAttribute("data-connected-state")).toBe("connected");
|
||||
expect(container.querySelector("[data-run-id='run-3']")?.getAttribute("data-connected-state")).toBe("connected");
|
||||
expect(container.querySelector("[data-run-id='run-4']")?.getAttribute("data-connected-state")).toBe("faded");
|
||||
|
||||
const layout = computeLayout(data, {
|
||||
gutter: 176,
|
||||
rowH: 34,
|
||||
barH: 15,
|
||||
laneGap: 4,
|
||||
pxPerMinute: 8,
|
||||
nowMs: new Date("2026-07-02T12:00:00.000Z").getTime(),
|
||||
});
|
||||
expect(layout.connectors).toMatchObject([
|
||||
{ sourceRunId: "run-1", targetRunId: "run-2", dashed: false },
|
||||
{ sourceRunId: "run-2", targetRunId: "run-3", dashed: false },
|
||||
]);
|
||||
const bars = new Map(layout.rows.flatMap((row) => row.bars.map((bar) => [bar.span.runId, bar])));
|
||||
expect(layout.connectors[0].x1).toBe(bars.get("run-1")?.x2);
|
||||
expect(layout.connectors[0].x2).toBe(bars.get("run-2")?.x1);
|
||||
});
|
||||
|
||||
it("renders kickoff chips with human avatar images but not delegating agents", () => {
|
||||
const data = timelineSample();
|
||||
data.actors.push({
|
||||
id: "user:dotta",
|
||||
type: "user",
|
||||
name: "Dotta",
|
||||
avatar: "/api/assets/dotta-avatar/content",
|
||||
});
|
||||
data.edges = [
|
||||
{
|
||||
fromActorId: "user:dotta",
|
||||
toActorId: "agent:codex",
|
||||
issueId: "issue-1",
|
||||
at: "2026-07-02T08:45:00.000Z",
|
||||
kind: "delegation",
|
||||
},
|
||||
{
|
||||
fromActorId: "agent:codex",
|
||||
toActorId: "agent:qa",
|
||||
issueId: "issue-2",
|
||||
at: "2026-07-02T10:45:00.000Z",
|
||||
kind: "delegation",
|
||||
},
|
||||
];
|
||||
|
||||
renderChart(data);
|
||||
|
||||
const kickoffChips = container.querySelectorAll("[data-testid='timeline-kickoff-chip']");
|
||||
expect(kickoffChips).toHaveLength(1);
|
||||
expect(kickoffChips[0].querySelector("image")?.getAttribute("href")).toBe("/api/assets/dotta-avatar/content");
|
||||
expect(kickoffChips[0].textContent).not.toContain("DO");
|
||||
});
|
||||
|
||||
it("reserves normal wheel input for panning and uses modifier-wheel for continuous zoom", () => {
|
||||
const onZoomScaleChange = vi.fn();
|
||||
renderChart(timelineSample(), { onZoomScaleChange });
|
||||
|
||||
const scroller = container.querySelector<HTMLElement>("[data-testid='work-timeline-scroll']")!;
|
||||
flushSync(() => {
|
||||
scroller.dispatchEvent(new WheelEvent("wheel", { deltaY: 80, bubbles: true, cancelable: true }));
|
||||
});
|
||||
expect(onZoomScaleChange).not.toHaveBeenCalled();
|
||||
|
||||
flushSync(() => {
|
||||
scroller.dispatchEvent(new WheelEvent("wheel", { deltaY: 80, ctrlKey: true, bubbles: true, cancelable: true }));
|
||||
});
|
||||
expect(onZoomScaleChange).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("opens task bars in a new company-prefixed window", () => {
|
||||
const open = vi.spyOn(window, "open").mockImplementation(() => null);
|
||||
renderChart(timelineSample());
|
||||
|
||||
const bar = container.querySelector<SVGGElement>("[data-run-id='run-1']")!;
|
||||
flushSync(() => {
|
||||
bar.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(open).toHaveBeenCalledWith("/PAP/issues/issue-1", "_blank", "noopener,noreferrer");
|
||||
});
|
||||
|
||||
it("lets minimap edge handles resize the visible range and update zoom", () => {
|
||||
const onZoomScaleChange = vi.fn();
|
||||
renderChart(timelineSample(), { onZoomScaleChange });
|
||||
|
||||
const rightHandle = container.querySelector<SVGGElement>("[data-testid='timeline-minimap-right-handle']")!;
|
||||
const minimap = rightHandle.ownerSVGElement!;
|
||||
vi.spyOn(minimap, "getBoundingClientRect").mockReturnValue({
|
||||
x: 0,
|
||||
y: 0,
|
||||
left: 0,
|
||||
top: 0,
|
||||
right: 900,
|
||||
bottom: 54,
|
||||
width: 900,
|
||||
height: 54,
|
||||
toJSON: () => ({}),
|
||||
});
|
||||
|
||||
flushSync(() => {
|
||||
rightHandle.dispatchEvent(new MouseEvent("mousedown", { clientX: 300, bubbles: true, cancelable: true }));
|
||||
document.dispatchEvent(new MouseEvent("mousemove", { clientX: 520, bubbles: true, cancelable: true }));
|
||||
document.dispatchEvent(new MouseEvent("mouseup", { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(onZoomScaleChange).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows grab-handle affordances on minimap selection edges", () => {
|
||||
renderChart(timelineSample(), { onZoomScaleChange: vi.fn() });
|
||||
|
||||
const leftHandle = container.querySelector<SVGGElement>("[data-testid='timeline-minimap-left-handle']")!;
|
||||
const rightHandle = container.querySelector<SVGGElement>("[data-testid='timeline-minimap-right-handle']")!;
|
||||
|
||||
expect(leftHandle.getAttribute("class")).toContain("cursor-grab");
|
||||
expect(rightHandle.getAttribute("class")).toContain("cursor-grab");
|
||||
expect(leftHandle.querySelectorAll("line")).toHaveLength(3);
|
||||
expect(leftHandle.textContent).toContain("Drag left edge");
|
||||
});
|
||||
|
||||
it("cleans up chart drag listeners when unmounted mid-drag", () => {
|
||||
const add = vi.spyOn(document, "addEventListener");
|
||||
const remove = vi.spyOn(document, "removeEventListener");
|
||||
renderChart(timelineSample(), { onZoomScaleChange: vi.fn() });
|
||||
|
||||
const chartSvg = container.querySelector<SVGSVGElement>("svg.absolute")!;
|
||||
vi.spyOn(chartSvg, "getBoundingClientRect").mockReturnValue({
|
||||
x: 0,
|
||||
y: 0,
|
||||
left: 0,
|
||||
top: 0,
|
||||
right: 1000,
|
||||
bottom: 400,
|
||||
width: 1000,
|
||||
height: 400,
|
||||
toJSON: () => ({}),
|
||||
});
|
||||
|
||||
flushSync(() => {
|
||||
chartSvg.dispatchEvent(new MouseEvent("mousedown", { clientX: 260, bubbles: true, cancelable: true }));
|
||||
});
|
||||
|
||||
expect(add).toHaveBeenCalledWith("mousemove", expect.any(Function));
|
||||
expect(add).toHaveBeenCalledWith("mouseup", expect.any(Function));
|
||||
|
||||
flushSync(() => root.unmount());
|
||||
root = createRoot(container);
|
||||
|
||||
expect(remove).toHaveBeenCalledWith("mousemove", expect.any(Function));
|
||||
expect(remove).toHaveBeenCalledWith("mouseup", expect.any(Function));
|
||||
});
|
||||
|
||||
it("cleans up minimap drag listeners when unmounted mid-drag", () => {
|
||||
const add = vi.spyOn(document, "addEventListener");
|
||||
const remove = vi.spyOn(document, "removeEventListener");
|
||||
renderChart(timelineSample(), { onZoomScaleChange: vi.fn() });
|
||||
|
||||
const rightHandle = container.querySelector<SVGGElement>("[data-testid='timeline-minimap-right-handle']")!;
|
||||
const minimap = rightHandle.ownerSVGElement!;
|
||||
vi.spyOn(minimap, "getBoundingClientRect").mockReturnValue({
|
||||
x: 0,
|
||||
y: 0,
|
||||
left: 0,
|
||||
top: 0,
|
||||
right: 900,
|
||||
bottom: 54,
|
||||
width: 900,
|
||||
height: 54,
|
||||
toJSON: () => ({}),
|
||||
});
|
||||
|
||||
flushSync(() => {
|
||||
rightHandle.dispatchEvent(new MouseEvent("mousedown", { clientX: 300, bubbles: true, cancelable: true }));
|
||||
});
|
||||
|
||||
expect(add).toHaveBeenCalledWith("mousemove", expect.any(Function));
|
||||
expect(add).toHaveBeenCalledWith("mouseup", expect.any(Function));
|
||||
|
||||
flushSync(() => root.unmount());
|
||||
root = createRoot(container);
|
||||
|
||||
expect(remove).toHaveBeenCalledWith("mousemove", expect.any(Function));
|
||||
expect(remove).toHaveBeenCalledWith("mouseup", expect.any(Function));
|
||||
});
|
||||
|
||||
it("keeps the default now timestamp stable across rerenders", () => {
|
||||
const now = new Date("2026-07-02T12:00:00.000Z").getTime();
|
||||
const later = new Date("2026-07-02T13:00:00.000Z").getTime();
|
||||
let currentNow = now;
|
||||
vi.spyOn(Date, "now").mockImplementation(() => currentNow);
|
||||
const data = timelineSample();
|
||||
data.spans[0] = {
|
||||
...data.spans[0],
|
||||
end: null,
|
||||
status: "running",
|
||||
};
|
||||
|
||||
renderChart(data, { nowMs: undefined });
|
||||
const initialWidth = container
|
||||
.querySelector<SVGRectElement>("[data-run-id='run-1'] rect")
|
||||
?.getAttribute("width");
|
||||
|
||||
currentNow = later;
|
||||
renderChart(data, { nowMs: undefined });
|
||||
|
||||
expect(container.querySelector<SVGRectElement>("[data-run-id='run-1'] rect")?.getAttribute("width")).toBe(initialWidth);
|
||||
});
|
||||
|
||||
it("lets dragging the chart grid select a time range to zoom into", () => {
|
||||
const onZoomScaleChange = vi.fn();
|
||||
renderChart(timelineSample(), { onZoomScaleChange });
|
||||
|
||||
const chartSvg = container.querySelector<SVGSVGElement>("svg.absolute")!;
|
||||
const width = Number(chartSvg.getAttribute("width") ?? "1000");
|
||||
const height = Number(chartSvg.getAttribute("height") ?? "400");
|
||||
vi.spyOn(chartSvg, "getBoundingClientRect").mockReturnValue({
|
||||
x: 0,
|
||||
y: 0,
|
||||
left: 0,
|
||||
top: 0,
|
||||
right: width,
|
||||
bottom: height,
|
||||
width,
|
||||
height,
|
||||
toJSON: () => ({}),
|
||||
});
|
||||
|
||||
flushSync(() => {
|
||||
chartSvg.dispatchEvent(new MouseEvent("mousedown", { clientX: 260, bubbles: true, cancelable: true }));
|
||||
document.dispatchEvent(new MouseEvent("mousemove", { clientX: 520, bubbles: true, cancelable: true }));
|
||||
});
|
||||
|
||||
expect(container.querySelector("[data-testid='timeline-drag-selection']")).not.toBeNull();
|
||||
|
||||
flushSync(() => {
|
||||
document.dispatchEvent(new MouseEvent("mouseup", { clientX: 520, bubbles: true, cancelable: true }));
|
||||
});
|
||||
|
||||
expect(onZoomScaleChange).toHaveBeenCalled();
|
||||
expect(container.querySelector("[data-testid='timeline-drag-selection']")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,29 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { GUIDANCE_COMPANY, GUIDANCE_CONNECTION, installConnectionGuidanceFixtures } from "../../../storybook/fixtures/connectionInstructions";
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
it("keeps the directory and unimplemented connector requests inside the preview", async () => {
|
||||
const fallback = vi.fn().mockRejectedValue(new Error("Unexpected network request"));
|
||||
vi.stubGlobal("fetch", fallback);
|
||||
const client = new QueryClient();
|
||||
const cleanup = installConnectionGuidanceFixtures(client, "Honcho", { setup: false, askFirst: false });
|
||||
try {
|
||||
const directory = await window.fetch(`/api/companies/${GUIDANCE_COMPANY}/user-directory`);
|
||||
expect((await directory.json()).users[0].user.name).toBe("Riley Board");
|
||||
const unknownOperation = await window.fetch(`/api/companies/${GUIDANCE_COMPANY}/tools/unsupported-operation`, { method: "POST" });
|
||||
expect(unknownOperation.status).toBe(422);
|
||||
const providerTest = await window.fetch(`/api/tool-connections/${GUIDANCE_CONNECTION}/test-action`, { method: "POST" });
|
||||
expect(providerTest.status).toBe(422);
|
||||
const oauth = await window.fetch("/api/tools/oauth/start", { method: "POST" });
|
||||
expect(oauth.status).toBe(422);
|
||||
expect(fallback).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
cleanup();
|
||||
client.clear();
|
||||
}
|
||||
expect(window.fetch).toBe(fallback);
|
||||
});
|
||||
@@ -1,81 +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 type { GoogleWorkspaceServiceSelection } from "@paperclipai/shared";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { GoogleWorkspaceServicesDialog } from "./GoogleWorkspaceServices";
|
||||
|
||||
vi.mock("@/api/tools", () => ({ toolsApi: { listConnectionGrants: vi.fn() } }));
|
||||
vi.mock("@/pages/apps/AppLogo", () => ({ AppLogo: () => null }));
|
||||
|
||||
const removedText = [
|
||||
"What agents can do",
|
||||
"How your data is used",
|
||||
"agents can read and search your email",
|
||||
"agents can read and search your files",
|
||||
"agents can see your calendars",
|
||||
"Paperclip does not send email",
|
||||
"Agents read this content only to do the tasks you give them.",
|
||||
"sent to the AI model provider configured for your workspace",
|
||||
"It is not used to train general AI models.",
|
||||
"Results are saved in the task and its run history",
|
||||
];
|
||||
|
||||
describe("Google Workspace service picker", () => {
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
let client: QueryClient;
|
||||
const onContinue = vi.fn();
|
||||
|
||||
async function render(initial?: GoogleWorkspaceServiceSelection) {
|
||||
await act(async () => { root.render(<QueryClientProvider client={client}>
|
||||
<GoogleWorkspaceServicesDialog initial={initial} onContinue={onContinue} onCancel={vi.fn()} />
|
||||
</QueryClientProvider>); });
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
client = new QueryClient();
|
||||
});
|
||||
afterEach(async () => {
|
||||
await act(async () => { root.unmount(); });
|
||||
client.clear();
|
||||
container.remove();
|
||||
});
|
||||
|
||||
it.each<[string, GoogleWorkspaceServiceSelection | undefined]>([
|
||||
["all services with read & write", undefined],
|
||||
["all services read only", { gmail: "read", drive: "read", calendar: "read" }],
|
||||
["a single service", { calendar: "write" }],
|
||||
["no services", {}],
|
||||
])("shows only the service rows and the privacy policy link for %s", async (_label, initial) => {
|
||||
await render(initial);
|
||||
const dialog = document.querySelector('[role="dialog"]')!;
|
||||
for (const text of removedText) expect(dialog.textContent).not.toContain(text);
|
||||
expect(dialog.querySelector("h3")).toBeNull();
|
||||
expect(dialog.querySelector("ul")).toBeNull();
|
||||
expect(document.querySelectorAll('[role="switch"]')).toHaveLength(3);
|
||||
const link = [...dialog.querySelectorAll("a")].find(item => item.textContent?.includes("Limited Use"))!;
|
||||
expect(link.textContent).toBe("Read our privacy policy, including how we meet Google's Limited Use requirements (opens in a new tab)");
|
||||
expect(link.getAttribute("href")).toBe("https://paperclip.ing/privacy");
|
||||
expect(link.getAttribute("target")).toBe("_blank");
|
||||
const description = document.getElementById(dialog.getAttribute("aria-describedby") ?? "");
|
||||
expect(description?.textContent).toBe("Choose the Google services to connect.");
|
||||
});
|
||||
|
||||
it("keeps Continue disabled with no services and submits the chosen services", async () => {
|
||||
await render({});
|
||||
const disabled = [...document.querySelectorAll("button")].find(item => item.textContent === "Continue")!;
|
||||
expect(disabled.disabled).toBe(true);
|
||||
expect(document.querySelector('[role="status"]')?.textContent).toBe("Select at least one service to continue.");
|
||||
await act(async () => { root.unmount(); });
|
||||
root = createRoot(container);
|
||||
await render({ gmail: "read" });
|
||||
await act(async () => { [...document.querySelectorAll("button")].find(item => item.textContent === "Continue")!.click(); });
|
||||
expect(onContinue).toHaveBeenCalledWith({ gmail: "read" });
|
||||
});
|
||||
});
|
||||
@@ -1,68 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { getConnectableAppDefinition } from "@paperclipai/shared";
|
||||
import { OAuthConnectStateScreen, type OAuthConnectPhase } from "./ConnectionSetupFlow";
|
||||
|
||||
vi.mock("@/api/tools", () => ({ toolsApi: {} }));
|
||||
vi.mock("@/pages/apps/AppLogo", () => ({ AppLogo: () => null }));
|
||||
|
||||
describe("Google Workspace sign-in state screen", () => {
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
afterEach(() => {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
});
|
||||
|
||||
async function render(phase: OAuthConnectPhase, error?: string) {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<OAuthConnectStateScreen
|
||||
entry={getConnectableAppDefinition("google-workspace")}
|
||||
phase={phase}
|
||||
error={error}
|
||||
onRetry={() => undefined}
|
||||
onBack={() => undefined}
|
||||
onCancel={() => undefined}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const links = () => [...container.querySelectorAll("a")].map((link) => link.getAttribute("href") ?? "");
|
||||
|
||||
it.each<[string, OAuthConnectPhase, string | undefined]>([
|
||||
["opening the sign-in", "redirecting", undefined],
|
||||
["preparing the sign-in", "starting", undefined],
|
||||
["failing to open the sign-in window", "error", "Paperclip couldn’t open the sign-in window."],
|
||||
])("shows no MCP wording or MCP guide link while %s", async (_label, phase, error) => {
|
||||
await render(phase, error);
|
||||
expect(container.textContent).toContain("Connect Google Workspace");
|
||||
expect(container.textContent).toContain("Secure sign-in");
|
||||
expect(container.textContent).not.toMatch(/\bMCP\b/);
|
||||
expect(links().some((href) => href.includes("configure-mcp-servers"))).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps the MCP label for a server the user pasted", async () => {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<OAuthConnectStateScreen
|
||||
identity={{ name: "Example", unverifiedHost: "mcp.example.com" }}
|
||||
phase="redirecting"
|
||||
onRetry={() => undefined}
|
||||
onBack={() => undefined}
|
||||
onCancel={() => undefined}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
expect(container.textContent).toContain("Secure MCP sign-in");
|
||||
});
|
||||
});
|
||||
@@ -1,37 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildAgentOnboardingPrompt } from "./agent-onboarding-prompt";
|
||||
|
||||
describe("buildAgentOnboardingPrompt", () => {
|
||||
it("includes Hermes Gateway setup guidance for external agents", () => {
|
||||
const prompt = buildAgentOnboardingPrompt({
|
||||
onboardingTextUrl: "http://localhost:3100/api/invites/token-123/onboarding.txt",
|
||||
connectionCandidates: ["http://192.168.1.10:3100"],
|
||||
});
|
||||
|
||||
expect(prompt).toContain('adapterType: "hermes_gateway"');
|
||||
expect(prompt).toContain("API_SERVER_ENABLED=true");
|
||||
expect(prompt).toContain("API_SERVER_KEY");
|
||||
expect(prompt).toContain("exact same value as `API_SERVER_KEY`");
|
||||
expect(prompt).toContain("not the Paperclip API key");
|
||||
expect(prompt).toContain("hermes gateway run --replace --accept-hooks");
|
||||
expect(prompt).toContain("default Hermes API server port is `8642`");
|
||||
expect(prompt).toContain("agentDefaultsPayload.apiBaseUrl");
|
||||
expect(prompt).toContain("agentDefaultsPayload.paperclipApiUrl");
|
||||
expect(prompt).toContain("http://127.0.0.1:8642");
|
||||
expect(prompt).toContain("http://127.0.0.1:9119");
|
||||
expect(prompt).toContain("http://127.0.0.1:9119/chat");
|
||||
expect(prompt).toContain("Paperclip maps it to `/api`");
|
||||
expect(prompt).toContain("`/chat` and the dashboard root are browser UI routes");
|
||||
expect(prompt).toContain("`/api/v1/runs`");
|
||||
expect(prompt).toContain("http://<private-ip>:8642");
|
||||
expect(prompt).toContain("http://<tailnet-host>:8642");
|
||||
expect(prompt).toContain("http://host.docker.internal:8642");
|
||||
expect(prompt).toContain("https://hermes-gateway.example");
|
||||
expect(prompt).toContain("`hermes_local` runs Hermes on the Paperclip host");
|
||||
expect(prompt).toContain("Hermes-originated Paperclip API calls");
|
||||
expect(prompt).toContain("Do not rotate or invent a Paperclip key manually");
|
||||
expect(prompt).toContain("parsed `token` field from the raw HTTP JSON response");
|
||||
expect(prompt).toContain("A token value containing literal `...` or `[redacted]`");
|
||||
expect(prompt).toContain("never persist a displayed preview that contains `...`");
|
||||
});
|
||||
});
|
||||
@@ -6,9 +6,16 @@ import { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import type { DocumentRevision } from "@paperclipai/shared";
|
||||
import type { ConnectionGrant, DocumentRevision } from "@paperclipai/shared";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { AccountQuotaPanels } from "@/components/AccountQuotaPanels";
|
||||
import { AgentSetupPrompt } from "@/components/AgentSetupPrompt";
|
||||
import { AiConnectionAccountControls } from "@/components/ai-connections/AiConnectionAccountControls";
|
||||
import { AiConnectionIdentity } from "@/components/ai-connections/AiConnectionIdentity";
|
||||
import { AiConnectionPicker } from "@/components/ai-connections/AiConnectionPicker";
|
||||
import { AiConnectionPoolRunDetails } from "@/components/ai-connections/AiConnectionPoolRunDetails";
|
||||
import { DocumentDiffModal } from "@/components/DocumentDiffModal";
|
||||
import { CopyField } from "@/components/routine-triggers/WebhookFields";
|
||||
import { RunInvocationCard } from "@/components/run-log/RunDetails";
|
||||
import { ChatConversationList } from "@/pages/apps/chat/ChatConversationList";
|
||||
import { VoiceTranscript } from "@/components/voice/VoiceTranscript";
|
||||
@@ -386,6 +393,104 @@ describe("session replay text masking", () => {
|
||||
expect(tag).toMatch(/ANALYTICS_MASK_CLASS|ANALYTICS_NO_CAPTURE_CLASS/);
|
||||
});
|
||||
|
||||
it("masks the subscription account label in AccountQuotaPanels", () => {
|
||||
document.body.innerHTML = renderToStaticMarkup(<AccountQuotaPanels accounts={[{
|
||||
provider: "anthropic", accountKey: "key", accountLabel: "fenwick.oriel@example.test", ok: true,
|
||||
windows: [{ label: "Weekly limit", usedPercent: 40, valueLabel: null, resetsAt: null, detail: null }],
|
||||
}]} />);
|
||||
expect(replayLeaks("fenwick.oriel@example.test")).toEqual({ rendered: true, recorded: false });
|
||||
expect(replayLeaks("Weekly limit")).toEqual({ rendered: true, recorded: true });
|
||||
});
|
||||
|
||||
it("blocks the webhook URL and secret in WebhookFields CopyField", () => {
|
||||
document.body.innerHTML = renderToStaticMarkup(<>
|
||||
<CopyField label="Webhook URL" value="https://paperclip.example.test/api/routine-triggers/hook_k4Zr9Qe1" />
|
||||
<CopyField label="Authentication key" value="whsec_Tq8vLm2Rz7Np" />
|
||||
</>);
|
||||
expect(isBlockedFromReplay("hook_k4Zr9Qe1", document.body)).toBe(true);
|
||||
expect(isBlockedFromReplay("whsec_Tq8vLm2Rz7Np", document.body)).toBe(true);
|
||||
});
|
||||
|
||||
it("filters incompatible OpenRouter models and masks account labels in AiConnectionPicker", () => {
|
||||
document.body.innerHTML = renderToStaticMarkup(<AiConnectionPicker
|
||||
adapterType="opencode_local" model="zai/glm-5" requirement={{ companyId: "company", provider: "openrouter" }}
|
||||
connections={[{ id: "router", grantId: "grant", companyId: "company", provider: "openrouter", method: "api_key",
|
||||
name: "Shared router", ownership: "shared", status: "connected" }]}
|
||||
currentUserId="user" agentId="agent" agentName="Nova" onChange={vi.fn()} onConnect={vi.fn()} />);
|
||||
expect(document.body.textContent).not.toContain("Shared router");
|
||||
expect(document.querySelector<HTMLButtonElement>('[aria-label="Responsible user’s connection"]')!.disabled).toBe(true);
|
||||
expect(document.body.textContent).toContain("Incompatible with this harness and model");
|
||||
|
||||
document.body.innerHTML = renderToStaticMarkup(<AiConnectionPicker
|
||||
requirement={{ companyId: "company", provider: "anthropic" }}
|
||||
connections={[{ id: "connection", grantId: "grant", companyId: "company", provider: "anthropic", method: "api_key",
|
||||
name: "Shared Claude key", accountLabel: "orla.brisk@example.test", ownership: "shared", status: "connected" }]}
|
||||
currentUserId="user" agentId="agent" agentName="Nova" onChange={vi.fn()} onConnect={vi.fn()} />);
|
||||
expect(replayLeaks("orla.brisk@example.test")).toEqual({ rendered: true, recorded: false });
|
||||
|
||||
document.body.innerHTML = renderToStaticMarkup(<AiConnectionPicker
|
||||
requirement={{ companyId: "company", provider: "anthropic" }}
|
||||
connections={[{ id: "mine", grantId: "grant", companyId: "company", provider: "anthropic", method: "subscription",
|
||||
name: "Orla's Claude Max", ownership: "personal", ownerUserId: "user", isDefault: true, status: "connected" }]}
|
||||
currentUserId="user" agentId="agent" agentName="Nova" onChange={vi.fn()} onConnect={vi.fn()} />);
|
||||
expect(replayLeaks("Orla's Claude Max")).toEqual({ rendered: true, recorded: false });
|
||||
});
|
||||
|
||||
it("masks account labels in AiConnectionAccountControls, AiConnectionIdentity, and AiConnectionPoolRunDetails", () => {
|
||||
document.body.innerHTML = renderToStaticMarkup(<AiConnectionAccountControls
|
||||
account={{ id: "connection", grantId: "grant", companyId: "company", provider: "openai", method: "subscription",
|
||||
name: "Team ChatGPT", accountLabel: "tamsin.vale@example.test", ownership: "shared", status: "connected" }}
|
||||
grant={{ id: "grant", capabilities: { canRevoke: true, canEditAudience: false } } as ConnectionGrant}
|
||||
currentUserId="user" onMakeDefault={vi.fn()} onReconnect={vi.fn()} onRevoke={vi.fn()} />);
|
||||
expect(replayLeaks("tamsin.vale@example.test")).toEqual({ rendered: true, recorded: false });
|
||||
expect(replayLeaks("Reconnect")).toEqual({ rendered: true, recorded: true });
|
||||
|
||||
document.body.innerHTML = renderToStaticMarkup(<AiConnectionIdentity connection={{
|
||||
id: "connection", grantId: "grant", companyId: "company", provider: "anthropic", method: "subscription",
|
||||
name: "Zephyr Labs Claude", accountLabel: "quill.marten@example.test", ownership: "shared", status: "connected",
|
||||
}} />);
|
||||
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 });
|
||||
|
||||
document.body.innerHTML = renderToStaticMarkup(<AiConnectionPoolRunDetails context={{
|
||||
aiRouterSelection: { binding: { provider: "anthropic" }, runtimeConfig: { model: "claude-sonnet" }, notes: [] },
|
||||
aiConnection: { accountName: "Juniper Ops Pool Account", connectionId: "connection" },
|
||||
}} />);
|
||||
expect(replayLeaks("Juniper Ops Pool Account")).toEqual({ rendered: true, recorded: false });
|
||||
expect(replayLeaks("claude-sonnet")).toEqual({ rendered: true, recorded: true });
|
||||
});
|
||||
|
||||
it("blocks the setup prompt preview carrying pairing tokens in AgentSetupPrompt", async () => {
|
||||
const prevMatchMedia = window.matchMedia;
|
||||
window.matchMedia = ((query: string) => ({
|
||||
matches: query.includes("reduce"),
|
||||
media: query,
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
addListener: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
onchange: null,
|
||||
dispatchEvent: vi.fn(),
|
||||
})) as unknown as typeof window.matchMedia;
|
||||
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText: vi.fn(async () => {}) } });
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const root = createRoot(host);
|
||||
try {
|
||||
const prompt = "Run: paperclipai pair --token pcp_pair_8f3kQz2LmWv";
|
||||
await act(async () => root.render(<AgentSetupPrompt prompt={prompt} />));
|
||||
await act(async () => host.querySelector<HTMLButtonElement>("button")!.click());
|
||||
expect(document.querySelector("pre[aria-label='Setup prompt']")).not.toBeNull();
|
||||
expect(isBlockedFromReplay("pcp_pair_8f3kQz2LmWv", document.body)).toBe(true);
|
||||
} finally {
|
||||
await act(async () => root.unmount());
|
||||
host.remove();
|
||||
window.matchMedia = prevMatchMedia;
|
||||
Reflect.deleteProperty(navigator, "clipboard");
|
||||
}
|
||||
});
|
||||
|
||||
it("never lets autocapture record element text or attribute values", () => {
|
||||
expect(options.mask_all_text).toBe(true);
|
||||
expect(options.mask_all_element_attributes).toBe(true);
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildGrokAccessPrompt, buildGrokRoutinePrompt } from "./grok-bot-setup-prompt";
|
||||
describe("Grok Bot onboarding instructions", () => {
|
||||
it("keeps pairing and routine credentials out of chat instructions", () => {
|
||||
const access = buildGrokAccessPrompt("https://paperclip.example/mcp/runner", "Night Shift");
|
||||
expect(access).toContain("paperclip_grok_inbox");
|
||||
expect(access).toContain("enter the one-use pairing code there");
|
||||
expect(access).not.toContain("paperclip_dot_");
|
||||
const routine = buildGrokRoutinePrompt("11111111-1111-4111-8111-111111111111", "Night Shift");
|
||||
expect(routine).toContain("paperclip_grok_ack_wake");
|
||||
expect(routine).toContain("bindingGeneration");
|
||||
expect(routine).toContain("paperclip_grok_request_turn");
|
||||
expect(routine).toContain("paperclip_grok_operation_status");
|
||||
expect(routine).toContain("before finishing, drain paperclip_grok_inbox");
|
||||
expect(routine).not.toContain("paperclip_dot_");
|
||||
expect(routine).not.toContain("Bearer ");
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,3 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { CompanySecretProviderConfig, SecretProviderDescriptor } from "@paperclipai/shared";
|
||||
|
||||
@@ -1,326 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { Browse, pendingFirstSignInOnlyApplicationIds } from "./Browse";
|
||||
import { getAppStoreDefinition } from "@paperclipai/shared";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import type { AggregatorAppCatalogEntry } from "@paperclipai/shared/aggregator-app-catalog";
|
||||
import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils";
|
||||
|
||||
const aggregatorCatalogMock = vi.hoisted(() => [] as AggregatorAppCatalogEntry[]);
|
||||
const openNewIssueMock = vi.hoisted(() => vi.fn());
|
||||
const listAgentsMock = vi.hoisted(() => vi.fn());
|
||||
const setupComposioAppMock = vi.hoisted(() => vi.fn());
|
||||
const listComposioAppsMock = vi.hoisted(() => vi.fn());
|
||||
const syncComposioAppsMock = vi.hoisted(() => vi.fn());
|
||||
const refreshComposioAppsMock = vi.hoisted(() => vi.fn());
|
||||
const manageComposioAppAccountMock = vi.hoisted(() => vi.fn());
|
||||
|
||||
function genericResponse(value: { apps?: any[]; sync?: Record<string, unknown> }) {
|
||||
return {
|
||||
provider: "composio",
|
||||
discovery: { availability: "available", message: null },
|
||||
sync: { status: "ready", ...value.sync },
|
||||
apps: (value.apps ?? []).map((snapshot) => ({
|
||||
...snapshot,
|
||||
provider: snapshot.provider ?? "composio",
|
||||
appSlug: snapshot.appSlug ?? aggregatorCatalogMock.find((app) => app.aliases.includes(snapshot.toolkit) || app.routes.some((route) => route.toolkit === snapshot.toolkit))?.slug ?? snapshot.toolkit,
|
||||
appName: snapshot.appName ?? snapshot.toolkit,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
vi.mock("@/api/agents", () => ({ agentsApi: { list: (companyId: string) => listAgentsMock(companyId) } }));
|
||||
vi.mock("@paperclipai/shared/aggregator-app-catalog", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@paperclipai/shared/aggregator-app-catalog")>();
|
||||
return {
|
||||
...actual,
|
||||
AGGREGATOR_APP_CATALOG: aggregatorCatalogMock,
|
||||
findComposioCatalogApp: (toolkit: string) =>
|
||||
aggregatorCatalogMock.find((app) => app.aliases.includes(toolkit) || app.routes.some((route) => route.provider === "composio" && route.toolkit === toolkit)),
|
||||
};
|
||||
});
|
||||
vi.mock("@/context/DialogContext", () => ({ useDialogActions: () => ({ openNewIssue: openNewIssueMock }) }));
|
||||
|
||||
const accountIdentity = vi.hoisted(() => ({ userId: "board-user" as string | null, settled: true, failed: false }));
|
||||
vi.mock("@/api/companies-query", () => ({ useAccountIdentity: () => accountIdentity }));
|
||||
|
||||
const poolListMock = vi.hoisted(() => vi.fn());
|
||||
const poolRemoveMock = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@/api/ai-connection-pools", () => ({ aiConnectionPoolsApi: { list: poolListMock, remove: poolRemoveMock } }));
|
||||
|
||||
const assistantConnectionsMock = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@/api/publicMcp", () => ({ publicMcpApi: { connections: assistantConnectionsMock } }));
|
||||
const tailscaleConnectionsMock = vi.hoisted(() => vi.fn(async () => [] as Array<{ id: string; companyId: string; name: string; status: string }>));
|
||||
vi.mock("@/api/tailscale", () => ({ tailscaleApi: { list: tailscaleConnectionsMock } }));
|
||||
|
||||
const listGalleryMock = vi.hoisted(() => vi.fn());
|
||||
const listApplicationsMock = vi.hoisted(() => vi.fn());
|
||||
const listConnectionsMock = vi.hoisted(() => vi.fn());
|
||||
const listAiConnectionsMock = vi.hoisted(() => vi.fn());
|
||||
const setAiDefaultMock = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@/api/ai-connections", () => ({ aiConnectionsApi: { list: listAiConnectionsMock, setDefault: setAiDefaultMock } }));
|
||||
const listUserDirectoryMock = vi.hoisted(() => vi.fn());
|
||||
const boardAccessMock = vi.hoisted(() => vi.fn());
|
||||
const archiveConnectionMock = vi.hoisted(() => vi.fn());
|
||||
const pushToastMock = vi.hoisted(() => vi.fn());
|
||||
const navigateMock = vi.hoisted(() => vi.fn());
|
||||
const setBreadcrumbsMock = vi.hoisted(() => vi.fn());
|
||||
const experimentalMock = vi.hoisted(() => vi.fn());
|
||||
const chatSetupMock = vi.hoisted(() => vi.fn());
|
||||
const emailControlMock = vi.hoisted(() => vi.fn());
|
||||
const chatListMock = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@/api/instanceSettings", () => ({ instanceSettingsApi: { getExperimental: experimentalMock } }));
|
||||
vi.mock("@/api/chatEndpoints", () => ({ chatEndpointsApi: { list: chatListMock, setup: chatSetupMock } }));
|
||||
vi.mock("@/api/email", () => ({ emailApi: { control: emailControlMock } }));
|
||||
|
||||
vi.mock("@/api/tools", () => ({
|
||||
toolsApi: {
|
||||
listAggregatorApps: async (...args: unknown[]) => genericResponse(await listComposioAppsMock(...args)),
|
||||
syncAggregatorApps: async (...args: unknown[]) => genericResponse(await syncComposioAppsMock(...args)),
|
||||
refreshAggregatorApps: async (...args: unknown[]) => genericResponse(await refreshComposioAppsMock(...args)),
|
||||
refreshCatalog: vi.fn().mockResolvedValue({}),
|
||||
configureArcadeDiscovery: vi.fn(),
|
||||
syncComposioApps: (...args: unknown[]) => syncComposioAppsMock(...args),
|
||||
listComposioApps: (...args: unknown[]) => listComposioAppsMock(...args),
|
||||
refreshComposioApps: (...args: unknown[]) => refreshComposioAppsMock(...args),
|
||||
manageComposioAppAccount: (...args: unknown[]) => manageComposioAppAccountMock(...args),
|
||||
setupComposioApp: (...args: unknown[]) => setupComposioAppMock(...args),
|
||||
listGallery: (companyId: string) => listGalleryMock(companyId),
|
||||
listApplications: (companyId: string) => listApplicationsMock(companyId),
|
||||
listConnections: (companyId: string) => listConnectionsMock(companyId),
|
||||
archiveConnection: (connectionId: string) => archiveConnectionMock(connectionId),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/api/access", () => ({
|
||||
accessApi: {
|
||||
listUserDirectory: (companyId: string) => listUserDirectoryMock(companyId),
|
||||
getCurrentBoardAccess: boardAccessMock,
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/router", () => ({
|
||||
Link: ({ children, to, className }: { children: React.ReactNode; to: string; className?: string }) => (
|
||||
<a href={to} className={className}>{children}</a>
|
||||
),
|
||||
useNavigate: () => navigateMock,
|
||||
}));
|
||||
|
||||
vi.mock("@/context/CompanyContext", () => ({
|
||||
useCompany: () => ({
|
||||
selectedCompanyId: "company-1",
|
||||
selectedCompany: { id: "company-1", name: "Paperclip" },
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@/context/BreadcrumbContext", () => ({
|
||||
useBreadcrumbs: () => ({ setBreadcrumbs: setBreadcrumbsMock }),
|
||||
}));
|
||||
|
||||
vi.mock("@/context/ToastContext", () => ({
|
||||
useToast: () => ({ pushToast: pushToastMock }),
|
||||
useOptionalToastActions: () => ({ pushToast: pushToastMock }),
|
||||
}));
|
||||
|
||||
async function act(callback: () => void | Promise<void>) {
|
||||
let result: void | Promise<void> = undefined;
|
||||
flushSync(() => {
|
||||
result = callback();
|
||||
});
|
||||
await result;
|
||||
}
|
||||
|
||||
async function flushReact() {
|
||||
for (let index = 0; index < 5; index += 1) {
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
await new Promise((resolve) => window.setTimeout(resolve, 0));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function application(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: "app-notion",
|
||||
name: "Notion",
|
||||
description: "Read and update workspace content.",
|
||||
status: "active",
|
||||
applicationKey: "app-gallery:notion:one",
|
||||
metadata: { sourceTemplateKey: "notion" },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function connection(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: "conn-notion",
|
||||
applicationId: "app-notion",
|
||||
transport: "mcp_remote",
|
||||
name: "devinfoley@gmail.com",
|
||||
status: "active",
|
||||
enabled: true,
|
||||
authKind: "oauth",
|
||||
healthStatus: "ok",
|
||||
healthMessage: null,
|
||||
lastError: null,
|
||||
createdByUserId: "user-1",
|
||||
config: { sourceTemplateKey: "notion" },
|
||||
transportConfig: {},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("Connectors landing page privacy & access gates", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: ReturnType<typeof createRoot>;
|
||||
|
||||
beforeEach(() => {
|
||||
boardAccessMock.mockReset().mockResolvedValue({ source: "session", isInstanceAdmin: true });
|
||||
accountIdentity.userId = "board-user";
|
||||
accountIdentity.settled = true;
|
||||
assistantConnectionsMock.mockReset().mockResolvedValue([]);
|
||||
syncComposioAppsMock.mockReset().mockImplementation((...args) => listComposioAppsMock(...args));
|
||||
listComposioAppsMock.mockReset().mockResolvedValue({ apps: [] });
|
||||
refreshComposioAppsMock.mockReset().mockResolvedValue({ apps: [] });
|
||||
manageComposioAppAccountMock.mockReset();
|
||||
listAgentsMock.mockResolvedValue([{ id: "default-agent", name: "Default agent", role: "ceo", reportsTo: null, status: "active", createdAt: new Date(0) }]);
|
||||
aggregatorCatalogMock.splice(0);
|
||||
experimentalMock.mockResolvedValue({ enableChatConnectors: true, enableGitHubReviewBots: true });
|
||||
chatListMock.mockResolvedValue([]);
|
||||
chatSetupMock.mockReset().mockResolvedValue({ status: "archived" });
|
||||
emailControlMock.mockReset().mockResolvedValue({ status: "archived" });
|
||||
listGalleryMock.mockResolvedValue({ apps: [] });
|
||||
listApplicationsMock.mockResolvedValue({ applications: [] });
|
||||
listConnectionsMock.mockResolvedValue({ connections: [] });
|
||||
listAiConnectionsMock.mockReset().mockResolvedValue({ currentUserId: "board-user", canManageConnections: true, connections: [] });
|
||||
setAiDefaultMock.mockReset().mockResolvedValue({ ok: true });
|
||||
listUserDirectoryMock.mockResolvedValue({ users: [] });
|
||||
archiveConnectionMock.mockResolvedValue(connection({ status: "archived" }));
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root?.unmount());
|
||||
container.remove();
|
||||
document.body.innerHTML = "";
|
||||
window.history.replaceState({}, "", "/");
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
async function renderBrowse(allCatalog = true) {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
root = createRoot(container);
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={client}>
|
||||
<TooltipProvider><Browse /></TooltipProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await flushReact();
|
||||
if (allCatalog) {
|
||||
await clickButton("All", container);
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
async function clickButton(text: string, scope: ParentNode = document) {
|
||||
const button = Array.from(scope.querySelectorAll<HTMLButtonElement>("button")).find((b) => b.textContent?.trim() === text)!;
|
||||
expect(button).toBeTruthy();
|
||||
await act(() => button.click());
|
||||
await flushReact();
|
||||
}
|
||||
|
||||
async function search(value: string) {
|
||||
const input = container.querySelector<HTMLInputElement>('input[aria-label="Search connectors"]')!;
|
||||
await act(() => {
|
||||
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
await flushReact();
|
||||
}
|
||||
|
||||
it("titles the Google AI connector after Antigravity and Gemini", async () => {
|
||||
listGalleryMock.mockResolvedValue({ apps: [getAppStoreDefinition("google")] });
|
||||
await renderBrowse(false);
|
||||
const google = container.querySelector('[data-app-slug="google"]');
|
||||
expect(google?.querySelector("h2")?.textContent).toBe("Google Antigravity and Gemini");
|
||||
expect(google?.textContent).toContain("Connect Google Antigravity accounts or Gemini API keys for your agents.");
|
||||
expect(container.querySelector('[aria-label="Connect Google Antigravity and Gemini"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it("does not advertise Tailscale setup or request tailnets for non-instance-admin members", async () => {
|
||||
boardAccessMock.mockResolvedValue({ source: "session", isInstanceAdmin: false });
|
||||
await renderBrowse(false);
|
||||
await search("Tailscale");
|
||||
expect(container.querySelector('[aria-label="Connect Tailscale"]')).toBeNull();
|
||||
expect(container.querySelector('[data-app-slug="tailscale"]')).toBeNull();
|
||||
expect(tailscaleConnectionsMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("masks upstream account labels in the Manage dialog from session replay", async () => {
|
||||
aggregatorCatalogMock.push({
|
||||
name: "Fathom",
|
||||
slug: "fathom",
|
||||
aliases: ["fathom"],
|
||||
routes: [{ provider: "composio", toolkit: "fathom", logoUrl: "https://logos.example.com/fathom.svg", docsUrl: "https://docs.composio.dev/fathom" }],
|
||||
});
|
||||
listGalleryMock.mockResolvedValue({ apps: [getAppStoreDefinition("composio")] });
|
||||
listApplicationsMock.mockResolvedValue({ applications: [application({ id: "gateway-app", name: "Composio", metadata: { sourceTemplateKey: "composio" } })] });
|
||||
listConnectionsMock.mockResolvedValue({ connections: [connection({ applicationId: "gateway-app", name: "Composio account", transport: "mcp_remote", config: { sourceTemplateKey: "composio" } })] });
|
||||
const snapshot = { connectionId: "conn-notion", toolkit: "fathom", status: "connected", checkedAt: new Date().toISOString(), accounts: [{ id: "ca-work", alias: "Meeting notes", status: "ACTIVE", isDefault: true }] };
|
||||
listComposioAppsMock.mockResolvedValue({ apps: [snapshot] });
|
||||
refreshComposioAppsMock.mockResolvedValue({ apps: [snapshot] });
|
||||
|
||||
await renderBrowse();
|
||||
await clickButton("Manage", container);
|
||||
const dialog = document.querySelector('[role="dialog"]')!;
|
||||
expect(replayLeaks("Meeting notes", dialog)).toEqual({ rendered: true, recorded: false });
|
||||
expect(replayLeaks("Composio account", dialog)).toEqual({ rendered: true, recorded: false });
|
||||
});
|
||||
|
||||
it("masks Notebook account labels in the row and removal confirmation dialog from session replay", async () => {
|
||||
listGalleryMock.mockResolvedValue({ apps: [getAppStoreDefinition("paperclip-notebook")] });
|
||||
listApplicationsMock.mockResolvedValue({ applications: [application({
|
||||
id: "notebook-app", name: "Paperclip Notebook", applicationKey: "app-gallery:paperclip-notebook:one",
|
||||
metadata: { sourceTemplateKey: "paperclip-notebook" },
|
||||
})] });
|
||||
listConnectionsMock.mockResolvedValue({ connections: [connection({
|
||||
id: "saved-notebook", applicationId: "notebook-app", name: "Notebook account",
|
||||
config: { sourceTemplateKey: "paperclip-notebook" }, healthStatus: "error", requiresReauthorization: true,
|
||||
})] });
|
||||
|
||||
await renderBrowse();
|
||||
const row = container.querySelector('[data-app-slug="paperclip-notebook"]')!;
|
||||
await act(() => { row.querySelector<HTMLButtonElement>('button[aria-label^="Manage "]')!.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true })); });
|
||||
await flushReact();
|
||||
expect(replayLeaks("Notebook account", row)).toEqual({ rendered: true, recorded: false });
|
||||
await act(() => { [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find((item) => item.textContent?.trim() === "Remove connection")!.click(); });
|
||||
await flushReact();
|
||||
const removeDialog = document.querySelector('[role="alertdialog"]')!;
|
||||
expect(replayLeaks("Notebook account", removeDialog)).toEqual({ rendered: true, recorded: false });
|
||||
});
|
||||
|
||||
it("finds apps with only unfinished sign-ins in one pass over a large list", () => {
|
||||
const connections = Array.from({ length: 5000 }, (_, index) => ({
|
||||
applicationId: `app-${index % 2500}`,
|
||||
status: index < 2500 ? "draft" as const : "active" as const,
|
||||
firstSignInPending: index < 2500 || undefined,
|
||||
}));
|
||||
connections.push({ applicationId: "app-only-pending", status: "draft", firstSignInPending: true });
|
||||
let reads = 0;
|
||||
const counted = new Proxy(connections, {
|
||||
get(target, key, receiver) {
|
||||
if (typeof key === "string" && /^\d+$/.test(key)) reads += 1;
|
||||
return Reflect.get(target, key, receiver);
|
||||
},
|
||||
});
|
||||
expect([...pendingFirstSignInOnlyApplicationIds(counted)]).toEqual(["app-only-pending"]);
|
||||
expect(reads).toBeLessThanOrEqual(connections.length);
|
||||
});
|
||||
});
|
||||
@@ -1,461 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { flushSync } from "react-dom";
|
||||
import type { ReactNode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ToolCatalogEntry } from "@paperclipai/shared";
|
||||
import { ActionTestDialog, errorHints } from "./ActionTestDialog";
|
||||
import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils";
|
||||
|
||||
const listTestAgentsMock = vi.hoisted(() => vi.fn());
|
||||
const getTestAgentAccessMock = vi.hoisted(() => vi.fn());
|
||||
const runTestCallMock = vi.hoisted(() => vi.fn());
|
||||
const getTestCallStatusMock = vi.hoisted(() => vi.fn());
|
||||
const declineActionRequestMock = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("@/api/tools", () => ({
|
||||
toolsApi: {
|
||||
listTestAgents: (connectionId: string) => listTestAgentsMock(connectionId),
|
||||
getTestAgentAccess: (connectionId: string, agentId: string) => getTestAgentAccessMock(connectionId, agentId),
|
||||
runTestCall: (connectionId: string, input: unknown) => runTestCallMock(connectionId, input),
|
||||
getTestCallStatus: (connectionId: string, requestId: string) => getTestCallStatusMock(connectionId, requestId),
|
||||
declineActionRequest: (companyId: string, requestId: string) => declineActionRequestMock(companyId, requestId),
|
||||
},
|
||||
}));
|
||||
vi.mock("@/context/CompanyContext", () => ({
|
||||
useCompany: () => ({ selectedCompanyId: "company-1" }),
|
||||
}));
|
||||
vi.mock("@/lib/router", () => ({
|
||||
Link: ({ to, children, ...props }: { to: string; children: ReactNode }) => <a href={to} {...props}>{children}</a>,
|
||||
}));
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const entry = {
|
||||
id: "asana-list-projects",
|
||||
companyId: "company-1",
|
||||
applicationId: "app-asana",
|
||||
connectionId: "conn-1",
|
||||
entryKind: "tool",
|
||||
toolName: "list_projects",
|
||||
title: "List projects",
|
||||
description: "Find Asana projects.",
|
||||
inputSchema: { type: "object", properties: {} },
|
||||
outputSchema: null,
|
||||
annotations: null,
|
||||
riskLevel: "read",
|
||||
isReadOnly: true,
|
||||
isWrite: false,
|
||||
isDestructive: false,
|
||||
status: "active",
|
||||
addedAt: new Date("2026-09-01T00:00:00Z"),
|
||||
version: null,
|
||||
schemaHash: null,
|
||||
firstSeenAt: new Date("2026-09-01T00:00:00Z"),
|
||||
lastSeenAt: new Date("2026-10-01T00:00:00Z"),
|
||||
reviewedAt: null,
|
||||
reviewedByAgentId: null,
|
||||
reviewedByUserId: null,
|
||||
createdAt: new Date("2026-09-01T00:00:00Z"),
|
||||
updatedAt: new Date("2026-10-01T00:00:00Z"),
|
||||
} as ToolCatalogEntry;
|
||||
|
||||
const askFirstEntry = {
|
||||
...entry,
|
||||
id: "asana-create-task",
|
||||
toolName: "create_task",
|
||||
title: "Create task",
|
||||
riskLevel: "write",
|
||||
isReadOnly: false,
|
||||
isWrite: true,
|
||||
} as ToolCatalogEntry;
|
||||
|
||||
let container: HTMLDivElement;
|
||||
let root: ReturnType<typeof createRoot>;
|
||||
let client: QueryClient;
|
||||
|
||||
async function act(callback: () => void | Promise<void>) {
|
||||
let result: void | Promise<void> | undefined;
|
||||
flushSync(() => { result = callback(); });
|
||||
await result;
|
||||
}
|
||||
|
||||
async function flushReact() {
|
||||
for (let i = 0; i < 4; i += 1) {
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
await new Promise((resolve) => window.setTimeout(resolve, 0));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function renderDialog(testEntry = entry) {
|
||||
await act(() => root.render(
|
||||
<QueryClientProvider client={client}>
|
||||
<ActionTestDialog connectionId="conn-1" appName="Asana" entry={testEntry} open onOpenChange={() => undefined} />
|
||||
</QueryClientProvider>,
|
||||
));
|
||||
await flushReact();
|
||||
}
|
||||
|
||||
async function openAndRun(testEntry = entry) {
|
||||
await renderDialog(testEntry);
|
||||
const button = [...document.body.querySelectorAll("button")].find((candidate) => candidate.textContent?.trim() === "Run");
|
||||
expect(button).toBeTruthy();
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });
|
||||
try {
|
||||
await act(() => button!.click());
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(260); });
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
await flushReact();
|
||||
}
|
||||
|
||||
function allowAskFirst() {
|
||||
getTestAgentAccessMock.mockResolvedValue({
|
||||
access: {
|
||||
connectionId: "conn-1", toolCount: 1, allowedCount: 0, askFirstCount: 1, offCount: 0,
|
||||
lastChangedAt: null, lastChangedByAgentId: null, lastChangedByName: null,
|
||||
tools: [{ toolName: "create_task", gatewayToolName: "asana__create_task", displayName: "Create task", risk: "write", decision: "ask_first", reasonCode: null, matchedPolicyIds: [] }],
|
||||
},
|
||||
});
|
||||
runTestCallMock.mockResolvedValue({ decision: "ask_first", invocationId: "ask-invocation", actionRequestId: "request-1" });
|
||||
}
|
||||
|
||||
function requestStatus(phase: "waiting" | "running" | "done" | "denied") {
|
||||
return {
|
||||
actionRequestId: "request-1", invocationId: "ask-invocation", phase,
|
||||
parameters: {}, requestedAt: "2026-10-01T00:00:00.000Z",
|
||||
resolvedAt: phase === "waiting" ? null : "2026-10-01T00:00:05.000Z",
|
||||
durationMs: phase === "done" ? 1200 : null,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
listTestAgentsMock.mockReset().mockResolvedValue({
|
||||
agents: [{ id: "agent-ceo", name: "CEO", role: "ceo", title: "CEO", status: "active", orgDepth: 0 }],
|
||||
});
|
||||
getTestAgentAccessMock.mockReset().mockResolvedValue({
|
||||
access: {
|
||||
connectionId: "conn-1", toolCount: 1, allowedCount: 1, askFirstCount: 0, offCount: 0,
|
||||
lastChangedAt: null, lastChangedByAgentId: null, lastChangedByName: null,
|
||||
tools: [{ toolName: "list_projects", gatewayToolName: "asana__list_projects", displayName: "List projects", risk: "read", decision: "allowed", reasonCode: null, matchedPolicyIds: [] }],
|
||||
},
|
||||
});
|
||||
runTestCallMock.mockReset();
|
||||
getTestCallStatusMock.mockReset().mockResolvedValue(requestStatus("waiting"));
|
||||
declineActionRequestMock.mockReset();
|
||||
window.sessionStorage.clear();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await act(() => root.unmount());
|
||||
container.remove();
|
||||
window.sessionStorage.clear();
|
||||
});
|
||||
|
||||
describe("Permissions action Test dialog", () => {
|
||||
it("forwards an explicitly cleared optional text field", async () => {
|
||||
const textEntry = {
|
||||
...entry,
|
||||
inputSchema: { type: "object", properties: { update_text: { type: "string" } } },
|
||||
} as ToolCatalogEntry;
|
||||
runTestCallMock.mockResolvedValue({ decision: "allowed", invocationId: "empty-text" });
|
||||
|
||||
await renderDialog(textEntry);
|
||||
const moreOptions = [...document.body.querySelectorAll("button")].find((button) => button.textContent?.trim() === "More options");
|
||||
expect(moreOptions).toBeTruthy();
|
||||
await act(() => moreOptions!.click());
|
||||
const input = document.body.querySelector<HTMLInputElement>('input[aria-label="Update Text"]');
|
||||
expect(input).toBeTruthy();
|
||||
const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
|
||||
await act(() => {
|
||||
setValue!.call(input, "draft");
|
||||
input!.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
await act(() => {
|
||||
setValue!.call(input, "");
|
||||
input!.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
const runButton = [...document.body.querySelectorAll("button")].find((button) => button.textContent?.trim() === "Run");
|
||||
await act(() => runButton!.click());
|
||||
await flushReact();
|
||||
|
||||
expect(runTestCallMock).toHaveBeenCalledWith("conn-1", {
|
||||
agentId: "agent-ceo",
|
||||
toolName: "list_projects",
|
||||
parameters: { update_text: "" },
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards false, zero, and an explicit object default without normalization", async () => {
|
||||
const defaultsEntry = {
|
||||
...entry,
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
enabled: { type: "boolean", default: false },
|
||||
count: { type: "integer", default: 0 },
|
||||
options: {
|
||||
type: "object",
|
||||
default: { enabled: false, count: 0 },
|
||||
required: ["enabled", "count"],
|
||||
properties: {
|
||||
enabled: { type: "boolean" },
|
||||
count: { type: "integer" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
} as ToolCatalogEntry;
|
||||
runTestCallMock.mockResolvedValue({ decision: "allowed", invocationId: "defaults" });
|
||||
|
||||
await renderDialog(defaultsEntry);
|
||||
const runButton = [...document.body.querySelectorAll("button")].find((button) => button.textContent?.trim() === "Run");
|
||||
await act(() => runButton!.click());
|
||||
await flushReact();
|
||||
|
||||
expect(runTestCallMock).toHaveBeenCalledWith("conn-1", {
|
||||
agentId: "agent-ceo",
|
||||
toolName: "list_projects",
|
||||
parameters: { enabled: false, count: 0, options: { enabled: false, count: 0 } },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects an explicitly supplied empty optional object with required children", async () => {
|
||||
const objectEntry = {
|
||||
...entry,
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
options: {
|
||||
type: "object",
|
||||
default: {},
|
||||
required: ["name"],
|
||||
properties: { name: { type: "string" } },
|
||||
},
|
||||
},
|
||||
},
|
||||
} as ToolCatalogEntry;
|
||||
|
||||
await renderDialog(objectEntry);
|
||||
const runButton = [...document.body.querySelectorAll("button")].find((button) => button.textContent?.trim() === "Run");
|
||||
await act(() => runButton!.click());
|
||||
await flushReact();
|
||||
|
||||
expect(document.body.textContent).toContain("This field is required");
|
||||
expect(runTestCallMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("runs the actual ActionTester with Firecrawl's minimal URL input after opening More options", async () => {
|
||||
const firecrawlEntry = {
|
||||
...entry,
|
||||
id: "firecrawl-scrape",
|
||||
toolName: "firecrawl_scrape",
|
||||
title: "Firecrawl scrape",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
url: { type: "string" },
|
||||
profile: { type: "object", required: ["name"], properties: { name: { type: "string" } } },
|
||||
queryOptions: {
|
||||
type: "object",
|
||||
required: ["prompt"],
|
||||
properties: {
|
||||
mode: { type: "string", enum: ["directQuote", "freeform"], default: "freeform" },
|
||||
prompt: { type: "string" },
|
||||
},
|
||||
},
|
||||
screenshotOptions: {
|
||||
type: "object",
|
||||
properties: {
|
||||
viewport: {
|
||||
type: "object",
|
||||
required: ["width", "height"],
|
||||
properties: { width: { type: "number" }, height: { type: "number" } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
} as ToolCatalogEntry;
|
||||
getTestAgentAccessMock.mockResolvedValue({
|
||||
access: {
|
||||
connectionId: "conn-1", toolCount: 1, allowedCount: 1, askFirstCount: 0, offCount: 0,
|
||||
lastChangedAt: null, lastChangedByAgentId: null, lastChangedByName: null,
|
||||
tools: [{ toolName: "firecrawl_scrape", gatewayToolName: "firecrawl__firecrawl_scrape", displayName: "Firecrawl scrape", risk: "read", decision: "allowed", reasonCode: null, matchedPolicyIds: [] }],
|
||||
},
|
||||
});
|
||||
runTestCallMock.mockResolvedValue({ decision: "allowed", invocationId: "firecrawl-minimal" });
|
||||
|
||||
await renderDialog(firecrawlEntry);
|
||||
const moreOptions = [...document.body.querySelectorAll("button")].find((button) => button.textContent?.trim() === "More options");
|
||||
expect(moreOptions).toBeTruthy();
|
||||
await act(() => moreOptions!.click());
|
||||
const urlInput = document.body.querySelector<HTMLInputElement>('input[aria-label="Url"]');
|
||||
expect(urlInput, document.body.textContent).toBeTruthy();
|
||||
const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
|
||||
await act(() => {
|
||||
setValue!.call(urlInput, "https://paperclip.ing");
|
||||
urlInput!.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
const runButton = [...document.body.querySelectorAll("button")].find((button) => button.textContent?.trim() === "Run");
|
||||
expect(runButton).toBeTruthy();
|
||||
await act(() => runButton!.click());
|
||||
await flushReact();
|
||||
|
||||
expect(document.body.textContent).not.toContain("This field is required");
|
||||
expect(runTestCallMock).toHaveBeenCalledWith("conn-1", {
|
||||
agentId: "agent-ceo",
|
||||
toolName: "firecrawl_scrape",
|
||||
parameters: { url: "https://paperclip.ing" },
|
||||
});
|
||||
});
|
||||
|
||||
it("renders structured MCP rows and keeps the full response behind the raw disclosure", async () => {
|
||||
runTestCallMock.mockResolvedValue({
|
||||
decision: "allowed", invocationId: "structured",
|
||||
result: {
|
||||
content: '{"data":[{"name":"Q4 launch"},{"name":"Customer onboarding"}]}',
|
||||
data: {
|
||||
content: [{ type: "text", text: '{"data":[{"name":"Q4 launch"},{"name":"Customer onboarding"}]}' }],
|
||||
structuredContent: { data: [{ name: "Q4 launch" }, { name: "Customer onboarding" }] },
|
||||
isError: false, transport: "mcp_http",
|
||||
},
|
||||
},
|
||||
});
|
||||
await openAndRun();
|
||||
expect(runTestCallMock).toHaveBeenCalledWith("conn-1", { agentId: "agent-ceo", toolName: "list_projects", parameters: {} });
|
||||
expect(document.body.textContent).toContain("Worked. 2 rows came back.");
|
||||
expect(document.body.querySelector("table")?.textContent).toContain("Q4 launch");
|
||||
expect(document.body.textContent).not.toContain("structuredContent");
|
||||
const raw = [...document.body.querySelectorAll("button")].find((button) => button.textContent?.trim() === "Show raw response");
|
||||
expect(replayLeaks("Customer onboarding", document.body)).toEqual({ rendered: true, recorded: false });
|
||||
await act(() => raw!.click());
|
||||
expect(document.body.textContent).toContain("structuredContent");
|
||||
expect(replayLeaks("structuredContent", document.body)).toEqual({ rendered: true, recorded: false });
|
||||
expect(replayLeaks("Customer onboarding", document.body).recorded).toBe(false);
|
||||
});
|
||||
|
||||
it("parses JSON text when structured content is absent", async () => {
|
||||
runTestCallMock.mockResolvedValue({
|
||||
decision: "allowed", invocationId: "text",
|
||||
result: { content: '{"data":[{"name":"Q4 launch"}]}', data: { content: [{ type: "text", text: '{"data":[{"name":"Q4 launch"}]}' }], structuredContent: null, isError: false } },
|
||||
});
|
||||
await openAndRun();
|
||||
expect(document.body.querySelector("table")?.textContent).toContain("Q4 launch");
|
||||
});
|
||||
|
||||
it("uses structured content when an MCP result has no content blocks", async () => {
|
||||
runTestCallMock.mockResolvedValue({
|
||||
decision: "allowed", invocationId: "structured-only",
|
||||
result: { content: "", data: { structuredContent: { results: [{ name: "Northstar launch plan" }] }, isError: false } },
|
||||
});
|
||||
await openAndRun();
|
||||
expect(document.body.textContent).toContain("Worked. 1 row came back.");
|
||||
expect(document.body.querySelector("table")?.textContent).toContain("Northstar launch plan");
|
||||
expect(document.body.textContent).not.toContain("structuredContent");
|
||||
});
|
||||
|
||||
it("shows wide search results as readable cards with a safe page link", async () => {
|
||||
const rows = [{
|
||||
id: "11111111-2222-4333-8444-555555555555",
|
||||
title: "Northstar launch plan",
|
||||
url: "https://www.notion.so/11111111222243338444555555555555",
|
||||
type: "page",
|
||||
highlight: "The launch plan covers milestones, owners, and a detailed summary that should not stretch a table row in the dialog.",
|
||||
timestamp: "2026-09-10T14:30:00.000Z",
|
||||
}];
|
||||
runTestCallMock.mockResolvedValue({
|
||||
decision: "allowed", invocationId: "notion-wide",
|
||||
result: { content: JSON.stringify({ results: rows }), data: { content: [{ type: "text", text: JSON.stringify({ results: rows }) }], structuredContent: null, isError: false } },
|
||||
});
|
||||
await openAndRun();
|
||||
expect(document.body.querySelector("table")).toBeNull();
|
||||
expect(document.body.textContent).toContain("Northstar launch plan");
|
||||
expect(document.body.textContent).toContain("The launch plan covers milestones");
|
||||
expect(document.body.querySelector('a[href="https://www.notion.so/11111111222243338444555555555555"]')?.textContent).toBe("Open link");
|
||||
});
|
||||
|
||||
it("shows a non-link URL as a field in a result card", async () => {
|
||||
const rows = [{ title: "Northstar launch plan", url: "notion://workspace/launch", description: "A long description that keeps the card layout useful even when the provider supplies a URL that cannot open in a browser." }];
|
||||
runTestCallMock.mockResolvedValue({
|
||||
decision: "allowed", invocationId: "non-link-url",
|
||||
result: { content: JSON.stringify({ results: rows }), data: { content: [{ type: "text", text: JSON.stringify({ results: rows }) }], isError: false } },
|
||||
});
|
||||
await openAndRun();
|
||||
expect(document.body.querySelector('a[href="notion://workspace/launch"]')).toBeNull();
|
||||
expect(document.body.textContent).toContain("notion://workspace/launch");
|
||||
});
|
||||
|
||||
it("keeps an ask-first request visible after reopening the dialog", async () => {
|
||||
allowAskFirst();
|
||||
await openAndRun(askFirstEntry);
|
||||
expect(document.body.textContent).toContain("Sent for your OK.");
|
||||
expect(document.body.textContent).toContain("Cancel this request");
|
||||
expect(document.body.querySelector('a[href="/apps/conn-1/review"]')).toBeTruthy();
|
||||
|
||||
await act(() => root.unmount());
|
||||
root = createRoot(container);
|
||||
await renderDialog(askFirstEntry);
|
||||
expect(runTestCallMock).toHaveBeenCalledTimes(1);
|
||||
expect(document.body.textContent).toContain("Sent for your OK.");
|
||||
});
|
||||
|
||||
it("shows an approved request running and then the completed result", async () => {
|
||||
allowAskFirst();
|
||||
getTestCallStatusMock.mockResolvedValue(requestStatus("running"));
|
||||
await openAndRun(askFirstEntry);
|
||||
expect(document.body.textContent).toContain("Approved · running");
|
||||
expect(document.body.textContent).not.toContain("Cancel this request");
|
||||
|
||||
getTestCallStatusMock.mockResolvedValue({ ...requestStatus("done"), result: [{ name: "Northstar launch plan" }] });
|
||||
await act(async () => { await client.invalidateQueries({ queryKey: ["tools"] }); });
|
||||
await flushReact();
|
||||
expect(document.body.textContent).toContain("Worked.");
|
||||
expect(document.body.textContent).toContain("Northstar launch plan");
|
||||
expect(runTestCallMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("shows a denied request without offering cancellation", async () => {
|
||||
allowAskFirst();
|
||||
getTestCallStatusMock.mockResolvedValue(requestStatus("denied"));
|
||||
await openAndRun(askFirstEntry);
|
||||
expect(document.body.textContent).toContain("Denied — see Review for why");
|
||||
expect(document.body.textContent).not.toContain("Cancel this request");
|
||||
});
|
||||
|
||||
it("shows a tool error and opens its raw response", async () => {
|
||||
runTestCallMock.mockResolvedValue({
|
||||
decision: "allowed", invocationId: "error",
|
||||
result: { content: "Asana denied access to this workspace.", data: { content: [{ type: "text", text: "Asana denied access to this workspace." }], isError: true }, error: "MCP tool returned an error result" },
|
||||
});
|
||||
await openAndRun();
|
||||
expect(document.body.textContent).toContain("It didn't work.");
|
||||
expect(document.body.textContent).toContain("Asana denied access to this workspace.");
|
||||
expect(document.body.textContent).toContain("Hide raw response");
|
||||
});
|
||||
|
||||
it("opens the raw response when an MCP block has an unexpected shape", async () => {
|
||||
runTestCallMock.mockResolvedValue({
|
||||
decision: "allowed", invocationId: "malformed",
|
||||
result: { content: "", data: { content: [{ type: "text", payload: "missing text" }], structuredContent: null, isError: false } },
|
||||
});
|
||||
await openAndRun();
|
||||
expect(document.body.textContent).toContain("Hide raw response");
|
||||
expect(document.body.textContent).toContain("missing text");
|
||||
});
|
||||
|
||||
it("keeps useful and generic error hints", () => {
|
||||
expect(errorHints("Not found", "NOT_FOUND").join(" ")).toMatch(/check|verify|ID/i);
|
||||
expect(errorHints("Unexpected provider failure", null).length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
@@ -1,72 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ToolCatalogEntry } from "@paperclipai/shared";
|
||||
import { ActionsSection } from "./PermissionsPanel";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
vi.mock("@/context/CompanyContext", () => ({
|
||||
useCompany: () => ({ selectedCompanyId: "company-1", selectedCompany: { id: "company-1", issuePrefix: "PAP" } }),
|
||||
}));
|
||||
|
||||
let container: HTMLDivElement | null = null;
|
||||
|
||||
afterEach(() => {
|
||||
container?.remove();
|
||||
container = null;
|
||||
});
|
||||
|
||||
const entry = (id: string, riskLevel: string) =>
|
||||
({ id, toolName: id, title: id, riskLevel, status: "active" }) as unknown as ToolCatalogEntry;
|
||||
|
||||
describe("Permissions group control", () => {
|
||||
it("sets every action in the group in one change", () => {
|
||||
const onSetPermission = vi.fn();
|
||||
const writes = [entry("send", "write"), entry("delete", "destructive"), entry("label", "write")];
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
flushSync(() =>
|
||||
root.render(
|
||||
<QueryClientProvider client={new QueryClient()}>
|
||||
<MemoryRouter>
|
||||
<ActionsSection
|
||||
connectionId="conn-1"
|
||||
appName="Gmail"
|
||||
readOnly={[entry("search", "read")]}
|
||||
canChange={writes}
|
||||
quarantined={[]}
|
||||
enabledIds={new Set(["search", "send", "delete", "label"])}
|
||||
askFirstIds={new Set(["delete"])}
|
||||
disabled={false}
|
||||
refreshPending={false}
|
||||
canConfigure
|
||||
onSetPermission={onSetPermission}
|
||||
onReviewQuarantined={vi.fn()}
|
||||
onRefreshActions={vi.fn()}
|
||||
/>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
),
|
||||
);
|
||||
|
||||
const select = container.querySelector<HTMLSelectElement>('select[aria-label="Set every action in Write (3)"]');
|
||||
expect(select).toBeTruthy();
|
||||
expect(select!.value).toBe("");
|
||||
flushSync(() => {
|
||||
select!.value = "ask";
|
||||
select!.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(onSetPermission).toHaveBeenCalledTimes(1);
|
||||
const [ids, next] = onSetPermission.mock.calls[0]!;
|
||||
expect([...ids].sort()).toEqual(["delete", "label", "send"]);
|
||||
expect(next).toBe("ask");
|
||||
});
|
||||
});
|
||||
@@ -1,84 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ToolConnectionStoredContent } from "@paperclipai/shared";
|
||||
|
||||
const api = vi.hoisted(() => ({
|
||||
getStoredContent: vi.fn(),
|
||||
getStoredContentDeletion: vi.fn(),
|
||||
deleteStoredContent: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/api/tools", () => ({ toolsApi: api }));
|
||||
vi.mock("@/context/ToastContext", () => ({ useToast: () => ({ pushToast: vi.fn() }) }));
|
||||
|
||||
import { StoredContentDeletionDialog, storedContentStatus, storedContentSummary } from "./StoredContentDeletion";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const counts = { toolCalls: 0, approvals: 0, auditEvents: 0, appViews: 0, runs: 0, runsInProgress: 0, itemsInProgress: 0 };
|
||||
const stored: ToolConnectionStoredContent = {
|
||||
stored: { toolCalls: 12, approvals: 2, appViews: 0, runs: 3, runsInProgress: 1 },
|
||||
deletion: null,
|
||||
};
|
||||
|
||||
let container: HTMLDivElement | null = null;
|
||||
afterEach(() => {
|
||||
container?.remove();
|
||||
container = null;
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
async function flush() {
|
||||
for (let i = 0; i < 10; i++) await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
|
||||
}
|
||||
|
||||
describe("stored content deletion", () => {
|
||||
it("describes how much will be deleted in plain words", () => {
|
||||
expect(storedContentSummary(stored, "Google Workspace")).toBe(
|
||||
"Paperclip will delete what it saved from 12 tool calls, 2 approval requests and the full transcripts of 3 runs that used Google Workspace or received its results.",
|
||||
);
|
||||
expect(storedContentSummary({ ...stored, stored: { toolCalls: 0, approvals: 0, appViews: 1, runs: 0, runsInProgress: 0 } }, "Docs"))
|
||||
.toBe("Paperclip will delete what it saved from 1 app view that used Docs.");
|
||||
expect(storedContentSummary({ ...stored, stored: { toolCalls: 0, approvals: 0, appViews: 0, runs: 0, runsInProgress: 0 } }, "Docs"))
|
||||
.toBe("Paperclip found no saved data from Docs's tool calls. You can still delete to check again.");
|
||||
expect(storedContentStatus({ ...stored, deletion: { id: "d", status: "pending", requestedAt: "", completedAt: null, retrying: true, counts } }))
|
||||
.toBe("Deleting was interrupted. Paperclip keeps trying until it finishes.");
|
||||
});
|
||||
|
||||
it("confirms with counts, warns about running work, and starts the deletion", async () => {
|
||||
api.getStoredContent.mockResolvedValue(stored);
|
||||
const pendingDeletion = { id: "d", status: "pending" as const, requestedAt: new Date().toISOString(), completedAt: null, retrying: false, counts };
|
||||
api.deleteStoredContent.mockResolvedValue({ deletion: pendingDeletion });
|
||||
api.getStoredContentDeletion.mockResolvedValue({ deletion: pendingDeletion });
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={client}>
|
||||
<StoredContentDeletionDialog connectionId="connection-1" appName="Google Workspace" onClose={() => undefined} />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await flush();
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Delete data read through Google Workspace?");
|
||||
expect(text).toContain("12 tool calls");
|
||||
expect(text).toContain("1 run is still working and will be skipped.");
|
||||
expect(text).toContain("This cannot be undone.");
|
||||
expect(text).not.toContain("connection-1");
|
||||
|
||||
const confirm = Array.from(document.body.querySelectorAll("button")).find((button) => button.textContent === "Delete data");
|
||||
await act(async () => { confirm!.click(); });
|
||||
await flush();
|
||||
expect(api.deleteStoredContent).toHaveBeenCalledWith("connection-1");
|
||||
expect(document.body.textContent).toContain("Deleting now. You can close this window.");
|
||||
expect(api.getStoredContent).toHaveBeenCalledTimes(1);
|
||||
await act(async () => { root.unmount(); });
|
||||
});
|
||||
});
|
||||
@@ -1,995 +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 { MemoryRouter, Route, Routes, useLocation } from "react-router-dom";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { GitHubChatSetup, gitHubAppManifestAction } from "./GitHubChatSetup";
|
||||
import { defaultGitHubReviewPolicy } from "@paperclipai/shared";
|
||||
import { ChatEndpointDetail } from "./ChatEndpointDetail";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { agentsApi } from "@/api/agents";
|
||||
import { chatEndpointsApi } from "@/api/chatEndpoints";
|
||||
import { githubChatApi } from "@/api/githubChat";
|
||||
import { projectsApi } from "@/api/projects";
|
||||
import { toolsApi } from "@/api/tools";
|
||||
import { copyTextToClipboard } from "@/lib/clipboard";
|
||||
import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils";
|
||||
|
||||
const fixture = vi.hoisted(() => ({
|
||||
agents: [] as any[],
|
||||
endpoint: null as any,
|
||||
setBreadcrumbs: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/lib/router", async () => import("react-router-dom"));
|
||||
vi.mock("@/context/CompanyContext", () => ({
|
||||
useCompany: () => ({
|
||||
selectedCompanyId: "company-1",
|
||||
selectedCompany: {
|
||||
id: "company-1",
|
||||
name: "Bot Company",
|
||||
issuePrefix: "BOT",
|
||||
},
|
||||
}),
|
||||
}));
|
||||
vi.mock("@/context/BreadcrumbContext", () => ({
|
||||
useBreadcrumbs: () => ({ setBreadcrumbs: fixture.setBreadcrumbs }),
|
||||
}));
|
||||
vi.mock("@/context/ToastContext", () => ({
|
||||
useToast: () => ({ pushToast: vi.fn() }),
|
||||
}));
|
||||
vi.mock("@/components/SetupWizard", () => ({
|
||||
SetupWizardNavigation: () => null,
|
||||
SetupWizardFooter: ({ children, onSaveExit }: any) => (
|
||||
<footer>
|
||||
<button type="button" onClick={onSaveExit}>Save & exit</button>
|
||||
{children}
|
||||
</footer>
|
||||
),
|
||||
}));
|
||||
vi.mock("@/components/AgentMultiSelect", () => ({
|
||||
AgentSelect: ({ agents, value, onChange }: any) => (
|
||||
<select
|
||||
aria-label="Agent"
|
||||
value={value}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
>
|
||||
<option value="">Choose an agent</option>
|
||||
{agents.map((agent: any) => (
|
||||
<option key={agent.id} value={agent.id}>
|
||||
{agent.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
),
|
||||
}));
|
||||
vi.mock("@/api/agents", () => ({
|
||||
agentsApi: { list: vi.fn(), get: vi.fn(), updatePermissions: vi.fn() },
|
||||
}));
|
||||
vi.mock("@/api/chatEndpoints", () => ({
|
||||
chatEndpointsApi: {
|
||||
list: vi.fn(),
|
||||
create: vi.fn(),
|
||||
get: vi.fn(),
|
||||
listResources: vi.fn(),
|
||||
setup: vi.fn(),
|
||||
generateSetupSecret: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock("@/api/projects", () => ({ projectsApi: { repositoryOptions: vi.fn() } }));
|
||||
vi.mock("@/api/githubChat", () => ({
|
||||
githubChatApi: {
|
||||
configuration: vi.fn(),
|
||||
advance: vi.fn(),
|
||||
repositories: vi.fn(),
|
||||
registration: vi.fn(),
|
||||
restartRegistration: vi.fn(),
|
||||
saveDraft: vi.fn(),
|
||||
startIdentity: vi.fn(),
|
||||
confirmIdentity: vi.fn(),
|
||||
identity: vi.fn(),
|
||||
connectApp: vi.fn(),
|
||||
personalConnections: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock("@/api/tools", () => ({
|
||||
toolsApi: { startCloudConnectorEnrollment: vi.fn() },
|
||||
}));
|
||||
vi.mock("@/lib/clipboard", () => ({ copyTextToClipboard: vi.fn() }));
|
||||
|
||||
function Location() {
|
||||
const location = useLocation();
|
||||
return (
|
||||
<output>
|
||||
{location.pathname}
|
||||
{location.search}
|
||||
</output>
|
||||
);
|
||||
}
|
||||
|
||||
describe("GitHub App wizard", () => {
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
let client: QueryClient;
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
fixture.agents = [
|
||||
{
|
||||
id: "reviewer",
|
||||
name: "Reviewer",
|
||||
status: "idle",
|
||||
role: "engineer",
|
||||
permissions: { canCreateAgents: true, canCreateSkills: false },
|
||||
access: { canAssignTasks: true },
|
||||
createdAt: "2026-01-01",
|
||||
},
|
||||
{
|
||||
id: "helper",
|
||||
name: "Setup helper",
|
||||
status: "idle",
|
||||
role: "ceo",
|
||||
permissions: {},
|
||||
createdAt: "2026-01-01",
|
||||
},
|
||||
{
|
||||
id: "low",
|
||||
name: "Low-trust helper",
|
||||
status: "idle",
|
||||
role: "engineer",
|
||||
permissions: { trustPreset: "low_trust_review" },
|
||||
createdAt: "2026-01-01",
|
||||
},
|
||||
];
|
||||
fixture.endpoint = {
|
||||
id: "draft-1",
|
||||
companyId: "company-1",
|
||||
provider: "github",
|
||||
assignedAgentId: "reviewer",
|
||||
assignedAgentName: "Reviewer",
|
||||
status: "draft",
|
||||
setup: { github: { stage: "setup" } },
|
||||
};
|
||||
vi.mocked(agentsApi.list).mockImplementation(async () => fixture.agents);
|
||||
vi.mocked(agentsApi.get).mockImplementation(async (id) =>
|
||||
fixture.agents.find((agent) => agent.id === id),
|
||||
);
|
||||
vi.mocked(agentsApi.updatePermissions).mockImplementation(
|
||||
async (id, permissions) => {
|
||||
fixture.agents = fixture.agents.map((agent) =>
|
||||
agent.id === id ? { ...agent, permissions } : agent,
|
||||
);
|
||||
return fixture.agents.find((agent) => agent.id === id);
|
||||
},
|
||||
);
|
||||
vi.mocked(chatEndpointsApi.get).mockImplementation(
|
||||
async () => fixture.endpoint,
|
||||
);
|
||||
vi.mocked(chatEndpointsApi.create).mockResolvedValue(fixture.endpoint);
|
||||
vi.mocked(chatEndpointsApi.list).mockResolvedValue([]);
|
||||
vi.mocked(projectsApi.repositoryOptions).mockResolvedValue({
|
||||
repositories: [], connectionCount: 0, failedConnectionCount: 0,
|
||||
});
|
||||
vi.mocked(chatEndpointsApi.listResources).mockResolvedValue([]);
|
||||
vi.mocked(githubChatApi.advance).mockResolvedValue({
|
||||
endpointId: "draft-1",
|
||||
state: "create",
|
||||
});
|
||||
vi.mocked(githubChatApi.configuration).mockResolvedValue({
|
||||
revision: 1,
|
||||
configuration: { version: 1, toolsEnabled: true, responsibleUserId: "board", memberAccess: "selected", people: [],
|
||||
defaults: defaultGitHubReviewPolicy(), repositories: {} },
|
||||
});
|
||||
vi.mocked(githubChatApi.repositories).mockResolvedValue({
|
||||
items: [], nextOffset: null, totalCount: 1, enabledCount: 1, availableCount: 1,
|
||||
});
|
||||
vi.mocked(githubChatApi.saveDraft).mockResolvedValue({ saved: true });
|
||||
vi.mocked(githubChatApi.personalConnections).mockResolvedValue([]);
|
||||
vi.mocked(copyTextToClipboard).mockResolvedValue();
|
||||
client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, gcTime: 60_000 } },
|
||||
});
|
||||
container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
afterEach(async () => {
|
||||
await act(async () => root.unmount());
|
||||
client.clear();
|
||||
container.remove();
|
||||
});
|
||||
async function settle() {
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
});
|
||||
}
|
||||
it("shows pending signed delivery as waiting, not failed setup", async () => {
|
||||
fixture.endpoint.botExternalId = "1234";
|
||||
vi.mocked(githubChatApi.advance).mockResolvedValue({
|
||||
endpointId: "draft-1",
|
||||
state: "verify",
|
||||
message: "Waiting for GitHub to verify webhook delivery…",
|
||||
verification: {
|
||||
ready: false,
|
||||
checks: [
|
||||
{
|
||||
key: "webhook",
|
||||
label: "Signed webhook delivery",
|
||||
ok: false,
|
||||
detail:
|
||||
"Keep this page open. Setup will continue automatically when GitHub’s signed ping arrives.",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
await render("resume=draft-1");
|
||||
expect(container.querySelector('[role="status"]')?.textContent).toContain(
|
||||
"Waiting for GitHub",
|
||||
);
|
||||
expect(container.querySelector('[role="alert"]')).toBeNull();
|
||||
expect(container.textContent).toContain("continue automatically");
|
||||
expect(githubChatApi.registration).not.toHaveBeenCalled();
|
||||
});
|
||||
it("replaces a stale ping wait as soon as signed delivery arrives", async () => {
|
||||
vi.mocked(githubChatApi.advance).mockResolvedValue({
|
||||
endpointId: "draft-1",
|
||||
state: "verify",
|
||||
message: "Waiting for GitHub to verify webhook delivery…",
|
||||
verification: {
|
||||
ready: false,
|
||||
checks: [{ key: "webhook", label: "Signed delivery", ok: false,
|
||||
detail: "Keep this page open until the signed ping arrives." }],
|
||||
},
|
||||
});
|
||||
await render("resume=draft-1");
|
||||
expect(container.textContent).toContain("Waiting for GitHub");
|
||||
// Endpoint polling observes the receipt while full access verification is
|
||||
// still in flight. The previous progress response must not mislead users.
|
||||
await act(async () => {
|
||||
client.setQueryData(["github-setup", "draft-1"], {
|
||||
...fixture.endpoint,
|
||||
setup: { ...fixture.endpoint.setup, webhookVerifiedAt: "2026-10-08T10:31:10Z" },
|
||||
});
|
||||
});
|
||||
await settle();
|
||||
expect(container.querySelector('[role="status"]')?.textContent).toContain(
|
||||
"GitHub delivery verified. Checking App and repository access",
|
||||
);
|
||||
expect(container.textContent).not.toContain("Waiting for GitHub");
|
||||
expect(container.textContent).not.toContain("until the signed ping arrives");
|
||||
expect(container.textContent).not.toContain("GitHub connected");
|
||||
expect(githubChatApi.registration).not.toHaveBeenCalled();
|
||||
});
|
||||
it("completes a fresh credential-entry handoff through App import", async () => {
|
||||
await render("resume=draft-1&stage=credentials");
|
||||
expect(container.querySelector("#github-app-id")).not.toBeNull();
|
||||
expect(container.querySelector("#github-webhook-secret")).not.toBeNull();
|
||||
expect(githubChatApi.advance).not.toHaveBeenCalled();
|
||||
expect(githubChatApi.registration).not.toHaveBeenCalled();
|
||||
const privateKey = "-----BEGIN PRIVATE KEY-----\nfixture\n-----END PRIVATE KEY-----";
|
||||
for (const [selector, value] of [["#github-app-id", "1234"], ["#github-webhook-secret", "human-webhook-secret"]]) {
|
||||
await act(async () => {
|
||||
const input = container.querySelector<HTMLInputElement>(selector)!;
|
||||
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
}
|
||||
const paste = new Event("paste", { bubbles: true, cancelable: true });
|
||||
Object.defineProperty(paste, "clipboardData", { value: { getData: () => privateKey } });
|
||||
await act(async () => container.querySelector("#github-private-key")!.dispatchEvent(paste));
|
||||
const connect = container.querySelector<HTMLButtonElement>('[aria-label="Connect existing App"]')!;
|
||||
expect(connect.disabled).toBe(false);
|
||||
await act(async () => connect.click());
|
||||
expect(githubChatApi.connectApp).toHaveBeenCalledWith("draft-1", { appId: "1234", privateKey, webhookSecret: "human-webhook-secret" });
|
||||
expect(chatEndpointsApi.setup).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(["webhookSecret", "clientSecret"])("saves a configured %s handoff without replacing the private key", async (field) => {
|
||||
fixture.endpoint.status = "active";
|
||||
fixture.endpoint.botExternalId = "1234";
|
||||
vi.mocked(chatEndpointsApi.setup).mockResolvedValue(fixture.endpoint);
|
||||
await render(`resume=draft-1&stage=credentials&reconnect=1&credentialFields=${field}&credentialMode=all`);
|
||||
const selector = field === "webhookSecret" ? "#github-webhook-secret" : "#github-client-secret";
|
||||
const input = container.querySelector<HTMLInputElement>(selector);
|
||||
expect(input).not.toBeNull();
|
||||
expect(container.querySelector("#github-private-key")).toBeNull();
|
||||
expect(chatEndpointsApi.setup).not.toHaveBeenCalled();
|
||||
const submit = container.querySelector<HTMLButtonElement>('[aria-label="Verify and reconnect"]')!;
|
||||
expect(submit.disabled).toBe(true);
|
||||
await act(async () => {
|
||||
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "human-replacement");
|
||||
input!.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
expect(submit.disabled).toBe(false);
|
||||
await act(async () => submit.click());
|
||||
expect(chatEndpointsApi.setup).toHaveBeenCalledWith("draft-1", { action: "reconnect", credentials: { [field]: "human-replacement" } });
|
||||
expect(githubChatApi.connectApp).not.toHaveBeenCalled();
|
||||
expect(chatEndpointsApi.generateSetupSecret).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(["all", "any"])("honors %s completion for combined credential entry", async (mode) => {
|
||||
fixture.endpoint.status = "active";
|
||||
fixture.endpoint.botExternalId = "1234";
|
||||
vi.mocked(chatEndpointsApi.setup).mockResolvedValue(fixture.endpoint);
|
||||
await render(`resume=draft-1&stage=credentials&reconnect=1&credentialFields=privateKey,webhookSecret&credentialMode=${mode}`);
|
||||
const input = container.querySelector<HTMLInputElement>("#github-webhook-secret")!;
|
||||
await act(async () => {
|
||||
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "human-webhook");
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
const submit = container.querySelector<HTMLButtonElement>('[aria-label="Verify and reconnect"]')!;
|
||||
expect(submit.disabled).toBe(mode === "all");
|
||||
const privateKey = "-----BEGIN PRIVATE KEY-----\nfixture\n-----END PRIVATE KEY-----";
|
||||
if (mode === "all") {
|
||||
const paste = new Event("paste", { bubbles: true, cancelable: true });
|
||||
Object.defineProperty(paste, "clipboardData", { value: { getData: () => privateKey } });
|
||||
await act(async () => container.querySelector("#github-private-key")!.dispatchEvent(paste));
|
||||
}
|
||||
expect(submit.disabled).toBe(false);
|
||||
await act(async () => submit.click());
|
||||
expect(chatEndpointsApi.setup).toHaveBeenCalledWith("draft-1", { action: "reconnect", credentials: {
|
||||
webhookSecret: "human-webhook", ...(mode === "all" ? { appId: "1234", privateKey } : {}),
|
||||
} });
|
||||
});
|
||||
it("keeps legacy credential-entry links usable with only a webhook replacement", async () => {
|
||||
fixture.endpoint.status = "active";
|
||||
fixture.endpoint.botExternalId = "1234";
|
||||
vi.mocked(chatEndpointsApi.setup).mockResolvedValue(fixture.endpoint);
|
||||
await render("resume=draft-1&stage=credentials&reconnect=1");
|
||||
const input = container.querySelector<HTMLInputElement>("#github-webhook-secret")!;
|
||||
await act(async () => {
|
||||
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "human-webhook");
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
await act(async () => container.querySelector<HTMLButtonElement>('[aria-label="Verify and reconnect"]')!.click());
|
||||
expect(chatEndpointsApi.setup).toHaveBeenCalledWith("draft-1", { action: "reconnect", credentials: { webhookSecret: "human-webhook" } });
|
||||
});
|
||||
it("keeps a saved rotation handoff open through generation and reconnect failures", async () => {
|
||||
fixture.endpoint.status = "active";
|
||||
fixture.endpoint.botExternalId = "1234";
|
||||
const secret = "a".repeat(64);
|
||||
vi.mocked(githubChatApi.advance).mockResolvedValue({ endpointId: "draft-1", state: "connected" } as any);
|
||||
vi.mocked(chatEndpointsApi.generateSetupSecret).mockRejectedValueOnce(new Error("Temporarily unavailable")).mockResolvedValue({ webhookSecret: secret });
|
||||
vi.mocked(chatEndpointsApi.setup).mockRejectedValueOnce(new Error("Waiting for the new signed webhook")).mockResolvedValue(fixture.endpoint);
|
||||
await render("resume=draft-1&stage=credentials&reconnect=1&rotateSecret=1");
|
||||
const reconnect = () => [...container.querySelectorAll("button")].find(button => button.getAttribute("aria-label") === "Reconnect saved App")!;
|
||||
const generate = () => [...container.querySelectorAll("button")].find(button => button.textContent === "Generate webhook secret")!;
|
||||
expect(reconnect().disabled).toBe(true);
|
||||
expect(chatEndpointsApi.generateSetupSecret).not.toHaveBeenCalled();
|
||||
expect(githubChatApi.advance).not.toHaveBeenCalled();
|
||||
await act(async () => generate().click());
|
||||
expect(container.querySelector('[role="alert"]')?.textContent).toContain("Temporarily unavailable");
|
||||
expect(reconnect().disabled).toBe(true);
|
||||
await act(async () => generate().click());
|
||||
expect(chatEndpointsApi.generateSetupSecret).toHaveBeenLastCalledWith("draft-1");
|
||||
expect((container.querySelector("#github-rotation-secret") as HTMLInputElement).value).toBe(secret);
|
||||
expect((container.querySelector("#github-rotation-secret") as HTMLInputElement).type).toBe("password");
|
||||
await act(async () => (container.querySelector('[aria-label="Copy webhook secret"]') as HTMLButtonElement).click());
|
||||
expect(copyTextToClipboard).toHaveBeenLastCalledWith(secret);
|
||||
await act(async () => reconnect().click());
|
||||
expect(container.querySelector('[role="alert"]')?.textContent).toContain("Waiting for the new signed webhook");
|
||||
expect(reconnect().disabled).toBe(false);
|
||||
await act(async () => reconnect().click());
|
||||
expect(chatEndpointsApi.setup).toHaveBeenLastCalledWith("draft-1", { action: "reconnect" });
|
||||
expect(githubChatApi.connectApp).not.toHaveBeenCalled();
|
||||
expect(chatEndpointsApi.create).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(["unchanged", "changed", "unavailable"])("reconciles a failed replacement without using an uncertain secret (%s)", async (outcome) => {
|
||||
const previous = "11111111-1111-4111-8111-111111111111";
|
||||
const generated = "22222222-2222-4222-8222-222222222222";
|
||||
const replacement = "33333333-3333-4333-8333-333333333333";
|
||||
const secret = "b".repeat(64);
|
||||
fixture.endpoint.status = "active";
|
||||
fixture.endpoint.botExternalId = "1234";
|
||||
fixture.endpoint.setup.credentialRotationId = previous;
|
||||
vi.mocked(chatEndpointsApi.get).mockReset().mockImplementation(async () => fixture.endpoint);
|
||||
vi.mocked(chatEndpointsApi.generateSetupSecret).mockReset().mockResolvedValueOnce({ webhookSecret: secret, credentialRotationId: generated }).mockRejectedValueOnce(new Error("Replacement request failed"));
|
||||
await render(`resume=draft-1&stage=credentials&reconnect=1&rotateSecret=1&afterRotationId=${previous}`);
|
||||
const button = (label: string) => [...container.querySelectorAll("button")].find(item => item.textContent === label)!;
|
||||
const reconnect = () => [...container.querySelectorAll("button")].find(item => item.getAttribute("aria-label") === "Reconnect saved App")!;
|
||||
await act(async () => button("Generate webhook secret").click());
|
||||
const before = vi.mocked(chatEndpointsApi.get).mock.calls.length;
|
||||
if (outcome === "unavailable") vi.mocked(chatEndpointsApi.get).mockRejectedValueOnce(new Error("Status unavailable"));
|
||||
else vi.mocked(chatEndpointsApi.get).mockResolvedValueOnce({ ...fixture.endpoint, setup: { ...fixture.endpoint.setup, credentialRotationId: outcome === "unchanged" ? generated : replacement } });
|
||||
await act(async () => button("Generate another secret").click());
|
||||
expect(chatEndpointsApi.get).toHaveBeenCalledTimes(before + 1);
|
||||
if (outcome === "unchanged") {
|
||||
expect((container.querySelector("#github-rotation-secret") as HTMLInputElement).value).toBe(secret);
|
||||
expect(reconnect().disabled).toBe(false);
|
||||
await act(async () => (container.querySelector('[aria-label="Copy webhook secret"]') as HTMLButtonElement).click());
|
||||
expect(copyTextToClipboard).toHaveBeenLastCalledWith(secret);
|
||||
} else {
|
||||
expect(container.querySelector('[aria-label="Copy webhook secret"]')).toBeNull();
|
||||
expect(reconnect().disabled).toBe(true);
|
||||
if (outcome === "unavailable") {
|
||||
vi.mocked(chatEndpointsApi.get).mockResolvedValueOnce({ ...fixture.endpoint, setup: { ...fixture.endpoint.setup, credentialRotationId: generated } });
|
||||
await act(async () => button("Check saved secret status").click());
|
||||
expect((container.querySelector("#github-rotation-secret") as HTMLInputElement).value).toBe(secret);
|
||||
expect(reconnect().disabled).toBe(false);
|
||||
}
|
||||
}
|
||||
});
|
||||
it.each([
|
||||
{ generation: "22222222-2222-4222-8222-222222222222", verified: true, canResume: true },
|
||||
{ generation: "22222222-2222-4222-8222-222222222222", verified: false, canResume: true },
|
||||
{ generation: "11111111-1111-4111-8111-111111111111", verified: true, canResume: false },
|
||||
])("resumes only the saved rotation generation without requiring its secret again ($verified, $canResume)", async ({ generation, verified, canResume }) => {
|
||||
fixture.endpoint.status = "attention";
|
||||
fixture.endpoint.botExternalId = "1234";
|
||||
fixture.endpoint.setup.credentialRotationId = generation;
|
||||
fixture.endpoint.setup.webhookVerifiedAt = verified ? new Date().toISOString() : null;
|
||||
vi.mocked(chatEndpointsApi.setup).mockResolvedValue(fixture.endpoint);
|
||||
await render("resume=draft-1&stage=credentials&reconnect=1&rotateSecret=1&afterRotationId=11111111-1111-4111-8111-111111111111");
|
||||
const reconnect = [...container.querySelectorAll("button")].find(button => button.getAttribute("aria-label") === "Reconnect saved App")!;
|
||||
expect(reconnect.disabled).toBe(!canResume);
|
||||
expect(container.querySelector("#github-rotation-secret")).toBeNull();
|
||||
expect(chatEndpointsApi.generateSetupSecret).not.toHaveBeenCalled();
|
||||
if (canResume) {
|
||||
await act(async () => reconnect.click());
|
||||
expect(chatEndpointsApi.setup).toHaveBeenCalledWith("draft-1", { action: "reconnect" });
|
||||
}
|
||||
});
|
||||
it("reconnects the same App using vaulted credentials without requiring another paste", async () => {
|
||||
fixture.endpoint.status = "attention";
|
||||
fixture.endpoint.botExternalId = "1234";
|
||||
vi.mocked(chatEndpointsApi.setup).mockResolvedValue(fixture.endpoint);
|
||||
await render("resume=draft-1&reconnect=1");
|
||||
const button = [...container.querySelectorAll("button")].find(
|
||||
(button) => button.getAttribute("aria-label") === "Reconnect saved App",
|
||||
)!;
|
||||
expect(button.disabled).toBe(false);
|
||||
expect(container.querySelector("#github-private-key")).toBeNull();
|
||||
expect(container.querySelector("#github-webhook-secret")).toBeNull();
|
||||
await act(async () => {
|
||||
button.click();
|
||||
});
|
||||
expect(chatEndpointsApi.setup).toHaveBeenCalledWith("draft-1", {
|
||||
action: "reconnect",
|
||||
});
|
||||
expect(githubChatApi.connectApp).not.toHaveBeenCalled();
|
||||
});
|
||||
it("keeps a failed saved-App repair retryable and explains the credential fallback", async () => {
|
||||
fixture.endpoint.status = "attention";
|
||||
fixture.endpoint.botExternalId = "1234";
|
||||
vi.mocked(chatEndpointsApi.setup).mockRejectedValue(new Error("GitHub could not verify the saved private key"));
|
||||
await render("resume=draft-1&reconnect=1");
|
||||
const button = [...container.querySelectorAll("button")].find(button => button.getAttribute("aria-label") === "Reconnect saved App")!;
|
||||
await act(async () => button.click());
|
||||
expect(container.querySelector('[role="alert"]')?.textContent).toContain("Could not reconnect the saved App");
|
||||
expect(button.disabled).toBe(false);
|
||||
expect(container.querySelector("#github-private-key")).toBeNull();
|
||||
const replace = [...container.querySelectorAll("button")].find(button => button.textContent === "Replace App credentials…")!;
|
||||
await act(async () => replace.click());
|
||||
expect((container.querySelector("#github-app-id") as HTMLInputElement).value).toBe("1234");
|
||||
expect(container.textContent).toContain("Credentials → Key pairs → New key");
|
||||
expect((container.querySelector("#github-private-key") as HTMLInputElement).type).toBe("password");
|
||||
expect([...container.querySelectorAll("button")].find(button => button.getAttribute("aria-label") === "Verify and reconnect")?.disabled).toBe(true);
|
||||
expect(githubChatApi.advance).not.toHaveBeenCalled();
|
||||
});
|
||||
it("does not reuse an old connected result when fresh verification fails", async () => {
|
||||
fixture.endpoint.status = "attention";
|
||||
fixture.endpoint.botExternalId = "1234";
|
||||
client.setQueryData(["github-wizard", "draft-1"], { endpointId: "draft-1", state: "connected" });
|
||||
vi.mocked(chatEndpointsApi.setup).mockResolvedValue(fixture.endpoint);
|
||||
vi.mocked(githubChatApi.advance).mockRejectedValue(new Error("Delivery verification is unavailable"));
|
||||
await render("resume=draft-1&reconnect=1");
|
||||
await act(async () => [...container.querySelectorAll("button")].find(button => button.getAttribute("aria-label") === "Reconnect saved App")!.click());
|
||||
expect(container.querySelector("output")?.textContent).toContain("/BOT/apps/chat/connect");
|
||||
expect(container.textContent).toContain("Delivery verification is unavailable");
|
||||
expect([...container.querySelectorAll("button")].find(button => button.getAttribute("aria-label") === "Reconnect saved App")?.disabled).toBe(false);
|
||||
});
|
||||
it.each(["paste", "upload"])("preserves a multiline PEM from %s when replacing credentials", async (source) => {
|
||||
fixture.endpoint.status = "attention";
|
||||
fixture.endpoint.botExternalId = "1234";
|
||||
vi.mocked(chatEndpointsApi.setup).mockResolvedValue(fixture.endpoint);
|
||||
await render("resume=draft-1&reconnect=1");
|
||||
await act(async () => [...container.querySelectorAll("button")].find(button => button.textContent === "Replace App credentials…")!.click());
|
||||
const key = "-----BEGIN RSA PRIVATE KEY-----\nfixture-only\n-----END RSA PRIVATE KEY-----";
|
||||
if (source === "paste") {
|
||||
const paste = new Event("paste", { bubbles: true, cancelable: true });
|
||||
Object.defineProperty(paste, "clipboardData", { value: { getData: () => key } });
|
||||
await act(async () => container.querySelector("#github-private-key")!.dispatchEvent(paste));
|
||||
} else {
|
||||
const upload = container.querySelector('input[type="file"]')!;
|
||||
Object.defineProperty(upload, "files", { value: [{ text: async () => key }] });
|
||||
await act(async () => upload.dispatchEvent(new Event("change", { bubbles: true })));
|
||||
}
|
||||
expect((container.querySelector("#github-private-key") as HTMLInputElement).value).toBe("");
|
||||
expect(container.querySelector('[role="status"]')?.textContent).toContain("Private key loaded");
|
||||
await act(async () => [...container.querySelectorAll("button")].find(button => button.getAttribute("aria-label") === "Verify and reconnect")!.click());
|
||||
expect(chatEndpointsApi.setup).toHaveBeenCalledWith("draft-1", { action: "reconnect", credentials: { appId: "1234", privateKey: key } });
|
||||
});
|
||||
it("treats typing after loading a PEM as a new key instead of editing a flattened PEM", async () => {
|
||||
fixture.endpoint.status = "attention";
|
||||
fixture.endpoint.botExternalId = "1234";
|
||||
await render("resume=draft-1&reconnect=1");
|
||||
await act(async () => [...container.querySelectorAll("button")].find(button => button.textContent === "Replace App credentials…")!.click());
|
||||
const input = container.querySelector("#github-private-key") as HTMLInputElement;
|
||||
const paste = new Event("paste", { bubbles: true, cancelable: true });
|
||||
Object.defineProperty(paste, "clipboardData", { value: { getData: () => "-----BEGIN RSA PRIVATE KEY-----\nfixture-only\n-----END RSA PRIVATE KEY-----" } });
|
||||
await act(async () => input.dispatchEvent(paste));
|
||||
expect(input.value).toBe("");
|
||||
await act(async () => {
|
||||
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "replacement");
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
expect(input.value).toBe("replacement");
|
||||
expect(container.textContent).not.toContain("Private key loaded");
|
||||
expect([...container.querySelectorAll("button")].find(button => button.getAttribute("aria-label") === "Verify and reconnect")?.disabled).toBe(true);
|
||||
expect(chatEndpointsApi.setup).not.toHaveBeenCalled();
|
||||
});
|
||||
async function render(query = "agentId=reviewer") {
|
||||
await act(async () =>
|
||||
root.render(
|
||||
<QueryClientProvider client={client}>
|
||||
<MemoryRouter
|
||||
initialEntries={[`/BOT/apps/chat/connect?provider=github&${query}`]}
|
||||
>
|
||||
<TooltipProvider>
|
||||
<Routes>
|
||||
<Route path="/BOT/apps/chat/connect" element={<GitHubChatSetup />} />
|
||||
<Route path="/apps/chat/:endpointId/:tab" element={<ChatEndpointDetail />} />
|
||||
<Route path="/apps" element={<div>Connectors</div>} />
|
||||
</Routes>
|
||||
<Location />
|
||||
</TooltipProvider>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
),
|
||||
);
|
||||
await settle();
|
||||
// Completion mounts Settings and its own queries after the wizard redirect.
|
||||
await settle();
|
||||
await settle();
|
||||
}
|
||||
async function click(label: string) {
|
||||
const button = Array.from(document.querySelectorAll("button")).find(
|
||||
(button) =>
|
||||
button.textContent === label ||
|
||||
button.getAttribute("aria-label") === label,
|
||||
);
|
||||
expect(button, label).toBeTruthy();
|
||||
await act(async () => button!.click());
|
||||
await settle();
|
||||
}
|
||||
it("binds Cloud enrollment return to the same draft without a duplicated company prefix", async () => {
|
||||
vi.mocked(githubChatApi.advance).mockResolvedValue({ endpointId: "draft-1", state: "enrollment" });
|
||||
vi.mocked(toolsApi.startCloudConnectorEnrollment).mockResolvedValue({ configured: false, status: "pending", brokerBaseUrl: "https://gateway.example", instanceId: "instance-1", environment: "staging", origins: [] });
|
||||
const prior = `${window.location.pathname}${window.location.search}`;
|
||||
window.history.replaceState(null, "", "/BOT/apps/chat/connect?provider=github&purpose=chat&resume=draft-1");
|
||||
try {
|
||||
await render("purpose=chat&resume=draft-1");
|
||||
await click("Connect Paperclip Cloud");
|
||||
expect(toolsApi.startCloudConnectorEnrollment).toHaveBeenCalledWith("company-1", undefined, "/apps/chat/connect?provider=github&purpose=chat&resume=draft-1");
|
||||
} finally {
|
||||
window.history.replaceState(null, "", prior);
|
||||
}
|
||||
});
|
||||
it("starts with agent selection and saves the low-trust repair before removing its warning", async () => {
|
||||
await render();
|
||||
expect(container.querySelector("h1")?.textContent).toBe("Choose agent");
|
||||
expect(container.textContent).not.toContain("permanent");
|
||||
expect(container.textContent).not.toContain("Copy setup prompt");
|
||||
await click("Change Reviewer to a low trust agent");
|
||||
expect(agentsApi.updatePermissions).toHaveBeenCalledWith(
|
||||
"reviewer",
|
||||
expect.objectContaining({
|
||||
trustPreset: "low_trust_review",
|
||||
canCreateAgents: false,
|
||||
canCreateSkills: false,
|
||||
canAssignTasks: true,
|
||||
}),
|
||||
"company-1",
|
||||
);
|
||||
expect(container.querySelector('[role="alert"]')).toBeNull();
|
||||
await click("Continue");
|
||||
expect(chatEndpointsApi.create).toHaveBeenCalledWith("company-1", {
|
||||
provider: "github",
|
||||
assignedAgentId: "reviewer",
|
||||
});
|
||||
expect(container.querySelector("h1")?.textContent).toBe("Connect GitHub");
|
||||
expect(container.querySelector("output:not([for])")?.textContent).toContain(
|
||||
"resume=draft-1",
|
||||
);
|
||||
});
|
||||
it("does not offer a new connection while a saved draft cannot be loaded", async () => {
|
||||
vi.mocked(chatEndpointsApi.get).mockRejectedValue(new Error("Not found"));
|
||||
await render("resume=missing-draft&agentId=reviewer");
|
||||
expect(container.textContent).toContain("Could not load this connection");
|
||||
expect(container.textContent).not.toContain("Choose agent");
|
||||
expect(chatEndpointsApi.create).not.toHaveBeenCalled();
|
||||
});
|
||||
it("keeps the warning and shows the failure when changing trust fails", async () => {
|
||||
vi.mocked(agentsApi.updatePermissions).mockRejectedValueOnce(
|
||||
new Error("Permission denied"),
|
||||
);
|
||||
await render();
|
||||
await click("Change Reviewer to a low trust agent");
|
||||
expect(container.textContent).toContain("Permission denied");
|
||||
expect(container.textContent).toContain(
|
||||
"Reviewer is not configured for low-trust review",
|
||||
);
|
||||
});
|
||||
it("resumes the assigned draft with only account and App name choices", async () => {
|
||||
await render("resume=draft-1");
|
||||
expect(container.querySelector("h1")?.textContent).toBe("Connect GitHub");
|
||||
expect(container.textContent).toContain("My account");
|
||||
expect(container.textContent).toContain("Another organization");
|
||||
expect(container.textContent).not.toContain("GitHub will ask you");
|
||||
expect(container.textContent).not.toContain("Creates your own GitHub App");
|
||||
expect(container.textContent).not.toContain("Assign setup task");
|
||||
expect(container.textContent).not.toContain("Copy setup prompt");
|
||||
expect(container.textContent).not.toContain("Choose setup method");
|
||||
expect(
|
||||
container.querySelector("input#github-app-name")?.getAttribute("value"),
|
||||
).toBe("Reviewer");
|
||||
expect(chatEndpointsApi.create).not.toHaveBeenCalled();
|
||||
});
|
||||
it("offers known organizations from repositories and connected bots, without personal owners or duplicates", async () => {
|
||||
vi.mocked(projectsApi.repositoryOptions).mockResolvedValue({
|
||||
repositories: [
|
||||
{ id: "1", fullName: "acme/api", ownerType: "organization", url: "https://github.com/acme/api", connections: ["GitHub"] },
|
||||
{ id: "2", fullName: "ACME/web", ownerType: "organization", url: "https://github.com/ACME/web", connections: ["GitHub"] },
|
||||
{ id: "3", fullName: "octocat/site", ownerType: "personal", url: "https://github.com/octocat/site", connections: ["GitHub"] },
|
||||
{ id: "4", fullName: "unknown/legacy", url: "https://github.com/unknown/legacy", connections: ["GitHub"] },
|
||||
], connectionCount: 1, failedConnectionCount: 0,
|
||||
});
|
||||
vi.mocked(chatEndpointsApi.list).mockResolvedValue([
|
||||
{ ...fixture.endpoint, id: "connected", status: "active", setup: { github: { ownerType: "organization", ownerLogin: "paperclipai" } } },
|
||||
{ ...fixture.endpoint, id: "unconnected", setup: { github: { ownerType: "organization", ownerLogin: "unfinished" } } },
|
||||
]);
|
||||
await render("resume=draft-1");
|
||||
const select = container.querySelector("#github-owner-type") as HTMLSelectElement;
|
||||
expect([...select.options].map(option => option.textContent)).toEqual([
|
||||
"My account", "ACME", "paperclipai", "Another organization",
|
||||
]);
|
||||
await act(async () => {
|
||||
select.value = "organization:paperclipai";
|
||||
select.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
});
|
||||
expect(container.querySelector("#github-owner-login")).toBeNull();
|
||||
await click("Continue to GitHub");
|
||||
expect(githubChatApi.registration).toHaveBeenCalledWith("draft-1", {
|
||||
name: "Reviewer", ownerType: "organization", ownerLogin: "paperclipai",
|
||||
});
|
||||
});
|
||||
it("keeps Another organization editable even when the typed name is already known", async () => {
|
||||
vi.mocked(chatEndpointsApi.list).mockResolvedValue([
|
||||
{ ...fixture.endpoint, status: "active", setup: { github: { ownerType: "organization", ownerLogin: "acme" } } },
|
||||
]);
|
||||
await render("resume=draft-1");
|
||||
const select = container.querySelector("#github-owner-type") as HTMLSelectElement;
|
||||
await act(async () => {
|
||||
select.value = "organization:acme";
|
||||
select.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
});
|
||||
await act(async () => {
|
||||
select.value = "organization";
|
||||
select.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
});
|
||||
const input = container.querySelector("#github-owner-login") as HTMLInputElement;
|
||||
expect(input.value).toBe("");
|
||||
await act(async () => {
|
||||
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "acme");
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
expect(container.querySelector("#github-owner-login")).toBe(input);
|
||||
await click("Save & exit");
|
||||
expect(githubChatApi.saveDraft).toHaveBeenCalledWith("draft-1", {
|
||||
name: "Reviewer", ownerType: "organization", ownerLogin: "acme",
|
||||
});
|
||||
});
|
||||
it("preserves the saved organization when known accounts arrive and allows manual setup after lookup failure", async () => {
|
||||
fixture.endpoint.setup.github = { ownerType: "organization", ownerLogin: "saved-org", appName: "Saved App" };
|
||||
vi.mocked(projectsApi.repositoryOptions).mockRejectedValue(new Error("Unavailable"));
|
||||
vi.mocked(chatEndpointsApi.list).mockResolvedValue([
|
||||
{ ...fixture.endpoint, id: "connected", status: "active" },
|
||||
]);
|
||||
await render("resume=draft-1");
|
||||
expect((container.querySelector("#github-owner-type") as HTMLSelectElement).value).toBe("organization:saved-org");
|
||||
expect(container.textContent).toContain("Could not load some connected GitHub accounts");
|
||||
expect(replayLeaks("saved-org", container.querySelector("#github-owner-type")!)).toEqual({ rendered: true, recorded: false });
|
||||
await click("Save & exit");
|
||||
expect(githubChatApi.saveDraft).toHaveBeenCalledWith("draft-1", {
|
||||
name: "Saved App", ownerType: "organization", ownerLogin: "saved-org",
|
||||
});
|
||||
});
|
||||
it("requires no-App-created confirmation before restarting an expired handoff", async () => {
|
||||
vi.mocked(githubChatApi.advance).mockResolvedValue({ endpointId: "draft-1", state: "recovery", restartableRegistrationId: "expired-1", message: "Handoff expired" });
|
||||
vi.mocked(githubChatApi.restartRegistration).mockResolvedValue({ endpointId: "draft-1", state: "create" });
|
||||
await render("resume=draft-1");
|
||||
const button = [...container.querySelectorAll("button")].find(b => b.textContent === "Continue to GitHub")!;
|
||||
expect(button.disabled).toBe(true);
|
||||
expect(githubChatApi.restartRegistration).not.toHaveBeenCalled();
|
||||
await act(async () => (container.querySelector("#github-app-not-created") as HTMLElement).click());
|
||||
expect(button.disabled).toBe(false);
|
||||
await click("Continue to GitHub");
|
||||
expect(githubChatApi.restartRegistration).toHaveBeenCalledWith("draft-1", "expired-1");
|
||||
expect(chatEndpointsApi.create).not.toHaveBeenCalled();
|
||||
expect(githubChatApi.registration).not.toHaveBeenCalled();
|
||||
});
|
||||
it("does not offer registration restart for an uncertain exchange", async () => {
|
||||
vi.mocked(githubChatApi.advance).mockResolvedValue({ endpointId: "draft-1", state: "recovery", message: "Recover existing App" });
|
||||
await render("resume=draft-1");
|
||||
expect(container.querySelector("#github-app-not-created")).toBeNull();
|
||||
expect(container.textContent).not.toContain("Continue to GitHub");
|
||||
expect(container.textContent).toContain("Use existing App credentials");
|
||||
});
|
||||
it("saves ownership and the suggested name when exiting", async () => {
|
||||
await render("resume=draft-1");
|
||||
const owner = container.querySelector(
|
||||
"#github-owner-type",
|
||||
) as HTMLSelectElement;
|
||||
await act(async () => {
|
||||
owner.value = "organization";
|
||||
owner.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
});
|
||||
const input = container.querySelector(
|
||||
"#github-owner-login",
|
||||
) as HTMLInputElement;
|
||||
await act(async () => {
|
||||
Object.getOwnPropertyDescriptor(
|
||||
HTMLInputElement.prototype,
|
||||
"value",
|
||||
)!.set!.call(input, "acme");
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
await click("Save & exit");
|
||||
expect(githubChatApi.saveDraft).toHaveBeenCalledWith("draft-1", {
|
||||
name: "Reviewer",
|
||||
ownerType: "organization",
|
||||
ownerLogin: "acme",
|
||||
});
|
||||
expect(container.querySelector("output:not([for])")?.textContent).toBe("/apps");
|
||||
});
|
||||
it("replaces stale cached form defaults when the saved draft refreshes", async () => {
|
||||
await render("resume=draft-1");
|
||||
expect(
|
||||
(container.querySelector("#github-app-name") as HTMLInputElement).value,
|
||||
).toBe("Reviewer");
|
||||
fixture.endpoint = {
|
||||
...fixture.endpoint,
|
||||
setup: {
|
||||
github: {
|
||||
ownerType: "organization",
|
||||
ownerLogin: "acme",
|
||||
appName: "Saved App",
|
||||
},
|
||||
},
|
||||
};
|
||||
await act(async () =>
|
||||
client.invalidateQueries({ queryKey: ["github-setup", "draft-1"] }),
|
||||
);
|
||||
await settle();
|
||||
expect(
|
||||
(container.querySelector("#github-owner-type") as HTMLSelectElement)
|
||||
.value,
|
||||
).toBe("organization");
|
||||
expect(
|
||||
(container.querySelector("#github-owner-login") as HTMLInputElement)
|
||||
.value,
|
||||
).toBe("acme");
|
||||
expect(
|
||||
(container.querySelector("#github-app-name") as HTMLInputElement).value,
|
||||
).toBe("Saved App");
|
||||
});
|
||||
it("submits the manifest directly, preserving the bound registration on retry", async () => {
|
||||
const registration = {
|
||||
registrationUrl:
|
||||
"https://github.com/organizations/acme/settings/apps/new?state=bound",
|
||||
manifest: { name: "Reviewer", public: false },
|
||||
expiresAt: "2026-10-06T20:00:00Z",
|
||||
};
|
||||
vi.mocked(githubChatApi.advance).mockResolvedValue({
|
||||
endpointId: "draft-1",
|
||||
state: "create",
|
||||
registration,
|
||||
});
|
||||
await render("resume=draft-1");
|
||||
const form = container.querySelector("form")!;
|
||||
expect(form.method).toBe("post");
|
||||
expect(form.action).toBe(registration.registrationUrl);
|
||||
expect((form.querySelector('[name="manifest"]') as HTMLInputElement).value)
|
||||
.toBe(JSON.stringify(registration.manifest));
|
||||
expect(form.querySelector('button[type="submit"]')?.textContent).toBe("Continue to GitHub");
|
||||
expect((form.querySelector('button[type="button"]') as HTMLButtonElement).textContent).toBe("Save & exit");
|
||||
expect(githubChatApi.registration).not.toHaveBeenCalled();
|
||||
expect((container.querySelector("#github-owner-type") as HTMLSelectElement).disabled).toBe(true);
|
||||
expect(() => gitHubAppManifestAction({ ...registration, registrationUrl: "https://evil.example/apps/new" }))
|
||||
.toThrow("invalid registration");
|
||||
});
|
||||
it("submits the mounted native form after preparing a fresh registration", async () => {
|
||||
const registration = {
|
||||
registrationUrl: "https://github.com/settings/apps/new?state=bound",
|
||||
manifest: { name: "Reviewer", public: false }, expiresAt: "2026-10-07T20:00:00Z",
|
||||
};
|
||||
vi.mocked(githubChatApi.registration).mockResolvedValue({ endpointId: "draft-1", state: "create", registration });
|
||||
const requestSubmit = vi.spyOn(HTMLFormElement.prototype, "requestSubmit").mockImplementation(function (this: HTMLFormElement) {
|
||||
expect(this.isConnected).toBe(true);
|
||||
expect((this.querySelector('[name="manifest"]') as HTMLInputElement).value).toBe(JSON.stringify(registration.manifest));
|
||||
this.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
|
||||
});
|
||||
try {
|
||||
await render("resume=draft-1");
|
||||
await click("Continue to GitHub");
|
||||
await settle();
|
||||
expect(requestSubmit).toHaveBeenCalledTimes(1);
|
||||
expect(githubChatApi.registration).toHaveBeenCalledTimes(1);
|
||||
} finally { requestSubmit.mockRestore(); }
|
||||
});
|
||||
it("shows passive installation progress without a duplicate repository picker or refresh gate", async () => {
|
||||
vi.mocked(githubChatApi.advance).mockResolvedValue({
|
||||
endpointId: "draft-1",
|
||||
state: "install",
|
||||
installationUrl: "https://github.com/apps/reviewer/installations/new",
|
||||
});
|
||||
await render("resume=draft-1");
|
||||
expect(container.textContent).toContain("GitHub");
|
||||
expect(container.textContent).not.toContain("I’ve installed it");
|
||||
expect(container.textContent).not.toContain("Refresh repositories");
|
||||
expect(container.textContent).not.toContain("Prepare registration");
|
||||
expect(
|
||||
container.querySelector(
|
||||
'a[href="https://github.com/apps/reviewer/installations/new"]',
|
||||
),
|
||||
).toBeTruthy();
|
||||
});
|
||||
it("requires an explicit identity confirmation only for an unlinked account", async () => {
|
||||
vi.mocked(githubChatApi.advance).mockResolvedValue({
|
||||
endpointId: "draft-1",
|
||||
state: "identity",
|
||||
identity: { githubUserId: "42", login: "octocat", avatarUrl: null },
|
||||
});
|
||||
vi.mocked(githubChatApi.confirmIdentity).mockResolvedValue({
|
||||
endpointId: "draft-1",
|
||||
state: "connected",
|
||||
});
|
||||
await render("resume=draft-1");
|
||||
await click("Confirm my account");
|
||||
expect(githubChatApi.confirmIdentity).toHaveBeenCalledWith("draft-1", "42");
|
||||
expect(githubChatApi.startIdentity).not.toHaveBeenCalled();
|
||||
});
|
||||
it("lets a member add a personal connection without manager setup APIs", async () => {
|
||||
vi.mocked(githubChatApi.advance).mockRejectedValue(
|
||||
new Error("Manager permission required"),
|
||||
);
|
||||
await render("resume=draft-1&stage=identity");
|
||||
expect(
|
||||
container.querySelector('a[href="/apps/connect?source=github"]'),
|
||||
).toBeTruthy();
|
||||
expect(container.textContent).not.toContain("Manager permission required");
|
||||
expect(githubChatApi.advance).not.toHaveBeenCalled();
|
||||
expect(githubChatApi.startIdentity).not.toHaveBeenCalled();
|
||||
await click("Save & exit");
|
||||
expect(githubChatApi.saveDraft).not.toHaveBeenCalled();
|
||||
});
|
||||
it("links a member's verified personal account without advancing bot setup", async () => {
|
||||
vi.mocked(githubChatApi.personalConnections).mockResolvedValue([
|
||||
{
|
||||
connectionId: "personal-1",
|
||||
name: "My GitHub",
|
||||
login: "octocat",
|
||||
status: "active",
|
||||
enabled: true,
|
||||
},
|
||||
]);
|
||||
vi.mocked(githubChatApi.identity).mockResolvedValue({
|
||||
connectionId: "personal-1",
|
||||
githubUserId: "42",
|
||||
login: "octocat",
|
||||
avatarUrl: null,
|
||||
});
|
||||
await render("resume=draft-1&stage=identity");
|
||||
const account = container.querySelector(
|
||||
"#github-personal-account",
|
||||
) as HTMLSelectElement;
|
||||
await act(async () => {
|
||||
account.value = "personal-1";
|
||||
account.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
});
|
||||
await click("Check my account");
|
||||
expect(githubChatApi.identity).toHaveBeenLastCalledWith(
|
||||
"draft-1",
|
||||
"personal-1",
|
||||
undefined,
|
||||
);
|
||||
await click("Confirm my account");
|
||||
expect(githubChatApi.identity).toHaveBeenLastCalledWith(
|
||||
"draft-1",
|
||||
"personal-1",
|
||||
"42",
|
||||
);
|
||||
expect(container.textContent).toContain(
|
||||
"You can now mention this bot on GitHub",
|
||||
);
|
||||
expect(githubChatApi.advance).not.toHaveBeenCalled();
|
||||
expect(githubChatApi.startIdentity).not.toHaveBeenCalled();
|
||||
expect(githubChatApi.confirmIdentity).not.toHaveBeenCalled();
|
||||
});
|
||||
it("completes automatically while reporting runtime readiness separately", async () => {
|
||||
fixture.endpoint = {
|
||||
...fixture.endpoint,
|
||||
status: "active",
|
||||
setup: { step: "complete" },
|
||||
botLabel: "Actual GitHub Name",
|
||||
botUsername: "actual-agent[bot]",
|
||||
resources: [{ enabled: true, label: "acme/repo" }],
|
||||
};
|
||||
vi.mocked(githubChatApi.advance).mockResolvedValue({
|
||||
endpointId: "draft-1",
|
||||
state: "connected",
|
||||
runtimeChecks: [
|
||||
{
|
||||
key: "runtime",
|
||||
label: "Runtime",
|
||||
ok: false,
|
||||
detail: "Configure a runtime before the first review.",
|
||||
},
|
||||
],
|
||||
});
|
||||
await render("resume=draft-1");
|
||||
expect(document.querySelector('[role="dialog"] h2')?.textContent).toBe("GitHub connected");
|
||||
expect(document.body.textContent).toContain("Actual GitHub Name");
|
||||
expect(document.body.textContent).toContain("GitHub App name and logo");
|
||||
expect(document.body.textContent).toContain("1 repository enabled");
|
||||
expect(container.querySelector("output:not([for])")?.textContent).toBe("/apps/chat/draft-1/settings");
|
||||
expect(document.querySelector('[role="dialog"] details')?.hasAttribute("open")).toBe(false);
|
||||
expect(document.body.textContent).toContain("Before your first review");
|
||||
expect(document.body.textContent).toContain("Configure a runtime");
|
||||
expect(document.body.textContent).not.toContain("Finish");
|
||||
await click("Copy mention");
|
||||
expect(copyTextToClipboard).toHaveBeenCalledWith(
|
||||
"@actual-agent review this pull request",
|
||||
);
|
||||
});
|
||||
it.each(["Done", "Close", "Escape"])("dismisses with %s onto the same mounted Settings page", async (action) => {
|
||||
fixture.endpoint = { ...fixture.endpoint, status: "active", setup: { step: "complete" } };
|
||||
vi.mocked(githubChatApi.advance).mockResolvedValue({ endpointId: "draft-1", state: "connected" });
|
||||
await render("resume=draft-1");
|
||||
const settings = container.querySelector("textarea");
|
||||
expect(settings).not.toBeNull();
|
||||
expect(document.querySelector('[role="dialog"]')).not.toBeNull();
|
||||
if (action === "Escape") {
|
||||
await act(async () => {
|
||||
document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
|
||||
});
|
||||
await settle();
|
||||
} else await click(action);
|
||||
expect(document.querySelector('[role="dialog"]')).toBeNull();
|
||||
expect(container.querySelector("output:not([for])")?.textContent).toBe("/apps/chat/draft-1/settings");
|
||||
expect(container.querySelector("textarea")).toBe(settings);
|
||||
expect(container.querySelector("h1")?.textContent).toBe("Reviewer");
|
||||
expect(document.activeElement).toBe(container.querySelector("h1"));
|
||||
expect(githubChatApi.saveDraft).not.toHaveBeenCalled();
|
||||
expect(chatEndpointsApi.create).not.toHaveBeenCalled();
|
||||
});
|
||||
it("reports copy failure without undoing the completed connection", async () => {
|
||||
fixture.endpoint = { ...fixture.endpoint, status: "active", setup: { step: "complete" }, botUsername: "actual-agent[bot]" };
|
||||
vi.mocked(githubChatApi.advance).mockResolvedValue({ endpointId: "draft-1", state: "connected" });
|
||||
vi.mocked(copyTextToClipboard).mockRejectedValueOnce(new Error("Clipboard unavailable"));
|
||||
await render("resume=draft-1");
|
||||
await click("Copy mention");
|
||||
expect(document.body.textContent).toContain("Copy failed");
|
||||
expect(document.querySelector('[role="dialog"] h2')?.textContent).toBe("GitHub connected");
|
||||
expect(githubChatApi.registration).not.toHaveBeenCalled();
|
||||
});
|
||||
it("shows a useful next step when a connected bot has no enabled repositories", async () => {
|
||||
fixture.endpoint = { ...fixture.endpoint, status: "active", setup: { step: "complete" } };
|
||||
vi.mocked(githubChatApi.advance).mockResolvedValue({ endpointId: "draft-1", state: "connected" });
|
||||
vi.mocked(githubChatApi.repositories).mockResolvedValue({
|
||||
items: [], nextOffset: null, totalCount: 2, enabledCount: 0, availableCount: 2,
|
||||
});
|
||||
await render("resume=draft-1");
|
||||
expect(document.body.textContent).toContain("No repositories enabled");
|
||||
expect(document.body.textContent).toContain("Enable a repository in Access to try your bot");
|
||||
expect(document.querySelector('[role="dialog"] a[href="/apps/chat/draft-1/access"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it("does not flash App creation controls while checking a resumed connection", async () => {
|
||||
fixture.endpoint = { ...fixture.endpoint, status: "active", setup: { step: "complete" }, botUsername: "actual-agent[bot]" };
|
||||
vi.mocked(githubChatApi.advance).mockReturnValue(new Promise(() => {}));
|
||||
await render("resume=draft-1");
|
||||
expect(container.textContent).toContain("Checking your GitHub connection");
|
||||
expect(container.querySelector("#github-app-name")).toBeNull();
|
||||
expect(container.textContent).not.toContain("I already have an App");
|
||||
expect(container.textContent).not.toContain("GitHub connected");
|
||||
});
|
||||
|
||||
});
|
||||
@@ -1,178 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
import { StrictMode, act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { beforeEach, afterEach, expect, it, vi } from "vitest";
|
||||
import type { ChatEndpoint } from "@/api/chatEndpoints";
|
||||
import { ManagedSlackSetup } from "./ManagedSlackSetup";
|
||||
import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils";
|
||||
|
||||
const api = vi.hoisted(() => ({ slackSetupOptions: vi.fn(), provisionManagedSlack: vi.fn(), authorizeSlackManager: vi.fn(), get: vi.fn() }));
|
||||
vi.mock("@/api/chatEndpoints", () => ({ chatEndpointsApi: api }));
|
||||
// Stop at the navigation boundary without leaving jsdom.
|
||||
const navigation = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@/lib/oauthHandoff", () => ({ prepareOAuthNavigation: navigation, savePendingCloudHandoff: vi.fn() }));
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
let client: QueryClient;
|
||||
let endpoint: ChatEndpoint;
|
||||
const props = () => ({ endpoint, stage: "app" as const, disabled: false, autoStart: true, saveDetails: vi.fn().mockResolvedValue(undefined), onSaved: vi.fn(), onBusy: vi.fn(), onSaveExit: vi.fn(), onManual: vi.fn(), onContinue: vi.fn() });
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
container = document.createElement("div"); document.body.append(container); root = createRoot(container);
|
||||
client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
endpoint = { id: "endpoint", companyId: "company", assignedAgentName: "Maya", setup: { slackSetupMethod: "managed" } } as ChatEndpoint;
|
||||
api.slackSetupOptions.mockResolvedValue({ managedAvailable: true, workspaces: [{ grantId: "grant", workspaceName: "Paperclip" }] });
|
||||
api.provisionManagedSlack.mockResolvedValue({}); api.get.mockResolvedValue(endpoint);
|
||||
api.authorizeSlackManager.mockResolvedValue({ authorizationUrl: "https://slack.com/oauth" });
|
||||
navigation.mockImplementation(() => new Promise(() => {}));
|
||||
});
|
||||
afterEach(async () => { await act(async () => root.unmount()); client.clear(); container.remove(); vi.restoreAllMocks(); });
|
||||
async function render(overrides = {}) {
|
||||
await act(async () => { root.render(<StrictMode><QueryClientProvider client={client}><ManagedSlackSetup {...props()} {...overrides} /></QueryClientProvider></StrictMode>); });
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 30)); });
|
||||
}
|
||||
it("starts a single managed install after Continue even across rerenders", async () => {
|
||||
await render(); await render();
|
||||
expect(api.provisionManagedSlack).toHaveBeenCalledTimes(1);
|
||||
expect(api.provisionManagedSlack).toHaveBeenCalledWith("endpoint", expect.objectContaining({ grantId: "grant" }));
|
||||
expect(api.authorizeSlackManager).not.toHaveBeenCalled();
|
||||
});
|
||||
it("requests explicit reinstall when reconnecting a configured app", async () => {
|
||||
endpoint.setup!.slackRegistration = { status: "configured", appId: "app", managerGrantId: "grant" } as NonNullable<ChatEndpoint["setup"]>["slackRegistration"];
|
||||
await render({ autoStart: false, reconnect: true });
|
||||
const button = Array.from(container.querySelectorAll("button")).find(item => item.textContent === "Continue in Slack");
|
||||
expect(button).toBeDefined();
|
||||
await act(async () => button!.click());
|
||||
expect(api.provisionManagedSlack).toHaveBeenCalledWith("endpoint", expect.objectContaining({ grantId: "grant", reconnect: true, requestId: expect.any(String) }));
|
||||
});
|
||||
it("reuses the reconnect receipt after a lost response and failed recovery read", async () => {
|
||||
endpoint.setup!.slackRegistration = { status: "configured", appId: "app", managerGrantId: "grant" } as NonNullable<ChatEndpoint["setup"]>["slackRegistration"];
|
||||
api.provisionManagedSlack.mockRejectedValue(new Error("Response lost"));
|
||||
api.get.mockRejectedValue(new Error("Recovery read unavailable"));
|
||||
await render({ autoStart: false, reconnect: true });
|
||||
const button = () => Array.from(container.querySelectorAll("button")).find(item => item.textContent === "Continue in Slack")!;
|
||||
await act(async () => button().click());
|
||||
await act(async () => button().click());
|
||||
expect(api.provisionManagedSlack).toHaveBeenCalledTimes(2);
|
||||
expect(api.provisionManagedSlack.mock.calls[1]![1]).toEqual(api.provisionManagedSlack.mock.calls[0]![1]);
|
||||
});
|
||||
it("opens manager authorization directly when there is no saved workspace", async () => {
|
||||
api.slackSetupOptions.mockResolvedValue({ managedAvailable: true, workspaces: [] });
|
||||
await render();
|
||||
expect(api.authorizeSlackManager).toHaveBeenCalledTimes(1);
|
||||
expect(navigation).toHaveBeenCalledWith({ authorizationUrl: "https://slack.com/oauth" });
|
||||
expect(api.provisionManagedSlack).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([0, 1, 2])("offers workspace reconnection before an app exists with %i active workspaces", async (activeWorkspaces) => {
|
||||
endpoint.setup!.slackManagerError = "slack_manager_reauthorize";
|
||||
api.slackSetupOptions.mockResolvedValue({ managedAvailable: true, workspaces: Array.from({ length: activeWorkspaces }, (_, i) => ({ grantId: `grant-${i}`, workspaceName: `Workspace ${i}` })) });
|
||||
await render();
|
||||
expect(container.querySelector('[role="alert"]')?.textContent).toBe("Reconnect your Slack workspace to continue setting up this agent.");
|
||||
const reconnect = Array.from(container.querySelectorAll("button")).find(item => item.textContent === "Reconnect Slack workspace");
|
||||
expect(reconnect).toBeDefined();
|
||||
expect(reconnect!.disabled).toBe(false);
|
||||
expect(container.textContent).not.toContain("Connect another Slack workspace");
|
||||
expect(api.authorizeSlackManager).not.toHaveBeenCalled();
|
||||
await act(async () => reconnect!.click());
|
||||
expect(api.authorizeSlackManager).toHaveBeenCalledExactlyOnceWith("endpoint");
|
||||
expect(navigation).toHaveBeenCalledWith({ authorizationUrl: "https://slack.com/oauth" });
|
||||
expect(api.provisionManagedSlack).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([0, 1, 2])("offers workspace reconnection after an authorization request fails with %i active workspaces", async (activeWorkspaces) => {
|
||||
api.slackSetupOptions.mockResolvedValue({ managedAvailable: true, workspaces: Array.from({ length: activeWorkspaces }, (_, i) => ({ grantId: `grant-${i}`, workspaceName: `Workspace ${i}` })) });
|
||||
api.authorizeSlackManager.mockRejectedValueOnce(new Error("Reconnect your Slack workspace to continue setting up this agent."));
|
||||
await render({ autoStart: activeWorkspaces === 0 });
|
||||
if (activeWorkspaces) {
|
||||
const connectAnother = Array.from(container.querySelectorAll("button")).find(item => item.textContent === "Connect another Slack workspace");
|
||||
await act(async () => connectAnother!.click());
|
||||
}
|
||||
const reconnect = Array.from(container.querySelectorAll("button")).find(item => item.textContent === "Reconnect Slack workspace");
|
||||
expect(reconnect).toBeDefined();
|
||||
expect(reconnect!.disabled).toBe(false);
|
||||
expect(api.authorizeSlackManager).toHaveBeenCalledTimes(1);
|
||||
await act(async () => reconnect!.click());
|
||||
expect(api.authorizeSlackManager).toHaveBeenCalledTimes(2);
|
||||
expect(navigation).toHaveBeenCalledWith({ authorizationUrl: "https://slack.com/oauth" });
|
||||
expect(api.provisionManagedSlack).not.toHaveBeenCalled();
|
||||
});
|
||||
it("keeps one workspace reconnect action when a saved app needs reauthorization", async () => {
|
||||
endpoint.setup!.slackRegistration = { status: "failed", appId: "app", managerGrantId: "grant", errorCode: "slack_manager_reauthorize" } as NonNullable<ChatEndpoint["setup"]>["slackRegistration"];
|
||||
await render();
|
||||
const reconnect = Array.from(container.querySelectorAll("button")).filter(item => item.textContent === "Reconnect Slack workspace");
|
||||
expect(reconnect).toHaveLength(1);
|
||||
await act(async () => reconnect[0]!.click());
|
||||
expect(api.authorizeSlackManager).toHaveBeenCalledExactlyOnceWith("endpoint");
|
||||
expect(api.provisionManagedSlack).not.toHaveBeenCalled();
|
||||
});
|
||||
it("does not start while Choose agent is visible or after Save & exit", async () => {
|
||||
await render({ autoStart: false });
|
||||
expect(api.provisionManagedSlack).not.toHaveBeenCalled();
|
||||
expect(api.authorizeSlackManager).not.toHaveBeenCalled();
|
||||
});
|
||||
it("waits for an explicit workspace choice when there are several", async () => {
|
||||
api.slackSetupOptions.mockResolvedValue({ managedAvailable: true, workspaces: [{ grantId: "one", workspaceName: "One" }, { grantId: "two", workspaceName: "Two" }] });
|
||||
await render(); expect(api.provisionManagedSlack).not.toHaveBeenCalled();
|
||||
expect(container.textContent).toContain("Choose a Slack workspace");
|
||||
});
|
||||
it.each(["uncertain", "failed", "creating", "install", "credentials_saved"])("does not automatically retry a %s registration", async status => {
|
||||
endpoint.setup!.slackRegistration = { status } as NonNullable<ChatEndpoint["setup"]>["slackRegistration"];
|
||||
await render(); expect(api.provisionManagedSlack).not.toHaveBeenCalled(); expect(api.authorizeSlackManager).not.toHaveBeenCalled();
|
||||
});
|
||||
it("does not loop authorization after denial", async () => {
|
||||
endpoint.setup!.slackManagerError = "slack_install_declined";
|
||||
await render(); expect(api.authorizeSlackManager).not.toHaveBeenCalled(); expect(api.provisionManagedSlack).not.toHaveBeenCalled();
|
||||
});
|
||||
it("does not silently retry an ambiguous request after refresh of setup options", async () => {
|
||||
api.provisionManagedSlack.mockRejectedValue(new Error("Request failed"));
|
||||
await render(); await render();
|
||||
expect(api.provisionManagedSlack).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each(["popup", "fallback"])("continues after manager authorization returns through the %s", async (mode) => {
|
||||
const popup = { closed: false, opener: window, location: { href: "about:blank", assign: vi.fn() }, focus: vi.fn(), close: vi.fn() };
|
||||
popup.location.assign.mockImplementation((url: string) => { popup.location.href = url; });
|
||||
vi.spyOn(window, "open").mockReturnValue(mode === "popup" ? popup as unknown as Window : null);
|
||||
navigation.mockResolvedValue({ kind: "authorization", url: "https://slack.com/oauth" });
|
||||
api.slackSetupOptions.mockResolvedValue({ managedAvailable: true, workspaces: [] });
|
||||
const onSaved = vi.fn();
|
||||
await render({ onSaved });
|
||||
expect(api.authorizeSlackManager).toHaveBeenCalledTimes(1);
|
||||
|
||||
if (mode === "popup") {
|
||||
// Returning focus while Slack is still open must not interrupt sign-in.
|
||||
await act(async () => { window.dispatchEvent(new Event("focus")); });
|
||||
expect(api.get).not.toHaveBeenCalled();
|
||||
expect(popup.close).not.toHaveBeenCalled();
|
||||
popup.location.href = `${window.location.origin}/UIP/apps/chat/connect?provider=slack&resume=endpoint`;
|
||||
}
|
||||
if (mode === "fallback") {
|
||||
await act(async () => { window.dispatchEvent(new Event("focus")); });
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 30)); });
|
||||
expect(container.querySelector('a[target="_blank"]')?.textContent).toBe("Open sign-in in a new tab");
|
||||
expect(api.provisionManagedSlack).not.toHaveBeenCalled();
|
||||
}
|
||||
api.slackSetupOptions.mockResolvedValue({ managedAvailable: true, workspaces: [{ grantId: "grant", workspaceName: "Paperclip" }] });
|
||||
await act(async () => { window.dispatchEvent(new Event("focus")); });
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 30)); });
|
||||
expect(onSaved).toHaveBeenCalledWith(endpoint);
|
||||
expect(api.provisionManagedSlack).not.toHaveBeenCalled();
|
||||
const button = Array.from(container.querySelectorAll("button")).find(item => item.textContent === "Continue")!;
|
||||
await act(async () => button.click());
|
||||
expect(api.authorizeSlackManager).toHaveBeenCalledTimes(1);
|
||||
expect(api.provisionManagedSlack).toHaveBeenCalledWith("endpoint", expect.objectContaining({ grantId: "grant" }));
|
||||
});
|
||||
it("keeps the chosen workspace name out of session replay in the closed picker", async () => {
|
||||
api.slackSetupOptions.mockResolvedValue({ managedAvailable: true, workspaces: [{ grantId: "one", workspaceName: "Globex Sales" }, { grantId: "two", workspaceName: "Initech Ops" }] });
|
||||
endpoint.setup!.slackRegistration = { status: "failed", managerGrantId: "two" } as NonNullable<ChatEndpoint["setup"]>["slackRegistration"];
|
||||
await render();
|
||||
const trigger = container.querySelector('[aria-label="Slack workspace"]');
|
||||
expect(trigger?.textContent).toContain("Initech Ops");
|
||||
expect(replayLeaks("Initech Ops", document.body)).toEqual({ rendered: true, recorded: false });
|
||||
});
|
||||
it("keeps the only workspace name out of session replay", async () => {
|
||||
api.slackSetupOptions.mockResolvedValue({ managedAvailable: true, workspaces: [{ grantId: "grant", workspaceName: "Globex Sales" }] });
|
||||
endpoint.setup!.slackRegistration = { status: "failed" } as NonNullable<ChatEndpoint["setup"]>["slackRegistration"];
|
||||
await render();
|
||||
expect(replayLeaks("Globex Sales", document.body)).toEqual({ rendered: true, recorded: false });
|
||||
});
|
||||
@@ -1,4 +1,3 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type {
|
||||
|
||||
@@ -1,120 +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 { ToolsAccess } from "./ToolsAccess";
|
||||
|
||||
const mockParams = vi.hoisted(() => ({ tab: undefined as string | undefined }));
|
||||
const navigateMock = vi.hoisted(() => vi.fn(({ to }: { to: string }) => <div data-navigate={to} />));
|
||||
|
||||
vi.mock("@/lib/router", () => ({
|
||||
Link: ({ children, to }: { children: React.ReactNode; to: string }) => <a href={to}>{children}</a>,
|
||||
Navigate: (props: { to: string; replace?: boolean }) => navigateMock(props),
|
||||
useParams: () => mockParams,
|
||||
}));
|
||||
|
||||
vi.mock("@/context/BreadcrumbContext", () => ({
|
||||
useBreadcrumbs: () => ({ setBreadcrumbs: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock("@/context/CompanyContext", () => ({
|
||||
useCompany: () => ({
|
||||
selectedCompanyId: "company-1",
|
||||
selectedCompany: { id: "company-1", name: "Paperclip" },
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("./profiles/ProfilesIndex", () => ({
|
||||
ProfilesIndex: () => <section>Tool profiles</section>,
|
||||
}));
|
||||
|
||||
vi.mock("./PasteConfigTab", () => ({
|
||||
PasteConfigTab: () => <section>Paste tab</section>,
|
||||
}));
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
async function act(callback: () => void | Promise<void>) {
|
||||
let result: void | Promise<void> = undefined;
|
||||
flushSync(() => {
|
||||
result = callback();
|
||||
});
|
||||
await result;
|
||||
}
|
||||
|
||||
async function flushReact() {
|
||||
await Promise.resolve();
|
||||
await new Promise((resolve) => window.setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
describe("ToolsAccess", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: ReturnType<typeof createRoot>;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
mockParams.tab = undefined;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
document.body.innerHTML = "";
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
async function render() {
|
||||
await act(async () => {
|
||||
root.render(<ToolsAccess />);
|
||||
await flushReact();
|
||||
});
|
||||
}
|
||||
|
||||
it.each(["applications", "connections", "overview", "examples", "audit"])(
|
||||
"redirects retired %s tab links to Connectors",
|
||||
async (tab) => {
|
||||
mockParams.tab = tab;
|
||||
await render();
|
||||
|
||||
expect(navigateMock).toHaveBeenCalledWith(expect.objectContaining({ to: "/apps", replace: true }));
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
["runtime", "/apps"],
|
||||
["policies", "/apps/advanced/profiles"],
|
||||
["run-your-own", "/apps"],
|
||||
])("redirects the retired %s page to %s", async (tab, target) => {
|
||||
mockParams.tab = tab;
|
||||
await render();
|
||||
|
||||
expect(navigateMock).toHaveBeenCalledWith(expect.objectContaining({ to: target, replace: true }));
|
||||
});
|
||||
|
||||
it("uses Paste a config as the only advanced setup page", async () => {
|
||||
await render();
|
||||
|
||||
expect(container.textContent).toContain("Paste tab");
|
||||
expect(container.textContent).not.toContain("Run your own");
|
||||
expect(container.querySelector('a[href="/apps/advanced/paste-config"]')).toBeTruthy();
|
||||
});
|
||||
|
||||
it("uses Profiles as the developer entry point without a second page shell", async () => {
|
||||
await render();
|
||||
|
||||
expect(container.querySelector('a[href="/apps/advanced/profiles"]')?.textContent).toContain(
|
||||
"Open developer tools",
|
||||
);
|
||||
|
||||
mockParams.tab = "profiles";
|
||||
await render();
|
||||
|
||||
expect(container.textContent).not.toContain("Developer tools");
|
||||
expect(container.textContent).toContain("Tool profiles");
|
||||
expect(container.firstElementChild?.classList.contains("max-w-5xl")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,28 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { AGENT_AVATAR_SIZES, AGENT_PALETTE_IDS, CHARACTER_STATES, appearanceForPalette } from "@paperclipai/shared";
|
||||
import { agentAvatarUrl as productionUrl } from "../../src/lib/agent-avatar-url";
|
||||
import { agentAvatarUrl } from "./agent-avatar-url";
|
||||
|
||||
describe("packaged Storybook avatar URLs", () => {
|
||||
it("keeps production on the public API and resolves preview assets under a branch prefix", () => {
|
||||
const appearance = appearanceForPalette("bubblegum-sky");
|
||||
expect(productionUrl(appearance, 24, 2)).toBe("/api/agent-avatars/cap-v1/bubblegum-sky/rest.png?size=24&scale=2");
|
||||
expect(new URL(agentAvatarUrl(appearance, 24, 2), "https://example.com/branches/personas/builds/123/iframe.html").href)
|
||||
.toBe("https://example.com/branches/personas/builds/123/agent-avatar-images/cap-v1/bubblegum-sky/rest-24-2.png");
|
||||
expect(agentAvatarUrl(appearance)).toBe("./agent-avatar-images/cap-v1/bubblegum-sky/rest-512-1.png");
|
||||
expect(agentAvatarUrl(appearance, 256, 2, "rest", false, "transparent", "portrait")).toBe("./agent-avatar-images/cap-v1/bubblegum-sky/rest-256-2-portrait-v1.png");
|
||||
});
|
||||
|
||||
it("gives every finite preset a distinct filename, retaining logical size separately from density", () => {
|
||||
const paths = new Set<string>();
|
||||
for (const palette of AGENT_PALETTE_IDS) for (const pose of CHARACTER_STATES)
|
||||
for (const size of AGENT_AVATAR_SIZES) for (const scale of [1, 2] as const) {
|
||||
paths.add(agentAvatarUrl(appearanceForPalette(palette), size, scale, pose));
|
||||
paths.add(agentAvatarUrl(appearanceForPalette(palette), size, scale, pose, true));
|
||||
}
|
||||
expect(paths.size).toBe((AGENT_PALETTE_IDS.length + 1) * CHARACTER_STATES.length * AGENT_AVATAR_SIZES.length * 2);
|
||||
expect(agentAvatarUrl(appearanceForPalette("arctic-blue"), 24, 2))
|
||||
.not.toBe(agentAvatarUrl(appearanceForPalette("arctic-blue"), 48, 1));
|
||||
expect([...paths].every(path => !path.includes("?") && path.startsWith("./agent-avatar-images/cap-v1/"))).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,72 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { ONBOARDING_STORAGE_KEY } from "@/components/OnboardingWizard";
|
||||
import {
|
||||
ONBOARDING_ARC_ENTRY_STEP,
|
||||
STORYBOOK_COMPANY_ID,
|
||||
clearOnboardingDraft,
|
||||
readOnboardingDraft,
|
||||
seedOnboardingDraft,
|
||||
} from "./onboardingDraft";
|
||||
|
||||
afterEach(() => {
|
||||
window.localStorage.clear();
|
||||
});
|
||||
|
||||
describe("storybook onboarding draft", () => {
|
||||
// The leak this exists to stop: `localStorage` is per-origin and shared by
|
||||
// every story in a session, so a seeded draft left behind makes the *next*
|
||||
// story restore a saved step instead of the one it asked for. The reviewer
|
||||
// then sees a screen they did not click on, which reads as a wizard bug.
|
||||
it("leaves nothing behind once cleared", () => {
|
||||
seedOnboardingDraft();
|
||||
expect(readOnboardingDraft()).not.toBeNull();
|
||||
|
||||
clearOnboardingDraft();
|
||||
expect(readOnboardingDraft()).toBeNull();
|
||||
expect(window.localStorage.getItem(ONBOARDING_STORAGE_KEY)).toBeNull();
|
||||
});
|
||||
|
||||
// The wizard captures `entryStep` from this draft once, at mount, and offers
|
||||
// Back only while `currentStep > entryStep`. Seeding a later step is therefore
|
||||
// not a shortcut to it — it is a step that can never show its Back button.
|
||||
it("enters the arc at its first step, so later steps can be walked into", () => {
|
||||
seedOnboardingDraft();
|
||||
expect(readOnboardingDraft()?.step).toBe(ONBOARDING_ARC_ENTRY_STEP);
|
||||
});
|
||||
|
||||
// `createdAgentId` is what `launchStateIncomplete` checks. Filling it in
|
||||
// before the hire would paint over the guard step 5 is supposed to show when
|
||||
// it is reached without an agent.
|
||||
it("does not claim an agent exists before the hire", () => {
|
||||
seedOnboardingDraft();
|
||||
expect(readOnboardingDraft()?.createdAgentId).toBe("");
|
||||
});
|
||||
|
||||
// A run standing on step 3 has not reached the connect step, so it cannot
|
||||
// have chosen a source there. Seeding one is not a harmless head start: the
|
||||
// step reads a saved `adapterType` as "already picked", and every arc story
|
||||
// opened with Claude Code selected and its sign-in panel already showing —
|
||||
// the preselection the step was changed to stop doing, restored by the
|
||||
// fixture. Stories that need a source click one, the way a customer does.
|
||||
it("does not claim a model source was chosen before the connect step", () => {
|
||||
seedOnboardingDraft();
|
||||
expect(readOnboardingDraft()).not.toHaveProperty("adapterType");
|
||||
});
|
||||
|
||||
// `restoreOnboardingState` treats restoring as an authorization decision and
|
||||
// throws the whole blob away when the saved company is not one the account
|
||||
// owns. Seeding a company the fixtures do not report would silently restore
|
||||
// nothing, and every story would quietly fall back to its `initialStep`.
|
||||
it("names the company the fixtures report as owned", () => {
|
||||
seedOnboardingDraft();
|
||||
expect(readOnboardingDraft()?.createdCompanyId).toBe(STORYBOOK_COMPANY_ID);
|
||||
});
|
||||
|
||||
it("survives a malformed value without throwing", () => {
|
||||
window.localStorage.setItem(ONBOARDING_STORAGE_KEY, "{not json");
|
||||
expect(readOnboardingDraft()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,228 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createPrivacyState, installPrivacyApi, privacyCompanyId, privacyTask, privacyGrant } from "./privateTasks";
|
||||
describe("private task creation preview", () => {
|
||||
it.each([
|
||||
[{ title: "Open task" }, "open", null, null],
|
||||
[{ title: "Private task", visibility: "private" }, "private", "privacy-created", null],
|
||||
[{ title: "Private child", parentId: "privacy-root" }, "private", "privacy-root", "privacy-root"],
|
||||
[{ title: "Private project task", projectId: "project-private" }, "private", "privacy-created", null],
|
||||
])("matches creation defaults for %j", async (data, visibility, privacyRootIssueId, privacyParentIssueId) => {
|
||||
const restore = installPrivacyApi(createPrivacyState({}));
|
||||
try {
|
||||
const response = await fetch(`/api/companies/${privacyCompanyId}/issues`, { method: "POST", body: JSON.stringify(data) });
|
||||
const task = await response.json();
|
||||
expect(task).toMatchObject({ visibility, privacyRootIssueId, privacyParentIssueId });
|
||||
} finally { restore(); }
|
||||
});
|
||||
});
|
||||
|
||||
describe("task privacy moves in the preview", () => {
|
||||
it.each([
|
||||
[{ projectId: "project-private" }, "privacy-root", "privacy-root", null],
|
||||
[{ parentId: "privacy-child" }, "privacy-sibling", "privacy-root", "privacy-child"],
|
||||
])("inherits privacy when moving an open task into %j", async (data, id, root, parent) => {
|
||||
const restore = installPrivacyApi(createPrivacyState({ visibility: "open" }));
|
||||
try {
|
||||
const response = await fetch(`/api/issues/${id}`, { method: "PATCH", body: JSON.stringify(data) });
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toMatchObject({ visibility: "private", privacyRootIssueId: root, privacyParentIssueId: parent });
|
||||
} finally { restore(); }
|
||||
});
|
||||
it("inherits a parent's private project even if the parent is open", async () => {
|
||||
const state = createPrivacyState({ visibility: "open", taskProject: true });
|
||||
const restore = installPrivacyApi(state);
|
||||
try {
|
||||
const response = await fetch("/api/issues/privacy-sibling", { method: "PATCH", body: JSON.stringify({ parentId: "privacy-root" }) });
|
||||
expect(await response.json()).toMatchObject({ visibility: "private", privacyRootIssueId: "privacy-root", privacyParentIssueId: "privacy-root" });
|
||||
} finally { restore(); }
|
||||
});
|
||||
it("rejects publishing under a private project without mutating its scope", async () => {
|
||||
const state = createPrivacyState({ taskProject: true }); const restore = installPrivacyApi(state);
|
||||
try {
|
||||
const response = await fetch("/api/issues/privacy-root", { method: "PATCH", body: JSON.stringify({ visibility: "open" }) });
|
||||
expect(response.status).toBe(422);
|
||||
expect(state.tasks[0]).toMatchObject({ visibility: "private", projectId: "project-private" });
|
||||
} finally { restore(); }
|
||||
});
|
||||
it("leaves a personal project when making its task public", async () => {
|
||||
const restore = installPrivacyApi(createPrivacyState({ taskProject: true, personal: true }));
|
||||
try {
|
||||
const response = await fetch("/api/issues/privacy-root", { method: "PATCH", body: JSON.stringify({ visibility: "open" }) });
|
||||
expect(await response.json()).toMatchObject({ visibility: "open", projectId: null, project: null });
|
||||
} finally { restore(); }
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("preview descendants and effective access", () => {
|
||||
it.each([
|
||||
{ projectId: "project-private" },
|
||||
{ parentId: "private-peer" },
|
||||
{ visibility: "private" },
|
||||
])("protects the whole task subtree for %j", async (data) => {
|
||||
const state = createPrivacyState({ visibility: "open", grants: "empty" });
|
||||
for (const task of state.tasks) {
|
||||
task.visibility = "open";
|
||||
task.privacyRootIssueId = null;
|
||||
task.privacyParentIssueId = null;
|
||||
}
|
||||
// Include a provenance-only descendant, as well as ordinary child links.
|
||||
state.tasks[2]!.parentId = null;
|
||||
state.tasks[2]!.privacyParentIssueId = "privacy-child";
|
||||
state.tasks.push(privacyTask({ id: "private-peer", privacyRootIssueId: "private-peer" }));
|
||||
state.tasks.push(privacyTask({ id: "unrelated", visibility: "open", privacyRootIssueId: null }));
|
||||
const restore = installPrivacyApi(state);
|
||||
try {
|
||||
const response = await fetch("/api/issues/privacy-root", { method: "PATCH", body: JSON.stringify(data) });
|
||||
const root = await response.json();
|
||||
expect(response.status).toBe(200);
|
||||
for (const id of ["privacy-child", "privacy-grandchild", "privacy-sibling"]) {
|
||||
const child = await fetch(`/api/issues/${id}`).then(response => response.json());
|
||||
expect(child).toMatchObject({ visibility: "private", privacyRootIssueId: root.privacyRootIssueId });
|
||||
expect(child.privacyParentIssueId).not.toBeNull();
|
||||
}
|
||||
expect(state.tasks.find(task => task.id === "unrelated")?.visibility).toBe("open");
|
||||
} finally { restore(); }
|
||||
});
|
||||
it("drops former personal-project members after publishing and making the task private again", async () => {
|
||||
const restore = installPrivacyApi(createPrivacyState({ taskProject: true, personal: true, grants: "empty" }));
|
||||
try {
|
||||
const grants = () => fetch("/api/issues/privacy-root/access-grants").then(response => response.json());
|
||||
expect(await grants()).toContainEqual(expect.objectContaining({ subjectId: "user-product", source: "project" }));
|
||||
const published = await fetch("/api/issues/privacy-root", { method: "PATCH", body: JSON.stringify({ visibility: "open" }) }).then(response => response.json());
|
||||
expect(published).toMatchObject({ projectId: null, privacyRootIssueId: null });
|
||||
await fetch("/api/issues/privacy-root", { method: "PATCH", body: JSON.stringify({ visibility: "private" }) });
|
||||
expect(await grants()).not.toContainEqual(expect.objectContaining({ source: "project" }));
|
||||
} finally { restore(); }
|
||||
});
|
||||
it("removes inherited project membership after detaching from its parent", async () => {
|
||||
const restore = installPrivacyApi(createPrivacyState({ taskProject: true, grants: "empty" }));
|
||||
try {
|
||||
const grants = () => fetch("/api/issues/privacy-child/access-grants").then(response => response.json());
|
||||
expect(await grants()).toContainEqual(expect.objectContaining({ subjectId: "user-product", source: "project" }));
|
||||
await fetch("/api/issues/privacy-child", { method: "PATCH", body: JSON.stringify({ parentId: null }) });
|
||||
expect(await grants()).not.toContainEqual(expect.objectContaining({ source: "project" }));
|
||||
} finally { restore(); }
|
||||
});
|
||||
it("shows a child share only on that child and its descendants", async () => {
|
||||
const restore = installPrivacyApi(createPrivacyState({ grants: "empty" }));
|
||||
try {
|
||||
await fetch("/api/issues/privacy-child/access-grants", { method: "POST", body: JSON.stringify({ subjectType: "user", subjectId: "user-product" }) });
|
||||
for (const [id, expected] of [["privacy-root", false], ["privacy-child", true], ["privacy-grandchild", true], ["privacy-sibling", false]] as const) {
|
||||
const grants = await fetch(`/api/issues/${id}/access-grants`).then(response => response.json());
|
||||
expect(grants.some((grant: { subjectId: string }) => grant.subjectId === "user-product")).toBe(expected);
|
||||
if (id === "privacy-grandchild") expect(grants).toContainEqual(expect.objectContaining({ inherited: true, issueId: "privacy-child" }));
|
||||
}
|
||||
} finally { restore(); }
|
||||
});
|
||||
it("protects descendants when a project becomes private and keeps tasks private after opening it", async () => {
|
||||
const state = createPrivacyState({ visibility: "open", taskProject: true, grants: "empty" });
|
||||
state.projects[0]!.visibility = "open";
|
||||
for (const task of state.tasks) { task.visibility = "open"; task.privacyRootIssueId = null; }
|
||||
const restore = installPrivacyApi(state);
|
||||
try {
|
||||
await fetch("/api/projects/project-private", { method: "PATCH", body: JSON.stringify({ visibility: "private" }) });
|
||||
expect(state.tasks.every(task => task.visibility === "private" && task.privacyRootIssueId !== null)).toBe(true);
|
||||
await fetch("/api/projects/project-private", { method: "PATCH", body: JSON.stringify({ visibility: "open" }) });
|
||||
expect(state.tasks.every(task => task.visibility === "private")).toBe(true);
|
||||
const grants = await fetch("/api/issues/privacy-root/access-grants").then(response => response.json());
|
||||
expect(grants).not.toContainEqual(expect.objectContaining({ source: "project" }));
|
||||
} finally { restore(); }
|
||||
});
|
||||
it("keeps existing private descendants private when their parent is published", async () => {
|
||||
const state = createPrivacyState(); const restore = installPrivacyApi(state);
|
||||
try {
|
||||
await fetch("/api/issues/privacy-root", { method: "PATCH", body: JSON.stringify({ visibility: "open" }) });
|
||||
expect(state.tasks[0]).toMatchObject({ visibility: "open", privacyRootIssueId: null });
|
||||
expect(state.tasks.slice(1).every(task => task.visibility === "private")).toBe(true);
|
||||
} finally { restore(); }
|
||||
});
|
||||
it("does not revoke an ancestor grant through the child's endpoint", async () => {
|
||||
const state = createPrivacyState(); const restore = installPrivacyApi(state);
|
||||
try {
|
||||
const response = await fetch("/api/issues/privacy-child/access-grants/grant-morgan/revoke", { method: "POST", body: "{}" });
|
||||
expect(response.status).toBe(404);
|
||||
expect(state.grants.find(grant => grant.id === "grant-morgan")?.revokedAt).toBeNull();
|
||||
} finally { restore(); }
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("preview owner and saved assignment access", () => {
|
||||
it("keeps a child's own owner and assignment reasons after its parent becomes public", async () => {
|
||||
const state = createPrivacyState();
|
||||
state.tasks[1]!.responsibleUserId = "user-product";
|
||||
state.tasks[1]!.createdByUserId = "user-finance";
|
||||
const restore = installPrivacyApi(state);
|
||||
try {
|
||||
await fetch("/api/issues/privacy-root", { method: "PATCH", body: JSON.stringify({ visibility: "open" }) });
|
||||
const grants = await fetch("/api/issues/privacy-child/access-grants").then(response => response.json());
|
||||
for (const subjectId of ["user-product", "user-finance"]) expect(grants).toContainEqual(expect.objectContaining({ issueId: "privacy-child", subjectId, source: "owner", inherited: false }));
|
||||
expect(grants).toContainEqual(expect.objectContaining({ issueId: "privacy-child", subjectId: "agent-dedicated", source: "assignment", inherited: false }));
|
||||
expect(grants.every((grant: { issueId: string }) => grant.issueId === "privacy-child")).toBe(true);
|
||||
} finally { restore(); }
|
||||
});
|
||||
it("saves assignment access when a project becomes private and retains it after unassignment", async () => {
|
||||
const state = createPrivacyState({ visibility: "open", taskProject: true });
|
||||
state.projects[0]!.visibility = "open";
|
||||
for (const task of state.tasks) { task.visibility = "open"; task.privacyRootIssueId = null; }
|
||||
state.grants = [];
|
||||
const restore = installPrivacyApi(state);
|
||||
try {
|
||||
await fetch("/api/projects/project-private", { method: "PATCH", body: JSON.stringify({ visibility: "private" }) });
|
||||
await fetch("/api/issues/privacy-child", { method: "PATCH", body: JSON.stringify({ assigneeAgentId: null }) });
|
||||
await fetch("/api/projects/project-private", { method: "PATCH", body: JSON.stringify({ visibility: "open" }) });
|
||||
const grants = await fetch("/api/issues/privacy-child/access-grants").then(response => response.json());
|
||||
expect(grants).toContainEqual(expect.objectContaining({ issueId: "privacy-child", subjectId: "agent-dedicated", source: "assignment", inherited: false }));
|
||||
expect(grants).not.toContainEqual(expect.objectContaining({ source: "project" }));
|
||||
} finally { restore(); }
|
||||
});
|
||||
it("does not add an assignment grant beside an existing independent direct grant", async () => {
|
||||
const state = createPrivacyState({ grants: "empty" });
|
||||
state.grants.push(privacyGrant({ subjectType: "agent", subjectId: "agent-dedicated" }));
|
||||
const restore = installPrivacyApi(state);
|
||||
try {
|
||||
await fetch("/api/issues/privacy-root", { method: "PATCH", body: JSON.stringify({ assigneeAgentId: "agent-dedicated" }) });
|
||||
expect(state.grants.filter(grant => grant.issueId === "privacy-root" && grant.subjectId === "agent-dedicated")).toHaveLength(1);
|
||||
} finally { restore(); }
|
||||
});
|
||||
it.each([null, "agent-dedicated"])("uses the new task's actual assignment %s", async (assigneeAgentId) => {
|
||||
const restore = installPrivacyApi(createPrivacyState({ grants: "empty" }));
|
||||
try {
|
||||
await fetch(`/api/companies/${privacyCompanyId}/issues`, { method: "POST", body: JSON.stringify({ title: "Created private task", visibility: "private", assigneeAgentId }) });
|
||||
const grants = await fetch("/api/issues/privacy-created/access-grants").then(response => response.json());
|
||||
expect(grants).toContainEqual(expect.objectContaining({ issueId: "privacy-created", subjectId: "user-board", source: "owner", inherited: false }));
|
||||
expect(grants.filter((grant: { source: string }) => grant.source === "assignment")).toHaveLength(assigneeAgentId ? 1 : 0);
|
||||
} finally { restore(); }
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("revoked assignment access in previews", () => {
|
||||
it("does not restore a revoked assignment grant after unrelated edits", async () => {
|
||||
const state = createPrivacyState(); const restore = installPrivacyApi(state);
|
||||
try {
|
||||
await fetch("/api/issues/privacy-root/access-grants/grant-assignment/revoke", { method: "POST", body: "{}" });
|
||||
for (const data of [{ title: "Edited after revocation" }, { status: "done" }]) {
|
||||
await fetch("/api/issues/privacy-root", { method: "PATCH", body: JSON.stringify(data) });
|
||||
}
|
||||
const grants = await fetch("/api/issues/privacy-root/access-grants").then(response => response.json());
|
||||
expect(grants.filter((grant: { issueId: string; subjectId: string; revokedAt: string | null }) => grant.issueId === "privacy-root" && grant.subjectId === "agent-dedicated" && grant.revokedAt === null)).toHaveLength(0);
|
||||
expect(state.tasks[0]!.assigneeAgentId).toBe("agent-dedicated");
|
||||
} finally { restore(); }
|
||||
});
|
||||
it("saves a fresh assignment grant after an actual reassignment", async () => {
|
||||
const state = createPrivacyState(); const restore = installPrivacyApi(state);
|
||||
try {
|
||||
await fetch("/api/issues/privacy-root/access-grants/grant-assignment/revoke", { method: "POST", body: "{}" });
|
||||
await fetch("/api/issues/privacy-root", { method: "PATCH", body: JSON.stringify({ assigneeAgentId: null }) });
|
||||
await fetch("/api/issues/privacy-root", { method: "PATCH", body: JSON.stringify({ assigneeAgentId: "agent-dedicated" }) });
|
||||
const grants = await fetch("/api/issues/privacy-root/access-grants").then(response => response.json());
|
||||
const active = grants.filter((grant: { issueId: string; subjectId: string; revokedAt: string | null }) => grant.issueId === "privacy-root" && grant.subjectId === "agent-dedicated" && grant.revokedAt === null);
|
||||
expect(active).toHaveLength(1);
|
||||
expect(active[0]).toMatchObject({ source: "assignment", inherited: false });
|
||||
expect(active[0].id).not.toBe("grant-assignment");
|
||||
} finally { restore(); }
|
||||
});
|
||||
});
|
||||
@@ -1,41 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { AgentInstructions } from "./routineWebhookFields";
|
||||
import { webhookAgentInstructions as instructions } from "@/components/routine-triggers/webhook-instructions";
|
||||
|
||||
const demoWebhookUrl = "https://acme.paperclip.example/api/routine-triggers/public/0123456789abcdef01234567/fire";
|
||||
const webhookAgentInstructions = (sender: "custom" | "github") =>
|
||||
instructions(sender, "Verify a deployment", demoWebhookUrl, "demo_webhook_key_for_storybook_only");
|
||||
|
||||
const container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
let root: ReturnType<typeof createRoot>;
|
||||
afterEach(async () => {
|
||||
if (root) await act(async () => root.unmount());
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it.each(["custom", "github"] as const)("copies complete %s instructions from the agent instructions card", async (sender) => {
|
||||
const writeText = vi.fn().mockResolvedValue(undefined);
|
||||
vi.stubGlobal("navigator", { clipboard: { writeText } });
|
||||
const value = webhookAgentInstructions(sender);
|
||||
root = createRoot(container);
|
||||
await act(async () => root.render(<AgentInstructions value={value} />));
|
||||
await act(async () => container.querySelector<HTMLButtonElement>("button")!.click());
|
||||
expect(writeText).toHaveBeenCalledExactlyOnceWith(value);
|
||||
expect(value).toContain(demoWebhookUrl);
|
||||
expect(value).toContain("HTTP POST");
|
||||
expect(value).toContain("JSON object");
|
||||
expect(value).toContain("Content-Type: application/json");
|
||||
expect(value).toContain("demo_webhook_key_for_storybook_only");
|
||||
expect(value).toContain("They do not start the routine or create a task.");
|
||||
expect(value).toContain("Test events are not replayed.");
|
||||
if (sender === "custom") expect(value).toContain("Authorization: Bearer demo_webhook_key_for_storybook_only");
|
||||
else {
|
||||
expect(value).toContain("X-Hub-Signature-256");
|
||||
expect(value).not.toContain("Authorization: Bearer");
|
||||
}
|
||||
expect(container.querySelector("button")!.textContent).toContain("Copied");
|
||||
});
|
||||
@@ -1,35 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { defaultSelection, selectedScopes, services } from "./ServiceConsent";
|
||||
|
||||
const scope = (name: string) => `https://www.googleapis.com/auth/${name}`;
|
||||
describe("Workspace service consent preview", () => {
|
||||
it("requests nothing before selection", () => {
|
||||
expect(selectedScopes({})).toEqual([]);
|
||||
});
|
||||
it("keeps a Gmail-only reviewer request read-only", () => {
|
||||
expect(selectedScopes({ gmail: "read" })).toEqual([scope("gmail.readonly")]);
|
||||
});
|
||||
it("adds compose only for the explicit draft selection", () => {
|
||||
expect(selectedScopes({ gmail: "write" })).toEqual([scope("gmail.compose"), scope("gmail.readonly")]);
|
||||
});
|
||||
it("checks every supported service with write access by default", () => {
|
||||
expect(Object.keys(defaultSelection)).toEqual(services.map(service => service.id));
|
||||
expect(Object.values(defaultSelection)).toEqual(Array(3).fill("write"));
|
||||
const scopes = selectedScopes(defaultSelection);
|
||||
expect(scopes.some(value => value.includes("/auth/chat."))).toBe(false);
|
||||
expect(scopes).toContain(scope("gmail.compose"));
|
||||
expect(scopes).not.toContain(scope("contacts.readonly"));
|
||||
expect(scopes).not.toContain(scope("directory.readonly"));
|
||||
});
|
||||
it("ignores removed service keys in old preview selections", () => {
|
||||
expect(selectedScopes({ chat: "write", search: "read", people: "read", docs: "write", sheets: "write", slides: "write" })).toEqual([]);
|
||||
});
|
||||
it("combines Drive, Docs, Sheets, and Slides into one deduplicated permission group", () => {
|
||||
expect(selectedScopes({ drive: "write" })).toEqual([
|
||||
scope("documents"), scope("drive.file"), scope("drive.readonly"), scope("presentations"), scope("spreadsheets"),
|
||||
]);
|
||||
expect(selectedScopes({ drive: "read" })).toEqual([
|
||||
scope("documents.readonly"), scope("drive.readonly"), scope("presentations.readonly"), scope("spreadsheets.readonly"),
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,86 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
installFixtureApi,
|
||||
prepareFixtureApi,
|
||||
activatePreparedFixtures,
|
||||
} from "./api";
|
||||
let cleanup: (() => void) | undefined;
|
||||
afterEach(() => {
|
||||
cleanup?.();
|
||||
cleanup = undefined;
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
localStorage.clear();
|
||||
});
|
||||
describe("capability story API boundary", () => {
|
||||
it("activates story routes after preview defaults and restores those defaults", async () => {
|
||||
const preview = vi.fn(async () => Response.json({ source: "preview" }));
|
||||
const fixture = prepareFixtureApi([
|
||||
{ path: "/api/subject", read: () => ({ source: "story" }) },
|
||||
]);
|
||||
cleanup = fixture.cleanup;
|
||||
vi.stubGlobal("fetch", preview);
|
||||
activatePreparedFixtures();
|
||||
expect(await (await window.fetch("/api/subject")).json()).toEqual({
|
||||
source: "story",
|
||||
});
|
||||
expect(await (await window.fetch("/api/other")).json()).toEqual({
|
||||
source: "preview",
|
||||
});
|
||||
fixture.cleanup();
|
||||
cleanup = undefined;
|
||||
expect(window.fetch).toBe(preview);
|
||||
});
|
||||
it("blocks an unregistered mutation without calling the outer fetch", async () => {
|
||||
const outer = vi
|
||||
.spyOn(window, "fetch")
|
||||
.mockResolvedValue(Response.json({ unexpected: true }));
|
||||
cleanup = installFixtureApi([]).cleanup;
|
||||
const reply = await window.fetch("/api/companies/company-storybook", {
|
||||
method: "PATCH",
|
||||
body: "{}",
|
||||
});
|
||||
expect(reply.status).toBe(501);
|
||||
expect(outer).not.toHaveBeenCalled();
|
||||
});
|
||||
it("parses Request bodies and records the mutation before a simulated denial", async () => {
|
||||
const handler = vi.fn(() => ({ saved: true }));
|
||||
const fixture = installFixtureApi(
|
||||
[{ path: "/api/example", method: "POST", read: handler }],
|
||||
"mutation-permission",
|
||||
);
|
||||
cleanup = fixture.cleanup;
|
||||
const result = await window.fetch(
|
||||
new Request(`${location.origin}/api/example`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ value: 42 }),
|
||||
}),
|
||||
);
|
||||
expect(result.status).toBe(403);
|
||||
expect(fixture.requests[0].body).toEqual({ value: 42 });
|
||||
expect(handler).not.toHaveBeenCalled();
|
||||
});
|
||||
it("keeps prerequisite flags available during a subject error and restores fetch and company selection", async () => {
|
||||
const previous = window.fetch;
|
||||
localStorage.setItem("paperclip.selectedCompanyId", "original-company");
|
||||
const fixture = installFixtureApi(
|
||||
[
|
||||
{ path: "/api/flags", state: "ready", read: () => ({ enabled: true }) },
|
||||
{ path: "/api/subject", read: () => [] },
|
||||
],
|
||||
"failure",
|
||||
);
|
||||
cleanup = fixture.cleanup;
|
||||
expect(await (await window.fetch("/api/flags")).json()).toEqual({
|
||||
enabled: true,
|
||||
});
|
||||
expect((await window.fetch("/api/subject")).status).toBe(500);
|
||||
fixture.cleanup();
|
||||
cleanup = undefined;
|
||||
expect(window.fetch).toBe(previous);
|
||||
expect(localStorage.getItem("paperclip.selectedCompanyId")).toBe(
|
||||
"original-company",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,74 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import sample from "../../../fixtures/antigravity-swarm.sample.json";
|
||||
import { FIXTURE, deriveSwarm, parseSwarmFixture, postKind, progressLine, threadCount, threadState } from "./swarm-model";
|
||||
import { runningWithBlocked, stopped } from "./swarm-variants";
|
||||
|
||||
const states = (atSeq: number) => Object.fromEntries(deriveSwarm(FIXTURE, atSeq).helpers.map((helper) => [helper.name, helper.state]));
|
||||
|
||||
describe("swarm fixture derivation", () => {
|
||||
it("rejects a fixture with a missing field instead of rendering a blank story", () => {
|
||||
const broken = { ...sample, files: { ...sample.files, board: undefined } };
|
||||
expect(() => parseSwarmFixture(broken)).toThrow("files.board should be an array");
|
||||
});
|
||||
|
||||
it("derives helper states mid-run from board posts and helper steps", () => {
|
||||
expect(states(8)).toEqual({
|
||||
"html-writer": "in_review",
|
||||
"css-writer": "working",
|
||||
"logic-writer": "working",
|
||||
"docs-writer": "in_review",
|
||||
verifier: "working",
|
||||
monitor: "waiting",
|
||||
});
|
||||
const view = deriveSwarm(FIXTURE, 8);
|
||||
expect(view.helpers.find((helper) => helper.name === "css-writer")?.action).toBe("Writing style.css");
|
||||
expect(progressLine(view)).toBe("0 of 5 done · 2 in review · 2 threads open");
|
||||
});
|
||||
|
||||
it("keeps actions from the same second as the cutoff post", () => {
|
||||
const cutoff = FIXTURE.board.find((post) => post.seq === 7)!.time;
|
||||
const sameSecond = cutoff.replace(/\.\d+Z$/, "Z");
|
||||
const css = FIXTURE.workers["css-writer"]!;
|
||||
const fixture = { ...FIXTURE, workers: { ...FIXTURE.workers, "css-writer": { ...css, actions: [...css.actions.filter((action) => Date.parse(action.at) < Date.parse(cutoff)), { at: sameSecond, tool: "write_file", target: "<task-folder>/same-second.css" }] } } };
|
||||
expect(deriveSwarm(fixture, 7).helpers.find((helper) => helper.name === "css-writer")?.action).toBe("Writing same-second.css");
|
||||
});
|
||||
|
||||
it("marks everything done once the verifier reports", () => {
|
||||
const view = deriveSwarm(FIXTURE, 12, "completed");
|
||||
expect(Object.values(states(12)).filter((state) => state === "done")).toHaveLength(5);
|
||||
expect(view.threads.map((thread) => [threadState(view, thread), threadCount(view, thread)])).toEqual([["done", "4/4"], ["done", "1/1"]]);
|
||||
expect(progressLine(view)).toBe("5 of 5 done · 0 threads open");
|
||||
});
|
||||
|
||||
it("attaches usage and changed files only when the snapshot reaches the end of the turn", () => {
|
||||
const done = deriveSwarm(FIXTURE, 12, "completed");
|
||||
expect(done.usage?.total).toBe(179_931);
|
||||
expect(done.usage?.helpers?.input).toBeGreaterThan(0);
|
||||
expect(done.files).toEqual(FIXTURE.filesChanged);
|
||||
expect(stopped().usage).toBeUndefined();
|
||||
expect(deriveSwarm(FIXTURE, 8, "completed").usage).toBeUndefined();
|
||||
});
|
||||
|
||||
it("derives the blocked state from the recorded permission failure text", () => {
|
||||
const helper = runningWithBlocked().helpers.find((entry) => entry.name === FIXTURE.recordedBlock.helper);
|
||||
expect(helper?.state).toBe("blocked");
|
||||
expect(helper?.action).toBe("Blocked: tried to change ../shared/units.json, outside the task folder");
|
||||
});
|
||||
|
||||
it("clears the blocked state when the helper later reports done", () => {
|
||||
const at = FIXTURE.board.find((post) => post.seq === 8)!.time;
|
||||
const block = { seq: 7.5, agent: "logic-writer", text: FIXTURE.recordedBlock.text, time: at };
|
||||
const board = [...FIXTURE.board.filter((post) => post.seq <= 7), block, ...FIXTURE.board.filter((post) => post.seq > 7)];
|
||||
const view = deriveSwarm({ ...FIXTURE, board }, 12, "completed");
|
||||
expect(view.helpers.find((helper) => helper.name === "logic-writer")?.state).toBe("done");
|
||||
expect(progressLine(view)).toBe("5 of 5 done · 0 threads open");
|
||||
});
|
||||
|
||||
it("classifies board posts", () => {
|
||||
expect(postKind("monitor", "@coordinator [stall] nobody is working")).toBe("stall");
|
||||
expect(postKind("css-writer", "@verifier [done] style.css created")).toBe("done");
|
||||
expect(postKind("coordinator", "[done] built and verified")).toBe("finish");
|
||||
expect(postKind("coordinator", "@html-writer You own index.html", "brief")).toBe("brief");
|
||||
expect(postKind("logic-writer", FIXTURE.recordedBlock.text)).toBe("blocked");
|
||||
});
|
||||
});
|
||||
@@ -1,55 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { FixtureApi } from "./fixture-api";
|
||||
import { endpoint, reviews } from "./fixtures";
|
||||
|
||||
vi.mock("@/context/EditorAutocompleteContext", () => ({
|
||||
EditorAutocompleteProvider: ({ children }: { children: ReactNode }) => children,
|
||||
}));
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it("serves a review detail to the routed preview and rejects unknown review IDs", async () => {
|
||||
vi.spyOn(window, "fetch").mockResolvedValue(Response.json({}));
|
||||
const container = document.createElement("div");
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
flushSync(() => root.render(<FixtureApi><span>Ready</span></FixtureApi>));
|
||||
const path = `/api/chat-endpoints/${endpoint.id}/github/reviews/`;
|
||||
const response = await window.fetch(path + reviews[0].id);
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toMatchObject({
|
||||
id: reviews[0].id, headSha: reviews[0].headSha,
|
||||
});
|
||||
expect((await window.fetch(path + "missing-review")).status).toBe(404);
|
||||
} finally {
|
||||
flushSync(() => root.unmount());
|
||||
}
|
||||
});
|
||||
|
||||
it("persists connection defaults, preserves omitted values and clears them explicitly", async () => {
|
||||
vi.spyOn(window, "fetch").mockResolvedValue(Response.json({}));
|
||||
let root = createRoot(document.createElement("div"));
|
||||
const url = `/api/chat-endpoints/${endpoint.id}`;
|
||||
const patch = async (body: unknown) => (await window.fetch(url, {
|
||||
method: "PATCH", body: JSON.stringify(body),
|
||||
})).json();
|
||||
try {
|
||||
flushSync(() => root.render(<FixtureApi><span>Ready</span></FixtureApi>));
|
||||
const executionDefaults = { projectId: null, workspace: { kind: "task_directory" } };
|
||||
expect(await patch({ executionDefaults })).toMatchObject({ executionDefaults });
|
||||
expect(await (await window.fetch(url)).json()).toMatchObject({ executionDefaults });
|
||||
expect(await patch({ communicationInstructions: "Fixture instructions" })).toMatchObject({ executionDefaults });
|
||||
expect(await patch({ executionDefaults: null })).toMatchObject({ executionDefaults: null });
|
||||
flushSync(() => root.unmount());
|
||||
root = createRoot(document.createElement("div"));
|
||||
flushSync(() => root.render(<FixtureApi><span>Ready</span></FixtureApi>));
|
||||
expect((await (await window.fetch(url)).json()).executionDefaults).toEqual(endpoint.executionDefaults);
|
||||
} finally {
|
||||
flushSync(() => root.unmount());
|
||||
}
|
||||
});
|
||||
@@ -1,24 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
import { QueryClient } from '@tanstack/react-query';
|
||||
import { expect, it } from 'vitest';
|
||||
import { skillSourcesApi } from '@/api/skillSources';
|
||||
import { COMPANY_ID } from '../fixtures/githubSkillSources';
|
||||
import { installBranchSelectionFixtures } from './skillSourceBranchSelection';
|
||||
|
||||
it('requires the newly returned revision before the concurrent-update journey can save', async () => {
|
||||
const client = new QueryClient();
|
||||
const fixture = installBranchSelectionFixtures('save-conflict', client);
|
||||
try {
|
||||
const [source] = await skillSourcesApi.list(COMPANY_ID);
|
||||
const input = { revision: source!.revision, trackingRef: 'develop' };
|
||||
await expect(skillSourcesApi.settings(COMPANY_ID, source!.id, input)).rejects.toMatchObject({ status: 409 });
|
||||
const [updated] = await skillSourcesApi.list(COMPANY_ID);
|
||||
expect(updated!.revision).toBeGreaterThan(source!.revision);
|
||||
await expect(skillSourcesApi.settings(COMPANY_ID, source!.id, input)).rejects.toMatchObject({ status: 409 });
|
||||
const saved = await skillSourcesApi.settings(COMPANY_ID, source!.id, { ...input, revision: updated!.revision });
|
||||
expect(saved.trackingRef).toBe('develop');
|
||||
expect(saved.revision).toBeGreaterThan(updated!.revision);
|
||||
} finally {
|
||||
fixture.cleanup(); client.clear();
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user