Files
PaperClipAI/ui/src/components/SidebarRecentTasks.tsx
T
5b56d430e9 feat(ui): refine core navigation and task detail (#12854)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The main navigation and task detail view are core operator surfaces.
> - Several controls used different hover states, popover layouts, and
spacing rules.
> - Recent task actions also needed a compact menu and correct inbox
archive behavior.
> - These differences made the interface feel inconsistent and caused
some content to look crowded or clipped.
> - This pull request aligns these surfaces with the Paperclip design
tokens and current interaction patterns.
> - The benefit is a simpler and more consistent operator experience in
light and dark modes.

## Linked Issues or Issue Description

**What happened?**

Profile and organization popovers used inconsistent layouts. Navigation
controls used different hover and selected backgrounds. Task warnings
and the composer could crowd nearby content. Archiving a recent task
could also remove it from more than the inbox.

**Expected behavior**

Popover menus should use the same compact visual language. Navigation
controls should share readable hover and selected tokens. Task detail
content should keep consistent spacing. Archiving should hide a task
from the inbox while keeping it in the task list.

**Steps to reproduce**

1. Open the main sidebar in light or dark mode.
2. Open the profile and organization menus.
3. Hover navigation items, the organization trigger, the profile
trigger, and the feedback flag.
4. Open a task with a warning banner and a long thread.
5. Use the recent task overflow menu and archive a task.

**Paperclip version or commit**

Reproduced on `master` before this branch.

**Deployment mode**

Local dev (`pnpm dev`).

## What Changed

- Rebuilt the profile and organization popovers with compact token-based
layouts.
- Matched organization popover width and alignment to the profile
popover.
- Unified sidebar hover and selected states in light and dark modes.
- Added a recent task overflow menu with rename, archive, and pause or
restart actions.
- Kept archived tasks in the task list while removing them from the
inbox.
- Improved warning banner and composer spacing in task detail views.
- Added and updated focused UI tests for the changed behavior.

## Verification

- `pnpm check:token-gates` passed.
- `pnpm --filter @paperclipai/ui typecheck` passed.
- The seven affected UI test files passed with 216 tests.
- `pnpm --filter @paperclipai/ui build` passed.
- GitHub CI passed the full build, typecheck and release registry,
general test, serialized server, canary dry-run, and end-to-end
matrices.
- Greptile reviewed commit `6e296be85` at 5/5 with no outstanding
actionable findings.

## Risks

- Risk is limited to sidebar presentation, recent task actions, and task
detail layout.
- The recent task archive action now follows inbox-only archive
semantics.
- No database schema or public API contract changed.

> I checked [`ROADMAP.md`](ROADMAP.md). This pull request does not
duplicate planned core work.

## Model Used

- OpenAI Codex, GPT-5.6. The model used high reasoning, tool use, and
code execution. The context window size was not exposed.

## 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: Scott Tong <scott@scottsmbpm5max.lan>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-09-04 16:15:21 -07:00

349 lines
13 KiB
TypeScript

import { useState, type FormEvent } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Archive, MoreHorizontal, Pencil, RefreshCw } from "lucide-react";
import { agentsApi } from "@/api/agents";
import { authApi } from "@/api/auth";
import { issuesApi } from "@/api/issues";
import { queryKeys } from "@/lib/queryKeys";
import { useRecentTasks } from "@/hooks/useRecentTasks";
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 { SidebarSection } from "./SidebarSection";
import { SidebarNavItem } from "./SidebarNavItem";
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(storageKey: string | null) {
return storageKey ? `${storageKey}${RESTART_WAKE_RETRY_STORAGE_SUFFIX}` : null;
}
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 { data: session, isPending } = useQuery({
queryKey: queryKeys.auth.session,
queryFn: () => authApi.getSession(),
retry: false,
});
if (!companyId || isPending) return null;
const userId = session?.user?.id ?? session?.session?.userId ?? 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 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(storageKey);
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],
});
} catch (error) {
toastActions?.pushToast({
title: "Task pause update failed",
body: errorMessage(error, "Unable to pause or restart this task."),
tone: "error",
});
} finally {
setPendingAction(null);
}
};
return (
<>
<SidebarSection label="Recent Tasks">
{entries.map((entry) => (
<div key={entry.id} className="group/recent-task relative">
<SidebarNavItem
to={`/issues/${entry.id}`}
label={entry.title}
className={rail ? undefined : "pr-10"}
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="absolute right-2 top-(--pct-50) z-10 -translate-y-(--pct-50) text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:opacity-100 pointer-coarse:opacity-100 group-hover/recent-task:opacity-100 group-focus-within/recent-task:opacity-100 data-[state=open]:bg-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>
))}
</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>
</>
);
}