Fix Recents ordering and add sidebar pins (#22219)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The sidebar gives people quick access to tasks, chats, and projects.
> - Recents should reflect the order in which a person opened their
tasks.
> - Opening a task only updated its saved details. It did not update the
visit time.
> - This pull request records task visits and adds Recents shortcuts to
the existing sidebar pins.
> - People can find their last task and keep frequently used items above
More.

## Linked Issues or Issue Description

**What happened?**

Opening a personal task left it in its old position or added it at the
bottom of Recents. The Recents rows also had no controls to pin their
items.

**Expected behavior**

Opening a task moves it to the top of Recents. Opening a nested task
moves its parent group to the top. A person can pin a task, chat, or
project from Recents.

**Steps to reproduce**

1. Open two personal tasks in the Coordinator workspace.
2. Reopen the first task and check its position in Recents.
3. Hover over a Recents row and look for a pin button.

**Paperclip version or commit**

Reproduced on source checkout `43b2d8be22`.

**Deployment mode**

Local dev with an isolated embedded PostgreSQL database.

Related work: #22024, #21649, and #19685.

## What Changed

- Record the first loaded task visit and subsequent reopens. Keep the
timestamp during background refreshes.
- Use the most recent task visit in each displayed group when ordering
parent rows.
- Add tasks, agent chats, and projects from Coordinator Recents to the
existing sortable sidebar pins. Resolve saved shortcuts with the current
company data and task read permissions.
- Use the same highlight state for a Recents row and its pin button.
This includes the current row, hover, and keyboard focus.

## Verification

- The reopen test failed before the fix because the older task stayed
below the newer task. The Chromium check also reproduced the missing pin
on the current row before the highlight fix.
- Ran the eight focused Vitest files for task detail, the two sidebars,
recent task state, task warmup, and pinned navigation on macOS. Ran
`pnpm --filter @paperclipai/ui typecheck`.
- In Chromium on the isolated dev server, opened two tasks and reopened
the first. Pinned a task and project and confirmed that both survived
reload. Checked current, hovered, and keyboard-focused rows. Checked
that a pointer click did not keep the pin visible after leaving an
inactive row.
- `pnpm verify` requested broader CI coverage because the product
documentation changed.

- GitHub CI passed on `b77fc06393`. The initial native-server and Canary
jobs lost their runners. Both jobs passed on retry without a code
change. [CI
retry](https://github.com/paperclipai/paperclip/actions/runs/44373716458/attempts/2)
- Greptile scored the same commit 5/5 and left no review threads.
[Greptile
review](https://github.com/paperclipai/paperclip/pull/22219#issuecomment-6988318333)

## Risks

- Recent ordering keeps the existing participation filter and subtask
groups. A task pin uses the existing summary batch to check read access
independently of participation.
- Pins are stored per browser user. Task and project keys include the
company ID. Existing page and agent-chat keys keep their saved order.
- The change uses the existing summaries API. It requires no schema
migration.

## Model Used

- OpenAI GPT-6 via Codex, with shell, GitHub CLI, and Chromium
verification tools.

## 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 linked existing issues or described the issue using
the relevant issue template
- [x] I have not referenced internal or instance-local Paperclip issues
or links
- [x] My branch name describes the change and contains no internal
Paperclip ticket ID
- [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 <1504818+scotttong@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
authored and GitHub committed 2026-11-18 12:52:37 -08:00
1 parent 33fac97cad
commit 911fe5bb9a
11 files changed
+259 -87

No files matched your search

+6
View File
@@ -98,6 +98,12 @@ a linked card at creation time with the current title, task number, and status.
The Tasks tab keeps the full relationship list and shows each task once. Project
groups omit tasks already shown in the other sections and disappear when empty.
Opening a personal task moves it to the top of sidebar Recents. A visit to a
nested task moves its parent group. Coordinator Recents lets you pin tasks, agent
chats, and projects above More. The pin button appears on the current row or
when a row is hovered or focused with the keyboard. Shortcuts share the saved
order with pinned pages and stay available as Recents changes.
Sidebar Recents shows readable direct subtasks below a recent parent. Each group
can fold independently, starts with at most ten children, and loads more on
request. Waiting external chat children remain visible in explicit child lists.
+62 -12
View File
@@ -3,20 +3,22 @@ import { act, type ReactNode } from "react";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { Agent, AttentionFeed, AttentionItem } from "@paperclipai/shared";
import type { Agent, AttentionFeed, AttentionItem, IssueSummary, Project } from "@paperclipai/shared";
import { buildPinnedNavigationItems, CoordinatorSidebar } from "./CoordinatorSidebar";
import { TooltipProvider } from "./ui/tooltip";
import { coordinatorAttentionQueryKey, coordinatorAttentionSummaryQueryKey, coordinatorAttentionTasksQueryKey } from "@/lib/coordinator-attention";
import { queryKeys } from "@/lib/queryKeys";
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const fixture = vi.hoisted(() => ({ attention: vi.fn(), summary: vi.fn(), openNewIssue: vi.fn(), pathname: "/COO/issues", search: "", userId: "reviewer" as string | null, chats: [] as Array<{ isUnreadForMe: boolean }>,
recentTasks: [] as Array<Record<string, unknown>>, projects: [] as Array<Record<string, unknown>>, projectTasks: vi.fn(), enableCases: false, enableResponsibilities: false, agents: [] as Agent[] }));
const fixture = vi.hoisted(() => ({ attention: vi.fn(), summary: vi.fn(), openNewIssue: vi.fn(), pathname: "/COO/issues", search: "", userId: "reviewer" as string | null, chats: [] as Array<{ id?: string; conversationAgentId?: string; updatedAt?: string; isUnreadForMe: boolean }>,
recentTasks: [] as Array<Record<string, unknown>>, taskSummaries: [] as Array<Record<string, unknown>>, projects: [] as Array<Record<string, unknown>>, projectTasks: vi.fn(), enableCases: false, enableResponsibilities: false, agents: [] as Agent[] }));
vi.mock("@/hooks/useCoordinatorWorkspaceEnabled", () => ({ useCoordinatorWorkspaceEnabled: () => ({ enabled: true, userId: fixture.userId }) }));
vi.mock("@/hooks/useAgentChatNavigation", () => ({ useAgentChatNavigation: () => ({
companyId: "company", userId: fixture.userId, agents: { data: fixture.agents }, chats: { data: fixture.chats }, session: { isSuccess: true },
}) }));
vi.mock("@/hooks/useRecentTasks", () => ({ useRecentTasks: () => ({ entries: fixture.recentTasks }) }));
vi.mock("@/hooks/useRecentTasks", () => ({ useRecentTasks: ({ pinnedTaskIds }: { pinnedTaskIds: string[] }) => ({
entries: fixture.recentTasks, pinnedTasks: fixture.taskSummaries.filter(task => pinnedTaskIds.includes(String(task.id))),
}) }));
vi.mock("@/api/issues", () => ({ issuesApi: { listCompact: fixture.projectTasks } }));
const taskPrefetch = vi.hoisted(() => vi.fn(() => Promise.resolve()));
vi.mock("@/lib/issueDetailCache", async (importOriginal) => ({
@@ -52,7 +54,7 @@ function summary(items: AttentionItem[], mineCount = items.length) {
let root: Root, container: HTMLDivElement, client: QueryClient;
beforeEach(() => {
vi.clearAllMocks(); localStorage.clear(); fixture.userId = "reviewer"; fixture.pathname = "/COO/issues"; fixture.search = "";
fixture.chats = []; fixture.recentTasks = []; fixture.projects = []; fixture.enableCases = false; fixture.enableResponsibilities = false; fixture.agents = [];
fixture.chats = []; fixture.recentTasks = []; fixture.taskSummaries = []; fixture.projects = []; fixture.enableCases = false; fixture.enableResponsibilities = false; fixture.agents = [];
fixture.summary.mockResolvedValue(summary([pending("question"), pending("review")]));
container = document.createElement("div"); document.body.appendChild(container); root = createRoot(container);
client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
@@ -142,6 +144,20 @@ describe("Coordinator task creation", () => {
expect(region.textContent).not.toContain("Recents");
expect(region.querySelector('a[href="/issues/TASK-0"]')).not.toBeNull();
});
it("moves the recent parent group ahead of newer rows after opening its child", async () => {
const parent = { id: "parent", companyId: "company", identifier: "TASK-1", title: "Parent", status: "todo", recordedAt: 1, subtaskCount: 1 };
const child = { id: "child", companyId: "company", identifier: "TASK-2", title: "Child", status: "todo", recordedAt: 2, parentId: parent.id };
const other = { id: "other", companyId: "company", identifier: "TASK-3", title: "Other", status: "todo", recordedAt: 3 };
fixture.recentTasks = [other, child, parent];
fixture.projectTasks.mockResolvedValue([child]);
await renderSidebar();
const order = () => Array.from(container.querySelectorAll('[aria-label="Recents"] a'), link => link.getAttribute("href"));
expect(order()).toEqual(["/issues/TASK-3", "/issues/TASK-1", "/issues/TASK-2"]);
fixture.pathname = "/COO/issues/TASK-2";
fixture.recentTasks = [{ ...child, recordedAt: 4 }, other, parent];
await renderSidebar();
expect(order()).toEqual(["/issues/TASK-1", "/issues/TASK-2", "/issues/TASK-3"]);
});
it("opens global search from the organization header", async () => {
await renderSidebar();
const listener = vi.fn();
@@ -167,6 +183,38 @@ describe("Coordinator task creation", () => {
});
describe("Coordinator pinned pages", () => {
it("pins tasks, chats, and projects from Recents and restores them above More in saved order", async () => {
const task = { id: "e4acf42d-422f-44b8-84b8-9d678f8b7c7c", companyId: "company", identifier: "TASK-1", title: "Release task", status: "todo", recordedAt: 1 };
fixture.agents = [{ id: "cto", companyId: "company", name: "CTO", urlKey: "cto", role: "cto", status: "idle" } as Agent];
fixture.chats = [{ id: "chat", conversationAgentId: "cto", updatedAt: "2026-11-11T12:00:00Z", isUnreadForMe: false }];
fixture.projects = [{ id: "project", companyId: "company", name: "Launch", urlKey: "launch" }];
fixture.pathname = "/COO/projects/launch";
fixture.taskSummaries = [task];
fixture.recentTasks = [task];
await renderSidebar();
const recents = container.querySelector('[aria-label="Recents"]')!;
const pinnedLinks = () => Array.from(navigation().querySelectorAll(".group\\/coordinator-pin a"), link => link.getAttribute("href"));
for (const label of ["Release task", "CTO", "Launch"]) {
const button = recents.querySelector<HTMLButtonElement>(`button[aria-label="Pin ${label}"]`)!;
expect(button).not.toBeNull();
expect(button.closest("a")).toBeNull();
await act(async () => button.click());
expect(button.getAttribute("aria-pressed")).toBe("true");
}
expect(pinnedLinks()).toEqual(["/issues/TASK-1", "/chats/cto", "/projects/launch"]);
fixture.pathname = "/COO/issues";
fixture.recentTasks = [];
fixture.chats = [];
fixture.taskSummaries = [{ ...task, title: "Renamed release task" }];
await act(async () => root.unmount());
root = createRoot(container);
await renderSidebar();
expect(container.querySelector('[aria-label="Recents"]')).toBeNull();
expect(pinnedLinks()).toEqual(["/issues/TASK-1", "/chats/cto", "/projects/launch"]);
expect(pinnedPage("/issues/TASK-1")?.textContent).toContain("Renamed release task");
await click("Unpin Renamed release task");
expect(pinnedLinks()).toEqual(["/chats/cto", "/projects/launch"]);
});
it("matches pinned and recent agent avatar dimensions to task status icons", async () => {
fixture.agents = [{ id: "cto", companyId: "company", name: "CTO", urlKey: "cto", role: "cto", status: "idle" } as Agent];
const chat = { id: "chat-cto", conversationAgentId: "cto", updatedAt: "2026-11-11T12:00:00Z", isUnreadForMe: false };
@@ -189,20 +237,22 @@ describe("Coordinator pinned pages", () => {
expect(avatar.height).toBe(height);
}
});
it("builds hundreds of agent pins with input reads proportional to list size", () => {
const agents = Array.from({ length: 500 }, (_, index) => ({ id: `agent-${index}`, companyId: "company", name: `Agent ${index}`, urlKey: `agent-${index}` } as Agent));
const pins = agents.map(agent => `agent-chat:company:${agent.id}`).reverse();
it("builds hundreds of mixed pins with input reads proportional to list size", () => {
const agents = Array.from({ length: 200 }, (_, index) => ({ id: `agent-${index}`, companyId: "company", name: `Agent ${index}`, urlKey: `agent-${index}` } as Agent));
const tasks = Array.from({ length: 200 }, (_, index): IssueSummary => ({ id: `task-${index}`, companyId: "company", title: `Task ${index}`, identifier: `TASK-${index}`, status: "todo", updatedAt: new Date(0), externalConversationState: null }));
const projects = Array.from({ length: 200 }, (_, index) => ({ id: `project-${index}`, companyId: "company", name: `Project ${index}`, urlKey: `project-${index}` } as Project));
const pins = agents.flatMap((agent, index) => [`agent-chat:company:${agent.id}`, `project:company:${projects[index]!.id}`, `task:company:${tasks[index]!.id}`]).reverse();
let reads = 0;
function bounded<T>(items: T[]) {
return new Proxy(items, { get(target, property, receiver) {
if (typeof property === "string" && /^\d+$/.test(property) && ++reads > 4 * agents.length) throw new Error("Pin construction scans growing lists repeatedly");
if (typeof property === "string" && /^\d+$/.test(property) && ++reads > 4 * pins.length) throw new Error("Pin construction scans growing lists repeatedly");
return Reflect.get(target, property, receiver);
} });
}
const items = buildPinnedNavigationItems(bounded(pins), bounded(agents), []);
const items = buildPinnedNavigationItems(bounded(pins), bounded(agents), [], bounded(tasks), bounded(projects));
expect(items.map(item => item.key)).toEqual(pins);
expect(reads).toBeLessThanOrEqual(4 * agents.length);
expect(items[0].to).toBe("/chats/agent-499");
expect(reads).toBeLessThanOrEqual(4 * pins.length);
expect(items.slice(0, 3).map(item => item.to)).toEqual(["/issues/TASK-199", "/projects/project-199", "/chats/agent-199"]);
});
it("keeps mixed pins above More in stored order and prevents native link dragging", async () => {
fixture.agents = [{ id: "cto", companyId: "company", name: "CTO", urlKey: "cto", role: "cto", status: "idle" } as Agent];
+85 -27
View File
@@ -1,7 +1,7 @@
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { useQuery } from "@tanstack/react-query";
import { Inbox, Boxes, ChevronRight, CircleCheck, Compass, FolderOpen, History, LayoutDashboard, MessageCircle, MoreHorizontal, Network, Pin, PinOff, Plus, Repeat, Search, Settings, SquarePen, Unplug, type LucideIcon } from "lucide-react";
import type { Agent, Project } from "@paperclipai/shared";
import type { Agent, IssueSummary, Project } from "@paperclipai/shared";
import { useCoordinatorAttentionCount } from "@/hooks/useCoordinatorAttentionCount";
import { issuesApi } from "@/api/issues";
import { instanceSettingsApi } from "@/api/instanceSettings";
@@ -13,11 +13,12 @@ import { usePinnedNavigation } from "@/hooks/usePinnedNavigation";
import { useDialogActions } from "@/context/DialogContext";
import { useSidebar } from "@/context/SidebarContext";
import { queryKeys } from "@/lib/queryKeys";
import type { RecentTaskEntry } from "@/lib/recent-tasks";
import { Link, useLocation } from "@/lib/router";
import { agentRouteRef, cn, projectRouteRef } from "@/lib/utils";
import { SidebarCompanyMenu } from "./SidebarCompanyMenu";
import { SidebarNavItem } from "./SidebarNavItem";
import { RecentTaskNavItem } from "./RecentTaskNavItem";
import { RecentTaskNavItem, recentTaskPathRef } from "./RecentTaskNavItem";
import { RecentTaskGroup } from "./RecentTaskGroup";
import { recentTaskHierarchy } from "@/lib/recent-task-hierarchy";
import { SidebarSection } from "./SidebarSection";
@@ -34,6 +35,9 @@ import { PinnedNavigationList, type PinnedNavigationItem } from "./PinnedNavigat
import { companyProjectsQuery } from "@/lib/company-projects-query";
const NO_RECENT_TASKS: never[] = [];
const TASK_PIN_ID_PATTERN = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
const taskPinKey = (companyId: string, id: string) => `task:${companyId}:${id}`;
const projectPinKey = (project: Project) => `project:${project.companyId}:${project.id}`;
const moreDestinations = [
{ label: "Search", to: "/search", icon: Search },
@@ -48,20 +52,62 @@ const moreDestinations = [
{ label: "Settings", to: "/settings", icon: Settings },
] as const;
export function buildPinnedNavigationItems(pins: readonly string[], agents: readonly Agent[], destinations: readonly { to: string; label: string; icon: LucideIcon }[]): PinnedNavigationItem[] {
export function buildPinnedNavigationItems(
pins: readonly string[],
agents: readonly Agent[],
destinations: readonly { to: string; label: string; icon: LucideIcon }[],
tasks: readonly IssueSummary[] = [],
projects: readonly Project[] = [],
): PinnedNavigationItem[] {
if (!pins.length) return [];
const keys = new Set(pins);
const items = new Map<string, PinnedNavigationItem>(destinations.map(item => [item.to, { key: item.to, to: item.to, label: item.label, icon: <item.icon className="size-4" /> }]));
for (const agent of agents) {
const key = agentChatPinKey(agent.companyId, agent.id);
if (keys.has(key)) items.set(key, { key, to: `/chats/${encodeURIComponent(agentRouteRef(agent))}`, label: agent.name, icon: <AgentAvatar agent={agent} size={16} /> });
}
for (const task of tasks) {
const key = taskPinKey(task.companyId, task.id);
if (keys.has(key)) items.set(key, { key, to: `/issues/${recentTaskPathRef(task)}`, label: task.title, icon: <StatusIcon {...taskStatusIconProps(task)} />, task });
}
for (const project of projects) {
const key = projectPinKey(project);
if (keys.has(key)) items.set(key, { key, to: `/projects/${projectRouteRef(project)}`, label: project.name, icon: <FolderOpen className="size-4" /> });
}
return pins.flatMap(key => {
const item = items.get(key);
return item ? [item] : [];
});
}
function ProjectRecent({ project }: { project: Project }) {
type PinControls = { keys: ReadonlySet<string>; canPin: boolean; toggle: (key: string) => void };
type RecentTaskLink = Omit<RecentTaskEntry, "recordedAt">;
function NavigationPinButton({ pinKey, label, pins, className }: { pinKey: string; label: string; pins: PinControls; className: string }) {
const pinned = pins.keys.has(pinKey);
const Icon = pinned ? PinOff : Pin;
const actionLabel = `${pinned ? "Unpin" : "Pin"} ${label}`;
return <button type="button" aria-label={actionLabel} title={actionLabel} aria-pressed={pinned} disabled={!pins.canPin}
onClick={() => pins.toggle(pinKey)} className={cn("absolute top-1/2 flex -translate-y-1/2 items-center justify-center rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring hover:text-foreground", pinned ? "text-foreground" : "text-muted-foreground", className)}>
<Icon aria-hidden className="size-3.5" />
</button>;
}
function RecentPinRow({ pinKey, label, pins, children }: { pinKey: string; label: string; pins: PinControls; children: ReactNode }) {
if (!pins.canPin) return <>{children}</>;
return <div className="design-sidebar-pin-target relative min-w-0">
{children}
<NavigationPinButton pinKey={pinKey} label={label} pins={pins} className="right-3 size-7" />
</div>;
}
function RecentTaskPinRow({ task, pins }: { task: RecentTaskLink; pins: PinControls }) {
return <RecentPinRow pinKey={taskPinKey(task.companyId, task.id)} label={task.title} pins={pins}>
<RecentTaskNavItem className="design-sidebar-item" task={task} label={task.title} iconNode={<StatusIcon {...taskStatusIconProps(task)} />} />
</RecentPinRow>;
}
function ProjectRecent({ project, pins }: { project: Project; pins: PinControls }) {
const [expanded, setExpanded] = useState(false);
const { data: tasks, isPending, error } = useQuery({
queryKey: [...queryKeys.issues.listByProject(project.companyId, project.id), "coordinator-recents"],
@@ -69,16 +115,19 @@ function ProjectRecent({ project }: { project: Project }) {
enabled: expanded,
});
return <div>
<div className="group/coordinator-recent relative">
<SidebarNavItem to={`/projects/${projectRouteRef(project)}`} label={project.name} icon={FolderOpen} className="design-sidebar-item pr-9" />
<div className="flex min-w-0 items-center">
<div className="min-w-0 flex-1">
<RecentPinRow pinKey={projectPinKey(project)} label={project.name} pins={pins}>
<SidebarNavItem to={`/projects/${projectRouteRef(project)}`} label={project.name} icon={FolderOpen} className="design-sidebar-item" />
</RecentPinRow>
</div>
<button type="button" aria-label={`${expanded ? "Collapse" : "Expand"} ${project.name}`} aria-expanded={expanded}
className="absolute right-3 top-1/2 -translate-y-1/2 rounded-md p-1 text-muted-foreground hover:bg-sidebar-accent focus-visible:ring-2 focus-visible:ring-ring" onClick={() => setExpanded(!expanded)}>
className="mr-2 flex size-6 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-sidebar-accent focus-visible:ring-2 focus-visible:ring-ring" onClick={() => setExpanded(!expanded)}>
<ChevronRight className={cn("size-3.5 transition-transform", expanded && "rotate-90")} />
</button>
</div>
{expanded && <div className="ml-5 border-l border-border pl-1">
{isPending ? <p className="px-3 py-2 text-xs text-muted-foreground" role="status">Loading tasks…</p> : error ? <p className="px-3 py-2 text-xs text-muted-foreground">Couldn’t load tasks.</p> : tasks?.length ? tasks.map(task =>
<RecentTaskNavItem className="design-sidebar-item" key={task.id} task={task} label={task.title} iconNode={<StatusIcon {...taskStatusIconProps(task)} />} />)
{isPending ? <p className="px-3 py-2 text-xs text-muted-foreground" role="status">Loading tasks…</p> : error ? <p className="px-3 py-2 text-xs text-muted-foreground">Couldn’t load tasks.</p> : tasks?.length ? tasks.map(task => <RecentTaskPinRow key={task.id} task={task} pins={pins} />)
: <p className="px-3 py-2 text-xs text-muted-foreground">No tasks yet.</p>}
</div>}
</div>;
@@ -113,6 +162,17 @@ export function CoordinatorSidebar({ children }: { children?: ReactNode }) {
const { companyId, userId, agents, chats, session } = useAgentChatNavigation();
const unreadChatCount = chats.data?.filter(chat => chat.isUnreadForMe).length ?? 0;
const pinnedNavigation = usePinnedNavigation(userId);
const pinKeys = useMemo(() => new Set(pinnedNavigation.pins), [pinnedNavigation.pins]);
const pins = { keys: pinKeys, canPin: pinnedNavigation.canPin, toggle: pinnedNavigation.toggle };
const pinnedTaskIds = useMemo(() => {
if (!companyId || !session.isSuccess) return [];
const prefix = taskPinKey(companyId, "");
return pinnedNavigation.pins.flatMap(key => {
if (!key.startsWith(prefix)) return [];
const id = key.slice(prefix.length);
return TASK_PIN_ID_PATTERN.test(id) ? [id] : [];
});
}, [companyId, pinnedNavigation.pins, session.isSuccess]);
const { data: experimental } = useQuery({
queryKey: queryKeys.instance.experimentalSettings,
queryFn: () => instanceSettingsApi.getExperimental(),
@@ -129,8 +189,7 @@ export function CoordinatorSidebar({ children }: { children?: ReactNode }) {
const [moreOpen, setMoreOpen] = useState(false);
const [recentsOpen, setRecentsOpen] = useState(true);
const moreContentRef = useRef<HTMLDivElement>(null);
const orderedPins = useMemo(() => buildPinnedNavigationItems(pinnedNavigation.pins, agents.data ?? [], destinations), [pinnedNavigation.pins, agents.data, destinations]);
const { entries: recentTasks } = useRecentTasks({ companyId, userId });
const { entries: recentTasks, pinnedTasks } = useRecentTasks({ companyId, userId, pinnedTaskIds });
const { isMobile, setSidebarOpen } = useSidebar();
// Warm opens only while the Recents list is on screen.
const location = useLocation();
@@ -139,6 +198,8 @@ export function CoordinatorSidebar({ children }: { children?: ReactNode }) {
const hierarchy = useMemo(() => recentTaskHierarchy(recentTasks, location.pathname), [recentTasks, location.pathname]);
const attentionCount = useCoordinatorAttentionCount(companyId);
const { data: projects } = useQuery({ ...companyProjectsQuery(companyId!), enabled: !!companyId });
const orderedPins = useMemo(() => buildPinnedNavigationItems(pinnedNavigation.pins, agents.data ?? [], destinations,
pinnedTasks, session.isSuccess ? projects : undefined), [pinnedNavigation.pins, agents.data, destinations, pinnedTasks, projects, session.isSuccess]);
// Only project IDs and visit times are kept in memory. Labels and task lists
// always come from the authorized API, scoped to the current person/company.
const scope = `${companyId}:${userId}`;
@@ -151,7 +212,7 @@ export function CoordinatorSidebar({ children }: { children?: ReactNode }) {
}, [location.pathname, projects, scope]);
const recents = useMemo(() => {
const roster = new Map((agents.data ?? []).map(agent => [agent.id, agent]));
const taskRows = recentTasks.filter(task => !hierarchy.nestedIds.has(task.id)).map(task => ({ kind: "task" as const, id: task.id, time: task.recordedAt, task }));
const taskRows = hierarchy.roots.map(task => ({ kind: "task" as const, id: task.id, time: hierarchy.latestVisitByRoot.get(task.id)!, task }));
const chatRows = (chats.data ?? []).flatMap(chat => {
const agent = chat.conversationAgentId ? roster.get(chat.conversationAgentId) : null;
return agent ? [{ kind: "chat" as const, id: chat.id, time: new Date(chat.updatedAt).getTime(), agent }] : [];
@@ -159,7 +220,7 @@ export function CoordinatorSidebar({ children }: { children?: ReactNode }) {
const projectRows = (projects ?? []).flatMap(project => projectVisits.scope === scope && projectVisits.entries[project.id]
? [{ kind: "project" as const, id: project.id, time: projectVisits.entries[project.id]!, project }] : []);
return [...taskRows, ...chatRows, ...projectRows].sort((a, b) => b.time - a.time);
}, [agents.data, chats.data, recentTasks, projects, projectVisits, scope, hierarchy]);
}, [agents.data, chats.data, projects, projectVisits, scope, hierarchy]);
const newTaskButton = <Button type="button" variant="ghost" className="design-sidebar-new-task rounded-lg" aria-label="New task" onClick={() => openNewIssue()}>
<SquarePen aria-hidden />
<span className="truncate">New task</span>
@@ -186,21 +247,15 @@ export function CoordinatorSidebar({ children }: { children?: ReactNode }) {
<Flyout open={moreOpen} onOpenChange={setMoreOpen}>
<FlyoutTrigger asChild><button type="button" aria-label="More workspace pages" className="design-sidebar-item flex w-auto items-center gap-2.5 rounded-lg py-1.5 text-left transition-colors focus-visible:ring-2 focus-visible:ring-ring"><MoreHorizontal className="size-4 shrink-0" /><span>More</span></button></FlyoutTrigger>
<FlyoutContent ref={moreContentRef} tabIndex={-1} onOpenAutoFocus={(event) => { event.preventDefault(); moreContentRef.current?.focus(); }} side={isMobile ? "bottom" : "right"} align="start" className="w-56 p-1" aria-label="More workspace pages">
{destinations.map(({ label, to, icon: Icon }, index) => {
const pinned = pinnedNavigation.pins.includes(to);
const PinIcon = pinned ? PinOff : Pin;
return <div key={to}>
{destinations.map(({ label, to, icon: Icon }, index) => <div key={to}>
{index === 6 || index === 10 ? <div role="separator" className="my-1 border-t border-border" /> : null}
<div className="group/coordinator-more relative flex items-center rounded-sm transition-colors hover:bg-accent">
<div className="group/navigation-pin relative flex items-center rounded-sm transition-colors hover:bg-accent">
<Link to={to} onClick={() => { setMoreOpen(false); if (isMobile) setSidebarOpen(false); }} className="flex min-w-0 flex-1 items-center gap-2 rounded-sm px-2 py-1.5 pr-10 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring">
<Icon className="size-4 shrink-0 text-muted-foreground" />{label}
</Link>
<button type="button" aria-label={`${pinned ? "Unpin" : "Pin"} ${label}`} aria-pressed={pinned} title={`${pinned ? "Unpin" : "Pin"} ${label}`} disabled={!pinnedNavigation.canPin} onClick={() => pinnedNavigation.toggle(to)} className={cn("absolute right-0.5 top-1/2 flex size-8 -translate-y-1/2 items-center justify-center rounded-sm opacity-0 transition-opacity outline-none group-hover/coordinator-more:opacity-100 focus-visible:opacity-100 pointer-coarse:opacity-100 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring", pinned ? "text-foreground" : "text-muted-foreground")}>
<PinIcon className="size-3.5" />
</button>
<NavigationPinButton pinKey={to} label={label} pins={pins} className="right-0.5 size-8 rounded-sm opacity-0 transition-opacity group-hover/navigation-pin:opacity-100 group-focus-within/navigation-pin:opacity-100 pointer-coarse:opacity-100" />
</div>
</div>;
})}
</div>)}
</FlyoutContent>
</Flyout>
</div>
@@ -209,12 +264,15 @@ export function CoordinatorSidebar({ children }: { children?: ReactNode }) {
<RecentNavigationList>
{recents.map(item => item.kind === "task"
? <RecentTaskGroup key={`${scope}:${item.id}`} task={item.task} userId={userId} className="design-sidebar-item" flattened={hierarchy.flattenedIds.has(item.id)}
selectedChild={hierarchy.selectedChild?.parentId === item.id ? hierarchy.selectedChild : undefined}>
<RecentTaskNavItem className="design-sidebar-item" task={item.task} label={item.task.title} iconNode={<StatusIcon {...taskStatusIconProps(item.task)} />} />
selectedChild={hierarchy.selectedChild?.parentId === item.id ? hierarchy.selectedChild : undefined}
renderChild={task => <RecentTaskPinRow task={task} pins={pins} />}>
<RecentTaskPinRow task={item.task} pins={pins} />
</RecentTaskGroup>
: item.kind === "chat"
? <SidebarNavItem className="design-sidebar-item" key={item.id} to={`/chats/${encodeURIComponent(agentRouteRef(item.agent))}`} label={item.agent.name} iconNode={<AgentAvatar agent={item.agent} size={16} />} />
: <ProjectRecent key={item.id} project={item.project} />)}
? <RecentPinRow key={item.id} pinKey={agentChatPinKey(item.agent.companyId, item.agent.id)} label={item.agent.name} pins={pins}>
<SidebarNavItem className="design-sidebar-item" to={`/chats/${encodeURIComponent(agentRouteRef(item.agent))}`} label={item.agent.name} iconNode={<AgentAvatar agent={item.agent} size={16} />} />
</RecentPinRow>
: <ProjectRecent key={`${scope}:${item.id}`} project={item.project} pins={pins} />)}
</RecentNavigationList>
</SidebarSection></div>}
{children}
+10 -2
View File
@@ -3,10 +3,17 @@ import { DndContext, KeyboardSensor, PointerSensor, closestCenter, useSensor, us
import { SortableContext, arrayMove, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { GripVertical, PinOff } from "lucide-react";
import { RecentTaskNavItem } from "./RecentTaskNavItem";
import { SidebarNavItem } from "./SidebarNavItem";
import { cn } from "@/lib/utils";
export interface PinnedNavigationItem { key: string; to: string; label: string; icon: ReactNode }
export interface PinnedNavigationItem {
key: string;
to: string;
label: string;
icon: ReactNode;
task?: { id: string; identifier: string | null; isUnreadForMe?: boolean };
}
/** Keep this row mounted when a pin is toggled so its controls retain focus. */
export function SortablePinnedRow({ id, label, disabled = false, className, handleClassName, handleIconClassName, children, ...props }: Omit<ComponentPropsWithoutRef<"div">, "id"> & {
@@ -26,9 +33,10 @@ export function SortablePinnedRow({ id, label, disabled = false, className, hand
}
function PinnedItem({ item, onUnpin }: { item: PinnedNavigationItem; onUnpin: (key: string) => void }) {
const link = { to: item.to, label: item.label, iconNode: item.icon, className: "design-sidebar-item design-sidebar-pinned-item group-hover/coordinator-pin:bg-sidebar-accent" };
return <SortablePinnedRow id={item.key} label={item.label} className="group/coordinator-pin relative"
handleClassName="right-3 size-7 group-hover/coordinator-pin:opacity-100 group-focus-within/coordinator-pin:opacity-100" handleIconClassName="size-3.5">
<SidebarNavItem to={item.to} label={item.label} iconNode={item.icon} className="design-sidebar-item group-hover/coordinator-pin:bg-sidebar-accent pr-16" />
{item.task ? <RecentTaskNavItem {...link} task={item.task} /> : <SidebarNavItem {...link} />}
<button type="button" aria-label={`Unpin ${item.label}`} title={`Unpin ${item.label}`}
onMouseDown={event => event.stopPropagation()} onClick={() => onUnpin(item.key)}
className="absolute right-10 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-sidebar-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring group-hover/coordinator-pin:opacity-100 group-focus-within/coordinator-pin:opacity-100 pointer-coarse:opacity-100"><PinOff className="size-3.5" /></button>
+1 -1
View File
@@ -305,7 +305,7 @@ function RecentTasksList({
return (
<>
<SidebarSection label="Recent Tasks">
{entries.filter(entry => !hierarchy.nestedIds.has(entry.id)).map((entry) => (
{hierarchy.roots.map((entry) => (
<RecentTaskGroup key={entry.id} task={entry} userId={userId} flattened={hierarchy.flattenedIds.has(entry.id)}
selectedChild={hierarchy.selectedChild?.parentId === entry.id ? hierarchy.selectedChild : undefined} renderChild={renderTaskRow}>
{renderTaskRow(entry)}
+34 -3
View File
@@ -35,12 +35,12 @@ describe("recent task synchronization", () => {
let clients: QueryClient[];
let renders: number;
function RecentTasks({ name, companyId = "company-1", userId = "user-1" }: { name: string; companyId?: string; userId?: string }) {
const { entries } = useRecentTasks({ companyId, userId });
function RecentTasks({ name, companyId = "company-1", userId = "user-1", pinnedTaskIds }: { name: string; companyId?: string; userId?: string; pinnedTaskIds?: string[] }) {
const { entries, pinnedTasks } = useRecentTasks({ companyId, userId, pinnedTaskIds });
renders += 1;
// Fail promptly if a regression restores the cross-cache render loop.
if (renders > 100) throw new Error("Recent Tasks did not settle");
return <div data-tab={name}>{entries.map((entry) => `${entry.title}:${entry.status}`).join(",")}</div>;
return <div data-tab={name} data-pins={pinnedTasks.map(task => task.title).join(",")}>{entries.map((entry) => `${entry.title}:${entry.status}`).join(",")}</div>;
}
function client(snapshot?: ReturnType<typeof task>) {
@@ -77,6 +77,37 @@ describe("recent task synchronization", () => {
vi.restoreAllMocks();
});
it("restores readable task pins independently of participation and drops tasks omitted by authorization", async () => {
const recent = task(10, "Recent task");
const pinned = { ...task(20, "Pinned task"), id: "pinned", isParticipantForMe: false };
const otherCompany = { ...task(20, "Other company"), id: "foreign", companyId: "company-2" };
recordRecentTask(recent, "user-1");
const pins = [pinned.id, otherCompany.id, "missing"];
const cache = client();
summaries.mockResolvedValue([recent, pinned, otherCompany]);
await act(async () => root.render(<QueryClientProvider client={cache}><RecentTasks name="pinned" pinnedTaskIds={pins} /></QueryClientProvider>));
await flush();
expect(summaries).toHaveBeenCalledTimes(1);
expect(summaries.mock.calls[0]?.[1]).toEqual(["foreign", "issue-1", "missing", "pinned"]);
expect(container.textContent).toBe("Recent task:todo");
const visiblePins = () => container.querySelector("[data-pins]")?.getAttribute("data-pins");
expect(visiblePins()).toBe("Pinned task");
expect(readRecentTasks(storageKey, "company-1").map(entry => entry.id)).toEqual([recent.id]);
summaries.mockResolvedValue([recent]);
await act(async () => { await cache.invalidateQueries({ queryKey: queryKeys.issues.summaries("company-1") }); });
await flush();
expect(visiblePins()).toBe("");
const revisited = { ...pinned, isParticipantForMe: true };
summaries.mockResolvedValue([recent, revisited]);
await act(async () => recordRecentTask(revisited, "user-1", 30));
await flush();
expect(summaries).toHaveBeenCalledTimes(3);
expect(visiblePins()).toBe("Pinned task");
expect(container.textContent).toBe("Pinned task:todo,Recent task:todo");
});
it("settles independent stale and fresh query caches and displays the newer snapshot in both", async () => {
const older = task(10, "Old title");
const newer = task(20, "New title", "done");
+16 -3
View File
@@ -1,6 +1,7 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { ISSUE_SUMMARIES_MAX_IDS, type Issue, type IssueSummary } from "@paperclipai/shared";
import { ApiError } from "@/api/client";
import { issuesApi } from "@/api/issues";
import { queryKeys } from "@/lib/queryKeys";
import {
@@ -20,15 +21,19 @@ type RecentTasksUpdatedDetail = {
};
const RECENT_TASK_ORDER_DEBOUNCE_MS = 1_000;
const NO_PINNED_TASK_IDS: readonly string[] = [];
const NO_PINNED_TASKS: readonly IssueSummary[] = [];
/** Summary chunks in flight at once for a history longer than one request. */
export const RECENT_TASK_SUMMARY_CONCURRENCY = 3;
export function useRecentTasks({
companyId,
userId,
pinnedTaskIds = NO_PINNED_TASK_IDS,
}: {
companyId: string | null | undefined;
userId: string | null | undefined;
pinnedTaskIds?: readonly string[];
}) {
const storageKey = useMemo(
() => companyId ? getRecentTasksStorageKey(companyId, userId) : null,
@@ -70,8 +75,9 @@ export function useRecentTasks({
};
}, [companyId, storageKey]);
const queryIds = useMemo(() => entries.map((entry) => entry.id).sort(), [entries]);
const scope = JSON.stringify([storageKey, queryIds]);
const recentIds = useMemo(() => entries.map((entry) => entry.id).sort(), [entries]);
const queryIds = useMemo(() => pinnedTaskIds.length ? [...new Set([...recentIds, ...pinnedTaskIds])].sort() : recentIds, [recentIds, pinnedTaskIds]);
const scope = JSON.stringify([storageKey, recentIds, queryIds]);
const summaryKey = queryKeys.issues.summaryBatch(companyId ?? "__none__", userId, queryIds);
// A cached omission predates IDs that the user has just added back. Only a
// response completed during this visit to the batch may remove those IDs.
@@ -124,6 +130,12 @@ export function useRecentTasks({
const confirmedRows = summaryQuery.data ?? (lastConfirmed?.storageKey === storageKey ? lastConfirmed.summaries : undefined);
const confirmed = useMemo(() => new Map((confirmedRows ?? []).filter((issue) => issue.companyId === companyId)
.map((issue) => [issue.id, issue])), [confirmedRows, companyId]);
const error = summaryQuery.error;
const denied = error instanceof ApiError && (error.status === 401 || error.status === 403);
const pinnedTasks = useMemo(() => denied || !pinnedTaskIds.length ? NO_PINNED_TASKS : pinnedTaskIds.flatMap((id) => {
const issue = confirmed.get(id);
return issue ? [issue] : [];
}), [confirmed, denied, pinnedTaskIds]);
// A visit is only a candidate. Neither imported provenance nor a persisted
// browser snapshot proves personal participation for the current account.
const refreshedEntries: RecentTaskEntry[] = useMemo(() => entries.filter(entry => confirmed.get(entry.id)?.isParticipantForMe === true).map((entry) => {
@@ -142,7 +154,7 @@ export function useRecentTasks({
// eligibility or ineligibility. Keep those candidates until a current read.
const returnedIds = new Set(summaries.filter((issue) => issue.companyId === companyId && issue.isParticipantForMe !== false).map((issue) => issue.id));
updateRecentTaskSnapshots(storageKey, companyId, summaries);
const omittedIds = new Set(queryIds.filter((id) => !returnedIds.has(id)));
const omittedIds = new Set(recentIds.filter((id) => !returnedIds.has(id)));
if (omittedIds.size && updateCount <= batchVisit.initialUpdateCount) {
void summaryQuery.refetch({ cancelRefetch: false });
return;
@@ -201,6 +213,7 @@ export function useRecentTasks({
return {
entries: orderedEntries,
pinnedTasks,
storageKey,
};
}
+7
View File
@@ -4832,7 +4832,14 @@ html:has(.design-proposal-theme) .design-navigation-group-label {
color: color-mix(in oklab, var(--muted-foreground) 60%, transparent);
}
.design-sidebar .design-sidebar-item { min-height: var(--design-sidebar-item-height); margin-inline: var(--design-sidebar-item-inset); padding-inline: var(--design-sidebar-item-inset); color: var(--design-sidebar-item-foreground); font-size: var(--design-sidebar-label-size); line-height: var(--design-sidebar-label-leading); }
.design-sidebar-pin-target > .design-sidebar-item { padding-inline-end: calc(var(--spacing) * 10); }
.design-sidebar .design-sidebar-pinned-item { padding-inline-end: calc(var(--spacing) * 16); }
.design-sidebar .design-sidebar-item:is(:hover, [aria-current="page"]) { background: var(--design-sidebar-item-highlight); color: var(--design-sidebar-item-active-foreground); }
.design-sidebar-pin-target > button { opacity: 0; pointer-events: none; }
.design-sidebar-pin-target:is(:hover, :has(> [aria-current="page"], > :focus-visible)) {
> .design-sidebar-item { background: var(--design-sidebar-item-highlight); color: var(--design-sidebar-item-active-foreground); }
> button { opacity: 1; pointer-events: auto; }
}
.design-sidebar-new-task { display: flex; justify-content: flex-start; width: calc(100% - var(--design-sidebar-item-inset) * 2); height: var(--design-sidebar-item-height); margin-inline: var(--design-sidebar-item-inset); padding-inline: var(--design-sidebar-item-inset); gap: calc(var(--spacing) * 2.5); font-size: var(--design-sidebar-label-size); line-height: var(--design-sidebar-label-leading); font-weight: var(--font-weight-medium); color: var(--design-sidebar-item-foreground); }
.design-sidebar-new-task svg { width: var(--design-page-icon-size); height: var(--design-page-icon-size); }
.design-sidebar-new-task:hover { background: var(--design-sidebar-item-highlight); color: var(--design-sidebar-item-active-foreground); }
+7 -1
View File
@@ -38,7 +38,13 @@ export function recentTaskHierarchy(entries: readonly RecentTaskEntry[], pathnam
}
}
const nestedIds = new Set(entries.filter(entry => nested.get(entry.id)).map(entry => entry.id));
const latestVisitByRoot = new Map<string, number>();
for (const entry of entries) {
const rootId = nestedIds.has(entry.id) ? parents.get(entry.id)! : entry.id;
latestVisitByRoot.set(rootId, Math.max(latestVisitByRoot.get(rootId) ?? -Infinity, entry.recordedAt));
}
const roots = [...latestVisitByRoot.keys()].map(id => byId.get(id)!);
const selectedRef = parseIssuePathIdFromPath(pathname);
const selected = entries.find(entry => entry.id === selectedRef || entry.identifier === selectedRef);
return { nestedIds, flattenedIds, selectedChild: selected && nestedIds.has(selected.id) ? selected : undefined };
return { roots, latestVisitByRoot, nestedIds, flattenedIds, selectedChild: selected && nestedIds.has(selected.id) ? selected : undefined };
}
+24 -33
View File
@@ -3145,7 +3145,7 @@ describe("IssueDetail", () => {
expect(mockSetPanelVisible).toHaveBeenCalledWith(true);
});
it("refreshes task snapshots without promoting background activity or passive revisits", async () => {
it.each(["first open", "reopen"])("moves the task to the top on %s and keeps snapshot refreshes from changing the order", async (visit) => {
const authRequest = createDeferred<{
session: { userId: string };
user: { id: string };
@@ -3155,6 +3155,10 @@ describe("IssueDetail", () => {
status: "todo",
updatedAt: new Date(100),
});
const storageKey = getRecentTasksStorageKey("company-1", "user-1");
const other = createIssue({ id: "other-task" });
if (visit === "reopen") recordRecentTask(issue, "user-1", 10);
recordRecentTask(other, "user-1", 20);
mockAuthApi.getSession.mockReturnValue(authRequest.promise);
mockIssuesApi.get.mockResolvedValue(issue);
@@ -3176,19 +3180,12 @@ describe("IssueDetail", () => {
});
await waitForAssertion(() => {
expect(
readRecentTasks(
getRecentTasksStorageKey("company-1", "user-1"),
"company-1",
),
).toEqual([
expect.objectContaining({
id: "issue-1",
title: "Initial recent title",
status: "todo",
recordedAt: 0,
}),
]);
readRecentTasks(storageKey, "company-1").map((task) => task.id),
).toEqual([issue.id, other.id]);
});
const openedAt = readRecentTasks(storageKey, "company-1")[0]!.recordedAt;
expect(openedAt).toBeGreaterThan(20);
await act(async () => recordRecentTask(other, "user-1", openedAt + 1));
act(() => {
queryClient.setQueryData(queryKeys.issues.detail("PAP-1"), {
@@ -3200,21 +3197,14 @@ describe("IssueDetail", () => {
});
await flushReact();
expect(
readRecentTasks(
getRecentTasksStorageKey("company-1", "user-1"),
"company-1",
)[0],
).toMatchObject({
title: "Snapshot refresh title",
status: "in_progress",
recordedAt: 0,
});
expect(readRecentTasks(storageKey, "company-1")).toMatchObject([
{ id: other.id },
{ id: issue.id, title: "Snapshot refresh title", status: "in_progress", recordedAt: openedAt },
]);
});
it.each(["reassignment", "run settings"])("advances recency only after a comment with %s saves", async (mode) => {
const issue = createIssue({ updatedAt: new Date(10) });
const comment = createIssueComment({ createdAt: new Date(30) });
const save = createDeferred<Issue & { comment: IssueComment }>();
mockAuthApi.getSession.mockResolvedValue({ user: { id: "user-1" } });
mockAgentsApi.list.mockResolvedValue([createAgent()]);
@@ -3225,6 +3215,11 @@ describe("IssueDetail", () => {
recordRecentTask(createIssue({ id: "newer-work" }), "user-1", 20);
await act(async () => renderIssueView());
await waitForAssertion(() => expect(mockIssueChatThreadRender).toHaveBeenCalled());
const entries = () => readRecentTasks(getRecentTasksStorageKey("company-1", "user-1"), "company-1");
await waitForAssertion(() => expect(entries()[0]?.id).toBe(issue.id));
const openedAt = entries()[0]!.recordedAt;
recordRecentTask(createIssue({ id: "newer-work" }), "user-1", openedAt + 1);
const comment = createIssueComment({ createdAt: new Date(openedAt + 2) });
const props = mockIssueChatThreadRender.mock.calls.at(-1)![0];
let pending!: Promise<void>;
await act(async () => {
@@ -3234,14 +3229,13 @@ describe("IssueDetail", () => {
mode === "run settings" ? { model: "gpt-6-astra", effort: "high", fast: false } : undefined);
});
await waitForAssertion(() => expect(mockIssuesApi.update).toHaveBeenCalled());
const entries = () => readRecentTasks(getRecentTasksStorageKey("company-1", "user-1"), "company-1");
expect(entries().map(entry => entry.id)).toEqual(["newer-work", issue.id]);
await act(async () => {
save.resolve({ ...issue, updatedAt: new Date(15), comment });
await pending;
});
expect(entries().map(entry => entry.id)).toEqual([issue.id, "newer-work"]);
expect(entries()[0]?.recordedAt).toBe(30);
expect(entries()[0]?.recordedAt).toBe(openedAt + 2);
});
it.each([false, true])("renders a linked Decisions-v1 record in task context (Coordinator %s)", async (enabled) => {
@@ -5906,7 +5900,9 @@ describe("IssueDetail", () => {
expect(optimisticComment).toMatchObject({ clientStatus: "pending" });
expect(optimisticComment?.queueState).toBeUndefined();
const postedAt = new Date("2026-04-21T00:00:10.000Z");
const storageKey = getRecentTasksStorageKey("company-1", null);
const openedAt = readRecentTasks(storageKey, "company-1")[0]!.recordedAt;
const postedAt = new Date(openedAt + 10_000);
await act(async () => {
postedComment.resolve(
createIssueComment({
@@ -5918,12 +5914,7 @@ describe("IssueDetail", () => {
});
await flushReact();
expect(
readRecentTasks(
getRecentTasksStorageKey("company-1", null),
"company-1",
)[0],
).toMatchObject({
expect(readRecentTasks(storageKey, "company-1")[0]).toMatchObject({
id: "issue-1",
recordedAt: postedAt.getTime(),
});
+7 -5
View File
@@ -3841,12 +3841,14 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
enabled: !!selectedCompanyId,
});
const currentUserId = session?.user?.id ?? session?.session?.userId ?? null;
const recentTaskVisit = useRef<string | null>(null);
useEffect(() => {
if (!streamlinedUiEnabled || !issue || !sessionResolved) return;
// Passive reads refresh the snapshot without promoting it. The navigation
// summary still decides whether this candidate is personal work.
recordRecentTask(issue, currentUserId);
}, [issue, currentUserId, sessionResolved, streamlinedUiEnabled]);
if (!(streamlinedUiEnabled || coordinatorWorkspaceEnabled) || !loadedIssue || !sessionResolved
|| conversation || loadedIssue.conversationAgentId || loadedIssue.hiddenAt) return;
const visit = `${loadedIssue.companyId}:${currentUserId}:${loadedIssue.id}`;
recordRecentTask(loadedIssue, currentUserId, recentTaskVisit.current === visit ? undefined : Date.now());
recentTaskVisit.current = visit;
}, [loadedIssue, currentUserId, sessionResolved, streamlinedUiEnabled, coordinatorWorkspaceEnabled, conversation]);
const { data: boardAccess } = useQuery({
queryKey: queryKeys.access.currentBoardAccess,
queryFn: () => accessApi.getCurrentBoardAccess(),