From 33fac97cad5d4e4393403bee01d4a16ef472e17b Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:13:15 -0600 Subject: [PATCH] feat(routines): ship the redesigned routine page and let live webhooks be tested again (#22205) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Routines start agent work on a schedule, from a webhook, or on demand > - The routine detail page split one routine across eight sections behind a section sidebar (overview, triggers, variables, secrets, delivery, runs, activity, history) > - People had to hunt through sections to see what a routine does and to change it, and a finished webhook could not be tested again without starting the routine > - This pull request makes the approved two-column routine page, one Edit dialog and one Webhook dialog the real routed page, and lets a live webhook go back into test mode > - The benefit is one page that answers what the routine does, when it runs, who runs it and what it made, with every change in one dialog ## Linked Issues or Issue Description **Problem** The routine detail page spreads one routine over eight sections and a section sidebar. Changing a routine means visiting several sections, each with its own save bar. A webhook that is already live cannot be tested again: the API only accepts `setupPending: false`, so testing a live webhook starts the routine. **Proposed solution** Ship the reviewed design (stories `routine-page-design`, `routine-edit-dialog-design`, `routine-webhook-dialog-design`) as the routed page in both UI shells, wired to the real API. Let `PATCH /api/routine-triggers/:id` accept `setupPending: true` for a live webhook so the next events are checked but never start the routine. **Alternatives considered** Keep the sections and restyle them. The owner rejected this: the section sidebar should go. ## What Changed - `/routines/:id` renders `RoutinePage` in both shells (`RoutineDetail.production.tsx` is removed). Status switch, Repeats rows, default agent, responsible user, project, Asks for, Secrets, Run rules, Managed by plugin, Instructions with Show all, copy and the comment count, and History. - History is paged: 20 tasks per page from `GET /companies/:id/issues?originKind=routine_execution&originId=…&sortField=created&sortDir=desc&limit=21&offset=…`, with a real Load more. Coalesced runs show as "folded into a task". - A failed refetch keeps the loaded page on screen (`useQueryView`); a History failure shows `QueryErrorState` in place. - Header: Edit, "…" (Version history, Audit log, Archive / Restore) and Run now. In the streamlined desktop shell they sit in the breadcrumb toolbar; elsewhere above the page. - Version history (`/routines/:id/history`, restore and restored-webhook keys kept) and Audit log (`/routines/:id/activity`, `RoutineAuditActivity`) open as sub-views with a way back. Old section addresses and `?tab=` redirect to `/routines/:id`. - Edit dialog saves title, instructions, variables, secrets, agent, project and responsible user in one request against the revision the dialog opened with (save conflict shows "changed while you were editing"). The first schedule is created, changed or removed after that. Priority and delivery settings are never sent, so saved values stay. - Webhooks are created, changed, tested and removed (with Undo) right away from the Edit dialog, with the Webhook dialog nested inside it. Closing the Webhook dialog ends setup or test mode. A webhook left in test mode shows "Testing · events don’t run" on the page and offers Finish testing. - Responsibility (only with `enableResponsibilities`): the page shows direct and through-project responsibilities from the link lookup; the dialog links or unlinks the direct one. With the flag off nothing is fetched or shown. - The routines list creates routines with the same dialog in create mode, filed in the open folder, and opens the new routine page. - Server: `setupPending: true` on a live webhook enters test mode (planned by a pure `planTriggerUpdate`, which also gives the activity action) (422 for other trigger kinds; 409 for a disabled or removed webhook or an archived routine). Test deliveries keep the last real delivery as `lastWebhookDelivery.previous`, and finishing testing restores it. Activity `routine.trigger_test_started`. - Additions to the reviewed design, from review, so no capability is lost: the schedule popover has Pause/Resume; standing-check and API rows open a small popover with Pause/Resume and Remove; removing a trigger from the page leaves a "… removed. Undo" line under Repeats. Stories: `StandingCheckOpened`, `ScheduleTriggerPaused(Opened)`, `RemovedWithUndo`. - Save is several requests (routine, schedule, responsibility). It changes only the schedule the form opened with, records each finished step, and a partial failure says what was saved and that saving again finishes it. The dialog cannot be dismissed while saving. Failed reads show a Retry state, never empty choices. - Removed: the routine section sidebar and contextual sidebar, the trigger wizard, trigger cards, save bar, section components and their tests. - Storybook: the three routine stories moved to `stories/routines` as current production stories, a new story mounts the routed page against a fixture API, and stories that used the old page were updated or removed. ## Verification - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/routines-e2e.test.ts` (17/17) and `src/__tests__/routines-service.test.ts` (105/105). - `pnpm exec vitest run` on the routine page, routines list, routine form, webhook instructions, Layout, shell navigation, audit and editor tests: 275 tests pass. - `cd ui && npx tsc -p tsconfig.json --noEmit`, `node scripts/check-token-gates.mjs`, `node scripts/check-maps.mjs`, `node scripts/storybook-catalog.mjs --check`: pass. - `pnpm verify` exits 2 (global CI input changed); required CI supplies the broad coverage. - Manual: an isolated worktree instance (`pnpm paperclipai worktree init --empty`, `pnpm dev`) with a seeded routine. Headless Playwright: an old `/triggers` address redirects, no section sidebar, History shows 20 then 23 after Load more, the schedule popover opens, pause and resume, Edit → Add webhook → created key → Finish, title save, Test webhook → Finish testing, Version history, Audit log shows "Started testing a webhook", phone width has no horizontal overflow, and Create routine from the list opens the new page. No console errors or failed API calls. ## Risks - Behaviour change: the section pages are gone. Old links redirect to the single page. - The delivery-setting editors (concurrency, catch-up, activity gate) and priority are removed from the UI. Saved values stay, and the API still accepts them. - The create dialog no longer offers a folder picker or delivery settings. A new routine goes into the folder the list is showing and takes the default settings. - Replace key in the Webhook dialog acts at once, as in the reviewed design. The old confirmation is gone. - No migration. `lastWebhookDelivery.previous` is an optional field inside the existing jsonb column. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use (shell, file edits, headless browser) and subagents for the server change and the Storybook move. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.2 --- doc/connections/FIREFLIES.md | 6 +- docs/api/routines.md | 4 +- maps/feature-map/activity.md | 6 +- maps/feature-map/routines.md | 17 +- packages/shared/src/types/routine.ts | 2 + packages/shared/src/validators/routine.ts | 2 +- .../routine-trigger-update-plan.test.ts | 44 + server/src/__tests__/routines-e2e.test.ts | 135 +- server/src/routes/routines.ts | 3 +- .../services/routine-trigger-update-plan.ts | 45 + server/src/services/routines.ts | 43 +- .../runner-e2e/source-sdk-public-inputs.json | 4 +- tests/storybook-visual/fireflies-pr.spec.ts | 14 +- .../project-repository-skills.spec.ts | 15 +- ui/src/App.tsx | 6 +- ui/src/api/responsibilities.ts | 6 + ui/src/components/InlineEntitySelector.tsx | 6 +- ui/src/components/Layout.test.tsx | 13 +- ui/src/components/Layout.tsx | 7 - ui/src/components/RoutineActivityRow.tsx | 2 +- .../RoutineContextualSidebar.test.tsx | 114 -- .../components/RoutineContextualSidebar.tsx | 121 -- ui/src/components/RoutineOverview.test.tsx | 213 --- ui/src/components/RoutineOverview.tsx | 263 --- .../RoutineResponsibleUser.test.tsx | 147 -- ui/src/components/RoutineResponsibleUser.tsx | 105 -- ui/src/components/RoutineSaveBar.test.tsx | 95 -- ui/src/components/RoutineSaveBar.tsx | 203 --- .../components/RoutineSectionHeading.test.tsx | 73 - ui/src/components/RoutineSectionHeading.tsx | 30 - ui/src/components/RoutineSubSidebar.test.tsx | 117 -- ui/src/components/RoutineSubSidebar.tsx | 216 --- ui/src/components/RoutineTriggerCard.tsx | 207 --- ui/src/components/RoutineVariablesEditor.tsx | 151 ++ ui/src/components/ScheduleEditor.tsx | 17 +- .../environment-variables-editor/Row.tsx | 4 +- .../environment-variables-editor/index.tsx | 17 +- .../routine-page/RoutineCreateDialog.tsx | 94 ++ .../routine-page/RoutineEditDialog.test.tsx | 127 ++ .../routine-page/RoutineEditDialog.tsx | 543 ++++++ .../components/routine-page/RoutinePage.tsx | 795 +++++++++ .../RoutineWebhookDialog.test.tsx | 130 ++ .../routine-page/RoutineWebhookDialog.tsx | 208 +++ .../routine-page/routine-form.test.ts | 137 ++ .../components/routine-page/routine-form.ts | 156 ++ .../components/routine-page/routine-routes.ts | 24 + .../routine-page/routine-summary.ts | 188 +++ .../routine-page/useRoutineFormOptions.ts | 144 ++ .../routine-page/useRoutineWebhookDialog.ts | 207 +++ .../components/routine-sections/context.tsx | 182 -- .../editable-sections.production.tsx | 862 ---------- .../editable-sections.test.tsx | 179 -- .../routine-sections/editable-sections.tsx | 642 ------- .../operate-sections.test.tsx | 83 - .../routine-sections/operate-sections.tsx | 162 -- .../routine-triggers/RoutineTriggers.tsx | 668 -------- .../routine-triggers/TriggerCard.tsx | 66 - .../routine-triggers/TriggerWizard.test.tsx | 46 - .../routine-triggers/TriggerWizard.tsx | 597 ------- .../webhook-instructions.test.ts | 41 + .../routine-triggers/webhook-instructions.ts | 80 + ui/src/index.css | 2 +- ui/src/lib/cron-readable.test.ts | 31 - ui/src/lib/cron-readable.ts | 79 - ui/src/lib/queryKeys.ts | 3 + ui/src/lib/routine-description-copy.test.ts | 28 - ui/src/lib/routine-description-copy.ts | 12 - ui/src/lib/shell-navigation.test.ts | 3 +- ui/src/lib/shell-navigation.ts | 10 +- ui/src/pages/RoutineDetail.production.tsx | 956 ----------- ui/src/pages/RoutineDetail.test.tsx | 540 +++++- ui/src/pages/RoutineDetail.tsx | 1480 +++++++---------- ui/src/pages/Routines.production.tsx | 443 +---- ui/src/pages/Routines.test.tsx | 44 +- ui/src/pages/Routines.tsx | 446 +---- ui/storybook/fixtures/routineTriggerCard.tsx | 1 - .../fixtures/routineTriggerWizard.tsx | 11 - .../fixtures/routineWebhookFields.test.tsx | 6 +- ui/storybook/fixtures/routineWebhooks.tsx | 11 +- .../agent-setup-prompt.stories.tsx | 4 +- .../connection-setup/fireflies-pr.stories.tsx | 88 +- .../routines/routine-detail-c.stories.tsx | 475 ------ .../routines/routine-edit-dialog.stories.tsx | 118 ++ .../routines/routine-page-routed.stories.tsx | 124 ++ .../stories/routines/routine-page.stories.tsx | 92 + .../routines/routine-secrets.stories.tsx | 10 +- .../routine-webhook-dialog.stories.tsx | 87 + .../routines/routine-webhooks-ux.stories.tsx | 286 ---- .../routines/routine-webhooks.stories.tsx | 37 +- .../stories/routines/run-now.stories.tsx | 25 +- .../support/projectRepositorySkills.ts | 7 + .../support/routines/RoutedRoutinePage.tsx | 180 ++ .../support/routines/RoutinePagePreview.tsx | 476 ++++++ .../support/routines/routine-page-data.ts | 379 +++++ 94 files changed, 6116 insertions(+), 9212 deletions(-) create mode 100644 server/src/__tests__/routine-trigger-update-plan.test.ts create mode 100644 server/src/services/routine-trigger-update-plan.ts delete mode 100644 ui/src/components/RoutineContextualSidebar.test.tsx delete mode 100644 ui/src/components/RoutineContextualSidebar.tsx delete mode 100644 ui/src/components/RoutineOverview.test.tsx delete mode 100644 ui/src/components/RoutineOverview.tsx delete mode 100644 ui/src/components/RoutineResponsibleUser.test.tsx delete mode 100644 ui/src/components/RoutineResponsibleUser.tsx delete mode 100644 ui/src/components/RoutineSaveBar.test.tsx delete mode 100644 ui/src/components/RoutineSaveBar.tsx delete mode 100644 ui/src/components/RoutineSectionHeading.test.tsx delete mode 100644 ui/src/components/RoutineSectionHeading.tsx delete mode 100644 ui/src/components/RoutineSubSidebar.test.tsx delete mode 100644 ui/src/components/RoutineSubSidebar.tsx delete mode 100644 ui/src/components/RoutineTriggerCard.tsx create mode 100644 ui/src/components/routine-page/RoutineCreateDialog.tsx create mode 100644 ui/src/components/routine-page/RoutineEditDialog.test.tsx create mode 100644 ui/src/components/routine-page/RoutineEditDialog.tsx create mode 100644 ui/src/components/routine-page/RoutinePage.tsx create mode 100644 ui/src/components/routine-page/RoutineWebhookDialog.test.tsx create mode 100644 ui/src/components/routine-page/RoutineWebhookDialog.tsx create mode 100644 ui/src/components/routine-page/routine-form.test.ts create mode 100644 ui/src/components/routine-page/routine-form.ts create mode 100644 ui/src/components/routine-page/routine-routes.ts create mode 100644 ui/src/components/routine-page/routine-summary.ts create mode 100644 ui/src/components/routine-page/useRoutineFormOptions.ts create mode 100644 ui/src/components/routine-page/useRoutineWebhookDialog.ts delete mode 100644 ui/src/components/routine-sections/context.tsx delete mode 100644 ui/src/components/routine-sections/editable-sections.production.tsx delete mode 100644 ui/src/components/routine-sections/editable-sections.test.tsx delete mode 100644 ui/src/components/routine-sections/editable-sections.tsx delete mode 100644 ui/src/components/routine-sections/operate-sections.test.tsx delete mode 100644 ui/src/components/routine-sections/operate-sections.tsx delete mode 100644 ui/src/components/routine-triggers/RoutineTriggers.tsx delete mode 100644 ui/src/components/routine-triggers/TriggerCard.tsx delete mode 100644 ui/src/components/routine-triggers/TriggerWizard.test.tsx delete mode 100644 ui/src/components/routine-triggers/TriggerWizard.tsx create mode 100644 ui/src/components/routine-triggers/webhook-instructions.test.ts create mode 100644 ui/src/components/routine-triggers/webhook-instructions.ts delete mode 100644 ui/src/lib/cron-readable.test.ts delete mode 100644 ui/src/lib/cron-readable.ts delete mode 100644 ui/src/lib/routine-description-copy.test.ts delete mode 100644 ui/src/lib/routine-description-copy.ts delete mode 100644 ui/src/pages/RoutineDetail.production.tsx delete mode 100644 ui/storybook/fixtures/routineTriggerCard.tsx delete mode 100644 ui/storybook/fixtures/routineTriggerWizard.tsx delete mode 100644 ui/storybook/stories/routines/routine-detail-c.stories.tsx create mode 100644 ui/storybook/stories/routines/routine-edit-dialog.stories.tsx create mode 100644 ui/storybook/stories/routines/routine-page-routed.stories.tsx create mode 100644 ui/storybook/stories/routines/routine-page.stories.tsx create mode 100644 ui/storybook/stories/routines/routine-webhook-dialog.stories.tsx delete mode 100644 ui/storybook/stories/routines/routine-webhooks-ux.stories.tsx create mode 100644 ui/storybook/support/routines/RoutedRoutinePage.tsx create mode 100644 ui/storybook/support/routines/RoutinePagePreview.tsx create mode 100644 ui/storybook/support/routines/routine-page-data.ts diff --git a/doc/connections/FIREFLIES.md b/doc/connections/FIREFLIES.md index 199529a7392..a94b6878305 100644 --- a/doc/connections/FIREFLIES.md +++ b/doc/connections/FIREFLIES.md @@ -175,10 +175,8 @@ accounts or send provider requests. | --- | --- | | Catalog definition and branded artwork | Fireflies catalog; artwork in dark/light themes; Access, OAuth, API-key, and retry screens | | Preserved action restrictions | Permissions with Allowed, Ask first, and Off examples | -| `TriggerWizard.tsx` | Shared app choice, HTTPS warning, signing secret/bearer copy, four verification states, save/resume, hidden-secret rotation, legacy drafts, mobile and light theme | -| `RoutineTriggers.tsx` | Saved app-webhook settings, rotated secret/agent instructions, rejected delivery | -| `RoutineTriggerCard.tsx` | Advanced card with `app_webhook` and no timestamp replay window | -| `editable-sections.production.tsx` | Advanced creation with shared signing-mode description | +| `RoutineWebhookDialog.tsx` | Choosing the sender, the one-time key with agent instructions, waiting/received/rejected test states, HTTPS warning, hidden key and Replace key, existing bearer and signed webhooks, mobile and light theme | +| Routine page and Edit dialog | Saved app webhook, replaced key, rejected delivery, adding a webhook from the Edit dialog | ```sh pnpm storybook diff --git a/docs/api/routines.md b/docs/api/routines.md index 6a2d208ae81..b31da462a1b 100644 --- a/docs/api/routines.md +++ b/docs/api/routines.md @@ -349,7 +349,9 @@ Routine detail exposes `setupPending` and `lastWebhookDelivery` (`status`, `rece Finish setup with `PATCH /api/routine-triggers/{id}` and `{ "setupPending": false }`. Future deliveries use normal routine dispatch and still respect the routine's enabled state. Test events are not dispatched on activation. Retries with the same `Idempotency-Key`, GitHub `X-GitHub-Delivery`, or timestamp-HMAC replay key remain test receipts after activation. Send a unique delivery ID per event so a sender's retries can be recognized. Requests without a delivery ID are new events after activation. -For compatibility, API-created triggers without `setupPending: true` are immediately live. Completed triggers cannot be returned to setup mode. Checking a previously enabled webhook observes real deliveries and can start the routine; the management UI explains this difference. +For compatibility, API-created triggers without `setupPending: true` are immediately live. + +To test a live webhook again, send `PATCH /api/routine-triggers/{id}` with `{ "setupPending": true }`. Only enabled, non-removed webhook triggers on a routine that is not archived can enter test mode: other trigger kinds return `422`, and a disabled or removed webhook or an archived routine returns `409`. While testing, every authenticated delivery, including real events from the sender, is recorded as a test and never starts the routine. Each test delivery's `lastWebhookDelivery.previous` holds the last real delivery from before testing (or `null`). Sending `{ "setupPending": false }` returns the webhook to live and restores that last real delivery as `lastWebhookDelivery`. Events received while testing are not replayed, and retries of them with the same delivery ID stay test receipts. Trigger cards support removal with Undo. `PATCH` with `{ "archived": true }` excludes a trigger from routine detail and scheduling, and rejects its webhook deliveries. Setting `archived` back to `false` restores the same URL and credentials. `DELETE` remains the permanent deletion API. diff --git a/maps/feature-map/activity.md b/maps/feature-map/activity.md index 7c2c03524e8..76076f22ff7 100644 --- a/maps/feature-map/activity.md +++ b/maps/feature-map/activity.md @@ -69,9 +69,9 @@ regressions cover this route separately from company-wide audit. Live sandbox agent access remains unverified; use the companion recipe. Audit-event Load more and run listings differ: Runs currently loads at most 200 -entries without pagination. The tested RoutineAuditActivity component has no -registered activity-route host; inspect execution links actually offered by -the routine rather than treating that component test as a reachable journey. +entries without pagination. RoutineAuditActivity is reachable as the routine +page's Audit log (`/routines/:routineId/activity`); inspect execution links +from there rather than treating its component test as the journey. ### `agent-commentary` diff --git a/maps/feature-map/routines.md b/maps/feature-map/routines.md index a718dcb13d1..95fd016333e 100644 --- a/maps/feature-map/routines.md +++ b/maps/feature-map/routines.md @@ -8,7 +8,7 @@ Operators define repeatable work, configure its inputs and triggers, run it on d Feature ID: `routines`. -Implementation: [routine list](../../ui/src/pages/Routines.tsx), [routine detail](../../ui/src/pages/RoutineDetail.tsx), [trigger editor](../../ui/src/components/routine-triggers/TriggerWizard.tsx). +Implementation: [routine list](../../ui/src/pages/Routines.tsx), [routine detail](../../ui/src/pages/RoutineDetail.tsx), [routine page](../../ui/src/components/routine-page/RoutinePage.tsx), [edit dialog](../../ui/src/components/routine-page/RoutineEditDialog.tsx), [webhook dialog](../../ui/src/components/routine-page/RoutineWebhookDialog.tsx). Agent access: [companion](../agent-access-map/routines.md). @@ -24,12 +24,17 @@ Agent access: [companion](../agent-access-map/routines.md). ### `routine-editor` -Open `/routines`, create one, and inspect `/routines/:routineId` and its edit sections. +Open `/routines`, create one (New routine opens the edit dialog), and inspect +`/routines/:routineId`. Edit opens the same dialog; older section addresses +redirect to the page. ### `trigger-history` -Use the routine's trigger controls and Runs/Recent Runs/Audit links; lists also -offer Run now. **History** records configuration versions, not executions. +Schedules and webhooks are listed under Repeats on the routine page; a webhook +opens its dialog there, and both are added or changed in the Edit dialog. Tasks +the routine created are under History on the page. The page menu leads to +**Version history** (`/routines/:routineId/history`, configuration versions, not +executions) and **Audit log** (`/routines/:routineId/activity`). Lists also offer Run now. ## Driving it with Playwright and the Paperclip CLI @@ -37,7 +42,7 @@ Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Use ### `routine-editor` -Automated: [routine detail helper](../../ui/src/pages/RoutineDetail.test.tsx) tests project-selector options, not the rendered editor. [Routine service](../../server/src/__tests__/routines-service.test.ts) covers server contracts. Saving and running through the editor remain manual checks. +Automated: [routed routine page tests](../../ui/src/pages/RoutineDetail.test.tsx) cover old-address redirects, History paging, the status switch, saving edits against the opened revision, the save-conflict state, webhook test mode and the responsibility flag gate; [routine form tests](../../ui/src/components/routine-page/routine-form.test.ts) cover schedule and responsibility sync. [Routine service](../../server/src/__tests__/routines-service.test.ts) covers server contracts. Running a routine through the page remains a manual check. 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. @@ -48,7 +53,7 @@ complete the generated task or establish a useful task output. ### `trigger-history` -Automated: [trigger wizard](../../ui/src/components/routine-triggers/TriggerWizard.test.tsx) is 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 [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. Manual: Set a near-term disposable schedule or authorized test webhook, verify one eligible execution and its source trigger, then disable it and confirm further invocations stop. Inspect a failed execution without losing its history. Remove the temporary trigger after testing. diff --git a/packages/shared/src/types/routine.ts b/packages/shared/src/types/routine.ts index 850fdeb686d..6b2f2fd2718 100644 --- a/packages/shared/src/types/routine.ts +++ b/packages/shared/src/types/routine.ts @@ -179,6 +179,8 @@ export interface RoutineWebhookDelivery { status: "received" | "rejected"; receivedAt: string; test: boolean; + /** While testing, the last real (non-test) delivery, restored when testing ends. */ + previous?: RoutineWebhookDelivery | null; } export interface RoutineTrigger { diff --git a/packages/shared/src/validators/routine.ts b/packages/shared/src/validators/routine.ts index 05bb57f404c..95f04abf9cb 100644 --- a/packages/shared/src/validators/routine.ts +++ b/packages/shared/src/validators/routine.ts @@ -162,7 +162,7 @@ export const createRoutineTriggerSchema = z.discriminatedUnion("kind", [ export type CreateRoutineTrigger = z.infer; export const updateRoutineTriggerSchema = z.object({ - setupPending: z.literal(false).optional(), + setupPending: z.boolean().optional(), archived: z.boolean().optional(), label: z.string().trim().max(120).optional().nullable(), enabled: z.boolean().optional(), diff --git a/server/src/__tests__/routine-trigger-update-plan.test.ts b/server/src/__tests__/routine-trigger-update-plan.test.ts new file mode 100644 index 00000000000..baef7f05a09 --- /dev/null +++ b/server/src/__tests__/routine-trigger-update-plan.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from "vitest"; +import { planTriggerUpdate, triggerUpdateActivityAction } from "../services/routine-trigger-update-plan.js"; + +const real = { status: "received" as const, receivedAt: "2026-11-17T10:00:00Z", test: false }; + +describe("planTriggerUpdate", () => { + it("starts testing without touching the delivery", () => { + const plan = planTriggerUpdate({ setupPending: true }, { kind: "webhook", setupPending: false, lastWebhookDelivery: real }); + expect(plan).toMatchObject({ startsTesting: true, finishesTesting: false, restoredDelivery: null, changeSummary: "Started testing webhook", activityAction: "routine.trigger_test_started" }); + }); + + it("restores the last real delivery when a test ends", () => { + const plan = planTriggerUpdate({ setupPending: false }, { + kind: "webhook", + setupPending: true, + lastWebhookDelivery: { status: "received", receivedAt: "2026-11-18T10:00:00Z", test: true, previous: real }, + }); + expect(plan.restoredDelivery).toEqual({ value: real }); + expect(plan.changeSummary).toBe("Finished testing webhook"); + expect(plan.activityAction).toBe("routine.trigger_setup_finished"); + }); + + it("clears a test result that had no real delivery before it", () => { + const plan = planTriggerUpdate({ setupPending: false }, { + kind: "webhook", + setupPending: true, + lastWebhookDelivery: { status: "received", receivedAt: "2026-11-18T10:00:00Z", test: true, previous: null }, + }); + expect(plan.restoredDelivery).toEqual({ value: null }); + expect(plan.changeSummary).toBe("Finished webhook setup or test"); + }); + + it("leaves deliveries recorded before test bookkeeping alone", () => { + const legacy = { status: "received" as const, receivedAt: "2026-11-18T10:00:00Z", test: true }; + expect(planTriggerUpdate({ setupPending: false }, { kind: "webhook", setupPending: true, lastWebhookDelivery: legacy }).restoredDelivery).toBeNull(); + }); + + it("names other updates by trigger kind and maps every activity action", () => { + expect(planTriggerUpdate({}, { kind: "schedule", setupPending: false, lastWebhookDelivery: null }).changeSummary).toBe("Updated schedule trigger"); + expect(triggerUpdateActivityAction({ archived: true, setupPending: true })).toBe("routine.trigger_removed"); + expect(triggerUpdateActivityAction({ archived: false })).toBe("routine.trigger_restored"); + expect(triggerUpdateActivityAction({})).toBe("routine.trigger_updated"); + }); +}); diff --git a/server/src/__tests__/routines-e2e.test.ts b/server/src/__tests__/routines-e2e.test.ts index 7a89c40d61a..1901f271cd9 100644 --- a/server/src/__tests__/routines-e2e.test.ts +++ b/server/src/__tests__/routines-e2e.test.ts @@ -567,7 +567,6 @@ describeEmbeddedPostgres("routine routes end-to-end", () => { expect((await deliver("live-event")).body.id).toBe(live.body.id); expect(await db.select().from(activityLog).where(eq(activityLog.action, "routine.run_triggered"))).toHaveLength(1); expect(await db.select().from(issues)).toHaveLength(1); - expect((await request(board).patch(`/api/routine-triggers/${trigger.id}`).send({ setupPending: true })).status).toBe(400); expect((await request(board).patch(`/api/routine-triggers/${trigger.id}`).send({ archived: true })).status).toBe(200); expect((await deliver("removed-event")).status).toBe(404); expect((await request(board).get(`/api/routines/${routineId}`)).body.triggers).toHaveLength(0); @@ -583,6 +582,140 @@ describeEmbeddedPostgres("routine routes end-to-end", () => { expect((await request(board).get(`/api/routines/${routineId}`)).body.triggers).toHaveLength(2); }); + it("puts a live webhook back into test mode without starting runs and restores its last real delivery", async () => { + vi.stubEnv("PAPERCLIP_API_URL", "http://localhost:3100"); + vi.stubEnv("PAPERCLIP_IN_WORKTREE", "false"); + const { companyId, agentId, projectId, userId } = await seedFixture(); + const board = await createApp({ type: "board", source: "local_implicit", userId, isInstanceAdmin: true }); + const created = await request(board).post(`/api/companies/${companyId}/routines`).send({ + projectId, assigneeAgentId: agentId, title: "Triage alerts", description: "Look at the alert", concurrencyPolicy: "always_enqueue", + }); + expect(created.status).toBe(201); + const routineId = created.body.id; + const configured = await request(board).post(`/api/routines/${routineId}/triggers`).send({ kind: "webhook", signingMode: "bearer" }); + expect(configured.status).toBe(201); + const { trigger, secretMaterial } = configured.body; + const path = new URL(secretMaterial.webhookUrl).pathname; + const publicApp = await createApp({ type: "none" }); + const deliver = (key: string) => request(publicApp).post(path) + .set("Authorization", `Bearer ${secretMaterial.webhookSecret}`).set("Idempotency-Key", key).send({ event: "alert.fired" }); + const triggerRow = async () => (await db.select().from(routineTriggers).where(eq(routineTriggers.id, trigger.id)))[0]!; + + const live = await deliver("live-1"); + expect(live.body.status, JSON.stringify(live.body)).toBe("issue_created"); + expect(await db.select().from(issues)).toHaveLength(1); + const realDelivery = (await triggerRow()).lastWebhookDelivery!; + expect(realDelivery).toMatchObject({ status: "received", test: false }); + expect(realDelivery.previous).toBeUndefined(); + + const outsider = await createApp({ type: "board", userId: randomUUID(), source: "session", companyIds: [randomUUID()] }); + expect((await request(outsider).patch(`/api/routine-triggers/${trigger.id}`).send({ setupPending: true })).status).toBe(404); + expect((await triggerRow()).setupPending).toBe(false); + + const started = await request(board).patch(`/api/routine-triggers/${trigger.id}`).send({ setupPending: true }); + expect(started.status, JSON.stringify(started.body)).toBe(200); + expect(started.body).toMatchObject({ setupPending: true, lastWebhookDelivery: realDelivery }); + expect(await db.select().from(activityLog).where(eq(activityLog.action, "routine.trigger_test_started"))).toHaveLength(1); + const revisions = await request(board).get(`/api/routines/${routineId}/revisions`); + expect(revisions.body.map((revision: { changeSummary: string }) => revision.changeSummary)).toContain("Started testing webhook"); + + for (const key of ["test-1", "test-2"]) { + const tested = await deliver(key); + expect(tested.status, JSON.stringify(tested.body)).toBe(202); + expect(tested.body).toMatchObject({ status: "test_received", routineStarted: false, linkedIssueId: null }); + } + expect(await db.select().from(issues)).toHaveLength(1); + expect(await db.select().from(routineRuns)).toHaveLength(1); + expect((await triggerRow()).lastWebhookDelivery).toMatchObject({ + status: "received", test: true, previous: { ...realDelivery, test: false }, + }); + + const finished = await request(board).patch(`/api/routine-triggers/${trigger.id}`).send({ setupPending: false }); + expect(finished.status).toBe(200); + expect(finished.body).toMatchObject({ setupPending: false, lastWebhookDelivery: realDelivery }); + expect((await triggerRow()).lastWebhookDelivery).toEqual(realDelivery); + expect(await db.select().from(activityLog).where(eq(activityLog.action, "routine.trigger_setup_finished"))).toHaveLength(1); + expect((await request(board).get(`/api/routines/${routineId}/revisions`)).body + .map((revision: { changeSummary: string }) => revision.changeSummary)).toContain("Finished testing webhook"); + + // A sender retry of an event received during testing stays a test receipt. + expect((await deliver("test-1")).body.status).toBe("test_received"); + expect(await db.select().from(issues)).toHaveLength(1); + const next = await deliver("live-2"); + expect(next.body.status, JSON.stringify(next.body)).toBe("issue_created"); + expect(await db.select().from(issues)).toHaveLength(2); + expect((await triggerRow()).lastWebhookDelivery).toMatchObject({ status: "received", test: false }); + expect((await triggerRow()).lastWebhookDelivery?.previous).toBeUndefined(); + }); + + it("starts each test of a never-used webhook without the last test's result", async () => { + vi.stubEnv("PAPERCLIP_API_URL", "http://localhost:3100"); + vi.stubEnv("PAPERCLIP_IN_WORKTREE", "false"); + const { companyId, agentId, projectId, userId } = await seedFixture(); + const board = await createApp({ type: "board", source: "local_implicit", userId, isInstanceAdmin: true }); + const created = await request(board).post(`/api/companies/${companyId}/routines`).send({ projectId, assigneeAgentId: agentId, title: "Quiet hook" }); + const routineId = created.body.id; + const configured = await request(board).post(`/api/routines/${routineId}/triggers`).send({ kind: "webhook", signingMode: "bearer" }); + const { trigger, secretMaterial } = configured.body; + const path = new URL(secretMaterial.webhookUrl).pathname; + const publicApp = await createApp({ type: "none" }); + const triggerRow = async () => (await db.select().from(routineTriggers).where(eq(routineTriggers.id, trigger.id)))[0]!; + + expect((await request(board).patch(`/api/routine-triggers/${trigger.id}`).send({ setupPending: true })).status).toBe(200); + const tested = await request(publicApp).post(path).set("Authorization", `Bearer ${secretMaterial.webhookSecret}`) + .set("Idempotency-Key", "test-1").send({ event: "ping" }); + expect(tested.body.status).toBe("test_received"); + expect((await triggerRow()).lastWebhookDelivery).toMatchObject({ status: "received", test: true, previous: null }); + + expect((await request(board).patch(`/api/routine-triggers/${trigger.id}`).send({ setupPending: false })).status).toBe(200); + expect((await triggerRow()).lastWebhookDelivery).toBeNull(); + expect((await request(board).patch(`/api/routine-triggers/${trigger.id}`).send({ setupPending: true })).status).toBe(200); + // A new test starts clean: nothing reads as "Test event received" before an event arrives. + expect((await triggerRow()).lastWebhookDelivery).toBeNull(); + expect(await db.select().from(issues)).toHaveLength(0); + }); + + it("only starts testing on an active, enabled webhook", async () => { + vi.stubEnv("PAPERCLIP_API_URL", "http://localhost:3100"); + const { companyId, agentId, projectId, userId } = await seedFixture(); + const board = await createApp({ type: "board", source: "local_implicit", userId, isInstanceAdmin: true }); + const created = await request(board).post(`/api/companies/${companyId}/routines`).send({ + projectId, assigneeAgentId: agentId, title: "Triage alerts", description: "Look at the alert", + }); + const routineId = created.body.id; + const webhook = (await request(board).post(`/api/routines/${routineId}/triggers`).send({ kind: "webhook", signingMode: "bearer" })).body.trigger; + const schedule = (await request(board).post(`/api/routines/${routineId}/triggers`) + .send({ kind: "schedule", cronExpression: "0 9 * * 1-5", timezone: "UTC" })).body.trigger; + const startTesting = (id: string, extra: Record = {}) => + request(board).patch(`/api/routine-triggers/${id}`).send({ setupPending: true, ...extra }); + + const scheduleAttempt = await startTesting(schedule.id); + expect(scheduleAttempt.status).toBe(422); + expect(scheduleAttempt.body.error).toBe("Only webhooks can be tested"); + + const disablingAttempt = await startTesting(webhook.id, { enabled: false }); + expect(disablingAttempt.status).toBe(409); + expect((await request(board).patch(`/api/routine-triggers/${webhook.id}`).send({ enabled: false })).status).toBe(200); + const disabledAttempt = await startTesting(webhook.id); + expect(disabledAttempt.status).toBe(409); + expect(disabledAttempt.body.error).toBe("Turn the webhook on before testing it"); + await request(board).patch(`/api/routine-triggers/${webhook.id}`).send({ enabled: true }); + + await request(board).patch(`/api/routine-triggers/${webhook.id}`).send({ archived: true }); + const archivedAttempt = await startTesting(webhook.id); + expect(archivedAttempt.status).toBe(409); + expect(archivedAttempt.body.error).toBe("This webhook was removed"); + await request(board).patch(`/api/routine-triggers/${webhook.id}`).send({ archived: false }); + + await db.update(routines).set({ status: "archived" }).where(eq(routines.id, routineId)); + const archivedRoutineAttempt = await startTesting(webhook.id); + expect(archivedRoutineAttempt.status).toBe(409); + expect(archivedRoutineAttempt.body.error).toBe("This routine is archived"); + + expect((await db.select().from(routineTriggers).where(eq(routineTriggers.id, webhook.id)))[0]?.setupPending).toBe(false); + expect(await db.select().from(activityLog).where(eq(activityLog.action, "routine.trigger_test_started"))).toHaveLength(0); + }); + it("supports creating, scheduling, and manually running a routine through the API", async () => { const { companyId, agentId, projectId, userId } = await seedFixture(); const app = await createApp({ diff --git a/server/src/routes/routines.ts b/server/src/routes/routines.ts index 9612c8e5b15..d3c87823cab 100644 --- a/server/src/routes/routines.ts +++ b/server/src/routes/routines.ts @@ -1,4 +1,5 @@ import { Router, type Request } from "express"; +import { triggerUpdateActivityAction } from "../services/routine-trigger-update-plan.js"; import { listProtectedEnvironmentKeyHolders, protectedEnvironmentKeyWarnings } from "../services/protected-environment-keys.js"; import type { Db } from "@paperclipai/db"; import { @@ -561,7 +562,7 @@ export function routineRoutes( agentId: actor.agentId, runId: actor.runId, agentApiKeyId: actor.agentApiKeyId, - action: req.body.archived === true ? "routine.trigger_removed" : req.body.archived === false ? "routine.trigger_restored" : req.body.setupPending === false ? "routine.trigger_setup_finished" : "routine.trigger_updated", + action: triggerUpdateActivityAction(req.body), entityType: "routine", entityId: routine.id, details: { triggerId: trigger.id, kind: updated?.trigger.kind ?? trigger.kind }, diff --git a/server/src/services/routine-trigger-update-plan.ts b/server/src/services/routine-trigger-update-plan.ts new file mode 100644 index 00000000000..e8cc919cf04 --- /dev/null +++ b/server/src/services/routine-trigger-update-plan.ts @@ -0,0 +1,45 @@ +import type { RoutineWebhookDelivery, UpdateRoutineTrigger } from "@paperclipai/shared"; + +/** The trigger fields a plan reads, as stored. */ +export interface TriggerUpdatePlanState { + kind: string; + setupPending: boolean; + lastWebhookDelivery: RoutineWebhookDelivery | null; +} + +/** What one `PATCH /routine-triggers/:id` does to test mode, delivery status, the revision and the activity log. */ +export interface TriggerUpdatePlan { + startsTesting: boolean; + finishesTesting: boolean; + /** Ending a test puts back the last real delivery (or null), so no stale test result stays behind. */ + restoredDelivery: { value: RoutineWebhookDelivery | null } | null; + changeSummary: string; + activityAction: string; +} + +/** The activity action for a trigger update body; also used when the service is not reached. */ +export function triggerUpdateActivityAction(patch: Pick): string { + if (patch.archived === true) return "routine.trigger_removed"; + if (patch.archived === false) return "routine.trigger_restored"; + if (patch.setupPending === true) return "routine.trigger_test_started"; + if (patch.setupPending === false) return "routine.trigger_setup_finished"; + return "routine.trigger_updated"; +} + +/** Pure plan for a trigger update, so the service and the route's activity entry cannot drift. */ +export function planTriggerUpdate( + patch: Pick, + current: TriggerUpdatePlanState, +): TriggerUpdatePlan { + const startsTesting = patch.setupPending === true && !current.setupPending; + const finishesTesting = patch.setupPending === false && current.setupPending; + const last = current.lastWebhookDelivery; + // A test delivery always records `previous` (null when there was no real delivery). + const restoredDelivery = finishesTesting && last?.test && "previous" in last ? { value: last.previous ?? null } : null; + const changeSummary = startsTesting + ? "Started testing webhook" + : finishesTesting + ? restoredDelivery?.value ? "Finished testing webhook" : "Finished webhook setup or test" + : `Updated ${current.kind} trigger`; + return { startsTesting, finishesTesting, restoredDelivery, changeSummary, activityAction: triggerUpdateActivityAction(patch) }; +} diff --git a/server/src/services/routines.ts b/server/src/services/routines.ts index eaf7ba06a65..710ca0c8edf 100644 --- a/server/src/services/routines.ts +++ b/server/src/services/routines.ts @@ -49,6 +49,7 @@ import type { RoutineTrigger, RoutineTriggerSecretMaterial, RoutineVariable, + RoutineWebhookDelivery, RunRoutine, UpdateRoutine, UpdateRoutineTrigger, @@ -89,6 +90,7 @@ import { queueIssueAssignmentWakeup, type IssueAssignmentWakeupDeps } from "./is import { logActivity } from "./activity-log.js"; import type { PluginWorkerManager } from "./plugin-worker-manager.js"; import { runtimePublicOrigin } from "./cloud-runtime-identity.js"; +import { planTriggerUpdate } from "./routine-trigger-update-plan.js"; const OPEN_ISSUE_STATUSES = ["backlog", "todo", "in_progress", "in_review", "blocked"]; const LIVE_HEARTBEAT_RUN_STATUSES = ["queued", "running", "scheduled_retry"]; @@ -2794,11 +2796,21 @@ export function routineService( } } + if (patch.setupPending === true && existing.kind !== "webhook") { + throw unprocessable("Only webhooks can be tested"); + } + const result = await db.transaction(async (tx) => { const txDb = tx as unknown as Db; await tx.execute(sql`select id from ${routines} where ${routines.id} = ${existing.routineId} for update`); const current = await txDb - .select({ signingMode: routineTriggers.signingMode }) + .select({ + signingMode: routineTriggers.signingMode, + enabled: routineTriggers.enabled, + archived: routineTriggers.archived, + setupPending: routineTriggers.setupPending, + lastWebhookDelivery: routineTriggers.lastWebhookDelivery, + }) .from(routineTriggers) .where(eq(routineTriggers.id, id)) .then((rows) => rows[0] ?? null); @@ -2806,13 +2818,29 @@ export function routineService( if (existing.kind === "webhook" && current.signingMode !== "none") { assertAgentWebhookAuthenticated(actor, patch.signingMode); } + const plan = planTriggerUpdate(patch, { + kind: existing.kind, + setupPending: current.setupPending, + lastWebhookDelivery: current.lastWebhookDelivery ?? null, + }); + if (patch.setupPending === true) { + if (patch.archived ?? current.archived) throw conflict("This webhook was removed"); + if (!(patch.enabled ?? current.enabled)) throw conflict("Turn the webhook on before testing it"); + const [lockedRoutine] = await txDb + .select({ status: routines.status }) + .from(routines) + .where(eq(routines.id, existing.routineId)); + if (!lockedRoutine) throw notFound("Routine not found"); + if (lockedRoutine.status === "archived") throw conflict("This routine is archived"); + } await notifyDeliveryWork(txDb, DELIVERY_QUEUES.routineSchedules); const [updated] = await txDb .update(routineTriggers) .set({ label: patch.label === undefined ? existing.label : patch.label, enabled: patch.enabled ?? existing.enabled, - ...(patch.setupPending === false ? { setupPending: false } : {}), + ...(patch.setupPending !== undefined ? { setupPending: patch.setupPending } : {}), + ...(plan.restoredDelivery ? { lastWebhookDelivery: plan.restoredDelivery.value } : {}), ...(patch.archived !== undefined ? { archived: patch.archived } : {}), cronExpression, timezone, @@ -2832,9 +2860,7 @@ export function routineService( .where(eq(routines.id, existing.routineId)) .then((rows) => rows[0] ?? null); if (!routine) throw notFound("Routine not found"); - const appended = await appendRoutineRevision(txDb, routine, actor, { - changeSummary: `Updated ${existing.kind} trigger`, - }); + const appended = await appendRoutineRevision(txDb, routine, actor, { changeSummary: plan.changeSummary }); return { trigger: updated as RoutineTrigger, revision: appended.revision }; }); return result; @@ -3172,7 +3198,12 @@ export function routineService( if (!trigger.enabled || (!trigger.setupPending && routine.status !== "active")) throw conflict("Routine trigger is not active"); const recordDelivery = async (status: "received" | "rejected") => { const receivedAt = new Date().toISOString(); - await txDb.update(routineTriggers).set({ lastWebhookDelivery: { status, receivedAt, test: trigger.setupPending } }).where(eq(routineTriggers.id, trigger.id)); + const last = trigger.lastWebhookDelivery; + // While testing, carry the last real delivery so finishing the test can restore it. + const delivery: RoutineWebhookDelivery = trigger.setupPending + ? { status, receivedAt, test: true, previous: last ? (last.test ? last.previous ?? null : last) : null } + : { status, receivedAt, test: false }; + await txDb.update(routineTriggers).set({ lastWebhookDelivery: delivery }).where(eq(routineTriggers.id, trigger.id)); await logActivity(txDb, { companyId: routine.companyId, actorType: "system", actorId: "routine-webhook", action: trigger.setupPending ? `routine.webhook_test_${status}` : `routine.webhook_${status}`, diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 34505c1d108..ff6d1b3b0be 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -438,7 +438,7 @@ "packages/shared/src/types/quota.ts": "a0686a9afb3111a4de093f66200dc0c9152e883e", "packages/shared/src/types/resource-memberships.ts": "9eab6fad50facf3e489f8c40e5bedd92e1d1faf8", "packages/shared/src/types/responsibility.ts": "2a0f0dafdca5daa7b49f7e66ebf4fa551a870f69", - "packages/shared/src/types/routine.ts": "850fdeb686d2dfcab190811cede79ee5d66be689", + "packages/shared/src/types/routine.ts": "6b2f2fd27187c19f98afe99f926460ded2752f20", "packages/shared/src/types/runtime-exposure.ts": "785f053a7ad5448cde94f36738cdb90585bbc92e", "packages/shared/src/types/search.ts": "4e208a9b1942991bfe5f29ef58ec71625e2693e9", "packages/shared/src/types/secrets.ts": "05b07bce0550c1b3a160615bed661bc7f9c26156", @@ -524,7 +524,7 @@ "packages/shared/src/validators/resource-memberships.ts": "b124ac8a8f24b4dbb03ae82bcc87541f6b4ecdfd", "packages/shared/src/validators/responsibility.ts": "4cb056a0d4da3622ba7ddc50fbcd9673e7de35fc", "packages/shared/src/validators/routine.test.ts": "1501907ade577c1ab4c4b3098397e5d080446878", - "packages/shared/src/validators/routine.ts": "05bb57f404c5345179b54c9fdfeb64a0ffa8673a", + "packages/shared/src/validators/routine.ts": "95f04abf9cbafad8ad121ece7642b8cba1a6eb36", "packages/shared/src/validators/runtime-exposure.test.ts": "31175388dbab9f3d5dba920cd711ea6e0e6c6ece", "packages/shared/src/validators/runtime-exposure.ts": "362cfc4721581beb4f495987bde60028e6f390f0", "packages/shared/src/validators/search.ts": "3b81dae383682c42f0582b644009b520da4031dc", diff --git a/tests/storybook-visual/fireflies-pr.spec.ts b/tests/storybook-visual/fireflies-pr.spec.ts index 573bc173c56..9fb97483dc5 100644 --- a/tests/storybook-visual/fireflies-pr.spec.ts +++ b/tests/storybook-visual/fireflies-pr.spec.ts @@ -22,14 +22,14 @@ test("every PR surface renders and completes its Storybook interactions", async await page.close(); }); -test("mobile setup keeps its footer reachable without horizontal overflow", async ({ page }) => { +test("mobile setup keeps the new key and its footer reachable without horizontal overflow", async ({ page }) => { await page.setViewportSize({ width: 390, height: 844 }); await page.goto(`/iframe.html?id=${prefix}mobile-setup&viewMode=story`); - const next = page.getByRole("button", { name: "Check connection", exact: true }); - await next.scrollIntoViewIfNeeded(); - await expect(next).toBeVisible(); - await expect(page.getByRole("button", { name: "Save & exit" })).toBeVisible(); + await expect(page.getByRole("button", { name: "Copy Secret key", exact: true })).toBeVisible(); + const finish = page.getByRole("button", { name: "Finish without testing", exact: true }); + await finish.scrollIntoViewIfNeeded(); + await expect(finish).toBeVisible(); expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true); - await next.click(); - await expect(page.getByRole("heading", { name: "Check your connection" })).toBeVisible(); + await finish.click(); + await expect(page.getByText(/No webhook was saved/)).toBeVisible(); }); diff --git a/tests/storybook-visual/project-repository-skills.spec.ts b/tests/storybook-visual/project-repository-skills.spec.ts index 38c6e49e9a9..6debd3323e3 100644 --- a/tests/storybook-visual/project-repository-skills.spec.ts +++ b/tests/storybook-visual/project-repository-skills.spec.ts @@ -85,33 +85,34 @@ test('empty repositories explain automatic discovery of future skills', async ({ test('routine instructions stay stable while new executions follow updated skill content', async ({ page }) => { await page.goto(story('routine-reference')); - const description = page.getByRole('region', { name: 'Description', exact: true }); + const description = page.locator('section').filter({ has: page.getByRole('heading', { name: 'Instructions', exact: true }) }); + const tasks = page.getByRole('list', { name: 'Tasks created by this routine', exact: true }); await expect(description.getByRole('link', { name: '/code-review', exact: true })).toBeVisible(); const instructions = await description.innerText(); await page.getByRole('button', { name: 'Run now', exact: true }).click(); await page.getByRole('button', { name: 'Run routine', exact: true }).click(); - await page.getByRole('link', { name: 'Open PAP-124: Review project changes', exact: true }).click(); + await tasks.getByRole('link', { name: 'Open PAP-124: Review project changes', exact: true }).click(); const outcome = page.getByText(/^Completed using code review version /); await expect(outcome).toContainText('version-entry-1 at commit a17d36'); await expect(outcome).toBeVisible(); const first = await outcome.textContent() ?? ''; expect(first).toContain('version-entry-1 at commit a17d36'); await expect(page.getByRole('alert')).toHaveCount(0); + await page.getByRole('button', { name: 'More workspace pages', exact: true }).click(); await page.getByRole('link', { name: 'Skills', exact: true }).click(); await page.getByLabel('Skills', { exact: true }).getByRole('link', { name: 'Sources', exact: true }).click(); await page.getByRole('region', { name: 'acme/team-skills', exact: true }).getByRole('button', { name: 'Refresh', exact: true }).click(); await expect(page.getByText('Security review', { exact: true })).toBeVisible(); + await page.getByRole('button', { name: 'More workspace pages', exact: true }).click(); await page.getByRole('link', { name: 'Routines', exact: true }).click(); await page.getByRole('main').getByText('Review project changes', { exact: true }).click(); - await page.getByLabel('Routine navigation', { exact: true }).getByRole('link', { name: 'Overview', exact: true }).click(); await expect(description).toHaveText(instructions, { useInnerText: true }); await page.getByRole('button', { name: 'Run now', exact: true }).click(); await page.getByRole('button', { name: 'Run routine', exact: true }).click(); - await page.getByRole('link', { name: 'Open PAP-125: Review project changes', exact: true }).click(); + await tasks.getByRole('link', { name: 'Open PAP-125: Review project changes', exact: true }).click(); await expect(outcome).toContainText('version-entry-1-updated at commit bbbbbbbb'); - await page.getByRole('link', { name: 'Routine', exact: true }).click(); - await page.getByLabel('Routine navigation', { exact: true }).getByRole('link', { name: 'Runs', exact: true }).click(); - await page.getByRole('link', { name: 'Open PAP-124: Review project changes', exact: true }).click(); + await page.goBack(); + await tasks.getByRole('link', { name: 'Open PAP-124: Review project changes', exact: true }).click(); await expect(outcome).toHaveText(first); }); diff --git a/ui/src/App.tsx b/ui/src/App.tsx index 3d4d3adf77d..4de1a8fea09 100644 --- a/ui/src/App.tsx +++ b/ui/src/App.tsx @@ -144,7 +144,6 @@ const CompanyExport = lazy(() => import("./pages/CompanyExport").then((module) = const ProductionAgents = lazy(() => import("./pages/Agents.production").then((module) => ({ default: module.Agents }))); const ProductionRoutines = lazy(() => import("./pages/Routines.production").then((module) => ({ default: module.Routines }))); -const ProductionRoutineDetail = lazy(() => import("./pages/RoutineDetail.production").then((module) => ({ default: module.RoutineDetail }))); const ProductionCompanySkills = lazy(() => import("./pages/CompanySkills.production").then((module) => ({ default: module.CompanySkills }))); const ProductionCompanyActivity = lazy(() => import("./pages/audit/CompanyActivity.production").then((module) => ({ default: module.CompanyActivity }))); const ProductionOrgChart = lazy(() => import("./pages/OrgChart.production").then((module) => ({ default: module.OrgChart }))); @@ -368,8 +367,9 @@ function boardRoutes(streamlinedUiEnabled: boolean, combinedInboxTasksEnabled: b {/* Back-compat: the board lived at /status-cards before PAP-15223. */} } /> } /> - : } /> - : } /> + {/* One routine page in both shells; older section addresses redirect inside it. */} + } /> + } /> }> }> } /> diff --git a/ui/src/api/responsibilities.ts b/ui/src/api/responsibilities.ts index 2715179d7b4..d134b5cb261 100644 --- a/ui/src/api/responsibilities.ts +++ b/ui/src/api/responsibilities.ts @@ -9,6 +9,7 @@ import type { ResponsibilityDelegationResult, ResponsibilityDetail, ResponsibilityLink, + ResponsibilityLinkLookupResult, ResponsibilityOverview, ResponsibilityStatusReportState, ResponsibilityStatusReportsOverview, @@ -73,6 +74,11 @@ export const responsibilitiesApi = { api.delete( `/responsibilities/${encodeURIComponent(id)}/links/${encodeURIComponent(linkId)}`, ), + /** The responsibilities a routine is under, directly or through its project. */ + lookupRoutineLinks: (companyId: string, routineId: string) => + api.get( + `/companies/${encodeURIComponent(companyId)}/responsibility-links/lookup?${new URLSearchParams({ routineId })}`, + ), delegate: (id: string, data: DelegateResponsibility) => api.post(`/responsibilities/${encodeURIComponent(id)}/delegate`, data), /** The agent-written status of every active responsibility the owner (default: the acting user) holds, in one read. */ diff --git a/ui/src/components/InlineEntitySelector.tsx b/ui/src/components/InlineEntitySelector.tsx index 8fccd9c3272..6653f3e9e87 100644 --- a/ui/src/components/InlineEntitySelector.tsx +++ b/ui/src/components/InlineEntitySelector.tsx @@ -20,6 +20,8 @@ interface InlineEntitySelectorProps { noneAtTop?: boolean; /** Keep the no-selection action after the project choices. */ noneAtEnd?: boolean; + /** Leave out the no-selection action, for a value that can be changed but not cleared. */ + hideNone?: boolean; searchPlaceholder: string; emptyMessage: string; onChange: (id: string) => void; @@ -76,6 +78,7 @@ export const InlineEntitySelector = forwardRef(() => { + if (hideNone) return orderItemsBySelectedAndRecent([...options], value, recentOptionIds); const baseOptions = [{ id: "", label: noneLabel, searchText: noneLabel }, ...options]; const ordered = orderItemsBySelectedAndRecent(baseOptions, value, recentOptionIds); if (noneAtTop) return [baseOptions[0]!, ...ordered.filter((option) => option.id)]; return noneAtEnd ? [...ordered.filter((option) => option.id), baseOptions[0]!] : ordered; - }, [noneAtEnd, noneAtTop, noneLabel, options, recentOptionIds, value]); + }, [hideNone, noneAtEnd, noneAtTop, noneLabel, options, recentOptionIds, value]); const filteredOptions = useMemo(() => { const term = query.trim().toLowerCase(); diff --git a/ui/src/components/Layout.test.tsx b/ui/src/components/Layout.test.tsx index c8f34664b13..bc5a4304c19 100644 --- a/ui/src/components/Layout.test.tsx +++ b/ui/src/components/Layout.test.tsx @@ -102,12 +102,6 @@ vi.mock("./AgentContextualSidebar", () => ({ ), })); -vi.mock("./RoutineContextualSidebar", () => ({ - RoutineContextualSidebar: ({ routineId }: { routineId: string }) => ( -
Routine sidebar {routineId}
- ), -})); - vi.mock("./SkillsContextualSidebar", () => ({ SkillsContextualSidebar: () =>
Skills sidebar
, })); @@ -885,7 +879,7 @@ describe("Layout", () => { }); }); - it("keeps global navigation beside Agent and Routine details", async () => { + it("keeps global navigation beside Agent details", async () => { async function renderAt(pathname: string) { currentPathname = pathname; const root = createRoot(container); @@ -907,7 +901,6 @@ describe("Layout", () => { "/PAP/agents/briefing-analyst/runs/run-1", "Agent sidebar briefing-analyst", ], - ["/PAP/routines/routine-1/overview", "Routine sidebar routine-1"], ] as const) { const root = await renderAt(pathname); expect(container.textContent).toContain(sidebarText); @@ -957,7 +950,7 @@ describe("Layout", () => { expect(container.textContent).toContain("Main company nav"); if (pathname.includes("/agents/")) expect(container.textContent).toContain("Agent sidebar"); else expect(container.textContent).not.toContain("Agent sidebar"); - expect(container.textContent).not.toContain("Routine sidebar"); + if (pathname.includes("/routines/")) expect(container.querySelector("[data-secondary-sidebar]")).toBeNull(); await act(async () => { root.unmount(); @@ -1027,7 +1020,7 @@ describe("Layout", () => { expect(container.textContent).toContain("Main company nav"); expect(container.textContent).not.toContain("Agent sidebar"); - expect(container.textContent).not.toContain("Routine sidebar"); + if (pathname.includes("/routines/")) expect(container.querySelector("[data-secondary-sidebar]")).toBeNull(); await act(async () => { root.unmount(); diff --git a/ui/src/components/Layout.tsx b/ui/src/components/Layout.tsx index f6e03ad0ce3..ea49a7340c4 100644 --- a/ui/src/components/Layout.tsx +++ b/ui/src/components/Layout.tsx @@ -5,7 +5,6 @@ import { useBrowserTimeZoneSync } from "@/hooks/useBrowserTimeZoneSync"; import { useDesignSandbox } from "@/context/DesignSandboxContext"; import { DesignSandboxSidebar } from "./DesignSandboxSidebar"; import { BoardDialogs } from "./BoardDialogs"; -import { SetupWizardSidebarOutlet } from "./SetupWizard"; import { ChatSetupSidebarProvider } from "@/context/ChatSetupSidebarContext"; import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react"; import { useQuery } from "@tanstack/react-query"; @@ -16,7 +15,6 @@ import { CompanySettingsNav } from "./access/CompanySettingsNav"; import { AppsSidebar, AppsMobileNav } from "./AppsSidebar"; import { AppDetailSidebar } from "./AppConnectionSidebar"; import { AgentContextualSidebar } from "./AgentContextualSidebar"; -import { RoutineContextualSidebar } from "./RoutineContextualSidebar"; import { SkillsContextualSidebar } from "./SkillsContextualSidebar"; import { BreadcrumbBar } from "./BreadcrumbBar"; import { PropertiesPanel } from "./PropertiesPanel"; @@ -109,12 +107,10 @@ export function Layout({ sidebarSections }: { sidebarSections?: ReactNode }) { companyPrefix, pluginRoutePath: matchedPluginRoutePath, agentId, - routineId, } = useParams<{ companyPrefix: string; pluginRoutePath?: string; agentId?: string; - routineId?: string; }>(); const navigate = useNavigate(); const location = useLocation(); @@ -220,14 +216,11 @@ export function Layout({ sidebarSections }: { sidebarSections?: ReactNode }) { ) : null; const secondarySidebar = isAgentChatRoute ? : shellRoute.builtInContextualSurface === "agent" && agentId ? ( - ) : streamlinedUiEnabled && shellRoute.builtInContextualSurface === "routine" && routineId ? ( - ) : sharedSecondarySidebar; const hasSecondarySidebar = secondarySidebar != null; const keepsPrimarySidebar = streamlinedUiEnabled && hasSecondarySidebar && ( isAgentChatRoute || shellRoute.builtInContextualSurface === "agent" - || shellRoute.builtInContextualSurface === "routine" || isAppsRoute || isToolsRoute ); diff --git a/ui/src/components/RoutineActivityRow.tsx b/ui/src/components/RoutineActivityRow.tsx index e236047923e..5129c6b88fd 100644 --- a/ui/src/components/RoutineActivityRow.tsx +++ b/ui/src/components/RoutineActivityRow.tsx @@ -47,7 +47,7 @@ const actionLabels: Record = { "routine.webhook_rejected": "Webhook authentication failed", "routine.created": "Routine created", "routine.updated": "Routine updated", "routine.trigger_created": "Trigger added", "routine.trigger_updated": "Trigger updated", - "routine.trigger_deleted": "Trigger removed", "routine.trigger_removed": "Trigger removed", "routine.trigger_restored": "Trigger restored", "routine.trigger_setup_finished": "Webhook setup finished", "routine.trigger_secret_rotated": "Webhook key replaced", + "routine.trigger_deleted": "Trigger removed", "routine.trigger_removed": "Trigger removed", "routine.trigger_restored": "Trigger restored", "routine.trigger_setup_finished": "Webhook setup finished", "routine.trigger_test_started": "Started testing a webhook", "routine.trigger_secret_rotated": "Webhook key replaced", "routine.run_triggered": "Routine started", "routine.run_created": "Run created", }; function actionLabel(action: string) { diff --git a/ui/src/components/RoutineContextualSidebar.test.tsx b/ui/src/components/RoutineContextualSidebar.test.tsx deleted file mode 100644 index 888591c53d8..00000000000 --- a/ui/src/components/RoutineContextualSidebar.test.tsx +++ /dev/null @@ -1,114 +0,0 @@ -// @vitest-environment jsdom - -import type { ReactNode } from "react"; -import { flushSync } from "react-dom"; -import { createRoot, type Root } from "react-dom/client"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { - RoutineContextualSidebar, - resolveRoutineDetailDestination, - routineDetailHref, -} from "./RoutineContextualSidebar"; - -vi.mock("@/lib/router", () => ({ - useParams: () => ({ routineId: "routine-route" }), -})); - -vi.mock("@/api/routines", () => ({ - routinesApi: { get: vi.fn() }, -})); - -vi.mock("./ContextualSidebarFrame", () => ({ - ContextualSidebarFrame: ({ - surface, - title, - fallbackTo, - showHeader, - className, - children, - }: { - surface: string; - title: string; - fallbackTo: string; - showHeader?: boolean; - className?: string; - children: ReactNode; - }) => ( - - ), -})); - -vi.mock("./SidebarNavItem", () => ({ - SidebarNavItem: ({ to, label }: { to: string; label: string }) => {label}, -})); - -describe("routine contextual navigation", () => { - let container: HTMLDivElement; - let root: Root; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - }); - - afterEach(() => { - flushSync(() => root.unmount()); - container.remove(); - }); - - it("builds stable routine detail destinations", () => { - expect(routineDetailHref("routine-1")).toBe("/routines/routine-1/overview"); - expect(routineDetailHref("routine-1", "triggers")).toBe("/routines/routine-1/triggers"); - expect(routineDetailHref("routine-1", "runs")).toBe( - "/routines/routine-1/runs", - ); - expect(routineDetailHref("routine-1", "activity")).toBe( - "/routines/routine-1/activity", - ); - }); - - it("defaults and resolves legacy operation routes locally without remembering a prior section", () => { - expect(resolveRoutineDetailDestination({ routineId: "routine-1" })) - .toBe("/routines/routine-1/overview"); - expect(resolveRoutineDetailDestination({ routineId: "routine-1", section: "unknown" })) - .toBe("/routines/routine-1/overview"); - expect(resolveRoutineDetailDestination({ routineId: "routine-1", section: "runs" })) - .toBe("/routines/routine-1/runs"); - expect(resolveRoutineDetailDestination({ routineId: "routine-1", legacyTab: "activity" })) - .toBe("/routines/routine-1/activity"); - }); - - it("renders the routine contextual sidebar with configuration and operation links", () => { - const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); - flushSync(() => root.render( - - - , - )); - - const frame = container.querySelector("aside"); - expect(frame?.getAttribute("data-surface")).toBe("routine"); - expect(frame?.getAttribute("data-title")).toBe("Weekly release review"); - expect(frame?.getAttribute("data-fallback")).toBe("/routines"); - expect(frame?.getAttribute("data-show-header")).toBe("false"); - expect(frame?.classList).toContain("bg-background"); - expect(frame?.classList).toContain("border-r"); - expect(container.querySelector('a[href="/routines/routine-1/overview"]')?.textContent).toBe("Overview"); - expect(container.querySelector('a[href="/routines/routine-1/triggers"]')?.textContent).toBe("Triggers"); - expect(container.querySelector('a[href="/routines/routine-1/runs"]')) - .not.toBeNull(); - expect(container.querySelector('a[href="/routines/routine-1/activity"]')) - .not.toBeNull(); - expect(container.textContent).not.toContain("History"); - }); -}); diff --git a/ui/src/components/RoutineContextualSidebar.tsx b/ui/src/components/RoutineContextualSidebar.tsx deleted file mode 100644 index 4e562e10226..00000000000 --- a/ui/src/components/RoutineContextualSidebar.tsx +++ /dev/null @@ -1,121 +0,0 @@ -import { useQuery } from "@tanstack/react-query"; -import { - Activity, - Braces, - CalendarClock, - KeyRound, - LayoutDashboard, - Play, - Repeat, - Send, - type LucideIcon, -} from "lucide-react"; -import { routinesApi } from "@/api/routines"; -import { queryKeys } from "@/lib/queryKeys"; -import { useParams } from "@/lib/router"; -import { ContextualSidebarFrame } from "./ContextualSidebarFrame"; -import { SidebarNavItem } from "./SidebarNavItem"; - -export const ROUTINE_DETAIL_VIEWS = [ - "overview", - "triggers", - "variables", - "delivery", - "secrets", - "history", - "runs", - "activity", -] as const; - -export type RoutineDetailView = (typeof ROUTINE_DETAIL_VIEWS)[number]; - -export type RoutineContextualNavItem = { - view: Exclude; - label: string; - icon: LucideIcon; -}; - -export const ROUTINE_CONTEXTUAL_NAV_ITEMS: readonly RoutineContextualNavItem[] = [ - { view: "overview", label: "Overview", icon: LayoutDashboard }, - { view: "triggers", label: "Triggers", icon: CalendarClock }, - { view: "variables", label: "Variables", icon: Braces }, - { view: "delivery", label: "Delivery", icon: Send }, - { view: "secrets", label: "Secrets", icon: KeyRound }, -]; - -export function isRoutineDetailView(value: string | null | undefined): value is RoutineDetailView { - return ROUTINE_DETAIL_VIEWS.includes(value as RoutineDetailView); -} - -export function routineDetailHref(routineId: string, view: RoutineDetailView = "overview") { - return `/routines/${routineId}/${view}`; -} - -/** Keep routine configuration and operations in the routine detail shell. */ -export function resolveRoutineDetailDestination(input: { - routineId: string; - section?: string | null; - legacyTab?: string | null; -}) { - const requested = input.legacyTab ?? input.section; - if (isRoutineDetailView(requested)) return routineDetailHref(input.routineId, requested); - return routineDetailHref(input.routineId, "overview"); -} - -export function RoutineContextualSidebar({ - routineId: routineIdProp, - title, -}: { - routineId?: string; - title?: string; -} = {}) { - const params = useParams<{ routineId?: string }>(); - const routineId = routineIdProp ?? params.routineId ?? ""; - const { data: routine } = useQuery({ - queryKey: queryKeys.routines.detail(routineId), - queryFn: () => routinesApi.get(routineId), - enabled: Boolean(routineId && !title), - }); - const frameTitle = title ?? routine?.title ?? "Routine"; - - return ( - - - - ); -} diff --git a/ui/src/components/RoutineOverview.test.tsx b/ui/src/components/RoutineOverview.test.tsx deleted file mode 100644 index 2562a0e1100..00000000000 --- a/ui/src/components/RoutineOverview.test.tsx +++ /dev/null @@ -1,213 +0,0 @@ -// @vitest-environment jsdom - -import type { ReactNode } from "react"; -import { flushSync } from "react-dom"; -import { createRoot, type Root } from "react-dom/client"; -import type { RoutineDetail, RoutineRunSummary } from "@paperclipai/shared"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { RoutineDetailContext, type RoutineDetailContextValue } from "./routine-sections/context"; -import { - RoutineOverview, - routineRunIssue, - summarizeRoutineSchedule, -} from "./RoutineOverview"; - -const issueRowRender = vi.hoisted(() => vi.fn()); - -vi.mock("./RoutineResponsibleUser", () => ({ - RoutineResponsibleUser: ({ routine }: { routine: RoutineDetail }) =>
Responsible user
, -})); - -vi.mock("@/components/IssueRow", () => ({ - IssueRow: (props: { issue: { title: string }; presentation?: string }) => { - issueRowRender(props); - return
{props.issue.title}
; - }, -})); - -vi.mock("@/components/MarkdownBody", () => ({ - MarkdownBody: ({ children }: { children: string }) =>
{children}
, -})); - -vi.mock("@/lib/router", () => ({ - Link: ({ to, children, ...props }: { to: string; children: ReactNode }) => ( - {children} - ), -})); - -const triggeredAt = new Date("2026-08-31T16:00:00.000Z"); -const run: RoutineRunSummary = { - id: "run-1", - companyId: "company-1", - routineId: "routine-1", - triggerId: "trigger-1", - source: "schedule", - status: "succeeded", - triggeredAt, - idempotencyKey: null, - triggerPayload: null, - dispatchFingerprint: null, - linkedIssueId: "issue-1", - coalescedIntoRunId: null, - failureReason: null, - completedAt: triggeredAt, - createdAt: triggeredAt, - updatedAt: triggeredAt, - trigger: { id: "trigger-1", kind: "schedule", label: "weekday" }, - linkedIssue: { - id: "issue-1", - identifier: "PAP-42", - title: "Prepare the release digest", - status: "done", - priority: "high", - updatedAt: triggeredAt, - }, -}; - -const routine = { - id: "routine-1", - companyId: "company-1", - projectId: "project-1", - folderId: null, - goalId: null, - parentIssueId: null, - title: "Weekly release review", - description: "Summarize **release readiness** for the operator.", - assigneeAgentId: "agent-1", - priority: "medium", - status: "active", - concurrencyPolicy: "coalesce_if_active", - catchUpPolicy: "skip_missed", - activityGatePolicy: "always", - activityGateScope: "company", - variables: [], - env: { PRIVATE_TOKEN: { type: "secret_ref", secretId: "secret-1" } }, - latestRevisionId: "revision-1", - latestRevisionNumber: 1, - createdByAgentId: null, - createdByUserId: null, - responsibleUserId: null, - updatedByAgentId: null, - updatedByUserId: null, - lastTriggeredAt: triggeredAt, - lastEnqueuedAt: triggeredAt, - createdAt: triggeredAt, - updatedAt: triggeredAt, - project: null, - assignee: { id: "agent-1", name: "Release Manager", role: "manager", title: null, urlKey: "release-manager" }, - parentIssue: null, - triggers: [{ - id: "trigger-1", - companyId: "company-1", - routineId: "routine-1", - kind: "schedule", - label: "weekday", - enabled: true, - cronExpression: "0 9 * * 1-5", - timezone: "America/Los_Angeles", - nextRunAt: new Date("2026-09-01T16:00:00.000Z"), - lastFiredAt: triggeredAt, - publicId: null, - secretId: null, - signingMode: null, - replayWindowSec: null, - lastRotatedAt: null, - lastResult: "succeeded", - createdByAgentId: null, - createdByUserId: null, - updatedByAgentId: null, - updatedByUserId: null, - createdAt: triggeredAt, - updatedAt: triggeredAt, - }], - recentRuns: [run], - activeIssue: null, -} as RoutineDetail; - -function contextFixture(): RoutineDetailContextValue { - return { - routine, - routineId: routine.id, - companyId: routine.companyId, - routineRuns: [run], - currentAssignee: { - id: "agent-1", - name: "Release Manager", - urlKey: "release-manager", - }, - hasLiveRun: false, - } as RoutineDetailContextValue; -} - -describe("RoutineOverview", () => { - let container: HTMLDivElement; - let root: Root; - - beforeEach(() => { - issueRowRender.mockClear(); - vi.spyOn(Date, "now").mockReturnValue(new Date("2026-08-31T17:00:00.000Z").getTime()); - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - }); - - afterEach(() => { - flushSync(() => root.unmount()); - container.remove(); - vi.restoreAllMocks(); - }); - - it("summarizes enabled schedules and their next run", () => { - expect(summarizeRoutineSchedule(routine.triggers)).toMatchObject({ - label: "1 active schedule", - detail: "0 9 * * 1-5 · America/Los_Angeles", - nextRunAt: new Date("2026-09-01T16:00:00.000Z"), - }); - expect(summarizeRoutineSchedule([{ ...routine.triggers[0]!, enabled: false }])).toEqual({ - label: "No active schedule", - detail: "Manual runs only", - nextRunAt: null, - }); - }); - - it("describes webhook-only routines as externally triggered", () => { - expect(summarizeRoutineSchedule([{ ...routine.triggers[0]!, kind: "webhook", enabled: true }])).toEqual({ - label: "1 active webhook", detail: "Runs on incoming requests", nextRunAt: null, - }); - }); - - it("adapts compact run tasks to the canonical task presentation", () => { - const issue = routineRunIssue(run.linkedIssue!, run, "company-1", "project-1"); - expect(issue).toMatchObject({ - id: "issue-1", - companyId: "company-1", - projectId: "project-1", - status: "done", - priority: "high", - originKind: "routine_execution", - originId: "routine-1", - originRunId: "run-1", - }); - }); - - it("shows operational facts, readable description, agent, and recent task rows without secrets", () => { - flushSync(() => root.render( - - - , - )); - - expect(container.textContent).toContain("1 active schedule"); - expect(container.textContent).toContain("Next run"); - expect(container.textContent).toContain("Release Manager"); - expect(container.textContent).toContain("Summarize **release readiness** for the operator."); - expect(container.textContent).toContain("Prepare the release digest"); - expect(container.textContent).not.toContain("PRIVATE_TOKEN"); - expect(container.textContent).not.toContain("secret-1"); - expect(issueRowRender).toHaveBeenCalledWith(expect.objectContaining({ presentation: "task" })); - expect(container.querySelector('a[href="/routines/routine-1/runs"]')) - .not.toBeNull(); - expect(container.querySelector('a[href="/routines/routine-1/activity"]')) - .not.toBeNull(); - }); -}); diff --git a/ui/src/components/RoutineOverview.tsx b/ui/src/components/RoutineOverview.tsx deleted file mode 100644 index 625573e2044..00000000000 --- a/ui/src/components/RoutineOverview.tsx +++ /dev/null @@ -1,263 +0,0 @@ -import type { - Issue, - IssuePriority, - IssueStatus, - RoutineRunSummary, - RoutineTrigger, -} from "@paperclipai/shared"; -import { ISSUE_PRIORITIES, ISSUE_STATUSES } from "@paperclipai/shared"; -import { CalendarClock, Clock3, Play, Repeat, UserRound } from "lucide-react"; -import { IssueRow } from "@/components/IssueRow"; -import { MarkdownBody } from "@/components/MarkdownBody"; -import { StatusBadge } from "@/components/StatusBadge"; -import { Button } from "@/components/ui/button"; -import { createIssueDetailLocationState } from "@/lib/issueDetailBreadcrumb"; -import { Link } from "@/lib/router"; -import { - routineDetailHref, -} from "./RoutineContextualSidebar"; -import { useRoutineDetail } from "./routine-sections/context"; -import { RoutineResponsibleUser } from "./RoutineResponsibleUser"; - -export type RoutineScheduleSummary = { - label: string; - detail: string; - nextRunAt: Date | null; -}; - -export function formatRoutineTimestamp(value: Date | string) { - return new Date(value).toLocaleString(undefined, { - dateStyle: "medium", - timeStyle: "short", - }); -} - -export function summarizeRoutineSchedule(triggers: RoutineTrigger[]): RoutineScheduleSummary { - const schedules = triggers.filter((trigger) => trigger.kind === "schedule" && trigger.enabled); - const nextRunAt = schedules - .map((trigger) => trigger.nextRunAt ? new Date(trigger.nextRunAt) : null) - .filter((value): value is Date => value !== null && Number.isFinite(value.getTime())) - .sort((left, right) => left.getTime() - right.getTime())[0] ?? null; - - if (schedules.length === 0) { - const webhooks = triggers.filter((trigger) => trigger.kind === "webhook" && trigger.enabled); - if (webhooks.length > 0) { - return { - label: `${webhooks.length} active webhook${webhooks.length === 1 ? "" : "s"}`, - detail: "Runs on incoming requests", - nextRunAt: null, - }; - } - if (triggers.some((trigger) => trigger.kind === "heartbeat" && trigger.enabled)) { - return { label: "Standing check", detail: "Carried out on each of the agent's wake-ups", nextRunAt: null }; - } - return { label: "No active schedule", detail: "Manual runs only", nextRunAt: null }; - } - - const first = schedules[0]!; - return { - label: schedules.length === 1 ? "1 active schedule" : `${schedules.length} active schedules`, - detail: first.cronExpression - ? `${first.cronExpression}${first.timezone ? ` · ${first.timezone}` : ""}` - : first.label ?? "Scheduled trigger", - nextRunAt, - }; -} - -function normalizeIssueStatus(value: string): IssueStatus { - return ISSUE_STATUSES.includes(value as IssueStatus) ? value as IssueStatus : "todo"; -} - -function normalizeIssuePriority(value: string): IssuePriority { - return ISSUE_PRIORITIES.includes(value as IssuePriority) ? value as IssuePriority : "medium"; -} - -/** Display-only adapter for the canonical task row; run summaries intentionally carry compact task data. */ -export function routineRunIssue( - summary: NonNullable, - run: RoutineRunSummary, - companyId: string, - projectId: string | null, -): Issue { - return { - ...summary, - companyId, - projectId, - projectWorkspaceId: null, - goalId: null, - parentId: null, - description: null, - status: normalizeIssueStatus(summary.status), - workMode: "standard", - priority: normalizeIssuePriority(summary.priority), - reviewPolicy: null, - assigneeAgentId: null, - assigneeUserId: null, - checkoutRunId: null, - executionRunId: null, - executionAgentNameKey: null, - executionLockedAt: null, - createdByAgentId: null, - createdByUserId: null, - responsibleUserId: null, - issueNumber: null, - originKind: "routine_execution", - originId: run.routineId, - originRunId: run.id, - requestDepth: 0, - billingCode: null, - assigneeAdapterOverrides: null, - executionWorkspaceId: null, - executionWorkspacePreference: null, - executionWorkspaceSettings: null, - startedAt: null, - completedAt: null, - cancelledAt: null, - hiddenAt: null, - createdAt: run.triggeredAt, - }; -} - -function OverviewFact({ - icon: Icon, - label, - value, - detail, -}: { - icon: typeof Clock3; - label: string; - value: React.ReactNode; - detail?: React.ReactNode; -}) { - return ( -
-
-
-
{value}
- {detail ?
{detail}
: null} -
- ); -} - -export function RoutineOverview() { - const { routine, routineRuns, currentAssignee, hasLiveRun } = useRoutineDetail(); - const schedule = summarizeRoutineSchedule(routine.triggers); - const hasWebhook = routine.triggers.some((trigger) => trigger.kind === "webhook" && trigger.enabled); - const sortedRuns = [...(routineRuns ?? [])].sort( - (left, right) => new Date(right.triggeredAt).getTime() - new Date(left.triggeredAt).getTime(), - ); - const lastRun = sortedRuns[0] ?? null; - const recentRuns = sortedRuns.slice(0, 5); - const detailOrigin = createIssueDetailLocationState( - routine.title, - routineDetailHref(routine.id), - "issues", - ); - const automationState = routine.status === "archived" - ? "archived" - : !routine.assigneeAgentId - ? "draft" - : routine.status; - - return ( -
-
- } - detail={hasLiveRun ? "A run is active now" : "No active run"} - /> - {schedule.detail}} - /> - - : "No runs yet"} - detail={lastRun ? formatRoutineTimestamp(lastRun.triggeredAt) : "Run manually or wait for a trigger"} - /> -
- -
-
-

Default agent

- {currentAssignee ? ( - -
- -
- -
-

Description

- {routine.description?.trim() ? ( - - {routine.description} - - ) : ( -

No description yet.

- )} -
- -
-
-

Recent runs

- -
- {recentRuns.length === 0 ? ( -

- No runs yet. Run the routine now or wait for its schedule. -

- ) : ( -
- {recentRuns.map((run) => run.linkedIssue ? ( - - - {formatRoutineTimestamp(run.triggeredAt)} - - )} - /> - ) : ( -
- - {run.trigger?.label ?? "Routine run"} - {formatRoutineTimestamp(run.triggeredAt)} -
- ))} -
- )} - -
-
- ); -} diff --git a/ui/src/components/RoutineResponsibleUser.test.tsx b/ui/src/components/RoutineResponsibleUser.test.tsx deleted file mode 100644 index b5836f6ead5..00000000000 --- a/ui/src/components/RoutineResponsibleUser.test.tsx +++ /dev/null @@ -1,147 +0,0 @@ -// @vitest-environment jsdom -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query"; -import type { RoutineDetail } from "@paperclipai/shared"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { accessApi } from "@/api/access"; -import { ApiError } from "@/api/client"; -import { routinesApi } from "@/api/routines"; -import { queryKeys } from "@/lib/queryKeys"; -import { RoutineResponsibleUser } from "./RoutineResponsibleUser"; - -const routine = { - id: "routine-1", companyId: "company-1", responsibleUserId: "user-alex", - latestRevisionId: "revision-1", canChangeResponsibleUser: true, -} as RoutineDetail; -const users = ["Alex", "Sam"].map((name) => ({ - principalId: `user-${name.toLowerCase()}`, status: "active" as const, membershipRole: "member" as const, - user: { id: `user-${name.toLowerCase()}`, name, email: `${name.toLowerCase()}@example.test`, image: null }, -})); - -describe("RoutineResponsibleUser", () => { - let root: Root; - let container: HTMLDivElement; - let client: QueryClient; - - beforeEach(() => { - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); - vi.stubGlobal("ResizeObserver", class { observe() {} unobserve() {} disconnect() {} }); - HTMLElement.prototype.scrollIntoView = vi.fn(); - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }); - vi.spyOn(accessApi, "listUserDirectory").mockResolvedValue({ users }); - vi.spyOn(routinesApi, "update").mockResolvedValue({ ...routine, responsibleUserId: "user-sam" }); - }); - - afterEach(async () => { - await act(async () => root.unmount()); - container.remove(); - client.clear(); - vi.restoreAllMocks(); - vi.unstubAllGlobals(); - }); - - async function render(value = routine) { - await act(async () => root.render()); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); }); - } - - async function selectSam() { - await act(async () => container.querySelector("button")!.click()); - const option = [...document.querySelectorAll('[role="option"]')].find((item) => item.textContent?.includes("Sam")); - expect(option).toBeDefined(); - await act(async () => option!.click()); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); }); - } - - it("shows the person and inheritance rules to read-only viewers", async () => { - await render({ ...routine, canChangeResponsibleUser: false }); - expect(container.textContent).toContain("Alex"); - expect(container.textContent).toContain("Automatic tasks use this person. Manual runs use the person who starts them."); - expect(container.querySelector("button")).toBeNull(); - }); - - it("saves only responsibility and its base revision, then refreshes routine data", async () => { - const invalidate = vi.spyOn(client, "invalidateQueries"); - await render(); - await selectSam(); - expect(routinesApi.update).toHaveBeenCalledWith("routine-1", { responsibleUserId: "user-sam", baseRevisionId: "revision-1" }); - expect(invalidate).toHaveBeenCalledWith({ queryKey: queryKeys.routines.detail("routine-1") }); - expect(invalidate).toHaveBeenCalledWith({ queryKey: queryKeys.routines.revisions("routine-1") }); - expect(invalidate).toHaveBeenCalledWith({ queryKey: queryKeys.routines.activity("company-1", "routine-1") }); - expect(document.querySelector('[role="option"]')).toBeNull(); - }); - - it("keeps the picker disabled until the saved detail is refreshed, then uses the new revision", async () => { - let resolveRefresh!: (value: RoutineDetail) => void; - const refresh = new Promise((resolve) => { resolveRefresh = resolve; }); - const saved = { ...routine, responsibleUserId: "user-sam", latestRevisionId: "revision-2" }; - vi.mocked(routinesApi.update).mockResolvedValue(saved); - function Detail() { - const detail = useQuery({ - queryKey: queryKeys.routines.detail(routine.id), - queryFn: () => refresh, - initialData: routine, - staleTime: Infinity, - }); - return ; - } - await act(async () => root.render()); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); }); - await selectSam(); - expect(container.querySelector("button")?.disabled).toBe(true); - expect(container.textContent).toContain("Saving…"); - await act(async () => resolveRefresh(saved)); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); }); - expect(container.querySelector("button")?.disabled).toBe(false); - expect(container.textContent).toContain("Sam"); - await act(async () => container.querySelector("button")!.click()); - const alex = [...document.querySelectorAll('[role="option"]')].find((item) => item.textContent?.includes("Alex")); - await act(async () => alex!.click()); - expect(routinesApi.update).toHaveBeenLastCalledWith(routine.id, { responsibleUserId: "user-alex", baseRevisionId: "revision-2" }); - }); - - it("does not save when the current person is selected", async () => { - await render(); - await act(async () => container.querySelector("button")!.click()); - const option = [...document.querySelectorAll('[role="option"]')].find((item) => item.textContent?.includes("Alex")); - await act(async () => option!.click()); - expect(routinesApi.update).not.toHaveBeenCalled(); - }); - - it.each([403, 409])("keeps the saved person and shows the %s failure", async (status) => { - vi.mocked(routinesApi.update).mockRejectedValue(new ApiError("Missing permission: tasks:assign", status, null)); - await render(); - await selectSam(); - expect(container.textContent).toContain("Alex"); - expect(container.querySelector('[role="alert"]')?.textContent).toContain(status === 409 ? "Reload before changing responsibility" : "Missing permission"); - }); - - it("shows an unavailable person without inventing a name and permits repair", async () => { - await render({ ...routine, responsibleUserId: "former-user" }); - expect(container.textContent).toContain("Unavailable user"); - await selectSam(); - expect(routinesApi.update).toHaveBeenCalledWith(routine.id, expect.objectContaining({ responsibleUserId: "user-sam" })); - }); - - it("disables the picker and explains a directory failure", async () => { - vi.mocked(accessApi.listUserDirectory).mockRejectedValue(new Error("Unavailable")); - await render(); - expect(container.querySelector("button")?.disabled).toBe(true); - expect(container.querySelector('[role="alert"]')?.textContent).toContain("Unavailable"); - expect(container.textContent).toContain("Retry"); - }); - - it("keeps a cached person visible without a local alert during a transient directory failure", async () => { - await render(); - vi.mocked(accessApi.listUserDirectory).mockRejectedValue(new ApiError("tenant_app_unavailable", 503, { error: "tenant_app_unavailable" })); - await act(async () => client.invalidateQueries({ queryKey: queryKeys.access.companyUserDirectory(routine.companyId) })); - await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); }); - expect(container.textContent).toContain("Alex"); - expect(container.querySelector("button")?.disabled).toBe(false); - expect(container.querySelector('[role="alert"]')).toBeNull(); - }); -}); diff --git a/ui/src/components/RoutineResponsibleUser.tsx b/ui/src/components/RoutineResponsibleUser.tsx deleted file mode 100644 index b7684f0f2cc..00000000000 --- a/ui/src/components/RoutineResponsibleUser.tsx +++ /dev/null @@ -1,105 +0,0 @@ -import { useState } from "react"; -import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import type { RoutineDetail } from "@paperclipai/shared"; -import { Check, ChevronDown, UserRound } from "lucide-react"; -import { accessApi } from "@/api/access"; -import { ApiError } from "@/api/client"; -import { describeError } from "@/api/errors"; -import { routinesApi } from "@/api/routines"; -import { buildCompanyUserProfileMap } from "@/lib/company-members"; -import { queryKeys } from "@/lib/queryKeys"; -import { Command, CommandEmpty, CommandInput, CommandItem, CommandList } from "./ui/command"; -import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover"; -import { QueryErrorState, useQueryView } from "./QueryView"; - -export function RoutineResponsibleUser({ routine }: { routine: RoutineDetail }) { - const [open, setOpen] = useState(false); - const queryClient = useQueryClient(); - const directory = useQuery({ - queryKey: queryKeys.access.companyUserDirectory(routine.companyId), - queryFn: () => accessApi.listUserDirectory(routine.companyId), - }); - const directoryView = useQueryView(directory); - const profiles = buildCompanyUserProfileMap(directory.data?.users); - const label = routine.responsibleUserId - ? profiles.get(routine.responsibleUserId)?.label - ?? (directory.isPending ? "Loading…" : "Unavailable user") - : "No responsible user"; - const change = useMutation({ - mutationFn: (responsibleUserId: string) => routinesApi.update(routine.id, { - responsibleUserId, - baseRevisionId: routine.latestRevisionId, - }), - onSuccess: async (saved) => { - queryClient.setQueryData(queryKeys.routines.detail(routine.id), (current) => ( - current ? { ...current, ...saved } : current - )); - await Promise.all([ - queryClient.invalidateQueries({ queryKey: queryKeys.routines.detail(routine.id) }), - queryClient.invalidateQueries({ queryKey: queryKeys.routines.list(routine.companyId) }), - queryClient.invalidateQueries({ queryKey: queryKeys.routines.revisions(routine.id) }), - queryClient.invalidateQueries({ queryKey: queryKeys.routines.activity(routine.companyId, routine.id) }), - ]); - }, - }); - - return ( -
-

Responsible user

- {routine.canChangeResponsibleUser ? ( - - - - - - - - - No people found. - {(directory.data?.users ?? []).map((member) => ( - { - setOpen(false); - if (member.principalId !== routine.responsibleUserId) change.mutate(member.principalId); - }} - > - - ))} - - - - - ) : ( -

-

- )} -

Automatic tasks use this person. Manual runs use the person who starts them.

- {directoryView.kind === "error" ? ( - - ) : null} - {change.error ? ( -

- {change.error instanceof ApiError && change.error.status === 409 - ? "This routine changed. Reload before changing responsibility." - : describeError(change.error, { action: "change responsibility" }).body} -

- ) : null} -
- ); -} diff --git a/ui/src/components/RoutineSaveBar.test.tsx b/ui/src/components/RoutineSaveBar.test.tsx deleted file mode 100644 index a5dd6ad2aa3..00000000000 --- a/ui/src/components/RoutineSaveBar.test.tsx +++ /dev/null @@ -1,95 +0,0 @@ -// @vitest-environment jsdom - -import type React from "react"; -import { flushSync } from "react-dom"; -import { createRoot } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { RoutineSaveBar } from "./RoutineSaveBar"; -import type { RoutineHistoryDirtyFieldDescriptor } from "./RoutineHistoryTab"; - -function act(callback: () => void) { - flushSync(callback); -} - -let container: HTMLDivElement; -let root: ReturnType; - -beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); -}); - -afterEach(() => { - act(() => root.unmount()); - container.remove(); - vi.clearAllMocks(); -}); - -const DIRTY: RoutineHistoryDirtyFieldDescriptor[] = [ - { key: "title", label: "the title" }, - { key: "description", label: "the description" }, -]; - -function renderBar(props: Partial>) { - const handlers = { - onSave: vi.fn(), - onDiscard: vi.fn(), - onReload: vi.fn(), - }; - act(() => { - root.render( - , - ); - }); - return handlers; -} - -describe("RoutineSaveBar", () => { - it("renders nothing when clean and no conflict", () => { - renderBar({ dirtyFields: [] }); - expect(container.textContent).toBe(""); - }); - - it("shows the unsaved change count when dirty", () => { - renderBar({ dirtyFields: DIRTY }); - expect(container.textContent).toContain("2 unsaved changes"); - }); - - it("invokes onSave on Cmd/Ctrl+S while dirty", () => { - const handlers = renderBar({ dirtyFields: DIRTY }); - act(() => { - window.dispatchEvent(new KeyboardEvent("keydown", { key: "s", metaKey: true })); - }); - expect(handlers.onSave).toHaveBeenCalledTimes(1); - }); - - it("does not invoke onSave on Cmd+S when clean", () => { - const handlers = renderBar({ dirtyFields: [] }); - act(() => { - window.dispatchEvent(new KeyboardEvent("keydown", { key: "s", metaKey: true })); - }); - expect(handlers.onSave).not.toHaveBeenCalled(); - }); - - it("surfaces the conflict recovery actions on saveConflict", () => { - const handlers = renderBar({ dirtyFields: DIRTY, saveConflict: true }); - expect(container.textContent).toContain("Routine changed elsewhere"); - const buttons = Array.from(container.querySelectorAll("button")); - const reload = buttons.find((button) => button.textContent?.includes("Reload latest")); - const overwrite = buttons.find((button) => button.textContent?.includes("Overwrite anyway")); - expect(reload).toBeTruthy(); - expect(overwrite).toBeTruthy(); - act(() => { - reload!.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - expect(handlers.onReload).toHaveBeenCalledTimes(1); - }); -}); diff --git a/ui/src/components/RoutineSaveBar.tsx b/ui/src/components/RoutineSaveBar.tsx deleted file mode 100644 index 5c7d2a5a8e9..00000000000 --- a/ui/src/components/RoutineSaveBar.tsx +++ /dev/null @@ -1,203 +0,0 @@ -import { useEffect, useState } from "react"; -import { AlertTriangle, Loader2 } from "lucide-react"; -import { Button } from "@/components/ui/button"; -import { - Dialog, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, -} from "@/components/ui/dialog"; -import { - Popover, - PopoverContent, - PopoverTrigger, -} from "@/components/ui/popover"; -import { - Tooltip, - TooltipContent, - TooltipProvider, - TooltipTrigger, -} from "@/components/ui/tooltip"; -import { cn } from "@/lib/utils"; -import type { RoutineHistoryDirtyFieldDescriptor } from "./RoutineHistoryTab"; - -/** - * Per-section sticky save bar (§1.4–§1.5). Hidden when clean; reveals on dirty. - * On a 409 it swaps to the conflict-recovery surface ("Reload latest" / - * "Overwrite anyway"). Wires ⌘/Ctrl+S → save and Esc → discard-with-confirm. - */ -export function RoutineSaveBar({ - dirtyFields, - isSaving, - saveConflict, - onSave, - onDiscard, - onReload, - disabled, -}: { - dirtyFields: RoutineHistoryDirtyFieldDescriptor[]; - isSaving: boolean; - saveConflict: boolean; - onSave: () => void; - onDiscard: () => void; - onReload: () => void; - disabled?: boolean; -}) { - const dirtyCount = dirtyFields.length; - const isDirty = dirtyCount > 0; - const [confirmDiscardOpen, setConfirmDiscardOpen] = useState(false); - - useEffect(() => { - if (!isDirty && !saveConflict) return; - const handler = (event: KeyboardEvent) => { - if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "s") { - event.preventDefault(); - if (!isSaving && !disabled) onSave(); - } else if (event.key === "Escape" && isDirty) { - event.preventDefault(); - setConfirmDiscardOpen(true); - } - }; - window.addEventListener("keydown", handler); - return () => window.removeEventListener("keydown", handler); - }, [isDirty, saveConflict, isSaving, disabled, onSave]); - - if (!isDirty && !saveConflict) return null; - - return ( - <> -
- {saveConflict ? ( -
- - Routine changed elsewhere. Reload to merge. -
- ) : ( - - - - - -

- Pending changes -

-
    - {dirtyFields.map((field) => ( -
  • - - {field.label} -
  • - ))} -
-
-
- )} - -
- {saveConflict ? ( - <> - - - - - - - - Replaces the newer revision with your local edits. - - - - - ) : ( - <> - - - - )} -
-
- - - - - Discard changes? - - This will revert {dirtyCount} unsaved{" "} - {dirtyCount === 1 ? "change" : "changes"} in this section. - - - - - - - - - - ); -} - -/** Read-only strip for non-owners on editable sections (§1.6). */ -export function RoutineReadOnlyStrip() { - return ( -
- Read-only — you don't own this routine. -
- ); -} diff --git a/ui/src/components/RoutineSectionHeading.test.tsx b/ui/src/components/RoutineSectionHeading.test.tsx deleted file mode 100644 index 210edbdae1b..00000000000 --- a/ui/src/components/RoutineSectionHeading.test.tsx +++ /dev/null @@ -1,73 +0,0 @@ -// @vitest-environment jsdom - -import { flushSync } from "react-dom"; -import { createRoot } from "react-dom/client"; -import { afterEach, describe, expect, it, vi } from "vitest"; -import { RoutineSectionHeading } from "./RoutineSectionHeading"; - -const copyTextToClipboard = vi.hoisted(() => vi.fn(async () => {})); - -vi.mock("@/lib/clipboard", () => ({ - copyTextToClipboard, -})); - -(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - -async function act(callback: () => void | Promise) { - let result: void | Promise = undefined; - flushSync(() => { - result = callback(); - }); - await result; -} - -describe("RoutineSectionHeading", () => { - let container: HTMLDivElement; - - afterEach(() => { - container?.remove(); - copyTextToClipboard.mockClear(); - }); - - it("copies the description markdown from the button next to the heading", async () => { - container = document.createElement("div"); - document.body.appendChild(container); - const root = createRoot(container); - const description = "```text\n- keep this line\n```"; - - await act(async () => { - root.render(); - }); - - const button = container.querySelector('button[aria-label="Copy description"]'); - expect(button).not.toBeNull(); - expect(container.querySelector("#routine-section-title")?.textContent).toBe("Overview"); - - await act(async () => { - button?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - - expect(copyTextToClipboard).toHaveBeenCalledWith(description); - - await act(async () => { - root.unmount(); - }); - }); - - it("omits the copy button on sections that are not the overview", async () => { - container = document.createElement("div"); - document.body.appendChild(container); - const root = createRoot(container); - - await act(async () => { - root.render(); - }); - - expect(container.querySelector('button[aria-label="Copy description"]')).toBeNull(); - expect(container.querySelector("#routine-section-title")?.textContent).toBe("Triggers"); - - await act(async () => { - root.unmount(); - }); - }); -}); diff --git a/ui/src/components/RoutineSectionHeading.tsx b/ui/src/components/RoutineSectionHeading.tsx deleted file mode 100644 index 053012feba8..00000000000 --- a/ui/src/components/RoutineSectionHeading.tsx +++ /dev/null @@ -1,30 +0,0 @@ -import { Copy } from "lucide-react"; -import { CopyText } from "./CopyText"; - -export function RoutineSectionHeading({ - title, - copyText = null, -}: { - title: string; - /** Description markdown to copy. Omit the button when this is null. */ - copyText?: string | null; -}) { - return ( -
-

- {title} -

- {copyText != null ? ( - - - ) : null} -
- ); -} diff --git a/ui/src/components/RoutineSubSidebar.test.tsx b/ui/src/components/RoutineSubSidebar.test.tsx deleted file mode 100644 index 2a028c88aae..00000000000 --- a/ui/src/components/RoutineSubSidebar.test.tsx +++ /dev/null @@ -1,117 +0,0 @@ -// @vitest-environment jsdom - -import type { AnchorHTMLAttributes, ReactNode } from "react"; -import { flushSync } from "react-dom"; -import { createRoot } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -vi.mock("@/lib/router", () => ({ - Link: ({ - to, - children, - ...props - }: AnchorHTMLAttributes & { to: string; children: ReactNode; replace?: boolean }) => { - const { replace: _replace, ...rest } = props as Record; - return ( - )}> - {children} - - ); - }, -})); - -import { RoutineSubSidebar } from "./RoutineSubSidebar"; -import type { RoutineSectionKey } from "./routine-sections/context"; - -function act(callback: () => void) { - flushSync(callback); -} - -let container: HTMLDivElement; -let root: ReturnType; - -beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); -}); - -afterEach(() => { - act(() => root.unmount()); - container.remove(); - vi.clearAllMocks(); -}); - -function renderSidebar(overrides?: { - activeSection?: RoutineSectionKey; - dirty?: RoutineSectionKey[]; - hasLiveRun?: boolean; - onNavigate?: (section: RoutineSectionKey) => void; -}) { - const dirty = new Set(overrides?.dirty ?? []); - const onNavigate = overrides?.onNavigate ?? vi.fn(); - act(() => { - root.render( - `/routines/r1/${section}`} - isSectionDirty={(section) => dirty.has(section)} - hasLiveRun={overrides?.hasLiveRun ?? false} - onNavigate={onNavigate} - />, - ); - }); - return { onNavigate }; -} - -describe("RoutineSubSidebar", () => { - it("renders all eight sections grouped under ROUTINE and OPERATE", () => { - renderSidebar(); - const links = Array.from(container.querySelectorAll("a")); - const labels = links.map((link) => link.textContent?.trim()); - expect(labels).toEqual([ - "Overview", - "Triggers", - "Variables", - "Secrets", - "Delivery", - "Runs", - "Activity", - "History", - ]); - const groupLabels = Array.from(container.querySelectorAll("p")).map((p) => p.textContent); - expect(groupLabels).toContain("Routine"); - expect(groupLabels).toContain("Operate"); - }); - - it("marks the active section with aria-current=page", () => { - renderSidebar({ activeSection: "secrets" }); - const active = container.querySelector('a[aria-current="page"]'); - expect(active?.textContent?.trim()).toBe("Secrets"); - }); - - it("links each section to its section URL", () => { - renderSidebar(); - const variables = Array.from(container.querySelectorAll("a")).find( - (link) => link.textContent?.trim() === "Variables", - ); - expect(variables?.getAttribute("href")).toBe("/routines/r1/variables"); - }); - - it("shows a dirty marker only on dirty editable sections", () => { - renderSidebar({ dirty: ["overview", "delivery"] }); - const dirtyMarkers = container.querySelectorAll('[aria-label="Unsaved changes"]'); - expect(dirtyMarkers.length).toBe(2); - }); - - it("fires onNavigate when a section is clicked", () => { - const { onNavigate } = renderSidebar(); - const triggers = Array.from(container.querySelectorAll("a")).find( - (link) => link.textContent?.trim() === "Triggers", - ) as HTMLAnchorElement; - act(() => { - triggers.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - expect(onNavigate).toHaveBeenCalledWith("triggers"); - }); -}); diff --git a/ui/src/components/RoutineSubSidebar.tsx b/ui/src/components/RoutineSubSidebar.tsx deleted file mode 100644 index 9964bc1d287..00000000000 --- a/ui/src/components/RoutineSubSidebar.tsx +++ /dev/null @@ -1,216 +0,0 @@ -import { useRef } from "react"; -import { - Activity as ActivityIcon, - Circle, - Clock3, - History as HistoryIcon, - KeyRound, - LayoutGrid, - Play, - Send, - SlidersHorizontal, -} from "lucide-react"; -import type { LucideIcon } from "lucide-react"; -import { Link } from "@/lib/router"; -import { cn } from "@/lib/utils"; -import { - ROUTINE_SECTION_KEYS, - type RoutineSectionKey, -} from "./routine-sections/context"; -import { - Select, - SelectContent, - SelectGroup, - SelectItem, - SelectLabel, - SelectTrigger, - SelectValue, -} from "@/components/ui/select"; - -type NavItem = { - key: RoutineSectionKey; - label: string; - icon: LucideIcon; -}; - -type NavGroup = { - label: string; - items: NavItem[]; -}; - -const NAV_GROUPS: NavGroup[] = [ - { - label: "Routine", - items: [ - { key: "overview", label: "Overview", icon: Circle }, - { key: "triggers", label: "Triggers", icon: Clock3 }, - { key: "variables", label: "Variables", icon: LayoutGrid }, - { key: "secrets", label: "Secrets", icon: KeyRound }, - { key: "delivery", label: "Delivery", icon: Send }, - ], - }, - { - label: "Operate", - items: [ - { key: "runs", label: "Runs", icon: Play }, - { key: "activity", label: "Activity", icon: ActivityIcon }, - { key: "history", label: "History", icon: HistoryIcon }, - ], - }, -]; - -const ALL_ITEMS: NavItem[] = NAV_GROUPS.flatMap((group) => group.items); - -export function RoutineSubSidebar({ - activeSection, - hrefFor, - isSectionDirty, - hasLiveRun, - onNavigate, -}: { - activeSection: RoutineSectionKey; - hrefFor: (section: RoutineSectionKey) => string; - isSectionDirty: (section: RoutineSectionKey) => boolean; - hasLiveRun: boolean; - onNavigate: (section: RoutineSectionKey) => void; -}) { - const itemRefs = useRef>([]); - - const focusItem = (index: number) => { - const clamped = (index + ALL_ITEMS.length) % ALL_ITEMS.length; - itemRefs.current[clamped]?.focus(); - onNavigate(ALL_ITEMS[clamped].key); - }; - - const handleKeyDown = (event: React.KeyboardEvent, index: number) => { - switch (event.key) { - case "ArrowDown": - event.preventDefault(); - focusItem(index + 1); - break; - case "ArrowUp": - event.preventDefault(); - focusItem(index - 1); - break; - case "Home": - event.preventDefault(); - focusItem(0); - break; - case "End": - event.preventDefault(); - focusItem(ALL_ITEMS.length - 1); - break; - default: - break; - } - }; - - let flatIndex = -1; - - return ( - - ); -} - -/** Mobile section picker — collapses the sub-sidebar into a grouped ` { - if (ROUTINE_SECTION_KEYS.includes(value as RoutineSectionKey)) { - onNavigate(value as RoutineSectionKey); - } - }} - > - - - - - {NAV_GROUPS.map((group) => ( - - - {group.label} - - {group.items.map((item) => ( - - - - {item.label} - {isSectionDirty(item.key) ? ( - - ) : null} - - - ))} - - ))} - - - - ); -} - -export { ALL_ITEMS as ROUTINE_NAV_ITEMS }; diff --git a/ui/src/components/RoutineTriggerCard.tsx b/ui/src/components/RoutineTriggerCard.tsx deleted file mode 100644 index 0e8ea0f9ee9..00000000000 --- a/ui/src/components/RoutineTriggerCard.tsx +++ /dev/null @@ -1,207 +0,0 @@ -import { useEffect, useState } from "react"; -import { Clock3, Radar, RefreshCw, Save, Trash2, Webhook, Zap } from "lucide-react"; -import type { RoutineTrigger } from "@paperclipai/shared"; -import { Button } from "@/components/ui/button"; -import { Input } from "@/components/ui/input"; -import { Label } from "@/components/ui/label"; -import { Badge } from "@/components/ui/badge"; -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from "@/components/ui/select"; -import { ScheduleEditor } from "./ScheduleEditor"; -import { buildRoutineTriggerPatch } from "../lib/routine-trigger-patch"; -import { describeCron } from "../lib/cron-readable"; - -const signingModes = ["app_webhook", "bearer", "hmac_sha256", "github_hmac", "none"]; -const SIGNING_MODES_WITHOUT_REPLAY_WINDOW = new Set(["app_webhook", "bearer", "github_hmac", "fireflies_hmac", "none"]); - -function getLocalTimezone(): string { - try { - return Intl.DateTimeFormat().resolvedOptions().timeZone; - } catch { - return "UTC"; - } -} - -/** - * Single trigger card with its own field-edit + save state (§3.2). Extracted - * from the previous inline `TriggerEditor` in `RoutineDetail.tsx` — same logic. - */ -export function RoutineTriggerCard({ - trigger, - onSave, - onRotate, - onDelete, - disabled, -}: { - trigger: RoutineTrigger; - onSave: (id: string, patch: Record) => void; - onRotate: (id: string) => void; - onDelete: (id: string) => void; - disabled?: boolean; -}) { - const [draft, setDraft] = useState({ - label: trigger.label ?? "", - cronExpression: trigger.cronExpression ?? "", - signingMode: trigger.signingMode ?? "bearer", - replayWindowSec: String(trigger.replayWindowSec ?? 300), - }); - - useEffect(() => { - setDraft({ - label: trigger.label ?? "", - cronExpression: trigger.cronExpression ?? "", - signingMode: trigger.signingMode ?? "bearer", - replayWindowSec: String(trigger.replayWindowSec ?? 300), - }); - }, [trigger]); - - const KindIcon = - trigger.kind === "schedule" ? Clock3 : trigger.kind === "webhook" ? Webhook : trigger.kind === "heartbeat" ? Radar : Zap; - const humanCron = trigger.kind === "schedule" ? describeCron(draft.cronExpression) : null; - const lastResultFailed = /fail|error/i.test(trigger.lastResult ?? ""); - const lastResultLabel = trigger.lastResult?.startsWith("Created execution issue ") - ? "Task created" - : trigger.lastResult; - - return ( -
event.preventDefault()} - > -
-
-
- - {trigger.label ?? trigger.kind} -
- {humanCron ? ( -

- {humanCron} -

- ) : null} -
-
- {trigger.lastResult ? ( - - {lastResultLabel} - - ) : null} - - {trigger.kind === "schedule" && trigger.nextRunAt - ? `Next: ${new Date(trigger.nextRunAt).toLocaleString()}` - : trigger.kind === "webhook" - ? "Webhook" - : trigger.kind === "heartbeat" - ? "Standing check" - : "API"} - -
-
- - {trigger.kind === "webhook" && trigger.webhookUrl && ( -
- - event.target.select()} /> -

- Send a POST request with Content-Type: application/json. Keep this URL private when signing is disabled. -

-
- )} - -
-
- - setDraft((current) => ({ ...current, label: event.target.value }))} - /> -
- {trigger.kind === "schedule" && ( -
- - - setDraft((current) => ({ ...current, cronExpression })) - } - /> -
- )} - {trigger.kind === "webhook" && ( - <> -
- - -
- {!SIGNING_MODES_WITHOUT_REPLAY_WINDOW.has(draft.signingMode) && ( -
- - - setDraft((current) => ({ ...current, replayWindowSec: event.target.value })) - } - /> -
- )} - - )} -
- - {!disabled && ( -
- - {trigger.kind === "webhook" && ( - - )} - -
- )} -
- ); -} diff --git a/ui/src/components/RoutineVariablesEditor.tsx b/ui/src/components/RoutineVariablesEditor.tsx index f8bd71b797f..db9c693bfcb 100644 --- a/ui/src/components/RoutineVariablesEditor.tsx +++ b/ui/src/components/RoutineVariablesEditor.tsx @@ -55,11 +55,14 @@ export function RoutineVariablesEditor({ description, value, onChange, + variant = "default", }: { title: string; description: string; value: RoutineVariable[]; onChange: (value: RoutineVariable[]) => void; + /** `compact` puts each variable on one row under shared column labels. */ + variant?: "default" | "compact"; }) { const [open, setOpen] = useState(true); const syncedVariables = useMemo( @@ -79,6 +82,15 @@ export function RoutineVariablesEditor({ return null; } + if (variant === "compact") { + return ( + onChange(updateVariableList(syncedVariables, name, mutate))} + /> + ); + } + return ( @@ -249,6 +261,145 @@ export function RoutineVariablesEditor({ ); } +const compactColumns = { + name: "w-full shrink-0 sm:w-48", + type: "w-28 shrink-0", + defaultValue: "min-w-0 flex-1 basis-32", + required: "flex w-16 shrink-0 justify-center", +}; + +/** One row per variable: name, type, default and required, with the column labels shown once. + * A saved label is kept as-is; this layout does not edit it. */ +function CompactVariableRows({ + variables, + onPatch, +}: { + variables: RoutineVariable[]; + onPatch: (name: string, mutate: (variable: RoutineVariable) => RoutineVariable) => void; +}) { + return ( +
+ + + {variables.map((variable) => { + const patch = (change: Partial) => onPatch(variable.name, (current) => ({ ...current, ...change })); + return ( +
+
+ + {`{{${variable.name}}}`} + + +
+ {variable.type === "boolean" ? ( + + ) : variable.type === "select" ? ( + + ) : variable.type === "textarea" ? ( +