fix(ui): clean up routines controls and folder loading (#22009)

## Thinking Path

> - Paperclip helps people manage AI agents and their work.
> - Routines define work that repeats and provide controls to find and
organize it.
> - The routine list appeared before its folder data. The folder rail
then moved the list.
> - The page also repeated its folder summary and showed an extra
selection control.
> - This change loads the folder view with the list and reduces the
controls.
> - The result is a stable page with consistent folder rows and clear
icon controls.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

The Routines list page and its folder navigation.

**Current behavior**

The page shows a Select button, a repeated “All routines” summary, and
text buttons for Sort and Group. A delayed folder response moves the
visible list and can show “Unknown folder.” Folder names and counts use
different columns.

**Proposed behavior**

Remove Select and the repeated summary. Show Sort and Group as named
icon buttons. Wait for the initial folder read before showing a
folder-based list. Align folder icons, names, and counts. Show folder
read errors with a retry control. Keep routines readable after an error
or a 15-second request deadline.

**Reason and benefit**

Operators can scan the list without a layout shift or repeated page
labels. Sorting, grouping, search, folder navigation, and per-row filing
remain available.

**Breaking changes**

The routine list no longer has bulk selection. Each row retains its Move
to menu. No API or database contract changes.

The roadmap has no overlapping page cleanup. The open routines PR search
found backend, archive, and scheduling changes, with no matching list
cleanup.

## What Changed

- Remove the selection control, its unused bulk mode, and the repeated
folder summary.
- Use icon buttons with accessible names for Sort and Group. Keep them
beside search on small screens.
- Load folder data before the initial folder list appears. Keep cached
rows visible during a folder refresh. Show folder read errors.
- Use the same icon, name, count, and action columns for All routines,
folders, and Unfiled.
- Add regressions for delayed folder data, failed reads, retry recovery
and stalled requests.
- Keep cached folder names and rows visible after refresh failures.
Suppress empty-folder prompts when the first read fails.
- Update the Storybook test to use the new accessible button names.
- Use the shared fail-fast retry helper with an explicit reason. The
query-error policy check passes.
- Remove the unused folder-row grid token.

## Verification

- Revision: `27d70d1a37bda20496793bbff0fc6adf3a037e80`. Local Linux
checkout, Node 25.9.0, Chromium 151.
- Red/green: delayed folders, failed folder reads, stalled requests and
saved folder filters each failed before their fixes. All now pass.
Failed background reads preserve the routine link and folder navigation.
A failed first read shows all routines; Retry restores the saved folder
or Unfiled filter.
- `pnpm --dir ui exec vitest run src/pages/Routines.test.tsx
src/components/folders/FolderControls.test.tsx src/api/client.test.ts`:
51 tests pass.
- Chromium checks pass for delayed first reveal, folder filters, Sort,
Group, search, mobile folder selection, failed folder reads, the
15-second deadline, and retry recovery. No page errors occurred.
- Storybook: the routine toolbar interaction test passes with the new
button names. Seven interaction and geometry tests pass. The multi-story
navigation test could not finish in the local dev server. Chromium
reported insufficient resources. The first attempts also needed a
browser install and the supported preview hostname. These attempts are
not a full suite pass.
- The visual baseline manifest has zero snapshots and no archive URL.
There is no published baseline to refresh. Screenshots were captured for
review; no baseline archive was created.
- `pnpm --dir ui exec tsc --noEmit`: passes after stopping the local
preview servers. An earlier overlapping attempt hit the workspace memory
limit and is not a pass.
- `node scripts/check-query-error-rendering.mjs --enforce --summary`:
passes with zero findings.
- `git diff --check`: passes. The ignored Storybook catalog was
generated.
- The original `pnpm verify` run selected 578 files and was stopped
after source edits. It is not a pass. Focused checks above cover the
final source. Required CI is running for the new revision.
- Current-head Greptile and Paperclip reviews both give 5/5. All review
threads are resolved. Build, policy and typecheck have passed. Remaining
server suites are running. Squash auto-merge is enabled and waits for
required checks.
- Setup note: full preflight could not build Rust binaries because Cargo
is absent.
- Screenshots use the local source UI with sample API and WebSocket
responses. They do not show a staging deployment or prove backend
behavior.

## Risks

Low risk. The initial folder view now waits for two reads. A folder read
has a 15-second deadline and an explicit retry. A failed read with no
cached data shows the routines without folder groups. Other group modes
do not wait for folder data. Cached background reads keep the visible
rows. Shared folder row alignment also applies to the legacy routines
page.

## Model Used

OpenAI Codex, GPT-6. The runtime did not expose a more specific model
revision. Used reasoning, shell execution, 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
- [ ] 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-17 14:45:30 +00:00
1 parent 1ca90d2d6f
commit 35c4526887
7 files changed
+271 -188

No files matched your search

@@ -159,10 +159,10 @@ test("routines toolbar updates search, sort, group and creation intent", async (
const preview = await openToolbars(page, "routines");
await preview.getByRole("textbox", { name: "Search routines", exact: true }).fill("review");
await expect(preview.locator("output")).toContainText("Search: review");
await preview.getByRole("button", { name: "Sort", exact: true }).click();
await preview.getByRole("button", { name: "Sort routines", exact: true }).click();
await page.getByRole("button", { name: "Title", exact: true }).click();
await expect(preview.locator("output")).toContainText("Sort: title · Direction: asc");
await preview.getByRole("button", { name: "Group", exact: true }).click();
await preview.getByRole("button", { name: "Group routines", exact: true }).click();
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);
+3 -3
View File
@@ -8,11 +8,11 @@ import type {
MoveFolderRequest,
UpdateFolderRequest,
} from "@paperclipai/shared";
import { api } from "./client";
import { api, type RequestOptions } from "./client";
export const foldersApi = {
list: (companyId: string, kind: FolderKind) =>
api.get<FolderListResult>(`/companies/${encodeURIComponent(companyId)}/folders?kind=${kind}`),
list: (companyId: string, kind: FolderKind, options?: RequestOptions) =>
api.get<FolderListResult>(`/companies/${encodeURIComponent(companyId)}/folders?kind=${kind}`, options),
create: (companyId: string, payload: CreateFolderRequest) =>
api.post<Folder>(`/companies/${encodeURIComponent(companyId)}/folders`, payload),
ensureMy: (companyId: string, payload: EnsureMySkillFolderRequest = {}) =>
+74 -77
View File
@@ -8,7 +8,7 @@ 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, selectMode, onToggleSelect }: {
export function RoutinesToolbar({ query, onQueryChange, sortField, sortDir, groupBy, onSortChange, onGroupChange, onNewFolder, onCreateRoutine, tasksHref }: {
query: string;
onQueryChange: (value: string) => void;
sortField: RoutineSortField;
@@ -19,85 +19,82 @@ export function RoutinesToolbar({ query, onQueryChange, sortField, sortDir, grou
onNewFolder?: () => void;
onCreateRoutine: () => void;
tasksHref?: string;
selectMode?: boolean;
onToggleSelect?: () => void;
}) {
return <div data-canonical-toolbar="routines" role="toolbar" aria-label="Routines controls" className="flex flex-wrap items-center gap-4">
<ToolbarSearch query={query} onQueryChange={onQueryChange} label="Search routines" placeholder="Search routines…" />
<Popover>
<PopoverTrigger asChild>
<Button variant="outline" size="sm" title="Sort">
<ArrowUpDown className="h-3.5 w-3.5 sm:h-3 sm:w-3 sm:mr-1" />
<span >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
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="sm" title="Group">
<Layers className="h-3.5 w-3.5 sm:h-3 sm:w-3 sm:mr-1" />
<span >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
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>
))}
</div>
</PopoverContent>
</Popover>
<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">
<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>
<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
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>
))}
</div>
</PopoverContent>
</Popover>
</div>
<div className="design-toolbar-actions">
{onToggleSelect && <Button variant="outline" size="sm" onClick={onToggleSelect}>{selectMode ? "Done" : "Select"}</Button>}
{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>
+12 -11
View File
@@ -208,22 +208,23 @@ export function FolderRail({
<button
type="button"
className={cn(
"grid w-full grid-cols-(--gtc-folder-row) items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors hover:bg-accent/40",
"grid w-full grid-cols-(--gtc-folder-row-actions) items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors hover:bg-accent/40",
active ? "bg-accent/60 text-foreground" : "text-muted-foreground",
)}
aria-current={active ? "page" : undefined}
onClick={() => onSelect(key)}
>
<span className="h-4 w-4">{icon}</span>
<span className="flex h-4 w-4 items-center">{icon}</span>
<span className="truncate">{label}</span>
<span className="text-xs text-muted-foreground">{count}</span>
<span aria-hidden="true" className="h-6 w-6" />
</button>
);
}
return (
<nav aria-label={`${itemLabelPlural} folders`} className="hidden w-(--sz-folder-rail) shrink-0 border-r border-border pr-3 md:block">
<div className="mb-2 flex items-center justify-between gap-2">
<div className="mb-2 flex items-center justify-between gap-2 px-2">
<div className="text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground">Folders</div>
<Button variant="ghost" size="icon-sm" title="New folder" onClick={onCreate}>
<Plus className="h-3.5 w-3.5" />
@@ -257,7 +258,7 @@ export function FolderRail({
<div className="px-2 pb-1 pt-3 text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground">
System
</div>
{renderVirtualRow("unfiled", "Unfiled", result?.unfiledCount ?? 0, <FolderSwatch color={null} className="mt-0.5" />)}
{renderVirtualRow("unfiled", "Unfiled", result?.unfiledCount ?? 0, <FolderSwatch color={null} />)}
</div>
)}
</nav>
@@ -265,9 +266,8 @@ export function FolderRail({
}
/**
* One selectable rail row. The leading 1rem grid column is the reserved
* disclosure/indent slot so nested folders can slot in later without relayout
* (ux-spec §3.1/§3.2 "nesting-ready").
* One selectable rail row. Use the same icon, label, count and action columns
* as All and Unfiled so every folder label and count aligns.
*/
export function FolderRailItem({
folder,
@@ -297,19 +297,20 @@ export function FolderRailItem({
return (
<div
className={cn(
"group grid grid-cols-(--gtc-folder-row-actions) items-center gap-2 rounded-md px-2 py-1 text-sm transition-colors hover:bg-accent/40",
"group grid grid-cols-(--gtc-folder-row-actions) items-center gap-2 rounded-md px-2 py-1.5 text-sm transition-colors hover:bg-accent/40",
active ? "bg-accent/60 text-foreground" : "text-muted-foreground",
)}
>
<span className="h-4 w-4" />
<button
type="button"
className="flex min-w-0 items-center gap-2 text-left"
className="col-span-2 flex min-w-0 items-center gap-2 text-left"
aria-current={active ? "page" : undefined}
onClick={onSelect}
onDoubleClick={onStartRename}
>
<FolderSwatch color={folder.color} />
<span className="flex h-4 w-4 shrink-0 items-center">
<FolderSwatch color={folder.color} />
</span>
{renaming ? (
<input
value={renameDraft}
-1
View File
@@ -392,7 +392,6 @@
--folder-color-cyan: #06b6d4;
--folder-color-amber: #f59e0b;
--folder-color-slate: #64748b;
--gtc-folder-row: 1rem minmax(0, 1fr) auto;
--gtc-folder-row-actions: 1rem minmax(0, 1fr) auto auto;
--sz-folder-rail: 13.25rem;
--sz-folder-sheet-max: 80dvh;
+146 -2
View File
@@ -6,6 +6,8 @@ import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { FolderListResult, Issue, RoutineListItem } from "@paperclipai/shared";
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";
let currentSearch = "";
@@ -20,7 +22,7 @@ async function act(callback: () => void | Promise<void>) {
const navigateMock = vi.fn();
const routinesListMock = vi.fn<(companyId: string) => Promise<RoutineListItem[]>>();
const foldersListMock = vi.fn<(companyId: string, kind: string) => Promise<FolderListResult>>();
const foldersListMock = vi.fn<(companyId: string, kind: string, options?: RequestOptions) => Promise<FolderListResult>>();
const issuesListMock = vi.fn<(companyId: string, filters?: Record<string, unknown>) => Promise<Issue[]>>();
const markdownEditorRenderMock = vi.fn((props: { mentions?: Array<{ id: string; name: string }> }) => props);
const issuesListRenderMock = vi.fn(({ issues }: { issues: Issue[] }) => (
@@ -64,7 +66,7 @@ vi.mock("../api/routines", () => ({
vi.mock("../api/folders", () => ({
foldersApi: {
list: (companyId: string, kind: string) => foldersListMock(companyId, kind),
list: (companyId: string, kind: string, options?: RequestOptions) => foldersListMock(companyId, kind, options),
create: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
@@ -613,6 +615,148 @@ describe("Routines page", () => {
});
});
it("reveals routines with their folder navigation after a delayed folder read", async () => {
routinesListMock.mockResolvedValue([createRoutine({ title: "Delayed folder routine", folderId: "folder-1" })]);
let resolveFolders!: (result: FolderListResult) => void;
foldersListMock.mockReturnValue(new Promise((resolve) => { resolveFolders = resolve; }));
const root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => {
root.render(<QueryClientProvider client={queryClient}><Routines /></QueryClientProvider>);
await flush();
});
await act(async () => { await flush(); });
expect(container.textContent).not.toContain("Delayed folder routine");
await act(async () => {
resolveFolders({
kind: "routine", allCount: 1, unfiledCount: 0,
folders: [{
id: "folder-1", companyId: "company-1", kind: "routine", parentId: null,
name: "Reporting", slug: "reporting", systemKey: null, path: "reporting",
depth: 1, color: "indigo", position: 0, itemCount: 1,
createdAt: new Date(), updatedAt: new Date(),
}],
});
await flush();
});
await act(async () => { await flush(); });
expect(container.textContent).toContain("Delayed folder routine");
expect(container.querySelector('nav[aria-label="routines folders"]')).not.toBeNull();
expect(container.textContent).not.toContain("Unknown folder");
const folderKey = queryKeys.folders.list("company-1", "routine");
const cachedFolders = queryClient.getQueryData<FolderListResult>(folderKey)!;
const routineLink = container.querySelector('a[href="/routines/routine-1"]');
let resolveRefresh!: (result: FolderListResult) => void;
foldersListMock.mockReturnValueOnce(new Promise((resolve) => { resolveRefresh = resolve; }));
await act(async () => {
void queryClient.invalidateQueries({ queryKey: folderKey });
await flush();
});
expect(container.textContent).toContain("Delayed folder routine");
expect(container.querySelector('a[href="/routines/routine-1"]')).toBe(routineLink);
await act(async () => { resolveRefresh(cachedFolders); await flush(); });
foldersListMock.mockRejectedValueOnce(new Error("Folder refresh failed"));
await act(async () => {
await queryClient.invalidateQueries({ queryKey: folderKey });
await flush();
});
await act(async () => { await flush(); });
expect(container.querySelector('a[href="/routines/routine-1"]')).toBe(routineLink);
expect(container.querySelector('nav[aria-label="routines folders"]')).not.toBeNull();
expect(container.textContent).toContain("Reporting");
expect(container.textContent).not.toContain("Unknown folder");
await act(async () => { root.unmount(); });
});
it.each(["all", "folder-1", "unfiled"])("keeps routines readable after a folder read fails, then restores the %s filter on retry", async (selection) => {
currentSearch = selection === "all" ? "" : `folder=${selection}`;
routinesListMock.mockResolvedValue([
createRoutine({ title: "Filed routine", folderId: "folder-1" }),
createRoutine({ id: "routine-2", title: "Loose routine", folderId: null }),
]);
foldersListMock.mockRejectedValueOnce(new Error("Folder read failed"));
const root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
try {
await act(async () => {
root.render(<QueryClientProvider client={queryClient}><Routines /></QueryClientProvider>);
await flush();
});
await act(async () => { await flush(); });
expect(container.textContent).toContain("Filed routine");
expect(container.textContent).toContain("Loose routine");
expect(container.querySelector('[role="alert"]')).not.toBeNull();
expect(container.textContent).not.toContain("Unknown folder");
expect(container.textContent).not.toContain("Create your first folder");
expect(Array.from(container.querySelectorAll("button")).some(button => button.textContent === "New folder")).toBe(false);
expect(container.textContent).not.toContain("All routines");
foldersListMock.mockResolvedValue({
kind: "routine", allCount: 2, unfiledCount: 1,
folders: [{
id: "folder-1", companyId: "company-1", kind: "routine", parentId: null,
name: "Reporting", slug: "reporting", systemKey: null, path: "reporting",
depth: 1, color: "indigo", position: 0, itemCount: 1,
createdAt: new Date(), updatedAt: new Date(),
}],
});
const retry = Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Retry");
expect(retry).toBeTruthy();
await act(async () => { retry!.click(); await flush(); });
await act(async () => { await flush(); });
expect(container.querySelector('[role="alert"]')).toBeNull();
expect(container.querySelector('nav[aria-label="routines folders"]')).not.toBeNull();
expect(container.textContent).toContain("Reporting");
if (selection === "unfiled") {
expect(container.textContent).not.toContain("Filed routine");
} else {
expect(container.textContent).toContain("Filed routine");
}
if (selection === "folder-1") {
expect(container.textContent).not.toContain("Loose routine");
} else {
expect(container.textContent).toContain("Loose routine");
}
} 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" })]);
foldersListMock.mockImplementation((companyId, _kind, options) => actual.foldersApi.list(companyId, "routine", options));
const fetchMock = vi.fn<typeof fetch>(() => new Promise<Response>(() => {}));
vi.stubGlobal("fetch", fetchMock);
vi.useFakeTimers();
const root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
try {
await act(() => root.render(<QueryClientProvider client={queryClient}><Routines /></QueryClientProvider>));
await act(async () => { await vi.advanceTimersByTimeAsync(0); });
expect(container.textContent).not.toContain("Accessible after timeout");
await act(async () => { await vi.advanceTimersByTimeAsync(15_000); });
await act(async () => { await vi.advanceTimersByTimeAsync(1); });
expect(container.textContent).toContain("Accessible after timeout");
expect(container.querySelector('[role="alert"]')).not.toBeNull();
expect(container.textContent).toContain("Retry");
expect(container.textContent).not.toContain("Unknown folder");
expect(container.textContent).not.toContain("Create your first folder");
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock.mock.calls[0][1]?.signal?.aborted).toBe(true);
} finally {
await act(() => root.unmount());
queryClient.clear();
vi.useRealTimers();
vi.unstubAllGlobals();
}
});
it("defaults the routines list to folder mode with inline folder sections", async () => {
foldersListMock.mockResolvedValue({
kind: "routine",
+34 -92
View File
@@ -16,6 +16,7 @@ import { useToastActions } from "../context/ToastContext";
import { buildMarkdownMentionOptions } from "../lib/company-members";
import { cn } from "../lib/utils";
import { queryKeys } from "../lib/queryKeys";
import { retryTransientOnly } from "../lib/query-client";
import { groupBy } from "../lib/groupBy";
import { createIssueDetailLocationState } from "../lib/issueDetailBreadcrumb";
import { collectLiveIssueIds } from "../lib/liveIssueIds";
@@ -56,17 +57,14 @@ import type { FolderListItem } from "@paperclipai/shared";
import { Tabs } from "@/components/ui/tabs";
import {
AllUnfiledBanner,
BulkBar,
DeleteFolderDialog,
FolderChip,
FolderFormDialog,
FolderRail,
FolderSwatch,
MobileFolderSheet,
MoveToMenu,
folderSearchValue,
normalizeFolderSelection,
selectedFolderFromList,
type FolderSelection,
} from "../components/folders/FolderControls";
import { useUpdateIssueMutation } from "../hooks/useUpdateIssueMutation";
@@ -326,8 +324,6 @@ export function Routines() {
const [folderDialogTarget, setFolderDialogTarget] = useState<FolderListItem | null>(null);
const [deleteFolderTarget, setDeleteFolderTarget] = useState<FolderListItem | null>(null);
const [mobileFoldersOpen, setMobileFoldersOpen] = useState(false);
const [selectMode, setSelectMode] = useState(false);
const [selectedRoutineIds, setSelectedRoutineIds] = useState<string[]>([]);
const [moveAfterCreateIds, setMoveAfterCreateIds] = useState<string[]>([]);
const [runningRoutineId, setRunningRoutineId] = useState<string | null>(null);
const [statusMutationRoutineId, setStatusMutationRoutineId] = useState<string | null>(null);
@@ -380,11 +376,15 @@ export function Routines() {
});
const { data: routines, isLoading } = routinesQuery;
const routinesView = useQueryView(routinesQuery);
const { data: routineFolders, isLoading: foldersLoading } = useQuery({
const foldersQuery = useQuery({
queryKey: queryKeys.folders.list(selectedCompanyId!, "routine"),
queryFn: () => foldersApi.list(selectedCompanyId!, "routine"),
queryFn: ({ signal }) => foldersApi.list(selectedCompanyId!, "routine", { signal, timeoutMs: 15_000 }),
// Keep first reveal bounded by the request deadline; the page offers Retry.
retry: retryTransientOnly(0),
enabled: !!selectedCompanyId,
});
const { data: routineFolders, isLoading: foldersLoading } = foldersQuery;
const foldersView = useQueryView(foldersQuery);
const { data: agents } = useQuery({
queryKey: queryKeys.agents.list(selectedCompanyId!),
queryFn: () => agentsApi.list(selectedCompanyId!),
@@ -670,11 +670,11 @@ export function Routines() {
});
}
const folderFilteredRoutines = useMemo(() => {
if (routineViewState.groupBy !== "folder") return visibleRoutines;
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, routineViewState.groupBy, visibleRoutines]);
}, [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(() => {
@@ -706,13 +706,15 @@ export function Routines() {
},
[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, routineViewState.groupBy, projectById, agentById, folderById),
[agentById, folderById, projectById, routineViewState.groupBy, sortedRoutines],
() => buildRoutineSections(sortedRoutines, effectiveGroupBy, projectById, agentById, folderById),
[agentById, folderById, projectById, effectiveGroupBy, sortedRoutines],
);
const currentAssignee = draft.assigneeAgentId ? agentById.get(draft.assigneeAgentId) ?? null : null;
const currentProject = draft.projectId ? projectById.get(draft.projectId) ?? null : null;
const activeFolder = selectedFolderFromList(routineFolders?.folders ?? [], folderSelection);
const hasRoutineFolders = (routineFolders?.folders.length ?? 0) > 0;
const showFolderRail = routineViewState.groupBy === "folder" && hasRoutineFolders;
@@ -748,27 +750,6 @@ export function Routines() {
setComposerOpen(true);
}
async function moveSelectedRoutines(folderId: string | null) {
const ids = selectedRoutineIds;
if (ids.length === 0) return;
try {
await Promise.all(ids.map((itemId) => foldersApi.moveItem(selectedCompanyId!, { kind: "routine", itemId, folderId })));
setSelectedRoutineIds([]);
setSelectMode(false);
await Promise.all([
queryClient.invalidateQueries({ queryKey: queryKeys.routines.list(selectedCompanyId!) }),
queryClient.invalidateQueries({ queryKey: queryKeys.folders.list(selectedCompanyId!, "routine") }),
]);
pushToast({ title: "Routines moved", body: `${ids.length} routine${ids.length === 1 ? "" : "s"} filed.`, tone: "success" });
} catch (moveError) {
pushToast({
title: "Failed to move routines",
body: describeError(moveError, { action: "move the selected routines" }).body,
tone: "error",
});
}
}
function handleRunNow(routine: RoutineListItem) {
setRunDialogRoutine(routine);
}
@@ -805,7 +786,9 @@ export function Routines() {
// Keep loaded routines on screen through a failed refetch; only a real
// failure, or an outage before the first load, replaces the page.
if (isLoading || routinesView.kind === "reconnecting") {
const waitingForFolders = activeTab === "routines" && routineViewState.groupBy === "folder"
&& (foldersLoading || foldersView.kind === "reconnecting");
if (isLoading || routinesView.kind === "reconnecting" || waitingForFolders) {
return <PageSkeleton variant="issues-list" />;
}
@@ -859,10 +842,9 @@ export function Routines() {
sortField={routineViewState.sortField} sortDir={routineViewState.sortDir} groupBy={routineViewState.groupBy}
onSortChange={(sortField, sortDir) => updateRoutineView({ sortField, sortDir })}
onGroupChange={groupBy => updateRoutineView({ groupBy, collapsedGroups: [] })}
onNewFolder={routineViewState.groupBy === "folder" && !hasRoutineFolders ? () => openCreateFolder() : undefined}
onNewFolder={routineViewState.groupBy === "folder" && routineFolders && !hasRoutineFolders ? () => openCreateFolder() : undefined}
onCreateRoutine={openCreateRoutine}
tasksHref="/issues?view=all&originKind=routine_execution&sortField=created&sortDir=desc"
selectMode={selectMode} onToggleSelect={showFolderRail ? () => setSelectMode(current => !current) : undefined}
/>
{!streamlinedUiEnabled ? (
@@ -879,18 +861,16 @@ export function Routines() {
</Tabs>
) : null}
<div className="flex flex-col gap-4">
{routineViewState.groupBy === "folder" ? (
<div className="md:hidden">
<FolderChip
result={railFolderResult}
selection={folderSelection}
allLabel="All routines"
onClick={() => setMobileFoldersOpen(true)}
/>
</div>
) : null}
</div>
{routineViewState.groupBy === "folder" && routineFolders ? (
<div className="md:hidden">
<FolderChip
result={railFolderResult}
selection={folderSelection}
allLabel="All routines"
onClick={() => setMobileFoldersOpen(true)}
/>
</div>
) : null}
<Dialog
open={composerOpen}
@@ -1176,6 +1156,11 @@ export function Routines() {
/>
) : null}
{routineViewState.groupBy === "folder" && foldersView.kind === "error" ? (
<QueryErrorState error={foldersView.error} action="load routine folders"
onRetry={foldersView.retry} retrying={foldersView.isFetching} />
) : null}
<div className={cn(showFolderRail && "flex gap-4")}>
{showFolderRail ? (
<FolderRail
@@ -1195,37 +1180,13 @@ export function Routines() {
/>
) : null}
<div className="min-w-0 flex-1">
{routineViewState.groupBy === "folder" && hasRoutineFolders ? (
<div className="mb-3 flex flex-wrap items-center gap-2">
{folderSelection === "all" ? <FolderIconHeader label="All routines" count={sortedRoutines.length} /> : (
<div className="flex min-w-0 items-center gap-2 text-sm">
<FolderSwatch color={activeFolder?.color} />
<span className="truncate font-medium">{folderSelection === "unfiled" ? "Unfiled" : activeFolder?.name ?? "Folder"}</span>
<span className="text-muted-foreground">{sortedRoutines.length} routine{sortedRoutines.length === 1 ? "" : "s"}</span>
</div>
)}
</div>
) : null}
{routineViewState.groupBy === "folder" && !hasRoutineFolders && !foldersLoading && visibleRoutines.length > 0 ? (
{routineViewState.groupBy === "folder" && routineFolders && !hasRoutineFolders && !foldersLoading && visibleRoutines.length > 0 ? (
<AllUnfiledBanner
storageKey={`paperclip:routines-folder-nudge:${selectedCompanyId ?? "none"}`}
itemLabelPlural="routines"
onCreateFolder={() => openCreateFolder()}
/>
) : null}
{selectMode ? (
<BulkBar
selectedCount={selectedRoutineIds.length}
folders={routineFolders?.folders ?? []}
onMove={(folderId) => void moveSelectedRoutines(folderId)}
onCreateAndMove={() => openCreateFolder(selectedRoutineIds)}
onClear={() => setSelectedRoutineIds([])}
onDone={() => {
setSelectMode(false);
setSelectedRoutineIds([]);
}}
/>
) : null}
{visibleRoutines.length === 0 ? (
<div className="py-12">
<EmptyState
@@ -1286,15 +1247,6 @@ export function Routines() {
onRunNow={handleRunNow}
onToggleEnabled={handleToggleEnabled}
onToggleArchived={handleToggleArchived}
selectMode={selectMode}
selected={selectedRoutineIds.includes(routine.id)}
onSelectChange={(selectedRoutine, selected) => {
setSelectedRoutineIds((current) =>
selected
? Array.from(new Set([...current, selectedRoutine.id]))
: current.filter((id) => id !== selectedRoutine.id)
);
}}
extraMenuItems={
<MoveToMenu
folders={routineFolders?.folders ?? []}
@@ -1383,13 +1335,3 @@ export function Routines() {
</div>
);
}
function FolderIconHeader({ label, count }: { label: string; count: number }) {
return (
<div className="flex min-w-0 items-center gap-2 text-sm">
<Repeat className="h-3.5 w-3.5 text-muted-foreground" />
<span className="truncate font-medium">{label}</span>
<span className="text-muted-foreground">{count} routine{count === 1 ? "" : "s"}</span>
</div>
);
}