From 5b750fdf25f773adccf68a72ab9cf2952922cce2 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 08:51:04 -0600 Subject: [PATCH] feat(ui): add foldable sidebar subtasks with bounded refreshes (#21649) ## Thinking Path > - Paperclip helps people manage AI agents for work. > - The sidebar helps people return to recent tasks. > - Recent parents need foldable child tasks. > - Busy companies must not refresh every child group for unrelated work. > - Exact unread counts must preserve personal reads and task access. > - This pull request adds child groups and bounds their refresh work. > - People can scan subtasks without repeated background requests. ## Linked Issues or Issue Description **Subsystem affected** Task navigation in the standard and Classic sidebars. **Problem or motivation** Recent parent tasks did not show their subtasks. The first implementation refreshed every previously viewed group. One unrelated update caused 52 child-page requests and one summary request after viewing 50 groups. Exact child counts also repeated privacy and unread checks per child. **Proposed solution** Show direct subtasks with independent folding and ten-row pages. Refresh affected groups and summary batches. Stop offscreen reads. Bound child-request concurrency. Aggregate viewer facts once and preserve the existing inbox unread rule. **Roadmap alignment** This extends existing task navigation. The existing feature PR is reused for its performance repair. No new PR duplicates it. ## What Changed - Add shared parent groups to both sidebar layouts. Preserve Classic row actions and active-child visibility. - Keep unread state personal to each task. Folding and paging do not mark tasks read. Counts include readable children beyond ten. - Target live refreshes with authorized current and previous parent IDs. Reuse parent metadata from the narrow run-binding read. Resolve fallback lookups once per delivery batch. Keep the previous summary fallback for older servers. - Limit child requests to three at a time. Cancel active and queued reads when groups leave the viewport. - Discard extra cached pages on Show less and collapse. - Compute exact navigation counts in one SQL statement. Materialize readable candidate IDs once. Use indexed participation sources and conservative unread candidates before the shared inbox rule. - Skip recursive privacy walks for standalone open tasks without a project. Keep the recursive rule for all restricted or inherited shapes and all delegated principals. - Add request-count, cancellation, reparenting, read-receipt, inbox-parity and privacy regressions. Include a disposable PostgreSQL benchmark. - Update product and API documentation. Retain the production Storybook states. ## Verification - Published head: `4148861437c1b6b635479ad92509dbc71155a232`. Its tree matches local `04be9d66d481d9bcd1c4d6158acf063a1e65ac7e`: `a23533e93d3d155918f0254d296a7fd2f0c7c12f`. - Rebased on master `ca23330c69b1f2b25bdadfcbda68317db97deaef`. Remote publication preserves prior feature commits. - The request regression failed before the fix and passes after it. An unrelated event now sends zero child requests. Current servers also avoid the unrelated summary request. Old-server events keep one summary fallback. - A relevant update after Show less reads one page. Reparenting refreshes two affected groups. Offscreen reads stay at zero and resume once on return. Active and queued cancellation tests pass. - The same synthetic authenticated HTTP workload with 50,000 read children improved from 767 ms to 92.84 ms median. Five warm samples per case. The all-unread case improved from 463.85 to 351.65 ms. Untouched children improved from 208.01 to 131.09 ms. The old-receipt case improved from 799.70 to 245.80 ms. These local measurements are not a production capacity guarantee. - Focused PostgreSQL routes, inbox-parity, privacy and WebSocket tests passed: 38 tests. - All 325 affected UI tests passed. All 38 focused PostgreSQL, privacy and WebSocket tests passed. UI typecheck and low-memory server declaration checks passed. - All 41 Chromium Storybook checks passed. They cover 20 states in both themes and keyboard, folding, paging and unread behavior. They use production components with HTTP fixtures. - Both new review findings failed as regressions before their fixes and pass afterward. Explicit child reads include waiting external conversations. Deleting a child publishes a separate parent-authorized update without deleted-child content. Both review threads are resolved. - `pnpm verify --explain` returned exit 2 because product documentation requires broader CI. [The prior CI run](https://github.com/paperclipai/paperclip/actions/runs/43711489306) found type errors in the new test fixtures. The same errors failed locally. The fixture fix passes `node server/scripts/typecheck-layers.mjs --layer test-tree-0` and all 21 issue summary route tests. Production code is unchanged. That CI run then found a live-delivery read regression. The existing test failed locally with eight statements against its six-statement budget. A new PostgreSQL regression also found three parent lookups for two same-batch calls. Run delivery now reuses parent metadata from its narrow run-binding query. Fallback lookups resolve to one promise. Both regressions pass without increasing the budgets. All 74 targeted route, WebSocket and privacy tests pass. The affected below, above and test-tree-0 typecheck layers pass. [CI attempt 2](https://github.com/paperclipai/paperclip/actions/runs/43715541480/attempts/2) passes on the published head. All 62 check runs are terminal and clean: 57 succeeded, two were neutral and three were skipped. Typecheck, build, policy, all general and serialized server suites, E2E and the [final verify gate](https://github.com/paperclipai/paperclip/actions/runs/43715541480/job/132829783231) pass. The separate security status passes. Attempt 1's server shard 7/12 reached its 20-minute job limit without a test verdict. One retry of that job passed without a source change. [Greptile completed successfully on this head](https://github.com/paperclipai/paperclip/runs/132816163906) with a [5/5 score](https://github.com/paperclipai/paperclip/pull/21649#issuecomment-6883916606). All five review threads are resolved. The final CI gate is complete. - A full local Storybook build exceeded available memory while server typechecking ran. Browser verification uses the current-source development server. Rebuilding stale Runner and SDK declarations resolved the initial server check errors. The first browser attempt lacked Chromium; all checks passed after installation. - Reproduce the database measurements with `pnpm --filter @paperclipai/server exec tsx scripts/benchmark-sidebar-subtasks.ts`. - Extra local shard diagnosis ran 164 suites. Under this shell's `0077` creation mask, 157 suites passed and three had fixture permission or timing failures. Rerunning those three with `0022` resolved the permission failures. The remaining ten cases passed with one worker: two workspace cases and eight archive cases. The eight archive cases also passed on the pre-performance-fix revision, whose archive source is identical. The broad local shard is not claimed as one passing execution. The same-head CI retry supplies complete final CI coverage. - Nothing is merged or deployed. ## Risks - Exact counts still grow with the readable hierarchy and comment history. The change reduces repeated work; it does not cap or approximate counts. - A relevant summary batch can contain several recent parents. Older servers retain a broader summary fallback until upgraded. - Live delivery adds bounded, permission-checked parent lookups. Short delivery-window reuse limits repeated reads. - The authorization fast path applies only to open tasks with no privacy parent and no project. Restricted cases retain the shared predicate. - No migration is required. ## Model Used OpenAI Codex, based on GPT-6. Used code execution, native GitHub tools, PostgreSQL and Chromium verification. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either linked a public issue or described the issue in this PR - [x] I have not referenced internal or instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal issue id - [x] I have run focused tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation - [x] I have considered and documented risks - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open findings - [x] I will address all review comments before requesting merge --------- Co-authored-by: Paperclip --- doc/PRODUCT.md | 16 ++ docs/api/issues.md | 14 ++ packages/shared/src/types/issue.ts | 5 + packages/shared/src/validators/issue.ts | 1 + server/scripts/benchmark-sidebar-subtasks.ts | 113 +++++++++++++ .../authorization-privacy-query.test.ts | 3 + .../__tests__/issue-summaries-routes.test.ts | 150 +++++++++++++++++- .../__tests__/live-events-run-read.test.ts | 8 +- server/src/realtime/live-events-ws.ts | 25 ++- server/src/realtime/recent-subtask-parents.ts | 33 ++++ server/src/routes/issues.ts | 42 ++++- server/src/services/authorization.ts | 9 +- server/src/services/issue-participation.ts | 6 +- server/src/services/issue-summaries.ts | 102 +++++++++++- server/src/services/issues.ts | 38 +++-- .../runner-e2e/source-sdk-public-inputs.json | 4 +- .../storybook-visual/recent-subtasks.spec.ts | 65 ++++++++ ui/src/api/issues.ts | 6 +- ui/src/components/CoordinatorSidebar.test.tsx | 73 +++++++++ ui/src/components/CoordinatorSidebar.tsx | 15 +- .../RecentTaskGroup.performance.test.tsx | 140 ++++++++++++++++ ui/src/components/RecentTaskGroup.tsx | 120 ++++++++++++++ ui/src/components/RecentTaskNavItem.tsx | 11 +- ui/src/components/SidebarRecentTasks.test.tsx | 27 ++++ ui/src/components/SidebarRecentTasks.tsx | 128 ++++++++------- .../LiveUpdatesProvider.read-receipts.test.ts | 7 +- ui/src/context/LiveUpdatesProvider.test.ts | 29 +++- ui/src/context/LiveUpdatesProvider.tsx | 18 ++- ui/src/hooks/useRecentTasks.test.tsx | 20 +++ ui/src/hooks/useRecentTasks.ts | 29 ++-- ui/src/index.css | 3 + ui/src/lib/recent-subtask-requests.test.ts | 30 ++++ ui/src/lib/recent-subtask-requests.ts | 34 ++++ ui/src/lib/recent-subtasks-refresh.ts | 53 +++++++ ui/src/lib/recent-task-hierarchy.test.ts | 32 ++++ ui/src/lib/recent-task-hierarchy.ts | 44 +++++ ui/src/lib/recent-tasks.ts | 5 + ui/src/pages/IssueDetail.tsx | 6 +- .../recent-subtasks.stories.tsx | 107 +++++++++++++ 39 files changed, 1454 insertions(+), 117 deletions(-) create mode 100644 server/scripts/benchmark-sidebar-subtasks.ts create mode 100644 server/src/realtime/recent-subtask-parents.ts create mode 100644 tests/storybook-visual/recent-subtasks.spec.ts create mode 100644 ui/src/components/RecentTaskGroup.performance.test.tsx create mode 100644 ui/src/components/RecentTaskGroup.tsx create mode 100644 ui/src/lib/recent-subtask-requests.test.ts create mode 100644 ui/src/lib/recent-subtask-requests.ts create mode 100644 ui/src/lib/recent-subtasks-refresh.ts create mode 100644 ui/src/lib/recent-task-hierarchy.test.ts create mode 100644 ui/src/lib/recent-task-hierarchy.ts create mode 100644 ui/storybook/stories/navigation-preferences/recent-subtasks.stories.tsx diff --git a/doc/PRODUCT.md b/doc/PRODUCT.md index e9e562d983a..ed26afbd17b 100644 --- a/doc/PRODUCT.md +++ b/doc/PRODUCT.md @@ -98,6 +98,22 @@ 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. +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. + Agent-owned tasks show **In Progress** only while a task-linked run is queued or running. When execution ends, their visible status reflects recovery (**Blocked**), a pending response or review (**In Review**), monitoring, or diff --git a/docs/api/issues.md b/docs/api/issues.md index 9be228b683f..dac6071142c 100644 --- a/docs/api/issues.md +++ b/docs/api/issues.md @@ -22,6 +22,7 @@ Query parameters: | `ids` | One to 100 comma-separated task UUIDs; requires `view=index` or `view=rows` without `attention` | | `parentIds` | One to 100 comma-separated parent UUIDs for batched child context; same projection restriction as `ids` | | `oneChildPerParent` | With `view=index` and `parentIds`, return at most one readable child per parent for collapsed-tree affordances | +| `includeReadState` | Board-only `true` adds the current user's personal read state without removing read or untouched tasks | Results sorted by priority. @@ -31,6 +32,19 @@ endpoint for its instruction and related content. Company and private-task acces checks apply before results are returned. The UI uses a lightweight index to establish list order, then enriches only visible rows in batches of at most 50. +## Navigation summaries + +`GET /api/companies/{companyId}/issues/summaries?ids={comma-separated UUIDs}` +returns a bounded title/status projection. Missing, hidden, and unreadable tasks +are omitted. The response does not include task bodies or mark tasks read. + +Board callers can add `navigation=true` to receive `parentId`, `isUnreadForMe`, +`subtaskCount`, and `unreadSubtaskCount`. Counts include readable direct children +only. Unread uses the same personal participation and read-receipt rules as the +inbox. A parent read receipt does not mark children read. Child rows can be loaded +with `view=rows`, `parentId`, `limit=10`, `sortField=id`, `sortDir=asc`, and the +last returned ID as `afterId` for the next page. + ## Get Issue ``` diff --git a/packages/shared/src/types/issue.ts b/packages/shared/src/types/issue.ts index 51b3c3e22ad..7183a5a1123 100644 --- a/packages/shared/src/types/issue.ts +++ b/packages/shared/src/types/issue.ts @@ -899,6 +899,11 @@ export type IssueSummary = Pick< externalConversationState: "active" | "waiting" | null; /** Present for blocked tasks so summary views resolve the same status glyph as detail views. */ blockerAttention?: IssueBlockerAttention; + /** Navigation-only projection. Counts include only readable direct children. */ + parentId?: string | null; + isUnreadForMe?: boolean; + subtaskCount?: number; + unreadSubtaskCount?: number; }; export interface Issue { diff --git a/packages/shared/src/validators/issue.ts b/packages/shared/src/validators/issue.ts index 120ffa23b57..9877f071ad9 100644 --- a/packages/shared/src/validators/issue.ts +++ b/packages/shared/src/validators/issue.ts @@ -50,6 +50,7 @@ import { objectWithoutDefaults } from "./partial.js"; import { questionSetToAskUserQuestionsPayload } from "../question-set.js"; export const issueSummariesQuerySchema = z.object({ + navigation: z.literal("true").optional(), ids: z.string().transform((value) => value.split(",").map((id) => id.trim().toLowerCase())) .pipe(z.array(z.string().guid()).min(1).max(ISSUE_SUMMARIES_MAX_IDS)) .transform((ids) => [...new Set(ids)]), diff --git a/server/scripts/benchmark-sidebar-subtasks.ts b/server/scripts/benchmark-sidebar-subtasks.ts new file mode 100644 index 00000000000..745a2a9b26d --- /dev/null +++ b/server/scripts/benchmark-sidebar-subtasks.ts @@ -0,0 +1,113 @@ +import assert from 'node:assert/strict'; +import { randomUUID } from 'node:crypto'; +import { mkdir, writeFile } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { performance } from 'node:perf_hooks'; +import express from 'express'; +import { drizzle } from 'drizzle-orm/postgres-js'; +import { createDb, startEmbeddedPostgresTestDatabase } from '../../packages/db/src/index.ts'; +import { issueRoutes } from '../../server/src/routes/issues.ts'; +import { errorHandler } from '../../server/src/middleware/index.ts'; +import { seedIssueReadVisibilityFixture } from '../../server/src/__tests__/helpers/issue-read-visibility-fixture.ts'; +import { listIssueNavigationState } from '../../server/src/services/issue-summaries.ts'; +import { issueReadSqlCondition } from '../../server/src/services/authorization.ts'; + +// Run from the server package: pnpm --filter @paperclipai/server exec tsx scripts/benchmark-sidebar-subtasks.ts +// All data is synthetic. The temporary PostgreSQL cluster is removed in finally. +const directory = resolve(process.env.PAPERCLIP_BENCHMARK_OUTPUT ?? '../test-results/sidebar-subtasks-benchmark'); +await mkdir(directory, { recursive: true }); +const out = pathToFileURL(directory + '/'); +const report: any = { synthetic: true, node: process.version, pool: 10, samples: 5, cases: [] }; +const keeper = setInterval(() => {}, 1000); +const fixture = await startEmbeddedPostgresTestDatabase('sidebar-subtasks-perf-'); +const db = createDb(fixture.connectionString, { maxConnections: 10 }); +const client = db.$client; +const statements: Array<{query: string; params: unknown[]}> = []; +let record = false; +const counted = drizzle(client, { schema: db._.fullSchema, logger: { logQuery(query, params) { if (record) statements.push({query, params}); } } }) as typeof db; +let server: ReturnType['listen'] extends (...a:any[]) => infer R ? R : never; +const stats = (xs: number[]) => { const s = [...xs].sort((a,b)=>a-b); return {medianMs:+s[Math.floor(s.length/2)]!.toFixed(2), maxMs:+s.at(-1)!.toFixed(2), samplesMs:xs.map(x=>+x.toFixed(2))}; }; +try { + process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = 'enforce'; + const f = await seedIssueReadVisibilityFixture(db, {publicCount: 50}); + const actor = f.actors['cloud tenant owner']; + const userId = (actor as any).userId!; + const parents = f.publicIds; + // Make each measured parent independent and participated-in by this viewer. + await client.unsafe('update issues set parent_id=null, created_by_user_id=$2 where company_id=$1 and id=any($3::uuid[])',[f.companyId,userId,parents]); + await client.unsafe(`create table perf_parents as select id from issues where id=any($1::uuid[])`,[parents]); + await client.unsafe(`insert into issues (company_id,title,status,created_by_user_id) select $1,'Unrelated history '||n,'done',$2 from generate_series(1,20000)n`,[f.companyId,f.strangerUserId]); + await client.unsafe(`insert into activity_log(company_id,actor_type,actor_id,action,entity_type,entity_id,created_at) select $1,'system','synthetic-agent','issue.updated','issue',$2,now() from generate_series(1,100000)n`,[f.companyId,parents[0]]); + const connections=await Promise.all(Array.from({length:10},()=>client.reserve())); + for(const connection of connections){await connection.unsafe("set statement_timeout='20s'");connection.release();} + const app=express(); + app.use((req,_res,next)=>{req.actor=actor as any;next();}); + app.use('/api',issueRoutes(counted,{} as never)); app.use(errorHandler); + server=app.listen(0,'127.0.0.1'); await new Promise(r=>server.once('listening',r)); + const origin=`http://127.0.0.1:${(server.address() as any).port}`; + const summaryPath=`/api/companies/${f.companyId}/issues/summaries?ids=${parents.join(',')}`; + async function read(path:string) {const r=await fetch(origin+path);const body=await r.json();assert.equal(r.status,200,JSON.stringify(body));return body;} + async function measure(path:string) {await read(path);const times=[];for(let n=0;n<5;n++){const t=performance.now();await read(path);times.push(performance.now()-t);}record=true;statements.length=0;const body=await read(path);record=false;return {time:stats(times),statements:statements.length,sqlBytes:statements.reduce((n,x)=>n+Buffer.byteLength(x.query),0),responseBytes:Buffer.byteLength(JSON.stringify(body)),body};} + report.postgres=(await client.unsafe('select version()'))[0]!.version; + report.fixture={parents:50,noiseIssues:20000,noiseActivity:100000,privacy:'enforce',actor:'cloud tenant owner',commentBytes:128}; + let previous=0; + for(const perParent of [0,10,100,1000]) { + if(perParent>previous) { + await client.unsafe(`insert into issues(company_id,parent_id,title,status,created_by_user_id,created_at,updated_at) + select $1,p.id,'Synthetic child '||n,'todo',$2,'2026-01-01','2026-01-01' from perf_parents p cross join generate_series($3::int,$4::int)n`,[f.companyId,userId,previous+1,perParent]); + // One external comment per child, deliberately all read: the unread test + // must check its pending/withdrawal branches rather than short-circuit. + await client.unsafe(`insert into issue_comments(company_id,issue_id,author_user_id,body,created_at) + select $1,i.id,$2,repeat('x',128),'2026-01-02' from issues i where i.company_id=$1 and i.parent_id=any($3::uuid[]) and not exists(select 1 from issue_comments c where c.issue_id=i.id)`,[f.companyId,f.strangerUserId,parents]); + await client.unsafe(`insert into issue_read_states(company_id,issue_id,user_id,last_read_at) + select $1,i.id,$2,'2026-01-03' from issues i where i.company_id=$1 and i.parent_id=any($3::uuid[]) on conflict(company_id,issue_id,user_id) do nothing`,[f.companyId,userId,parents]); + } + await client.unsafe('vacuum analyze'); + const base=await measure(summaryPath); + const nav=await measure(summaryPath+'&navigation=true'); + for(const row of nav.body) {assert.equal(row.subtaskCount,perParent);assert.equal(row.unreadSubtaskCount,0);} + const plans: any[]=[]; + for(const [index,s] of statements.entries()) { + const plan=await client.unsafe('explain (analyze,buffers,format json) '+s.query,s.params as any[]); + plans.push({index,sql:s.query,plan:plan[0]['QUERY PLAN']}); + } + await writeFile(new URL(`plans-${perParent}.json`,out),JSON.stringify(plans,null,2)); + const childPath=`/api/companies/${f.companyId}/issues?parentId=${parents[0]}&view=rows&limit=10&sortField=id&sortDir=asc&includeRoutineExecutions=true&includeReadState=true`; + const page=perParent?await measure(childPath):null; + const item={childrenPerParent:perParent,totalCountedChildren:perParent*50,baseline:{...base,body:undefined},navigation:{...nav,body:undefined},firstChildPage:page?{...page,body:undefined,rows:page.body.length}:null}; + report.cases.push(item);console.log(JSON.stringify(item)); + await writeFile(new URL('database-results.json',out),JSON.stringify(report,null,2)); + previous=perParent; + } + // Compare the same large hierarchy when children are unread and when they + // have never been touched by this person. + for(const state of ['unread','untouched']) { + if(state==='unread') await client.unsafe(`update issue_read_states set last_read_at='2026-01-01' where company_id=$1`,[f.companyId]); + else await client.unsafe(`update issues set created_by_user_id=$2 where company_id=$1 and parent_id=any($3::uuid[])`,[f.companyId,f.strangerUserId,parents]); + await client.unsafe('vacuum analyze'); + const m=await measure(summaryPath+'&navigation=true'); + assert.ok(m.body.every((x:any)=>x.unreadSubtaskCount===(state==='unread'?1000:0))); + const plans=[]; + for(const [index,s] of statements.entries()) { + const plan=await client.unsafe('explain (analyze,buffers,format json) '+s.query,s.params as any[]); + plans.push({index,sql:s.query,plan:plan[0]['QUERY PLAN']}); + } + await writeFile(new URL(`plans-${state}.json`,out),JSON.stringify(plans,null,2)); + const item={state,childrenPerParent:1000,...m,body:undefined};report.cases.push(item);console.log(JSON.stringify(item)); + } + // A mature viewer's old withdrawal receipts exercise the indexed JSON lookup. + await client.unsafe(`insert into activity_log(company_id,actor_type,actor_id,action,entity_type,entity_id,details,created_at) + select $1,'user',$2,'issue.thread_interaction_withdrawn','issue',$3,jsonb_build_object('handledForUserId',$2::text,'receipt',jsonb_build_object('outcome','withdrawn','issueId',$3::text)),'2025-12-01' from generate_series(1,5000)n`,[f.companyId,userId,parents[0]]); + await client.unsafe(`update issues set created_by_user_id=$2 where company_id=$1 and parent_id=any($3::uuid[])`,[f.companyId,userId,parents]); + await client.unsafe(`update issue_read_states set last_read_at='2026-01-03' where company_id=$1`,[f.companyId]); + await client.unsafe('vacuum analyze'); + const receipts=await measure(summaryPath+'&navigation=true'); + report.receiptStress={oldViewerReceipts:5000,...receipts,body:undefined};console.log(JSON.stringify(report.receiptStress)); + const readCondition=await issueReadSqlCondition(db,actor); + const q=()=>listIssueNavigationState(db,f.companyId,parents,readCondition,userId); + const start=performance.now();await Promise.all(Array.from({length:3},q));report.concurrentThreeServiceRequestsMs=+(performance.now()-start).toFixed(2); + await writeFile(new URL('database-results.json',out),JSON.stringify(report,null,2)); +} finally { + server?.close(); await client.end({timeout:0}); await fixture.cleanup(); clearInterval(keeper); +} diff --git a/server/src/__tests__/authorization-privacy-query.test.ts b/server/src/__tests__/authorization-privacy-query.test.ts index 3f3c3de068f..bf0e2d43399 100644 --- a/server/src/__tests__/authorization-privacy-query.test.ts +++ b/server/src/__tests__/authorization-privacy-query.test.ts @@ -22,6 +22,9 @@ describe("privacy ancestry query work", () => { const [explain] = await db.$client.unsafe(`explain (analyze,buffers,format json) ${statement.sql}`, statement.params as never[]); const work = recursiveIssueWork(explain["QUERY PLAN"][0].Plan); expect(work.recursiveNodes).toBeGreaterThan(0); + // Open roots have no restricted ancestor. Their count reads must not + // execute a recursive privacy lookup for every task. + expect(work.inspectedRows).toBe(0); expect(work.inspectedRows).toBeLessThanOrEqual(f.ids.length * 3); expect(work.projectProbes).toBeLessThanOrEqual(f.ids.length * 3); }); diff --git a/server/src/__tests__/issue-summaries-routes.test.ts b/server/src/__tests__/issue-summaries-routes.test.ts index 848671c3b42..94413545c5e 100644 --- a/server/src/__tests__/issue-summaries-routes.test.ts +++ b/server/src/__tests__/issue-summaries-routes.test.ts @@ -1,15 +1,20 @@ import { randomUUID } from "node:crypto"; import express from "express"; import request from "supertest"; -import { eq } from "drizzle-orm"; +import { and, eq, inArray } from "drizzle-orm"; +import { drizzle } from "drizzle-orm/postgres-js"; +import * as schema from "@paperclipai/db/schema/index"; import { afterAll, beforeAll, expect, it, vi } from "vitest"; import { - agents, chatConversations, chatEndpoints, heartbeatRuns, issueRelations, issues, toolApplications, toolConnections, + activityLog, agents, chatConversations, chatEndpoints, companyMemberships, heartbeatRuns, issueComments, issueReadStates, issueRelations, issues, issueThreadInteractions, toolApplications, toolConnections, } from "@paperclipai/db"; import { ISSUE_SUMMARIES_MAX_IDS } from "@paperclipai/shared"; import { issueRoutes } from "../routes/issues.js"; import * as issueServices from "../services/issues.js"; import { errorHandler } from "../middleware/index.js"; +import { ensureHumanRoleDefaultGrants } from "../services/principal-access-compatibility.js"; +import { recentSubtaskParents } from "../realtime/recent-subtask-parents.js"; +import { subscribeCompanyLiveEvents } from "../services/live-events.js"; import { describeEmbeddedPostgres, seedCompanyWithBoardAccess, useEmbeddedPostgres, type BoardActor } from "./helpers/route-test-harness.js"; describeEmbeddedPostgres("bounded issue summaries", () => { @@ -27,7 +32,7 @@ describeEmbeddedPostgres("bounded issue summaries", () => { { companyId: company.companyId, title: "First", description: "Do not serialize this".repeat(100), status: "todo" }, { companyId: company.companyId, title: "Second", status: "done" }, ]).returning(); - return { ...company, rows }; + return { ...company, actor: { ...company.actor, source: "session" as const }, rows }; } function app(actor: BoardActor | Express.Request["actor"]) { const result = express(); @@ -39,6 +44,136 @@ describeEmbeddedPostgres("bounded issue summaries", () => { } const url = (companyId: string) => `/api/companies/${companyId}/issues/summaries`; + it("matches the inbox unread predicate across participation, request, withdrawal and read histories", async () => { + const f = await fixture(); + const user = f.actor.userId!; + const names = ["created", "read", "untouched", "assigned", "human-comment", "derived-comment", "activity", + "read-only-activity", "pending", "not-creator", "withdrawn", "withdrawn-read", "deleted-comment", "self-after-external"]; + const day = (n: number) => new Date(`2026-01-0${n}`); + const rows = await ctx.db.insert(issues).values(names.map(title => ({ + companyId: f.companyId, parentId: f.rows[0]!.id, title, createdAt: day(1), updatedAt: day(1), + createdByUserId: ["created", "read", "withdrawn", "withdrawn-read", "deleted-comment", "self-after-external"].includes(title) ? user : "other", + assigneeUserId: title === "assigned" ? user : null, + }))).returning(); + const byName = new Map(rows.map(row => [row.title, row])); + const id = (name: string) => byName.get(name)!.id; + const noExternal = new Set(["pending", "not-creator", "withdrawn", "withdrawn-read"]); + await ctx.db.insert(issueComments).values(rows.filter(row => !noExternal.has(row.title)).map(row => ({ + companyId: f.companyId, issueId: row.id, authorUserId: "other", body: "External", createdAt: day(3), + deletedAt: row.title === "deleted-comment" ? day(4) : null, + }))); + await ctx.db.insert(issueComments).values(["human-comment", "derived-comment", "self-after-external"].map(name => ({ + companyId: f.companyId, issueId: id(name), authorUserId: user, body: "Mine", + createdAt: day(name === "self-after-external" ? 4 : 2), + metadata: name === "derived-comment" ? { version: 1, sections: [], sourceChannel: "slack" } : null, + }))); + await ctx.db.insert(issueReadStates).values(["read", "withdrawn-read"].map(name => ({ + companyId: f.companyId, issueId: id(name), userId: user, lastReadAt: day(4), + }))); + await ctx.db.insert(activityLog).values(["activity", "read-only-activity", "withdrawn", "withdrawn-read"].map(name => ({ + companyId: f.companyId, entityType: "issue", entityId: id(name), actorType: "user", + actorId: name.startsWith("withdrawn") ? "other" : user, + action: name.startsWith("withdrawn") ? "issue.thread_interaction_withdrawn" : name === "activity" ? "issue.updated" : "issue.read_marked", + createdAt: day(3), details: name.startsWith("withdrawn") ? { handledForUserId: user, receipt: { outcome: "withdrawn", issueId: id(name) } } : null, + }))); + await ctx.db.insert(issueThreadInteractions).values(["pending", "not-creator"].map(name => ({ + companyId: f.companyId, issueId: id(name), kind: "request_confirmation", payload: { version: 1, prompt: "Confirm this task." }, + addresseeUserId: user, createdByUserId: user, createdAt: day(3), + effectiveResolverPolicy: name === "not-creator" ? "not_creator" as const : "anyone" as const, + }))); + const oracle = await ctx.db.select({ id: issues.id }).from(issues).where(and( + eq(issues.companyId, f.companyId), inArray(issues.id, rows.map(row => row.id)), + issueServices.unreadForUserCondition(f.companyId, user), + )); + const expected = new Set(oracle.map(row => row.id)); + expect(rows.filter(row => expected.has(row.id)).map(row => row.title).sort()).toEqual([ + "activity", "assigned", "created", "human-comment", "pending", "withdrawn", + ]); + const res = await request(app(f.actor)).get(url(f.companyId)).query({ + ids: [f.rows[0]!.id, ...rows.map(row => row.id)].join(","), navigation: "true", + }).expect(200); + expect(res.body[0]).toMatchObject({ subtaskCount: rows.length, unreadSubtaskCount: expected.size }); + for (const row of res.body.slice(1)) expect(row.isUnreadForMe, byName.get(row.title)?.title).toBe(expected.has(row.id)); + }); + + it("authorizes both reparenting hints and excludes hidden, private and foreign parents", async () => { + const f = await fixture(); + const foreign = await fixture(); + const privateId = randomUUID(); + await ctx.db.insert(issues).values({ id: privateId, companyId: f.companyId, title: "Secret", visibility: "private", createdByUserId: "other" }); + const [child] = await ctx.db.insert(issues).values({ companyId: f.companyId, title: "Child", parentId: privateId }).returning(); + const payload = { entityType: "issue", entityId: child!.id, details: { _previous: { parentId: f.rows[0]!.id } } }; + const queries: string[] = []; + const observedDb = drizzle(ctx.db.$client, { schema, logger: { logQuery(query) { queries.push(query); } } }) as typeof ctx.db; + const reads = new Map>(); + for (let delivery = 0; delivery < 2; delivery++) { + expect(await recentSubtaskParents(observedDb, f.actor, f.companyId, payload, reads)).toEqual({ recentSubtaskParentIds: [f.rows[0]!.id] }); + } + expect(queries.filter(query => query.startsWith('select "parent_id" from "issues"'))).toHaveLength(1); + await ctx.db.update(issues).set({ parentId: f.rows[1]!.id }).where(eq(issues.id, child!.id)); + expect(new Set((await recentSubtaskParents(ctx.db, f.actor, f.companyId, payload)).recentSubtaskParentIds)).toEqual(new Set(f.rows.map(row => row.id))); + await ctx.db.update(issues).set({ hiddenAt: new Date() }).where(eq(issues.id, f.rows[0]!.id)); + expect(await recentSubtaskParents(ctx.db, f.actor, f.companyId, { + ...payload, details: { parentId: foreign.rows[0]!.id, _previous: { parentId: f.rows[0]!.id } }, + })).toEqual({ recentSubtaskParentIds: [f.rows[1]!.id] }); + }); + + it("publishes a parent event when an uncached child is deleted", async () => { + const f = await fixture(); + const parentId = f.rows[0]!.id; + const [child] = await ctx.db.insert(issues).values({ companyId: f.companyId, parentId, title: "Uncached child" }).returning(); + const events: Array> = []; + const unsubscribe = subscribeCompanyLiveEvents(f.companyId, event => { if (event.type === "activity.logged") events.push(event.payload); }); + try { + await request(app(f.actor)).delete(`/api/issues/${child!.id}`).expect(200); + const deleted = events.find(event => event.action === "issue.deleted")!; + expect(deleted.details).toMatchObject({ parentId }); + expect(await recentSubtaskParents(ctx.db, f.actor, f.companyId, deleted)).toEqual({ recentSubtaskParentIds: [parentId] }); + // The deleted task no longer passes live read authorization. Its + // independently authorized parent still receives a content-free update. + expect(events).toContainEqual(expect.objectContaining({ action: "issue.child_deleted", entityType: "issue", entityId: parentId })); + const res = await request(app(f.actor)).get(url(f.companyId)).query({ ids: parentId, navigation: "true" }).expect(200); + expect(res.body[0]).toMatchObject({ subtaskCount: 0, unreadSubtaskCount: 0 }); + } finally { unsubscribe(); } + }); + + it("counts only readable subtasks and preserves each person's unread state beyond ten children", async () => { + const f = await fixture(); + const parent = f.rows[0]!; + const children = await ctx.db.insert(issues).values(Array.from({ length: 14 }, (_, index) => ({ + companyId: f.companyId, parentId: parent.id, title: `Child ${index}`, createdByUserId: f.actor.userId, + createdAt: new Date("2026-01-01"), updatedAt: new Date("2026-01-01"), + }))).returning(); + await ctx.db.insert(issueComments).values(children.map(child => ({ + companyId: f.companyId, issueId: child.id, authorUserId: "another-user", body: "New message", createdAt: new Date("2026-01-02"), + }))); + await ctx.db.update(issues).set({ hiddenAt: new Date() }).where(eq(issues.id, children[0]!.id)); + await ctx.db.update(issues).set({ visibility: "private", privacyRootIssueId: children[1]!.id, responsibleUserId: "another-user", createdByUserId: "another-user" }).where(eq(issues.id, children[1]!.id)); + const read = () => request(app(f.actor)).get(url(f.companyId)).query({ ids: `${parent.id},${children[13]!.id}`, navigation: "true" }).expect(200); + const first = (await read()).body; + expect(first[0]).toMatchObject({ parentId: null, isUnreadForMe: false, subtaskCount: 12, unreadSubtaskCount: 12 }); + expect(first[1]).toMatchObject({ parentId: parent.id, isUnreadForMe: true, subtaskCount: 0 }); + // Opening a parent records only its own read receipt. + await ctx.db.insert(issueReadStates).values({ companyId: f.companyId, issueId: parent.id, userId: f.actor.userId!, lastReadAt: new Date("2026-01-03") }); + expect((await read()).body[0].unreadSubtaskCount).toBe(12); + await ctx.db.insert(issueReadStates).values({ companyId: f.companyId, issueId: children[13]!.id, userId: f.actor.userId!, lastReadAt: new Date("2026-01-03") }); + const last = (await read()).body; + expect(last[0].unreadSubtaskCount).toBe(11); + expect(last[1].isUnreadForMe).toBe(false); + const [untouched] = await ctx.db.insert(issues).values({ companyId: f.companyId, parentId: parent.id, title: "Untouched child" }).returning(); + const childrenRead = await request(app(f.actor)).get(`/api/companies/${f.companyId}/issues`).query({ + parentId: parent.id, view: "rows", limit: 100, includeReadState: "true", + }).expect(200); + expect(childrenRead.body).toHaveLength(13); + expect(childrenRead.body.find((row: { id: string }) => row.id === children[13]!.id)?.isUnreadForMe).toBe(false); + expect(childrenRead.body.find((row: { id: string }) => row.id === children[12]!.id)?.isUnreadForMe).toBe(true); + expect(childrenRead.body.find((row: { id: string }) => row.id === untouched!.id)?.isUnreadForMe).toBe(false); + const otherViewer = { ...f.actor, userId: "untouched-viewer" }; + await ctx.db.insert(companyMemberships).values({ companyId: f.companyId, principalType: "user", principalId: otherViewer.userId, status: "active", membershipRole: "owner" }); + await ensureHumanRoleDefaultGrants(ctx.db, { companyId: f.companyId, principalId: otherViewer.userId, membershipRole: "owner", grantedByUserId: null }); + expect((await request(app(otherViewer)).get(url(f.companyId)).query({ ids: parent.id, navigation: "true" }).expect(200)).body[0].unreadSubtaskCount).toBe(0); + }); + it("returns only summaries in requested order without full-detail reads", async () => { const f = await fixture(); const original = issueServices.issueService; @@ -95,6 +230,7 @@ describeEmbeddedPostgres("bounded issue summaries", () => { const actor: Express.Request["actor"] = { type: "agent", agentId: agent!.id, companyId: f.companyId, source: "agent_key" }; const res = await request(app(actor)).get(url(f.companyId)).query({ ids: f.rows[0]!.id }).expect(200); expect(res.body).toHaveLength(1); + await request(app(actor)).get(`/api/companies/${f.companyId}/issues`).query({ view: "rows", includeReadState: "true" }).expect(403); await request(app({ ...actor, keyScope: { kind: "task_bridge", issueId: f.rows[0]!.id } } as Express.Request["actor"])) .get(url(f.companyId)).query({ ids: f.rows[0]!.id }).expect(403); }); @@ -103,7 +239,7 @@ describeEmbeddedPostgres("bounded issue summaries", () => { const f = await fixture(); const [agent] = await ctx.db.insert(agents).values({ companyId: f.companyId, name: "Chat", role: "general", adapterType: "process" }).returning(); const issue = f.rows[0]!; - await ctx.db.update(issues).set({ status: "in_review", assigneeAgentId: agent!.id }).where(eq(issues.id, issue.id)); + await ctx.db.update(issues).set({ status: "in_review", assigneeAgentId: agent!.id, parentId: f.rows[1]!.id }).where(eq(issues.id, issue.id)); const [application] = await ctx.db.insert(toolApplications).values({ companyId: f.companyId, name: "Slack", type: "chat" }).returning(); const connectionId = randomUUID(); await ctx.db.insert(toolConnections).values({ id: connectionId, companyId: f.companyId, applicationId: application!.id, uid: connectionId, name: "Slack", transport: "chat_sdk", connectionPurpose: "channel" }); @@ -113,6 +249,12 @@ describeEmbeddedPostgres("bounded issue summaries", () => { const read = () => request(app(f.actor)).get(url(f.companyId)).query({ ids: issue.id }).expect(200); const waiting = (await read()).body[0]; expect(waiting.externalConversationState).toBe("waiting"); + const children = await request(app(f.actor)).get(`/api/companies/${f.companyId}/issues`).query({ + parentId: f.rows[1]!.id, view: "rows", includeRoutineExecutions: "true", includeReadState: "true", + }).expect(200); + expect(children.body.map((row: { id: string }) => row.id)).toEqual([issue.id]); + const count = await request(app(f.actor)).get(url(f.companyId)).query({ ids: f.rows[1]!.id, navigation: "true" }).expect(200); + expect(count.body[0].subtaskCount).toBe(children.body.length); expect((await issueServices.issueService(ctx.db).getById(issue.id))?.externalConversationState).toBe("waiting"); await ctx.db.update(chatConversations).set({ state: "active" }).where(eq(chatConversations.id, conversation!.id)); const active = (await read()).body[0]; diff --git a/server/src/__tests__/live-events-run-read.test.ts b/server/src/__tests__/live-events-run-read.test.ts index 43e098bc53a..0e514cfd15f 100644 --- a/server/src/__tests__/live-events-run-read.test.ts +++ b/server/src/__tests__/live-events-run-read.test.ts @@ -142,6 +142,12 @@ describe("live-event run read boundaries", () => { expect(await deliver(run.id, issueId)).toMatchObject([{ payload: { runId: run.id, issueId, status: "running" } }]); expect(queries.length - batchStart).toBeLessThanOrEqual(6); expect(queries.slice(batchStart).filter(query => query.startsWith("select ") && query.includes('from "issues"')).length).toBeLessThanOrEqual(2); + const [parent] = await db.insert(issues).values({ companyId, title: "Readable parent" }).returning(); + await db.update(issues).set({ parentId: parent.id }).where(eq(issues.id, issueId)); + expect(await deliver(run.id, issueId)).toMatchObject([{ payload: { recentSubtaskParentIds: [parent.id] } }]); + await db.update(issues).set({ hiddenAt: new Date() }).where(eq(issues.id, parent.id)); + expect(await deliver(run.id, issueId)).toMatchObject([{ payload: { recentSubtaskParentIds: [] } }]); + await db.update(issues).set({ parentId: null }).where(eq(issues.id, issueId)); expect(await deliver(hiddenRun.id, issueId)).toEqual([]); expect(await deliver(run.id, hiddenIssueId)).toEqual([]); expect(await deliver(run.id, randomUUID())).toEqual([]); @@ -164,7 +170,7 @@ describe("live-event run read boundaries", () => { expect(reads).toHaveLength(deliveries); for (const query of reads) { - expect(query).toMatch(/^select "company_id", "scope_kind", "issue_id" from "heartbeat_runs"/); + expect(query).toMatch(/^select "heartbeat_runs"\."company_id", "heartbeat_runs"\."scope_kind", "heartbeat_runs"\."issue_id", "issues"\."parent_id" from "heartbeat_runs"/); expect(query).not.toMatch(/context_snapshot|runner_profile_json|stdout_excerpt|result_json/); } expect(JSON.stringify(messages)).not.toMatch(/private-context|private-profile|private-output/); diff --git a/server/src/realtime/live-events-ws.ts b/server/src/realtime/live-events-ws.ts index e5d3d23031b..7388f875df0 100644 --- a/server/src/realtime/live-events-ws.ts +++ b/server/src/realtime/live-events-ws.ts @@ -7,11 +7,12 @@ import { createRequire } from "node:module"; import type { Duplex } from "node:stream"; import { and, eq, isNull } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; -import { agentApiKeys, companyMemberships, instanceUserRoles, heartbeatRuns, projects } from "@paperclipai/db"; +import { agentApiKeys, companyMemberships, instanceUserRoles, heartbeatRuns, issues, projects } from "@paperclipai/db"; import { issueActivityChangesTaskIdentity, type DeploymentMode, type LiveEvent } from "@paperclipai/shared"; import type { BetterAuthSessionResult } from "../auth/better-auth.js"; import { logger } from "../middleware/logger.js"; import { activityToastIdentity } from "./activity-toast-identity.js"; +import { recentSubtaskParents } from "./recent-subtask-parents.js"; import { taskToastEligible } from "./task-toast-eligibility.js"; import { subscribeCompanyLiveEvents } from "../services/live-events.js"; import { trackIdleWork } from "../services/task-admission.js"; @@ -292,7 +293,12 @@ export function setupLiveEventsWebSocketServer( if (event.type === "activity.logged" && event.payload.entityType === "issue") { return { ...event, payload: { ...event.payload, taskIdentityChanged: issueActivityChangesTaskIdentity(event.payload.action, event.payload.details), - ...await activityToastIdentity(db, event.companyId, event.payload) } }; + ...await activityToastIdentity(db, event.companyId, event.payload), + ...await recentSubtaskParents(db, context!.actor, event.companyId, event.payload, reads) } }; + } + if (event.type === "heartbeat.run.status" || event.type === "heartbeat.run.queued") { + return { ...event, payload: { ...event.payload, + ...await recentSubtaskParents(db, context!.actor, event.companyId, event.payload, reads) } }; } return event; } @@ -322,6 +328,7 @@ export function setupLiveEventsWebSocketServer( if (!allowed) return null; } const readBindings: Parameters[3][number][] = []; + let navigationTask: { id: string; parentId: string | null } | undefined; if (issueId) { readBindings.push({ companyId: event.companyId, scopeKind: "issue", issueId }); } @@ -330,9 +337,13 @@ export function setupLiveEventsWebSocketServer( companyId: heartbeatRuns.companyId, scopeKind: heartbeatRuns.scopeKind, issueId: heartbeatRuns.issueId, - }).from(heartbeatRuns).where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, event.companyId))))[0]); + // Reuse this narrow binding for navigation hints after authorization. + parentId: issues.parentId, + }).from(heartbeatRuns).leftJoin(issues, and(eq(issues.id, heartbeatRuns.issueId), eq(issues.companyId, heartbeatRuns.companyId))) + .where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, event.companyId))))[0]); if (!run) return null; readBindings.push(run); + if (run.issueId) navigationTask = { id: run.issueId, parentId: run.parentId }; } if (!(await sharedDeliveryRead(reads, `read:${issueId ?? ""}:${runId ?? ""}`, async () => (await getHeartbeatRunReadDecisions(db, access, context!.actor, readBindings)).every(Boolean)))) return null; @@ -349,7 +360,12 @@ export function setupLiveEventsWebSocketServer( if (!project || !(await access.decide({ actor: context!.actor, action: "project:read", resource: { type: "project", companyId: event.companyId, projectId: project.id } })).allowed) return null; } - if (event.type.startsWith("heartbeat.run.")) return runId ? event : null; + if (event.type.startsWith("heartbeat.run.")) { + if (!runId) return null; + return event.type === "heartbeat.run.status" || event.type === "heartbeat.run.queued" + ? { ...event, payload: { ...event.payload, ...await recentSubtaskParents(db, context!.actor, event.companyId, payload, reads, navigationTask) } } + : event; + } if (event.type === "agent.session.goal.changed") return issueId ? event : null; // Company-wide invalidations carry no task-derived content. Authorized // clients obtain details through viewer-filtered HTTP reads. @@ -365,6 +381,7 @@ export function setupLiveEventsWebSocketServer( : {}), // The task read check above authorizes attribution, but not arbitrary details. ...(issueId ? await activityToastIdentity(db, event.companyId, payload) : {}), + ...await recentSubtaskParents(db, context!.actor, event.companyId, payload, reads), } }; if (event.type === "agent.status") return { ...event, payload: { agentId: payload.agentId, status: payload.status } }; if (event.type === "agent.runtime_state.updated") return { ...event, payload: { agentId: payload.agentId } }; diff --git a/server/src/realtime/recent-subtask-parents.ts b/server/src/realtime/recent-subtask-parents.ts new file mode 100644 index 00000000000..88e3ff060fe --- /dev/null +++ b/server/src/realtime/recent-subtask-parents.ts @@ -0,0 +1,33 @@ +import { and, eq, inArray, isNull } from "drizzle-orm"; +import { issues, type Db } from "@paperclipai/db"; +import { z } from "zod"; +import { issueReadSqlCondition, type AuthorizationActor } from "../services/authorization.js"; +import { sharedDeliveryRead, type LiveDeliveryReads } from "./live-event-delivery.js"; + +/** Invalidation hints disclose only parents this subscriber can read. Called + * after task authorization; never expose raw activity details to the browser. */ +export async function recentSubtaskParents( + db: Db, actor: AuthorizationActor, companyId: string, payload: Record, + reads?: LiveDeliveryReads, + knownTask?: { id: string; parentId: string | null }, +) { + if (payload.entityType && payload.entityType !== "issue" && payload.entityType !== "heartbeat_run") return {}; + const issueId = payload.entityType === "issue" ? payload.entityId : payload.issueId; + if (actor.type !== "board" || typeof issueId !== "string") return {}; + // Materialize the query as one promise. A Drizzle query is a thenable and + // would execute again when the delivery cache attaches its rejection handler. + const task = knownTask?.id === issueId ? knownTask : (await sharedDeliveryRead(reads, `navigation-parent:${issueId}`, async () => + db.select({ parentId: issues.parentId }).from(issues) + .where(and(eq(issues.companyId, companyId), eq(issues.id, issueId))).limit(1)))[0]; + const details = payload.details as Record | null | undefined; + const previous = details?._previous as Record | null | undefined; + const ids = [...new Set([task?.parentId, details?.parentId, previous?.parentId] + .filter((id): id is string => typeof id === "string" && z.string().uuid().safeParse(id).success))]; + if (!ids.length) return { recentSubtaskParentIds: [] as string[] }; + const readable = await sharedDeliveryRead(reads, `navigation-readable:${[...ids].sort().join(",")}`, async () => + db.select({ id: issues.id }).from(issues).where(and( + eq(issues.companyId, companyId), inArray(issues.id, ids), isNull(issues.hiddenAt), + await issueReadSqlCondition(db, actor), + ))); + return { recentSubtaskParentIds: readable.map(row => row.id) }; +} diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 055e7a2bf49..41abc60ae32 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -20,7 +20,7 @@ import { ISSUE_SUMMARIES_MAX_IDS, issueChatBootstrapQuerySchema, issueSummariesQ import { readIssueChatBootstrapItems } from "../services/issue-chat-bootstrap.js"; import { issueRunPresenceService } from "../services/issue-run-presence.js"; import { activityService } from "../services/activity.js"; -import { listIssueSummaries } from "../services/issue-summaries.js"; +import { listIssueNavigationState, listIssueSummaries } from "../services/issue-summaries.js"; import { listIssueStatusBlockerAttention } from "../services/issue-status-presentation.js"; import { assertNoCaseHandoffMutation } from "../services/heartbeat/case-handoff-lifecycle.js"; import { assertHandedOffRunTaskOwnership } from "../run-task-ownership.js"; @@ -8786,11 +8786,20 @@ export function issueRoutes( } const parsed = issueSummariesQuerySchema.safeParse(req.query); if (!parsed.success) { - res.status(400).json({ error: `ids must be the only query parameter and contain one to ${ISSUE_SUMMARIES_MAX_IDS} comma-separated UUIDs` }); + res.status(400).json({ error: `ids must contain one to ${ISSUE_SUMMARIES_MAX_IDS} comma-separated UUIDs; navigation=true is the only optional parameter` }); return; } - const rows = await listIssueSummaries(db, companyId, parsed.data.ids, await issueReadSqlCondition(db, req.actor)); + if (parsed.data.navigation && req.actor.type !== "board") { + res.status(403).json({ error: "Navigation summaries require board authentication" }); + return; + } + const readCondition = await issueReadSqlCondition(db, req.actor); + const rows = await listIssueSummaries(db, companyId, parsed.data.ids, readCondition); const visible = await filterIssuesForActor(req, rows); + const navigation = parsed.data.navigation ? await listIssueNavigationState( + db, companyId, visible.map(row => row.id), readCondition, + getActorInfo(req).actorId, + ) : null; // Blocked rows carry glyph-only blocker state so every task view resolves // the same glyph (covered → "in queue") as the task pane. At most ISSUE_SUMMARIES_MAX_IDS IDs. const blockerAttention = await listIssueStatusBlockerAttention(db, companyId, visible, async (ids) => new Set( @@ -8808,6 +8817,7 @@ export function issueRoutes( displayStatus: row.displayStatus, updatedAt: row.updatedAt, externalConversationState: row.externalConversationState, + ...(navigation ? { parentId: row.parentId, ...navigation.get(row.id) } : {}), ...(attention ? { blockerAttention: attention } : {}), }; }); @@ -9115,6 +9125,15 @@ export function issueRoutes( string | undefined; const unreadForUserFilterRaw = req.query.unreadForUserId as string | undefined; + if (req.query.includeReadState !== undefined && !["true", "false"].includes(req.query.includeReadState as string)) { + res.status(400).json({ error: "includeReadState must be true or false" }); + return; + } + const includeReadState = req.query.includeReadState === "true"; + if (includeReadState && req.actor.type !== "board") { + res.status(403).json({ error: "includeReadState requires board authentication" }); + return; + } const assigneeUserId = assigneeUserFilterRaw === "me" && req.actor.type === "board" ? req.actor.userId @@ -9336,6 +9355,7 @@ export function issueRoutes( touchedByUserId, inboxArchivedByUserId, unreadForUserId, + readStateForUserId: includeReadState ? getActorInfo(req).actorId : undefined, projectId: uuidFilters.projectId, workspaceId: uuidFilters.workspaceId, executionWorkspaceId: uuidFilters.executionWorkspaceId, @@ -17437,6 +17457,22 @@ export function issueRoutes( action: "issue.deleted", entityType: "issue", entityId: issue.id, + details: { parentId: issue.parentId }, + }); + + // The removed child can no longer pass live read authorization. Notify + // its parent separately; delivery authorizes that parent and exposes no + // deleted-child identity or content to people who can only read the parent. + if (issue.parentId) await logActivity(db, { + companyId: issue.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + agentApiKeyId: actor.agentApiKeyId, + action: "issue.child_deleted", + entityType: "issue", + entityId: issue.parentId, }); await queueTaskWatchdogEvaluation(existing, actor.runId); diff --git a/server/src/services/authorization.ts b/server/src/services/authorization.ts index c6cc525780e..3b21951b726 100644 --- a/server/src/services/authorization.ts +++ b/server/src/services/authorization.ts @@ -679,7 +679,12 @@ function issuePrivacyPrincipalCondition(actor: AuthorizationActor): SQL where p.id = n.project_id and p.company_id = n.company_id and p.visibility = 'private' and m.subject_type = ${principal.type} and m.subject_id = ${principal.id} )` : sql`false`; - return sql`exists ( + // A standalone open task without a project has no restricted ancestor. + // Keep the recursive predicate for every other shape, including inherited + // privacy and delegated principals. This avoids one recursive walk per row + // in large readable-child aggregates. + return sql`((${issues.visibility} = 'open' + and ${issues.privacyParentIssueId} is null and ${issues.projectId} is null) or exists ( with recursive privacy_ancestors as ( select p.id, p.company_id, p.privacy_parent_issue_id, p.visibility, p.project_id, p.responsible_user_id, p.created_by_user_id, p.assignee_user_id, p.assignee_agent_id @@ -706,7 +711,7 @@ function issuePrivacyPrincipalCondition(actor: AuthorizationActor): SQL and private_project.company_id = restricted.company_id where restricted.visibility = 'private' or private_project.visibility = 'private' ) - )`; + ))`; } function issuePrivacyCondition(actor: AuthorizationActor): SQL { diff --git a/server/src/services/issue-participation.ts b/server/src/services/issue-participation.ts index e59feed954b..c7c2a815c0f 100644 --- a/server/src/services/issue-participation.ts +++ b/server/src/services/issue-participation.ts @@ -153,7 +153,7 @@ export function userParticipationActivityCondition(companyId: string, userId: st )`; } -export function touchedByUserCondition(companyId: string, userId: string) { +export function touchedByUserCondition(companyId: string, userId: string, directCommentExists?: SQL) { return sql` ( (${issues.createdByUserId} = ${userId} AND ${humanCreatedIssueCondition()}) @@ -165,14 +165,14 @@ export function touchedByUserCondition(companyId: string, userId: string) { WHERE ${activityLog.entityId} = ${issues.id}::text AND ${userParticipationActivityCondition(companyId, userId)} ) - OR EXISTS ( + OR ${directCommentExists ?? sql`EXISTS ( SELECT 1 FROM ${issueComments} WHERE ${issueComments.issueId} = ${issues.id} AND ${issueComments.companyId} = ${companyId} AND ${issueComments.authorUserId} = ${userId} AND ${directHumanCommentCondition()} - ) + )`} ) `; } diff --git a/server/src/services/issue-summaries.ts b/server/src/services/issue-summaries.ts index 645ff8a86c2..dd931c91987 100644 --- a/server/src/services/issue-summaries.ts +++ b/server/src/services/issue-summaries.ts @@ -1,7 +1,9 @@ import { issueDisplayStatusSql } from "./issue-display-status.js"; -import { and, eq, inArray, isNull, type SQL } from "drizzle-orm"; -import { issues, type Db } from "@paperclipai/db"; +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 { externalConversationStateSql } from "./slack-conversation-state.js"; /** A bounded projection with the columns needed by task-read authorization. */ @@ -38,3 +40,99 @@ export async function listIssueSummaries( return row ? [row] : []; }); } + +/** Counts stay on the server. Aggregate viewer facts once per readable task, + * then evaluate the shared inbox rule without repeated comment/read lookups. */ +export async function listIssueNavigationState( + db: Db, + companyId: string, + ids: readonly string[], + readCondition: SQL, + userId: string, +) { + if (ids.length > ISSUE_SUMMARIES_MAX_IDS) throw new Error("Too many issue summary IDs"); + if (!ids.length) return new Map(); + const requested = sql.join(ids.map(id => sql`${id}::uuid`), sql`, `); + const participation = mineParticipationIssueIds(db, companyId, userId); + const unread = unreadForUserCondition(companyId, userId, { + lastCommentAt: sql`issues.last_comment_at`, lastReadAt: sql`issues.last_read_at`, + lastExternalCommentAt: sql`issues.last_external_comment_at`, + }); + // Explicit SQL preserves qualification inside the shared correlated rules. + // 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; + }>(sql` + with navigation_candidates as materialized ( + select ${issues.id}, ${issues.parentId}, ${issues.conversationAgentId} + from ${issues} + where ${issues.companyId} = ${companyId} and ${issues.hiddenAt} is null + and (${issues.id} in (${requested}) or + (${issues.parentId} in (${requested}) and ${issues.conversationAgentId} is null)) + and ${readCondition} + ), 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 + -- decides participation, resolver policy, direct authorship and reads. + select c.id from navigation_candidates c + join ${issueComments} on ${issueComments.issueId} = c.id and ${issueComments.companyId} = ${companyId} + left join ${issueReadStates} on ${issueReadStates.issueId} = c.id + and ${issueReadStates.companyId} = ${companyId} and ${issueReadStates.userId} = ${userId} + where ${issueComments.deletedAt} is null + and (${issueComments.authorUserId} is null or ${issueComments.authorUserId} <> ${userId}) + and ${issueComments.createdAt} > coalesce(${issueReadStates.lastReadAt}, to_timestamp(0)) + union + select c.id from navigation_candidates c join ${issueThreadInteractions} + on ${issueThreadInteractions.issueId} = c.id and ${issueThreadInteractions.companyId} = ${companyId} + where ${issueThreadInteractions.status} = 'pending' and ${issueThreadInteractions.addresseeUserId} = ${userId} + union + select c.id from navigation_candidates c join ${activityLog} + on ${activityLog.details}->'receipt'->>'issueId' = c.id::text and ${activityLog.companyId} = ${companyId} + left join ${issueReadStates} on ${issueReadStates.issueId} = c.id + and ${issueReadStates.companyId} = ${companyId} and ${issueReadStates.userId} = ${userId} + where ${activityLog.details}->>'handledForUserId' = ${userId} + 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}) + ), navigation_comments as ( + select ${issueComments.issueId} as id, + max(${issueComments.createdAt}) filter (where ${issueComments.authorUserId} = ${userId} + and ${directHumanCommentCondition()}) as last_comment_at, + max(${issueComments.createdAt}) filter (where ${issueComments.deletedAt} is null + and (${issueComments.authorUserId} is null or ${issueComments.authorUserId} <> ${userId})) as last_external_comment_at + from ${issueComments} join unread_participants c on c.id = ${issueComments.issueId} + where ${issueComments.companyId} = ${companyId} + group by ${issueComments.issueId} + ), navigation_facts as ( + select ${issues.id}, ${issues.companyId}, ${issues.parentId}, ${issues.status}, + ${issues.conversationAgentId}, ${issues.createdByUserId}, ${issues.createdByAgentId}, + ${issues.assigneeUserId}, ${issues.createdAt}, ${issues.originKind}, + comments.last_comment_at, comments.last_external_comment_at, + ${issueReadStates.lastReadAt} as last_read_at + from navigation_candidates c join unread_participants possible on possible.id = c.id + join ${issues} on ${issues.id} = c.id and ${issues.companyId} = ${companyId} + left join navigation_comments comments on comments.id = c.id + left join ${issueReadStates} on ${issueReadStates.issueId} = c.id + and ${issueReadStates.companyId} = ${companyId} and ${issueReadStates.userId} = ${userId} + ), navigation_state as materialized ( + 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}) + union all + select 'children', c.parent_id, 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 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, + 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 5a92d3fc21e..5e1a8034e3b 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -1913,6 +1913,8 @@ export interface IssueFilters { touchedCandidates?: "participation"; inboxArchivedByUserId?: string; unreadForUserId?: string; + /** Read projection only; never filters the result set by participation. */ + readStateForUserId?: string; projectId?: string; workspaceId?: string; executionWorkspaceId?: string; @@ -2969,9 +2971,9 @@ function myLastReadAtExpr(companyId: string, userId: string) { `; } -function myLastTouchAtExpr(companyId: string, userId: string) { - const myLastCommentAt = myLastCommentAtExpr(companyId, userId); - const myLastReadAt = myLastReadAtExpr(companyId, userId); +function myLastTouchAtExpr(companyId: string, userId: string, facts?: UnreadCommentFacts) { + const myLastCommentAt = facts?.lastCommentAt ?? myLastCommentAtExpr(companyId, userId); + const myLastReadAt = facts?.lastReadAt ?? myLastReadAtExpr(companyId, userId); return sql` GREATEST( COALESCE(${myLastCommentAt}, to_timestamp(0)), @@ -3029,17 +3031,21 @@ function issueCanonicalLastActivityAtExpr(companyId: string) { `; } -function unreadForUserCondition(companyId: string, userId: string) { - const touchedCondition = touchedByUserCondition(companyId, userId); - const myLastTouchAt = myLastTouchAtExpr(companyId, userId); +type UnreadCommentFacts = { lastCommentAt: SQL; lastReadAt: SQL; lastExternalCommentAt: SQL }; + +/** Batch callers can supply the same facts once; the unread rules stay here. */ +export function unreadForUserCondition(companyId: string, userId: string, facts?: UnreadCommentFacts) { + const touchedCondition = touchedByUserCondition(companyId, userId, + facts ? sql`${facts.lastCommentAt} is not null` : undefined); + const myLastTouchAt = myLastTouchAtExpr(companyId, userId, facts); const myLastRequestReadAt = sql`GREATEST( - COALESCE(${myLastCommentAtExpr(companyId, userId)}, to_timestamp(0)), - COALESCE(${myLastReadAtExpr(companyId, userId)}, to_timestamp(0)) + COALESCE(${facts?.lastCommentAt ?? myLastCommentAtExpr(companyId, userId)}, to_timestamp(0)), + COALESCE(${facts?.lastReadAt ?? myLastReadAtExpr(companyId, userId)}, to_timestamp(0)) )`; return sql` ( ${touchedCondition} - AND (EXISTS ( + AND (${facts ? sql`${facts.lastExternalCommentAt} > ${myLastTouchAt}` : sql`EXISTS ( SELECT 1 FROM ${issueComments} WHERE ${issueComments.issueId} = ${issues.id} @@ -3050,7 +3056,7 @@ function unreadForUserCondition(companyId: string, userId: string) { OR ${issueComments.authorUserId} <> ${userId} ) AND ${issueComments.createdAt} > ${myLastTouchAt} - ) OR ${pendingUserRequestCondition(companyId, userId, myLastRequestReadAt)} + )`} OR ${pendingUserRequestCondition(companyId, userId, myLastRequestReadAt)} OR ${withdrawnForUserCondition(companyId, userId, myLastRequestReadAt)}) ) `; @@ -3061,7 +3067,7 @@ function unreadForUserCondition(companyId: string, userId: string) { * Each UNION member is one branch of `touchedByUserCondition`, so membership * equals that condition. The result is aliased `mine_participants` (`id`). */ -function mineParticipationIssueIds(db: Db, companyId: string, userId: string) { +export function mineParticipationIssueIds(db: Db, companyId: string, userId: string) { const directlyParticipated = or( and(eq(issues.createdByUserId, userId), humanCreatedIssueCondition()), eq(issues.assigneeUserId, userId), @@ -6685,7 +6691,7 @@ async function blockedInboxIssueConditions( filters?.inboxArchivedByUserId?.trim() || undefined; const unreadForUserId = filters?.unreadForUserId?.trim() || undefined; const contextUserId = - unreadForUserId ?? touchedByUserId ?? inboxArchivedByUserId; + unreadForUserId ?? touchedByUserId ?? inboxArchivedByUserId ?? filters?.readStateForUserId; if (filters?.createdFromIssueId) { conditions.push(createdFromIssueCondition(companyId, filters.createdFromIssueId)); @@ -8559,7 +8565,9 @@ export function issueService(db: Db) { } if (!filters?.q?.trim() && !filters?.issueIds) { conditions.push(isNull(issues.conversationAgentId)); - if (!filters?.touchedByUserId && !filters?.unreadForUserId && !filters?.inboxArchivedByUserId) { + // Explicit child navigation includes waiting chat tasks, just like + // readable-child counts. Ambient lists still omit idle conversations. + if (!filters?.parentId && !filters?.parentIds && !filters?.touchedByUserId && !filters?.unreadForUserId && !filters?.inboxArchivedByUserId) { conditions.push(nonIdleSlackIssueCondition()); } } @@ -8584,7 +8592,7 @@ export function issueService(db: Db) { filters?.inboxArchivedByUserId?.trim() || undefined; const unreadForUserId = filters?.unreadForUserId?.trim() || undefined; const contextUserId = - unreadForUserId ?? touchedByUserId ?? inboxArchivedByUserId; + unreadForUserId ?? touchedByUserId ?? inboxArchivedByUserId ?? filters?.readStateForUserId; const includeBlockedBy = filters?.includeBlockedBy === true; const includeBlockedInboxAttention = filters?.includeBlockedInboxAttention === true; @@ -8948,7 +8956,7 @@ export function issueService(db: Db) { if (creationCondition) conditions.push(creationCondition); if (!filters?.q?.trim()) { conditions.push(isNull(issues.conversationAgentId)); - if (!filters?.touchedByUserId && !filters?.unreadForUserId && !filters?.inboxArchivedByUserId) { + if (!filters?.parentId && !filters?.parentIds && !filters?.touchedByUserId && !filters?.unreadForUserId && !filters?.inboxArchivedByUserId) { conditions.push(nonIdleSlackIssueCondition()); } } diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index df9c7b3366f..11a49de8470 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -411,7 +411,7 @@ "packages/shared/src/types/index.ts": "8abf1f4ed91e67f8e620a1a0b127799c793554ff", "packages/shared/src/types/instance.ts": "ddabd7cc0d885b5fdf45b33a7937b7b704f8fb7d", "packages/shared/src/types/issue-tree-control.ts": "75489fffd491b8350b05caf57d7796419797d9df", - "packages/shared/src/types/issue.ts": "51b3c3e22ad9182f7caeb0c2d58bada8aaf483ca", + "packages/shared/src/types/issue.ts": "7183a5a11238c297e43917dc66897cbe73703835", "packages/shared/src/types/live.ts": "b90e55e4de8600c6fc17d7fa8d89079d4ae655ec", "packages/shared/src/types/native-finalization.ts": "c026a73003ae232fea4f7624d561493b383df358", "packages/shared/src/types/plugin.ts": "78519a2bbda1c9b465fbd73699ae77e9be577bfb", @@ -491,7 +491,7 @@ "packages/shared/src/validators/issue-chat-bootstrap.test.ts": "e1ebb9aa94da22c825bc3ddd32ce2cfc98bfe645", "packages/shared/src/validators/issue-tree-control.ts": "7144ef86a83e008ac0626e1d62a1d6164c46f438", "packages/shared/src/validators/issue.test.ts": "9a10bf1112d7c85f80cc1fd5db9920dda8974643", - "packages/shared/src/validators/issue.ts": "120ffa23b571374453a9777992b7e400d789403e", + "packages/shared/src/validators/issue.ts": "9877f071ad93952070507a79aec91fbf312d9a84", "packages/shared/src/validators/native-finalization.test.ts": "40c68bdd1d0e8a77cd70c4576fae53334fe5be0d", "packages/shared/src/validators/native-finalization.ts": "d4e674de6ac7d36385e6f6c2172fa16ffc9b1830", "packages/shared/src/validators/onboarding-seed.ts": "de302a8400d4199053f379d9ed853522a3ac6d32", diff --git a/tests/storybook-visual/recent-subtasks.spec.ts b/tests/storybook-visual/recent-subtasks.spec.ts new file mode 100644 index 00000000000..8d1ba35e44e --- /dev/null +++ b/tests/storybook-visual/recent-subtasks.spec.ts @@ -0,0 +1,65 @@ +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"]; +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) })) ?? []) }; + }); + expect(outcome).toMatchObject({ status: "success" }); +} + +for (const theme of ["light", "dark"]) { + for (const state of states) test(`${state} in ${theme}`, async ({ page }, testInfo) => { + 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); + } + 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); +}); diff --git a/ui/src/api/issues.ts b/ui/src/api/issues.ts index 5b53903e9e4..bbc5b17fa93 100644 --- a/ui/src/api/issues.ts +++ b/ui/src/api/issues.ts @@ -208,6 +208,8 @@ export type IssueListFilters = { touchedByUserId?: string; inboxArchivedByUserId?: string; unreadForUserId?: string; + /** Add the current board user's read state without filtering task membership. */ + includeReadState?: boolean; labelId?: string; workspaceId?: string; executionWorkspaceId?: string; @@ -252,6 +254,7 @@ function issueListSearchParams(filters?: IssueListFilters) { params.set("inboxArchivedByUserId", filters.inboxArchivedByUserId); if (filters?.unreadForUserId) params.set("unreadForUserId", filters.unreadForUserId); + if (filters?.includeReadState) params.set("includeReadState", "true"); if (filters?.labelId) params.set("labelId", filters.labelId); if (filters?.workspaceId) params.set("workspaceId", filters.workspaceId); if (filters?.executionWorkspaceId) @@ -291,11 +294,12 @@ export const issuesApi = { detachInflightGet(path); return api.get(path, { ...options, cache: "no-store" }); }, - summaries: async (companyId: string, issueIds: readonly string[], options?: RequestOptions): Promise => { + summaries: async (companyId: string, issueIds: readonly string[], options?: RequestOptions & { navigation?: boolean }): Promise => { if (issueIds.length > ISSUE_SUMMARIES_MAX_IDS) throw new Error("Too many issue summary IDs"); const ids = [...new Set(issueIds.map((id) => id.trim().toLowerCase()))].sort(); if (ids.length === 0) return []; const params = new URLSearchParams({ ids: ids.join(",") }); + if (options?.navigation) params.set("navigation", "true"); const path = `/companies/${companyId}/issues/summaries?${params}`; // React Query deduplicates within an account; URL-only HTTP coalescing must // never join a request sent with the previous account's cookie. diff --git a/ui/src/components/CoordinatorSidebar.test.tsx b/ui/src/components/CoordinatorSidebar.test.tsx index 3efb31ec241..2f6c9561c2b 100644 --- a/ui/src/components/CoordinatorSidebar.test.tsx +++ b/ui/src/components/CoordinatorSidebar.test.tsx @@ -58,6 +58,79 @@ 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 () => { + 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 }, + ]; + 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" }, + ]); + 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"); + }); + 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, diff --git a/ui/src/components/CoordinatorSidebar.tsx b/ui/src/components/CoordinatorSidebar.tsx index f2b622121dd..6529af2ba2c 100644 --- a/ui/src/components/CoordinatorSidebar.tsx +++ b/ui/src/components/CoordinatorSidebar.tsx @@ -17,6 +17,8 @@ import { agentRouteRef, cn, projectRouteRef, SIDEBAR_RAIL_HIDDEN_LABEL } from "@ import { SidebarCompanyMenu } from "./SidebarCompanyMenu"; import { SidebarNavItem } from "./SidebarNavItem"; import { RecentTaskNavItem } 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"; @@ -118,6 +120,7 @@ export function CoordinatorSidebar({ children }: { children?: ReactNode }) { ? [...moreDestinations, { label: "Cases", to: "/cases", icon: Boxes }] : moreDestinations, [experimental?.enableCases]); const [moreOpen, setMoreOpen] = useState(false); + const [recentsOpen, setRecentsOpen] = useState(true); const moreContentRef = useRef(null); const orderedPins = useMemo(() => buildPinnedNavigationItems(pinnedNavigation.pins, agents.data ?? [], destinations), [pinnedNavigation.pins, agents.data, destinations]); const { entries: recentTasks } = useRecentTasks({ companyId, userId }); @@ -127,6 +130,7 @@ export function CoordinatorSidebar({ children }: { children?: ReactNode }) { useRecentTaskOpenWarmup({ companyId, userId, tasks: !rail && session.isSuccess ? recentTasks : NO_RECENT_TASKS }); const { openNewIssue } = useDialogActions(); const location = useLocation(); + const hierarchy = useMemo(() => recentTaskHierarchy(recentTasks, location.pathname), [recentTasks, location.pathname]); const attentionCount = useCoordinatorAttentionCount(companyId); const { data: projects } = useQuery({ ...companyProjectsQuery(companyId!), enabled: !!companyId }); // Only project IDs and visit times are kept in memory. Labels and task lists @@ -141,7 +145,7 @@ export function CoordinatorSidebar({ children }: { children?: ReactNode }) { }, [location.pathname, projects, scope]); const recents = useMemo(() => { const roster = new Map((agents.data ?? []).map(agent => [agent.id, agent])); - const taskRows = recentTasks.map(task => ({ kind: "task" as const, id: task.id, time: task.recordedAt, task })); + const taskRows = recentTasks.filter(task => !hierarchy.nestedIds.has(task.id)).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 }] : []; @@ -149,7 +153,7 @@ export function CoordinatorSidebar({ children }: { children?: ReactNode }) { const projectRows = (projects ?? []).flatMap(project => projectVisits.scope === scope && projectVisits.entries[project.id] ? [{ kind: "project" as const, id: project.id, time: projectVisits.entries[project.id]!, project }] : []); return [...taskRows, ...chatRows, ...projectRows].sort((a, b) => b.time - a.time); - }, [agents.data, chats.data, recentTasks, projects, projectVisits, scope]); + }, [agents.data, chats.data, recentTasks, projects, projectVisits, scope, hierarchy]); 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/RecentTaskNavItem.tsx b/ui/src/components/RecentTaskNavItem.tsx index 7b7db9003a3..3c5682df5a2 100644 --- a/ui/src/components/RecentTaskNavItem.tsx +++ b/ui/src/components/RecentTaskNavItem.tsx @@ -1,6 +1,7 @@ import type { ComponentProps } from "react"; import { useIssueNavigationPrefetch } from "@/hooks/useIssueNavigationPrefetch"; import { SidebarNavItem } from "./SidebarNavItem"; +import { cn } from "@/lib/utils"; /** The route reference a Recents link opens: the identifier when the task has one. */ export function recentTaskPathRef(task: { id: string; identifier: string | null }) { @@ -15,13 +16,19 @@ export function recentTaskPathRef(task: { id: string; identifier: string | null export function RecentTaskNavItem({ task, to, + trailing, + labelClassName, ...props }: Omit, "to" | "linkHandlers"> & { - task: { id: string; identifier: string | null }; + task: { id: string; identifier: string | null; isUnreadForMe?: boolean }; /** Defaults to the board-relative task path. */ to?: string; }) { const pathRef = recentTaskPathRef(task); const linkHandlers = useIssueNavigationPrefetch(pathRef); - return ; + return {trailing}{task.isUnreadForMe && + }} />; } diff --git a/ui/src/components/SidebarRecentTasks.test.tsx b/ui/src/components/SidebarRecentTasks.test.tsx index 1239f1bdee1..f480a1976fb 100644 --- a/ui/src/components/SidebarRecentTasks.test.tsx +++ b/ui/src/components/SidebarRecentTasks.test.tsx @@ -19,6 +19,7 @@ const mockAgentsApi = vi.hoisted(() => ({ wakeup: vi.fn() })); const mockIssuesApi = vi.hoisted(() => ({ get: vi.fn(), summaries: vi.fn(), + listCompact: vi.fn(async (_company: string, _filters?: { parentId?: string }) => [] as unknown[]), update: vi.fn(), archiveFromInbox: vi.fn(), getTreeControlState: vi.fn(), @@ -31,6 +32,7 @@ vi.mock("@/api/agents", () => ({ agentsApi: mockAgentsApi })); vi.mock("@/api/auth", () => ({ authApi: mockAuthApi })); vi.mock("@/api/issues", () => ({ issuesApi: mockIssuesApi })); vi.mock("@/lib/router", () => ({ + useLocation: () => ({ pathname: "/PAP/issues" }), NavLink: ({ children, to, className, ...props }: { children: ReactNode; to: string; @@ -131,6 +133,31 @@ 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 () => { + const parent = { id: "parent", companyId: "company-1", title: "Parent", identifier: "PAP-1", status: "todo" as const, updatedAt: new Date(1), subtaskCount: 1 }; + 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); + await render(); + 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, + })); + 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({ diff --git a/ui/src/components/SidebarRecentTasks.tsx b/ui/src/components/SidebarRecentTasks.tsx index 20e18e5da1e..9f7c2aeb217 100644 --- a/ui/src/components/SidebarRecentTasks.tsx +++ b/ui/src/components/SidebarRecentTasks.tsx @@ -1,4 +1,4 @@ -import { useState, type FormEvent } from "react"; +import { useMemo, useState, type FormEvent } from "react"; import { useQueryClient } from "@tanstack/react-query"; import { Archive, MoreHorizontal, Pencil, RefreshCw } from "lucide-react"; import { agentsApi } from "@/api/agents"; @@ -32,6 +32,9 @@ 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"; const RECENT_TASK_MENU_ITEM_CLASS = @@ -106,6 +109,8 @@ function RecentTasksList({ rail: boolean; }) { 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); @@ -247,66 +252,73 @@ function RecentTasksList({ } }; + const renderTaskRow = (entry: RecentTaskEntry) => ( +
+ : undefined} + trailing={entry.status === "in_review" && entry.externalConversationState === "waiting" + ? Idle : undefined} + trailingLabel={entry.status === "in_review" && entry.externalConversationState === "waiting" ? "Idle" : undefined} + className={rail ? undefined : "sidebar-action-link pointer-coarse:pr-8"} + liveCount={liveIssueIds.has(entry.id) ? 1 : undefined} + /> + {!rail ? ( + + + + + + beginRename(entry)} + > + + void archiveTask(entry)} + > + + void toggleTaskPause(entry)} + > + + + + ) : null} +
+ ); + return ( <> - {entries.map((entry) => ( -
- : undefined} - trailing={entry.status === "in_review" && entry.externalConversationState === "waiting" - ? Idle : undefined} - trailingLabel={entry.status === "in_review" && entry.externalConversationState === "waiting" ? "Idle" : undefined} - className={rail ? undefined : "sidebar-action-link pointer-coarse:pr-8"} - liveCount={liveIssueIds.has(entry.id) ? 1 : undefined} - /> - {!rail ? ( - - - - - - beginRename(entry)} - > - - void archiveTask(entry)} - > - - void toggleTaskPause(entry)} - > - - - - ) : null} -
+ {entries.filter(entry => rail || !hierarchy.nestedIds.has(entry.id)).map((entry) => ( + + {renderTaskRow(entry)} + ))}
diff --git a/ui/src/context/LiveUpdatesProvider.read-receipts.test.ts b/ui/src/context/LiveUpdatesProvider.read-receipts.test.ts index d327a07442c..9e716b6bc96 100644 --- a/ui/src/context/LiveUpdatesProvider.read-receipts.test.ts +++ b/ui/src/context/LiveUpdatesProvider.read-receipts.test.ts @@ -42,7 +42,12 @@ describe("live read receipts", () => { const unread = queryKeys.issues.listUnreadTouchedByMe("company-1"); const badges = queryKeys.sidebarBadges("company-1"); const chats = queryKeys.agentChats.list("company-1", "viewer"); - const ownReads = [mine, touched, unread, badges, chats].map(key => watch(key)); + 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.test.ts b/ui/src/context/LiveUpdatesProvider.test.ts index 302fcf6b9e3..fbb7981015d 100644 --- a/ui/src/context/LiveUpdatesProvider.test.ts +++ b/ui/src/context/LiveUpdatesProvider.test.ts @@ -276,7 +276,7 @@ describe("LiveUpdatesProvider issue invalidation", () => { "refreshes company AI account previews after %s", (action) => { const invalidateQueries = vi.fn(); __liveUpdatesTestUtils.invalidateActivityQueries( - { invalidateQueries, getQueryData: () => undefined } as never, + { invalidateQueries, getQueryData: () => undefined, getQueryCache: () => ({ findAll: () => [] }) } as never, "company-1", { entityType: "connection_grant", entityId: "grant-1", action }, { userId: "owner", agentId: null }, ); @@ -288,6 +288,7 @@ describe("LiveUpdatesProvider issue invalidation", () => { it("refreshes touched inbox queries and only the changed issue data for issue updates", () => { const invalidations: unknown[] = []; const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), invalidateQueries: (input: unknown) => { invalidations.push(input); }, @@ -347,6 +348,7 @@ describe("LiveUpdatesProvider issue invalidation", () => { it("still refreshes comments when a comment activity event arrives", () => { const invalidations: unknown[] = []; const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), invalidateQueries: (input: unknown) => { invalidations.push(input); }, @@ -373,6 +375,7 @@ describe("LiveUpdatesProvider issue invalidation", () => { it("keeps heartbeat progress invalidation scoped away from hot list queries", () => { const invalidations: unknown[] = []; const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), invalidateQueries: (input: unknown) => { invalidations.push(input); }, @@ -416,6 +419,7 @@ describe("LiveUpdatesProvider issue invalidation", () => { it("refreshes the selected run detail after lifecycle events", () => { const invalidations: unknown[] = []; const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), invalidateQueries: (input: unknown) => { invalidations.push(input); }, @@ -521,6 +525,7 @@ describe("LiveUpdatesProvider issue invalidation", () => { [JSON.stringify(queryKeys.issues.runs("DEMO-759")), [{ runId: "run-1" }]], ]); const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), getQueryData: (key: unknown) => cache.get(JSON.stringify(key)), setQueryData: (key: unknown, updater: unknown) => { const cacheKey = JSON.stringify(key); @@ -625,6 +630,7 @@ describe("LiveUpdatesProvider issue invalidation", () => { it("refreshes issue document caches when a document activity event arrives", () => { const invalidations: unknown[] = []; const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), invalidateQueries: (input: unknown) => { invalidations.push(input); }, @@ -690,6 +696,7 @@ describe("LiveUpdatesProvider issue invalidation", () => { it("refreshes all issue document caches when document activity omits a document key", () => { const invalidations: unknown[] = []; const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), invalidateQueries: (input: unknown) => { invalidations.push(input); }, @@ -874,6 +881,7 @@ describe("LiveUpdatesProvider issue invalidation", () => { it("refreshes document annotation caches when annotation activity arrives", () => { const invalidations: unknown[] = []; const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), invalidateQueries: (input: unknown) => { invalidations.push(input); }, @@ -913,6 +921,7 @@ describe("LiveUpdatesProvider issue invalidation", () => { it("refreshes routine description annotation caches when routine annotation activity arrives", () => { const invalidations: unknown[] = []; const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), invalidateQueries: (input: unknown) => { invalidations.push(input); }, @@ -1103,6 +1112,7 @@ describe("LiveUpdatesProvider issue invalidation", () => { it("keeps self-authored comment events from refetching the active issue tree", () => { const invalidations: unknown[] = []; const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), invalidateQueries: (input: unknown) => { invalidations.push(input); }, @@ -1140,6 +1150,7 @@ describe("LiveUpdatesProvider issue invalidation", () => { it("treats self-authored comment-driven issue updates as inactive-only refreshes", () => { const invalidations: unknown[] = []; const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), invalidateQueries: (input: unknown) => { invalidations.push(input); }, @@ -1177,6 +1188,7 @@ describe("LiveUpdatesProvider issue invalidation", () => { it("keeps visible issue detail refetches inactive for downstream agent updates", () => { const invalidations: unknown[] = []; const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), invalidateQueries: (input: unknown) => { invalidations.push(input); }, @@ -1223,6 +1235,7 @@ describe("LiveUpdatesProvider issue invalidation", () => { it("still actively refetches visible issue detail for board-authored updates", () => { const invalidations: unknown[] = []; const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), invalidateQueries: (input: unknown) => { invalidations.push(input); }, @@ -1271,6 +1284,7 @@ describe("LiveUpdatesProvider issue invalidation", () => { it("actively refreshes interactions materialized by a visible native status decision", () => { const invalidations: unknown[] = []; const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), invalidateQueries: (input: unknown) => { invalidations.push(input); }, @@ -1323,6 +1337,7 @@ describe("LiveUpdatesProvider issue invalidation", () => { it("keeps visible issue comment updates inactive-only instead of active refetching", () => { const invalidations: unknown[] = []; const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), invalidateQueries: (input: unknown) => { invalidations.push(input); }, @@ -1421,6 +1436,7 @@ describe("LiveUpdatesProvider issue invalidation", () => { [JSON.stringify(queryKeys.issues.runs("issue-1")), [{ runId: "run-1" }]], ]); const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), invalidateQueries: (input: unknown) => { invalidations.push(input); }, @@ -1496,6 +1512,7 @@ describe("LiveUpdatesProvider issue invalidation", () => { (status) => { const invalidations: unknown[] = []; const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), invalidateQueries: (input: unknown) => invalidations.push(input), getQueryData: (key: unknown) => { if (JSON.stringify(key) === JSON.stringify(queryKeys.issues.detail("PAP-759"))) { @@ -1523,6 +1540,7 @@ describe("LiveUpdatesProvider issue invalidation", () => { it("ignores run status events for other issues", () => { const invalidations: unknown[] = []; const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), invalidateQueries: (input: unknown) => { invalidations.push(input); }, @@ -1603,6 +1621,7 @@ describe("LiveUpdatesProvider visible issue comment hydration", () => { const setCalls: Array<{ key: unknown; value: unknown }> = []; const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), getQueryData: (key: unknown) => { if (JSON.stringify(key) === JSON.stringify(queryKeys.issues.detail("PAP-759"))) { return { @@ -1684,6 +1703,7 @@ describe("LiveUpdatesProvider visible issue comment hydration", () => { describe("LiveUpdatesProvider visible issue toast suppression", () => { it("suppresses activity toasts for the issue page currently in view", () => { const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), getQueryData: (key: unknown) => { if (JSON.stringify(key) === JSON.stringify(queryKeys.issues.detail("PAP-759"))) { return { @@ -1725,6 +1745,7 @@ describe("LiveUpdatesProvider visible issue toast suppression", () => { it("suppresses run and agent status toasts for the assignee of the visible issue", () => { const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), getQueryData: (key: unknown) => { if (JSON.stringify(key) === JSON.stringify(queryKeys.issues.activeRun("PAP-759"))) return { id: "run-1" }; if (JSON.stringify(key) === JSON.stringify(queryKeys.issues.detail("PAP-759"))) { @@ -1767,6 +1788,7 @@ describe("LiveUpdatesProvider visible issue toast suppression", () => { describe("LiveUpdatesProvider run lifecycle toasts", () => { it("does not build start or success toasts for agent runs", () => { const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), getQueryData: () => [], }; @@ -1803,6 +1825,7 @@ describe("LiveUpdatesProvider run lifecycle toasts", () => { it("still builds failure toasts for agent errors and failed runs", () => { const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), getQueryData: () => [ { id: "agent-1", @@ -2014,6 +2037,7 @@ describe("LiveUpdatesProvider summary slot invalidation", () => { it("invalidates the slot and revisions queries on summary_slot.write", () => { const invalidations: unknown[] = []; const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), invalidateQueries: (input: unknown) => { invalidations.push(input); }, @@ -2048,6 +2072,7 @@ describe("LiveUpdatesProvider summary slot invalidation", () => { it("maps a null scopeId to a company-scoped slot key", () => { const invalidations: unknown[] = []; const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), invalidateQueries: (input: unknown) => { invalidations.push(input); }, @@ -2077,6 +2102,7 @@ describe("LiveUpdatesProvider summary slot invalidation", () => { it("skips slot invalidation when scope details are missing", () => { const invalidations: unknown[] = []; const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), invalidateQueries: (input: unknown) => { invalidations.push(input); }, @@ -2167,6 +2193,7 @@ describe("task subtree notification context", () => { const root = { id: "root", companyId: "company", identifier: "PAP-204", assigneeAgentId: "parent-agent" }; const descendants = [{ id: "child", identifier: "PAP-205", assigneeAgentId: "child-agent", executionRunId: "child-run" }]; const queryClient = { + getQueryCache: () => ({ findAll: () => [] }), getQueryData: (key: unknown) => { if (JSON.stringify(key) === JSON.stringify(queryKeys.issues.detail("PAP-204"))) return root; if (JSON.stringify(key) === JSON.stringify(queryKeys.issues.listByDescendantRoot("company", "root"))) return descendants; diff --git a/ui/src/context/LiveUpdatesProvider.tsx b/ui/src/context/LiveUpdatesProvider.tsx index da33c16bbe1..65a5d0fc553 100644 --- a/ui/src/context/LiveUpdatesProvider.tsx +++ b/ui/src/context/LiveUpdatesProvider.tsx @@ -4,6 +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 { createContext, useCallback, @@ -1489,7 +1490,11 @@ function invalidateHeartbeatQueries( companyId: string, payload: Record, ) { - queryClient.invalidateQueries({ queryKey: queryKeys.issues.summaries(companyId) }); + const parentIds = Array.isArray(payload.recentSubtaskParentIds) + ? 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) }); @@ -1583,6 +1588,8 @@ function invalidateActivityQueries( const actorType = readString(payload.actorType); const actorId = readString(payload.actorId); const details = readRecord(payload.details); + const subtaskParents = Array.isArray(payload.recentSubtaskParentIds) + ? payload.recentSubtaskParentIds.filter((id): id is string => typeof id === "string") : undefined; queryClient.invalidateQueries({ queryKey: queryKeys.activity(companyId) }); if (entityType === "issue" && (action === "issue.read_marked" || action === "issue.read_unmarked")) { // Audit views show read receipts, while unread state belongs to one person. @@ -1593,6 +1600,8 @@ 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), queryKeys.issues.listTouchedByMe(companyId), @@ -1625,6 +1634,8 @@ 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. for (const queryKey of [queryKeys.attention(companyId), ["decisions", companyId, "task-record"], ["issues", "decision-receipts"], ["issues", "chat-handoffs"], ["issues", "pending-questions"]]) { @@ -1664,6 +1675,8 @@ 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); const chatListKey = queryKeys.agentChats.list(companyId, currentActor.userId); @@ -1679,7 +1692,8 @@ function invalidateActivityQueries( } queryClient.invalidateQueries({ queryKey: queryKeys.issues.list(companyId), - predicate: excludingQueryKeys(queryKeys.issues.mentionPool(companyId), queryKeys.issues.listIndex(companyId)), + predicate: excludingQueryKeys(queryKeys.issues.mentionPool(companyId), queryKeys.issues.listIndex(companyId), + [...queryKeys.issues.list(companyId), "recent-subtasks"], 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 064c0e53e6b..ed6820c6480 100644 --- a/ui/src/hooks/useRecentTasks.test.tsx +++ b/ui/src/hooks/useRecentTasks.test.tsx @@ -176,6 +176,26 @@ describe("recent task synchronization", () => { expect(getIssue).not.toHaveBeenCalled(); expect(cache.getQueryCache().findAll({ queryKey: ["issues", "detail"] })).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"); + summaries.mockResolvedValue([parent]); + const cache = client(); + let entries: ReturnType["entries"] = []; + 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(readRecentTasks(storageKey, "company-1")[0]).not.toHaveProperty("isUnreadForMe"); + expect(readRecentTasks(storageKey, "company-1")[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 }); + }); it("does not fetch empty history", async () => { await act(async () => root.render()); diff --git a/ui/src/hooks/useRecentTasks.ts b/ui/src/hooks/useRecentTasks.ts index eadab2beb51..e826bebf2f5 100644 --- a/ui/src/hooks/useRecentTasks.ts +++ b/ui/src/hooks/useRecentTasks.ts @@ -40,9 +40,9 @@ export function useRecentTasks({ entries: storageKey && companyId ? readRecentTasks(storageKey, companyId) : [], })); // A scope change must not request the previous account's IDs for one render. - const entries = snapshot.storageKey === storageKey + const entries = useMemo(() => snapshot.storageKey === storageKey ? snapshot.entries - : storageKey && companyId ? readRecentTasks(storageKey, companyId) : []; + : storageKey && companyId ? readRecentTasks(storageKey, companyId) : [], [snapshot, storageKey, companyId]); const setEntries = (next: RecentTaskEntry[]) => setSnapshot({ storageKey, entries: next }); useEffect(() => { @@ -95,7 +95,7 @@ export function useRecentTasks({ const worker = async () => { while (next < chunks.length) { const index = next++; - results[index] = await issuesApi.summaries(companyId!, chunks[index]!, { signal }); + results[index] = await issuesApi.summaries(companyId!, chunks[index]!, { signal, navigation: true }); } }; await Promise.all(Array.from({ length: Math.min(RECENT_TASK_SUMMARY_CONCURRENCY, chunks.length) }, worker)); @@ -109,12 +109,16 @@ export function useRecentTasks({ const fetchingSummaries = summaryQuery.isFetching; const updateCount = queryClient.getQueryState(summaryKey)?.dataUpdateCount ?? 0; const summaries = summaryQuery.isSuccess ? summaryQuery.data : undefined; - const confirmed = new Map((summaries ?? []).filter((issue) => issue.companyId === companyId) - .map((issue) => [issue.id, issue])); - const refreshedEntries = entries.map((entry) => { + // 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 issue = confirmed.get(entry.id); - return issue ? mergeRecentTaskSnapshot(entry, issue) : entry; - }); + // 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); useEffect(() => { @@ -173,11 +177,14 @@ export function useRecentTasks({ return () => window.clearTimeout(timeout); }, [activityRevision, membership, settledOrder, storageKey]); - const entryById = new Map(refreshedEntries.map((entry) => [entry.id, entry])); - const hasSameMembership = settledOrder.length === entries.length && settledOrder.every((id) => entryById.has(id)); + const orderedEntries = useMemo(() => { + const entryById = new Map(refreshedEntries.map((entry) => [entry.id, entry])); + const hasSameMembership = settledOrder.length === refreshedEntries.length && settledOrder.every((id) => entryById.has(id)); + return hasSameMembership ? settledOrder.map((id) => entryById.get(id)!) : refreshedEntries; + }, [refreshedEntries, settledOrder]); return { - entries: hasSameMembership ? settledOrder.map((id) => entryById.get(id)!) : refreshedEntries, + entries: orderedEntries, storageKey, }; } diff --git a/ui/src/index.css b/ui/src/index.css index c9839ffea65..8de519452bf 100644 --- a/ui/src/index.css +++ b/ui/src/index.css @@ -4816,9 +4816,12 @@ html:has(.design-proposal-theme) .design-navigation-group-label { .design-sidebar-recents .design-sidebar-item { font-weight: var(--font-weight-normal); } .design-sidebar-navigation > :not(.design-sidebar-recents) { flex-shrink: 0; } .design-sidebar-recents { display: flex; flex: 1; min-height: 0; } +.design-sidebar-recents [data-slot="sidebar-group-label"] { color: var(--muted-foreground); } .design-sidebar-recents > div { display: flex; flex: 1; flex-direction: column; min-width: 0; min-height: 0; } .design-sidebar-recents > div > :first-child { flex-shrink: 0; } .design-sidebar-recents > div > :last-child { flex: 1; min-height: 0; } +.design-sidebar-recents [data-slot="collapsible-content"][data-state="open"], +.design-sidebar-recents [data-slot="collapsible-content"] > div { display: flex; flex: 1; flex-direction: column; min-width: 0; min-height: 0; } .design-sidebar-recent-list { --recent-fade-top: 0px; --recent-fade-bottom: 0px; diff --git a/ui/src/lib/recent-subtask-requests.test.ts b/ui/src/lib/recent-subtask-requests.test.ts new file mode 100644 index 00000000000..5edbc978e92 --- /dev/null +++ b/ui/src/lib/recent-subtask-requests.test.ts @@ -0,0 +1,30 @@ +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 new file mode 100644 index 00000000000..1f8082cebed --- /dev/null +++ b/ui/src/lib/recent-subtask-requests.ts @@ -0,0 +1,34 @@ +/** 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-subtasks-refresh.ts b/ui/src/lib/recent-subtasks-refresh.ts new file mode 100644 index 00000000000..4a72c2d393c --- /dev/null +++ b/ui/src/lib/recent-subtasks-refresh.ts @@ -0,0 +1,53 @@ +import type { InfiniteData, 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, +) { + // Old servers have no parent hints. Keep their summary fallback, while + // current servers identify new children even outside every cached page. + if (!parentIds) { + void client.invalidateQueries({ queryKey: queryKeys.issues.summaries(companyId) }); + return; + } + const affected = new Set(parentIds); + if (issueId) affected.add(issueId); + const batches = client.getQueryCache().findAll({ queryKey: queryKeys.issues.summaries(companyId) }); + for (const batch of batches) { + const rows = batch.state.data; + if (Array.isArray(rows)) for (const row of rows) { + if (row.companyId === companyId && row.id === issueId && typeof row.parentId === "string") affected.add(row.parentId); + } + } + for (const batch of batches) { + const ids = batch.queryKey[4]; + if (Array.isArray(ids) && ids.some(id => affected.has(id))) { + void client.invalidateQueries({ queryKey: batch.queryKey, exact: true }); + } + } +} diff --git a/ui/src/lib/recent-task-hierarchy.test.ts b/ui/src/lib/recent-task-hierarchy.test.ts new file mode 100644 index 00000000000..2a90d733d3f --- /dev/null +++ b/ui/src/lib/recent-task-hierarchy.test.ts @@ -0,0 +1,32 @@ +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 new file mode 100644 index 00000000000..caf1f2772ca --- /dev/null +++ b/ui/src/lib/recent-task-hierarchy.ts @@ -0,0 +1,44 @@ +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 selectedRef = parseIssuePathIdFromPath(pathname); + const selected = entries.find(entry => entry.id === selectedRef || entry.identifier === selectedRef); + return { nestedIds, flattenedIds, selectedChild: selected && nestedIds.has(selected.id) ? selected : undefined }; +} diff --git a/ui/src/lib/recent-tasks.ts b/ui/src/lib/recent-tasks.ts index 5dedf071330..f80c4a6603c 100644 --- a/ui/src/lib/recent-tasks.ts +++ b/ui/src/lib/recent-tasks.ts @@ -14,6 +14,11 @@ 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. diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx index a852c5ede64..bce716f434d 100644 --- a/ui/src/pages/IssueDetail.tsx +++ b/ui/src/pages/IssueDetail.tsx @@ -3354,6 +3354,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS const fileInputRef = useRef(null); const readReceiptRef = useRef<{ issueId: string; + companyId: string; account: ReturnType; attemptedSessionAt?: number; confirmed: boolean; @@ -4614,6 +4615,9 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS }, onSuccess: (_data, receipt) => { 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), @@ -6243,7 +6247,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS const receipt = readReceiptRef.current?.issueId === issue.id ? readReceiptRef.current : (readReceiptRef.current = pendingReadReceiptsRef.current.get(issue.id) - ?? { issueId: issue.id, account: bindAccount(queryClient), confirmed: false }); + ?? { issueId: issue.id, companyId: issue.companyId, account: bindAccount(queryClient), confirmed: false }); if (receipt.confirmed || pendingReadReceiptsRef.current.has(issue.id) || !receipt.account.isCurrentScope()) return; // Retry after a successful session read, without looping on a failed check. if (receipt.attemptedSessionAt === sessionUpdatedAt) return; diff --git a/ui/storybook/stories/navigation-preferences/recent-subtasks.stories.tsx b/ui/storybook/stories/navigation-preferences/recent-subtasks.stories.tsx new file mode 100644 index 00000000000..b33105b4f80 --- /dev/null +++ b/ui/storybook/stories/navigation-preferences/recent-subtasks.stories.tsx @@ -0,0 +1,107 @@ +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { expect, userEvent, within } from "storybook/test"; +import { CoordinatorSidebar } from "@/components/CoordinatorSidebar"; +import { SidebarRecentTasks } from "@/components/SidebarRecentTasks"; +import { recordRecentTask, getRecentTasksStorageKey } from "@/lib/recent-tasks"; +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 }; +const companyId = "company-storybook"; +const userId = "user-board"; +const parentTitle = "Ship the project workspace"; +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 }; +} +function SidebarExample({ scenario }: Args) { + return
+ {scenario === "classic" ? : } +
; +} + +const meta = { + id: "design-recent-subtasks", + title: "Oversight and operation/Navigation, profile, and announcements/Sidebar subtasks", + component: SidebarExample, + args: { scenario: "expanded" }, + 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.", + } }, + 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 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); + 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}/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); }; + }, + 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" })); + }, +} 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" } };