diff --git a/DESIGN.md b/DESIGN.md index d092f51a3b7..c057eda3204 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -710,6 +710,13 @@ Its sidebar groups Chat, Tasks and Needs you with space after New task and before More, and keeps global search beside the organization menu (below it in the collapsed rail). Recents appears only when it contains entries, without an empty state. +Task entries require the viewer's own participation under the Mine inbox rule, +regardless of inbox archive state. Automated provenance, account ownership and +read-only visits do not establish participation. A qualifying task's title and +status stay current, but passive visits and background updates do not promote it +above newer user activity. A first passive visit places a qualifying candidate +below existing history. Readable subtasks remain contextual navigation under a +qualifying parent. ### Reuse collection behavior as well as appearance diff --git a/doc/ui-internals.md b/doc/ui-internals.md index 28bade0628e..fdba5c49d3d 100644 --- a/doc/ui-internals.md +++ b/doc/ui-internals.md @@ -16,17 +16,31 @@ emits them under `ui/dist/fonts/`. The server package copies the same output int ## Recent task ordering -The streamlined sidebar keeps five recent tasks per company and account in browser -storage. It sorts by the newest observed task or comment activity, not by live-run -state. Older detail responses cannot move the stored activity time backward. +The streamlined sidebar keeps recent task candidates per company and account in browser +storage. A task appears only after the authenticated navigation summary confirms +personal participation using the same rule as Mine: manual creation, human assignment, +a direct comment, a meaningful audited action, or a live request addressed to the viewer. +Routine ownership, connected-account provenance and read-only visits do not qualify. +Inbox archive is independent of this personal history. Readable children remain +contextual navigation beneath a qualifying parent. + +Local human actions advance recency. Passive visits and background title, status +and readiness refreshes preserve the recorded time and never promote a task. +New passive candidates enter below existing history without using server update +time. A successful sidebar rename records explicit local human activity. Activity-only reorderings wait for one second without further activity changes; new and removed tasks appear immediately. Titles, status, and live indicators stay current during that delay. -The sidebar renders saved snapshots immediately and refreshes its exact five IDs -with one company/account-scoped summary query. Passive refreshes do not fetch +The sidebar validates saved candidates with company/account-scoped summary queries, +using bounded parallel chunks for long histories. Viewer participation and unread +facts are session data and are never trusted from browser storage. Passive refreshes do not fetch full task details or inspect workspaces. Successful omissions remove unavailable -tasks; failed batch reads retain saved history. Existing full-detail cache data +tasks and nonparticipants; failed batch reads retain saved history and any +previously confirmed session state, including after a change to the candidate batch. +These confirmed facts never cross account or company scopes. Unverified history +stays out of the visible list and does not affect the activity reorder delay. +Existing full-detail cache data can update an entry only after the current account's summary confirms access. The first healthy live subscription reconciles domain data without re-fetching session and health; reconnects and visibility recovery retain full reconciliation. diff --git a/packages/shared/src/types/issue.ts b/packages/shared/src/types/issue.ts index 7183a5a1123..d594c0037a8 100644 --- a/packages/shared/src/types/issue.ts +++ b/packages/shared/src/types/issue.ts @@ -901,6 +901,8 @@ export type IssueSummary = Pick< blockerAttention?: IssueBlockerAttention; /** Navigation-only projection. Counts include only readable direct children. */ parentId?: string | null; + /** Viewer participates under the Mine rule, regardless of inbox archive state. Navigation only. */ + isParticipantForMe?: 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 94413545c5e..f5e0ab59e8a 100644 --- a/server/src/__tests__/issue-summaries-routes.test.ts +++ b/server/src/__tests__/issue-summaries-routes.test.ts @@ -6,7 +6,7 @@ import { drizzle } from "drizzle-orm/postgres-js"; import * as schema from "@paperclipai/db/schema/index"; import { afterAll, beforeAll, expect, it, vi } from "vitest"; import { - activityLog, agents, chatConversations, chatEndpoints, companyMemberships, heartbeatRuns, issueComments, issueReadStates, issueRelations, issues, issueThreadInteractions, toolApplications, toolConnections, + activityLog, agents, chatConversations, chatEndpoints, companyMemberships, heartbeatRuns, issueComments, issueInboxArchives, issueReadStates, issueRelations, issues, issueThreadInteractions, toolApplications, toolConnections, } from "@paperclipai/db"; import { ISSUE_SUMMARIES_MAX_IDS } from "@paperclipai/shared"; import { issueRoutes } from "../routes/issues.js"; @@ -44,6 +44,39 @@ 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 () => { + const f = await fixture(); + const user = f.actor.userId!; + const names = ["manual", "routine", "github", "agent", "read", "comment", "edit", "assigned", "addressed", "other-request", "archived"]; + 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, + responsibleUserId: user, + assigneeUserId: title === "assigned" ? user : null, + }))).returning(); + const id = (name: string) => rows.find(row => row.title === name)!.id; + await ctx.db.insert(issueComments).values([ + { companyId: f.companyId, issueId: id("comment"), authorUserId: user, body: "Please do this." }, + { companyId: f.companyId, issueId: id("github"), authorUserId: user, metadata: { version: 1, sections: [], sourceChannel: "github" }, body: "Imported review" }, + ]); + await ctx.db.insert(activityLog).values([ + { companyId: f.companyId, entityType: "issue", entityId: id("read"), actorType: "user", actorId: user, action: "issue.read_marked" }, + { 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(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, + payload: { version: 1 as const, prompt: "Confirm." }, + }))); + 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"]); + expect(res.body.every((row: { isParticipantForMe: unknown }) => typeof row.isParticipantForMe === "boolean")).toBe(true); + }); + it("matches the inbox unread predicate across participation, request, withdrawal and read histories", async () => { const f = await fixture(); const user = f.actor.userId!; diff --git a/server/src/services/issue-summaries.ts b/server/src/services/issue-summaries.ts index dd931c91987..c098ea0d3dd 100644 --- a/server/src/services/issue-summaries.ts +++ b/server/src/services/issue-summaries.ts @@ -62,7 +62,7 @@ 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; total: number; unread_count: number; + kind: string; id: string; unread: boolean; participant: boolean; total: number; unread_count: number; }>(sql` with navigation_candidates as materialized ( select ${issues.id}, ${issues.parentId}, ${issues.conversationAgentId} @@ -71,6 +71,8 @@ export async function listIssueNavigationState( and (${issues.id} in (${requested}) or (${issues.parentId} in (${requested}) and ${issues.conversationAgentId} is null)) and ${readCondition} + ), navigation_participants as materialized ( + select c.id from navigation_candidates c where c.id in (select id from ${participation}) ), possible_unread as materialized ( -- A conservative set: any unread task must have a newer external -- comment, pending request, or withdrawal. The shared rule below still @@ -95,8 +97,7 @@ export async function listIssueNavigationState( and ${activityLog.details}->'receipt'->>'outcome' = 'withdrawn' and ${activityLog.createdAt} > coalesce(${issueReadStates.lastReadAt}, to_timestamp(0)) ), unread_participants as materialized ( - select possible.id from possible_unread possible - where possible.id in (select id from ${participation}) + select possible.id from possible_unread possible join navigation_participants p on p.id = possible.id ), navigation_comments as ( select ${issueComments.issueId} as id, max(${issueComments.createdAt}) filter (where ${issueComments.authorUserId} = ${userId} @@ -121,17 +122,19 @@ 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, 0 as total, 0 as unread_count - from navigation_candidates c left join navigation_state s on s.id = c.id where c.id in (${requested}) + 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 + 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, count(*)::int, count(*) filter (where s.unread)::int + select 'children', c.parent_id, 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 `); - const tasks = new Map(rows.filter(row => row.kind === "task").map(row => [row.id, row.unread])); + const tasks = new Map(rows.filter(row => row.kind === "task").map(row => [row.id, row])); const children = new Map(rows.filter(row => row.kind === "children").map(row => [row.id, row])); return new Map(ids.map(id => [id, { - isUnreadForMe: tasks.get(id) ?? false, + isParticipantForMe: tasks.get(id)?.participant ?? false, + isUnreadForMe: tasks.get(id)?.unread ?? false, subtaskCount: children.get(id)?.total ?? 0, unreadSubtaskCount: children.get(id)?.unread_count ?? 0, }])); diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index dfa279c54b1..073d42d1a47 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -413,7 +413,7 @@ "packages/shared/src/types/index.ts": "9c93d353993d6073389ae6dad752c7b8845377e1", "packages/shared/src/types/instance.ts": "ddabd7cc0d885b5fdf45b33a7937b7b704f8fb7d", "packages/shared/src/types/issue-tree-control.ts": "75489fffd491b8350b05caf57d7796419797d9df", - "packages/shared/src/types/issue.ts": "7183a5a11238c297e43917dc66897cbe73703835", + "packages/shared/src/types/issue.ts": "d594c0037a8d9882dc35d3ecd7cb8c276d7e2831", "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/ui/src/components/NewIssueDialog.tsx b/ui/src/components/NewIssueDialog.tsx index f55c57a1971..f54489c5932 100644 --- a/ui/src/components/NewIssueDialog.tsx +++ b/ui/src/components/NewIssueDialog.tsx @@ -648,7 +648,7 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) trackRecentProject(issue.projectId ?? "", companyId); if (issue.assigneeAgentId) trackRecentAssignee(issue.assigneeAgentId, companyId); if (issue.assigneeUserId) trackRecentAssigneeUser(issue.assigneeUserId, companyId); - if (streamlinedUiEnabled) recordRecentTask(issue, currentUserId); + if (streamlinedUiEnabled) recordRecentTask(issue, currentUserId, Date.now()); queryClient.invalidateQueries({ queryKey: queryKeys.issues.list(companyId) }); queryClient.invalidateQueries({ queryKey: queryKeys.issues.listMineByMe(companyId) }); queryClient.invalidateQueries({ queryKey: queryKeys.issues.listTouchedByMe(companyId) }); diff --git a/ui/src/components/SidebarRecentTasks.test.tsx b/ui/src/components/SidebarRecentTasks.test.tsx index f480a1976fb..61c15be5aba 100644 --- a/ui/src/components/SidebarRecentTasks.test.tsx +++ b/ui/src/components/SidebarRecentTasks.test.tsx @@ -69,7 +69,7 @@ describe("SidebarRecentTasks", () => { Object.values(mockIssuesApi).forEach((mock) => mock.mockReset()); mockIssuesApi.summaries.mockImplementation(async (_company: string, ids: string[]) => { const rows = await Promise.all(ids.map(id => mockIssuesApi.get.getMockImplementation()?.(id))); - return rows.filter(row => row && !row.hiddenAt); + return rows.filter(row => row && !row.hiddenAt).map(row => ({ ...row, isParticipantForMe: true })); }); container = document.createElement("div"); document.body.appendChild(container); @@ -134,7 +134,7 @@ describe("SidebarRecentTasks", () => { expect(container.textContent).not.toContain("Open or create a task"); }); it("keeps actions on both parent and nested child rows", async () => { - const parent = { id: "parent", companyId: "company-1", title: "Parent", identifier: "PAP-1", status: "todo" as const, updatedAt: new Date(1), subtaskCount: 1 }; + 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); @@ -149,7 +149,7 @@ describe("SidebarRecentTasks", () => { 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, + 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); @@ -203,7 +203,7 @@ describe("SidebarRecentTasks", () => { expect(actions?.className).toContain("opacity-0"); }); - it("keeps rows stable during alternating activity and applies the final order after quiet", async () => { + it("refreshes background activity without changing the personal order after quiet", async () => { const tasks = [1, 2, 3].map((id) => ({ id: `issue-${id}`, companyId: "company-1", @@ -214,7 +214,7 @@ describe("SidebarRecentTasks", () => { projectId: null, updatedAt: new Date(id), })); - tasks.forEach((task) => recordRecentTask(task, "user-1")); + tasks.forEach((task) => recordRecentTask(task, "user-1", task.updatedAt.getTime())); mockIssuesApi.get.mockImplementation(async (id: string) => tasks.find((task) => task.id === id)); const queryClient = await render(); const order = () => Array.from(container.querySelectorAll("a")).map((link) => link.getAttribute("href")); @@ -239,28 +239,29 @@ describe("SidebarRecentTasks", () => { await act(async () => { await vi.advanceTimersByTimeAsync(499); }); expect(order()).toEqual(originalOrder); await act(async () => { await vi.advanceTimersByTimeAsync(1); }); - expect(order()).toEqual(["/issues/PAP-2", "/issues/PAP-1", "/issues/PAP-3"]); + expect(order()).toEqual(originalOrder); expect(mockIssuesApi.get).not.toHaveBeenCalled(); expect(mockIssuesApi.summaries).toHaveBeenCalledTimes(1); queryClient.clear(); }); - it("adds and removes tasks immediately while an activity reorder is pending", async () => { + it("adds verified tasks and removes tasks while a personal activity reorder is pending", async () => { const task = (id: string, recordedAt: number) => ({ id, companyId: "company-1", title: id, identifier: id, status: "todo" as const, updatedAt: new Date(recordedAt), }); - recordRecentTask(task("first", 1), "user-1"); - recordRecentTask(task("second", 2), "user-1"); + recordRecentTask(task("first", 1), "user-1", 1); + recordRecentTask(task("second", 2), "user-1", 2); mockIssuesApi.get.mockImplementation(async (id: string) => task(id, 0)); const queryClient = await render(); vi.useFakeTimers(); - act(() => recordRecentTask(task("first", 3), "user-1")); + act(() => recordRecentTask(task("first", 3), "user-1", 3)); expect(container.querySelector("a")?.getAttribute("href")).toBe("/issues/second"); await act(async () => { - recordRecentTask(task("new", 4), "user-1"); - await vi.advanceTimersByTimeAsync(0); + recordRecentTask(task("new", 4), "user-1", 4); + await vi.advanceTimersByTimeAsync(10); }); + await act(async () => { await vi.advanceTimersByTimeAsync(10); }); expect(container.querySelector("a")?.getAttribute("href")).toBe("/issues/new"); act(() => pruneRecentTasks(getRecentTasksStorageKey("company-1", "user-1"), "company-1", new Set(["second"]))); expect(container.querySelector('a[href="/issues/second"]')).toBeNull(); @@ -358,8 +359,10 @@ describe("SidebarRecentTasks", () => { updatedAt: new Date(1), }; const renamedIssue = { ...issue, title: "New title", updatedAt: new Date(2) }; - recordRecentTask(issue, "user-1"); - mockIssuesApi.get.mockResolvedValue(issue); + const newer = { ...issue, id: "issue-2", identifier: "PAP-2", title: "Newer work" }; + recordRecentTask(issue, "user-1", 10); + recordRecentTask(newer, "user-1", 20); + mockIssuesApi.get.mockImplementation(async (id: string) => id === issue.id ? issue : newer); mockIssuesApi.update.mockResolvedValue(renamedIssue); const queryClient = await render(); @@ -383,6 +386,10 @@ describe("SidebarRecentTasks", () => { }); expect(mockIssuesApi.update).toHaveBeenCalledWith("issue-1", { title: "New title" }); + const stored = readRecentTasks(getRecentTasksStorageKey("company-1", "user-1"), "company-1"); + expect(stored.map(entry => entry.id)).toEqual(["issue-1", "issue-2"]); + expect(stored[0]?.recordedAt).toBeGreaterThan(20); + expect(stored[0]?.title).toBe("New title"); expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: queryKeys.issues.activity("issue-1"), }); @@ -518,7 +525,10 @@ describe("SidebarRecentTasks", () => { }); it("synchronizes recent tasks written by another tab", async () => { - mockIssuesApi.get.mockImplementation(() => new Promise(() => {})); + mockIssuesApi.get.mockResolvedValue({ + id: "issue-2", companyId: "company-1", title: "Cross-tab task", identifier: "PAP-2", + status: "todo", updatedAt: new Date(2), + }); await render(); const storageKey = getRecentTasksStorageKey("company-1", "user-1"); const entries = [{ @@ -533,8 +543,9 @@ describe("SidebarRecentTasks", () => { await act(async () => { window.localStorage.setItem(storageKey, JSON.stringify(entries)); window.dispatchEvent(new StorageEvent("storage", { key: storageKey })); - await Promise.resolve(); + await new Promise(resolve => setTimeout(resolve, 10)); }); + await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); }); expect(container.querySelector('a[href="/issues/PAP-2"]')?.textContent).toContain("Cross-tab task"); }); diff --git a/ui/src/components/SidebarRecentTasks.tsx b/ui/src/components/SidebarRecentTasks.tsx index 5033771ea73..509403b9351 100644 --- a/ui/src/components/SidebarRecentTasks.tsx +++ b/ui/src/components/SidebarRecentTasks.tsx @@ -10,7 +10,7 @@ import { useAccountIdentity } from "@/api/companies-query"; import { useSidebar } from "@/context/SidebarContext"; import { useOptionalToastActions } from "@/context/ToastContext"; import { - updateRecentTaskSnapshots, + recordRecentTask, type RecentTaskEntry, } from "@/lib/recent-tasks"; import { Button } from "@/components/ui/button"; @@ -108,7 +108,7 @@ function RecentTasksList({ liveIssueIds: ReadonlySet; rail: boolean; }) { - const { entries, storageKey } = useRecentTasks({ companyId, userId }); + const { entries } = useRecentTasks({ companyId, userId }); const { pathname } = useLocation(); const hierarchy = useMemo(() => recentTaskHierarchy(entries, pathname), [entries, pathname]); const queryClient = useQueryClient(); @@ -146,7 +146,7 @@ function RecentTasksList({ try { const updated = await issuesApi.update(renameEntry.id, { title: nextTitle }); queryClient.setQueryData(queryKeys.issues.detail(renameEntry.id), updated); - if (storageKey) updateRecentTaskSnapshots(storageKey, companyId, [updated]); + recordRecentTask(updated, userId, Date.now()); await refreshIssueQueries(renameEntry.id); setRenameEntry(null); toastActions?.pushToast({ title: "Task renamed", tone: "success" }); diff --git a/ui/src/hooks/useRecentTasks.test.tsx b/ui/src/hooks/useRecentTasks.test.tsx index ed6820c6480..e1090f3ba44 100644 --- a/ui/src/hooks/useRecentTasks.test.tsx +++ b/ui/src/hooks/useRecentTasks.test.tsx @@ -22,7 +22,7 @@ vi.mock("@/api/issues", () => ({ issuesApi: { get: getIssue, summaries } })); const task = (updatedAt: number, title: string, status: "todo" | "done" = "todo") => ({ id: "issue-1", companyId: "company-1", identifier: "TASK-1", title, status, - updatedAt: new Date(updatedAt), hiddenAt: null, projectId: null, + updatedAt: new Date(updatedAt), hiddenAt: null, projectId: null, isParticipantForMe: true, }); const storageKey = getRecentTasksStorageKey("company-1", "user-1"); // Node 24 uses jsdom Storage; newer Node versions use the setup's storage shim. @@ -159,7 +159,7 @@ describe("recent task synchronization", () => { )); await flush(); expect(readRecentTasks(storageKey, "company-1")).toHaveLength(1); - expect(container.textContent).toBe("Unavailable:todo"); + expect(container.textContent).toBe(""); expect(summaries).toHaveBeenCalledTimes(1); expect(getIssue).not.toHaveBeenCalled(); }); @@ -203,6 +203,94 @@ describe("recent task synchronization", () => { expect(summaries).not.toHaveBeenCalled(); }); + it.each(["account", "company"])("retains confirmed rows after a new batch fails, without crossing %s scopes", async (change) => { + const personal = task(10, "My work"); + recordRecentTask(personal, "user-1", 10); + summaries.mockResolvedValue([personal]); + const cache = client(); + await act(async () => root.render()); + await flush(); + expect(container.textContent).toBe("My work:todo"); + + summaries.mockRejectedValue(new ApiError("Unavailable", 503, null)); + await act(async () => { recordRecentTask({ ...task(20, "Unverified"), id: "unknown" }, "user-1"); }); + await flush(); + expect(container.textContent).toBe("My work:todo"); + expect(readRecentTasks(storageKey, "company-1")).toHaveLength(2); + + const companyId = change === "company" ? "company-2" : "company-1"; + const userId = change === "account" ? "user-2" : "user-1"; + recordRecentTask({ ...personal, companyId, title: "Unverified other scope" }, userId); + await act(async () => root.render()); + await flush(); + expect(container.textContent).toBe(""); + }); + + it("debounces personal reorders even when storage contains an unverified candidate", async () => { + const older = task(10, "Older"); + const newer = { ...task(20, "Newer"), id: "newer" }; + const unknown = { ...task(30, "Unverified"), id: "unknown", isParticipantForMe: undefined }; + [older, newer, unknown].forEach((issue, index) => recordRecentTask(issue, "user-1", index + 1)); + summaries.mockResolvedValue([older, newer, unknown]); + await act(async () => root.render()); + await flush(); + expect(container.textContent).toBe("Newer:todo,Older:todo"); + vi.useFakeTimers(); + try { + await act(async () => { recordRecentTask(older, "user-1", 100); }); + expect(container.textContent).toBe("Newer:todo,Older:todo"); + await act(async () => { await vi.advanceTimersByTimeAsync(999); }); + expect(container.textContent).toBe("Newer:todo,Older:todo"); + await act(async () => { await vi.advanceTimersByTimeAsync(1); }); + expect(container.textContent).toBe("Older:todo,Newer:todo"); + } finally { + vi.useRealTimers(); + } + }); + + it("hides unverified visits and removes automated history only after a successful participation read", async () => { + const personal = { ...task(10, "My work"), isParticipantForMe: true }; + const automated = { ...task(20, "Routine scan"), id: "routine", isParticipantForMe: false }; + recordRecentTask(personal, "user-1"); + recordRecentTask(automated, "user-1"); + let resolve!: (rows: unknown[]) => void; + summaries.mockReturnValueOnce(new Promise(done => { resolve = done; })).mockResolvedValue([personal]); + await act(async () => root.render()); + expect(container.textContent).toBe(""); + expect(readRecentTasks(storageKey, "company-1")).toHaveLength(2); + await act(async () => { resolve([personal, automated]); }); + await flush(); + expect(container.textContent).toBe("My work:todo"); + expect(readRecentTasks(storageKey, "company-1").map(entry => entry.id)).toEqual([personal.id]); + expect(readRecentTasks(storageKey, "company-1")[0]).not.toHaveProperty("isParticipantForMe"); + }); + + it("does not trust a participation flag from local storage or a full-detail cache", async () => { + localStorage.setItem(storageKey, JSON.stringify([{ ...task(10, "Imported review"), recordedAt: 10 }])); + const cache = client(); + cache.setQueryData(queryKeys.issues.detail("issue-1"), task(20, "Cached review")); + summaries.mockResolvedValue([{ ...task(30, "Review finished"), isParticipantForMe: false }]); + await act(async () => root.render()); + await flush(); + expect(container.textContent).toBe(""); + expect(readRecentTasks(storageKey, "company-1")).toEqual([]); + }); + + it("admits an automated task after the viewer participates despite a cached negative result", async () => { + const automated = { ...task(10, "Review"), isParticipantForMe: false }; + recordRecentTask(automated, "user-1"); + summaries.mockResolvedValue([automated]); + const cache = client(); + await act(async () => root.render()); + await flush(); + expect(readRecentTasks(storageKey, "company-1")).toEqual([]); + summaries.mockResolvedValue([{ ...automated, isParticipantForMe: true }]); + await act(async () => { recordRecentTask(automated, "user-1", 100); }); + await flush(); + expect(container.textContent).toBe("Review:todo"); + expect(readRecentTasks(storageKey, "company-1")[0]?.recordedAt).toBe(100); + }); + it("fetches a 25-task history in one request", async () => { const tasks = Array.from({ length: 25 }, (_, i) => ({ ...task(i + 1, `Task ${i}`), id: `issue-${String(i).padStart(2, "0")}` })); tasks.forEach(issue => recordRecentTask(issue, "user-1")); @@ -282,7 +370,7 @@ describe("recent task synchronization", () => { await act(async () => { resolveFirst([]); }); await flush(); expect(readRecentTasks(storageKey, "company-1").some(entry => entry.id === added.id)).toBe(true); - expect(container.textContent).toContain("New task"); + expect(container.textContent).not.toContain("New task"); }); it("isolates an account switch while the old request is pending", async () => { diff --git a/ui/src/hooks/useRecentTasks.ts b/ui/src/hooks/useRecentTasks.ts index e826bebf2f5..75746c0e35f 100644 --- a/ui/src/hooks/useRecentTasks.ts +++ b/ui/src/hooks/useRecentTasks.ts @@ -71,7 +71,6 @@ export function useRecentTasks({ }, [companyId, storageKey]); const queryIds = useMemo(() => entries.map((entry) => entry.id).sort(), [entries]); - const membership = JSON.stringify(queryIds); const scope = JSON.stringify([storageKey, queryIds]); const summaryKey = queryKeys.issues.summaryBatch(companyId ?? "__none__", userId, queryIds); // A cached omission predates IDs that the user has just added back. Only a @@ -103,29 +102,45 @@ export function useRecentTasks({ }, enabled: Boolean(companyId && queryIds.length), staleTime: 30_000, + // Membership changes can keep already verified personal rows visible while + // the new candidates load. Never carry facts across account/company scopes. + placeholderData: (previous, previousQuery) => previousQuery?.queryKey[1] === companyId + && previousQuery?.queryKey[3] === (userId ?? "__local_board__") ? previous : undefined, }); // Observe completion even when structural sharing preserves the data object. // The successful-update counter itself is only available on the cache state. const fetchingSummaries = summaryQuery.isFetching; const updateCount = queryClient.getQueryState(summaryKey)?.dataUpdateCount ?? 0; const summaries = summaryQuery.isSuccess ? summaryQuery.data : undefined; - // A failed background refresh must not flatten already loaded task groups. - // Only successful responses below may update/prune the stored history. - const confirmed = useMemo(() => new Map((summaryQuery.data ?? []).filter((issue) => issue.companyId === companyId) - .map((issue) => [issue.id, issue])), [summaryQuery.data, companyId]); - const refreshedEntries: RecentTaskEntry[] = useMemo(() => entries.map((entry) => { + const [lastConfirmed, setLastConfirmed] = useState<{ + storageKey: string | null; + summaries: IssueSummary[]; + } | null>(null); + useEffect(() => { + if (summaries && !summaryQuery.isPlaceholderData) setLastConfirmed({ storageKey, summaries }); + }, [summaries, summaryQuery.isPlaceholderData, storageKey]); + // Placeholder data disappears when a new batch fails. Keep the last successful + // authenticated batch for this scope, without admitting any new candidates. + 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]); + // 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 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; }), [entries, confirmed]); - const processed = useRef<{ scope: string; revision: number } | null>(null); + const processed = useRef<{ visit: typeof batchVisit; revision: number } | null>(null); useEffect(() => { - if (!storageKey || !companyId || !summaries) return; - if (processed.current?.scope === scope && processed.current.revision === updateCount) return; - processed.current = { scope, revision: updateCount }; - const returnedIds = new Set(summaries.filter((issue) => issue.companyId === companyId).map((issue) => issue.id)); + if (!storageKey || !companyId || !summaries || summaryQuery.isPlaceholderData) return; + if (processed.current?.visit === batchVisit && processed.current.revision === updateCount) return; + 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)); updateRecentTaskSnapshots(storageKey, companyId, summaries); const omittedIds = new Set(queryIds.filter((id) => !returnedIds.has(id))); if (omittedIds.size && updateCount <= batchVisit.initialUpdateCount) { @@ -136,12 +151,12 @@ export function useRecentTasks({ pruneRecentTasks(storageKey, companyId, omittedIds); // A storage notification must not republish the same successful revision. // eslint-disable-next-line react-hooks/exhaustive-deps - }, [batchVisit, companyId, fetchingSummaries, scope, updateCount, summaries, storageKey]); + }, [batchVisit, companyId, fetchingSummaries, scope, updateCount, summaries, storageKey, summaryQuery.isPlaceholderData]); useEffect(() => { if (!storageKey || !companyId || !summaries) return; const summaryById = new Map(summaries.filter((issue) => issue.companyId === companyId).map((issue) => [issue.id, issue])); - const authorizedIds = new Set(summaryById.keys()); + const authorizedIds = new Set([...summaryById.values()].filter(issue => issue.isParticipantForMe === true).map(issue => issue.id)); const mergeCached = (value: unknown) => { if (!value || typeof value !== "object") return; const issue = value as Issue; @@ -163,8 +178,9 @@ export function useRecentTasks({ }); }, [companyId, queryClient, summaries, storageKey]); - const [settledOrder, setSettledOrder] = useState(() => entries.map((entry) => entry.id)); - const activityRevision = JSON.stringify(entries.map((entry) => [entry.id, entry.recordedAt])); + const [settledOrder, setSettledOrder] = useState(() => refreshedEntries.map((entry) => entry.id)); + const membership = JSON.stringify(refreshedEntries.map((entry) => entry.id).sort()); + const activityRevision = JSON.stringify(refreshedEntries.map((entry) => [entry.id, entry.recordedAt])); useEffect(() => { const latestOrder = (JSON.parse(activityRevision) as Array<[string, number]>).map(([id]) => id); // Additions and removals are immediate. Only activity-driven moves wait for quiet. diff --git a/ui/src/lib/recent-tasks.test.ts b/ui/src/lib/recent-tasks.test.ts index 048bde18c3a..5918827bc86 100644 --- a/ui/src/lib/recent-tasks.test.ts +++ b/ui/src/lib/recent-tasks.test.ts @@ -54,6 +54,40 @@ describe("recent task persistence", () => { expect(entries.filter((entry) => entry.id === "4")).toHaveLength(1); }); + it("refreshes machine updates without moving a task above more recent personal work", () => { + const storageKey = getRecentTasksStorageKey("company-1", "user-1"); + recordRecentTask(issue("older"), "user-1", 10); + recordRecentTask(issue("newer"), "user-1", 20); + updateRecentTaskSnapshots(storageKey, "company-1", [{ + ...issue("older"), title: "Agent finished", status: "done", updatedAt: new Date(100), + }]); + recordRecentTask({ ...issue("older"), title: "Agent finished", status: "done", updatedAt: new Date(100) }, "user-1"); + expect(readRecentTasks(storageKey, "company-1").map(entry => entry.id)).toEqual(["newer", "older"]); + expect(readRecentTasks(storageKey, "company-1")[1]).toMatchObject({ + title: "Agent finished", status: "done", recordedAt: 10, snapshotUpdatedAt: 100, + }); + }); + + it("migrates v2 history once without accepting old-tab machine promotions", () => { + const key = getRecentTasksStorageKey("company-1", "user-1"); + const oldKey = "paperclip.recentTasks.v2:company-1:user-1"; + localStorage.setItem(oldKey, JSON.stringify([{ ...issue("1"), recordedAt: 10 }])); + migrateRecentTasks(key, "company-1"); + localStorage.setItem(oldKey, JSON.stringify([{ ...issue("2"), recordedAt: 100 }])); + migrateRecentTasks(key, "company-1"); + expect(readRecentTasks(key, "company-1").map(entry => entry.id)).toEqual(["1"]); + }); + + it("seeds passive visits below existing history independently of machine update times", () => { + const key = getRecentTasksStorageKey("company-1", "user-1"); + recordRecentTask(issue("personal"), "user-1", 10); + recordRecentTask({ ...issue("first-visit"), updatedAt: new Date(100) }, "user-1"); + recordRecentTask({ ...issue("second-visit"), updatedAt: new Date(1_000) }, "user-1"); + expect(readRecentTasks(key, "company-1").map(entry => entry.id)).toEqual(["personal", "first-visit", "second-visit"]); + recordRecentTask(issue("second-visit"), "user-1", 20); + expect(readRecentTasks(key, "company-1").map(entry => entry.id)).toEqual(["second-visit", "personal", "first-visit"]); + }); + it("refreshes conversation readiness when review or delivery changes without a task edit", () => { const task = { ...issue("1"), status: "in_review" as const, externalConversationState: "waiting" as const }; recordRecentTask(task, "user-1"); @@ -142,7 +176,7 @@ describe("recent task persistence", () => { id: "2", title: "Updated task", status: "in_progress", - recordedAt: 3, + recordedAt: 2, }), ]); }); @@ -191,7 +225,7 @@ describe("recent task persistence", () => { const storageKey = getRecentTasksStorageKey("company-1", "user-1"); const older = { ...issue("1"), title: "Old title", updatedAt: new Date(10) }; const newer = { ...issue("1"), title: "New title", status: "done" as const, updatedAt: new Date(20) }; - recordRecentTask(older, "user-1"); + recordRecentTask(older, "user-1", 10); updateRecentTaskSnapshots(storageKey, "company-1", [newer]); const setItem = vi.spyOn(storageMethods, "setItem"); const listener = vi.fn(); @@ -203,7 +237,7 @@ describe("recent task persistence", () => { updateRecentTaskSnapshots(storageKey, "company-1", [newer]); } expect(readRecentTasks(storageKey, "company-1")[0]).toMatchObject({ - title: "New title", status: "done", snapshotUpdatedAt: 20, recordedAt: 20, + title: "New title", status: "done", snapshotUpdatedAt: 20, recordedAt: 10, }); expect(setItem).not.toHaveBeenCalled(); expect(listener).not.toHaveBeenCalled(); diff --git a/ui/src/lib/recent-tasks.ts b/ui/src/lib/recent-tasks.ts index f80c4a6603c..1455c644d34 100644 --- a/ui/src/lib/recent-tasks.ts +++ b/ui/src/lib/recent-tasks.ts @@ -1,8 +1,8 @@ import type { Issue, IssueStatus, IssueSummary } from "@paperclipai/shared"; export const RECENT_TASKS_UPDATED_EVENT = "paperclip:recent-tasks-updated"; -const STORAGE_PREFIX = "paperclip.recentTasks.v2:"; -const LEGACY_STORAGE_PREFIX = "paperclip.recentTasks:"; +const STORAGE_PREFIX = "paperclip.recentTasks.v3:"; +const LEGACY_STORAGE_PREFIXES = ["paperclip.recentTasks.v2:", "paperclip.recentTasks:"]; export interface RecentTaskEntry { id: string; @@ -31,7 +31,7 @@ interface RecentTasksUpdatedDetail { } export function getRecentTasksStorageKey(companyId: string, userId: string | null | undefined) { - // Old tabs can still publish stale snapshots. Keep their writes out of v2. + // Old tabs still promote machine activity. Keep their writes out of v3. return `${STORAGE_PREFIX}${companyId}:${userId ?? "__local_board__"}`; } @@ -54,10 +54,10 @@ function isRecentTaskEntry(value: unknown, companyId: string): value is RecentTa export function readRecentTasks(storageKey: string, companyId: string): RecentTaskEntry[] { if (typeof window === "undefined") return []; try { - const legacyKey = storageKey.startsWith(STORAGE_PREFIX) - ? LEGACY_STORAGE_PREFIX + storageKey.slice(STORAGE_PREFIX.length) - : storageKey; - const raw = window.localStorage.getItem(storageKey) ?? window.localStorage.getItem(legacyKey); + const keys = storageKey.startsWith(STORAGE_PREFIX) + ? [storageKey, ...LEGACY_STORAGE_PREFIXES.map(prefix => prefix + storageKey.slice(STORAGE_PREFIX.length))] + : [storageKey]; + const raw = keys.map(key => window.localStorage.getItem(key)).find(value => value !== null); const parsed = JSON.parse(raw ?? "[]") as unknown; if (!Array.isArray(parsed)) return []; return normalizeRecentTasks( @@ -139,23 +139,25 @@ export function mergeRecentTaskSnapshot(entry: RecentTaskEntry, issue: TaskSnaps externalConversationState: issue.externalConversationState, blockerAttention: issue.blockerAttention, snapshotUpdatedAt, - recordedAt: Math.max(entry.recordedAt, snapshotUpdatedAt), }; } export function recordRecentTask( issue: Pick, userId: string | null | undefined, - recordedAt = new Date(issue.updatedAt).getTime(), + recordedAt?: number, ) { if (issue.conversationAgentId) return; const storageKey = getRecentTasksStorageKey(issue.companyId, userId); const current = readRecentTasks(storageKey, issue.companyId); const existing = current.find((candidate) => candidate.id === issue.id); - const activityAt = Number.isFinite(recordedAt) - ? recordedAt - : existing?.recordedAt ?? Date.now(); const snapshotUpdatedAt = new Date(issue.updatedAt).getTime(); + // Passive reads can seed a candidate, but only explicit local human actions + // advance its recency. New passive candidates go below existing history; + // their server update times are not personal activity. + const activityAt = recordedAt !== undefined && Number.isFinite(recordedAt) + ? recordedAt + : existing?.recordedAt ?? Math.min(0, (current.at(-1)?.recordedAt ?? 1) - 1); const snapshot: RecentTaskEntry = existing ? mergeRecentTaskSnapshot(existing, issue) : { id: issue.id, companyId: issue.companyId, diff --git a/ui/src/pages/IssueDetail.test.tsx b/ui/src/pages/IssueDetail.test.tsx index c2547cdda51..7b2091a5347 100644 --- a/ui/src/pages/IssueDetail.test.tsx +++ b/ui/src/pages/IssueDetail.test.tsx @@ -51,7 +51,7 @@ import { readIssueDetailBreadcrumb, rememberIssueDetailLocationState, } from "../lib/issueDetailBreadcrumb"; -import { getRecentTasksStorageKey, readRecentTasks } from "../lib/recent-tasks"; +import { getRecentTasksStorageKey, readRecentTasks, recordRecentTask } from "../lib/recent-tasks"; import { getLastProjectId, trackRecentProject } from "../lib/recent-projects"; import { ApiError } from "../api/client"; import type { issuesApi } from "../api/issues"; @@ -3145,7 +3145,7 @@ describe("IssueDetail", () => { expect(mockSetPanelVisible).toHaveBeenCalledWith(true); }); - it("uses task activity for recency and ignores passive revisits", async () => { + it("refreshes task snapshots without promoting background activity or passive revisits", async () => { const authRequest = createDeferred<{ session: { userId: string }; user: { id: string }; @@ -3185,7 +3185,7 @@ describe("IssueDetail", () => { id: "issue-1", title: "Initial recent title", status: "todo", - recordedAt: 100, + recordedAt: 0, }), ]); }); @@ -3208,10 +3208,42 @@ describe("IssueDetail", () => { ).toMatchObject({ title: "Snapshot refresh title", status: "in_progress", - recordedAt: 200, + recordedAt: 0, }); }); + 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()]); + mockIssuesApi.get.mockResolvedValue(issue); + mockIssuesApi.getCore.mockResolvedValue(issue); + mockIssuesApi.update.mockReturnValue(save.promise); + recordRecentTask(issue, "user-1", 10); + recordRecentTask(createIssue({ id: "newer-work" }), "user-1", 20); + await act(async () => renderIssueView()); + await waitForAssertion(() => expect(mockIssueChatThreadRender).toHaveBeenCalled()); + const props = mockIssueChatThreadRender.mock.calls.at(-1)![0]; + let pending!: Promise; + await act(async () => { + pending = props.onAdd(comment.body, false, + mode === "reassignment" ? { assigneeAgentId: "agent-1", assigneeUserId: null } : undefined, + undefined, "recency-comment", + 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); + }); + it.each([false, true])("renders a linked Decisions-v1 record in task context (Coordinator %s)", async (enabled) => { coordinatorPreference.enabled = enabled; mockLocation.hash = "#decision-recorded-1"; diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx index bce716f434d..935b43f473d 100644 --- a/ui/src/pages/IssueDetail.tsx +++ b/ui/src/pages/IssueDetail.tsx @@ -3836,6 +3836,8 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS const currentUserId = session?.user?.id ?? session?.session?.userId ?? 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]); const { data: boardAccess } = useQuery({ @@ -4655,7 +4657,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS if (nextIssue.identifier) issueRefs.add(nextIssue.identifier); mergeIssueResponseIntoCaches(issueRefs, nextIssue); if (streamlinedUiEnabled && sessionResolved) { - recordRecentTask(nextIssue, currentUserId); + recordRecentTask(nextIssue, currentUserId, Date.now()); } queryClient.invalidateQueries({ queryKey: queryKeys.issues.activity(issueId!), @@ -5691,6 +5693,9 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS if (!historyExpanded) { await queryClient.invalidateQueries({ queryKey: queryKeys.issues.comments(issueId!), exact: true, refetchType: "none" }); } + if (streamlinedUiEnabled && sessionResolved) { + recordRecentTask(nextIssue, currentUserId, new Date(comment.createdAt).getTime()); + } } if (context?.optimisticCommentId) { setOptimisticComments((current) =>