diff --git a/doc/PRODUCT.md b/doc/PRODUCT.md index 22da38a8c85..2151f7b70e4 100644 --- a/doc/PRODUCT.md +++ b/doc/PRODUCT.md @@ -189,6 +189,15 @@ The change creates a routine revision and applies to future automatic tasks. Existing tasks keep their responsibility. Manual runs use the person who starts them. Agents cannot transfer routine responsibility. +The Routines list shows the agent and responsible user in adjacent columns. +People can choose project, agent, responsible user, last run, and enabled columns. +Search, sort, group, and project, agent, enabled, responsible user, and source +filters are saved in the URL when changed. A shared filter URL takes precedence +over locally saved filters. Each signed-in person keeps their latest filters, +column choices, grouping, sorting, and collapsed groups in local storage for +each company. An explicit empty filter URL clears saved filters. +A trusted local installation without accounts uses a local board preference key. + ### Task collection creation filters diff --git a/tests/runner-e2e/product-journeys/routine-schedule-flow.ts b/tests/runner-e2e/product-journeys/routine-schedule-flow.ts index b79fb0bc918..35ceaaa9f90 100644 --- a/tests/runner-e2e/product-journeys/routine-schedule-flow.ts +++ b/tests/runner-e2e/product-journeys/routine-schedule-flow.ts @@ -83,7 +83,7 @@ export async function runScheduledRoutine(context: JourneyContext, session: Targ + "Then finish the task. Do not create other tasks or agents."; await routineUiStep("open_composer", async () => { await page.goto(`${api.origin}/${company.issuePrefix}/routines`, { waitUntil: "domcontentloaded" }); - await page.getByRole("button", { name: "Create routine", exact: true }).first().click(); + await page.getByRole("button", { name: "New routine", exact: true }).first().click(); }); const dialog = page.getByRole("dialog"); await routineUiStep("select_responsible", async () => { diff --git a/tests/storybook-visual/routines-list-view.spec.ts b/tests/storybook-visual/routines-list-view.spec.ts new file mode 100644 index 00000000000..fc5a411a3de --- /dev/null +++ b/tests/storybook-visual/routines-list-view.spec.ts @@ -0,0 +1,78 @@ +import { expect, test } from "@playwright/test"; +import { routineViewStorageKey } from "../../ui/src/lib/routine-list-view"; + +test.use({ viewport: { width: 1440, height: 900 } }); +const storageKey = routineViewStorageKey("company-storybook", "user-board"); +for (const theme of ["light", "dark"]) { + test(`routine columns and filters in ${theme}`, async ({ page }) => { + const errors: string[] = []; + page.on("pageerror", error => errors.push(error.message)); + page.on("console", message => { if (message.type() === "error") errors.push(message.text()); }); + await page.goto(`/iframe.html?id=routines-list-view--default&viewMode=story&globals=theme:${theme}`); + const toolbar = page.getByRole("toolbar", { name: "Routines controls" }); + await expect(page.getByRole("row").filter({ hasText: "Weekly project review" })).toBeVisible(); + expect(await toolbar.locator("button, input, a").filter({ visible: true }).evaluateAll(elements => elements.map(element => element.getAttribute("aria-label") ?? element.textContent))).toEqual([ + "New routine", "Search routines", "Sort routines", "Filter routines", "Group routines", "Routine columns", "View all tasks", + ]); + await expect(page.getByRole("columnheader")).toHaveText(["Routine", "Project", "Agent", "Responsible user", "Last run", "Enabled", "Actions"]); + await page.screenshot({ path: `test-results/routines-${theme}.png`, fullPage: true }); + await toolbar.getByRole("button", { name: "Filter routines", exact: true }).click(); + await page.screenshot({ path: `test-results/routines-filters-${theme}.png`, fullPage: true }); + await page.getByRole("checkbox", { name: "Alex Chen", exact: true }).click(); + await page.getByRole("checkbox", { name: "Enabled", exact: true }).click(); + await page.keyboard.press("Escape"); + await expect(page.getByRole("row").filter({ hasText: "Daily company summary" })).toBeVisible(); + await expect(page.getByRole("row").filter({ hasText: "Weekly project review" })).toHaveCount(0); + await expect(page.getByRole("row").filter({ hasText: "Nightly task triage" })).toHaveCount(0); + await expect(page.getByTestId("routine-view-location")).toHaveAttribute("href", /responsibleUsers=person-alex/); + await expect(page.getByTestId("routine-view-location")).toHaveAttribute("href", /statuses=active/); + await toolbar.getByRole("button", { name: "Routine columns" }).click(); + await page.getByRole("menuitemcheckbox", { name: "Project", exact: true }).click(); + await page.getByRole("menuitemcheckbox", { name: "Last run", exact: true }).click(); + await page.keyboard.press("Escape"); + await expect(page.getByRole("columnheader")).toHaveText(["Routine", "Agent", "Responsible user", "Enabled", "Actions"]); + expect(await page.evaluate(key => JSON.parse(localStorage.getItem(key)!).columns, storageKey)).toEqual(["assignee", "responsibleUser", "enabled"]); + await page.screenshot({ path: `test-results/routines-custom-columns-${theme}.png`, fullPage: true }); + expect(errors).toEqual([]); + }); +} + +test("linked filters open on current and classic pages and mobile stays within the viewport", async ({ page }) => { + await page.goto("/iframe.html?id=routines-list-view--linked-filters&viewMode=story"); + await expect(page.getByRole("row").filter({ hasText: "Daily company summary" })).toBeVisible(); + await expect(page.getByRole("row").filter({ hasText: "Weekly project review" })).toHaveCount(0); + await page.goto("/iframe.html?id=routines-list-view--classic&viewMode=story"); + await expect(page.getByRole("button", { name: "New routine", exact: true })).toBeVisible(); + await expect(page.getByRole("columnheader", { name: "Responsible user" })).toBeVisible(); + await page.setViewportSize({ width: 390, height: 844 }); + await page.goto("/iframe.html?id=routines-list-view--default&viewMode=story"); + await expect(page.getByRole("button", { name: "Routine columns" })).toBeVisible(); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true); + await page.getByRole("button", { name: "Dismiss folder suggestion", exact: true }).click(); + await page.screenshot({ path: "test-results/routines-mobile.png", fullPage: true }); +}); + +test("Classic selection keeps column headings aligned and exposes routine links", async ({ page }) => { + await page.goto("/iframe.html?id=routines-list-view--classic-selection&viewMode=story"); + await page.getByRole("button", { name: "Select", exact: true }).click(); + const row = page.getByRole("row").filter({ hasText: "Daily company summary" }); + await expect(row.getByRole("link", { name: "Daily company summary", exact: true })).toHaveAttribute("href", /\/routines\/daily-summary$/); + const heading = page.getByRole("columnheader", { name: "Routine", exact: true }); + const title = row.getByRole("cell").nth(1); + const headingBox = await heading.boundingBox(); + const titleBox = await title.boundingBox(); + expect(Math.abs(headingBox!.x - titleBox!.x)).toBeLessThan(1); + await row.getByRole("checkbox", { name: "Select Daily company summary" }).check(); + await expect(page.getByText("1 selected", { exact: true })).toBeVisible(); + await page.screenshot({ path: "test-results/routines-classic-selection.png", fullPage: true }); +}); + + +test("Classic Recent Runs hides routine list controls", async ({ page }) => { + await page.goto("/iframe.html?id=routines-list-view--classic-runs&viewMode=story"); + const toolbar = page.getByRole("toolbar", { name: "Routines controls" }); + await expect(toolbar.getByRole("button", { name: "New routine", exact: true })).toBeVisible(); + await expect(toolbar.getByRole("link", { name: "View all tasks" })).toBeVisible(); + await expect(toolbar.getByRole("textbox", { name: "Search routines" })).toHaveCount(0); + await expect(toolbar.getByRole("button", { name: "Routine columns" })).toHaveCount(0); +}); diff --git a/tests/storybook-visual/toolbars-design.spec.ts b/tests/storybook-visual/toolbars-design.spec.ts index 982a61be397..c5eefe22411 100644 --- a/tests/storybook-visual/toolbars-design.spec.ts +++ b/tests/storybook-visual/toolbars-design.spec.ts @@ -114,14 +114,14 @@ test("canonical toolbars share control geometry and keep the requested keyboard const controls = [...toolbar.querySelectorAll("button:not([data-toolbar-clear], .canonical-tab), [data-toolbar-control]")].filter(button => !button.closest(".design-view-toggle")); const style = getComputedStyle(search); return { name: toolbar.getAttribute("data-canonical-toolbar"), searchHeight: search.getBoundingClientRect().height, gap: getComputedStyle(toolbar).columnGap, - border: style.borderColor, radius: style.borderRadius, first: first.getAttribute("aria-label"), + border: style.borderColor, radius: style.borderRadius, first: first.getAttribute("aria-label") ?? first.textContent, controls: controls.map(button => ({ height: button.getBoundingClientRect().height, border: getComputedStyle(button).borderColor, radius: getComputedStyle(button).borderRadius })) }; })); expect(geometry).toHaveLength(6); for (const toolbar of geometry) { expect(toolbar.searchHeight).toBe(44); expect(toolbar.gap).toBe("8px"); - expect(toolbar.first).toBe(toolbar.name === "tasks" ? "Task view: All tasks" : toolbar.name === "skills" ? "Search installed skills" : `Search ${toolbar.name}`); + expect(toolbar.first).toBe(toolbar.name === "tasks" ? "Task view: All tasks" : toolbar.name === "skills" ? "Search installed skills" : toolbar.name === "routines" ? "New routine" : `Search ${toolbar.name}`); for (const control of toolbar.controls) { expect(control.height).toBe(toolbar.searchHeight); expect(control.border).toBe(toolbar.border); @@ -166,6 +166,6 @@ test("routines toolbar updates search, sort, group and creation intent", async ( await page.getByRole("button", { name: "Agent", exact: true }).click(); await expect(preview.locator("output")).toContainText("Group: assignee"); await expect(preview.getByRole("button", { name: "New folder" })).toHaveCount(0); - await preview.getByRole("button", { name: "Create routine" }).click(); + await preview.getByRole("button", { name: "New routine" }).click(); await expect(preview.locator("output")).toContainText("Create routine requested"); }); diff --git a/ui/src/components/CollectionFilterOptions.tsx b/ui/src/components/CollectionFilterOptions.tsx new file mode 100644 index 00000000000..efd3b0676a2 --- /dev/null +++ b/ui/src/components/CollectionFilterOptions.tsx @@ -0,0 +1,22 @@ +import { useId, type ReactNode } from "react"; +import { Search } from "lucide-react"; +import { Checkbox } from "./ui/checkbox"; +import { Input } from "./ui/input"; +import { TruncatedText } from "./TruncatedText"; + +export function FilterGroup({ title, searchLabel, query, onQueryChange, children, optionsKey }: { title: string; searchLabel?: string; query?: string; onQueryChange?: (value: string) => void; children: ReactNode; optionsKey: string }) { + const headingId = useId(); + return ( +
+

{title}

+
+ {searchLabel ?
onQueryChange?.(event.target.value)} />
: null} +
{children}
+
+
+ ); +} + +export function FilterRow({ label, checked, onToggle, icon }: { label: string; checked: boolean; onToggle: () => void; icon?: ReactNode }) { + return ; +} diff --git a/ui/src/components/IssueFilterPanel.tsx b/ui/src/components/IssueFilterPanel.tsx index e039d78c95a..0b6361dac0b 100644 --- a/ui/src/components/IssueFilterPanel.tsx +++ b/ui/src/components/IssueFilterPanel.tsx @@ -1,33 +1,14 @@ -import { useId, useState, type ComponentProps, type CSSProperties, type ReactNode } from "react"; -import { Bot, Search, User } from "lucide-react"; +import { useState, type ComponentProps, type CSSProperties } from "react"; +import { Bot, User } from "lucide-react"; import type { IssueFiltersPopover } from "./IssueFiltersPopover"; import { Button } from "./ui/button"; -import { Checkbox } from "./ui/checkbox"; -import { Input } from "./ui/input"; import { FlyoutHeader } from "./ui/flyout"; import { StatusIcon } from "./StatusIcon"; -import { TruncatedText } from "./TruncatedText"; +import { FilterGroup, FilterRow } from "./CollectionFilterOptions"; import { issueFilterLabel, issueStatusOrder, searchIssueFilterOptions, toggleIssueFilterValue } from "@/lib/issue-filters"; type PanelProps = Pick, "state" | "onChange" | "activeFilterCount" | "agents" | "projects" | "labels" | "creators" | "currentUserId" | "enableRoutineTasksFilter" | "enableAgentCreatedVisibilityFilter" | "enableLiveRunsFilter"> & { onClear: () => void }; -function FilterGroup({ title, searchLabel, query, onQueryChange, children, optionsKey }: { title: string; searchLabel?: string; query?: string; onQueryChange?: (value: string) => void; children: ReactNode; optionsKey: string }) { - const headingId = useId(); - return ( -
-

{title}

-
- {searchLabel ?
onQueryChange?.(event.target.value)} />
: null} -
{children}
-
-
- ); -} - -function FilterRow({ label, checked, onToggle, icon }: { label: string; checked: boolean; onToggle: () => void; icon?: ReactNode }) { - return ; -} - /** The collection retains ownership of filter state. */ export function IssueFilterPanel({ state, onChange, activeFilterCount, agents = [], projects = [], labels = [], creators = [], currentUserId, onClear, enableRoutineTasksFilter, enableAgentCreatedVisibilityFilter, enableLiveRunsFilter = true }: PanelProps) { const [queries, setQueries] = useState({ projects: "", creators: "", assignees: "", labels: "" }); diff --git a/ui/src/components/ManagedRoutinesList.test.tsx b/ui/src/components/ManagedRoutinesList.test.tsx index 8b54d204eab..5240cb3f666 100644 --- a/ui/src/components/ManagedRoutinesList.test.tsx +++ b/ui/src/components/ManagedRoutinesList.test.tsx @@ -4,6 +4,7 @@ import { renderToStaticMarkup } from "react-dom/server"; import { describe, expect, it, vi } from "vitest"; import { appearanceForPalette, agentAvatarUrl, resolveAgentAppearance } from "@paperclipai/shared"; import { ManagedRoutinesList } from "./ManagedRoutinesList"; +import { RoutineListRow } from "./RoutineList"; vi.mock("@/lib/router", () => ({ Link: ({ to, children, ...props }: { to: string; children: ReactNode }) => {children} })); const routines = [{ key: "routine", title: "Daily summary", status: "active", assigneeAgentId: "agent-one" }]; @@ -12,6 +13,20 @@ function avatarSrc(markup: string) { return document.querySelector('[data-slot="agent-avatar"] img')?.getAttribute("src"); } describe("routine agent identities", () => { + it("retains responsible people and selection in compact rows", () => { + const markup = renderToStaticMarkup(); + const document = new DOMParser().parseFromString(markup, "text/html"); + expect(document.body.textContent).toContain("Casey"); + expect(document.querySelector('input[aria-label="Select Weekly summary"]')?.checked).toBe(true); + expect(document.querySelector('a[href="/routines/r1"]')?.textContent).toBe("Weekly summary"); + }); it("keeps a saved palette for agents without legacy icons", () => { const appearance = appearanceForPalette("bubblegum-sky"); const markup = renderToStaticMarkup(); diff --git a/ui/src/components/RoutineList.tsx b/ui/src/components/RoutineList.tsx index 332422307f6..0f32dd5b808 100644 --- a/ui/src/components/RoutineList.tsx +++ b/ui/src/components/RoutineList.tsx @@ -1,7 +1,7 @@ import type { AgentAppearance } from "@paperclipai/shared"; import { AgentAvatar } from "@/components/AgentAvatar"; -import type { ReactNode } from "react"; -import { MoreHorizontal, Play } from "lucide-react"; +import type { MouseEvent, ReactNode } from "react"; +import { MoreHorizontal, Play, LoaderCircle } from "lucide-react"; import { Link } from "@/lib/router"; import { Button } from "@/components/ui/button"; import { @@ -11,6 +11,9 @@ import { DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; +import { Identity } from "./Identity"; +import type { CompanyUserProfile } from "@/lib/company-members"; +import { routineColumnGrid, type RoutineColumn } from "./RoutineTable"; import { ToggleSwitch } from "@/components/ui/toggle-switch"; export type RoutineListProjectSummary = { @@ -31,6 +34,7 @@ export type RoutineListRowItem = { status: string; projectId: string | null; assigneeAgentId: string | null; + responsibleUserId?: string | null; lastRun?: { triggeredAt?: Date | string | null; status?: string | null; @@ -52,30 +56,9 @@ export function nextRoutineStatus(currentStatus: string, enabled: boolean) { return enabled ? "active" : "paused"; } -export function RoutineListRow({ - routine, - projectById, - agentById, - runningRoutineId, - statusMutationRoutineId, - href, - configureLabel = "Edit", - managedByLabel, - secondaryDetails, - runNowButton = false, - disableRunNow = false, - disableToggle = false, - hideArchiveAction = false, - divider = true, - selected = false, - selectMode = false, - extraMenuItems, - onSelectChange, - onRunNow, - onToggleEnabled, - onToggleArchived, -}: { +type RoutineRowProps = { routine: TRoutine; + userById?: Map; projectById: Map; agentById: Map; runningRoutineId: string | null; @@ -97,7 +80,36 @@ export function RoutineListRow({ onRunNow: (routine: TRoutine) => void; onToggleEnabled: (routine: TRoutine, enabled: boolean) => void; onToggleArchived?: (routine: TRoutine) => void; -}) { +}; + +function openRoutineFromRow(event: MouseEvent) { + if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; + if ((event.target as Element).closest("a, button, input, [role='switch'], [role='checkbox']")) return; + event.currentTarget.querySelector("[data-routine-link]")?.click(); +} + +function routineRowParts({ + routine, + userById, + projectById, + agentById, + runningRoutineId, + statusMutationRoutineId, + href, + configureLabel = "Edit", + managedByLabel, + secondaryDetails, + runNowButton = false, + disableRunNow = false, + disableToggle = false, + hideArchiveAction = false, + selected = false, + extraMenuItems, + onSelectChange, + onRunNow, + onToggleEnabled, + onToggleArchived, +}: RoutineRowProps) { const enabled = routine.status === "active"; const isArchived = routine.status === "archived"; const isStatusPending = statusMutationRoutineId === routine.id; @@ -106,18 +118,35 @@ export function RoutineListRow({ const isDraft = !isArchived && !routine.assigneeAgentId; const runDisabled = runningRoutineId === routine.id || isArchived || disableRunNow; - return ( - - {selectMode ? ( -
{routine.projectId ? project?.name ?? "Unknown project" : "No project"}; + const agentCell = {routine.assigneeAgentId ? : null}{routine.assigneeAgentId ? agent?.name ?? "Unknown agent" : "No default agent"}; + const userCell = user ? : {routine.responsibleUserId ? "Unavailable user" : "No responsible user"}; + const lastRunCell = {formatLastRunTimestamp(routine.lastRun?.triggeredAt)}{routine.lastRun ? ` · ${formatRoutineRunStatus(routine.lastRun.status)}` : ""}; + const enabledCell =
{ event.preventDefault(); event.stopPropagation(); }}> onToggleEnabled(routine, enabled)} disabled={isStatusPending || isArchived || disableToggle} aria-label={enabled ? `Disable ${routine.title}` : `Enable ${routine.title}`} />{isArchived ? "Archived" : isDraft ? "Draft" : enabled ? "On" : "Off"}
; + const cellByColumn = { project: projectCell, assignee: agentCell, responsibleUser: userCell, lastRun: lastRunCell, enabled: enabledCell }; + const title = ( +
+
+ {routine.title} + {(isArchived || routine.status === "paused" || isDraft) ? ( + + {isArchived ? "archived" : isDraft ? "draft" : "paused"} + + ) : null} + {managedByLabel ? ( + {managedByLabel} + ) : null} +
+ {secondaryDetails ? ( +
{secondaryDetails}
+ ) : null} +
+ ); + const selection = ( +
{ - event.preventDefault(); event.stopPropagation(); }} > @@ -129,66 +158,23 @@ export function RoutineListRow({ onChange={(event) => onSelectChange?.(routine, event.target.checked)} />
- ) : null} -
-
- {routine.title} - {(isArchived || routine.status === "paused" || isDraft) ? ( - - {isArchived ? "archived" : isDraft ? "draft" : "paused"} - - ) : null} - {managedByLabel ? ( - {managedByLabel} - ) : null} -
-
- - - {routine.projectId ? (project?.name ?? "Unknown project") : "No project"} - - - {routine.assigneeAgentId ? : null} - {routine.assigneeAgentId ? (agent?.name ?? "Unknown agent") : "No default agent"} - - - {formatLastRunTimestamp(routine.lastRun?.triggeredAt)} - {routine.lastRun ? ` · ${formatRoutineRunStatus(routine.lastRun.status)}` : ""} - -
- {secondaryDetails ? ( -
{secondaryDetails}
- ) : null} -
- -
{ event.preventDefault(); event.stopPropagation(); }}> + ); + const actions = ( +
{ event.preventDefault(); event.stopPropagation(); }}> {runNowButton ? ( ) : null} -
- onToggleEnabled(routine, enabled)} - disabled={isStatusPending || isArchived || disableToggle} - aria-label={enabled ? `Disable ${routine.title}` : `Enable ${routine.title}`} - /> - - {isArchived ? "Archived" : isDraft ? "Draft" : enabled ? "On" : "Off"} - -
+ @@ -230,6 +216,28 @@ export function RoutineListRow({
- ); + return { title, selection, actions, cellByColumn }; +} + +export function RoutineTableRow(props: RoutineRowProps & { columns: RoutineColumn[]; userById: Map }) { + const { title, selection, actions, cellByColumn } = routineRowParts(props); + return
+ {props.selectMode ?
{selection}
: null} +
{title}
+ {props.columns.map(column =>
{cellByColumn[column]}
)} +
{actions}
+
; +} + +export function RoutineListRow(props: RoutineRowProps) { + const { title, selection, actions, cellByColumn } = routineRowParts(props); + return
+ {props.selectMode ? selection : null} +
+ {title} +
{cellByColumn.project}{cellByColumn.assignee}{props.userById ? cellByColumn.responsibleUser : null}{cellByColumn.lastRun}
+
+ {cellByColumn.enabled}{actions} +
; } diff --git a/ui/src/components/RoutineTable.tsx b/ui/src/components/RoutineTable.tsx new file mode 100644 index 00000000000..101971d7ddb --- /dev/null +++ b/ui/src/components/RoutineTable.tsx @@ -0,0 +1,18 @@ +import type { ReactNode } from "react"; +import { routineColumns, type RoutineColumn } from "@/lib/routine-list-view"; +export type { RoutineColumn } from "@/lib/routine-list-view"; + +export function routineColumnGrid(columns: RoutineColumn[], selectMode = false) { + return [selectMode ? "var(--routine-select-width)" : null, "minmax(var(--routine-title-min), 1fr)", ...columns.map(column => `var(--routine-column-${column})`), "var(--routine-actions-width)"].filter(Boolean).join(" "); +} +export function RoutineTable({ columns, children, label, selectMode = false }: { columns: RoutineColumn[]; children: ReactNode; label: string; selectMode?: boolean }) { + return
+
+ {selectMode ? Select : null} + Routine + {columns.map(id => {routineColumns.find(column => column.id === id)!.label})} + Actions +
+
{children}
+
; +} diff --git a/ui/src/components/RoutinesToolbar.test.tsx b/ui/src/components/RoutinesToolbar.test.tsx new file mode 100644 index 00000000000..76e2b4ba36c --- /dev/null +++ b/ui/src/components/RoutinesToolbar.test.tsx @@ -0,0 +1,28 @@ +// @vitest-environment jsdom +import type { ReactNode } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it, vi } from "vitest"; +import { RoutinesToolbar } from "./RoutinesToolbar"; +import { defaultRoutineView } from "@/lib/routine-list-view"; + +vi.mock("@/lib/router", () => ({ Link: ({ to, children }: { to: string; children: ReactNode }) => {children} })); + +describe("Routines filter rendering", () => { + it("bounds selection reads for a large company filter menu", () => { + const size = 1500; + let reads = 0; + const ids = Array.from({ length: size }, (_, i) => `project-${i}`); + const selected = new Proxy(ids, { + get(target, property, receiver) { + if (typeof property === "string" && /^\d+$/.test(property)) { + if (++reads > size * 2) throw new Error("Filter rendering repeatedly scanned its selected projects"); + } + return Reflect.get(target, property, receiver); + }, + }); + const markup = renderToStaticMarkup( {}} sortField="title" sortDir="asc" groupBy="none" onSortChange={() => {}} onGroupChange={() => {}} onCreateRoutine={() => {}} filters={{ ...defaultRoutineView, projects: selected }} filterOptions={{ projects: ids.map(id => ({ id, name: id })) }} />); + expect(markup).toContain("Filter routines (1500)"); + expect(reads).toBeGreaterThanOrEqual(size); + expect(reads).toBeLessThanOrEqual(size * 2); + }); +}); diff --git a/ui/src/components/RoutinesToolbar.tsx b/ui/src/components/RoutinesToolbar.tsx index 7c20cbed1b0..47aa908b1e2 100644 --- a/ui/src/components/RoutinesToolbar.tsx +++ b/ui/src/components/RoutinesToolbar.tsx @@ -1,14 +1,18 @@ -import { ArrowUpDown, Check, Layers, Plus } from "lucide-react"; +import { useState } from "react"; +import { ArrowUpDown, Check, Columns3, Filter, Layers, Plus } from "lucide-react"; import { Link } from "@/lib/router"; +import { defaultRoutineView, routineColumns, routineFilterKeys, type RoutineColumn, type RoutineFilterKey, type RoutineViewState, type RoutineGroupBy, type RoutineSortField, type RoutineSortDir } from "@/lib/routine-list-view"; import { ToolbarSearch } from "./ToolbarSearch"; +import { FilterGroup, FilterRow } from "./CollectionFilterOptions"; import { Button } from "./ui/button"; import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover"; +import { FlyoutAppearanceProvider, FlyoutHeader } from "./ui/flyout"; +import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "./ui/dropdown-menu"; +export type { RoutineGroupBy, RoutineSortField, RoutineSortDir } from "@/lib/routine-list-view"; +export type RoutineFilterOptions = Partial>; -export type RoutineGroupBy = "folder" | "none" | "project" | "assignee"; -export type RoutineSortField = "updated" | "created" | "title" | "lastRun"; -export type RoutineSortDir = "asc" | "desc"; - -export function RoutinesToolbar({ query, onQueryChange, sortField, sortDir, groupBy, onSortChange, onGroupChange, onNewFolder, onCreateRoutine, tasksHref }: { +export function RoutinesToolbar({ query, onQueryChange, sortField, sortDir, groupBy, onSortChange, onGroupChange, onNewFolder, onCreateRoutine, tasksHref, filters = defaultRoutineView, filterOptions = {}, onFiltersChange, columns = defaultRoutineView.columns, onColumnsChange, showListControls = true }: { + showListControls?: boolean; query: string; onQueryChange: (value: string) => void; sortField: RoutineSortField; @@ -19,85 +23,66 @@ export function RoutinesToolbar({ query, onQueryChange, sortField, sortDir, grou onNewFolder?: () => void; onCreateRoutine: () => void; tasksHref?: string; + filters?: Pick; + filterOptions?: RoutineFilterOptions; + onFiltersChange?: (patch: Partial) => void; + columns?: RoutineColumn[]; + onColumnsChange?: (columns: RoutineColumn[]) => void; }) { - return
-
+ const [optionQueries, setOptionQueries] = useState>({}); + const activeFilters = routineFilterKeys.reduce((count, key) => count + filters[key].length, 0); + return
+ +
+ {showListControls ? <> - - - + + Sort
- {([ - ["updated", "Updated"], - ["created", "Created"], - ["lastRun", "Last run"], - ["title", "Title"], - ] as const).map(([field, label]) => ( - ))}
- - - - -
- {([ - ["folder", "Folder"], - ["project", "Project"], - ["assignee", "Agent"], - ["none", "None"], - ] as const).map(([value, label]) => ( - - ))} + + + Filters{activeFilters ? ` (${activeFilters})` : ""}{activeFilters ? : null} +
+ {([["projects", "Project"], ["agents", "Agent"], ["statuses", "Enabled"], ["responsibleUsers", "Responsible user"], ["origins", "Source"]] as const).map(([key, title]) => { + const selected = new Set(filters[key]); + const options = filterOptions[key] ?? []; + const visible = options.filter(option => option.name.toLowerCase().includes((optionQueries[key] ?? "").toLowerCase())); + return 6 ? title.toLowerCase() : undefined} query={optionQueries[key] ?? ""} onQueryChange={value => setOptionQueries(current => ({ ...current, [key]: value }))}> + {visible.map(option => onFiltersChange?.({ [key]: selected.has(option.id) ? filters[key].filter(value => value !== option.id) : [...filters[key], option.id] })} />)} + {!visible.length ?

No options

: null} +
; + })}
+ + + Group
+ {([["folder", "Folder"], ["project", "Project"], ["assignee", "Agent"], ["none", "None"]] as const).map(([value, label]) => )} + {onNewFolder ? : null} +
+
+ + + Columns + {routineColumns.map(column => event.preventDefault()} onCheckedChange={checked => onColumnsChange?.(checked ? routineColumns.filter(item => item.id === column.id || columns.includes(item.id)).map(item => item.id) : columns.filter(id => id !== column.id))}>{column.label})} + onColumnsChange?.([...defaultRoutineView.columns])}>Reset columns + + + : null} + {tasksHref ? : null}
-
- {tasksHref && } - {onNewFolder && } - -
-
; +
; } diff --git a/ui/src/hooks/useCoordinatorWorkspaceEnabled.ts b/ui/src/hooks/useCoordinatorWorkspaceEnabled.ts index 355c7a793b4..bbe86c4d1cb 100644 --- a/ui/src/hooks/useCoordinatorWorkspaceEnabled.ts +++ b/ui/src/hooks/useCoordinatorWorkspaceEnabled.ts @@ -1,8 +1,7 @@ import { useContext } from "react"; import { QueryClient, QueryClientContext, useQuery } from "@tanstack/react-query"; import { useAccountBoundMutation } from "./useAccountBoundMutation"; -import { authApi } from "@/api/auth"; -import { healthApi } from "@/api/health"; +import { useResolvedViewerId } from "./useResolvedViewerId"; import { workspacePreferencesApi } from "@/api/workspacePreferences"; import { queryKeys } from "@/lib/queryKeys"; @@ -12,20 +11,8 @@ const getDetachedClient = () => detachedClient ??= new QueryClient(); export function useCoordinatorWorkspaceEnabled() { const contextClient = useContext(QueryClientContext); const client = contextClient ?? getDetachedClient(); - const session = useQuery({ - queryKey: queryKeys.auth.session, - queryFn: () => authApi.getSession(), - enabled: contextClient != null, - }, client); - const sessionUserId = session.data?.user?.id ?? session.data?.session?.userId ?? null; - const health = useQuery({ - queryKey: queryKeys.health, - queryFn: () => healthApi.get(), - enabled: contextClient != null && session.isSuccess && !sessionUserId, - }, client); - const userId = session.isSuccess - ? sessionUserId ?? (health.isSuccess && health.data.deploymentMode === "local_trusted" ? "local-board" : null) - : null; + const viewer = useResolvedViewerId({ client, enabled: contextClient != null }); + const { userId } = viewer; const preference = useQuery({ queryKey: queryKeys.workspacePreferences.mine(userId), queryFn: () => workspacePreferencesApi.get(), @@ -44,12 +31,11 @@ export function useCoordinatorWorkspaceEnabled() { }, client); const classicWorkspaceEnabled = !!userId && preference.isSuccess && preference.data.userId === userId && preference.data.coordinatorWorkspaceEnabled === false; - const identityLoaded = session.isFetched && (!!sessionUserId || session.isError || health.isFetched); return { enabled: !!contextClient && !classicWorkspaceEnabled, - loaded: !contextClient || (identityLoaded && (!userId || preference.isFetched)), + loaded: !contextClient || (viewer.loaded && (!userId || preference.isFetched)), userId, - error: session.error ?? (!sessionUserId ? health.error : null) ?? preference.error + error: viewer.error ?? preference.error ?? (mutation.variables?.owner === userId ? mutation.error : null), isSaving: mutation.isPending && mutation.variables?.owner === userId, setEnabled: async (companyId: string, enabled: boolean) => { @@ -58,8 +44,7 @@ export function useCoordinatorWorkspaceEnabled() { }, retry: async () => { mutation.reset(); - if (session.isError) return session.refetch(); - if (!sessionUserId && health.isError) return health.refetch(); + if (viewer.error) return viewer.retry(); if (userId) return preference.refetch(); }, }; diff --git a/ui/src/hooks/useResolvedViewerId.ts b/ui/src/hooks/useResolvedViewerId.ts new file mode 100644 index 00000000000..f7e3472fc97 --- /dev/null +++ b/ui/src/hooks/useResolvedViewerId.ts @@ -0,0 +1,20 @@ +import { useQuery, type QueryClient } from "@tanstack/react-query"; +import { authApi } from "@/api/auth"; +import { healthApi } from "@/api/health"; +import { queryKeys } from "@/lib/queryKeys"; + +export function useResolvedViewerId(options?: { client?: QueryClient; enabled?: boolean }) { + const enabled = options?.enabled ?? true; + const session = useQuery({ queryKey: queryKeys.auth.session, queryFn: () => authApi.getSession(), enabled }, options?.client); + const sessionUserId = session.data?.user?.id ?? session.data?.session?.userId ?? null; + const health = useQuery({ queryKey: queryKeys.health, queryFn: () => healthApi.get(), enabled: enabled && session.isSuccess && !sessionUserId }, options?.client); + return { + userId: session.isSuccess ? sessionUserId ?? (health.isSuccess && health.data.deploymentMode === "local_trusted" ? "local-board" : null) : null, + loaded: session.isFetched && (!!sessionUserId || session.isError || health.isFetched), + error: session.error ?? (!sessionUserId ? health.error : null), + retry: async () => { + if (session.isError) return session.refetch(); + if (!sessionUserId && health.isError) return health.refetch(); + }, + }; +} diff --git a/ui/src/hooks/useRoutineListView.test.tsx b/ui/src/hooks/useRoutineListView.test.tsx new file mode 100644 index 00000000000..41da76b1ae3 --- /dev/null +++ b/ui/src/hooks/useRoutineListView.test.tsx @@ -0,0 +1,145 @@ +// @vitest-environment jsdom +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { MemoryRouter, useLocation, useNavigate } from "react-router-dom"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { queryKeys } from "@/lib/queryKeys"; +import { defaultRoutineView, routineViewStorageKey } from "@/lib/routine-list-view"; +import { useRoutineListView } from "./useRoutineListView"; +import { authApi } from "@/api/auth"; + +vi.mock("@/lib/router", async () => { + const router = await import("react-router-dom"); + return { useSearchParams: router.useSearchParams }; +}); +vi.mock("@/api/auth", () => ({ authApi: { getSession: vi.fn() } })); + +let current: ReturnType; +let search = ""; +let navigate: ReturnType; +function Harness({ companyId }: { companyId: string }) { + current = useRoutineListView(companyId); + search = useLocation().search; + navigate = useNavigate(); + return {JSON.stringify(current[0])}; +} + +describe("routine view persistence", () => { + let container: HTMLDivElement; + let root: Root; + let client: QueryClient; + beforeEach(() => { + localStorage.clear(); + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } }); + client.setQueryData(queryKeys.auth.session, { user: { id: "u1" } }); + }); + afterEach(async () => { + await act(() => root.unmount()); + client.clear(); + container.remove(); + vi.restoreAllMocks(); + }); + async function render(companyId = "c1", entry = "/routines") { + await act(() => root.render()); + } + + it("restores changed filters and columns after a remount and isolates other people and companies", async () => { + await render(); + await act(() => current[1]({ projects: ["p1"], query: "weekly", groupBy: "none", sortField: "created", sortDir: "desc" })); + await act(() => current[1]({ columns: ["assignee", "responsibleUser"], collapsedGroups: ["g1"] })); + expect(new URLSearchParams(search).get("projects")).toBe("p1"); + expect(new URLSearchParams(search).get("q")).toBe("weekly"); + expect(JSON.parse(localStorage.getItem(routineViewStorageKey("c1", "u1"))!)).toEqual(current[0]); + await act(() => root.unmount()); + root = createRoot(container); + await render(); + expect(current[0]).toMatchObject({ projects: ["p1"], query: "weekly", columns: ["assignee", "responsibleUser"], collapsedGroups: ["g1"], sortField: "created", sortDir: "desc", groupBy: "none" }); + await render("c2"); + expect(current[0]).toEqual(defaultRoutineView); + await act(() => client.setQueryData(queryKeys.auth.session, { user: { id: "u2" } })); + await render(); + expect(current[0]).toEqual(defaultRoutineView); + }); + + it("lets shared and cleared URLs override saved filters during navigation", async () => { + localStorage.setItem(routineViewStorageKey("c1", "u1"), JSON.stringify({ ...defaultRoutineView, projects: ["saved"], statuses: ["paused"] })); + await render("c1", "/routines?projects=shared"); + expect(current[0].projects).toEqual(["shared"]); + expect(current[0].statuses).toEqual([]); + await act(() => navigate("/routines?filters=1")); + expect(current[0].projects).toEqual([]); + await act(() => navigate(-1)); + expect(current[0].projects).toEqual(["shared"]); + }); + + it("keeps controls usable when browser storage is unavailable", async () => { + vi.spyOn(Storage.prototype, "getItem").mockImplementation(() => { throw new Error("Storage unavailable"); }); + vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { throw new Error("Storage unavailable"); }); + await render(); + await act(() => current[1]({ columns: ["assignee"], agents: ["a1"] })); + expect(current[0].columns).toEqual(["assignee"]); + expect(current[0].agents).toEqual(["a1"]); + expect(new URLSearchParams(search).get("agents")).toBe("a1"); + }); + + it("restores and saves local-trusted preferences without an account", async () => { + client.setQueryData(queryKeys.auth.session, null); + client.setQueryData(queryKeys.health, { deploymentMode: "local_trusted" }); + localStorage.setItem("paperclip:routines-view:c1", JSON.stringify({ groupBy: "none", sortField: "created" })); + await render(); + expect(current[0].groupBy).toBe("none"); + await act(() => current[1]({ columns: ["assignee"], collapsedGroups: ["g1"] })); + expect(JSON.parse(localStorage.getItem(routineViewStorageKey("c1", "local-board"))!)).toMatchObject({ columns: ["assignee"], collapsedGroups: ["g1"] }); + await act(() => root.unmount()); + root = createRoot(container); + await render(); + expect(current[0].columns).toEqual(["assignee"]); + }); + + it("retains controls changed while the session is loading", async () => { + client.removeQueries({ queryKey: queryKeys.auth.session }); + let resolveSession!: (value: Awaited>) => void; + vi.mocked(authApi.getSession).mockReturnValue(new Promise(resolve => { resolveSession = resolve; })); + localStorage.setItem(routineViewStorageKey("c1", "u1"), JSON.stringify({ ...defaultRoutineView, columns: ["project"], groupBy: "none" })); + await render(); + await act(() => current[1]({ columns: ["assignee"], collapsedGroups: ["g1"] })); + await act(async () => { resolveSession({ user: { id: "u1" } } as Awaited>); }); + await vi.waitFor(() => expect(client.getQueryData(queryKeys.auth.session)).toMatchObject({ user: { id: "u1" } })); + await vi.waitFor(() => expect(current[0].groupBy).toBe("none")); + expect(current[0].columns).toEqual(["assignee"]); + expect(JSON.parse(localStorage.getItem(routineViewStorageKey("c1", "u1"))!)).toMatchObject({ columns: ["assignee"], collapsedGroups: ["g1"] }); + }); + + it("does not use local-board preferences for an unsigned authenticated deployment", async () => { + client.setQueryData(queryKeys.auth.session, null); + client.setQueryData(queryKeys.health, { deploymentMode: "authenticated" }); + await render(); + await act(() => current[1]({ columns: ["assignee"] })); + expect(localStorage.getItem(routineViewStorageKey("c1", "local-board"))).toBeNull(); + }); + + it("keeps personal filters when changing columns on a shared link", async () => { + localStorage.setItem(routineViewStorageKey("c1", "u1"), JSON.stringify({ ...defaultRoutineView, projects: ["personal"], groupBy: "none" })); + await render("c1", "/routines?projects=shared"); + await act(() => current[1]({ columns: ["assignee"] })); + expect(current[0].projects).toEqual(["shared"]); + expect(JSON.parse(localStorage.getItem(routineViewStorageKey("c1", "u1"))!)).toMatchObject({ projects: ["personal"], columns: ["assignee"] }); + await act(() => current[1]({ statuses: ["paused"] })); + await act(() => current[1]({ collapsedGroups: ["g1"] })); + expect(JSON.parse(localStorage.getItem(routineViewStorageKey("c1", "u1"))!)).toMatchObject({ projects: ["shared"], statuses: ["paused"], collapsedGroups: ["g1"] }); + }); + + it("restores personal filters after leaving a shared link with changed columns", async () => { + localStorage.setItem(routineViewStorageKey("c1", "u1"), JSON.stringify({ ...defaultRoutineView, projects: ["personal"], statuses: ["paused"] })); + await render("c1", "/routines?projects=shared"); + await act(() => current[1]({ columns: ["assignee"], collapsedGroups: ["g1"] })); + await act(() => navigate("/routines")); + expect(current[0]).toMatchObject({ projects: ["personal"], statuses: ["paused"], columns: ["assignee"], collapsedGroups: ["g1"] }); + await act(() => navigate(-1)); + expect(current[0].projects).toEqual(["shared"]); + }); +}); diff --git a/ui/src/hooks/useRoutineListView.ts b/ui/src/hooks/useRoutineListView.ts new file mode 100644 index 00000000000..94a987712d9 --- /dev/null +++ b/ui/src/hooks/useRoutineListView.ts @@ -0,0 +1,45 @@ +import { useEffect, useMemo, useState } from "react"; +import { useSearchParams } from "@/lib/router"; +import { useResolvedViewerId } from "./useResolvedViewerId"; +import { readRoutineView, routineViewStorageKey, writeRoutineViewParams, type RoutineViewState } from "@/lib/routine-list-view"; + +function changesLinkedView(patch: Partial) { + return Object.keys(patch).some(field => !["columns", "collapsedGroups"].includes(field)); +} + +export function useRoutineListView(companyId: string | null) { + const { userId } = useResolvedViewerId(); + const key = companyId && userId ? routineViewStorageKey(companyId, userId) : null; + const [params, setParams] = useSearchParams(); + const saved = useMemo(() => { + try { + if (!key) return null; + const current = localStorage.getItem(key); + if (current) return JSON.parse(current); + const legacy = JSON.parse(localStorage.getItem(`paperclip:routines-view:${companyId}`) ?? "null"); + return legacy ? { sortField: legacy.sortField, sortDir: legacy.sortDir, groupBy: legacy.groupBy, collapsedGroups: legacy.collapsedGroups } : null; + } + catch { return null; } + }, [key, companyId]); + const [edits, setEdits] = useState<{ key: string | null; companyId: string | null; patch: Partial }>({ key, companyId, patch: {} }); + let scopedEdits = edits; + if (edits.key !== key || edits.companyId !== companyId) { + scopedEdits = { key, companyId, patch: edits.companyId === companyId && edits.key === null ? edits.patch : {} }; + setEdits(scopedEdits); + } + const personalView = useMemo(() => readRoutineView(new URLSearchParams(), { ...saved, ...scopedEdits.patch }), [saved, scopedEdits.patch]); + const search = params.toString(); + const state = useMemo(() => readRoutineView(new URLSearchParams(search), personalView), [search, personalView]); + useEffect(() => { + if (!key || !Object.keys(scopedEdits.patch).length) return; + try { localStorage.setItem(key, JSON.stringify(personalView)); } catch {} + }, [key, personalView, scopedEdits.patch]); + function update(patch: Partial) { + const next = { ...state, ...patch }; + setEdits({ key, companyId, patch: { ...scopedEdits.patch, ...(changesLinkedView(patch) ? next : patch) } }); + if (changesLinkedView(patch)) { + setParams(current => writeRoutineViewParams(current, next), { replace: true }); + } + } + return [state, update] as const; +} diff --git a/ui/src/index.css b/ui/src/index.css index 4ab91420307..2a804f91c75 100644 --- a/ui/src/index.css +++ b/ui/src/index.css @@ -5817,3 +5817,16 @@ html:has(.design-proposal-theme) .agent-markdown-name-field [data-slot="input"], .secret-value-masked { -webkit-text-security: disc; } + +:root { + --routine-title-min: calc(var(--spacing) * 48); + --routine-column-project: calc(var(--spacing) * 36); + --routine-column-assignee: calc(var(--spacing) * 36); + --routine-column-responsibleUser: calc(var(--spacing) * 36); + --routine-column-lastRun: calc(var(--spacing) * 52); + --routine-column-enabled: calc(var(--spacing) * 24); + --routine-actions-width: calc(var(--spacing) * 20); + --routine-select-width: calc(var(--spacing) * 6); +} +.routine-table { min-width: max-content; } +.routine-table-grid { display: grid; align-items: center; gap: calc(var(--spacing) * 3); } diff --git a/ui/src/lib/routine-list-data.test.ts b/ui/src/lib/routine-list-data.test.ts new file mode 100644 index 00000000000..c2c58723844 --- /dev/null +++ b/ui/src/lib/routine-list-data.test.ts @@ -0,0 +1,85 @@ +import type { FolderListResult, RoutineListItem } from "@paperclipai/shared"; +import { describe, expect, it } from "vitest"; +import { selectRoutineRows } from "./routine-list-data"; +import { defaultRoutineView } from "./routine-list-view"; + +describe("routine rows shared by current and Classic pages", () => { + it.each(["all", "folder-17", "unfiled"])("bounds filtering, sorting, and folder counts for %s", (selection) => { + const folderCount = 120; + const routineCount = folderCount * 10; + let rowReads = 0; + let selectionReads = 0; + const selectedIds = (prefix: string) => new Proxy( + Array.from({ length: folderCount }, (_, index) => `${prefix}-${index}`), + { + get(target, property, receiver) { + if (typeof property === "string" && /^\d+$/.test(property)) { + if (++selectionReads > folderCount * 6) { + throw new Error("Routine filtering repeatedly scans selected IDs"); + } + } + return Reflect.get(target, property, receiver); + }, + }, + ); + const date = new Date("2026-04-01T00:00:00Z"); + const folders: FolderListResult = { + kind: "routine", allCount: routineCount, unfiledCount: folderCount, + folders: Array.from({ length: folderCount }, (_, index) => ({ + id: `folder-${index}`, companyId: "company-1", kind: "routine", + name: `Folder ${index}`, slug: `folder-${index}`, path: `folder-${index}`, + parentId: null, systemKey: null, depth: 0, color: null, position: index, + createdAt: date, updatedAt: date, itemCount: 9, + })), + }; + const routines = Array.from({ length: routineCount }, (_, index) => { + const folder = Math.floor(index / 10); + const slot = index % 10; + const row: RoutineListItem = { + id: `routine-${index}`, companyId: "company-1", folderId: slot === 9 ? null : `folder-${folder}`, + title: `${slot === 1 ? "Maintenance" : "Weekly digest"} ${String(index).padStart(4, "0")}`, + description: "Operations", projectId: slot === 2 ? "excluded" : `project-${folder}`, + assigneeAgentId: slot === 3 ? "excluded" : `agent-${folder}`, + responsibleUserId: slot === 4 ? "excluded" : `user-${folder}`, + originKind: slot === 5 ? "built_in_agent_bundle" : "manual", + status: slot === 6 ? "paused" : slot === 7 ? "archived" : "active", + goalId: null, parentIssueId: null, priority: "medium", + concurrencyPolicy: "coalesce_if_active", catchUpPolicy: "skip_missed", + activityGatePolicy: "always", activityGateScope: "company", variables: [], + latestRevisionId: null, latestRevisionNumber: 1, + createdByAgentId: null, createdByUserId: null, updatedByAgentId: null, updatedByUserId: null, + lastTriggeredAt: null, lastEnqueuedAt: null, createdAt: date, updatedAt: date, + triggers: [], lastRun: null, activeIssue: null, + }; + return new Proxy(row, { + get(target, property, receiver) { + if (++rowReads > routineCount * 64) { + throw new Error("Routine selection exceeded its collection work limit"); + } + return Reflect.get(target, property, receiver); + }, + }); + }).reverse(); + + // Both Routines pages call this selector for the table and folder rail. + const result = selectRoutineRows(routines, { + ...defaultRoutineView, query: "weekly operations", statuses: ["active"], origins: ["manual"], + projects: selectedIds("project"), agents: selectedIds("agent"), responsibleUsers: selectedIds("user"), + }, folders, selection); + const measuredRowReads = rowReads; + const expectedIds = Array.from({ length: folderCount }, (_, folder) => + (selection === "unfiled" ? [9] : selection === "all" ? [0, 8, 9] : folder === 17 ? [0, 8] : []) + .map(slot => `routine-${folder * 10 + slot}`), + ).flat(); + + expect(result.sortedRoutines.map(row => row.id)).toEqual(expectedIds); + expect(result.visibleRoutines).toHaveLength(folderCount * 8); + expect(result.railFolderResult).toMatchObject({ allCount: folderCount * 8, unfiledCount: folderCount }); + expect(result.railFolderResult?.folders.map(folder => folder.itemCount)).toEqual(Array(folderCount).fill(7)); + expect(folders.folders[0].itemCount).toBe(9); + expect(selectionReads).toBeGreaterThanOrEqual(folderCount * 3); + expect(selectionReads).toBeLessThanOrEqual(folderCount * 6); + expect(measuredRowReads).toBeGreaterThanOrEqual(routineCount); + expect(measuredRowReads).toBeLessThanOrEqual(routineCount * 64); + }); +}); diff --git a/ui/src/lib/routine-list-data.ts b/ui/src/lib/routine-list-data.ts new file mode 100644 index 00000000000..cd5309f01eb --- /dev/null +++ b/ui/src/lib/routine-list-data.ts @@ -0,0 +1,75 @@ +import type { FolderListResult, RoutineListItem } from "@paperclipai/shared"; +import { filterRoutines, matchesRoutineStatus, type RoutineViewState, type RoutineSortField, type RoutineSortDir } from "./routine-list-view"; + +function timestampValue(value: Date | string | null | undefined) { + if (!value) return Number.NEGATIVE_INFINITY; + const timestamp = new Date(value).getTime(); + return Number.isFinite(timestamp) ? timestamp : Number.NEGATIVE_INFINITY; +} + +function compareNullableText(left: string | null | undefined, right: string | null | undefined) { + return (left ?? "").localeCompare(right ?? "", undefined, { sensitivity: "base" }); +} + + +export function sortRoutines( + routines: RoutineListItem[], + sortField: RoutineSortField, + sortDir: RoutineSortDir, +): RoutineListItem[] { + const direction = sortDir === "asc" ? 1 : -1; + return [...routines].sort((left, right) => { + let result = 0; + + if (sortField === "title") { + result = compareNullableText(left.title, right.title); + } else if (sortField === "created") { + result = timestampValue(left.createdAt) - timestampValue(right.createdAt); + } else if (sortField === "lastRun") { + result = timestampValue(left.lastRun?.triggeredAt ?? left.lastTriggeredAt) - + timestampValue(right.lastRun?.triggeredAt ?? right.lastTriggeredAt); + } else { + result = timestampValue(left.updatedAt) - timestampValue(right.updatedAt); + } + + if (result !== 0) return result * direction; + return compareNullableText(left.title, right.title); + }); +} + +export function buildRoutineFilterOptions({ projects, agents, userById, routines }: { + projects: readonly { id: string; name: string }[]; + agents: readonly { id: string; name: string }[]; + userById: ReadonlyMap; + routines: readonly RoutineListItem[]; +}) { + return { + projects: [{ id: "__none", name: "No project" }, ...projects.map(project => ({ id: project.id, name: project.name }))], + agents: [{ id: "__none", name: "No default agent" }, ...agents.map(agent => ({ id: agent.id, name: agent.name }))], + responsibleUsers: [{ id: "__none", name: "No responsible user" }, ...Array.from(userById, ([id, profile]) => ({ id, name: profile.label }))], + statuses: [{ id: "active", name: "Enabled" }, { id: "paused", name: "Paused" }, { id: "archived", name: "Archived" }], + origins: [...new Set(["manual", "built_in_agent_bundle", ...routines.map(routine => routine.originKind ?? "manual")])].map(id => ({ id, name: id === "manual" ? "Custom" : id === "built_in_agent_bundle" ? "Built-in" : id.replaceAll("_", " ") })), + }; +} + +export function selectRoutineRows(routines: RoutineListItem[], view: RoutineViewState, folders: FolderListResult | undefined, folderSelection: string) { + const visibleRoutines = routines.filter(routine => matchesRoutineStatus(routine.status, view.statuses)); + const inFolder = view.groupBy !== "folder" || !folders || folderSelection === "all" + ? visibleRoutines + : visibleRoutines.filter(routine => folderSelection === "unfiled" ? !routine.folderId : routine.folderId === folderSelection); + const sortedRoutines = sortRoutines(filterRoutines(inFolder, view), view.sortField, view.sortDir); + if (!folders) return { visibleRoutines, sortedRoutines, railFolderResult: folders }; + const counts = new Map(); + let unfiled = 0; + for (const routine of visibleRoutines) { + if (routine.folderId) counts.set(routine.folderId, (counts.get(routine.folderId) ?? 0) + 1); + else unfiled += 1; + } + return { + visibleRoutines, + sortedRoutines, + railFolderResult: { ...folders, allCount: visibleRoutines.length, unfiledCount: unfiled, + folders: folders.folders.map(folder => ({ ...folder, itemCount: counts.get(folder.id) ?? 0 })), + }, + }; +} diff --git a/ui/src/lib/routine-list-view.test.ts b/ui/src/lib/routine-list-view.test.ts new file mode 100644 index 00000000000..4894815842e --- /dev/null +++ b/ui/src/lib/routine-list-view.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from "vitest"; +import { defaultRoutineView, readRoutineView, writeRoutineViewParams, filterRoutines, routineViewStorageKey } from "./routine-list-view"; + +describe("routine list views", () => { + it("uses linked filters instead of the recipient's saved filters", () => { + const saved = { ...defaultRoutineView, query: "saved", projects: ["other"], statuses: ["paused"] }; + const linked = readRoutineView(new URLSearchParams("projects=p1&agents=a1"), saved); + expect(linked).toMatchObject({ query: "", projects: ["p1"], agents: ["a1"], statuses: [] }); + }); + it("round trips an explicitly cleared view and preserves unrelated URL state", () => { + const params = writeRoutineViewParams(new URLSearchParams("folder=one&tab=routines"), defaultRoutineView); + expect(params.get("folder")).toBe("one"); + expect(readRoutineView(params, { ...defaultRoutineView, projects: ["saved"] }).projects).toEqual([]); + }); + it("validates malformed saved state and URL values", () => { + const view = readRoutineView(new URLSearchParams("sortField=oops&groupBy=oops&statuses=active,invalid"), { columns: ["project", "oops"], collapsedGroups: null }); + expect(view.sortField).toBe("title"); + expect(view.groupBy).toBe("folder"); + expect(view.columns).toEqual(["project"]); + expect(view.collapsedGroups).toEqual([]); + expect(view.statuses).toEqual(["active"]); + }); + it("applies AND across filter categories and OR within each category", () => { + const rows = [ + { title: "Weekly review", description: "company", projectId: "p1", assigneeAgentId: "a1", responsibleUserId: "u1", status: "active", originKind: "manual" }, + { title: "Weekly review", description: "company", projectId: "p1", assigneeAgentId: "a2", responsibleUserId: "u2", status: "paused", originKind: "manual" }, + ]; + expect(filterRoutines(rows, { ...defaultRoutineView, query: "company weekly", agents: ["a1", "a2"], responsibleUsers: ["u1"], statuses: ["active"] })).toEqual([rows[0]]); + expect(filterRoutines(rows, { ...defaultRoutineView, projects: ["__none"] })).toEqual([]); + }); + it("keeps preferences separate for each person and company", () => { + expect(routineViewStorageKey("c1", "u1")).not.toBe(routineViewStorageKey("c1", "u2")); + expect(routineViewStorageKey("c1", "u1")).not.toBe(routineViewStorageKey("c2", "u1")); + }); +}); diff --git a/ui/src/lib/routine-list-view.ts b/ui/src/lib/routine-list-view.ts new file mode 100644 index 00000000000..4a3adc88e81 --- /dev/null +++ b/ui/src/lib/routine-list-view.ts @@ -0,0 +1,80 @@ +export type RoutineGroupBy = "folder" | "none" | "project" | "assignee"; +export type RoutineSortField = "updated" | "created" | "title" | "lastRun"; +export type RoutineSortDir = "asc" | "desc"; +export const routineColumns = [ + { id: "project", label: "Project" }, + { id: "assignee", label: "Agent" }, + { id: "responsibleUser", label: "Responsible user" }, + { id: "lastRun", label: "Last run" }, + { id: "enabled", label: "Enabled" }, +] as const; +export type RoutineColumn = typeof routineColumns[number]["id"]; +export const routineFilterKeys = ["projects", "agents", "statuses", "responsibleUsers", "origins"] as const; +export type RoutineFilterKey = typeof routineFilterKeys[number]; +export type RoutineViewState = Record & { + query: string; + sortField: RoutineSortField; + sortDir: RoutineSortDir; + groupBy: RoutineGroupBy; + collapsedGroups: string[]; + columns: RoutineColumn[]; +}; +export const defaultRoutineView: RoutineViewState = { + query: "", projects: [], agents: [], statuses: [], responsibleUsers: [], origins: [], + sortField: "title", sortDir: "asc", groupBy: "folder", collapsedGroups: [], + columns: routineColumns.map(column => column.id), +}; +function strings(value: unknown): string[] { + return Array.isArray(value) ? [...new Set(value.filter((item): item is string => typeof item === "string" && !!item))] : []; +} +function choice(value: unknown, choices: readonly T[], fallback: T): T { + return choices.includes(value as T) ? value as T : fallback; +} +export function readRoutineView(params: URLSearchParams, saved: unknown = {}): RoutineViewState { + const raw = saved && typeof saved === "object" ? saved as Record : {}; + const linked = params.has("filters") || params.has("q") || routineFilterKeys.some(key => params.has(key)); + const filters = Object.fromEntries(routineFilterKeys.map(key => [key, linked + ? strings(params.getAll(key).flatMap(value => value.split(","))) : strings(raw[key])])) as Pick; + filters.statuses = filters.statuses.filter(value => ["active", "paused", "archived"].includes(value)); + return { + ...filters, + query: linked ? params.get("q") ?? "" : typeof raw.query === "string" ? raw.query : "", + sortField: choice(params.get("sortField") ?? raw.sortField, ["updated", "created", "title", "lastRun"], "title"), + sortDir: choice(params.get("sortDir") ?? raw.sortDir, ["asc", "desc"], "asc"), + groupBy: choice(params.get("groupBy") ?? raw.groupBy, ["folder", "none", "project", "assignee"], "folder"), + columns: Array.isArray(raw.columns) ? routineColumns.filter(column => strings(raw.columns).includes(column.id)).map(column => column.id) : [...defaultRoutineView.columns], + collapsedGroups: strings(raw.collapsedGroups), + }; +} +export function writeRoutineViewParams(current: URLSearchParams, view: RoutineViewState) { + const params = new URLSearchParams(current); + params.set("filters", "1"); + params.delete("q"); + if (view.query) params.set("q", view.query); + for (const key of routineFilterKeys) { + params.delete(key); + for (const value of view[key]) params.append(key, value); + } + params.set("sortField", view.sortField); + params.set("sortDir", view.sortDir); + params.set("groupBy", view.groupBy); + return params; +} +export function routineViewStorageKey(companyId: string, userId: string) { + return `paperclip:routines-view:${companyId}:user:${userId}`; +} +export function matchesRoutineStatus(status: string, statuses: readonly string[]) { + return statuses.length ? statuses.includes(status) : status !== "archived"; +} +export function filterRoutines(rows: T[], view: RoutineViewState): T[] { + const terms = view.query.toLowerCase().trim().split(/\s+/).filter(Boolean); + const selections = Object.fromEntries(routineFilterKeys.map(key => [key, new Set(view[key])])) as Record>; + const matches = (key: RoutineFilterKey, value: string | null | undefined) => !selections[key].size || selections[key].has(value ?? "__none"); + return rows.filter(row => { + const text = `${row.title} ${row.description ?? ""}`.toLowerCase(); + return terms.every(term => text.includes(term)) + && matches("projects", row.projectId) && matches("agents", row.assigneeAgentId) + && matches("responsibleUsers", row.responsibleUserId) && matches("origins", row.originKind ?? "manual") + && matchesRoutineStatus(row.status, view.statuses); + }); +} diff --git a/ui/src/pages/Routines.production.tsx b/ui/src/pages/Routines.production.tsx index 1389abe63c3..5661b0907e5 100644 --- a/ui/src/pages/Routines.production.tsx +++ b/ui/src/pages/Routines.production.tsx @@ -1,16 +1,22 @@ +import { useRoutineListView } from "../hooks/useRoutineListView"; +import { routineFilterKeys } from "../lib/routine-list-view"; +import { buildRoutineFilterOptions, selectRoutineRows } from "../lib/routine-list-data"; +import { RoutineTable } from "../components/RoutineTable"; import { companyProjectsQuery } from "@/lib/company-projects-query"; import { startTransition, useEffect, useMemo, useState } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { Link, useNavigate, useSearchParams } from "@/lib/router"; -import { ArrowUpDown, Check, ChevronRight, Layers, Plus, Repeat } from "lucide-react"; +import { ChevronRight, Plus, Repeat } from "lucide-react"; import { routinesApi } from "../api/routines"; import { foldersApi } from "../api/folders"; import { agentsApi } from "../api/agents"; +import { accessApi } from "../api/access"; import { issuesApi } from "../api/issues"; import { heartbeatsApi } from "../api/heartbeats"; import { useCompany } from "../context/CompanyContext"; import { useBreadcrumbs } from "../context/BreadcrumbContext"; import { useToastActions } from "../context/ToastContext"; +import { buildCompanyUserProfileMap } from "../lib/company-members"; import { cn } from "../lib/utils"; import { queryKeys } from "../lib/queryKeys"; import { groupBy } from "../lib/groupBy"; @@ -23,7 +29,7 @@ import { PageSkeleton } from "../components/PageSkeleton"; import { QueryErrorState, useQueryView } from "../components/QueryView"; import { describeError } from "../api/errors"; import { PageTabBar } from "../components/PageTabBar"; -import { RoutineListRow, nextRoutineStatus } from "../components/RoutineList"; +import { RoutineTableRow, nextRoutineStatus } from "../components/RoutineList"; import { RoutineCreateDialog } from "../components/routine-page/RoutineCreateDialog"; import { RoutineRunVariablesDialog, @@ -32,7 +38,7 @@ import { import { Button } from "@/components/ui/button"; import { Card, CardContent } from "@/components/ui/card"; import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"; -import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; +import { RoutinesToolbar, type RoutineGroupBy } from "@/components/RoutinesToolbar"; import { Tabs, TabsContent } from "@/components/ui/tabs"; import type { RoutineListItem } from "@paperclipai/shared"; import type { FolderListItem } from "@paperclipai/shared"; @@ -54,17 +60,6 @@ import { type RoutinesTab = "routines" | "runs"; -type RoutineGroupBy = "folder" | "none" | "project" | "assignee"; -type RoutineSortField = "updated" | "created" | "title" | "lastRun"; -type RoutineSortDir = "asc" | "desc"; - -type RoutineViewState = { - sortField: RoutineSortField; - sortDir: RoutineSortDir; - groupBy: RoutineGroupBy; - collapsedGroups: string[]; -}; - type RoutineGroup = { key: string; label: string | null; @@ -73,36 +68,6 @@ type RoutineGroup = { const builtInRoutineGroupKey = "__built_in_routines"; -const defaultRoutineViewState: RoutineViewState = { - sortField: "title", - sortDir: "asc", - groupBy: "folder", - collapsedGroups: [], -}; - -function getRoutineViewState(key: string): RoutineViewState { - try { - const raw = localStorage.getItem(key); - if (raw) return { ...defaultRoutineViewState, ...JSON.parse(raw) }; - } catch { - // Ignore malformed local state and fall back to defaults. - } - return { ...defaultRoutineViewState }; -} - -function saveRoutineViewState(key: string, state: RoutineViewState) { - localStorage.setItem(key, JSON.stringify(state)); -} - -function timestampValue(value: Date | string | null | undefined) { - if (!value) return Number.NEGATIVE_INFINITY; - const timestamp = new Date(value).getTime(); - return Number.isFinite(timestamp) ? timestamp : Number.NEGATIVE_INFINITY; -} - -function compareNullableText(left: string | null | undefined, right: string | null | undefined) { - return (left ?? "").localeCompare(right ?? "", undefined, { sensitivity: "base" }); -} type RoutineFolderGroupMeta = { name: string; position?: number | null }; @@ -209,30 +174,6 @@ export function buildRoutineSections( ]; } -export function sortRoutines( - routines: RoutineListItem[], - sortField: RoutineSortField, - sortDir: RoutineSortDir, -): RoutineListItem[] { - const direction = sortDir === "asc" ? 1 : -1; - return [...routines].sort((left, right) => { - let result = 0; - - if (sortField === "title") { - result = compareNullableText(left.title, right.title); - } else if (sortField === "created") { - result = timestampValue(left.createdAt) - timestampValue(right.createdAt); - } else if (sortField === "lastRun") { - result = timestampValue(left.lastRun?.triggeredAt ?? left.lastTriggeredAt) - - timestampValue(right.lastRun?.triggeredAt ?? right.lastTriggeredAt); - } else { - result = timestampValue(left.updatedAt) - timestampValue(right.updatedAt); - } - - if (result !== 0) return result * direction; - return compareNullableText(left.title, right.title); - }); -} function buildRoutinesTabHref(tab: RoutinesTab) { return tab === "runs" ? "/routines?tab=runs" : "/routines"; @@ -286,20 +227,14 @@ export function Routines() { const [composerOpen, setComposerOpen] = useState(false); const [createFolderId, setCreateFolderId] = useState(null); const activeTab: RoutinesTab = searchParams.get("tab") === "runs" ? "runs" : "routines"; - const routineViewStateKey = selectedCompanyId - ? `paperclip:routines-view:${selectedCompanyId}` - : "paperclip:routines-view"; - const [routineViewState, setRoutineViewState] = useState(() => getRoutineViewState(routineViewStateKey)); + const [routineViewState, updateRoutineView] = useRoutineListView(selectedCompanyId); + const query = routineViewState.query; const folderSelection = normalizeFolderSelection(searchParams.get("folder")); useEffect(() => { setBreadcrumbs([{ label: "Routines" }]); }, [setBreadcrumbs]); - useEffect(() => { - setRoutineViewState(getRoutineViewState(routineViewStateKey)); - }, [routineViewStateKey]); - const routinesQuery = useQuery({ queryKey: queryKeys.routines.list(selectedCompanyId!), queryFn: () => routinesApi.list(selectedCompanyId!), @@ -321,6 +256,13 @@ export function Routines() { ...companyProjectsQuery(selectedCompanyId!, { includeArchived: true }), enabled: !!selectedCompanyId, }); + const companyMembersQuery = useQuery({ + queryKey: queryKeys.access.companyUserDirectory(selectedCompanyId!), + queryFn: () => accessApi.listUserDirectory(selectedCompanyId!), + enabled: !!selectedCompanyId, + }); + const { data: companyMembers } = companyMembersQuery; + const companyMembersView = useQueryView(companyMembersQuery); const recentRunsQuery = useQuery({ queryKey: [...queryKeys.issues.list(selectedCompanyId!), "routine-executions"], queryFn: () => issuesApi.list(selectedCompanyId!, { originKind: "routine_execution" }), @@ -517,39 +459,11 @@ export function Routines() { [routineFolders], ); const liveIssueIds = useMemo(() => collectLiveIssueIds(liveRuns, routineExecutionIssues), [liveRuns, routineExecutionIssues]); - const visibleRoutines = useMemo( - () => (routines ?? []).filter((routine) => routine.status !== "archived"), - [routines], - ); - const folderFilteredRoutines = useMemo(() => { - if (routineViewState.groupBy !== "folder") return visibleRoutines; - if (folderSelection === "all") return visibleRoutines; - if (folderSelection === "unfiled") return visibleRoutines.filter((routine) => !routine.folderId); - return visibleRoutines.filter((routine) => routine.folderId === folderSelection); - }, [folderSelection, routineViewState.groupBy, visibleRoutines]); - // Rail counts reflect the page's visible scope (archived hidden), not raw DB - // counts (ux-spec §5.3). - const railFolderResult = useMemo(() => { - if (!routineFolders) return routineFolders; - const counts = new Map(); - let unfiled = 0; - for (const routine of visibleRoutines) { - if (routine.folderId) counts.set(routine.folderId, (counts.get(routine.folderId) ?? 0) + 1); - else unfiled += 1; - } - return { - ...routineFolders, - allCount: visibleRoutines.length, - unfiledCount: unfiled, - folders: routineFolders.folders.map((folder) => ({ - ...folder, - itemCount: counts.get(folder.id) ?? 0, - })), - }; - }, [routineFolders, visibleRoutines]); - const sortedRoutines = useMemo( - () => sortRoutines(folderFilteredRoutines, routineViewState.sortField, routineViewState.sortDir), - [folderFilteredRoutines, routineViewState.sortDir, routineViewState.sortField], + const userById = useMemo(() => buildCompanyUserProfileMap(companyMembers?.users), [companyMembers]); + const filterOptions = useMemo(() => buildRoutineFilterOptions({ projects: projects ?? [], agents: agents ?? [], userById, routines: routines ?? [] }), [projects, agents, userById, routines]); + const { visibleRoutines, sortedRoutines, railFolderResult } = useMemo( + () => selectRoutineRows(routines ?? [], routineViewState, routineFolders, folderSelection), + [routines, routineViewState, routineFolders, folderSelection], ); const routineSections = useMemo( () => buildRoutineSections(sortedRoutines, routineViewState.groupBy, projectById, agentById, folderById), @@ -568,19 +482,8 @@ export function Routines() { const hasRoutineFolders = (routineFolders?.folders.length ?? 0) > 0; const showFolderRail = activeTab === "routines" && routineViewState.groupBy === "folder" && hasRoutineFolders; - function updateRoutineView(patch: Partial) { - setRoutineViewState((current) => { - const next = { ...current, ...patch }; - saveRoutineViewState(routineViewStateKey, next); - return next; - }); - } - function handleTabChange(tab: string) { - const nextTab = tab === "runs" ? "runs" : "routines"; - startTransition(() => { - navigate(buildRoutinesTabHref(nextTab)); - }); + startTransition(() => navigate(buildRoutinesTabHref(tab === "runs" ? "runs" : "routines"))); } function setFolderSelection(selection: FolderSelection) { @@ -663,20 +566,19 @@ export function Routines() { return (
-
-
-

- Routines -

-

- Recurring work definitions that materialize into auditable execution tasks. -

-
- -
+

Routines

+ updateRoutineView({ query })} + sortField={routineViewState.sortField} sortDir={routineViewState.sortDir} groupBy={routineViewState.groupBy} + onSortChange={(sortField, sortDir) => updateRoutineView({ sortField, sortDir })} + onGroupChange={groupBy => updateRoutineView({ groupBy, collapsedGroups: [] })} + onNewFolder={routineViewState.groupBy === "folder" && routineFolders && !hasRoutineFolders ? () => openCreateFolder() : undefined} + onCreateRoutine={openCreateRoutine} + filters={routineViewState} filterOptions={filterOptions} onFiltersChange={updateRoutineView} + columns={routineViewState.columns} onColumnsChange={columns => updateRoutineView({ columns })} + tasksHref="/issues?view=all&originKind=routine_execution&sortField=created&sortDir=desc" + /> -
-

- {visibleRoutines.length} routine{visibleRoutines.length === 1 ? "" : "s"} -

-
- - - - - -
- {([ - ["updated", "Updated"], - ["created", "Created"], - ["lastRun", "Last run"], - ["title", "Title"], - ] as const).map(([field, label]) => ( - - ))} -
-
-
- - - - - -
- {([ - ["folder", "Folder"], - ["project", "Project"], - ["assignee", "Agent"], - ["none", "None"], - ] as const).map(([value, label]) => ( - - ))} -
-
-
- {routineViewState.groupBy === "folder" && !hasRoutineFolders ? ( - - ) : null} - {showFolderRail ? ( - - ) : null} -
-
{routineViewState.groupBy === "folder" ? (
) : null} + {activeTab === "routines" && companyMembersView.kind === "error" ? ( + + ) : null} + {activeTab === "routines" ? (
{showFolderRail ? ( @@ -863,6 +680,7 @@ export function Routines() { onCreateFolder={() => openCreateFolder()} /> ) : null} + {showFolderRail ? : null} {selectMode ? ( ) : null} - {visibleRoutines.length === 0 ? ( + {visibleRoutines.length === 0 && !routineViewState.statuses.length ? (
) : sortedRoutines.length === 0 ? (
routineViewState[key].length) || folderSelection === "all" ? "No routines match this view." : "This folder is empty."} /> {folderSelection !== "all" ? (
@@ -922,10 +740,13 @@ export function Routines() { /> ) : null} + {group.items.map((routine) => ( - ))} + ); diff --git a/ui/src/pages/Routines.test.tsx b/ui/src/pages/Routines.test.tsx index c4e3ce7f935..1c03438fcb8 100644 --- a/ui/src/pages/Routines.test.tsx +++ b/ui/src/pages/Routines.test.tsx @@ -1,6 +1,6 @@ // @vitest-environment jsdom -import type { AnchorHTMLAttributes, ComponentProps, ReactNode } from "react"; +import { useState, type AnchorHTMLAttributes, type ComponentProps, type ReactNode } from "react"; import { flushSync } from "react-dom"; import { createRoot } from "react-dom/client"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; @@ -8,8 +8,11 @@ import type { FolderListResult, Issue, RoutineListItem } from "@paperclipai/shar import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { queryKeys } from "../lib/queryKeys"; import type { RequestOptions } from "../api/client"; -import { Routines, buildRoutineGroups, buildRoutineSections, sortRoutines } from "./Routines"; +import { Routines, buildRoutineGroups, buildRoutineSections } from "./Routines"; +import { Routines as CurrentRoutines } from "./Routines.production"; +import { sortRoutines } from "../lib/routine-list-data"; import { routinesApi } from "../api/routines"; +import { accessApi } from "../api/access"; let currentSearch = ""; @@ -41,7 +44,13 @@ vi.mock("@/lib/router", () => ({ ), useNavigate: () => navigateMock, useLocation: () => ({ pathname: "/routines", search: currentSearch ? `?${currentSearch}` : "", hash: "" }), - useSearchParams: () => [new URLSearchParams(currentSearch), vi.fn()], + useSearchParams: () => { + const [, rerender] = useState(0); + return [new URLSearchParams(currentSearch), (update: URLSearchParams | ((params: URLSearchParams) => URLSearchParams)) => { + currentSearch = (typeof update === "function" ? update(new URLSearchParams(currentSearch)) : update).toString(); + rerender(count => count + 1); + }]; + }, })); vi.mock("../context/CompanyContext", () => ({ @@ -56,6 +65,8 @@ vi.mock("../context/ToastContext", () => ({ useToastActions: () => ({ pushToast: vi.fn() }), })); +vi.mock("../api/auth", () => ({ authApi: { getSession: vi.fn(async () => ({ user: { id: "user-1" } })) } })); + vi.mock("../api/routines", () => ({ routinesApi: { list: (companyId: string) => routinesListMock(companyId), @@ -732,6 +743,35 @@ describe("Routines page", () => { } }); + it.each([["classic", Routines], ["current", CurrentRoutines]] as const)("keeps %s routines readable when the people directory fails and restores names on retry", async (_variant, Page) => { + routinesListMock.mockResolvedValue([createRoutine({ title: "Owned routine", responsibleUserId: "user-1" })]); + vi.mocked(accessApi.listUserDirectory).mockRejectedValueOnce(new Error("Could not load responsible people")); + const root = createRoot(container); + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + + try { + await act(async () => { + root.render(); + await flush(); + }); + await act(async () => { await flush(); }); + const routineLink = container.querySelector('a[href="/routines/routine-1"]'); + expect(routineLink).not.toBeNull(); + const alert = container.querySelector('[role="alert"]'); + expect(alert?.textContent).toContain("Could not load responsible people"); + const retry = alert?.querySelector("button"); + expect(retry?.textContent).toBe("Retry"); + await act(async () => { retry!.click(); await flush(); }); + await act(async () => { await flush(); }); + expect(container.querySelector('[role="alert"]')).toBeNull(); + expect(container.querySelector('a[href="/routines/routine-1"]')).toBe(routineLink); + expect(container.textContent).toContain("Taylor"); + } finally { + await act(() => root.unmount()); + queryClient.clear(); + } + }); + it("bounds a stalled folder request and leaves routines accessible with a retry", async () => { const actual = await vi.importActual("../api/folders"); routinesListMock.mockResolvedValue([createRoutine({ title: "Accessible after timeout", folderId: "folder-1" })]); @@ -1104,14 +1144,14 @@ describe("Routines page", () => { }); let runNowButton = Array.from(container.querySelectorAll("button")).find((button) => - button.textContent?.includes("Run now"), + button.getAttribute("aria-label") === "Run now: Morning sync", ); for (let attempts = 0; attempts < 5 && !runNowButton; attempts += 1) { await act(async () => { await flush(); }); runNowButton = Array.from(container.querySelectorAll("button")).find((button) => - button.textContent?.includes("Run now"), + button.getAttribute("aria-label") === "Run now: Morning sync", ); } @@ -1132,8 +1172,8 @@ describe("Routines page", () => { .filter(element => element.textContent?.trim() === text); try { await act(async () => { root.render(); await flush(); }); - await vi.waitFor(() => expect(buttons("Create routine").length).toBeGreaterThan(0)); - await act(async () => { buttons("Create routine")[0]!.click(); await flush(); }); + await vi.waitFor(() => expect(buttons("New routine").length).toBeGreaterThan(0)); + await act(async () => { buttons("New routine")[0]!.click(); await flush(); }); const dialog = document.querySelector('[role="dialog"]'); expect(dialog?.textContent).toContain("New routine"); const title = dialog!.querySelector("input[placeholder='Send the weekly digest']")!; @@ -1179,14 +1219,14 @@ describe("Routines page", () => { }); let createButton = Array.from(container.querySelectorAll("button")).find((button) => - button.textContent?.includes("Create routine"), + button.textContent?.includes("New routine"), ); for (let attempts = 0; attempts < 5 && !createButton; attempts += 1) { await act(async () => { await flush(); }); createButton = Array.from(container.querySelectorAll("button")).find((button) => - button.textContent?.includes("Create routine"), + button.textContent?.includes("New routine"), ); } @@ -1229,14 +1269,14 @@ describe("Routines page", () => { }); let createButton = Array.from(container.querySelectorAll("button")).find((button) => - button.textContent?.includes("Create routine"), + button.textContent?.includes("New routine"), ); for (let attempts = 0; attempts < 5 && !createButton; attempts += 1) { await act(async () => { await flush(); }); createButton = Array.from(container.querySelectorAll("button")).find((button) => - button.textContent?.includes("Create routine"), + button.textContent?.includes("New routine"), ); } @@ -1272,6 +1312,44 @@ describe("Routines page", () => { }); }); + it("opens linked filters and restores saved columns with responsible people beside agents", async () => { + currentSearch = "projects=project-1&responsibleUsers=user-1&statuses=active"; + localStorage.setItem("paperclip:routines-view:company-1:user:user-1", JSON.stringify({ + projects: ["project-2"], columns: ["assignee", "responsibleUser"], groupBy: "none", + })); + routinesListMock.mockResolvedValue([ + createRoutine({ id: "match", title: "Linked routine", responsibleUserId: "user-1" }), + createRoutine({ id: "other", title: "Other routine", projectId: "project-2", responsibleUserId: "user-1" }), + createRoutine({ id: "paused", title: "Paused routine", status: "paused", responsibleUserId: "user-1" }), + ]); + const root = createRoot(container); + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + try { + await act(async () => { root.render(); await flush(); }); + await vi.waitFor(() => expect(container.textContent).toContain("Linked routine")); + const rows = container.querySelectorAll('[role="row"]'); + expect(container.textContent).not.toContain("Other routine"); + expect(container.textContent).not.toContain("Paused routine"); + expect(Array.from(rows[0].querySelectorAll('[role="columnheader"]'), cell => cell.textContent)).toEqual(["Routine", "Agent", "Responsible user", "Actions"]); + expect(rows[1].textContent).toContain("Agent One"); + expect(rows[1].textContent).toContain("Taylor"); + expect(rows[1].querySelector('a[href="/routines/match"]')?.textContent).toBe("Linked routine"); + expect(rows[1].querySelector('button[aria-label="Run now: Linked routine"]')?.textContent).toBe(""); + } finally { await act(() => root.unmount()); client.clear(); } + }); + + it("shows a filtered empty state when the enabled filter excludes all routines", async () => { + currentSearch = "statuses=paused"; + routinesListMock.mockResolvedValue([createRoutine({ status: "active" })]); + const root = createRoot(container); + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + try { + await act(async () => { root.render(); await flush(); }); + await vi.waitFor(() => expect(container.textContent).toContain("No routines match this view.")); + expect(container.textContent).not.toContain("define the first recurring workflow"); + } finally { await act(() => root.unmount()); client.clear(); } + }); + it("links View all tasks to the routine-filtered task list", async () => { routinesListMock.mockResolvedValue([]); const root = createRoot(container); @@ -1280,6 +1358,7 @@ describe("Routines page", () => { root.render(); await flush(); }); + await vi.waitFor(() => expect(container.textContent).toContain("View all tasks")); const link = Array.from(container.querySelectorAll("a")).find(anchor => anchor.textContent === "View all tasks"); expect(link?.getAttribute("href")).toBe("/issues?view=all&originKind=routine_execution&sortField=created&sortDir=desc"); expect(container.textContent).not.toContain("View all runs"); diff --git a/ui/src/pages/Routines.tsx b/ui/src/pages/Routines.tsx index 31f6b47f595..71ad91140df 100644 --- a/ui/src/pages/Routines.tsx +++ b/ui/src/pages/Routines.tsx @@ -1,3 +1,7 @@ +import { useRoutineListView } from "../hooks/useRoutineListView"; +import { routineFilterKeys } from "../lib/routine-list-view"; +import { buildRoutineFilterOptions, selectRoutineRows } from "../lib/routine-list-data"; +import { RoutineTable } from "../components/RoutineTable"; import { companyProjectsQuery } from "@/lib/company-projects-query"; import { startTransition, useEffect, useMemo, useState } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; @@ -6,11 +10,13 @@ import { ChevronRight, Plus, Repeat } from "lucide-react"; import { routinesApi } from "../api/routines"; import { foldersApi } from "../api/folders"; import { agentsApi } from "../api/agents"; +import { accessApi } from "../api/access"; import { issuesApi } from "../api/issues"; import { heartbeatsApi } from "../api/heartbeats"; import { useCompany } from "../context/CompanyContext"; import { useBreadcrumbs } from "../context/BreadcrumbContext"; import { useToastActions } from "../context/ToastContext"; +import { buildCompanyUserProfileMap } from "../lib/company-members"; import { cn } from "../lib/utils"; import { queryKeys } from "../lib/queryKeys"; import { retryTransientOnly } from "../lib/query-client"; @@ -23,7 +29,7 @@ import { PageSkeleton } from "../components/PageSkeleton"; import { QueryErrorState, useQueryView } from "../components/QueryView"; import { describeError } from "../api/errors"; import { PageTabBar } from "../components/PageTabBar"; -import { RoutineListRow, nextRoutineStatus } from "../components/RoutineList"; +import { RoutineTableRow, nextRoutineStatus } from "../components/RoutineList"; import { RoutineRunVariablesDialog, type RoutineRunDialogSubmitData, @@ -31,7 +37,7 @@ import { import { Button } from "@/components/ui/button"; import { Card, CardContent } from "@/components/ui/card"; import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"; -import { RoutinesToolbar, type RoutineGroupBy, type RoutineSortField, type RoutineSortDir } from "@/components/RoutinesToolbar"; +import { RoutinesToolbar, type RoutineGroupBy } from "@/components/RoutinesToolbar"; import { auditSectionHref } from "./audit/audit-navigation"; import { RoutineCreateDialog } from "../components/routine-page/RoutineCreateDialog"; import { routinePath } from "../components/routine-page/routine-routes"; @@ -56,13 +62,6 @@ import { useUpdateIssueMutation } from "../hooks/useUpdateIssueMutation"; type RoutinesTab = "routines" | "runs"; -type RoutineViewState = { - sortField: RoutineSortField; - sortDir: RoutineSortDir; - groupBy: RoutineGroupBy; - collapsedGroups: string[]; -}; - type RoutineGroup = { key: string; label: string | null; @@ -71,36 +70,6 @@ type RoutineGroup = { const builtInRoutineGroupKey = "__built_in_routines"; -const defaultRoutineViewState: RoutineViewState = { - sortField: "title", - sortDir: "asc", - groupBy: "folder", - collapsedGroups: [], -}; - -function getRoutineViewState(key: string): RoutineViewState { - try { - const raw = localStorage.getItem(key); - if (raw) return { ...defaultRoutineViewState, ...JSON.parse(raw) }; - } catch { - // Ignore malformed local state and fall back to defaults. - } - return { ...defaultRoutineViewState }; -} - -function saveRoutineViewState(key: string, state: RoutineViewState) { - localStorage.setItem(key, JSON.stringify(state)); -} - -function timestampValue(value: Date | string | null | undefined) { - if (!value) return Number.NEGATIVE_INFINITY; - const timestamp = new Date(value).getTime(); - return Number.isFinite(timestamp) ? timestamp : Number.NEGATIVE_INFINITY; -} - -function compareNullableText(left: string | null | undefined, right: string | null | undefined) { - return (left ?? "").localeCompare(right ?? "", undefined, { sensitivity: "base" }); -} type RoutineFolderGroupMeta = { name: string; position?: number | null }; @@ -207,30 +176,6 @@ export function buildRoutineSections( ]; } -export function sortRoutines( - routines: RoutineListItem[], - sortField: RoutineSortField, - sortDir: RoutineSortDir, -): RoutineListItem[] { - const direction = sortDir === "asc" ? 1 : -1; - return [...routines].sort((left, right) => { - let result = 0; - - if (sortField === "title") { - result = compareNullableText(left.title, right.title); - } else if (sortField === "created") { - result = timestampValue(left.createdAt) - timestampValue(right.createdAt); - } else if (sortField === "lastRun") { - result = timestampValue(left.lastRun?.triggeredAt ?? left.lastTriggeredAt) - - timestampValue(right.lastRun?.triggeredAt ?? right.lastTriggeredAt); - } else { - result = timestampValue(left.updatedAt) - timestampValue(right.updatedAt); - } - - if (result !== 0) return result * direction; - return compareNullableText(left.title, right.title); - }); -} function RoutineSectionHeader({ label, @@ -276,21 +221,14 @@ export function Routines() { const { enabled: streamlinedUiEnabled } = useStreamlinedUiEnabled(); const legacyRunsRequested = searchParams.get("tab") === "runs"; const activeTab: RoutinesTab = !streamlinedUiEnabled && legacyRunsRequested ? "runs" : "routines"; - const routineViewStateKey = selectedCompanyId - ? `paperclip:routines-view:${selectedCompanyId}` - : "paperclip:routines-view"; - const [query, setQuery] = useState(""); - const [routineViewState, setRoutineViewState] = useState(() => getRoutineViewState(routineViewStateKey)); + const [routineViewState, updateRoutineView] = useRoutineListView(selectedCompanyId); + const query = routineViewState.query; const folderSelection = normalizeFolderSelection(searchParams.get("folder")); useEffect(() => { setBreadcrumbs([{ label: "Routines" }]); }, [setBreadcrumbs]); - useEffect(() => { - setRoutineViewState(getRoutineViewState(routineViewStateKey)); - }, [routineViewStateKey]); - const routinesQuery = useQuery({ queryKey: queryKeys.routines.list(selectedCompanyId!), queryFn: () => routinesApi.list(selectedCompanyId!), @@ -316,6 +254,13 @@ export function Routines() { ...companyProjectsQuery(selectedCompanyId!, { includeArchived: true }), enabled: !!selectedCompanyId, }); + const companyMembersQuery = useQuery({ + queryKey: queryKeys.access.companyUserDirectory(selectedCompanyId!), + queryFn: () => accessApi.listUserDirectory(selectedCompanyId!), + enabled: !!selectedCompanyId, + }); + const { data: companyMembers } = companyMembersQuery; + const companyMembersView = useQueryView(companyMembersQuery); const recentRunsQuery = useQuery({ queryKey: [...queryKeys.issues.list(selectedCompanyId!), "routine-executions"], queryFn: () => issuesApi.list(selectedCompanyId!, { originKind: "routine_execution" }), @@ -501,9 +446,11 @@ export function Routines() { () => new Map((routineFolders?.folders ?? []).map((folder) => [folder.id, folder])), [routineFolders], ); - const visibleRoutines = useMemo( - () => (routines ?? []).filter((routine) => routine.status !== "archived"), - [routines], + const userById = useMemo(() => buildCompanyUserProfileMap(companyMembers?.users), [companyMembers]); + const filterOptions = useMemo(() => buildRoutineFilterOptions({ projects: projects ?? [], agents: agents ?? [], userById, routines: routines ?? [] }), [projects, agents, userById, routines]); + const { visibleRoutines, sortedRoutines, railFolderResult } = useMemo( + () => selectRoutineRows(routines ?? [], routineViewState, routineFolders, folderSelection), + [routines, routineViewState, routineFolders, folderSelection], ); const liveIssueIds = useMemo( () => collectLiveIssueIds(liveRuns, routineExecutionIssues), @@ -524,45 +471,6 @@ export function Routines() { navigate(nextTab === "runs" ? "/routines?tab=runs" : "/routines"); }); } - const folderFilteredRoutines = useMemo(() => { - if (routineViewState.groupBy !== "folder" || !routineFolders) return visibleRoutines; - if (folderSelection === "all") return visibleRoutines; - if (folderSelection === "unfiled") return visibleRoutines.filter((routine) => !routine.folderId); - return visibleRoutines.filter((routine) => routine.folderId === folderSelection); - }, [folderSelection, routineFolders, routineViewState.groupBy, visibleRoutines]); - // Rail counts reflect the page's visible scope (archived hidden), not raw DB - // counts (ux-spec §5.3). - const railFolderResult = useMemo(() => { - if (!routineFolders) return routineFolders; - const counts = new Map(); - let unfiled = 0; - for (const routine of visibleRoutines) { - if (routine.folderId) counts.set(routine.folderId, (counts.get(routine.folderId) ?? 0) + 1); - else unfiled += 1; - } - return { - ...routineFolders, - allCount: visibleRoutines.length, - unfiledCount: unfiled, - folders: routineFolders.folders.map((folder) => ({ - ...folder, - itemCount: counts.get(folder.id) ?? 0, - })), - }; - }, [routineFolders, visibleRoutines]); - const sortedRoutines = useMemo( - () => { - const terms = query.toLowerCase().trim().split(/\s+/).filter(Boolean); - const matches = folderFilteredRoutines.filter(routine => { - const text = `${routine.title} ${routine.description ?? ""}`.toLowerCase(); - return terms.every(term => text.includes(term)); - }); - return sortRoutines(matches, routineViewState.sortField, routineViewState.sortDir); - }, - [folderFilteredRoutines, query, routineViewState.sortDir, routineViewState.sortField], - ); - // A failed initial folder read is not an empty folder collection. Keep - // routine rows usable without inventing folder names or changing the saved view. const effectiveGroupBy = routineViewState.groupBy === "folder" && !routineFolders ? "none" : routineViewState.groupBy; const routineSections = useMemo( () => buildRoutineSections(sortedRoutines, effectiveGroupBy, projectById, agentById, folderById), @@ -571,14 +479,6 @@ export function Routines() { const hasRoutineFolders = (routineFolders?.folders.length ?? 0) > 0; const showFolderRail = routineViewState.groupBy === "folder" && hasRoutineFolders; - function updateRoutineView(patch: Partial) { - setRoutineViewState((current) => { - const next = { ...current, ...patch }; - saveRoutineViewState(routineViewStateKey, next); - return next; - }); - } - function setFolderSelection(selection: FolderSelection) { setSearchParams((current) => { const params = new URLSearchParams(current); @@ -687,13 +587,16 @@ export function Routines() { return (
+

Routines

updateRoutineView({ query })} sortField={routineViewState.sortField} sortDir={routineViewState.sortDir} groupBy={routineViewState.groupBy} onSortChange={(sortField, sortDir) => updateRoutineView({ sortField, sortDir })} onGroupChange={groupBy => updateRoutineView({ groupBy, collapsedGroups: [] })} onNewFolder={routineViewState.groupBy === "folder" && routineFolders && !hasRoutineFolders ? () => openCreateFolder() : undefined} onCreateRoutine={openCreateRoutine} + filters={routineViewState} filterOptions={filterOptions} onFiltersChange={updateRoutineView} + columns={routineViewState.columns} onColumnsChange={columns => updateRoutineView({ columns })} tasksHref="/issues?view=all&originKind=routine_execution&sortField=created&sortDir=desc" /> @@ -740,6 +643,11 @@ export function Routines() { /> ) : null} + {companyMembersView.kind === "error" ? ( + + ) : null} + {routineViewState.groupBy === "folder" && foldersView.kind === "error" ? ( @@ -771,18 +679,18 @@ export function Routines() { onCreateFolder={() => openCreateFolder()} /> ) : null} - {visibleRoutines.length === 0 ? ( + {visibleRoutines.length === 0 && !routineViewState.statuses.length ? (
) : sortedRoutines.length === 0 ? (
routineViewState[key].length) || folderSelection === "all" ? "No routines match this view." : "This folder is empty."} /> {folderSelection !== "all" ? (
@@ -817,10 +725,13 @@ export function Routines() { /> ) : null} + {group.items.map((routine) => ( - ))} + ); diff --git a/ui/storybook/stories/routines/routines-list-view.stories.tsx b/ui/storybook/stories/routines/routines-list-view.stories.tsx new file mode 100644 index 00000000000..43a7494542e --- /dev/null +++ b/ui/storybook/stories/routines/routines-list-view.stories.tsx @@ -0,0 +1,47 @@ +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { Routines } from "@/pages/Routines"; +import { Routines as ClassicRoutines } from "@/pages/Routines.production"; +import { Routes, Route, useLocation } from "@/lib/router"; +import { baseRoutine } from "../../fixtures/routineWebhooks"; +import { storybookAgents, storybookProjects } from "../../fixtures/paperclipData"; +import { prepareFixtureApi } from "../../support/capability-gaps/api"; +import { routineViewStorageKey } from "@/lib/routine-list-view"; + +function RoutineListPage({ classic = false }: { classic?: boolean }) { + const location = useLocation(); + return
Current routine view : } />
; +} +const routines = [ + { ...baseRoutine, id: "weekly-review", title: "Weekly project review", projectId: storybookProjects[0].id, responsibleUserId: "user-board", lastRun: { triggeredAt: "2026-11-17T08:00:00Z", status: "completed" } }, + { ...baseRoutine, id: "nightly-triage", title: "Nightly task triage", assigneeAgentId: storybookAgents[1].id, projectId: storybookProjects[1].id, responsibleUserId: "person-alex", status: "paused", lastRun: null }, + { ...baseRoutine, id: "daily-summary", title: "Daily company summary", projectId: storybookProjects[0].id, responsibleUserId: "person-alex", lastRun: null }, +]; +const meta = { + id: "routines-list-view", + title: "Automation and structured work/Routines, schedules, and triggers/List controls and columns", + component: RoutineListPage, + parameters: { + layout: "fullscreen", initialEntries: ["/PAP/routines"], + paperclip: { capabilities: ["routines/management"], status: "current", implementation: "production", boundary: "fixtures", notes: "Both production Routines pages with real search, filter, sort, group, columns and local view persistence. API reads use fictional fixtures. Manual execution and routine creation are outside this story's acceptance scope." }, + }, + beforeEach: ({ parameters }) => { + localStorage.removeItem(routineViewStorageKey("company-storybook", "user-board")); + return prepareFixtureApi([ + { path: "/api/workspace-preferences/me", read: () => ({ userId: "user-board", coordinatorWorkspaceEnabled: false, updatedAt: null }) }, + { path: "/api/companies/company-storybook/routines", read: () => routines }, + { path: "/api/companies/company-storybook/folders", read: () => ({ folders: parameters.withFolders ? [{ id: "folder-review", name: "Reviews", kind: "routine", parentId: null, position: 0, itemCount: 0 }] : [], allCount: routines.length, unfiledCount: routines.length }) }, + { path: "/api/companies/company-storybook/user-directory", read: () => ({ users: [ + { principalId: "user-board", status: "active", user: { name: "Taylor Morgan", email: "taylor@example.test", image: null } }, + { principalId: "person-alex", status: "active", user: { name: "Alex Chen", email: "alex@example.test", image: null } }, + ] }) }, + ]).cleanup; + }, +} satisfies Meta; +export default meta; +type Story = StoryObj; +export const Default: Story = {}; +export const LinkedFilters: Story = { parameters: { initialEntries: [`/PAP/routines?projects=${storybookProjects[0].id}&responsibleUsers=person-alex&statuses=active`] } }; +export const Classic: Story = { args: { classic: true } }; +export const ClassicSelection: Story = { args: { classic: true }, parameters: { withFolders: true } }; + +export const ClassicRuns: Story = { args: { classic: true }, parameters: { initialEntries: ["/PAP/routines?tab=runs"] } };