mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 23:56:43 +01:00
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:
1 parent
eb65fc0941
commit
5b750fdf25
39 files changed
+1454
-117
No files matched your search
@@ -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/);
|
||||
|
||||
@@ -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) };
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -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()}
|
||||
)
|
||||
)`}
|
||||
)
|
||||
`;
|
||||
}
|
||||
@@ -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,
|
||||
}]));
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user