feat(ui): align routine controls and remember list views (#22182)

## Thinking Path

> - Paperclip helps people manage AI agents and their work.
> - Routines define recurring work and create tasks.
> - People need the same controls to find and inspect routines as they
use for tasks.
> - The routine list had different search controls and no detailed
filters or column choices.
> - This pull request aligns the controls and remembers each person's
view.
> - People can share a filtered link and see the responsible person
beside the agent.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

The Routines list controls and metadata in the current and classic
interfaces.

**Subsystem affected**

ui/ — the React board.

**Current behavior**

Routines use different search controls from Tasks. The list has limited
view settings and no filters for project, agent, enabled state,
responsible person, or source. Routine metadata is fixed.

**Proposed behavior**

Show New routine on the left. Show Search, Sort, Filter, Group, Columns,
and View all tasks on the right, in that order. Use the shared Tasks
search and filter controls. Show the responsible person next to the
agent. Let people choose metadata columns. Save filters, search, sort,
and grouping in the URL. Remember view settings per person and company
in local storage. Use a play icon for manual runs.

**Reason and benefit**

People can scan routine ownership, find a subset, share its link, and
return to their preferred columns and view.

**Breaking changes**

The list uses metadata columns with horizontal scrolling on narrow
screens. Existing company-level sort and group preferences are read as a
fallback. No API or database change is required.

Related work: Refs #22009, Refs #18606, Refs #18317. The open PR search
found no duplicate of this list-control change. ROADMAP.md lists
Routines as shipped and has no overlapping control work.

## What Changed

- Align both Routines toolbars with the requested order and shared
search and button styles.
- Extract the existing Tasks filter group and checkbox row for reuse by
Routines.
- Add project, agent, enabled, responsible person, and source filters.
- Keep linked filters ahead of saved filters. Preserve unrelated URL
parameters.
- Save preferences per person and company. Keep the controls usable when
storage is unavailable.
- Add selectable Project, Agent, Responsible user, Last run, and Enabled
columns.
- Use play-only manual run buttons with accessible names and pending
indicators.
- Correct the empty message when a status filter excludes every routine.
- Add production-page Storybook examples and browser tests for both
interfaces.

## Verification

- Linux checkout, Node 25.9.0, system Chromium 148.0.7778.96.
- The final change includes master through `07d9316218`. It uses the
shared routine creation form and the upstream Runner test and SDK
source-pin fixes.
- 68 tests pass across eight focused UI suites at `440a9eb6a7`. UI
typecheck, token gates, and whitespace checks pass.
- Two new directory-error cases fail before the fix and pass after it.
Both pages keep routine rows mounted, show an error with Retry, and
restore responsible names after retry.
- 59 checks pass across the SDK source-pin, public-type, and evidence
suites.
- The Runner test program typechecks after building its eval dependency.
A local run of the native-session test file passed 300 tests. One
additional test could not run because the local debug Runner binary was
absent. CI must cover that case.
- Storybook builds and all 13 browser checks pass on
`64a87af7c085426d09eb8aa48bf9491487565990` after the latest master
integration. They cover current and Classic controls, filters, columns,
links, selection alignment, Recent Runs, mobile overflow, and shared
toolbar behavior.
- Storybook examples: Default, LinkedFilters, Classic, ClassicSelection,
and ClassicRuns. They mount production pages with fictional API
responses. Screenshots cover light, dark, filters, custom columns, and
mobile. The baseline manifest has no snapshots; these are visual review
captures.
- Earlier preference, shared-link, title-link, compact-row, and
filter-render-cost regressions have red/green evidence. The
scheduled-routine journey has 17 passing unit checks from the prior
revision.
- The shared selector has three large-list cases with 1,200 routines and
120 folders. All filters are active. Each case checks row order and
folder counts. Work counters throw if filtering repeatedly scans
selected IDs or folder counts scan the routine list for each folder.
Both deliberate regressions fail; the unchanged selector passes. Both
Routines pages use this selector. The latest commit adds only these
tests; production source is unchanged.
- [CI at
`64a87af7c0`](https://github.com/paperclipai/paperclip/actions/runs/44416091562)
passed all jobs, including typecheck, Build, Runner, general tests,
serialized tests, and E2E. [Final-head CI at
`440a9eb6a7`](https://github.com/paperclipai/paperclip/actions/runs/44419144971)
now passes on attempt 2. All 52 executed jobs pass; one file-selection
job is skipped. Typecheck, Build, all test shards, E2E, Runner, and the
aggregate verify gate pass. The first attempt failed in the
timing-sensitive watchdog fixture; its retry passes.
- `pnpm verify` returned exit 2 because this branch needs broad CI
coverage. Final-head CI passes. Greptile and Ponytail both give 5/5 at
`440a9eb6a75184a35001e99a17e6856b7cdb0bd5`. All 20 inline threads are
resolved.
- Prior CI at `10a5b0813b` passed all general and serialized test
shards, all E2E shards, and Build. It failed on a circular test-mock
type and a stale SDK source pin. Master now contains both repairs; the
final branch uses those repairs.
- The two Routines page bodies were already duplicated. This PR reduces
them and shares list data, controls, rows, and view state. Codie owns
the remaining page-shell consolidation as later work.
- Live provider execution and scheduler behavior are outside this
presentation change. Protected Storybook publication still requires a
configured human reviewer; no deployment approval is inferred from merge
authorization.

## Risks

View settings now include filters. A person can return to a filtered
list. The URL and active filter button show that state. Shared filter
URLs override local filters. Column choices stay local. The shared
filter extraction can affect Tasks, so its component and toolbar checks
are included. No migration is needed.

## Model Used

OpenAI GPT-6 through Codex. The runtime does not expose a more specific
model revision. Used reasoning, source editing, shell tools, and browser
automation. No sub-agents were used.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-11-18 17:43:29 -06:00
1 parent d702f567bc
commit 3f263e4faf
24 files changed
+1061 -574

No files matched your search

+9
View File
@@ -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
@@ -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 () => {
@@ -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);
});
@@ -114,14 +114,14 @@ test("canonical toolbars share control geometry and keep the requested keyboard
const controls = [...toolbar.querySelectorAll<HTMLElement>("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");
});
@@ -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 (
<section className="task-filter-group" aria-labelledby={headingId}>
<h3 id={headingId}>{title}</h3>
<div className="task-filter-group-body">
{searchLabel ? <div className="task-filter-search"><Search aria-hidden /><Input aria-label={`Search ${searchLabel}`} placeholder={`Search ${searchLabel}...`} value={query} onChange={event => onQueryChange?.(event.target.value)} /></div> : null}
<div className="task-filter-options" data-filter-options={optionsKey}>{children}</div>
</div>
</section>
);
}
export function FilterRow({ label, checked, onToggle, icon }: { label: string; checked: boolean; onToggle: () => void; icon?: ReactNode }) {
return <label className="task-filter-option" data-marquee-surface><Checkbox aria-label={label} checked={checked} onCheckedChange={onToggle} />{icon ? <span className="task-filter-icon" aria-hidden>{icon}</span> : null}<TruncatedText className="task-filter-option-label">{label}</TruncatedText></label>;
}
+3 -22
View File
@@ -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<ComponentProps<typeof IssueFiltersPopover>, "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 (
<section className="task-filter-group" aria-labelledby={headingId}>
<h3 id={headingId}>{title}</h3>
<div className="task-filter-group-body">
{searchLabel ? <div className="task-filter-search"><Search aria-hidden /><Input aria-label={`Search ${searchLabel}`} placeholder={`Search ${searchLabel}...`} value={query} onChange={event => onQueryChange?.(event.target.value)} /></div> : null}
<div className="task-filter-options" data-filter-options={optionsKey}>{children}</div>
</div>
</section>
);
}
function FilterRow({ label, checked, onToggle, icon }: { label: string; checked: boolean; onToggle: () => void; icon?: ReactNode }) {
return <label className="task-filter-option" data-marquee-surface><Checkbox aria-label={label} checked={checked} onCheckedChange={onToggle} />{icon ? <span className="task-filter-icon" aria-hidden>{icon}</span> : null}<TruncatedText className="task-filter-option-label">{label}</TruncatedText></label>;
}
/** 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: "" });
@@ -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 }) => <a href={to} {...props}>{children}</a> }));
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(<RoutineListRow
routine={{ id: "r1", title: "Weekly summary", status: "active", projectId: null, assigneeAgentId: null, responsibleUserId: "u1" }}
userById={new Map([["u1", { label: "Casey", image: null }]])}
projectById={new Map()} agentById={new Map()}
runningRoutineId={null} statusMutationRoutineId={null}
href="/routines/r1" selectMode selected onSelectChange={vi.fn()}
onRunNow={vi.fn()} onToggleEnabled={vi.fn()}
/>);
const document = new DOMParser().parseFromString(markup, "text/html");
expect(document.body.textContent).toContain("Casey");
expect(document.querySelector<HTMLInputElement>('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(<ManagedRoutinesList routines={routines} agents={[{ id: "agent-one", name: "One", appearance, icon: null }]} />);
+96 -88
View File
@@ -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<TRoutine extends RoutineListRowItem>({
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<TRoutine extends RoutineListRowItem> = {
routine: TRoutine;
userById?: Map<string, CompanyUserProfile>;
projectById: Map<string, RoutineListProjectSummary>;
agentById: Map<string, RoutineListAgentSummary>;
runningRoutineId: string | null;
@@ -97,7 +80,36 @@ export function RoutineListRow<TRoutine extends RoutineListRowItem>({
onRunNow: (routine: TRoutine) => void;
onToggleEnabled: (routine: TRoutine, enabled: boolean) => void;
onToggleArchived?: (routine: TRoutine) => void;
}) {
};
function openRoutineFromRow(event: MouseEvent<HTMLDivElement>) {
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<HTMLAnchorElement>("[data-routine-link]")?.click();
}
function routineRowParts<TRoutine extends RoutineListRowItem>({
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<TRoutine>) {
const enabled = routine.status === "active";
const isArchived = routine.status === "archived";
const isStatusPending = statusMutationRoutineId === routine.id;
@@ -106,18 +118,35 @@ export function RoutineListRow<TRoutine extends RoutineListRowItem>({
const isDraft = !isArchived && !routine.assigneeAgentId;
const runDisabled = runningRoutineId === routine.id || isArchived || disableRunNow;
return (
<Link
to={href}
className={`group flex flex-col gap-3 px-3 py-3 transition-colors hover:bg-accent/50 sm:flex-row sm:items-center no-underline text-inherit${
divider ? " border-b border-border last:border-b-0" : ""
}`}
>
{selectMode ? (
<div
const user = routine.responsibleUserId ? userById?.get(routine.responsibleUserId) : null;
const projectCell = <span className="flex min-w-0 items-center gap-2"><span className="h-2.5 w-2.5 shrink-0 rounded-sm" style={{ backgroundColor: project?.color ?? "var(--project-none)" }} /><span className="truncate">{routine.projectId ? project?.name ?? "Unknown project" : "No project"}</span></span>;
const agentCell = <span className="flex min-w-0 items-center gap-2">{routine.assigneeAgentId ? <AgentAvatar agent={{ ...agent, id: routine.assigneeAgentId }} size={16} className="h-3.5 w-3.5 shrink-0" /> : null}<span className="truncate">{routine.assigneeAgentId ? agent?.name ?? "Unknown agent" : "No default agent"}</span></span>;
const userCell = user ? <Identity name={user.label} avatarUrl={user.image} size="sm" /> : <span>{routine.responsibleUserId ? "Unavailable user" : "No responsible user"}</span>;
const lastRunCell = <span>{formatLastRunTimestamp(routine.lastRun?.triggeredAt)}{routine.lastRun ? ` · ${formatRoutineRunStatus(routine.lastRun.status)}` : ""}</span>;
const enabledCell = <div className="flex items-center gap-2" onClick={event => { event.preventDefault(); event.stopPropagation(); }}><ToggleSwitch size="lg" checked={enabled} onCheckedChange={() => onToggleEnabled(routine, enabled)} disabled={isStatusPending || isArchived || disableToggle} aria-label={enabled ? `Disable ${routine.title}` : `Enable ${routine.title}`} /><span className="text-xs text-muted-foreground">{isArchived ? "Archived" : isDraft ? "Draft" : enabled ? "On" : "Off"}</span></div>;
const cellByColumn = { project: projectCell, assignee: agentCell, responsibleUser: userCell, lastRun: lastRunCell, enabled: enabledCell };
const title = (
<div className="min-w-0 flex-1 space-y-1.5">
<div className="flex flex-wrap items-center gap-2">
<Link data-routine-link to={href} className="truncate text-sm font-medium no-underline text-inherit">{routine.title}</Link>
{(isArchived || routine.status === "paused" || isDraft) ? (
<span className="text-xs text-muted-foreground">
{isArchived ? "archived" : isDraft ? "draft" : "paused"}
</span>
) : null}
{managedByLabel ? (
<span className="text-xs text-muted-foreground">{managedByLabel}</span>
) : null}
</div>
{secondaryDetails ? (
<div className="text-xs text-muted-foreground">{secondaryDetails}</div>
) : null}
</div>
);
const selection = (
<div
className="flex items-start pt-0.5 sm:pt-1"
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
}}
>
@@ -129,66 +158,23 @@ export function RoutineListRow<TRoutine extends RoutineListRowItem>({
onChange={(event) => onSelectChange?.(routine, event.target.checked)}
/>
</div>
) : null}
<div className="min-w-0 flex-1 space-y-1.5">
<div className="flex flex-wrap items-center gap-2">
<span className="truncate text-sm font-medium">{routine.title}</span>
{(isArchived || routine.status === "paused" || isDraft) ? (
<span className="text-xs text-muted-foreground">
{isArchived ? "archived" : isDraft ? "draft" : "paused"}
</span>
) : null}
{managedByLabel ? (
<span className="text-xs text-muted-foreground">{managedByLabel}</span>
) : null}
</div>
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground">
<span className="flex items-center gap-2">
<span
className="h-2.5 w-2.5 shrink-0 rounded-sm"
style={{ backgroundColor: project?.color ?? "var(--project-none)" }}
/>
<span>{routine.projectId ? (project?.name ?? "Unknown project") : "No project"}</span>
</span>
<span className="flex items-center gap-2">
{routine.assigneeAgentId ? <AgentAvatar agent={{ ...agent, id: routine.assigneeAgentId }} size={16} className="h-3.5 w-3.5 shrink-0"/> : null}
<span>{routine.assigneeAgentId ? (agent?.name ?? "Unknown agent") : "No default agent"}</span>
</span>
<span>
{formatLastRunTimestamp(routine.lastRun?.triggeredAt)}
{routine.lastRun ? ` · ${formatRoutineRunStatus(routine.lastRun.status)}` : ""}
</span>
</div>
{secondaryDetails ? (
<div className="text-xs text-muted-foreground">{secondaryDetails}</div>
) : null}
</div>
<div className="flex items-center gap-3" onClick={(event) => { event.preventDefault(); event.stopPropagation(); }}>
);
const actions = (
<div className="flex items-center justify-end gap-3" onClick={(event) => { event.preventDefault(); event.stopPropagation(); }}>
{runNowButton ? (
<Button
variant="outline"
size="sm"
size="icon-sm"
aria-label={runningRoutineId === routine.id ? `Running ${routine.title}` : `Run now: ${routine.title}`}
title={runningRoutineId === routine.id ? "Running…" : "Run now"}
disabled={runDisabled}
onClick={() => onRunNow(routine)}
>
<Play className="h-3.5 w-3.5" />
{runningRoutineId === routine.id ? "Running..." : "Run now"}
{runningRoutineId === routine.id ? <LoaderCircle className="h-3.5 w-3.5 animate-spin" aria-hidden /> : <Play className="h-3.5 w-3.5" aria-hidden />}
</Button>
) : null}
<div className="flex items-center gap-3">
<ToggleSwitch
size="lg"
checked={enabled}
onCheckedChange={() => onToggleEnabled(routine, enabled)}
disabled={isStatusPending || isArchived || disableToggle}
aria-label={enabled ? `Disable ${routine.title}` : `Enable ${routine.title}`}
/>
<span className="w-12 text-xs text-muted-foreground">
{isArchived ? "Archived" : isDraft ? "Draft" : enabled ? "On" : "Off"}
</span>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
@@ -230,6 +216,28 @@ export function RoutineListRow<TRoutine extends RoutineListRowItem>({
</DropdownMenuContent>
</DropdownMenu>
</div>
</Link>
);
return { title, selection, actions, cellByColumn };
}
export function RoutineTableRow<TRoutine extends RoutineListRowItem>(props: RoutineRowProps<TRoutine> & { columns: RoutineColumn[]; userById: Map<string, CompanyUserProfile> }) {
const { title, selection, actions, cellByColumn } = routineRowParts(props);
return <div role="row" onClick={openRoutineFromRow} style={{ gridTemplateColumns: routineColumnGrid(props.columns, props.selectMode) }} className={`routine-table-grid group cursor-pointer px-3 py-3 transition-colors hover:bg-accent/50${props.divider !== false ? " border-b border-border last:border-b-0" : ""}`}>
{props.selectMode ? <div role="cell">{selection}</div> : null}
<div role="cell" className="min-w-0">{title}</div>
{props.columns.map(column => <div role="cell" key={column} className="min-w-0 truncate text-xs text-muted-foreground">{cellByColumn[column]}</div>)}
<div role="cell">{actions}</div>
</div>;
}
export function RoutineListRow<TRoutine extends RoutineListRowItem>(props: RoutineRowProps<TRoutine>) {
const { title, selection, actions, cellByColumn } = routineRowParts(props);
return <div onClick={openRoutineFromRow} className={`group flex flex-col gap-3 px-3 py-3 transition-colors hover:bg-accent/50 sm:flex-row sm:items-center cursor-pointer${props.divider !== false ? " border-b border-border last:border-b-0" : ""}`}>
{props.selectMode ? selection : null}
<div className="min-w-0 flex-1 space-y-1.5">
{title}
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground">{cellByColumn.project}{cellByColumn.assignee}{props.userById ? cellByColumn.responsibleUser : null}{cellByColumn.lastRun}</div>
</div>
{cellByColumn.enabled}{actions}
</div>;
}
+18
View File
@@ -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 <div className="overflow-x-auto"><div role="table" aria-label={label} className="routine-table">
<div role="row" className="routine-table-grid px-3 py-2 text-xs text-muted-foreground" style={{ gridTemplateColumns: routineColumnGrid(columns, selectMode) }}>
{selectMode ? <span role="columnheader"><span className="sr-only">Select</span></span> : null}
<span role="columnheader">Routine</span>
{columns.map(id => <span role="columnheader" key={id}>{routineColumns.find(column => column.id === id)!.label}</span>)}
<span role="columnheader" className="text-right">Actions</span>
</div>
<div role="rowgroup">{children}</div>
</div></div>;
}
@@ -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 }) => <a href={to}>{children}</a> }));
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(<RoutinesToolbar query="" onQueryChange={() => {}} 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);
});
});
+57 -72
View File
@@ -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<Record<RoutineFilterKey, { id: string; name: string }[]>>;
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<RoutineViewState, RoutineFilterKey>;
filterOptions?: RoutineFilterOptions;
onFiltersChange?: (patch: Partial<RoutineViewState>) => void;
columns?: RoutineColumn[];
onColumnsChange?: (columns: RoutineColumn[]) => void;
}) {
return <div data-canonical-toolbar="routines" role="toolbar" aria-label="Routines controls" className="flex flex-wrap items-center gap-4">
<div className="flex w-full min-w-0 items-center gap-2 sm:w-auto [&>[data-toolbar-search]]:min-w-0 [&>[data-toolbar-search]]:flex-1">
const [optionQueries, setOptionQueries] = useState<Record<string, string>>({});
const activeFilters = routineFilterKeys.reduce((count, key) => count + filters[key].length, 0);
return <FlyoutAppearanceProvider appearance="refreshed"><div data-canonical-toolbar="routines" role="toolbar" aria-label="Routines controls" className="design-page-toolbar">
<Button variant="outline" className="design-toolbar-button" data-toolbar-primary onClick={onCreateRoutine}><Plus aria-hidden />New routine</Button>
<div className="ml-auto flex min-w-0 flex-wrap items-center gap-2">
{showListControls ? <>
<ToolbarSearch query={query} onQueryChange={onQueryChange} label="Search routines" placeholder="Search routines…" />
<Popover>
<PopoverTrigger asChild>
<Button variant="outline" size="icon-sm" title="Sort" aria-label="Sort routines">
<ArrowUpDown className="h-3.5 w-3.5" aria-hidden="true" />
</Button>
</PopoverTrigger>
<PopoverTrigger asChild><Button variant="outline" className="design-toolbar-button design-toolbar-icon" title="Sort" aria-label="Sort routines"><ArrowUpDown aria-hidden /></Button></PopoverTrigger>
<PopoverContent align="end" className="w-44 p-0">
<FlyoutHeader>Sort</FlyoutHeader>
<div className="p-2 space-y-0.5">
{([
["updated", "Updated"],
["created", "Created"],
["lastRun", "Last run"],
["title", "Title"],
] as const).map(([field, label]) => (
<button
type="button"
key={field}
className={`flex w-full items-center justify-between rounded-sm px-2 py-1.5 text-sm ${
sortField === field
? "bg-accent/50 text-foreground"
: "text-muted-foreground hover:bg-accent/50"
}`}
onClick={() => {
onSortChange(field, sortField === field
? (sortDir === "asc" ? "desc" : "asc")
: (field === "title" ? "asc" : "desc"));
}}
>
<span>{label}</span>
{sortField === field ? (
<span className="text-xs text-muted-foreground">
{sortDir === "asc" ? "Asc" : "Desc"}
</span>
) : null}
{([["updated", "Updated"], ["created", "Created"], ["lastRun", "Last run"], ["title", "Title"]] as const).map(([field, label]) => (
<button type="button" key={field} className={`flex w-full items-center justify-between rounded-sm px-2 py-1.5 text-sm ${sortField === field ? "bg-accent/50 text-foreground" : "text-muted-foreground hover:bg-accent/50"}`}
onClick={() => onSortChange(field, sortField === field ? sortDir === "asc" ? "desc" : "asc" : field === "title" ? "asc" : "desc")}>
<span>{label}</span>{sortField === field ? <span className="text-xs text-muted-foreground">{sortDir === "asc" ? "Asc" : "Desc"}</span> : null}
</button>
))}
</div>
</PopoverContent>
</Popover>
<Popover>
<PopoverTrigger asChild>
<Button variant="outline" size="icon-sm" title="Group" aria-label="Group routines">
<Layers className="h-3.5 w-3.5" aria-hidden="true" />
</Button>
</PopoverTrigger>
<PopoverContent align="end" className="w-44 p-0">
<div className="p-2 space-y-0.5">
{([
["folder", "Folder"],
["project", "Project"],
["assignee", "Agent"],
["none", "None"],
] as const).map(([value, label]) => (
<button
type="button"
key={value}
className={`flex w-full items-center justify-between rounded-sm px-2 py-1.5 text-sm ${
groupBy === value
? "bg-accent/50 text-foreground"
: "text-muted-foreground hover:bg-accent/50"
}`}
onClick={() => onGroupChange(value)}
>
<span>{label}</span>
{groupBy === value ? <Check className="h-3.5 w-3.5" /> : null}
</button>
))}
<PopoverTrigger asChild><Button variant="outline" className="design-toolbar-button design-toolbar-icon" title="Filter" aria-label={activeFilters ? `Filter routines (${activeFilters})` : "Filter routines"} data-active={activeFilters > 0}><Filter aria-hidden /></Button></PopoverTrigger>
<PopoverContent align="end" className="task-filters-popover">
<FlyoutHeader className="task-filters-header"><span>Filters{activeFilters ? ` (${activeFilters})` : ""}</span>{activeFilters ? <Button variant="ghost" onClick={() => onFiltersChange?.(Object.fromEntries(routineFilterKeys.map(key => [key, []])))}>Clear</Button> : null}</FlyoutHeader>
<div className="task-filters-grid">
{([["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 <FilterGroup key={key} title={title} optionsKey={key} searchLabel={options.length > 6 ? title.toLowerCase() : undefined} query={optionQueries[key] ?? ""} onQueryChange={value => setOptionQueries(current => ({ ...current, [key]: value }))}>
{visible.map(option => <FilterRow key={option.id} label={option.name} checked={selected.has(option.id)} onToggle={() => onFiltersChange?.({ [key]: selected.has(option.id) ? filters[key].filter(value => value !== option.id) : [...filters[key], option.id] })} />)}
{!visible.length ? <p className="text-xs text-muted-foreground">No options</p> : null}
</FilterGroup>;
})}
</div>
</PopoverContent>
</Popover>
<Popover>
<PopoverTrigger asChild><Button variant="outline" className="design-toolbar-button design-toolbar-icon" title="Group" aria-label="Group routines"><Layers aria-hidden /></Button></PopoverTrigger>
<PopoverContent align="end" className="w-44 p-0"><FlyoutHeader>Group</FlyoutHeader><div className="p-2 space-y-0.5">
{([["folder", "Folder"], ["project", "Project"], ["assignee", "Agent"], ["none", "None"]] as const).map(([value, label]) => <button type="button" key={value} className={`flex w-full items-center justify-between rounded-sm px-2 py-1.5 text-sm ${groupBy === value ? "bg-accent/50 text-foreground" : "text-muted-foreground hover:bg-accent/50"}`} onClick={() => onGroupChange(value)}><span>{label}</span>{groupBy === value ? <Check className="h-3.5 w-3.5" aria-hidden /> : null}</button>)}
{onNewFolder ? <Button variant="ghost" size="sm" onClick={onNewFolder}><Plus className="h-3.5 w-3.5" />New folder</Button> : null}
</div></PopoverContent>
</Popover>
<DropdownMenu>
<DropdownMenuTrigger asChild><Button variant="outline" className="design-toolbar-button design-toolbar-icon" title="Columns" aria-label="Routine columns"><Columns3 aria-hidden /></Button></DropdownMenuTrigger>
<DropdownMenuContent align="end"><DropdownMenuLabel>Columns</DropdownMenuLabel>
{routineColumns.map(column => <DropdownMenuCheckboxItem key={column.id} checked={columns.includes(column.id)} onSelect={event => 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}</DropdownMenuCheckboxItem>)}
<DropdownMenuSeparator /><DropdownMenuItem onSelect={() => onColumnsChange?.([...defaultRoutineView.columns])}>Reset columns</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</> : null}
{tasksHref ? <Button variant="outline" className="design-toolbar-button" asChild><Link to={tasksHref}>View all tasks</Link></Button> : null}
</div>
<div className="design-toolbar-actions">
{tasksHref && <Button variant="outline" size="sm" asChild><Link data-toolbar-control to={tasksHref}>View all tasks</Link></Button>}
{onNewFolder && <Button variant="outline" size="sm" onClick={onNewFolder}><Plus className="h-4 w-4" />New folder</Button>}
<Button variant="outline" size="sm" data-toolbar-primary onClick={onCreateRoutine}><Plus className="h-4 w-4" />Create routine</Button>
</div>
</div>;
</div></FlyoutAppearanceProvider>;
}
+6 -21
View File
@@ -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();
},
};
+20
View File
@@ -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();
},
};
}
+145
View File
@@ -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<typeof useRoutineListView>;
let search = "";
let navigate: ReturnType<typeof useNavigate>;
function Harness({ companyId }: { companyId: string }) {
current = useRoutineListView(companyId);
search = useLocation().search;
navigate = useNavigate();
return <output>{JSON.stringify(current[0])}</output>;
}
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(<QueryClientProvider client={client}><MemoryRouter initialEntries={[entry]}><Harness companyId={companyId} /></MemoryRouter></QueryClientProvider>));
}
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<ReturnType<typeof authApi.getSession>>) => 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<ReturnType<typeof authApi.getSession>>); });
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"]);
});
});
+45
View File
@@ -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<RoutineViewState>) {
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<RoutineViewState> }>({ 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<RoutineViewState>) {
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;
}
+13
View File
@@ -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); }
+85
View File
@@ -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);
});
});
+75
View File
@@ -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<string, { label: string }>;
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<string, number>();
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 })),
},
};
}
+35
View File
@@ -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"));
});
});
+80
View File
@@ -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<RoutineFilterKey, string[]> & {
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<T extends string>(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<string, unknown> : {};
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<RoutineViewState, RoutineFilterKey>;
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<T extends { title: string; description?: string | null; projectId: string | null; assigneeAgentId: string | null; responsibleUserId?: string | null; status: string; originKind?: string }>(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<RoutineFilterKey, Set<string>>;
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);
});
}
+51 -229
View File
@@ -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<string | null>(null);
const activeTab: RoutinesTab = searchParams.get("tab") === "runs" ? "runs" : "routines";
const routineViewStateKey = selectedCompanyId
? `paperclip:routines-view:${selectedCompanyId}`
: "paperclip:routines-view";
const [routineViewState, setRoutineViewState] = useState<RoutineViewState>(() => 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<string, number>();
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<RoutineViewState>) {
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 (
<div className="space-y-6">
<div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
<div className="space-y-1">
<h1 className="text-2xl font-semibold tracking-tight">
Routines
</h1>
<p className="text-sm text-muted-foreground">
Recurring work definitions that materialize into auditable execution tasks.
</p>
</div>
<Button onClick={openCreateRoutine}>
<Plus className="mr-2 h-4 w-4" />
Create routine
</Button>
</div>
<h1 className="sr-only">Routines</h1>
<RoutinesToolbar
showListControls={activeTab === "routines"}
query={query} onQueryChange={query => 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"
/>
<Tabs value={activeTab} onValueChange={handleTabChange}>
<PageTabBar
@@ -689,96 +591,6 @@ export function Routines() {
]}
/>
<TabsContent value="routines" className="space-y-4">
<div className="flex items-center justify-between gap-3">
<p className="text-sm text-muted-foreground">
{visibleRoutines.length} routine{visibleRoutines.length === 1 ? "" : "s"}
</p>
<div className="flex items-center gap-1">
<Popover>
<PopoverTrigger asChild>
<Button variant="ghost" size="sm" className="text-xs" title="Sort">
<ArrowUpDown className="h-3.5 w-3.5 sm:h-3 sm:w-3 sm:mr-1" />
<span className="hidden sm:inline">Sort</span>
</Button>
</PopoverTrigger>
<PopoverContent align="end" className="w-44 p-0">
<div className="p-2 space-y-0.5">
{([
["updated", "Updated"],
["created", "Created"],
["lastRun", "Last run"],
["title", "Title"],
] as const).map(([field, label]) => (
<button
key={field}
className={`flex w-full items-center justify-between rounded-sm px-2 py-1.5 text-sm ${
routineViewState.sortField === field
? "bg-accent/50 text-foreground"
: "text-muted-foreground hover:bg-accent/50"
}`}
onClick={() => {
updateRoutineView(
routineViewState.sortField === field
? { sortDir: routineViewState.sortDir === "asc" ? "desc" : "asc" }
: { sortField: field, sortDir: field === "title" ? "asc" : "desc" },
);
}}
>
<span>{label}</span>
{routineViewState.sortField === field ? (
<span className="text-xs text-muted-foreground">
{routineViewState.sortDir === "asc" ? "Asc" : "Desc"}
</span>
) : null}
</button>
))}
</div>
</PopoverContent>
</Popover>
<Popover>
<PopoverTrigger asChild>
<Button variant="ghost" size="sm" className="text-xs" title="Group">
<Layers className="h-3.5 w-3.5 sm:h-3 sm:w-3 sm:mr-1" />
<span className="hidden sm:inline">Group</span>
</Button>
</PopoverTrigger>
<PopoverContent align="end" className="w-44 p-0">
<div className="p-2 space-y-0.5">
{([
["folder", "Folder"],
["project", "Project"],
["assignee", "Agent"],
["none", "None"],
] as const).map(([value, label]) => (
<button
key={value}
className={`flex w-full items-center justify-between rounded-sm px-2 py-1.5 text-sm ${
routineViewState.groupBy === value
? "bg-accent/50 text-foreground"
: "text-muted-foreground hover:bg-accent/50"
}`}
onClick={() => updateRoutineView({ groupBy: value, collapsedGroups: [] })}
>
<span>{label}</span>
{routineViewState.groupBy === value ? <Check className="h-3.5 w-3.5" /> : null}
</button>
))}
</div>
</PopoverContent>
</Popover>
{routineViewState.groupBy === "folder" && !hasRoutineFolders ? (
<Button variant="outline" size="sm" onClick={() => openCreateFolder()}>
<Plus className="mr-2 h-3.5 w-3.5" />
New folder
</Button>
) : null}
{showFolderRail ? (
<Button variant="ghost" size="sm" className="text-xs" onClick={() => setSelectMode((current) => !current)}>
{selectMode ? "Done" : "Select"}
</Button>
) : null}
</div>
</div>
{routineViewState.groupBy === "folder" ? (
<div className="md:hidden">
<FolderChip
@@ -825,6 +637,11 @@ export function Routines() {
/>
) : null}
{activeTab === "routines" && companyMembersView.kind === "error" ? (
<QueryErrorState error={companyMembersView.error} action="load responsible people" size="inline"
onRetry={companyMembersView.retry} retrying={companyMembersView.isFetching} />
) : null}
{activeTab === "routines" ? (
<div className={cn(showFolderRail && "flex gap-4")}>
{showFolderRail ? (
@@ -863,6 +680,7 @@ export function Routines() {
onCreateFolder={() => openCreateFolder()}
/>
) : null}
{showFolderRail ? <Button variant="ghost" size="sm" onClick={() => setSelectMode(current => !current)}>{selectMode ? "Done" : "Select"}</Button> : null}
{selectMode ? (
<BulkBar
selectedCount={selectedRoutineIds.length}
@@ -876,18 +694,18 @@ export function Routines() {
}}
/>
) : null}
{visibleRoutines.length === 0 ? (
{visibleRoutines.length === 0 && !routineViewState.statuses.length ? (
<div className="py-12">
<EmptyState
icon={Repeat}
message="No active routines. Use Create routine to define the first recurring workflow."
message="No active routines. Use New routine to define the first recurring workflow."
/>
</div>
) : sortedRoutines.length === 0 ? (
<div className="py-12">
<EmptyState
icon={Repeat}
message={folderSelection === "all" ? "No routines match this view." : "This folder is empty."}
message={query.trim() ? "No routines match your search." : routineFilterKeys.some(key => routineViewState[key].length) || folderSelection === "all" ? "No routines match this view." : "This folder is empty."}
/>
{folderSelection !== "all" ? (
<div className="mt-3 flex justify-center">
@@ -922,10 +740,13 @@ export function Routines() {
/>
) : null}
<CollapsibleContent>
<RoutineTable columns={routineViewState.columns} label={group.label ?? "Routines"} selectMode={selectMode}>
{group.items.map((routine) => (
<RoutineListRow
<RoutineTableRow
key={routine.id}
routine={routine}
columns={routineViewState.columns}
userById={userById}
projectById={projectById}
agentById={agentById}
runningRoutineId={runningRoutineId}
@@ -969,6 +790,7 @@ export function Routines() {
}
/>
))}
</RoutineTable>
</CollapsibleContent>
</Collapsible>
);
+90 -11
View File
@@ -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(<QueryClientProvider client={queryClient}><Page /></QueryClientProvider>);
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<typeof import("../api/folders")>("../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(<QueryClientProvider client={queryClient}><Routines /></QueryClientProvider>); 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<HTMLElement>('[role="dialog"]');
expect(dialog?.textContent).toContain("New routine");
const title = dialog!.querySelector<HTMLInputElement>("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(<QueryClientProvider client={client}><Routines /></QueryClientProvider>); 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(<QueryClientProvider client={client}><Routines /></QueryClientProvider>); 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(<QueryClientProvider client={queryClient}><Routines /></QueryClientProvider>);
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");
+39 -127
View File
@@ -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<RoutineViewState>(() => 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<string, number>();
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<RoutineViewState>) {
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 (
<div className="space-y-6">
<h1 className="sr-only">Routines</h1>
<RoutinesToolbar
query={query} onQueryChange={setQuery}
query={query} onQueryChange={query => 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" ? (
<QueryErrorState error={companyMembersView.error} action="load responsible people" size="inline"
onRetry={companyMembersView.retry} retrying={companyMembersView.isFetching} />
) : null}
{routineViewState.groupBy === "folder" && foldersView.kind === "error" ? (
<QueryErrorState error={foldersView.error} action="load routine folders"
onRetry={foldersView.retry} retrying={foldersView.isFetching} />
@@ -771,18 +679,18 @@ export function Routines() {
onCreateFolder={() => openCreateFolder()}
/>
) : null}
{visibleRoutines.length === 0 ? (
{visibleRoutines.length === 0 && !routineViewState.statuses.length ? (
<div className="py-12">
<EmptyState
icon={Repeat}
message="No active routines. Use Create routine to define the first recurring workflow."
message="No active routines. Use New routine to define the first recurring workflow."
/>
</div>
) : sortedRoutines.length === 0 ? (
<div className="py-12">
<EmptyState
icon={Repeat}
message={query.trim() ? "No routines match your search." : folderSelection === "all" ? "No routines match this view." : "This folder is empty."}
message={query.trim() ? "No routines match your search." : routineFilterKeys.some(key => routineViewState[key].length) || folderSelection === "all" ? "No routines match this view." : "This folder is empty."}
/>
{folderSelection !== "all" ? (
<div className="mt-3 flex justify-center">
@@ -817,10 +725,13 @@ export function Routines() {
/>
) : null}
<CollapsibleContent>
<RoutineTable columns={routineViewState.columns} label={group.label ?? "Routines"}>
{group.items.map((routine) => (
<RoutineListRow
<RoutineTableRow
key={routine.id}
routine={routine}
columns={routineViewState.columns}
userById={userById}
projectById={projectById}
agentById={agentById}
runningRoutineId={runningRoutineId}
@@ -855,6 +766,7 @@ export function Routines() {
}
/>
))}
</RoutineTable>
</CollapsibleContent>
</Collapsible>
);
@@ -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 <main className="design-proposal-theme p-6"><a className="sr-only" data-testid="routine-view-location" href={`${location.pathname}${location.search}`}>Current routine view</a><Routes><Route path="/PAP/routines" element={classic ? <ClassicRoutines /> : <Routines />} /></Routes></main>;
}
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<typeof RoutineListPage>;
export default meta;
type Story = StoryObj<typeof meta>;
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"] } };