Files
PaperClipAI/ui/src/components/SidebarRecentTasks.tsx
T
DottaandClaude Opus 5.5 ee6922f705 perf(tasks): open recent tasks without waiting on a slow ten-task preload (#21939)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A person opens a task from the sidebar's Recent Tasks, the Inbox or
the Tasks list, and the task chat shows its first frame from a
`chat-bootstrap` read
> - On staging, a task opened from Recent Tasks soon after a page load
took 15.3 s to show its chat. The same task from the Inbox took 0.19 s
> - Two defects cause this. Every task's bootstrap paid a fixed ~1.8 s
for its latest runs. Recent Tasks preloaded ten tasks in one request
(17.7 s), and an open waited for that whole request
> - Recent Tasks also warmed its tasks only once per page load. Unread
cache entries are dropped after five minutes, so its tasks were cold for
the rest of the session
> - This pull request makes the runs read use indexes, lets an open read
its own task instead of waiting for a ten-task preload, and re-warms
Recent Tasks on navigation
> - The benefit is that a task from Recent Tasks opens as fast as from a
task list

## Linked Issues or Issue Description

Refs #19818, Refs #16713 (earlier proposals of the same `runsForIssue`
rewrite; this PR adds a query-plan regression test and the client
fixes).

**What happened?**
On staging, a click on a Recent Tasks link about 6 s after a page load
took 15.3 s until the chat thread showed. The Inbox opened the same task
in 0.19 s.

**Steps to reproduce**
1. Load a page with a populated Recent Tasks sidebar.
2. Within a few seconds, click a recent task.
3. The chat stays on its loading state for many seconds.

**Expected behavior**
The task opens about as fast as from the Inbox or the Tasks list.

**Root cause (measured on staging)**
- `GET /issues/:id/runs?view=recent` took 1.7–1.9 s of server time for
tasks with 1 to 24 runs. Every other first-frame read took 80–350 ms.
The query filtered with `issue_id = $1 OR EXISTS (activity_log … run_id
= heartbeat_runs.id)`, so Postgres walked every run of the company.
- The bootstrap reads two tasks at a time, so the Recents preload of ten
tasks took 17.7 s. Each task in a batch settles only with the whole
request, and the page's reads wait for it (up to the 5 s share deadline,
then read again under load).
- `useRecentTaskOpenWarmup` remembered preloaded task ids for the life
of the page and never preloaded them again.

## What Changed

- `activityService.runsForIssue`: select the task's runs by `id IN (runs
with issue_id = task UNION run ids from the task's activity)`. Each half
uses its own index. The results are the same.
- `startIssueChatBootstrap`: when the only request for a task is a
background batch that is still loading, send a request for that task
alone. All refs of the task point to the new request. The later batch
answer only fills keys that are still empty or older.
- `loadIssueChatBootstraps` (background): a task whose answer did not
arrive is not held back for five minutes, so the next preload can retry
it.
- `useRecentTaskOpenWarmup`: use the background preload (five-minute
repeat, the same as the cache GC time) and run again after each
navigation (`navigationKey`). It no longer keeps a per-page-load set.
`SidebarRecentTasks` and `CoordinatorSidebar` pass the pathname.

## Verification

- `server/src/__tests__/issue-runs-read-cost.test.ts` (new): a company
with 20,003 runs, and a task with 3 runs. EXPLAIN ANALYZE of the runs
reads examined **40,011** run rows before the fix and **15** after
(red/green). The test also checks the run order and the run that is
linked only through activity.
- `ui/src/lib/issue-chat-bootstrap.test.ts`: a new test opens a task
while a ten-task preload is still loading. Before the fix it timed out
waiting on the batch. After the fix it reads its own request. A second
new test checks that a single-task request is still shared.
- `ui/src/hooks/useRecentTaskOpenWarmup.test.tsx`: a new test re-warms
Recents on a navigation after five minutes (red on the old hook).
Another new test sends nothing for navigations inside five minutes.
- Existing suites pass: activity service/routes, task cold open, agent
conversations (197 tests); sidebar, Recents, navigation prefetch, issue
detail cache, IssueDetail (341 tests).
- `tsc --noEmit` is clean for `server` and `ui` (apart from the
pre-existing Storybook index errors).
- `pnpm verify` exits 2 (an opaque server setup dependency), so CI
supplies the broad coverage.
- After deploy: on staging, time a Recent Tasks click a few seconds
after a cold load, and time `runs?view=recent`.

## Risks

- Low risk. The SQL change keeps the same filter. It changes only how
Postgres finds the candidate runs. The existing activity tests cover
retry, credential and conversation cases.
- An open during a background preload now sends one more bootstrap
request for that task. This happens only on an open or a resting hover,
never for each row.
- Recents now sends at most one preload per five minutes while the
person navigates. It sends nothing while the tab is idle or hidden.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, browser measurement on staging, code execution).

## Checklist

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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 15:26:22 -06:00

366 lines
14 KiB
TypeScript

import { useMemo, useState, type FormEvent } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { Archive, MoreHorizontal, Pencil, RefreshCw } from "lucide-react";
import { agentsApi } from "@/api/agents";
import { issuesApi } from "@/api/issues";
import { queryKeys } from "@/lib/queryKeys";
import { useRecentTasks } from "@/hooks/useRecentTasks";
import { useRecentTaskOpenWarmup } from "@/hooks/useRecentTaskOpenWarmup";
import { useAccountIdentity } from "@/api/companies-query";
import { useSidebar } from "@/context/SidebarContext";
import { useOptionalToastActions } from "@/context/ToastContext";
import {
updateRecentTaskSnapshots,
type RecentTaskEntry,
} from "@/lib/recent-tasks";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { StatusIcon } from "./StatusIcon";
import { SidebarSection } from "./SidebarSection";
import { RecentTaskNavItem } from "./RecentTaskNavItem";
import { RecentTaskGroup } from "./RecentTaskGroup";
import { recentTaskHierarchy } from "@/lib/recent-task-hierarchy";
import { useLocation } from "@/lib/router";
import { taskStatusIconProps } from "@/lib/task-status-presentation";
const RECENT_TASK_MENU_ITEM_CLASS =
"h-(--profile-popover-row-height) gap-(--profile-popover-row-gap) rounded-lg px-2.5 py-0 text-(length:--text-compact) font-medium leading-(--profile-popover-label-line-height) focus:bg-accent/50 focus:text-foreground";
const RESTART_WAKE_RETRY_STORAGE_SUFFIX = ":restart-wake-retry";
function restartWakeRetryStorageKey(companyId: string, userId: string | null) {
// Action retry state must survive changes to the recent-task snapshot format.
return `paperclip.recentTasks:${companyId}:${userId ?? "__local_board__"}${RESTART_WAKE_RETRY_STORAGE_SUFFIX}`;
}
function readRestartWakeRetryIssueIds(storageKey: string | null) {
if (!storageKey) return new Set<string>();
try {
const parsed = JSON.parse(window.localStorage.getItem(storageKey) ?? "[]") as unknown;
return new Set(Array.isArray(parsed) ? parsed.filter((value): value is string => typeof value === "string") : []);
} catch {
return new Set<string>();
}
}
function setRestartWakeRetryPending(storageKey: string | null, issueId: string, pending: boolean) {
if (!storageKey) return;
const issueIds = readRestartWakeRetryIssueIds(storageKey);
if (pending) issueIds.add(issueId);
else issueIds.delete(issueId);
try {
if (issueIds.size > 0) window.localStorage.setItem(storageKey, JSON.stringify([...issueIds]));
else window.localStorage.removeItem(storageKey);
} catch {
// Recent Tasks remains usable when browser storage is unavailable.
}
}
function errorMessage(error: unknown, fallback: string) {
return error instanceof Error && error.message.trim() ? error.message : fallback;
}
export function SidebarRecentTasks({
companyId,
liveIssueIds,
}: {
companyId: string | null | undefined;
liveIssueIds: ReadonlySet<string>;
}) {
const { collapsed, peeking } = useSidebar();
const rail = collapsed && !peeking;
const { userId, settled } = useAccountIdentity();
if (!companyId || !settled) return null;
return (
<RecentTasksList
key={`${companyId}:${userId ?? "__local_board__"}`}
companyId={companyId}
userId={userId}
liveIssueIds={liveIssueIds}
rail={rail}
/>
);
}
function RecentTasksList({
companyId,
userId,
liveIssueIds,
rail,
}: {
companyId: string;
userId: string | null;
liveIssueIds: ReadonlySet<string>;
rail: boolean;
}) {
const { entries, storageKey } = useRecentTasks({ companyId, userId });
const { pathname } = useLocation();
const hierarchy = useMemo(() => recentTaskHierarchy(entries, pathname), [entries, pathname]);
const queryClient = useQueryClient();
const toastActions = useOptionalToastActions();
const [renameEntry, setRenameEntry] = useState<RecentTaskEntry | null>(null);
const [renameValue, setRenameValue] = useState("");
const [pendingAction, setPendingAction] = useState<"rename" | "archive" | "pause" | null>(null);
const restartRetryStorageKey = restartWakeRetryStorageKey(companyId, userId);
useRecentTaskOpenWarmup({ companyId, userId, tasks: entries, navigationKey: pathname });
if (entries.length === 0) return null;
const refreshIssueQueries = async (issueId: string) => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: queryKeys.issues.detail(issueId) }),
queryClient.invalidateQueries({ queryKey: queryKeys.issues.list(companyId) }),
queryClient.invalidateQueries({ queryKey: queryKeys.issues.activity(issueId) }),
]);
};
const beginRename = (entry: RecentTaskEntry) => {
setRenameEntry(entry);
setRenameValue(entry.title);
};
const submitRename = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const nextTitle = renameValue.trim();
if (!renameEntry || !nextTitle || nextTitle === renameEntry.title) {
setRenameEntry(null);
return;
}
setPendingAction("rename");
try {
const updated = await issuesApi.update(renameEntry.id, { title: nextTitle });
queryClient.setQueryData(queryKeys.issues.detail(renameEntry.id), updated);
if (storageKey) updateRecentTaskSnapshots(storageKey, companyId, [updated]);
await refreshIssueQueries(renameEntry.id);
setRenameEntry(null);
toastActions?.pushToast({ title: "Task renamed", tone: "success" });
} catch (error) {
toastActions?.pushToast({
title: "Task rename failed",
body: errorMessage(error, "Unable to rename this task."),
tone: "error",
});
} finally {
setPendingAction(null);
}
};
const archiveTask = async (entry: RecentTaskEntry) => {
setPendingAction("archive");
try {
await issuesApi.archiveFromInbox(entry.id);
await refreshIssueQueries(entry.id);
await queryClient.invalidateQueries({
queryKey: queryKeys.sidebarBadges(companyId),
});
toastActions?.pushToast({ title: "Task archived from inbox", tone: "success" });
} catch (error) {
toastActions?.pushToast({
title: "Task archive failed",
body: errorMessage(error, "Unable to archive this task from the inbox."),
tone: "error",
});
} finally {
setPendingAction(null);
}
};
const toggleTaskPause = async (entry: RecentTaskEntry) => {
setPendingAction("pause");
try {
const state = await issuesApi.getTreeControlState(entry.id);
if (state.activePauseHold?.isRoot) {
const restartIssue = await issuesApi.get(entry.id);
setRestartWakeRetryPending(restartRetryStorageKey, entry.id, true);
await issuesApi.releaseTreeHold(entry.id, state.activePauseHold.holdId, {
reason: "Restarted from Recent Tasks.",
});
if (restartIssue.assigneeAgentId) {
const wakeResult = await agentsApi.wakeup(
restartIssue.assigneeAgentId,
{
source: "assignment",
triggerDetail: "manual",
reason: "recent_task_restart",
payload: { issueId: restartIssue.id },
},
restartIssue.companyId,
);
if (!("id" in wakeResult)) {
throw new Error(wakeResult.message ?? "The assignee wake was skipped.");
}
}
setRestartWakeRetryPending(restartRetryStorageKey, entry.id, false);
toastActions?.pushToast({ title: "Task restarted", tone: "success" });
} else if (state.activePauseHold) {
throw new Error("This task is paused by a parent task. Restart it from the pause root.");
} else if (readRestartWakeRetryIssueIds(restartRetryStorageKey).has(entry.id)) {
const restartIssue = await issuesApi.get(entry.id);
if (restartIssue.assigneeAgentId) {
const wakeResult = await agentsApi.wakeup(
restartIssue.assigneeAgentId,
{
source: "assignment",
triggerDetail: "manual",
reason: "recent_task_restart_retry",
payload: { issueId: restartIssue.id },
},
restartIssue.companyId,
);
if (!("id" in wakeResult)) {
throw new Error(wakeResult.message ?? "The assignee wake was skipped.");
}
}
setRestartWakeRetryPending(restartRetryStorageKey, entry.id, false);
toastActions?.pushToast({ title: "Task restarted", tone: "success" });
} else {
await issuesApi.createTreeHold(entry.id, {
mode: "pause",
reason: "Paused from Recent Tasks.",
releasePolicy: { strategy: "manual" },
});
toastActions?.pushToast({ title: "Task paused", tone: "success" });
}
await queryClient.invalidateQueries({
queryKey: ["issues", "tree-control-state", entry.id],
});
await queryClient.invalidateQueries({ queryKey: queryKeys.issues.summaries(companyId) });
} catch (error) {
toastActions?.pushToast({
title: "Task pause update failed",
body: errorMessage(error, "Unable to pause or restart this task."),
tone: "error",
});
} finally {
setPendingAction(null);
}
};
const renderTaskRow = (entry: RecentTaskEntry) => (
<div className="sidebar-action-row group/recent-task relative">
<RecentTaskNavItem
task={entry}
label={entry.title}
iconNode={entry.displayStatus === "monitoring" && !liveIssueIds.has(entry.id) ? <StatusIcon {...taskStatusIconProps(entry)} /> : undefined}
trailing={entry.status === "in_review" && entry.externalConversationState === "waiting"
? <span className="text-xs text-muted-foreground">Idle</span> : undefined}
trailingLabel={entry.status === "in_review" && entry.externalConversationState === "waiting" ? "Idle" : undefined}
className={rail ? undefined : "sidebar-action-link pointer-coarse:pr-8"}
liveCount={liveIssueIds.has(entry.id) ? 1 : undefined}
/>
{!rail ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon-xs"
aria-label={`More actions for ${entry.title}`}
className="sidebar-action-menu absolute right-2 top-(--pct-50) z-10 -translate-y-(--pct-50) text-muted-foreground pointer-events-none opacity-0 transition-opacity hover:bg-sidebar-accent dark:hover:bg-sidebar-accent hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 pointer-coarse:pointer-events-auto pointer-coarse:opacity-100 pointer-coarse:before:hidden group-hover/recent-task:pointer-events-auto group-hover/recent-task:opacity-100 group-focus-within/recent-task:pointer-events-auto group-focus-within/recent-task:opacity-100 data-[state=open]:pointer-events-auto data-[state=open]:bg-sidebar-accent data-[state=open]:text-foreground data-[state=open]:opacity-100"
>
<MoreHorizontal aria-hidden="true" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent
side="right"
align="start"
className="w-(--profile-popover-width) rounded-xl p-1.5 shadow-(--shadow-profile-popover)"
>
<DropdownMenuItem
className={RECENT_TASK_MENU_ITEM_CLASS}
onSelect={() => beginRename(entry)}
>
<Pencil aria-hidden="true" />
Rename
</DropdownMenuItem>
<DropdownMenuItem
className={RECENT_TASK_MENU_ITEM_CLASS}
disabled={pendingAction !== null}
onSelect={() => void archiveTask(entry)}
>
<Archive aria-hidden="true" />
Archive
</DropdownMenuItem>
<DropdownMenuItem
className={RECENT_TASK_MENU_ITEM_CLASS}
disabled={pendingAction !== null}
onSelect={() => void toggleTaskPause(entry)}
>
<RefreshCw aria-hidden="true" />
Pause/Restart
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
) : null}
</div>
);
return (
<>
<SidebarSection label="Recent Tasks">
{entries.filter(entry => rail || !hierarchy.nestedIds.has(entry.id)).map((entry) => (
<RecentTaskGroup key={entry.id} task={entry} userId={userId} rail={rail} flattened={hierarchy.flattenedIds.has(entry.id)}
selectedChild={hierarchy.selectedChild?.parentId === entry.id ? hierarchy.selectedChild : undefined} renderChild={renderTaskRow}>
{renderTaskRow(entry)}
</RecentTaskGroup>
))}
</SidebarSection>
<Dialog
open={renameEntry !== null}
onOpenChange={(open) => {
if (!open && pendingAction !== "rename") setRenameEntry(null);
}}
>
<DialogContent className="sm:max-w-md">
<form className="grid gap-4" onSubmit={(event) => void submitRename(event)}>
<DialogHeader>
<DialogTitle>Rename task</DialogTitle>
<DialogDescription>Choose a short, clear name for this task.</DialogDescription>
</DialogHeader>
<Input
autoFocus
aria-label="Task name"
value={renameValue}
disabled={pendingAction === "rename"}
onChange={(event) => setRenameValue(event.target.value)}
/>
<DialogFooter>
<Button
type="button"
variant="outline"
disabled={pendingAction === "rename"}
onClick={() => setRenameEntry(null)}
>
Cancel
</Button>
<Button
type="submit"
disabled={pendingAction === "rename" || !renameValue.trim()}
>
{pendingAction === "rename" ? "Saving..." : "Save"}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
</>
);
}