diff --git a/doc/PRODUCT.md b/doc/PRODUCT.md index 2151f7b70e4..0f29aab3481 100644 --- a/doc/PRODUCT.md +++ b/doc/PRODUCT.md @@ -98,27 +98,17 @@ 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 and Classic Recent Tasks show tasks from the viewer’s own +recent activity as a flat list. A subtask has its own row and its own unread +marker. Tasks archived from the viewer’s inbox leave Recents. Canceled and +completed tasks remain eligible. Opening a recent task moves its row to the top +of Recents. -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. -A selected child beyond the first ten replaces the last preview row. -Children already in recent history appear once under their recent root parent. -Orphans remain in the main list. Standard Recents and Classic Recent Tasks use -the same groups; Classic keeps its existing parent action menus. Child reads stop -when a group leaves the viewport. At most three child requests run together. -Show less discards extra cached pages, so the next refresh reads one preview. -Live updates refresh the affected child groups and recent summary batches; -permission changes clear cached children before refetching. - -Unread stays personal to each task. Folding, loading children, and Show more do -not mark tasks read. A folded group shows its readable unread-child count, -including children beyond ten, separately from the parent's own unread marker. +Standard Recents also shows recent chats and projects as individual links. +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. Agent-owned tasks show **In Progress** only while a task-linked run is queued or running. When execution ends, their visible status reflects recovery diff --git a/packages/shared/src/types/issue.ts b/packages/shared/src/types/issue.ts index e22382a6018..2ef360b54e5 100644 --- a/packages/shared/src/types/issue.ts +++ b/packages/shared/src/types/issue.ts @@ -913,6 +913,7 @@ export type IssueSummary = Pick< parentId?: string | null; /** Viewer participates under the Mine rule, regardless of inbox archive state. Navigation only. */ isParticipantForMe?: boolean; + isArchivedForMe?: boolean; isUnreadForMe?: boolean; subtaskCount?: number; unreadSubtaskCount?: number; diff --git a/server/src/__tests__/issue-summaries-routes.test.ts b/server/src/__tests__/issue-summaries-routes.test.ts index f5e0ab59e8a..8ad69ea7348 100644 --- a/server/src/__tests__/issue-summaries-routes.test.ts +++ b/server/src/__tests__/issue-summaries-routes.test.ts @@ -44,14 +44,15 @@ describeEmbeddedPostgres("bounded issue summaries", () => { } const url = (companyId: string) => `/api/companies/${companyId}/issues/summaries`; - it("qualifies recents by personal participation rather than automated provenance, reads or inbox archive", async () => { + it("reports personal participation and archive state for navigation", async () => { const f = await fixture(); const user = f.actor.userId!; - const names = ["manual", "routine", "github", "agent", "read", "comment", "edit", "assigned", "addressed", "other-request", "archived"]; + const names = ["manual", "routine", "github", "agent", "read", "comment", "edit", "assigned", "addressed", "other-request", "archived", "archived-by-other", "cancelled"]; const rows = await ctx.db.insert(issues).values(names.map(title => ({ companyId: f.companyId, title, originKind: title === "routine" ? "routine_execution" : title === "github" ? "chat_channel" : "manual", - createdByUserId: ["manual", "routine", "github", "archived"].includes(title) ? user : null, + createdByUserId: ["manual", "routine", "github", "archived", "archived-by-other", "cancelled"].includes(title) ? user : null, + status: title === "cancelled" ? "cancelled" : "todo", responsibleUserId: user, assigneeUserId: title === "assigned" ? user : null, }))).returning(); @@ -65,7 +66,10 @@ describeEmbeddedPostgres("bounded issue summaries", () => { { companyId: f.companyId, entityType: "issue", entityId: id("edit"), actorType: "user", actorId: user, action: "issue.updated" }, { companyId: f.companyId, entityType: "issue", entityId: id("agent"), actorType: "agent", actorId: "worker", action: "issue.updated", responsibleUserId: user }, ]); - await ctx.db.insert(issueInboxArchives).values({ companyId: f.companyId, issueId: id("archived"), userId: user }); + await ctx.db.insert(issueInboxArchives).values([ + { companyId: f.companyId, issueId: id("archived"), userId: user }, + { companyId: f.companyId, issueId: id("archived-by-other"), userId: "other" }, + ]); await ctx.db.insert(issueThreadInteractions).values(["addressed", "other-request"].map(title => ({ companyId: f.companyId, issueId: id(title), kind: "request_confirmation", status: "pending", addresseeUserId: title === "addressed" ? user : "other", effectiveResolverPolicy: "human_only" as const, @@ -73,7 +77,12 @@ describeEmbeddedPostgres("bounded issue summaries", () => { }))); const res = await request(app(f.actor)).get(url(f.companyId)).query({ ids: rows.map(row => row.id).join(","), navigation: "true" }).expect(200); expect(res.body.filter((row: { isParticipantForMe: boolean }) => row.isParticipantForMe).map((row: { title: string }) => row.title).sort()) - .toEqual(["addressed", "archived", "assigned", "comment", "edit", "manual"]); + .toEqual(["addressed", "archived", "archived-by-other", "assigned", "cancelled", "comment", "edit", "manual"]); + expect(res.body.filter((row: { isArchivedForMe: boolean }) => row.isArchivedForMe).map((row: { title: string }) => row.title)).toEqual(["archived"]); + expect(res.body).toContainEqual(expect.objectContaining({ id: id("cancelled"), status: "cancelled", isArchivedForMe: false })); + const general = await request(app(f.actor)).get(url(f.companyId)).query({ ids: [id("archived"), id("cancelled")].join(",") }).expect(200); + expect(general.body.map((row: { title: string }) => row.title)).toEqual(["archived", "cancelled"]); + expect(general.body[0]).not.toHaveProperty("isArchivedForMe"); expect(res.body.every((row: { isParticipantForMe: unknown }) => typeof row.isParticipantForMe === "boolean")).toBe(true); }); diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index 190b466b397..adb9810f31e 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -4509,10 +4509,13 @@ registry.registerPath({ path: "/api/companies/{companyId}/issues/summaries", tags: ["issues"], summary: "Get authorized recent-task summaries", - description: "Accepts only the ids query parameter: one to fifty comma-separated UUIDs, bounded before deduplication. IDs are trimmed and normalized to lowercase. Repeated, array and nested query syntax is rejected, including mixed forms. Returns accessible, visible tasks in request order; unavailable IDs are omitted. This private, no-store read excludes full task and workspace enrichment.", + description: "Accepts one to fifty comma-separated UUIDs, bounded before deduplication. IDs are trimmed and normalized to lowercase. Repeated, array and nested query syntax is rejected, including mixed forms. Returns accessible, visible tasks in request order; unavailable IDs are omitted. With navigation=true, board viewers receive personal navigation state, including whether each task is archived for them. This private, no-store read excludes full task and workspace enrichment.", request: { params: z.object({ companyId: z.string() }), - query: z.object({ ids: z.string().min(1).describe("One to fifty comma-separated task UUIDs; repeated query parameters are rejected") }), + query: z.object({ + ids: z.string().min(1).describe("One to fifty comma-separated task UUIDs. Repeated query parameters are rejected."), + navigation: z.literal("true").optional(), + }), }, responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden }, }); diff --git a/server/src/services/issue-summaries.ts b/server/src/services/issue-summaries.ts index c098ea0d3dd..be1b9150d82 100644 --- a/server/src/services/issue-summaries.ts +++ b/server/src/services/issue-summaries.ts @@ -3,7 +3,7 @@ import { and, eq, inArray, isNull, sql, type SQL } from "drizzle-orm"; import { activityLog, issueComments, issueReadStates, issueThreadInteractions, issues, type Db } from "@paperclipai/db"; import { ISSUE_SUMMARIES_MAX_IDS } from "@paperclipai/shared"; import { directHumanCommentCondition } from "./issue-participation.js"; -import { mineParticipationIssueIds, unreadForUserCondition } from "./issues.js"; +import { inboxVisibleForUserCondition, mineParticipationIssueIds, unreadForUserCondition } from "./issues.js"; import { externalConversationStateSql } from "./slack-conversation-state.js"; /** A bounded projection with the columns needed by task-read authorization. */ @@ -62,10 +62,11 @@ export async function listIssueNavigationState( // MATERIALIZED prevents PostgreSQL from repeating privacy and viewer facts // across the task-state and child-count branches of the final union. const rows = await db.execute<{ - kind: string; id: string; unread: boolean; participant: boolean; total: number; unread_count: number; + kind: string; id: string; unread: boolean; participant: boolean; archived: boolean; total: number; unread_count: number; }>(sql` with navigation_candidates as materialized ( - select ${issues.id}, ${issues.parentId}, ${issues.conversationAgentId} + select ${issues.id}, ${issues.parentId}, ${issues.conversationAgentId}, + case when ${issues.id} in (${requested}) then not (${inboxVisibleForUserCondition(companyId, userId)}) else false end as archived from ${issues} where ${issues.companyId} = ${companyId} and ${issues.hiddenAt} is null and (${issues.id} in (${requested}) or @@ -122,11 +123,11 @@ export async function listIssueNavigationState( select issues.id, issues.parent_id, issues.conversation_agent_id, coalesce(${unread}, false) as unread from navigation_facts as issues ) - select 'task' as kind, c.id, coalesce(s.unread, false) as unread, p.id is not null as participant, 0 as total, 0 as unread_count + select 'task' as kind, c.id, coalesce(s.unread, false) as unread, p.id is not null as participant, c.archived, 0 as total, 0 as unread_count from navigation_candidates c left join navigation_state s on s.id = c.id left join navigation_participants p on p.id = c.id where c.id in (${requested}) union all - select 'children', c.parent_id, false, false, count(*)::int, count(*) filter (where s.unread)::int + select 'children', c.parent_id, false, false, false, count(*)::int, count(*) filter (where s.unread)::int from navigation_candidates c left join navigation_state s on s.id = c.id where c.parent_id in (${requested}) and c.conversation_agent_id is null group by c.parent_id `); @@ -135,6 +136,7 @@ export async function listIssueNavigationState( return new Map(ids.map(id => [id, { isParticipantForMe: tasks.get(id)?.participant ?? false, isUnreadForMe: tasks.get(id)?.unread ?? false, + isArchivedForMe: tasks.get(id)?.archived ?? false, subtaskCount: children.get(id)?.total ?? 0, unreadSubtaskCount: children.get(id)?.unread_count ?? 0, }])); diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index 9e1f65510af..33bac37fbad 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -3128,7 +3128,7 @@ function withdrawnForUserCondition(companyId: string, userId: string, readAt: SQ )`; } -function inboxVisibleForUserCondition(companyId: string, userId: string) { +export function inboxVisibleForUserCondition(companyId: string, userId: string) { return sql` NOT EXISTS ( SELECT 1 diff --git a/tests/e2e/completed-task-paused-assignee.spec.ts b/tests/e2e/completed-task-paused-assignee.spec.ts index 2400ccb43c0..13aee62864f 100644 --- a/tests/e2e/completed-task-paused-assignee.spec.ts +++ b/tests/e2e/completed-task-paused-assignee.spec.ts @@ -81,11 +81,12 @@ for (const classic of [false, true]) { await testInfo.attach(name, { path, contentType: "image/png" }); }; const observe = async (status: string, warningVisible: boolean) => { - await expect(page.getByText(task.title, { exact: true }).first()).toBeVisible(); + const header = page.getByTestId("issue-detail-header"); + await expect(header.getByRole("heading", { name: task.title, exact: true })).toBeVisible(); const showProperties = page.getByRole("button", { name: "Show properties", exact: true }); if (await showProperties.isVisible()) await showProperties.click(); const statusLabel = status[0].toUpperCase() + status.slice(1); - await expect(page.getByTestId("issue-detail-header").getByRole("button", { + await expect(header.getByRole("button", { name: status === "blocked" ? /^Change status \(current: Blocked(?: · [^)]*)?\)$/ : `Change status (current: ${statusLabel})`, diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index c2f21a2a489..ea73f0bf83d 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -430,7 +430,7 @@ "packages/shared/src/types/index.ts": "4a489d81995adbb8e485cf7283e23fca4b8f3ff3", "packages/shared/src/types/instance.ts": "77b0052be0f64a5531c5ebf0fd078c9854084479", "packages/shared/src/types/issue-tree-control.ts": "75489fffd491b8350b05caf57d7796419797d9df", - "packages/shared/src/types/issue.ts": "e22382a60188594d17c0fa7c7c717a7612e68626", + "packages/shared/src/types/issue.ts": "2ef360b54e5e44a1c516935ab93e9029526abb40", "packages/shared/src/types/live.ts": "b90e55e4de8600c6fc17d7fa8d89079d4ae655ec", "packages/shared/src/types/native-finalization.ts": "c026a73003ae232fea4f7624d561493b383df358", "packages/shared/src/types/plugin.ts": "af85e6aa845c2ef6956d0151ff11332947bf3949", diff --git a/tests/storybook-visual/recent-subtasks.spec.ts b/tests/storybook-visual/recent-subtasks.spec.ts index 84ffb394a42..c5aacc86861 100644 --- a/tests/storybook-visual/recent-subtasks.spec.ts +++ b/tests/storybook-visual/recent-subtasks.spec.ts @@ -1,16 +1,16 @@ import { expect, test, type Page } from "@playwright/test"; -const states = ["expanded", "collapsed", "exactly-ten", "more-than-ten", "all-subtasks", "selected-subtask", "selected-beyond-ten", "mixed-statuses", "independent-groups", "long-titles", "narrow", "no-subtasks", "empty-recents", "loading", "load-failed", "no-children-available", "keyboard-focus", "section-collapsed", "parent-unread-children-read", "classic"]; +const states = ["expanded", "selected-subtask", "long-titles", "narrow", "empty-recents", "keyboard-focus", "section-collapsed", "classic"]; async function open(page: Page, state: string, theme = "dark") { await page.goto(`/iframe.html?id=design-recent-subtasks--${state}&viewMode=story&globals=theme:${theme}`); await expect.poll(() => page.evaluate(() => (window as unknown as { __STORYBOOK_ADDONS_CHANNEL__?: { data: Record> }; }).__STORYBOOK_ADDONS_CHANNEL__?.data.storyFinished?.[0]?.status), { timeout: 60_000 }).toBeDefined(); const outcome = await page.evaluate(() => { - const result = (window as unknown as { __STORYBOOK_ADDONS_CHANNEL__?: { data: { storyFinished?: Array<{ status: string; reporters?: Array<{ result?: { violations?: Array<{ id: string; nodes: Array<{ target: string[] }> }> } }> }> } } }).__STORYBOOK_ADDONS_CHANNEL__?.data.storyFinished?.[0]; - return { status: result?.status, violations: result?.reporters?.flatMap(reporter => reporter.result?.violations?.map(violation => ({ id: violation.id, targets: violation.nodes.map(node => node.target) })) ?? []) }; + const result = (window as unknown as { __STORYBOOK_ADDONS_CHANNEL__?: { data: { storyFinished?: Array<{ status: string }> } } }).__STORYBOOK_ADDONS_CHANNEL__?.data.storyFinished?.[0]; + return result?.status; }); - expect(outcome).toMatchObject({ status: "success" }); + expect(outcome).toBe("success"); } for (const theme of ["light", "dark"]) { @@ -18,90 +18,28 @@ for (const theme of ["light", "dark"]) { const errors: string[] = []; page.on("pageerror", error => errors.push(error.message)); await open(page, state, theme); - if (!["collapsed", "empty-recents", "no-subtasks", "section-collapsed", "loading", "load-failed", "no-children-available", "independent-groups"].includes(state)) { - const children = page.getByRole("group", { name: "Subtasks of Ship the project workspace", exact: true }); - if (state !== "long-titles") await expect(children.getByRole("link")).toHaveCount(state === "all-subtasks" ? 14 : ["exactly-ten", "more-than-ten", "selected-beyond-ten"].includes(state) ? 10 : 3); - } - if (state === "selected-beyond-ten") await expect(page.getByRole("link", { name: /Subtask 12/ })).toHaveAttribute("aria-current", "page"); - if (state === "more-than-ten") await expect(page.getByRole("button", { name: "Show more (4) · 4 unread" })).toBeVisible(); - if (state === "collapsed") await expect(page.getByRole("button", { name: "3 subtasks · 2 unread", exact: true })).toBeVisible(); - if (state === "parent-unread-children-read") { - await expect(page.getByRole("link", { name: /Ship the project workspace/ }).getByLabel("Unread")).toHaveCount(1); - await expect(page.getByRole("group", { name: "Subtasks of Ship the project workspace" }).getByLabel("Unread")).toHaveCount(0); - } - if (state === "narrow" || state === "all-subtasks") { - const overflow = await page.locator(".design-sidebar-recent-list").evaluate(element => ({ width: element.clientWidth, scrollWidth: element.scrollWidth, height: element.clientHeight, scrollHeight: element.scrollHeight })); - expect(overflow.scrollWidth).toBeLessThanOrEqual(overflow.width); - if (state === "all-subtasks") expect(overflow.scrollHeight).toBeGreaterThan(overflow.height); + + if (state === "expanded" || state === "narrow") { + const recents = page.getByRole("region", { name: "Recents", exact: true }); + const links = await recents.getByRole("link").all(); + expect(links).toHaveLength(4); + const rows = await Promise.all(links.map(link => link.boundingBox())); + expect(rows.every(row => row?.x === rows[0]?.x)).toBe(true); + const overflow = await recents.evaluate(element => element.scrollWidth - element.clientWidth); + expect(overflow).toBeLessThanOrEqual(0); } + expect(errors).toEqual([]); await page.locator(".coordinator-workspace").screenshot({ path: testInfo.outputPath(`${state}-${theme}.png`), animations: "disabled" }); }); } -test("fold, keyboard, overflow and parent navigation preserve personal unread state", async ({ page }) => { - await open(page, "more-than-ten"); - const group = page.getByRole("group", { name: "Subtasks of Ship the project workspace" }); - const parent = page.getByRole("link", { name: /Ship the project workspace/ }); - await expect(parent).toHaveCount(1); - await expect(parent.getByLabel("Unread")).toHaveCount(0); - const url = page.url(); - const collapse = page.getByRole("button", { name: "Collapse subtasks of Ship the project workspace", exact: true }); - await collapse.focus(); - await collapse.press("Enter"); - await expect(page.getByRole("button", { name: "14 subtasks · 13 unread", exact: true })).toBeVisible(); - expect(page.url()).toBe(url); - await page.getByRole("button", { name: "Expand subtasks of Ship the project workspace", exact: true }).press("Space"); - await expect(group.getByRole("link")).toHaveCount(10); - await page.getByRole("button", { name: /Show more/ }).click(); - await expect(group.getByRole("link")).toHaveCount(14); - await expect(group.getByLabel("Unread")).toHaveCount(13); - await page.getByRole("button", { name: "Show less", exact: true }).click(); - await expect(group.getByRole("link")).toHaveCount(10); - await expect(page.getByRole("button", { name: "Show more (4) · 4 unread" })).toBeVisible(); - await expect(parent).toHaveAttribute("href", "/PAP/issues/PAP-100"); - await parent.click(); - await expect(group.getByLabel("Unread")).toHaveCount(9); -}); - -for (const theme of ["light", "dark"]) test(`parent status icons align with leaves and the child guide, with the fold control on the right in ${theme}`, async ({ page }) => { - for (const state of ["expanded", "collapsed", "narrow", "parent-unread-children-read"]) { - await open(page, state, theme); - const parent = page.getByRole("link", { name: /Ship the project workspace/ }); - const leaf = page.getByRole("link", { name: /Review the company dashboard/ }); - const parentIcon = await parent.locator('[data-slot="sidebar-nav-icon"]').boundingBox(); - const leafIcon = await leaf.locator('[data-slot="sidebar-nav-icon"]').boundingBox(); - const parentBounds = await parent.boundingBox(); - const fold = await page.getByRole("button", { name: /^(Collapse|Expand) subtasks of Ship/ }).boundingBox(); - expect(parentIcon).not.toBeNull(); - expect(leafIcon).not.toBeNull(); - expect(Math.abs(parentIcon!.x - leafIcon!.x)).toBeLessThanOrEqual(0.5); - expect(fold!.x).toBeGreaterThanOrEqual(parentBounds!.x + parentBounds!.width); - if (state !== "collapsed") { - const guide = await page.getByRole("group", { name: "Subtasks of Ship the project workspace", exact: true }).boundingBox(); - expect(Math.abs(guide!.x + 0.5 - (parentIcon!.x + parentIcon!.width / 2))).toBeLessThanOrEqual(0.5); - } - } -}); - -test("Classic parent actions remain separate from the right fold control", async ({ page }) => { +test("Classic keeps recent task actions on flat rows", async ({ page }) => { await open(page, "classic"); - const parent = page.getByRole("link", { name: /Ship the project workspace/ }); - const leaf = page.getByRole("link", { name: /Review the company dashboard/ }); - expect((await parent.boundingBox())!.x).toBe((await leaf.boundingBox())!.x); - const fold = page.getByRole("button", { name: "Collapse subtasks of Ship the project workspace", exact: true }); - const menu = page.getByRole("button", { name: "More actions for Ship the project workspace", exact: true }); - await parent.hover(); - await expect(menu).toBeVisible(); - const menuBounds = (await menu.boundingBox())!; - const foldBounds = (await fold.boundingBox())!; - expect(menuBounds.x + menuBounds.width).toBeLessThanOrEqual(foldBounds.x); - const url = page.url(); - await menu.click(); - await expect(page.getByRole("menuitem", { name: "Rename", exact: true })).toBeVisible(); - await page.keyboard.press("Escape"); - await expect(fold).toHaveAttribute("aria-expanded", "true"); - await fold.click(); - await expect(page.getByRole("button", { name: "Expand subtasks of Ship the project workspace", exact: true })).toHaveAttribute("aria-expanded", "false"); - expect(page.url()).toBe(url); + const child = page.getByRole("link", { name: "Verify the saved workspace" }); + const parent = page.getByRole("link", { name: "Ship the project workspace" }); + expect((await child.boundingBox())!.x).toBe((await parent.boundingBox())!.x); + await child.hover(); + await page.getByRole("button", { name: "More actions for Verify the saved workspace" }).click(); + await expect(page.getByRole("menuitem", { name: "Archive", exact: true })).toBeVisible(); }); diff --git a/ui/src/components/CoordinatorSidebar.test.tsx b/ui/src/components/CoordinatorSidebar.test.tsx index 65b5853f898..899afaf85bf 100644 --- a/ui/src/components/CoordinatorSidebar.test.tsx +++ b/ui/src/components/CoordinatorSidebar.test.tsx @@ -20,11 +20,6 @@ vi.mock("@/hooks/useRecentTasks", () => ({ useRecentTasks: ({ pinnedTaskIds }: { 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) => ({ - ...await importOriginal(), - prefetchIssueDetailForNavigation: taskPrefetch, -})); vi.mock("@/context/DialogContext", () => ({ useDialogActions: () => ({ openNewIssue: fixture.openNewIssue }) })); vi.mock("@/context/SidebarContext", () => ({ useSidebar: () => ({ isMobile: false, setSidebarOpen: vi.fn() }) })); vi.mock("@/api/attention", () => ({ attentionApi: { list: fixture.attention, summary: fixture.summary } })); @@ -61,90 +56,80 @@ beforeEach(() => { }); describe("Coordinator task creation", () => { - it("shows every task once in a four-level recent chain", async () => { - fixture.recentTasks = ["a", "b", "c", "d"].map((id, index) => ({ - id, companyId: "company", identifier: `TASK-${id}`, title: `Task ${id}`, status: "todo", recordedAt: index, - parentId: index ? ["a", "b", "c"][index - 1] : null, subtaskCount: index < 3 ? 1 : 0, - })); - fixture.projectTasks.mockImplementation(async (_company, filters) => fixture.recentTasks.filter(task => task.parentId === filters.parentId)); - await renderSidebar(); - const region = container.querySelector('[aria-label="Recents"]')!; - expect(region.querySelectorAll("a")).toHaveLength(4); - for (const id of ["a", "b", "c", "d"]) expect(region.querySelectorAll(`a[href="/issues/TASK-${id}"]`)).toHaveLength(1); - }); - it("nests recent children once, limits the first page to ten, and keeps folding separate from read state", async () => { + it("shows opened parent and child tasks as independent rows in recent order", async () => { fixture.recentTasks = [ - { id: "parent", companyId: "company", identifier: "TASK-1", title: "Parent", status: "todo", recordedAt: 1, subtaskCount: 14, unreadSubtaskCount: 12, isUnreadForMe: false }, - { id: "child-00", companyId: "company", identifier: "TASK-2", title: "Child 0", status: "todo", recordedAt: 2, parentId: "parent", isUnreadForMe: true }, + { id: "parent", companyId: "company", identifier: "TASK-1", title: "Parent", status: "todo", recordedAt: 1, subtaskCount: 2 }, + { id: "child", companyId: "company", identifier: "TASK-2", title: "Opened child", status: "todo", recordedAt: 2, parentId: "parent", isUnreadForMe: true }, ]; - fixture.projectTasks.mockImplementation(async (_company, filters) => Array.from({ length: filters.afterId ? 4 : 10 }, (_, index) => ({ - id: `child-${String(index + (filters.afterId ? 10 : 0)).padStart(2, "0")}`, companyId: "company", parentId: "parent", - identifier: `CHILD-${index + (filters.afterId ? 10 : 0)}`, title: `Child ${index + (filters.afterId ? 10 : 0)}`, status: "todo", isUnreadForMe: true, - }))); - await renderSidebar(); - const region = () => container.querySelector('[aria-label="Recents"]')!; - expect(region().querySelectorAll("a")).toHaveLength(11); - expect(region().textContent?.match(/Child 0/g)).toHaveLength(1); - const collapse = region().querySelector('[aria-label="Collapse subtasks of Parent"]')!; - await act(async () => collapse.click()); - expect(region().querySelectorAll("a")).toHaveLength(1); - expect(region().textContent).toContain("12 unread"); - await act(async () => region().querySelector('[aria-label="Expand subtasks of Parent"]')!.click()); - await act(async () => Array.from(region().querySelectorAll("button")).find(button => button.textContent?.includes("Show more"))!.click()); - await flush(); - expect(region().querySelectorAll("a")).toHaveLength(15); - expect(region().textContent).toContain("Show less"); - expect(fixture.projectTasks).toHaveBeenCalledWith("company", expect.objectContaining({ parentId: "parent", limit: 10, afterId: "child-09", includeReadState: true }), expect.anything()); - }); - it("keeps the selected child beyond ten visible within the ten-row preview", async () => { - fixture.pathname = "/COO/issues/TASK-12"; - fixture.recentTasks = [ - { id: "parent", companyId: "company", identifier: "TASK-1", title: "Parent", status: "todo", recordedAt: 1, subtaskCount: 14 }, - { id: "child-12", companyId: "company", identifier: "TASK-12", title: "Selected child", status: "todo", recordedAt: 2, parentId: "parent", isUnreadForMe: true }, - ]; - fixture.projectTasks.mockResolvedValue(Array.from({ length: 10 }, (_, index) => ({ - id: `child-${index}`, companyId: "company", parentId: "parent", identifier: `PAGE-${index}`, title: `Page child ${index}`, status: "todo", - }))); - await renderSidebar(); - expect(container.querySelectorAll('[role="group"][aria-label="Subtasks of Parent"] a')).toHaveLength(10); - expect(container.querySelector('a[href="/issues/TASK-12"]')).not.toBeNull(); - expect(container.querySelector('a[href="/issues/TASK-12"] [aria-label="Unread"]')).not.toBeNull(); - expect(container.querySelector('a[href="/issues/TASK-1"] [aria-label="Unread"]')).toBeNull(); - }); - it("keeps the parent link on a failed child read and retries without navigation", async () => { - fixture.recentTasks = [{ id: "parent", companyId: "company", identifier: "TASK-1", title: "Parent", status: "todo", recordedAt: 1, subtaskCount: 1 }]; - fixture.projectTasks.mockRejectedValueOnce(new Error("Unavailable")).mockResolvedValueOnce([ - { id: "child", companyId: "company", parentId: "parent", identifier: "CHILD", title: "Recovered child", status: "todo" }, + fixture.projectTasks.mockResolvedValue([ + { ...fixture.recentTasks[1] }, + { id: "unopened", companyId: "company", identifier: "TASK-3", title: "Unopened child", status: "todo", parentId: "parent" }, ]); await renderSidebar(); - expect(container.querySelector('a[href="/issues/TASK-1"]')).not.toBeNull(); - expect(container.querySelector('[role="alert"]')).not.toBeNull(); - await act(async () => Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Retry")!.click()); - await flush(); - expect(container.textContent).toContain("Recovered child"); - expect(fixture.pathname).toBe("/COO/issues"); + const region = container.querySelector('[aria-label="Recents"]')!; + const links = [...region.querySelectorAll("a")]; + expect(links.map(link => link.getAttribute("href"))).toEqual(["/issues/TASK-2", "/issues/TASK-1"]); + expect(links[0]!.parentElement?.parentElement).toBe(links[1]!.parentElement?.parentElement); + expect(links[0]!.querySelector('[aria-label="Unread"]')).not.toBeNull(); + expect(links[1]!.querySelector('[aria-label="Unread"]')).toBeNull(); + expect(region.querySelector('button[aria-expanded]')).toBeNull(); + expect(fixture.projectTasks).not.toHaveBeenCalled(); }); - it("keeps cached children visible during a temporary refetch failure", async () => { - fixture.recentTasks = [{ id: "parent", companyId: "company", identifier: "TASK-1", title: "Parent", status: "todo", recordedAt: 1, subtaskCount: 1 }]; - fixture.projectTasks.mockResolvedValue([{ id: "child", companyId: "company", parentId: "parent", identifier: "CHILD", title: "Cached child", status: "todo" }]); - await renderSidebar(); - fixture.projectTasks.mockRejectedValue(Object.assign(new Error("Gateway unavailable"), { status: 503 })); - await act(async () => { await client.invalidateQueries({ queryKey: ["issues", "company", "recent-subtasks"] }); }); - expect(container.textContent).toContain("Cached child"); - expect(container.querySelector('[role="alert"]')).toBeNull(); - expect(container.querySelector('a[href="/issues/CHILD"]')).not.toBeNull(); - }); - it("keeps every recent entry below the section header instead of truncating at twelve", async () => { - fixture.recentTasks = Array.from({ length: 20 }, (_, index) => ({ - id: `task-${index}`, companyId: "company", identifier: `TASK-${index}`, title: `Recent task ${index}`, status: "todo", recordedAt: index, + it("keeps hundreds of mixed recent rows in visit order with bounded input reads", async () => { + const baseTime = Date.parse("2026-11-18T08:00:00Z"); + const tasks = Array.from({ length: 300 }, (_, index) => ({ + id: `task-${index}`, companyId: "company", identifier: `TASK-${index}`, title: `Recent task ${index}`, + status: "todo", recordedAt: baseTime + 2 * index, + parentId: index > 0 ? `task-${index - 1}` : null, subtaskCount: 1, })); + const agents = Array.from({ length: 100 }, (_, index) => ({ + id: `agent-${index}`, companyId: "company", name: `Agent ${index}`, urlKey: `agent-${index}`, role: "engineer", status: "idle", + } as Agent)); + const chats = agents.map((agent, index) => ({ + id: `chat-${index}`, conversationAgentId: agent.id, + updatedAt: new Date(baseTime + 6 * index + 3).toISOString(), isUnreadForMe: false, + })); + const projects = Array.from({ length: 60 }, (_, index) => ({ + id: `project-${index}`, companyId: "company", name: `Project ${index}`, urlKey: `project-${index}`, + })); + const inputCount = tasks.length + agents.length + chats.length + projects.length; + let reads = 0; + function bounded(items: T[]) { + return new Proxy(items, { get(target, property, receiver) { + if (typeof property === "string" && /^\d+$/.test(property) && ++reads > 4 * inputCount) { + throw new Error("Recents scans growing lists repeatedly"); + } + return Reflect.get(target, property, receiver); + } }); + } + + fixture.projects = bounded(projects); + const now = vi.spyOn(Date, "now").mockReturnValue(baseTime + 601); + try { + fixture.pathname = "/COO/projects/project-0"; + await renderSidebar(); + now.mockReturnValue(baseTime + 602); + fixture.pathname = "/COO/projects/project-1"; + await renderSidebar(); + } finally { + now.mockRestore(); + } + + fixture.recentTasks = bounded(tasks); + fixture.agents = bounded(agents); + fixture.chats = bounded(chats); await renderSidebar(); + const region = container.querySelector('[role="region"][aria-label="Recents"]')!; - expect(region.querySelectorAll("a")).toHaveLength(20); - expect(region.textContent).not.toContain("Recents"); - expect(region.querySelector('a[href="/issues/TASK-0"]')).not.toBeNull(); + const links = Array.from(region.querySelectorAll("a"), link => link.getAttribute("href")); + expect(links).toHaveLength(tasks.length + chats.length + 2); + expect(links.slice(0, 4)).toEqual(["/projects/project-1", "/projects/project-0", "/issues/TASK-299", "/chats/agent-99"]); + expect(links.at(-1)).toBe("/issues/TASK-0"); + expect(new Set(links).size).toBe(links.length); + expect(fixture.projectTasks).not.toHaveBeenCalled(); + expect(reads).toBeGreaterThanOrEqual(inputCount); }); - it("moves the recent parent group ahead of newer rows after opening its child", async () => { + it("moves the child ahead of newer rows when reopened", 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 }; @@ -152,11 +137,11 @@ describe("Coordinator task creation", () => { 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"]); + expect(order()).toEqual(["/issues/TASK-3", "/issues/TASK-2", "/issues/TASK-1"]); 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"]); + expect(order()).toEqual(["/issues/TASK-2", "/issues/TASK-3", "/issues/TASK-1"]); }); it("opens global search from the organization header", async () => { await renderSidebar(); @@ -509,26 +494,14 @@ describe("Coordinator task status glyphs (BUG-07)", () => { expect(glyph("/issues/ONB-1")?.getAttribute("aria-label")).toBe("Blocked · waiting on active sub-task ONB-3"); }); - it("shows project tasks with their full status presentation", async () => { + it("shows a recent project as a link without expanding its tasks", async () => { fixture.projects = [{ id: "project-1", companyId: "company", name: "Onboarding", urlKey: "onboarding" }]; - fixture.projectTasks.mockResolvedValue([ - { id: "task-1", identifier: "ONB-1", title: "Blocked parent", status: "blocked", displayStatus: "blocked", blockerAttention: covered }, - { id: "task-3", identifier: "ONB-3", title: "Waiting review", status: "in_review", displayStatus: "in_review", externalConversationState: "waiting" }, - ]); fixture.pathname = "/COO/projects/onboarding"; await renderSidebar(); - const expand = container.querySelector('button[aria-label="Expand Onboarding"]'); - expect(expand).not.toBeNull(); - await act(async () => expand!.click()); - await flush(); - expect(fixture.projectTasks).toHaveBeenCalledWith("company", expect.objectContaining({ projectId: "project-1", projection: "rows" })); - expect(glyph("/issues/ONB-1")?.style.color).toBe("var(--status-task-icon-in_queue)"); - expect(glyph("/issues/ONB-3")?.getAttribute("aria-label")).toBe("Idle"); - // A press on a project task warms its chat like a task list row does. - const link = container.querySelector('a[href="/issues/ONB-3"]'); - taskPrefetch.mockClear(); - await act(async () => link!.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true, button: 0 }))); - expect(taskPrefetch).toHaveBeenCalledWith(expect.anything(), "ONB-3", expect.objectContaining({ history: true })); + const region = container.querySelector('[aria-label="Recents"]')!; + expect(region.querySelector('a[href="/projects/onboarding"]')?.textContent).toBe("Onboarding"); + expect(region.querySelector('button[aria-expanded]')).toBeNull(); + expect(fixture.projectTasks).not.toHaveBeenCalled(); }); }); diff --git a/ui/src/components/CoordinatorSidebar.tsx b/ui/src/components/CoordinatorSidebar.tsx index 4154bc81249..9b32af12cd4 100644 --- a/ui/src/components/CoordinatorSidebar.tsx +++ b/ui/src/components/CoordinatorSidebar.tsx @@ -1,9 +1,8 @@ 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 { Inbox, Boxes, CircleCheck, Compass, FolderOpen, History, LayoutDashboard, MessageCircle, MoreHorizontal, Network, Pin, PinOff, Plus, Repeat, Search, Settings, SquarePen, Unplug, type LucideIcon } from "lucide-react"; import type { Agent, IssueSummary, Project } from "@paperclipai/shared"; import { useCoordinatorAttentionCount } from "@/hooks/useCoordinatorAttentionCount"; -import { issuesApi } from "@/api/issues"; import { instanceSettingsApi } from "@/api/instanceSettings"; import { useAgentChatNavigation } from "@/hooks/useAgentChatNavigation"; import { useResponsibilitiesEnabled } from "@/hooks/useResponsibilitiesEnabled"; @@ -19,8 +18,6 @@ import { agentRouteRef, cn, projectRouteRef } from "@/lib/utils"; import { SidebarCompanyMenu } from "./SidebarCompanyMenu"; import { SidebarNavItem } from "./SidebarNavItem"; import { RecentTaskNavItem, recentTaskPathRef } from "./RecentTaskNavItem"; -import { RecentTaskGroup } from "./RecentTaskGroup"; -import { recentTaskHierarchy } from "@/lib/recent-task-hierarchy"; import { SidebarSection } from "./SidebarSection"; import { TruncatedTextMarqueeProvider } from "./TruncatedText"; import { useScrollbarWhileScrolling } from "./side-panel/use-scrollbar-while-scrolling"; @@ -107,32 +104,6 @@ function RecentTaskPinRow({ task, pins }: { task: RecentTaskLink; pins: PinContr ; } -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"], - queryFn: () => issuesApi.listCompact(project.companyId, { projection: "rows", projectId: project.id, limit: 12, sortField: "updated", sortDir: "desc" }), - enabled: expanded, - }); - return
-
-
- - - -
- -
- {expanded &&
- {isPending ?

Loading tasks…

: error ?

Couldn’t load tasks.

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

No tasks yet.

} -
} -
; -} - function RecentNavigationList({ children }: { children: ReactNode }) { const scrollRef = useRef(null); const contentRef = useRef(null); @@ -195,7 +166,6 @@ export function CoordinatorSidebar({ children }: { children?: ReactNode }) { const location = useLocation(); useRecentTaskOpenWarmup({ companyId, userId, tasks: session.isSuccess ? recentTasks : NO_RECENT_TASKS, navigationKey: location.pathname }); const { openNewIssue } = useDialogActions(); - 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, @@ -212,7 +182,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 = hierarchy.roots.map(task => ({ kind: "task" as const, id: task.id, time: hierarchy.latestVisitByRoot.get(task.id)!, task })); + const taskRows = recentTasks.map(task => ({ kind: "task" as const, id: task.id, time: task.recordedAt, 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 }] : []; @@ -220,7 +190,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, projects, projectVisits, scope, hierarchy]); + }, [agents.data, chats.data, recentTasks, projects, projectVisits, scope]); const newTaskButton = - - {!expanded ? :
- {(view.kind === "loading" || view.kind === "reconnecting") &&

Loading subtasks…

} - {displayed.map(child =>
{childRow({ ...child, recordedAt: 0 })}
)} - {pinned && childRow(pinned)} - {view.kind === "error" ? { if (query.isFetchNextPageError) void query.fetchNextPage(); else view.retry(); }} /> - : view.data && loaded.length === 0 ?

No subtasks available.

: null} - {remaining > 0 && loaded.length > 0 && (loaded.length > displayed.length || query.hasNextPage) && view.kind !== "error" && } - {showAllLoaded && displayed.length > RECENT_SUBTASK_PAGE_SIZE && } -
} - ; -} diff --git a/ui/src/components/SidebarRecentTasks.test.tsx b/ui/src/components/SidebarRecentTasks.test.tsx index 4748c60f14a..414f9754f52 100644 --- a/ui/src/components/SidebarRecentTasks.test.tsx +++ b/ui/src/components/SidebarRecentTasks.test.tsx @@ -131,31 +131,25 @@ describe("SidebarRecentTasks", () => { expect(container.textContent).not.toContain("Recent Tasks"); expect(container.textContent).not.toContain("Open or create a task"); }); - it("keeps actions on both parent and nested child rows", async () => { + it("keeps actions on independent parent and child rows in recent order", async () => { const parent = { id: "parent", companyId: "company-1", title: "Parent", identifier: "PAP-1", status: "todo" as const, updatedAt: new Date(1), subtaskCount: 1, isParticipantForMe: true }; - recordRecentTask(parent, "user-1"); - mockIssuesApi.summaries.mockResolvedValue([parent]); - mockIssuesApi.listCompact.mockResolvedValue([{ id: "child", companyId: "company-1", parentId: "parent", title: "Child", identifier: "PAP-2", status: "todo" }] as never); + const child = { ...parent, id: "child", parentId: parent.id, title: "Child", identifier: "PAP-2", subtaskCount: 0 }; + recordRecentTask(parent, "user-1", 1); + recordRecentTask(child, "user-1", 2); + mockIssuesApi.summaries.mockResolvedValue([parent, child]); + await render(); + + const links = [...container.querySelectorAll("a")]; + expect(links.map(link => link.getAttribute("href"))).toEqual(["/issues/PAP-2", "/issues/PAP-1"]); + expect(links[0]!.parentElement?.parentElement).toBe(links[1]!.parentElement?.parentElement); + expect(mockIssuesApi.listCompact).not.toHaveBeenCalled(); expect(container.querySelector('[aria-label="More actions for Parent"]')).not.toBeNull(); - expect(container.querySelector('[aria-label="More actions for Child"]')).not.toBeNull(); await openActions("Child"); expect(menuItem("Rename")).toBeDefined(); expect(menuItem("Archive")).toBeDefined(); expect(menuItem("Pause/Restart")).toBeDefined(); }); - it("shows every task once in a four-level recent chain", async () => { - const tasks = ["a", "b", "c", "d"].map((id, index) => ({ - id, companyId: "company-1", identifier: `TASK-${id}`, title: `Task ${id}`, status: "todo" as const, updatedAt: new Date(index + 1), - parentId: index ? ["a", "b", "c"][index - 1] : null, subtaskCount: index < 3 ? 1 : 0, isParticipantForMe: true, - })); - tasks.forEach(task => recordRecentTask(task, "user-1")); - mockIssuesApi.summaries.mockResolvedValue(tasks); - mockIssuesApi.listCompact.mockImplementation(async (_company, filters) => tasks.filter(task => task.parentId === filters?.parentId)); - await render(); - expect(container.querySelectorAll("a")).toHaveLength(4); - for (const id of ["a", "b", "c", "d"]) expect(container.querySelectorAll(`a[href="/issues/TASK-${id}"]`)).toHaveLength(1); - }); it("renders refreshed task text and live state without shifting for a status icon", async () => { recordRecentTask({ @@ -309,7 +303,7 @@ describe("SidebarRecentTasks", () => { expect(container.textContent).toContain("Idle"); }); - it("archives a task from the inbox without hiding or removing the recent task", async () => { + it("removes a recent task after archiving it from the inbox", async () => { const issue = { id: "issue-1", companyId: "company-1", @@ -336,14 +330,11 @@ describe("SidebarRecentTasks", () => { expect(mockIssuesApi.archiveFromInbox).toHaveBeenCalledWith("issue-1"); expect(mockIssuesApi.update).not.toHaveBeenCalled(); - expect(container.textContent).toContain("Recent Tasks"); - expect(container.querySelector('a[href="/issues/PAP-1"]')?.textContent).toContain( - "Archive me", - ); + expect(container.querySelector('a[href="/issues/PAP-1"]')).toBeNull(); expect(readRecentTasks( getRecentTasksStorageKey("company-1", "user-1"), "company-1", - )).toHaveLength(1); + )).toEqual([]); }); it("refreshes task activity after a rename", async () => { diff --git a/ui/src/components/SidebarRecentTasks.tsx b/ui/src/components/SidebarRecentTasks.tsx index 53dd8749fb7..3547b2df6ee 100644 --- a/ui/src/components/SidebarRecentTasks.tsx +++ b/ui/src/components/SidebarRecentTasks.tsx @@ -1,4 +1,4 @@ -import { useMemo, useState, type FormEvent } from "react"; +import { useState, type FormEvent } from "react"; import { useQueryClient } from "@tanstack/react-query"; import { Archive, MoreHorizontal, Pencil, RefreshCw } from "lucide-react"; import { agentsApi } from "@/api/agents"; @@ -9,6 +9,7 @@ import { useRecentTaskOpenWarmup } from "@/hooks/useRecentTaskOpenWarmup"; import { useAccountIdentity } from "@/api/companies-query"; import { useOptionalToastActions } from "@/context/ToastContext"; import { + pruneRecentTasks, recordRecentTask, type RecentTaskEntry, } from "@/lib/recent-tasks"; @@ -31,8 +32,6 @@ import { Input } from "@/components/ui/input"; import { StatusIcon } from "./StatusIcon"; import { SidebarSection } from "./SidebarSection"; import { RecentTaskNavItem } from "./RecentTaskNavItem"; -import { RecentTaskGroup } from "./RecentTaskGroup"; -import { recentTaskHierarchy } from "@/lib/recent-task-hierarchy"; import { useLocation } from "@/lib/router"; import { taskStatusIconProps } from "@/lib/task-status-presentation"; @@ -102,9 +101,8 @@ function RecentTasksList({ userId: string | null; liveIssueIds: ReadonlySet; }) { - const { entries } = useRecentTasks({ companyId, userId }); + const { entries, storageKey } = useRecentTasks({ companyId, userId }); const { pathname } = useLocation(); - const hierarchy = useMemo(() => recentTaskHierarchy(entries, pathname), [entries, pathname]); const queryClient = useQueryClient(); const toastActions = useOptionalToastActions(); const [renameEntry, setRenameEntry] = useState(null); @@ -159,6 +157,7 @@ function RecentTasksList({ setPendingAction("archive"); try { await issuesApi.archiveFromInbox(entry.id); + if (storageKey) pruneRecentTasks(storageKey, companyId, new Set([entry.id])); await refreshIssueQueries(entry.id); await queryClient.invalidateQueries({ queryKey: queryKeys.sidebarBadges(companyId), @@ -247,7 +246,7 @@ function RecentTasksList({ }; const renderTaskRow = (entry: RecentTaskEntry) => ( -
+
- {hierarchy.roots.map((entry) => ( - - {renderTaskRow(entry)} - - ))} + {entries.map(renderTaskRow)} { const badges = queryKeys.sidebarBadges("company-1"); const chats = queryKeys.agentChats.list("company-1", "viewer"); const navigation = queryKeys.issues.summaryBatch("company-1", "viewer", ["task-1"]); - const subtasks = [...queryKeys.issues.list("company-1"), "recent-subtasks", "viewer", "parent-1"]; const ownReads = [mine, touched, unread, badges, chats, navigation].map(key => watch(key)); - const childRead = watch(subtasks); - client.setQueryData(subtasks, { pages: [[{id: "task-1", parentId: "parent-1", companyId: "company-1"}]], pageParams: [undefined] }); - ownReads.push(childRead); const unrelatedReads = [ queryKeys.issues.list("company-1"), [...queryKeys.issues.list("company-1"), "row-context"], diff --git a/ui/src/context/LiveUpdatesProvider.tsx b/ui/src/context/LiveUpdatesProvider.tsx index 4c9ed94c52c..a9aacca3502 100644 --- a/ui/src/context/LiveUpdatesProvider.tsx +++ b/ui/src/context/LiveUpdatesProvider.tsx @@ -4,7 +4,7 @@ import { getPageVisibility, usePageVisibility } from "../lib/page-visibility"; import { createLiveQueryRecovery } from "../lib/live-query-recovery"; import { isLiveReconciledQuery } from "../lib/live-reconcile"; import { refreshPendingTaskBrowserReads, refreshTaskBrowsers } from "../lib/task-browsers-refresh"; -import { refreshRecentSubtasks, refreshRecentTaskSummaries } from "../lib/recent-subtasks-refresh"; +import { refreshRecentTaskSummaries } from "../lib/recent-task-summary-refresh"; import { invalidateInteractionRecordViews } from "../lib/attention-record-views"; import { createContext, @@ -1495,7 +1495,6 @@ function invalidateHeartbeatQueries( ? payload.recentSubtaskParentIds.filter((id): id is string => typeof id === "string") : undefined; const issueId = readString(payload.issueId); refreshRecentTaskSummaries(queryClient, companyId, issueId, parentIds); - refreshRecentSubtasks(queryClient, companyId, issueId, parentIds); // Note: liveRuns(companyId) is intentionally NOT invalidated here — it is // event-sourced via applyRunLifecycleToCompanyLiveRuns in the caller. queryClient.invalidateQueries({ queryKey: queryKeys.heartbeats(companyId) }); @@ -1601,7 +1600,6 @@ function invalidateActivityQueries( } const readerId = readString(details?.userId) ?? (actorType === "user" ? actorId : null); if (readerId && readerId === currentActor.userId) { - refreshRecentSubtasks(queryClient, companyId, entityId, subtaskParents, currentActor.userId); refreshRecentTaskSummaries(queryClient, companyId, entityId, subtaskParents); for (const queryKey of [ queryKeys.issues.listMineByMe(companyId), @@ -1635,7 +1633,6 @@ function invalidateActivityQueries( action?.startsWith("company_membership.") || action?.startsWith("membership.") || action?.includes("privacy"); if (decisionAudienceChanged) { - void queryClient.resetQueries({ queryKey: [...queryKeys.issues.list(companyId), "recent-subtasks"] }); void queryClient.resetQueries({ queryKey: queryKeys.issues.summaries(companyId) }); // Drop old permission-filtered payloads immediately while the API resolves // the current audience. A failed refetch must not retain a revoked receipt. @@ -1679,7 +1676,6 @@ function invalidateActivityQueries( } if (entityType === "issue") { - refreshRecentSubtasks(queryClient, companyId, entityId, subtaskParents); refreshRecentTaskSummaries(queryClient, companyId, entityId, subtaskParents); // Browser lists stop polling while connected; this activity refreshes them. if (entityId && action?.startsWith("browser.")) refreshTaskBrowsers(queryClient, entityId); @@ -1697,7 +1693,7 @@ function invalidateActivityQueries( queryClient.invalidateQueries({ queryKey: queryKeys.issues.list(companyId), predicate: excludingQueryKeys(queryKeys.issues.mentionPool(companyId), queryKeys.issues.listIndex(companyId), - [...queryKeys.issues.list(companyId), "recent-subtasks"], queryKeys.issues.summaries(companyId)), + queryKeys.issues.summaries(companyId)), }); refreshTaskIndexForActivity(queryClient, companyId, ownActorActivity); refreshMentionPoolForActivity( diff --git a/ui/src/hooks/useRecentTasks.test.tsx b/ui/src/hooks/useRecentTasks.test.tsx index 215b8eadf68..7f65bdf3354 100644 --- a/ui/src/hooks/useRecentTasks.test.tsx +++ b/ui/src/hooks/useRecentTasks.test.tsx @@ -207,6 +207,36 @@ describe("recent task synchronization", () => { expect(getIssue).not.toHaveBeenCalled(); expect(cache.getQueryCache().findAll({ queryKey: ["issues", "detail"] })).toEqual([]); }); + it("keeps a canceled task in Recents and removes it on archive without dropping its pin", async () => { + const opened = task(10, "Recent task"); + const cancelled = { ...opened, status: "cancelled" as const, updatedAt: new Date(20) }; + recordRecentTask(opened, "user-1", 10); + summaries.mockResolvedValue([opened]); + const cache = client(); + const pins = [opened.id]; + const refresh = async () => { + await act(async () => { await cache.invalidateQueries({ queryKey: queryKeys.issues.summaries("company-1") }); }); + await flush(); + }; + await act(async () => root.render()); + await flush(); + expect(container.textContent).toBe("Recent task:todo"); + + summaries.mockResolvedValue([cancelled]); + await refresh(); + expect(container.textContent).toBe("Recent task:cancelled"); + expect(readRecentTasks(storageKey, "company-1")[0]?.recordedAt).toBe(10); + + await act(async () => recordRecentTask(cancelled, "user-1", 30)); + expect(readRecentTasks(storageKey, "company-1")[0]?.recordedAt).toBe(30); + + summaries.mockResolvedValue([{ ...cancelled, isArchivedForMe: true }]); + await refresh(); + expect(container.textContent).toBe(""); + expect(container.querySelector("[data-pins]")?.getAttribute("data-pins")).toBe("Recent task"); + expect(readRecentTasks(storageKey, "company-1")).toEqual([]); + }); + it("keeps loaded navigation state on a failed refresh without storing personal unread projections", async () => { const parent = { ...task(10, "Parent"), parentId: null, subtaskCount: 14, unreadSubtaskCount: 12, isUnreadForMe: true }; recordRecentTask(parent, "user-1"); @@ -216,16 +246,16 @@ describe("recent task synchronization", () => { function State() { entries = useRecentTasks({ companyId: "company-1", userId: "user-1" }).entries; return null; } await act(async () => root.render()); await flush(); - expect(entries[0]).toMatchObject({ subtaskCount: 14, unreadSubtaskCount: 12, isUnreadForMe: true }); + expect(entries[0]).toMatchObject({ isUnreadForMe: true }); expect(readRecentTasks(storageKey, "company-1")[0]).not.toHaveProperty("isUnreadForMe"); - expect(readRecentTasks(storageKey, "company-1")[0]).not.toHaveProperty("subtaskCount"); + expect(entries[0]).not.toHaveProperty("subtaskCount"); const stable = entries; await act(async () => root.render()); expect(entries).toBe(stable); summaries.mockRejectedValue(new ApiError("Unavailable", 503, null)); await act(async () => { await cache.invalidateQueries({ queryKey: queryKeys.issues.summaries("company-1") }); }); await flush(); - expect(entries[0]).toMatchObject({ subtaskCount: 14, unreadSubtaskCount: 12, isUnreadForMe: true }); + expect(entries[0]).toMatchObject({ isUnreadForMe: true }); }); it("does not fetch empty history", async () => { diff --git a/ui/src/hooks/useRecentTasks.ts b/ui/src/hooks/useRecentTasks.ts index 7541a35dddc..860de8fd422 100644 --- a/ui/src/hooks/useRecentTasks.ts +++ b/ui/src/hooks/useRecentTasks.ts @@ -138,11 +138,10 @@ export function useRecentTasks({ }), [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) => { + const refreshedEntries = useMemo(() => entries.flatMap((entry) => { const issue = confirmed.get(entry.id); - // Relationship/read state is session data, never a localStorage snapshot. - return issue ? { ...mergeRecentTaskSnapshot(entry, issue), parentId: issue.parentId, - isUnreadForMe: issue.isUnreadForMe, subtaskCount: issue.subtaskCount, unreadSubtaskCount: issue.unreadSubtaskCount } : entry; + if (issue?.isParticipantForMe !== true || issue.isArchivedForMe) return []; + return [{ ...mergeRecentTaskSnapshot(entry, issue), isUnreadForMe: issue.isUnreadForMe }]; }), [entries, confirmed]); const processed = useRef<{ visit: typeof batchVisit; revision: number } | null>(null); @@ -152,7 +151,7 @@ export function useRecentTasks({ processed.current = { visit: batchVisit, revision: updateCount }; // Older cached summaries without the new projection cannot prove either // 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)); + const returnedIds = new Set(summaries.filter((issue) => issue.companyId === companyId && issue.isParticipantForMe !== false && !issue.isArchivedForMe).map((issue) => issue.id)); updateRecentTaskSnapshots(storageKey, companyId, summaries); const omittedIds = new Set(recentIds.filter((id) => !returnedIds.has(id))); if (omittedIds.size && updateCount <= batchVisit.initialUpdateCount) { diff --git a/ui/src/lib/inboxArchiveCache.ts b/ui/src/lib/inboxArchiveCache.ts index 04e5d8adf7a..b2842ddb888 100644 --- a/ui/src/lib/inboxArchiveCache.ts +++ b/ui/src/lib/inboxArchiveCache.ts @@ -241,6 +241,7 @@ export function invalidateInboxIssueQueries(queryClient: QueryClient, companyId: queryClient.invalidateQueries({ queryKey }), ), queryClient.invalidateQueries({ queryKey: queryKeys.sidebarBadges(companyId) }), + queryClient.invalidateQueries({ queryKey: queryKeys.issues.summaries(companyId) }), ]); } diff --git a/ui/src/lib/recent-subtask-requests.test.ts b/ui/src/lib/recent-subtask-requests.test.ts deleted file mode 100644 index 5edbc978e92..00000000000 --- a/ui/src/lib/recent-subtask-requests.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { expect, it } from "vitest"; -import { readRecentSubtasks, RECENT_SUBTASK_CONCURRENCY } from "./recent-subtask-requests"; - -it("bounds simultaneous child HTTP reads and cancels queued groups before they start", async () => { - let active = 0, peak = 0; - const started: number[] = []; - const releases: Array<() => void> = []; - const controllers = Array.from({ length: 50 }, () => new AbortController()); - const work = controllers.map((controller, id) => readRecentSubtasks(controller.signal, async () => { - started.push(id); - peak = Math.max(peak, ++active); - await new Promise(resolve => releases.push(resolve)); - active--; - if (id === 0) throw new Error("HTTP failure"); - return id; - })); - const settled = Promise.allSettled(work); - await Promise.resolve(); - expect(started).toHaveLength(RECENT_SUBTASK_CONCURRENCY); - controllers.slice(3, 49).forEach(controller => controller.abort()); - // One request fails; its slot still becomes available to the remaining group. - releases.splice(0).forEach(release => release()); - for (let n = 0; n < 10; n++) await Promise.resolve(); - expect(started).toEqual([0, 1, 2, 49]); - releases.splice(0).forEach(release => release()); - const results = await settled; - expect(peak).toBe(3); - expect(results.filter(result => result.status === "fulfilled")).toHaveLength(3); - expect(results.at(-1)).toEqual({ status: "fulfilled", value: 49 }); -}); diff --git a/ui/src/lib/recent-subtask-requests.ts b/ui/src/lib/recent-subtask-requests.ts deleted file mode 100644 index 1f8082cebed..00000000000 --- a/ui/src/lib/recent-subtask-requests.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** Shared across sidebar groups. Aborted queued reads never start HTTP work. */ -export const RECENT_SUBTASK_CONCURRENCY = 3; -let active = 0; -const waiting = new Set<() => void>(); - -export async function readRecentSubtasks(signal: AbortSignal, read: () => Promise): Promise { - await new Promise((resolve, reject) => { - const abort = () => { - waiting.delete(start); - reject(signal.reason ?? new DOMException("Aborted", "AbortError")); - }; - const start = () => { - if (active >= RECENT_SUBTASK_CONCURRENCY) return; - waiting.delete(start); - signal.removeEventListener("abort", abort); - active++; - resolve(); - }; - if (signal.aborted) { abort(); return; } - signal.addEventListener("abort", abort, { once: true }); - waiting.add(start); - start(); - }); - try { - signal.throwIfAborted(); - return await read(); - } finally { - active--; - for (const start of waiting) { - if (active >= RECENT_SUBTASK_CONCURRENCY) break; - start(); - } - } -} diff --git a/ui/src/lib/recent-task-hierarchy.test.ts b/ui/src/lib/recent-task-hierarchy.test.ts deleted file mode 100644 index 2a90d733d3f..00000000000 --- a/ui/src/lib/recent-task-hierarchy.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { recentTaskHierarchy } from "./recent-task-hierarchy"; -import type { RecentTaskEntry } from "./recent-tasks"; - -const task = (id: string, parentId: string | null = null, subtaskCount = 0): RecentTaskEntry => ({ - id, parentId, subtaskCount, companyId: "company", title: id, identifier: id, status: "todo", recordedAt: 0, -}); -describe("recent task hierarchy", () => { - it("nests only beneath readable recent roots, retaining orphans and cycles", () => { - const entries = [task("root", null, 2), task("child", "root", 1), task("grandchild", "child"), - task("orphan", "absent"), task("cycle-a", "cycle-b", 1), task("cycle-b", "cycle-a", 1)]; - const hierarchy = recentTaskHierarchy(entries, "/PAP/issues/child"); - expect([...hierarchy.nestedIds]).toEqual(["child"]); - expect(hierarchy.selectedChild?.id).toBe("child"); - expect(hierarchy.flattenedIds).toEqual(new Set(["cycle-a", "cycle-b"])); - }); - it("deduplicates children of every displayed root in a four-level chain regardless of recent order", () => { - const entries = [task("d", "c"), task("b", "a", 1), task("c", "b", 1), task("a", null, 1)]; - expect(recentTaskHierarchy(entries, "/PAP/issues/d").nestedIds).toEqual(new Set(["b", "d"])); - }); - it("indexes a large history without rescanning it for each child", () => { - let reads = 0; - const entries = Array.from({ length: 10_000 }, (_, index) => ({ ...task(`task-${index}`, null, 1), - get parentId() { - if (++reads > 120_000) throw new Error("Repeated parent scans"); - return index % 2 ? `task-${index - 1}` : null; - }, - })); - expect(recentTaskHierarchy(entries, "/PAP/issues/task-9999").nestedIds.size).toBe(5_000); - expect(reads).toBeLessThan(120_000); - }); -}); diff --git a/ui/src/lib/recent-task-hierarchy.ts b/ui/src/lib/recent-task-hierarchy.ts deleted file mode 100644 index a91a2c9cc85..00000000000 --- a/ui/src/lib/recent-task-hierarchy.ts +++ /dev/null @@ -1,50 +0,0 @@ -import type { RecentTaskEntry } from "./recent-tasks"; -import { parseIssuePathIdFromPath } from "./issue-reference"; - -/** Only nest under a readable recent root. Orphans and cyclic links stay reachable. */ -export function recentTaskHierarchy(entries: readonly RecentTaskEntry[], pathname: string) { - const byId = new Map(entries.map(entry => [entry.id, entry])); - const parents = new Map(); - for (const entry of entries) { - const parentId = entry.parentId; - const parent = parentId ? byId.get(parentId) : undefined; - if (parent && (parent.subtaskCount ?? 0) > 0) parents.set(entry.id, parent.id); - } - // A displayed root owns its direct children. A deeper task can be a second - // displayed root, so its children must also leave the top-level list. - const nested = new Map(); - const flattenedIds = new Set(); - for (const entry of entries) { - if (nested.has(entry.id)) continue; - const path: string[] = []; - const positions = new Map(); - let current = entry.id; - while (!nested.has(current)) { - const cycleStart = positions.get(current); - if (cycleStart !== undefined) { - for (const id of path.slice(cycleStart)) { nested.set(id, false); flattenedIds.add(id); } - break; - } - positions.set(current, path.length); - path.push(current); - const parent = parents.get(current); - if (!parent) { nested.set(current, false); break; } - current = parent; - } - for (const id of path.reverse()) { - if (nested.has(id)) continue; - const parent = parents.get(id)!; - nested.set(id, !flattenedIds.has(parent) && nested.get(parent) === false); - } - } - 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 { roots, latestVisitByRoot, nestedIds, flattenedIds, selectedChild: selected && nestedIds.has(selected.id) ? selected : undefined }; -} diff --git a/ui/src/lib/recent-subtasks-refresh.ts b/ui/src/lib/recent-task-summary-refresh.ts similarity index 51% rename from ui/src/lib/recent-subtasks-refresh.ts rename to ui/src/lib/recent-task-summary-refresh.ts index 4a72c2d393c..8e6ed131b13 100644 --- a/ui/src/lib/recent-subtasks-refresh.ts +++ b/ui/src/lib/recent-task-summary-refresh.ts @@ -1,30 +1,6 @@ -import type { InfiniteData, QueryClient } from "@tanstack/react-query"; +import type { QueryClient } from "@tanstack/react-query"; import { queryKeys } from "./queryKeys"; -type Child = { id: string; parentId?: string | null; companyId: string }; - -/** Parent hints are separately authorized by live delivery, never raw details. */ -export function refreshRecentSubtasks( - client: QueryClient, - companyId: string, - issueId: string | null, - parentIds: readonly string[] = [], - viewerId?: string | null, -) { - const parents = new Set(parentIds); - if (issueId) parents.add(issueId); - for (const query of client.getQueryCache().findAll({ - queryKey: [...queryKeys.issues.list(companyId), "recent-subtasks"], - })) { - if (viewerId !== undefined && query.queryKey[3] !== (viewerId ?? "__local_board__")) continue; - const data = query.state.data as InfiniteData | undefined; - if (parents.has(String(query.queryKey[4])) || data?.pages?.some(page => - Array.isArray(page) && page.some(child => child.companyId === companyId && child.id === issueId))) { - void client.invalidateQueries({ queryKey: query.queryKey, exact: true }); - } - } -} - export function refreshRecentTaskSummaries( client: QueryClient, companyId: string, issueId: string | null, parentIds: readonly string[] | undefined, diff --git a/ui/src/lib/recent-tasks.ts b/ui/src/lib/recent-tasks.ts index 1455c644d34..61c3c40c4ca 100644 --- a/ui/src/lib/recent-tasks.ts +++ b/ui/src/lib/recent-tasks.ts @@ -14,11 +14,7 @@ export interface RecentTaskEntry { externalConversationState?: Issue["externalConversationState"]; /** Blocked tasks covered by active work render the "in queue" glyph everywhere. */ blockerAttention?: Issue["blockerAttention"]; - /** Refreshed navigation state; do not persist these personal read projections. */ - parentId?: string | null; isUnreadForMe?: boolean; - subtaskCount?: number; - unreadSubtaskCount?: number; recordedAt: number; // Server version of the title/status snapshot, independent of comment activity. // Legacy entries have no version until a detail query refreshes them. @@ -143,11 +139,11 @@ export function mergeRecentTaskSnapshot(entry: RecentTaskEntry, issue: TaskSnaps } export function recordRecentTask( - issue: Pick, + issue: Pick, userId: string | null | undefined, recordedAt?: number, ) { - if (issue.conversationAgentId) return; + if (issue.conversationAgentId || issue.archivedAt) return; const storageKey = getRecentTasksStorageKey(issue.companyId, userId); const current = readRecentTasks(storageKey, issue.companyId); const existing = current.find((candidate) => candidate.id === issue.id); diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx index efced31ccf5..c09b11945ea 100644 --- a/ui/src/pages/IssueDetail.tsx +++ b/ui/src/pages/IssueDetail.tsx @@ -4626,7 +4626,6 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS receipt.confirmed = true; // A late receipt belongs to its original company, even after navigation. queryClient.invalidateQueries({ queryKey: queryKeys.issues.summaries(receipt.companyId) }); - queryClient.invalidateQueries({ queryKey: [...queryKeys.issues.list(receipt.companyId), "recent-subtasks"] }); if (selectedCompanyId) { queryClient.invalidateQueries({ queryKey: queryKeys.issues.listMineByMe(selectedCompanyId), diff --git a/ui/storybook/stories/navigation-preferences/recent-subtasks.stories.tsx b/ui/storybook/stories/navigation-preferences/recent-subtasks.stories.tsx index b33105b4f80..2a936cefe4e 100644 --- a/ui/storybook/stories/navigation-preferences/recent-subtasks.stories.tsx +++ b/ui/storybook/stories/navigation-preferences/recent-subtasks.stories.tsx @@ -7,101 +7,120 @@ import { prepareFixtureApi } from "../../support/capability-gaps/api"; import { storybookIssues } from "../../fixtures/paperclipData"; import type { Issue } from "@paperclipai/shared"; -type Scenario = "expanded" | "collapsed" | "ten" | "many" | "all" | "selected" | "beyond-ten" | "statuses" | "independent" | "long" | "narrow" | "leaf" | "empty" | "loading" | "failure" | "stale" | "keyboard" | "section-collapsed" | "parent-unread" | "classic"; -type Args = { scenario: Scenario }; +type Args = { + classic: boolean; + childOnly: boolean; + empty: boolean; + collapseSection: boolean; + narrow: boolean; + longTitles: boolean; + focusChild: boolean; +}; + const companyId = "company-storybook"; const userId = "user-board"; const parentTitle = "Ship the project workspace"; +const childTitle = "Verify the saved workspace"; +const liveIssueIds = new Set(); + function task(index: number, title: string, parentId: string | null = null): Issue { - return { ...storybookIssues[0]!, id: `00000000-0000-4000-8000-${String(index).padStart(12, "0")}`, companyId, - identifier: `PAP-${100 + index}`, title, status: "todo", parentId, hiddenAt: null, conversationAgentId: null, - createdAt: new Date("2026-11-01"), updatedAt: new Date("2026-11-01"), isUnreadForMe: false }; + return { + ...storybookIssues[0]!, + id: `00000000-0000-4000-8000-${String(index).padStart(12, "0")}`, + companyId, identifier: `PAP-${100 + index}`, title, parentId, + status: "todo", hiddenAt: null, archivedAt: null, conversationAgentId: null, + createdAt: new Date("2026-11-01"), updatedAt: new Date("2026-11-01"), isUnreadForMe: false, + }; } -function SidebarExample({ scenario }: Args) { - return
- {scenario === "classic" ? : } -
; + +function SidebarExample({ classic, narrow }: Args) { + return ( +
+ {classic ? : } +
+ ); } const meta = { id: "design-recent-subtasks", - title: "Oversight and operation/Navigation, profile, and announcements/Sidebar subtasks", + title: "Oversight and operation/Navigation, profile, and announcements/Sidebar Recents", component: SidebarExample, - args: { scenario: "expanded" }, + args: { classic: false, childOnly: false, empty: false, collapseSection: false, narrow: false, longTitles: false, focusChild: false }, parameters: { layout: "fullscreen", initialEntries: ["/PAP/issues/PAP-100"], paperclip: { capabilities: ["navigation-preferences/preferences", "tasks/organize"], status: "current", implementation: "production", boundary: "fixtures", - notes: "Live standard and Classic sidebar components with HTTP summary/child fixtures. Covers independent unread state, authorized-count display, ten-row paging, selected-child visibility, folding and read errors. Server route tests cover private/company boundaries and real unread/read receipts. Browser fixture navigation does not mount task detail or prove a live deployment.", + notes: "Standard and Classic sidebars render real navigation components with simulated summary responses and browser-local visit history. The fixtures cover flat task order, independent unread state, canceled tasks, and archive filtering.", } }, beforeEach: ({ args }) => { - const parent = task(0, args.scenario === "long" ? `${parentTitle} and verify every account can return to its saved project context` : parentTitle); - parent.isUnreadForMe = args.scenario === "parent-unread"; - const size = ["many", "all", "beyond-ten"].includes(args.scenario) ? 14 : args.scenario === "ten" ? 10 : 3; - const children = Array.from({ length: size }, (_, index) => { - const child = task(index + 1, args.scenario === "long" ? `Subtask ${index + 1}: Keep the saved workspace and all task navigation labels readable in a narrow sidebar` : `Subtask ${index + 1}`, parent.id); - child.isUnreadForMe = args.scenario !== "parent-unread" && index !== 0; - if (args.scenario === "statuses") child.status = (["in_progress", "in_review", "blocked"] as const)[index % 3]!; - return child; - }); - const second = task(30, "Prepare the release notes"); - const secondChildren = [task(31, "Review the change list", second.id)]; - const leaf = task(40, "Review the company dashboard"); - const roots = args.scenario === "empty" ? [] : args.scenario === "leaf" ? [leaf] - : args.scenario === "independent" ? [parent, second, leaf] : [parent, leaf]; - const activeChild = args.scenario === "beyond-ten" ? children[11] : args.scenario === "selected" ? children[1] : undefined; - const rows = [...roots, ...children, ...secondChildren]; + const parent = task(0, parentTitle); + const child = task(1, args.longTitles ? `${childTitle} and confirm the account returns to its last project` : childTitle, parent.id); + child.isUnreadForMe = true; + const completed = { ...task(2, "Review the company dashboard"), status: "done" as const }; + const cancelled = { ...task(3, "Canceled task"), status: "cancelled" as const }; + const archived = task(4, "Archived task"); + const recent = args.empty ? [] : args.childOnly ? [child] : [child, parent, completed, cancelled]; const savedKey = getRecentTasksStorageKey(companyId, userId); const saved = localStorage.getItem(savedKey); localStorage.removeItem(savedKey); - roots.forEach((row, index) => recordRecentTask(row, userId, 100 - index)); - // Exercise deduplication for a child which is also in local recent history. - if (roots.length && args.scenario !== "leaf") recordRecentTask(activeChild ?? children[0]!, userId, 200); + if (!args.empty) [archived, ...recent].forEach((row, index) => recordRecentTask(row, userId, 100 - index)); const fixture = prepareFixtureApi([ - { path: `/api/companies/${companyId}/issues/summaries`, read: ({ url }) => rows.filter(row => url.searchParams.get("ids")?.split(",").includes(row.id)).map(row => { - const subtasks = row.id === parent.id ? children : row.id === second.id ? secondChildren : []; - return { ...row, externalConversationState: null, subtaskCount: subtasks.length, unreadSubtaskCount: subtasks.filter(child => child.isUnreadForMe).length }; - }) }, - { path: `/api/companies/${companyId}/issues`, state: args.scenario === "loading" ? "loading" : args.scenario === "failure" ? "failure" : "ready", read: ({ url }) => { - const subtasks = url.searchParams.get("parentId") === second.id ? secondChildren : children; - const after = url.searchParams.get("afterId"); - const start = after ? subtasks.findIndex(child => child.id === after) + 1 : 0; - return args.scenario === "stale" ? [] : subtasks.slice(start, start + 10); - } }, + { path: `/api/companies/${companyId}/issues/summaries`, read: ({ url }) => [archived, ...recent] + .filter(row => url.searchParams.get("ids")?.split(",").includes(row.id)) + .map(row => ({ ...row, externalConversationState: null, isParticipantForMe: true, isArchivedForMe: row.id === archived.id, + subtaskCount: row.id === parent.id ? 2 : 0, + })) }, { path: `/api/companies/${companyId}/chats`, read: () => [] }, { path: `/api/companies/${companyId}/projects`, read: () => [] }, { path: `/api/companies/${companyId}/issues/chat-bootstrap`, read: () => ({ items: [] }) }, ]); - return () => { fixture.cleanup(); if (saved === null) localStorage.removeItem(savedKey); else localStorage.setItem(savedKey, saved); }; + return () => { + fixture.cleanup(); + if (saved === null) localStorage.removeItem(savedKey); + else localStorage.setItem(savedKey, saved); + }; }, play: async ({ args, canvasElement }) => { const canvas = within(canvasElement); - if (args.scenario === "empty") { await expect(canvas.queryByText("Recents")).toBeNull(); return; } - if (args.scenario === "leaf") { await expect(canvas.findByText("Review the company dashboard")).resolves.toBeVisible(); return; } - const fold = await canvas.findByRole("button", { name: new RegExp(`Collapse subtasks of ${parentTitle}`) }); - if (args.scenario === "collapsed" || args.scenario === "independent") await userEvent.click(fold); - if (args.scenario === "all") await userEvent.click(await canvas.findByRole("button", { name: /Show more/ })); - if (args.scenario === "keyboard") { fold.focus(); await expect(fold).toHaveFocus(); } - if (args.scenario === "section-collapsed") await userEvent.click(await canvas.findByRole("button", { name: "Collapse Recents" })); + if (args.empty) { + await expect(canvas.queryByRole("region", { name: "Recents" })).toBeNull(); + return; + } + + const child = await canvas.findByRole("link", { name: new RegExp(childTitle) }); + await expect(within(child).getByLabelText("Unread")).toBeVisible(); + if (args.childOnly) { + await expect(canvas.getAllByRole("link", { name: /workspace/ })).toEqual([child]); + await expect(child).toHaveAttribute("aria-current", "page"); + } else { + const parent = canvas.getByRole("link", { name: parentTitle }); + await expect(within(parent).queryByLabelText("Unread")).toBeNull(); + await expect(child.compareDocumentPosition(parent) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + await expect(canvas.getByRole("link", { name: "Review the company dashboard" })).toBeVisible(); + await expect(canvas.getByRole("link", { name: "Canceled task" })).toBeVisible(); + } + await expect(canvas.queryByRole("group", { name: /Subtasks of/ })).toBeNull(); + await expect(canvas.queryByRole("link", { name: "Archived task" })).toBeNull(); + + if (args.focusChild) { + child.focus(); + await expect(child).toHaveFocus(); + } + if (args.collapseSection) { + await userEvent.click(canvas.getByRole("button", { name: "Collapse Recents" })); + await expect(canvas.queryByRole("link", { name: new RegExp(childTitle) })).toBeNull(); + } }, } satisfies Meta; export default meta; type Story = StoryObj; + export const Expanded: Story = {}; -export const Collapsed: Story = { args: { scenario: "collapsed" } }; -export const ExactlyTen: Story = { args: { scenario: "ten" } }; -export const MoreThanTen: Story = { args: { scenario: "many" } }; -export const AllSubtasks: Story = { args: { scenario: "all" } }; -export const SelectedSubtask: Story = { args: { scenario: "selected" }, parameters: { initialEntries: ["/PAP/issues/PAP-102"] } }; -export const SelectedBeyondTen: Story = { args: { scenario: "beyond-ten" }, parameters: { initialEntries: ["/PAP/issues/PAP-112"] } }; -export const MixedStatuses: Story = { args: { scenario: "statuses" } }; -export const IndependentGroups: Story = { args: { scenario: "independent" } }; -export const LongTitles: Story = { args: { scenario: "long" } }; -export const Narrow: Story = { args: { scenario: "narrow" } }; -export const NoSubtasks: Story = { args: { scenario: "leaf" } }; -export const EmptyRecents: Story = { args: { scenario: "empty" } }; -export const Loading: Story = { args: { scenario: "loading" } }; -export const LoadFailed: Story = { args: { scenario: "failure" } }; -export const NoChildrenAvailable: Story = { args: { scenario: "stale" } }; -export const KeyboardFocus: Story = { args: { scenario: "keyboard" } }; -export const SectionCollapsed: Story = { args: { scenario: "section-collapsed" } }; -export const ParentUnreadChildrenRead: Story = { args: { scenario: "parent-unread" } }; -export const Classic: Story = { args: { scenario: "classic" } }; +export const SelectedSubtask: Story = { + args: { childOnly: true }, + parameters: { initialEntries: ["/PAP/issues/PAP-101"] }, +}; +export const LongTitles: Story = { args: { longTitles: true } }; +export const Narrow: Story = { args: { narrow: true, longTitles: true } }; +export const EmptyRecents: Story = { args: { empty: true } }; +export const KeyboardFocus: Story = { args: { focusChild: true } }; +export const SectionCollapsed: Story = { args: { collapseSection: true } }; +export const Classic: Story = { args: { classic: true } };