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 <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-11-15 08:51:04 -06:00
1 parent eb65fc0941
commit 5b750fdf25
39 files changed
+1454 -117

No files matched your search

+16
View File
@@ -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
+14
View File
@@ -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
```
+5
View File
@@ -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 {
+1
View File
@@ -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)]),
@@ -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<typeof express>['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<void>(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);
}
@@ -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);
});
@@ -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<typeof issueComments.$inferInsert>(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<typeof issueThreadInteractions.$inferInsert>(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<string, Promise<unknown>>();
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<Record<string, unknown>> = [];
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];
@@ -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/);
+21 -4
View File
@@ -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<typeof getHeartbeatRunReadDecisions>[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 } };
@@ -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<string, unknown>,
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<string, unknown> | null | undefined;
const previous = details?._previous as Record<string, unknown> | 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) };
}
+39 -3
View File
@@ -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);
+7 -2
View File
@@ -679,7 +679,12 @@ function issuePrivacyPrincipalCondition(actor: AuthorizationActor): SQL<boolean>
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<boolean>`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<boolean>`((${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<boolean>
and private_project.company_id = restricted.company_id
where restricted.visibility = 'private' or private_project.visibility = 'private'
)
)`;
))`;
}
function issuePrivacyCondition(actor: AuthorizationActor): SQL<boolean> {
+3 -3
View File
@@ -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<boolean>) {
return sql<boolean>`
(
(${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<boolean>`EXISTS (
SELECT 1
FROM ${issueComments}
WHERE ${issueComments.issueId} = ${issues.id}
AND ${issueComments.companyId} = ${companyId}
AND ${issueComments.authorUserId} = ${userId}
AND ${directHumanCommentCondition()}
)
)`}
)
`;
}
+100 -2
View File
@@ -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<boolean>,
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,
}]));
}
+23 -15
View File
@@ -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<Date | null>`
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<boolean>`${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<boolean>`
(
${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());
}
}
@@ -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",
@@ -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<string, Array<{ status?: string }>> };
}).__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);
});
+5 -1
View File
@@ -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<InboxMineSnapshot>(path, { ...options, cache: "no-store" });
},
summaries: async (companyId: string, issueIds: readonly string[], options?: RequestOptions): Promise<IssueSummary[]> => {
summaries: async (companyId: string, issueIds: readonly string[], options?: RequestOptions & { navigation?: boolean }): Promise<IssueSummary[]> => {
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.
@@ -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<HTMLButtonElement>('[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<HTMLButtonElement>('[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,
+11 -4
View File
@@ -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<HTMLDivElement>(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 = <Button type="button" variant="ghost" className="design-sidebar-new-task rounded-lg" aria-label="New task" onClick={() => openNewIssue()}>
<SquarePen aria-hidden />
<span className={rail ? SIDEBAR_RAIL_HIDDEN_LABEL : "truncate"}>New task</span>
@@ -194,10 +198,13 @@ export function CoordinatorSidebar({ children }: { children?: ReactNode }) {
</Flyout>
</div>
{pinnedNavigation.error && <p role="alert" className="px-4 py-2 text-xs text-destructive">{pinnedNavigation.error}</p>}
{!rail && session.isSuccess && recents.length > 0 && <div className="design-sidebar-recents"><SidebarSection label="Recents">
{!rail && session.isSuccess && recents.length > 0 && <div className="design-sidebar-recents"><SidebarSection label="Recents" collapsible={{ open: recentsOpen, onOpenChange: setRecentsOpen }}>
<RecentNavigationList>
{recents.map(item => item.kind === "task"
? <RecentTaskNavItem className="design-sidebar-item" key={item.id} task={item.task} label={item.task.title} iconNode={<StatusIcon {...taskStatusIconProps(item.task)} />} />
? <RecentTaskGroup key={`${scope}:${item.id}`} task={item.task} userId={userId} className="design-sidebar-item" flattened={hierarchy.flattenedIds.has(item.id)}
selectedChild={hierarchy.selectedChild?.parentId === item.id ? hierarchy.selectedChild : undefined}>
<RecentTaskNavItem className="design-sidebar-item" task={item.task} label={item.task.title} iconNode={<StatusIcon {...taskStatusIconProps(item.task)} />} />
</RecentTaskGroup>
: item.kind === "chat"
? <SidebarNavItem className="design-sidebar-item" key={item.id} to={`/chats/${encodeURIComponent(agentRouteRef(item.agent))}`} label={item.agent.name} iconNode={<AgentAvatar agent={item.agent} size={16} />} />
: <ProjectRecent key={item.id} project={item.project} />)}
@@ -0,0 +1,140 @@
// @vitest-environment jsdom
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { QueryClient, QueryClientProvider, QueryObserver } from '@tanstack/react-query';
import { expect, it, vi } from 'vitest';
import { RecentTaskGroup } from './RecentTaskGroup';
import { queryKeys } from '@/lib/queryKeys';
import { __liveUpdatesTestUtils } from '@/context/LiveUpdatesProvider';
import { recentTaskHierarchy } from '@/lib/recent-task-hierarchy';
import { createCoalescingQueryClient } from '@/lib/query-invalidation-batcher';
const observed = vi.hoisted(()=>({callbacks:new Map<Element,IntersectionObserverCallback>(),requests:[] as any[], hold:false}));
vi.mock('@/api/issues',()=>({issuesApi:{listCompact:async(companyId:string,f:any,options?:{signal?:AbortSignal})=>{
observed.requests.push({parentId:f.parentId,afterId:f.afterId});
if (observed.hold) await new Promise<void>((_resolve,reject)=> {
const signal=options?.signal;
if(signal?.aborted) reject(signal.reason);
else signal?.addEventListener('abort',()=>reject(signal.reason),{once:true});
});
const start=f.afterId?Number(f.afterId.split(':').at(-1))+1:0;
return Array.from({length:10},(_,i)=>({id:`${f.parentId}:${start+i}`,companyId,parentId:f.parentId,title:`Child ${start+i}`,status:'todo',identifier:null}));
}}}));
vi.mock('./RecentTaskNavItem',()=>({RecentTaskNavItem:({task}:any)=><a>{task.title}</a>}));
vi.mock('./StatusIcon',()=>({StatusIcon:()=>null}));
(globalThis as any).IS_REACT_ACT_ENVIRONMENT=true;
it('measures visibility, paging and real live-event invalidation fanout',async()=>{
class Observer {
cb:IntersectionObserverCallback;
constructor(cb:IntersectionObserverCallback){this.cb=cb;}
observe(el:Element){observed.callbacks.set(el,this.cb);}
unobserve(){}
disconnect(){}
}
vi.stubGlobal('IntersectionObserver',Observer);
const company='company',user='viewer';
const tasks=Array.from({length:50},(_,i)=>({id:`parent-${i}`,companyId:company,title:`Parent ${i}`,identifier:null,status:'todo' as const,recordedAt:0,subtaskCount:100}));
const client=new QueryClient({defaultOptions:{queries:{retry:false,gcTime:0}}});
const batcher=__liveUpdatesTestUtils.createLiveInvalidationBatcher(client,company);
const liveClient=createCoalescingQueryClient(client,batcher);
const div=document.createElement('div');document.body.appendChild(div);const root=createRoot(div);
let summaryRequests=0;
const summary=new QueryObserver(client,{queryKey:queryKeys.issues.summaryBatch(company,user,tasks.map(t=>t.id)),queryFn:async()=>{summaryRequests++;return []},staleTime:30_000});
const unobserve=summary.subscribe(()=>{});
const flush=async()=>{await act(async()=>{await new Promise(r=>setTimeout(r,30));});};
const refresh=async(entityId='unrelated', parentIds?:string[], action='issue.updated', actorId='agent')=>{observed.requests.length=0;summaryRequests=0;await act(async()=>{
__liveUpdatesTestUtils.invalidateActivityQueries(liveClient,company,{entityType:'issue',entityId,action,actorType:action.startsWith('issue.read_')?'user':'agent',actorId,details:{},...(parentIds ? {recentSubtaskParentIds:parentIds} : {})},{userId:user} as any);
await batcher.flush();
});await flush();return {childRequests:observed.requests.length,summaryRequests,requestsByParent:Object.fromEntries(tasks.map(t=>[t.id,observed.requests.filter(r=>r.parentId===t.id).length]).filter(([,n])=>n))};};
try{
await act(async()=>root.render(<QueryClientProvider client={client}>{tasks.map(task=><RecentTaskGroup task={task} userId={user} key={task.id}><a>{task.title}</a></RecentTaskGroup>)}</QueryClientProvider>));await flush();
const report:any={environment:'jsdom; actual RecentTaskGroup/query hooks/coalesced live invalidation; simplified leaf markup',measurement:'requests per single flushed live-update batch; production ambient batches are spaced 5000ms',parents:50,initialOffscreenRequests:observed.requests.length};
expect(report.initialOffscreenRequests).toBe(0);
const anchors=[...observed.callbacks.entries()];
async function reveal(start:number,end:number,visible=true){await act(async()=>{for(const [el,cb]of anchors.slice(start,end))cb([{isIntersecting:visible,target:el} as any],{} as any)});await flush();}
await reveal(0,8);report.firstEightVisibleRequests=observed.requests.length;expect(report.firstEightVisibleRequests).toBe(8);
report.unrelatedEventWithEightVisited=await refresh();
// Load three pages of one group, then return it to ten visible children.
const group=div.querySelector('[aria-label="Subtasks of Parent 0"]')!;
for(let page=0;page<2;page++){await act(async()=>{[...group.querySelectorAll('button')].find(b=>b.textContent?.includes('Show more'))!.click()});await flush();}
await act(async()=>{[...group.querySelectorAll('button')].find(b=>b.textContent==='Show less')!.click()});await flush();
report.afterShowLess=await refresh();
report.relevantAfterShowLess=await refresh('parent-0:0', ['parent-0']);
expect(report.relevantAfterShowLess.childRequests).toBe(1);
expect(observed.requests[0].afterId).toBeUndefined();
report.newChildBeyondPreview=await refresh('new-child', ['parent-7']);
expect(report.newChildBeyondPreview.requestsByParent).toEqual({'parent-7':1});
report.reparent=await refresh('new-child', ['parent-6','parent-7']);
expect(report.reparent.requestsByParent).toEqual({'parent-6':1,'parent-7':1});
report.uncachedDeletion=await refresh('parent-7', [], 'issue.child_deleted');
expect(report.uncachedDeletion.requestsByParent).toEqual({'parent-7':1});
report.ownRead=await refresh('parent-7:0', ['parent-7'], 'issue.read_marked', user);
expect(report.ownRead.requestsByParent).toEqual({'parent-7':1});
report.otherRead=await refresh('parent-7:0', ['parent-7'], 'issue.read_marked', 'other-user');
expect(report.otherRead.childRequests).toBe(0);
// A current server supplies an empty authorized-parent set for unrelated work.
report.unrelatedWithParentHints=await refresh('unrelated', []);
expect(report.unrelatedWithParentHints).toMatchObject({childRequests:0,summaryRequests:0});
await reveal(0,8,false);
report.relevantOffscreen=await refresh('parent-7:0', ['parent-7']);
expect(report.relevantOffscreen.childRequests).toBe(0);
observed.requests.length=0;
await reveal(7,8);
report.returnToViewportRequests=observed.requests.length;
expect(report.returnToViewportRequests).toBe(1);
await reveal(8,50);
report.afterAllFiftyHaveBeenViewed=await refresh();
await act(async()=>{div.querySelector<HTMLButtonElement>('[aria-label="Collapse subtasks of Parent 0"]')!.click()});await flush();
report.afterCollapseOne=await refresh();
expect((await refresh('parent-0:0', ['parent-0'])).childRequests).toBe(0);
report.largeHierarchy=[];
for(const size of [50,500,5000,10000]){
const entries=Array.from({length:size},(_,i)=>({...tasks[0],id:`task-${i}`,parentId:i%2?`task-${i-1}`:null,subtaskCount:i%2?0:1}));
const samples=[];for(let i=0;i<25;i++){const start=performance.now();const h=recentTaskHierarchy(entries,'/PAP/issues/task-1');expect(h.nestedIds.size).toBe(size/2);samples.push(performance.now()-start);}
samples.sort((a,b)=>a-b);report.largeHierarchy.push({size,medianMs:samples[12],maxMs:samples.at(-1)});
}
expect(report.unrelatedEventWithEightVisited.childRequests).toBe(0);
expect(report.afterShowLess.childRequests).toBe(0);
expect(report.afterAllFiftyHaveBeenViewed.childRequests).toBe(0);
expect(report.afterCollapseOne.childRequests).toBe(0);
console.log(JSON.stringify(report));
}finally{batcher.dispose();unobserve();await act(async()=>root.unmount());client.clear();div.remove();vi.unstubAllGlobals();}
},30000);
it('cancels pending HTTP reads and queued groups when they leave the viewport', async () => {
observed.callbacks.clear(); observed.requests.length=0; observed.hold=true;
class Observer {
constructor(private cb:IntersectionObserverCallback) {}
observe(el:Element) { observed.callbacks.set(el,this.cb); }
disconnect() {}
}
vi.stubGlobal('IntersectionObserver',Observer);
const client=new QueryClient({defaultOptions:{queries:{retry:false,gcTime:0}}});
const div=document.createElement('div'); document.body.appendChild(div);
const root=createRoot(div);
const settle=()=>act(async()=>{await new Promise(resolve=>setTimeout(resolve,20));});
try {
const tasks=Array.from({length:50},(_,i)=>({id:`parent-${i}`,companyId:'company',title:`Parent ${i}`,identifier:null,status:'todo' as const,recordedAt:0,subtaskCount:100}));
await act(async()=>root.render(<QueryClientProvider client={client}>{tasks.map(task=><RecentTaskGroup task={task} userId="viewer" key={task.id}><a>{task.title}</a></RecentTaskGroup>)}</QueryClientProvider>));
const anchors=[...observed.callbacks.entries()];
const show=(visible:boolean)=>act(async()=>{
for(const [el,cb] of anchors) cb([{isIntersecting:visible,target:el} as IntersectionObserverEntry],{} as IntersectionObserver);
});
await show(true); await settle();
expect(observed.requests).toHaveLength(3);
expect(client.isFetching()).toBe(50);
await show(false); await settle();
expect(client.isFetching()).toBe(0);
expect(observed.requests).toHaveLength(3);
observed.hold=false;
const [el,cb]=anchors[49]!;
await act(async()=>cb([{isIntersecting:true,target:el} as IntersectionObserverEntry],{} as IntersectionObserver));
await settle();
expect(observed.requests.map(r=>r.parentId)).toEqual(['parent-0','parent-1','parent-2','parent-49']);
} finally {
observed.hold=false;
await act(async()=>root.unmount());client.clear();div.remove();vi.unstubAllGlobals();
}
});
+120
View File
@@ -0,0 +1,120 @@
import { useEffect, useId, useRef, useState, type ReactNode } from "react";
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
import { readRecentSubtasks } from "@/lib/recent-subtask-requests";
import { ChevronRight } from "lucide-react";
import { issuesApi } from "@/api/issues";
import { queryKeys } from "@/lib/queryKeys";
import { cn } from "@/lib/utils";
import type { RecentTaskEntry } from "@/lib/recent-tasks";
import { RecentTaskNavItem } from "./RecentTaskNavItem";
import { StatusIcon } from "./StatusIcon";
import { taskStatusIconProps } from "@/lib/task-status-presentation";
import { QueryErrorState, useQueryView } from "./QueryView";
export const RECENT_SUBTASK_PAGE_SIZE = 10;
/** Shared by the standard mixed Recents and Classic Recent Tasks. */
type RecentTaskGroupProps = {
task: RecentTaskEntry;
userId: string | null | undefined;
selectedChild?: RecentTaskEntry;
children: ReactNode;
className?: string;
rail?: boolean;
renderChild?: (task: RecentTaskEntry) => ReactNode;
/** Invalid cyclic ancestry remains reachable as plain task rows. */
flattened?: boolean;
};
export function RecentTaskGroup(props: RecentTaskGroupProps) {
if (!props.task.subtaskCount || props.rail || props.flattened) return <>{props.children}</>;
return <ExpandableRecentTaskGroup {...props} />;
}
function ExpandableRecentTaskGroup({ task, userId, selectedChild, children, className, rail = false, renderChild }: RecentTaskGroupProps) {
const [expanded, setExpanded] = useState(true);
const [showAllLoaded, setShowAllLoaded] = useState(false);
const anchor = useRef<HTMLDivElement>(null);
const [visible, setVisible] = useState(typeof IntersectionObserver === "undefined");
const contentId = useId();
const queryClient = useQueryClient();
const queryKey = [...queryKeys.issues.list(task.companyId), "recent-subtasks", userId ?? "__local_board__", task.id];
const count = task.subtaskCount ?? 0;
useEffect(() => { if (selectedChild) setExpanded(true); }, [selectedChild?.id]);
// Large recent histories must not start one child request per offscreen parent.
useEffect(() => {
if (!anchor.current || typeof IntersectionObserver === "undefined") return;
const observer = new IntersectionObserver(([entry]) => {
setVisible(Boolean(entry?.isIntersecting));
});
observer.observe(anchor.current);
return () => observer.disconnect();
}, [count, rail]);
const enabled = count > 0 && expanded && visible && !rail;
const query = useInfiniteQuery({
queryKey,
queryFn: ({ pageParam, signal }) => readRecentSubtasks(signal, () => issuesApi.listCompact(task.companyId, {
parentId: task.id, projection: "rows", limit: RECENT_SUBTASK_PAGE_SIZE,
sortField: "id", sortDir: "asc", afterId: pageParam, includeRoutineExecutions: true, includeReadState: true,
}, { signal, cache: "no-store", fresh: true })),
initialPageParam: undefined as string | undefined,
getNextPageParam: (lastPage) => lastPage.length === RECENT_SUBTASK_PAGE_SIZE ? lastPage.at(-1)?.id : undefined,
enabled,
staleTime: 30_000,
});
useEffect(() => {
if (!enabled) void queryClient.cancelQueries({ queryKey, exact: true });
// Scope and eligibility own cancellation; queryKey is rebuilt each render.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [queryClient, task.companyId, task.id, userId, enabled]);
const preview = () => {
setShowAllLoaded(false);
// Cancel first so an in-flight next page cannot restore discarded pages.
void queryClient.cancelQueries({ queryKey, exact: true }).then(() => {
queryClient.setQueryData<typeof query.data>(queryKey, data => data ? {
pages: data.pages.slice(0, 1), pageParams: data.pageParams.slice(0, 1),
} : data);
});
};
const view = useQueryView(query);
// Always filter by scope/parent, including cache data after an account switch.
const pages = query.data?.pages ?? [];
const loaded = [...new Map(pages.flat().filter(child => child.companyId === task.companyId && child.parentId === task.id)
.map(child => [child.id, child])).values()];
let displayed = showAllLoaded ? loaded : loaded.slice(0, RECENT_SUBTASK_PAGE_SIZE);
const pinned = selectedChild && !displayed.some(child => child.id === selectedChild.id) ? selectedChild : undefined;
// A selected child beyond the first page replaces the last preview row.
if (pinned && !showAllLoaded) displayed = displayed.slice(0, RECENT_SUBTASK_PAGE_SIZE - 1);
const hiddenUnread = Math.max(0, (task.unreadSubtaskCount ?? 0) - displayed.filter(child => child.isUnreadForMe).length - (pinned?.isUnreadForMe ? 1 : 0));
const remaining = Math.max(0, count - displayed.length - (pinned ? 1 : 0));
const controlClass = "mx-2 rounded-md px-2 py-1 text-left text-xs text-muted-foreground hover:bg-sidebar-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring";
const childRow = (child: RecentTaskEntry) => renderChild ? renderChild(child)
: <RecentTaskNavItem task={child} label={child.title} className={className} iconNode={<StatusIcon {...taskStatusIconProps(child)} />} />;
if (!count || rail) return <>{children}</>;
return <div ref={anchor} className="min-w-0">
<div className="relative">
<div className="pl-5">{children}</div>
<button type="button" aria-label={`${expanded ? "Collapse" : "Expand"} subtasks of ${task.title}`} aria-expanded={expanded} aria-controls={expanded ? contentId : undefined}
onClick={() => { if (expanded) preview(); setExpanded(value => !value); }}
className="absolute left-0 top-1 flex size-6 items-center justify-center rounded-md text-muted-foreground hover:bg-sidebar-accent focus-visible:ring-2 focus-visible:ring-ring">
<ChevronRight aria-hidden="true" className={cn("size-3.5 transition-transform motion-reduce:transition-none", expanded && "rotate-90")} />
</button>
</div>
{!expanded ? <button type="button" className={cn(controlClass, "ml-7")} onClick={() => setExpanded(true)}>
{count} subtasks{task.unreadSubtaskCount ? ` · ${task.unreadSubtaskCount} unread` : ""}
</button> : <div id={contentId} className="ml-5 min-w-0 border-l border-border pl-1" role="group" aria-label={`Subtasks of ${task.title}`}>
{(view.kind === "loading" || view.kind === "reconnecting") && <p role="status" className="px-3 py-1 text-xs text-muted-foreground">Loading subtasks…</p>}
{displayed.map(child => <div key={child.id}>{childRow({ ...child, recordedAt: 0 })}</div>)}
{pinned && childRow(pinned)}
{view.kind === "error" ? <QueryErrorState size="inline" action="load subtasks" error={view.error} retrying={view.isFetching}
className="px-3 py-1 text-xs" onRetry={() => { if (query.isFetchNextPageError) void query.fetchNextPage(); else view.retry(); }} />
: view.data && loaded.length === 0 ? <p className="px-3 py-1 text-xs text-muted-foreground">No subtasks available.</p> : null}
{remaining > 0 && loaded.length > 0 && (loaded.length > displayed.length || query.hasNextPage) && view.kind !== "error" && <button type="button" disabled={query.isFetching} className={controlClass}
onClick={() => { setShowAllLoaded(true); if (loaded.length <= displayed.length + (pinned ? 1 : 0) && query.hasNextPage) void query.fetchNextPage(); }}>
{query.isFetching ? "Loading…" : `Show more (${remaining})`}{hiddenUnread > 0 ? ` · ${hiddenUnread} unread` : ""}
</button>}
{showAllLoaded && displayed.length > RECENT_SUBTASK_PAGE_SIZE && <button type="button" className={controlClass} onClick={preview}>Show less</button>}
</div>}
</div>;
}
+9 -2
View File
@@ -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<ComponentProps<typeof SidebarNavItem>, "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 <SidebarNavItem {...props} to={to ?? `/issues/${pathRef}`} linkHandlers={linkHandlers} />;
return <SidebarNavItem {...props} to={to ?? `/issues/${pathRef}`} linkHandlers={linkHandlers}
labelClassName={cn(task.isUnreadForMe && "font-semibold", labelClassName)}
trailing={<>{trailing}{task.isUnreadForMe && <span className="flex shrink-0 items-center" aria-label="Unread">
<span className="size-1.5 rounded-full bg-primary" aria-hidden="true" /><span className="sr-only">Unread</span>
</span>}</>} />;
}
@@ -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({
+70 -58
View File
@@ -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<RecentTaskEntry | null>(null);
@@ -247,66 +252,73 @@ function RecentTasksList({
}
};
const renderTaskRow = (entry: RecentTaskEntry) => (
<div className="sidebar-action-row group/recent-task relative">
<RecentTaskNavItem
task={entry}
label={entry.title}
iconNode={entry.displayStatus === "monitoring" && !liveIssueIds.has(entry.id) ? <StatusIcon {...taskStatusIconProps(entry)} /> : undefined}
trailing={entry.status === "in_review" && entry.externalConversationState === "waiting"
? <span className="text-xs text-muted-foreground">Idle</span> : 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 ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon-xs"
aria-label={`More actions for ${entry.title}`}
className="sidebar-action-menu absolute right-2 top-(--pct-50) z-10 -translate-y-(--pct-50) text-muted-foreground pointer-events-none opacity-0 transition-opacity hover:bg-sidebar-accent dark:hover:bg-sidebar-accent hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 pointer-coarse:pointer-events-auto pointer-coarse:opacity-100 pointer-coarse:before:hidden group-hover/recent-task:pointer-events-auto group-hover/recent-task:opacity-100 group-focus-within/recent-task:pointer-events-auto group-focus-within/recent-task:opacity-100 data-[state=open]:pointer-events-auto data-[state=open]:bg-sidebar-accent data-[state=open]:text-foreground data-[state=open]:opacity-100"
>
<MoreHorizontal aria-hidden="true" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent
side="right"
align="start"
className="w-(--profile-popover-width) rounded-xl p-1.5 shadow-(--shadow-profile-popover)"
>
<DropdownMenuItem
className={RECENT_TASK_MENU_ITEM_CLASS}
onSelect={() => beginRename(entry)}
>
<Pencil aria-hidden="true" />
Rename
</DropdownMenuItem>
<DropdownMenuItem
className={RECENT_TASK_MENU_ITEM_CLASS}
disabled={pendingAction !== null}
onSelect={() => void archiveTask(entry)}
>
<Archive aria-hidden="true" />
Archive
</DropdownMenuItem>
<DropdownMenuItem
className={RECENT_TASK_MENU_ITEM_CLASS}
disabled={pendingAction !== null}
onSelect={() => void toggleTaskPause(entry)}
>
<RefreshCw aria-hidden="true" />
Pause/Restart
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
) : null}
</div>
);
return (
<>
<SidebarSection label="Recent Tasks">
{entries.map((entry) => (
<div key={entry.id} className="sidebar-action-row group/recent-task relative">
<RecentTaskNavItem
task={entry}
label={entry.title}
iconNode={entry.displayStatus === "monitoring" && !liveIssueIds.has(entry.id) ? <StatusIcon {...taskStatusIconProps(entry)} /> : undefined}
trailing={entry.status === "in_review" && entry.externalConversationState === "waiting"
? <span className="text-xs text-muted-foreground">Idle</span> : 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 ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon-xs"
aria-label={`More actions for ${entry.title}`}
className="sidebar-action-menu absolute right-2 top-(--pct-50) z-10 -translate-y-(--pct-50) text-muted-foreground pointer-events-none opacity-0 transition-opacity hover:bg-sidebar-accent dark:hover:bg-sidebar-accent hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 pointer-coarse:pointer-events-auto pointer-coarse:opacity-100 pointer-coarse:before:hidden group-hover/recent-task:pointer-events-auto group-hover/recent-task:opacity-100 group-focus-within/recent-task:pointer-events-auto group-focus-within/recent-task:opacity-100 data-[state=open]:pointer-events-auto data-[state=open]:bg-sidebar-accent data-[state=open]:text-foreground data-[state=open]:opacity-100"
>
<MoreHorizontal aria-hidden="true" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent
side="right"
align="start"
className="w-(--profile-popover-width) rounded-xl p-1.5 shadow-(--shadow-profile-popover)"
>
<DropdownMenuItem
className={RECENT_TASK_MENU_ITEM_CLASS}
onSelect={() => beginRename(entry)}
>
<Pencil aria-hidden="true" />
Rename
</DropdownMenuItem>
<DropdownMenuItem
className={RECENT_TASK_MENU_ITEM_CLASS}
disabled={pendingAction !== null}
onSelect={() => void archiveTask(entry)}
>
<Archive aria-hidden="true" />
Archive
</DropdownMenuItem>
<DropdownMenuItem
className={RECENT_TASK_MENU_ITEM_CLASS}
disabled={pendingAction !== null}
onSelect={() => void toggleTaskPause(entry)}
>
<RefreshCw aria-hidden="true" />
Pause/Restart
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
) : null}
</div>
{entries.filter(entry => rail || !hierarchy.nestedIds.has(entry.id)).map((entry) => (
<RecentTaskGroup key={entry.id} task={entry} userId={userId} rail={rail} flattened={hierarchy.flattenedIds.has(entry.id)}
selectedChild={hierarchy.selectedChild?.parentId === entry.id ? hierarchy.selectedChild : undefined} renderChild={renderTaskRow}>
{renderTaskRow(entry)}
</RecentTaskGroup>
))}
</SidebarSection>
@@ -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"],
+28 -1
View File
@@ -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;
+16 -2
View File
@@ -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<string, unknown>,
) {
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(
+20
View File
@@ -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<typeof useRecentTasks>["entries"] = [];
function State() { entries = useRecentTasks({ companyId: "company-1", userId: "user-1" }).entries; return null; }
await act(async () => root.render(<QueryClientProvider client={cache}><State /></QueryClientProvider>));
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(<QueryClientProvider client={cache}><State /></QueryClientProvider>));
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(<QueryClientProvider client={client()}><RecentTasks name="empty" /></QueryClientProvider>));
+18 -11
View File
@@ -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,
};
}
+3
View File
@@ -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;
@@ -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<void>(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 });
});
+34
View File
@@ -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<T>(signal: AbortSignal, read: () => Promise<T>): Promise<T> {
await new Promise<void>((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();
}
}
}
+53
View File
@@ -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<Child[]> | 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 });
}
}
}
+32
View File
@@ -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);
});
});
+44
View File
@@ -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<string, string>();
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<string, boolean>();
const flattenedIds = new Set<string>();
for (const entry of entries) {
if (nested.has(entry.id)) continue;
const path: string[] = [];
const positions = new Map<string, number>();
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 };
}
+5
View File
@@ -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.
+5 -1
View File
@@ -3354,6 +3354,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
const fileInputRef = useRef<HTMLInputElement | null>(null);
const readReceiptRef = useRef<{
issueId: string;
companyId: string;
account: ReturnType<typeof bindAccount>;
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;
@@ -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 <div className={`coordinator-workspace h-screen ${scenario === "narrow" ? "w-60" : "w-72"}`}>
{scenario === "classic" ? <SidebarRecentTasks companyId={companyId} liveIssueIds={new Set()} /> : <CoordinatorSidebar />}
</div>;
}
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<Args>;
export default meta;
type Story = StoryObj<typeof meta>;
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" } };