diff --git a/doc/PRODUCT.md b/doc/PRODUCT.md index 3aa84fa6289..22da38a8c85 100644 --- a/doc/PRODUCT.md +++ b/doc/PRODUCT.md @@ -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. diff --git a/ui/src/components/CoordinatorSidebar.test.tsx b/ui/src/components/CoordinatorSidebar.test.tsx index 3442e2f2584..65b5853f898 100644 --- a/ui/src/components/CoordinatorSidebar.test.tsx +++ b/ui/src/components/CoordinatorSidebar.test.tsx @@ -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>, projects: [] as Array>, 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>, taskSummaries: [] as Array>, projects: [] as Array>, 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(`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(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]; diff --git a/ui/src/components/CoordinatorSidebar.tsx b/ui/src/components/CoordinatorSidebar.tsx index 6db41611d71..4154bc81249 100644 --- a/ui/src/components/CoordinatorSidebar.tsx +++ b/ui/src/components/CoordinatorSidebar.tsx @@ -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(destinations.map(item => [item.to, { key: item.to, to: item.to, label: item.label, icon: }])); 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: }); } + 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: , 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: }); + } return pins.flatMap(key => { const item = items.get(key); return item ? [item] : []; }); } -function ProjectRecent({ project }: { project: Project }) { +type PinControls = { keys: ReadonlySet; canPin: boolean; toggle: (key: string) => void }; +type RecentTaskLink = Omit; + +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 ; +} + +function RecentPinRow({ pinKey, label, pins, children }: { pinKey: string; label: string; pins: PinControls; children: ReactNode }) { + if (!pins.canPin) return <>{children}; + return
+ {children} + +
; +} + +function RecentTaskPinRow({ task, pins }: { task: RecentTaskLink; pins: PinControls }) { + return + } /> + ; +} + +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
-
- +
+
+ + + +
{expanded &&
- {isPending ?

Loading tasks…

: error ?

Couldn’t load tasks.

: tasks?.length ? tasks.map(task => - } />) + {isPending ?

Loading tasks…

: error ?

Couldn’t load tasks.

: tasks?.length ? tasks.map(task => ) :

No tasks yet.

}
}
; @@ -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(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 = { 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
+ {destinations.map(({ label, to, icon: Icon }, index) =>
{index === 6 || index === 10 ?
: null} -
+
{ 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"> {label} - +
-
; - })} +
)}
@@ -209,12 +264,15 @@ export function CoordinatorSidebar({ children }: { children?: ReactNode }) { {recents.map(item => item.kind === "task" ? - } /> + selectedChild={hierarchy.selectedChild?.parentId === item.id ? hierarchy.selectedChild : undefined} + renderChild={task => }> + : item.kind === "chat" - ? } /> - : )} + ? + } /> + + : )}
} {children} diff --git a/ui/src/components/PinnedNavigationList.tsx b/ui/src/components/PinnedNavigationList.tsx index edcccb18095..eb3a946c516 100644 --- a/ui/src/components/PinnedNavigationList.tsx +++ b/ui/src/components/PinnedNavigationList.tsx @@ -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, "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 - + {item.task ? : } diff --git a/ui/src/components/SidebarRecentTasks.tsx b/ui/src/components/SidebarRecentTasks.tsx index 4d2fbd787c8..53dd8749fb7 100644 --- a/ui/src/components/SidebarRecentTasks.tsx +++ b/ui/src/components/SidebarRecentTasks.tsx @@ -305,7 +305,7 @@ function RecentTasksList({ return ( <> - {entries.filter(entry => !hierarchy.nestedIds.has(entry.id)).map((entry) => ( + {hierarchy.roots.map((entry) => ( {renderTaskRow(entry)} diff --git a/ui/src/hooks/useRecentTasks.test.tsx b/ui/src/hooks/useRecentTasks.test.tsx index e1090f3ba44..215b8eadf68 100644 --- a/ui/src/hooks/useRecentTasks.test.tsx +++ b/ui/src/hooks/useRecentTasks.test.tsx @@ -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
{entries.map((entry) => `${entry.title}:${entry.status}`).join(",")}
; + return
task.title).join(",")}>{entries.map((entry) => `${entry.title}:${entry.status}`).join(",")}
; } function client(snapshot?: ReturnType) { @@ -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()); + 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"); diff --git a/ui/src/hooks/useRecentTasks.ts b/ui/src/hooks/useRecentTasks.ts index 75746c0e35f..7541a35dddc 100644 --- a/ui/src/hooks/useRecentTasks.ts +++ b/ui/src/hooks/useRecentTasks.ts @@ -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, }; } diff --git a/ui/src/index.css b/ui/src/index.css index 0e336eaf6b1..4ab91420307 100644 --- a/ui/src/index.css +++ b/ui/src/index.css @@ -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); } diff --git a/ui/src/lib/recent-task-hierarchy.ts b/ui/src/lib/recent-task-hierarchy.ts index caf1f2772ca..a91a2c9cc85 100644 --- a/ui/src/lib/recent-task-hierarchy.ts +++ b/ui/src/lib/recent-task-hierarchy.ts @@ -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(); + 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 }; } diff --git a/ui/src/pages/IssueDetail.test.tsx b/ui/src/pages/IssueDetail.test.tsx index 7b2091a5347..ead620552b5 100644 --- a/ui/src/pages/IssueDetail.test.tsx +++ b/ui/src/pages/IssueDetail.test.tsx @@ -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(); 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; 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(), }); diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx index 061aa6e1ce2..efced31ccf5 100644 --- a/ui/src/pages/IssueDetail.tsx +++ b/ui/src/pages/IssueDetail.tsx @@ -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(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(),