From 9bc90cb189bbb0f31206c0baeda6286be052f103 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Fri, 20 Nov 2026 14:40:39 -0800 Subject: [PATCH] Show useful task notification content (#22441) Task notifications repeated identifiers and omitted useful activity details. Use task titles, actor and comment previews, and concrete field changes. Share bounded secret redaction per event after viewer access checks. Suppress updates without useful details. Verified with focused regression tests, package typechecks and server build, and the full green CI run. Greptile scored the final head 5/5 with no unresolved review threads. Co-Authored-By: Paperclip --- doc/TOASTS.md | 38 +++- .../issue-activity-events-routes.test.ts | 26 +++ .../__tests__/live-events-run-read.test.ts | 205 +++++++++++++++++- .../src/__tests__/live-events-toast.test.ts | 68 +++++- .../__tests__/run-secret-redaction.test.ts | 32 +++ .../realtime/activity-toast-details.test.ts | 38 ++++ server/src/realtime/activity-toast-details.ts | 42 ++++ .../src/realtime/activity-toast-identity.ts | 52 ++++- server/src/realtime/live-events-ws.ts | 17 +- server/src/routes/issues.ts | 2 +- server/src/services/run-secret-redaction.ts | 30 ++- .../context/LiveUpdatesProvider.hook.test.tsx | 8 +- ui/src/context/LiveUpdatesProvider.test.ts | 99 ++++++--- ui/src/context/LiveUpdatesProvider.tsx | 107 ++++----- 14 files changed, 636 insertions(+), 128 deletions(-) create mode 100644 server/src/realtime/activity-toast-details.test.ts create mode 100644 server/src/realtime/activity-toast-details.ts diff --git a/doc/TOASTS.md b/doc/TOASTS.md index fc984f1a640..6b1eb2517f4 100644 --- a/doc/TOASTS.md +++ b/doc/TOASTS.md @@ -63,10 +63,40 @@ never persisted or published on the shared company event bus. Authorized events still reach cache handling and component subscribers when eligibility is false. Lookup failure is logged but does not discard the authorized event. Existing task/run privacy checks and payload redaction remain in force. -Task activity titles, fallback text, and links use the authorized task identifier. -If the optional identifier lookup fails, the event still arrives and uses `Task` -unless the browser already has the identifier. Permission-check failures do not -use this fallback. +Task activity notifications use the task title as their heading. The body names +the actor and previews the comment or describes the change, including the old +and new status when available. Markdown in comment previews becomes plain text. +Updates without a meaningful change stay quiet. Comment-driven updates produce +one notification with the comment and its changes. Creation notifications name +the creator. The title is limited to 120 characters and the body to 240. + +After task-read authorization, the server adds the persisted task title and a +closed `notificationDetails` projection of the already-redacted activity. This +projection allows bounded comment IDs/previews, known status/priority values, +assignment/change flags, and comment/reopen context. It does not copy arbitrary +activity details, task descriptions, or raw change receipts. The title uses the +existing company-scoped identifier lookup. Comment previews read the complete +non-deleted comment by company, task, and comment ID. Task-registered secrets are +redacted from the complete title/comment before the preview is shortened, using +the same task redaction registry as HTTP reads. Titles and comment previews both apply the existing +pattern-based credential and configured username redaction, including creation +and update events without a comment. The notification +path uses the existing task-context indexes in two ordered reads, each limited to +129 rows. It accepts at most 128 distinct runs, 64 unique secrets and 64 KiB of +unique encrypted material, with a 16 KiB registry limit per run. Exceeding a limit +omits free text; the browser can use a previously loaded task title. HTTP history +reads retain their existing redaction behavior. + +Authorized viewers share one identity/redaction promise for the same published +event. Each viewer still passes its own access check before reading that result. +The shared result contains redacted text and expires with the event object. Each +new event reads fresh redaction data; no plaintext secret values are cached. +Registry reads select only secret metadata, not full run contexts. Missing comments +and read/redaction failures omit the preview; they never reuse the event snippet. +If the optional task-identity lookup fails, the event still arrives. The browser uses a cached +title or `Task`; task identifiers remain in navigation links. Permission-check +failures do not use this fallback. Older servers can supply cached titles and +legacy activity details, but unspecified updates remain quiet. When an authenticated comment event omits the comment ID, the visible task thread refreshes through its authorized HTTP read instead of trying to hydrate the comment. Closed sockets cannot deliver stale notifications after account/company changes. diff --git a/server/src/__tests__/issue-activity-events-routes.test.ts b/server/src/__tests__/issue-activity-events-routes.test.ts index 14a4cb6e93d..b138f7ab27f 100644 --- a/server/src/__tests__/issue-activity-events-routes.test.ts +++ b/server/src/__tests__/issue-activity-events-routes.test.ts @@ -284,6 +284,32 @@ describe("issue activity event routes", () => { expect(noOp.body.changes).not.toHaveProperty("title"); }); + it("includes field changes in the paired comment activity for one useful notification", async () => { + const issue = { ...makeIssue(), status: "backlog" }; + mockIssueService.getById.mockResolvedValue(issue); + mockIssueService.update.mockImplementation(async (_id: string, patch: Record) => + issueUpdateWithReceipt(issue, patch)); + mockIssueService.addComment.mockResolvedValue({ + id: "comment-1", companyId: issue.companyId, issueId: issue.id, + body: "Please review first", authorUserId: "local-board", authorAgentId: null, + createdAt: new Date(), updatedAt: new Date(), + }); + + const response = await request(await createApp()) + .patch(`/api/issues/${issue.id}`) + .send({ priority: "high", comment: "Please review first" }); + expect(response.status, JSON.stringify(response.body)).toBe(200); + expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ + action: "issue.updated", details: expect.objectContaining({ source: "comment" }), + })); + expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ + action: "issue.comment_added", details: expect.objectContaining({ + commentId: "comment-1", bodySnippet: "Please review first", updated: true, + changes: { priority: { from: "medium", to: "high" } }, + }), + })); + }); + it("echoes scalar blocker state and summaries when setting and clearing blockers", async () => { const issue = makeIssue(); const blockerId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; diff --git a/server/src/__tests__/live-events-run-read.test.ts b/server/src/__tests__/live-events-run-read.test.ts index 0e514cfd15f..2727ef5988f 100644 --- a/server/src/__tests__/live-events-run-read.test.ts +++ b/server/src/__tests__/live-events-run-read.test.ts @@ -3,9 +3,11 @@ import { plugins, heartbeatRunEvents } from "@paperclipai/db"; import { subscribeCompanyLiveEvents } from "../services/live-events.js"; import { createHash, randomBytes, randomUUID } from "node:crypto"; import { homedir } from "node:os"; +import { getSecretProvider } from "../secrets/provider-registry.js"; import { redactEventPayload } from "../redaction.js"; import { redactCurrentUserValue } from "../log-redaction.js"; import { createRunSecretRedactionRegistry } from "../services/run-secret-redaction.js"; +import { redactActivityDetails } from "../services/activity-log.js"; import { instanceSettingsService } from "../services/instance-settings.js"; import { once } from "node:events"; import { createServer } from "node:http"; @@ -13,10 +15,10 @@ import type { AddressInfo } from "node:net"; import { eq } from "drizzle-orm"; import { drizzle } from "drizzle-orm/postgres-js"; import { WebSocket } from "ws"; -import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { agentApiKeys, agents, authUsers, companies, companyMemberships, createDb, - heartbeatRuns, issueAccessGrants, issues, type Db, + heartbeatRuns, issueAccessGrants, issueComments, issues, type Db, } from "@paperclipai/db"; import * as schema from "@paperclipai/db/schema/index"; import { setupLiveEventsWebSocketServer } from "../realtime/live-events-ws.js"; @@ -295,6 +297,205 @@ describe("live-event run read boundaries", () => { } }); + it.each(["authenticated", "local_trusted"] as const)("redacts full saved notification text before preview truncation (%s)", async deploymentMode => { + const companyId = randomUUID(), viewer = randomUUID(), issueId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Notification redaction", issuePrefix: `NR${companyId.slice(0, 6)}` }); + await db.insert(authUsers).values({ id: viewer, name: "Fixture viewer", email: `${viewer}@example.test`, createdAt: new Date(), updatedAt: new Date() }); + await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: viewer, membershipRole: "operator", status: "active" }); + const [agent] = await db.insert(agents).values({ companyId, name: "Notification fixture", adapterType: "process" }).returning(); + const registered = "ordinary-notification-credential-value"; + await db.insert(issues).values({ id: issueId, companyId, title: `Review ${registered}` }); + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId: agent.id, scopeKind: "issue", issueId, + contextSnapshot: { issueId }, status: "running" }).returning(); + const registry = createRunSecretRedactionRegistry(db); + await registry.register(companyId, run.id, registered); + const previousCensor = (await instanceSettingsService(db).getGeneral()).censorUsernameInLogs; + await instanceSettingsService(db).updateGeneral({ censorUsernameInLogs: true }); + let failRedaction = false; + const observedDb = drizzle(db.$client, { schema, logger: { logQuery(query) { + if (failRedaction && query.startsWith("select ") && query.includes("paperclipSecretRedactions")) throw new Error("fixture secret registry unavailable"); + } } }) as Db; + const server = createServer(); + const wss = setupLiveEventsWebSocketServer(server, observedDb, { deploymentMode, + resolveCloudActor: async () => ({ userId: viewer, companyIds: [companyId] }) }); + server.listen(0, "127.0.0.1"); await once(server, "listening"); + const socket = new WebSocket(`ws://127.0.0.1:${(server.address() as AddressInfo).port}/api/companies/${companyId}/events/ws`); + const deliver = async (commentId: string, body: string) => { + const message = once(socket, "message"); + publishLiveEvent({ companyId, type: "activity.logged", payload: { action: "issue.comment_added", entityType: "issue", entityId: issueId, + actorType: "agent", actorId: agent.id, details: { commentId, bodySnippet: body.slice(0, 120), issueTitle: `Review ${registered}`, + changes: { description: { from: registered, to: body } } } } }); + const [bytes] = await message; + return JSON.parse(bytes.toString()).payload; + }; + try { + await once(socket, "open"); + for (const body of [`Review ${registered} now`, `${"x".repeat(110)} ${registered} now`, `${homedir()}/notify.txt Authorization: Bearer header-fixture-value`]) { + const [comment] = await db.insert(issueComments).values({ companyId, issueId, body, authorAgentId: agent.id }).returning(); + const payload = await deliver(comment.id, body); + const expected = await redactActivityDetails(db, await registry.redactForIssue(companyId, issueId, { issueTitle: `Review ${registered}`, bodySnippet: body })); + expect(payload.issueTitle).toBe(expected?.issueTitle); + expect(payload.notificationDetails.bodySnippet).toBe(expected?.bodySnippet); + expect(JSON.stringify(payload)).not.toContain(registered); + expect(JSON.stringify(payload)).not.toContain(registered.slice(0, 9)); + } + const titleWithPath = `${homedir()}/notify-task ${registered}`; + await db.update(issues).set({ title: titleWithPath }).where(eq(issues.id, issueId)); + const deliverTitle = async (action: string) => { + const message = once(socket, "message"); + publishLiveEvent({ companyId, type: "activity.logged", payload: { action, entityType: "issue", entityId: issueId, + actorType: "system", details: { status: "blocked" } } }); + const [bytes] = await message; + return JSON.parse(bytes.toString()).payload; + }; + const maskedTitle = await redactActivityDetails(db, await registry.redactForIssue(companyId, issueId, { issueTitle: titleWithPath })); + for (const action of ["issue.created", "issue.updated"]) { + const payload = await deliverTitle(action); + expect(payload.issueTitle).toBe(maskedTitle?.issueTitle); + expect(JSON.stringify(payload)).not.toContain(homedir()); + } + await instanceSettingsService(db).updateGeneral({ censorUsernameInLogs: false }); + const unmaskedTitle = await registry.redactForIssue(companyId, issueId, { issueTitle: titleWithPath }); + expect((await deliverTitle("issue.updated")).issueTitle).toBe(unmaskedTitle.issueTitle); + await instanceSettingsService(db).updateGeneral({ censorUsernameInLogs: true }); + const foreignIssueId = randomUUID(); + await db.insert(issues).values({ id: foreignIssueId, companyId, title: "Other task" }); + const [foreign] = await db.insert(issueComments).values({ companyId, issueId: foreignIssueId, body: registered }).returning(); + expect((await deliver(foreign.id, registered)).notificationDetails).not.toHaveProperty("bodySnippet"); + const [deleted] = await db.insert(issueComments).values({ companyId, issueId, body: registered, deletedAt: new Date() }).returning(); + expect((await deliver(deleted.id, registered)).notificationDetails).not.toHaveProperty("bodySnippet"); + const [comment] = await db.insert(issueComments).values({ companyId, issueId, body: registered }).returning(); + failRedaction = true; + const refused = await deliver(comment.id, registered); + expect(refused.issueTitle).toBeNull(); + expect(refused.notificationDetails).not.toHaveProperty("bodySnippet"); + expect(JSON.stringify(refused)).not.toContain(registered); + } finally { + await instanceSettingsService(db).updateGeneral({ censorUsernameInLogs: previousCensor }); + socket.terminate(); + wss.close(); + await new Promise(resolve => server.close(() => resolve())); + } + }); + + it("shares notification redaction across viewers and refreshes secrets for each new event", async () => { + const companyId = randomUUID(), viewer = randomUUID(), issueId = randomUUID(), otherIssueId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Notification fanout", issuePrefix: `NF${companyId.slice(0, 6)}` }); + await db.insert(authUsers).values({ id: viewer, name: "Fixture viewer", email: `${viewer}@example.test`, createdAt: new Date(), updatedAt: new Date() }); + await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: viewer, membershipRole: "operator", status: "active" }); + const [agent] = await db.insert(agents).values({ companyId, name: "Fanout fixture", adapterType: "process" }).returning(); + const registered = "fanout-registered-fixture-value"; + await db.insert(issues).values([{ id: issueId, companyId, title: `Review ${registered}`, createdByUserId: viewer }, { id: otherIssueId, companyId, title: "Unrelated history" }]); + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId: agent.id, scopeKind: "issue", issueId, contextSnapshot: { issueId } }).returning(); + await db.insert(heartbeatRuns).values(Array.from({ length: 512 }, () => ({ companyId, agentId: agent.id, scopeKind: "issue" as const, + issueId: otherIssueId, contextSnapshot: { issueId: otherIssueId } }))); + const registry = createRunSecretRedactionRegistry(db); + await registry.register(companyId, run.id, registered); + const registryQueries: Array<{ query: string; params: unknown[] }> = []; + const observedDb = drizzle(db.$client, { schema, logger: { logQuery(query, params) { + if (query.startsWith("select ") && query.includes("paperclipSecretRedactions")) registryQueries.push({ query, params }); + } } }) as Db; + const resolve = vi.spyOn(getSecretProvider("local_encrypted"), "resolveVersion"); + const server = createServer(); + const wss = setupLiveEventsWebSocketServer(server, observedDb, { deploymentMode: "authenticated", + resolveCloudActor: async () => ({ userId: viewer, companyIds: [companyId] }) }); + server.listen(0, "127.0.0.1"); await once(server, "listening"); + const url = `ws://127.0.0.1:${(server.address() as AddressInfo).port}/api/companies/${companyId}/events/ws`; + const sockets = Array.from({ length: 6 }, () => new WebSocket(url)); + const deliver = async () => { + const messages = Promise.all(sockets.map(socket => once(socket, "message"))); + publishLiveEvent({ companyId, type: "activity.logged", payload: { action: "issue.updated", entityType: "issue", entityId: issueId, + actorType: "system", details: { status: "done" } } }); + return (await messages).map(([bytes]) => JSON.parse(bytes.toString())); + }; + try { + await Promise.all(sockets.map(socket => once(socket, "open"))); + for (let event = 0; event < 3; event += 1) { + for (const message of await deliver()) expect(message.payload.issueTitle).toBe("Review ***REDACTED***"); + } + expect(registryQueries).toHaveLength(6); + expect(resolve).toHaveBeenCalledTimes(3); + const nextSecret = "newly-registered-fanout-value"; + await registry.register(companyId, run.id, nextSecret); + await db.update(issues).set({ title: `Review ${nextSecret}` }).where(eq(issues.id, issueId)); + for (const message of await deliver()) expect(message.payload.issueTitle).toBe("Review ***REDACTED***"); + expect(registryQueries).toHaveLength(8); + expect(resolve).toHaveBeenCalledTimes(5); + } finally { + resolve.mockRestore(); + sockets.forEach(socket => socket.terminate()); + wss.close(); + await new Promise(resolve => server.close(() => resolve())); + } + }); + + it("bounds notification history reads with existing indexes and hides text on budget overflow", async () => { + const companyId = randomUUID(), viewer = randomUUID(), issueId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Bounded notification", issuePrefix: `NB${companyId.slice(0, 6)}` }); + await db.insert(authUsers).values({ id: viewer, name: "Fixture viewer", email: `${viewer}@example.test`, createdAt: new Date(), updatedAt: new Date() }); + await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: viewer, membershipRole: "operator", status: "active" }); + const [agent] = await db.insert(agents).values({ companyId, name: "Budget fixture", adapterType: "process" }).returning(); + await db.insert(issues).values({ id: issueId, companyId, title: "Bounded title", createdByUserId: viewer }); + await db.insert(heartbeatRuns).values(Array.from({ length: 512 }, () => ({ companyId, agentId: agent.id, scopeKind: "issue" as const, + issueId, contextSnapshot: { paperclipIssue: { id: issueId } } }))); + const unrelatedIssueId = randomUUID(); + await db.insert(issues).values({ id: unrelatedIssueId, companyId, title: "Other task history" }); + await db.insert(heartbeatRuns).values(Array.from({ length: 1024 }, () => ({ companyId, agentId: agent.id, scopeKind: "issue" as const, + issueId: unrelatedIssueId, contextSnapshot: { paperclipIssue: { id: unrelatedIssueId } } }))); + const registryQueries: Array<{ query: string; params: unknown[] }> = []; + const observedDb = drizzle(db.$client, { schema, logger: { logQuery(query, params) { + if (query.startsWith("select ") && query.includes("paperclipSecretRedactions")) registryQueries.push({ query, params }); + } } }) as Db; + const resolve = vi.spyOn(getSecretProvider("local_encrypted"), "resolveVersion"); + const server = createServer(); + const wss = setupLiveEventsWebSocketServer(server, observedDb, { deploymentMode: "authenticated", + resolveCloudActor: async () => ({ userId: viewer, companyIds: [companyId] }) }); + server.listen(0, "127.0.0.1"); await once(server, "listening"); + const socket = new WebSocket(`ws://127.0.0.1:${(server.address() as AddressInfo).port}/api/companies/${companyId}/events/ws`); + try { + await once(socket, "open"); + const received = once(socket, "message"); + publishLiveEvent({ companyId, type: "activity.logged", payload: { action: "issue.updated", entityType: "issue", entityId: issueId, + actorType: "system", details: { status: "blocked" } } }); + const [bytes] = await received; + const event = JSON.parse(bytes.toString()); + expect(event.payload.issueTitle).toBeNull(); + expect(event.payload.notificationDetails).toEqual({ status: "blocked" }); + expect(registryQueries).toHaveLength(2); + expect(resolve).not.toHaveBeenCalled(); + await db.$client.unsafe('ANALYZE heartbeat_runs'); + for (const statement of registryQueries) { + expect(statement.query).toMatch(/order by .*created_at.*desc(?: nulls last)? limit/); + const rows = await db.$client.unsafe(`EXPLAIN (ANALYZE, FORMAT JSON) ${statement.query}`, statement.params as never[]); + const plan = JSON.stringify(rows[0]["QUERY PLAN"]); + expect(plan).toMatch(/heartbeat_runs_company_ctx_(?:issue|paperclip_issue)_created_idx/); + type Plan = { "Actual Rows": number; "Rows Removed by Filter"?: number; Plans?: Plan[] }; + const bounded = (node: Plan) => { + expect(node["Actual Rows"] + (node["Rows Removed by Filter"] ?? 0)).toBeLessThanOrEqual(129); + node.Plans?.forEach(bounded); + }; + bounded((rows[0]["QUERY PLAN"] as Array<{ Plan: Plan }>)[0].Plan); + } + const oversizedIssue = randomUUID(); + const oversizedSecret = "oversized-notification-fixture".repeat(1000); + await db.insert(issues).values({ id: oversizedIssue, companyId, title: oversizedSecret }); + const [oversizedRun] = await db.insert(heartbeatRuns).values({ companyId, agentId: agent.id, issueId: oversizedIssue, + scopeKind: "issue", contextSnapshot: { issueId: oversizedIssue } }).returning(); + await createRunSecretRedactionRegistry(db).register(companyId, oversizedRun.id, oversizedSecret); + const oversizedMessage = once(socket, "message"); + publishLiveEvent({ companyId, type: "activity.logged", payload: { action: "issue.updated", entityType: "issue", entityId: oversizedIssue, + actorType: "system", details: { status: "blocked" } } }); + const [oversizedBytes] = await oversizedMessage; + expect(JSON.parse(oversizedBytes.toString()).payload.issueTitle).toBeNull(); + expect(resolve).not.toHaveBeenCalled(); + } finally { + resolve.mockRestore(); + socket.terminate(); + wss.close(); + await new Promise(resolve => server.close(() => resolve())); + } + }); + it.each([["authenticated", "native"], ["local_trusted", "native"], ["authenticated", "panel"], ["local_trusted", "panel"]] as const)("redacts %s live rows like history reads for %s events", async (deploymentMode, kind) => { const companyId = randomUUID(), viewer = randomUUID(); await db.insert(companies).values({ id: companyId, name: "Live redaction", issuePrefix: `LR${companyId.slice(0, 6)}` }); diff --git a/server/src/__tests__/live-events-toast.test.ts b/server/src/__tests__/live-events-toast.test.ts index 8c1794b164a..ce8e7eaf978 100644 --- a/server/src/__tests__/live-events-toast.test.ts +++ b/server/src/__tests__/live-events-toast.test.ts @@ -23,15 +23,19 @@ vi.mock("../services/case-access.js", () => ({ canActorReadCase: async (_db: unknown, _actor: unknown, record: { id: string }) => record.id !== "hidden-case", })); function database(onPredicate: (kind: "where" | "join", condition: SQL) => void = () => {}) { - return { select: (fields: Record) => { + return { select: (fields: Record = {}) => { let table = ""; const query = { from: (value: Parameters[0]) => { table = getTableName(value); return query; }, innerJoin: (_table: unknown, condition: SQL) => { onPredicate("join", condition); return query; }, where: (condition: SQL) => { onPredicate("where", condition); return query; }, + orderBy: () => query, + then: (resolve: (rows: unknown[]) => unknown) => Promise.resolve(table === "instance_settings" + ? [{ id: "settings", general: { censorUsernameInLogs: false }, experimental: {} }] : []).then(resolve), limit: async () => { - if (table === "issues") return [{ id: "task", identifier: "PAP-1234" }]; + if (table === "issues") return [{ id: "task", identifier: "PAP-1234", title: "Fix task notifications" }]; if (table === "company_memberships") return fields.name ? [{ name: "Alex Example", image: "/alex.png" }] : [{ id: "membership" }]; + if (table === "issue_comments") return [{ body: "Ready for review" }]; if (table === "agents") return [{ name: "Coder", appearance: { schemaVersion: 1, characterVersion: "cap-v1", paletteId: "bubblegum-sky" } }]; return []; }, @@ -46,7 +50,7 @@ describe("authenticated activity notifications", () => { const pending = new Promise(resolve => { release = resolve; }); const started = new Promise(resolve => { entered = resolve; }); const db = database(), select = db.select; - db.select = fields => { + db.select = (fields = {}) => { const query = select(fields); if (fields.identifier) { const limit = query.limit; @@ -86,7 +90,7 @@ describe("authenticated activity notifications", () => { const db = database(); const select = db.select; const identifierRead = vi.fn(); - db.select = fields => { + db.select = (fields = {}) => { if (fields.identifier) { identifierRead(); if (identifierRead.mock.calls.length <= 3) throw new Error("Identifier lookup unavailable"); @@ -138,6 +142,48 @@ describe("authenticated activity notifications", () => { } }); + it.each(["authenticated", "local_trusted"] as const)("delivers useful task content through the real socket (%s)", async deploymentMode => { + const server = createServer(); + setupLiveEventsWebSocketServer(server, database() as never, { deploymentMode, + resolveCloudActor: async () => ({ userId: "viewer", companyIds: ["company"] }) }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const socket = new WebSocket(`ws://127.0.0.1:${(server.address() as { port: number }).port}/api/companies/company/events/ws`); + try { + await once(socket, "open"); + const messages: Array<{ payload: Record }> = []; + socket.on("message", data => messages.push(JSON.parse(data.toString()))); + const activity = (entityId: string, action: string, details: Record) => publishLiveEvent({ + companyId: "company", type: "activity.logged", payload: { + action, entityType: "issue", entityId, actorType: "system", issueTitle: "Spoofed title", details, + notificationDetails: { bodySnippet: "Spoofed preview" }, + }, + }); + const changes = { status: { from: "in_progress", to: "done" }, description: { from: "private old", to: "private new" } }; + if (deploymentMode === "authenticated") activity("hidden", "issue.comment_added", { bodySnippet: "Hidden comment" }); + let delivery = once(socket, "message"); + activity("visible", "issue.updated", { source: "comment", changes, secret: "private token" }); + await delivery; + delivery = once(socket, "message"); + activity("visible", "issue.comment_added", { commentId: "comment-1", bodySnippet: "Ready for review", changes, secret: "private token" }); + await delivery; + expect(messages).toHaveLength(2); + expect(messages[0].payload).toMatchObject({ issueTitle: "Fix task notifications", notificationDetails: { + source: "comment", status: "done", statusFrom: "in_progress", descriptionChanged: true, + } }); + expect(messages[1].payload).toMatchObject({ issueTitle: "Fix task notifications", notificationDetails: { + commentId: "comment-1", bodySnippet: "Ready for review", status: "done", statusFrom: "in_progress", descriptionChanged: true, + } }); + if (deploymentMode === "authenticated") { + expect(messages[1].payload).not.toHaveProperty("details"); + expect(JSON.stringify(messages)).not.toMatch(/private token|private old|private new|Spoofed|Hidden comment/); + } + } finally { + socket.terminate(); + await new Promise(resolve => server.close(() => resolve())); + } + }); + it("preserves only an authorized handoff task identity for empty case-panel refresh", async () => { const server = createServer(); setupLiveEventsWebSocketServer(server, database() as never, { deploymentMode: "authenticated", @@ -247,7 +293,7 @@ describe("authenticated activity notifications", () => { socket.on("message", (data) => messages.push(JSON.parse(data.toString()))); const activity = (entityId: string, actorType = "user") => publishLiveEvent({ companyId: "company", type: "activity.logged", payload: { action: "issue.created", entityType: "issue", entityId, actorType, actorId: actorType === "user" ? "viewer" : "agent", - issueIdentifier: "SPOOF-1", + issueIdentifier: "SPOOF-1", issueTitle: "Untrusted title", details: { bodySnippet: "private comment", secret: "not for the socket" }, } }); if (deploymentMode === "authenticated") activity("hidden"); @@ -255,7 +301,7 @@ describe("authenticated activity notifications", () => { activity("visible"); await first; expect(messages).toHaveLength(1); - expect(messages[0].payload).toMatchObject({ action: "issue.created", entityType: "issue", entityId: "visible", issueIdentifier: "PAP-1234", actorType: "user", actorId: "viewer", actorName: "Alex Example", actorImage: "/alex.png" }); + expect(messages[0].payload).toMatchObject({ action: "issue.created", entityType: "issue", entityId: "visible", issueIdentifier: "PAP-1234", issueTitle: "Fix task notifications", notificationDetails: {}, actorType: "user", actorId: "viewer", actorName: "Alex Example", actorImage: "/alex.png" }); if (deploymentMode === "authenticated") expect(messages[0].payload).not.toHaveProperty("details"); const second = once(socket, "message"); activity("visible", "agent"); @@ -269,8 +315,8 @@ describe("authenticated activity notifications", () => { details: { title: "Secret new title", hiddenAt: null }, } }); await third; - // A rename or hide is flagged with a closed boolean; its content stays off the socket. expect(messages[2].payload.taskIdentityChanged).toBe(true); + expect(messages[2].payload.notificationDetails).toEqual({ titleChanged: true }); if (deploymentMode === "authenticated") expect(JSON.stringify(messages[2].payload)).not.toContain("Secret new title"); } finally { socket.terminate(); @@ -290,9 +336,11 @@ describe("activity profile query boundaries", () => { expect(await activityToastIdentity(db as never, "company-A", { action: "issue.updated", entityType: "issue", entityId: "task-A", actorType: "system", })).toMatchObject({ issueIdentifier: "PAP-1234" }); - expect(predicates).toEqual([ - { sql: '("issues"."company_id" = $1 and "issues"."id" = $2)', params: ["company-A", "task-A"] }, - ]); + expect(predicates[0]).toEqual({ sql: '("issues"."company_id" = $1 and "issues"."id" = $2)', params: ["company-A", "task-A"] }); + expect(predicates).toHaveLength(4); + expect(predicates[1].params).toEqual(["company-A", "task-A"]); + expect(predicates[2].params).toEqual(["company-A", "task-A"]); + expect(predicates[3]).toEqual({ sql: '"instance_settings"."singleton_key" = $1', params: ["default"] }); }); it("requires the exact company, human actor, and active membership before reading a person profile", async () => { diff --git a/server/src/__tests__/run-secret-redaction.test.ts b/server/src/__tests__/run-secret-redaction.test.ts index a6f9a093e7e..3d4c002a941 100644 --- a/server/src/__tests__/run-secret-redaction.test.ts +++ b/server/src/__tests__/run-secret-redaction.test.ts @@ -138,3 +138,35 @@ describe("batched run secret redaction", () => { await expect(registry.redactForRuns("company", [{ id: "a", text: secret }])).rejects.toThrow("unavailable"); }); }); + +describe("bounded task notification redaction", () => { + beforeEach(() => { resolveVersion.mockClear(); }); + const entry = (id: number, value = secret) => ({ fingerprintSha256: `fixture-${id}`, material: { value } }); + const run = (id: number, entries = [entry(0)]) => ({ id: `run-${id}`, contextSnapshot: { paperclipSecretRedactions: entries } }); + function fixture(groups: unknown[][]) { + const limit = vi.fn(async () => groups.shift() ?? []); + const db = { select: () => ({ from: () => ({ where: () => ({ orderBy: () => ({ limit }) }) }) }) }; + return { registry: createRunSecretRedactionRegistry(db as unknown as Db), limit }; + } + it.each([ + { name: "too many unique secrets", rows: Array.from({ length: 65 }, (_, id) => run(id, [entry(id)])) }, + { name: "too much encrypted material", rows: Array.from({ length: 8 }, (_, id) => run(id, [entry(id, "x".repeat(9000))])) }, + { name: "an oversized SQL-projected registry", rows: [{ id: "oversized", contextSnapshot: null }] }, + ])("rejects $name before resolving any secret", async ({ rows }) => { + const { registry } = fixture([rows, []]); + await expect(registry.redactForIssueNotification("company", "task", { body: secret })).rejects.toThrow("budget exceeded"); + expect(resolveVersion).not.toHaveBeenCalled(); + }); + it("bounds the union of legacy and current task histories", async () => { + const { registry } = fixture([Array.from({ length: 65 }, (_, id) => run(id)), Array.from({ length: 64 }, (_, id) => run(id + 65))]); + await expect(registry.redactForIssueNotification("company", "task", secret)).rejects.toThrow("budget exceeded"); + expect(resolveVersion).not.toHaveBeenCalled(); + }); + it("deduplicates overlapping histories and resolves repeated secrets once", async () => { + const rows = Array.from({ length: 128 }, (_, id) => run(id)); + const { registry, limit } = fixture([rows, rows]); + expect(await registry.redactForIssueNotification("company", "task", { body: secret })).toEqual({ body: REDACTED_EVENT_VALUE }); + expect(limit).toHaveBeenCalledTimes(2); + expect(resolveVersion).toHaveBeenCalledTimes(1); + }); +}); diff --git a/server/src/realtime/activity-toast-details.test.ts b/server/src/realtime/activity-toast-details.test.ts new file mode 100644 index 00000000000..9444ad60ad8 --- /dev/null +++ b/server/src/realtime/activity-toast-details.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from "vitest"; +import { activityToastDetails } from "./activity-toast-details.js"; + +describe("task notification details", () => { + it("keeps only bounded notification content from comments", () => { + expect(activityToastDetails("issue.comment_added", { + commentId: "comment-1", bodySnippet: "Ready for review", source: "comment", + reopened: true, reopenedFrom: "done", secret: "private", description: "private text", + })).toEqual({ commentId: "comment-1", bodySnippet: "Ready for review", source: "comment", reopened: true, reopenedFrom: "done" }); + expect(String(activityToastDetails("issue.comment_added", { bodySnippet: "😀".repeat(300) }).bodySnippet)) + .toBe("😀".repeat(240)); + }); + + it("projects actual changes without copying titles, descriptions or assignee IDs", () => { + expect(activityToastDetails("issue.updated", { + status: "done", title: "unchanged title", changes: { + status: { from: "in_progress", to: "in_review" }, + priority: { from: "medium", to: "high" }, + assigneeAgentId: { from: null, to: "agent-private-id" }, + description: { from: "private old text", to: "private new text" }, + }, + })).toEqual({ status: "in_review", statusFrom: "in_progress", priority: "high", assignment: "reassigned", descriptionChanged: true }); + }); + + it("retains update context on a paired comment and suppresses the paired update", () => { + const changes = { status: { from: "in_progress", to: "done" } }; + expect(activityToastDetails("issue.updated", { source: "comment", changes })).toEqual({ source: "comment", statusFrom: "in_progress", status: "done" }); + expect(activityToastDetails("issue.comment_added", { commentId: "c", bodySnippet: "Finished", changes })).toEqual({ commentId: "c", bodySnippet: "Finished", statusFrom: "in_progress", status: "done" }); + }); + + it("supports older activity without change receipts and rejects unknown enum values", () => { + expect(activityToastDetails("issue.updated", { status: "blocked", assigneeAgentId: null, title: "New name" })) + .toEqual({ status: "blocked", assignment: "unassigned", titleChanged: true }); + expect(activityToastDetails("issue.updated", { status: "private text", priority: "private text", executionRunId: "run-private-id" })).toEqual({}); + expect(activityToastDetails("issue.updated", { status: "done", changes: {} })).toEqual({}); + expect(activityToastDetails("issue.updated", null)).toEqual({}); + }); +}); diff --git a/server/src/realtime/activity-toast-details.ts b/server/src/realtime/activity-toast-details.ts new file mode 100644 index 00000000000..b17912010a0 --- /dev/null +++ b/server/src/realtime/activity-toast-details.ts @@ -0,0 +1,42 @@ +import { ISSUE_PRIORITIES, ISSUE_STATUSES } from "@paperclipai/shared"; + +function record(value: unknown): Record | null { + return value && typeof value === "object" && !Array.isArray(value) + ? value as Record : null; +} + +function includes(values: readonly string[], value: unknown): value is string { + return typeof value === "string" && values.includes(value); +} + +export function activityToastDetails(action: unknown, value: unknown): Record { + const details = record(value) ?? {}; + const result: Record = {}; + if (details.source === "comment") result.source = "comment"; + if (details.reopened === true) { + result.reopened = true; + if (includes(ISSUE_STATUSES, details.reopenedFrom)) result.reopenedFrom = details.reopenedFrom; + } + if (action === "issue.comment_added") { + if (typeof details.commentId === "string") result.commentId = details.commentId.slice(0, 64); + if (typeof details.bodySnippet === "string") result.bodySnippet = Array.from(details.bodySnippet).slice(0, 240).join(""); + } + if (action !== "issue.updated" && action !== "issue.comment_added") return result; + const changes = record(details.changes); + if (action === "issue.comment_added" && !changes) return result; + const changed = (key: string) => changes ? Object.hasOwn(changes, key) : Object.hasOwn(details, key); + const next = (key: string) => changes ? record(changes[key])?.to : details[key]; + if (changed("status") && includes(ISSUE_STATUSES, next("status"))) { + result.status = next("status"); + const from = record(changes?.status)?.from; + if (includes(ISSUE_STATUSES, from)) result.statusFrom = from; + } + if (changed("priority") && includes(ISSUE_PRIORITIES, next("priority"))) result.priority = next("priority"); + if (changed("assigneeAgentId") || changed("assigneeUserId")) { + const assigned = ["assigneeAgentId", "assigneeUserId"].some(key => typeof next(key) === "string"); + result.assignment = assigned ? "reassigned" : "unassigned"; + } + if (changed("title")) result.titleChanged = true; + if (changed("description")) result.descriptionChanged = true; + return result; +} diff --git a/server/src/realtime/activity-toast-identity.ts b/server/src/realtime/activity-toast-identity.ts index b845c0630c5..4c77117829e 100644 --- a/server/src/realtime/activity-toast-identity.ts +++ b/server/src/realtime/activity-toast-identity.ts @@ -1,10 +1,13 @@ -import { and, eq } from "drizzle-orm"; -import { agents, authUsers, companyMemberships, issues, type Db } from "@paperclipai/db"; +import { and, eq, isNull } from "drizzle-orm"; +import { agents, authUsers, companyMemberships, issueComments, issues, type Db } from "@paperclipai/db"; +import type { LiveEvent } from "@paperclipai/shared"; import { logger } from "../middleware/logger.js"; +import { createRunSecretRedactionRegistry } from "../services/run-secret-redaction.js"; +import { redactActivityDetails } from "../services/activity-log.js"; +import { activityToastDetails } from "./activity-toast-details.js"; const TOAST_ACTIONS = new Set(["issue.created", "issue.updated", "issue.comment_added"]); -/** Called only after the viewer can read the activity's task. Never copy details. */ export async function activityToastIdentity( db: Db, companyId: string, @@ -18,19 +21,46 @@ export async function activityToastIdentity( const issueId = payload.entityType === "issue" && typeof payload.entityId === "string" ? payload.entityId : null; let issueIdentifier: string | null = null; + let issueTitle: string | null = null; if (issueId) { try { const [issue] = await db - .select({ identifier: issues.identifier }) + .select({ identifier: issues.identifier, title: issues.title }) .from(issues) .where(and(eq(issues.companyId, companyId), eq(issues.id, issueId))) .limit(1); issueIdentifier = issue?.identifier ?? null; + issueTitle = issue?.title ?? null; } catch (err) { logger.warn({ err, companyId, issueId }, "task toast identifier lookup failed"); } } - const identity = { ...actorIdentity, ...(issueId ? { issueIdentifier } : {}) }; + const details = payload.details && typeof payload.details === "object" && !Array.isArray(payload.details) + ? payload.details as Record : {}; + let notificationDetails = activityToastDetails(payload.action, { ...details, bodySnippet: undefined }); + if (issueId) { + try { + let bodySnippet: string | undefined; + if (payload.action === "issue.comment_added" && typeof details.commentId === "string") { + const [comment] = await db.select({ body: issueComments.body }).from(issueComments) + .where(and(eq(issueComments.companyId, companyId), eq(issueComments.issueId, issueId), + eq(issueComments.id, details.commentId), isNull(issueComments.deletedAt))).limit(1); + bodySnippet = comment?.body; + } + if (issueTitle || bodySnippet) { + const registeredSafe = await createRunSecretRedactionRegistry(db).redactForIssueNotification(companyId, issueId, { issueTitle, bodySnippet }); + const safe = await redactActivityDetails(db, registeredSafe); + issueTitle = typeof safe?.issueTitle === "string" ? safe.issueTitle : null; + notificationDetails = activityToastDetails(payload.action, { ...details, bodySnippet: safe?.bodySnippet }); + } + } catch (err) { + issueTitle = null; + logger.warn({ err, companyId, issueId }, "task notification content redaction failed"); + } + } + const identity = { ...actorIdentity, ...(issueId ? { + issueIdentifier, issueTitle, notificationDetails, + } : {}) }; if (!actorId) return identity; if (actorType === "agent") { @@ -57,3 +87,15 @@ export async function activityToastIdentity( } return identity; } + +export function createActivityToastIdentity(db: Db) { + const identities = new WeakMap>>>(); + return (event: LiveEvent) => { + let identity = identities.get(event); + if (!identity) { + identity = activityToastIdentity(db, event.companyId, event.payload); + identities.set(event, identity); + } + return identity; + }; +} diff --git a/server/src/realtime/live-events-ws.ts b/server/src/realtime/live-events-ws.ts index 7388f875df0..076985c141d 100644 --- a/server/src/realtime/live-events-ws.ts +++ b/server/src/realtime/live-events-ws.ts @@ -11,7 +11,7 @@ import { agentApiKeys, companyMemberships, instanceUserRoles, heartbeatRuns, iss 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 { createActivityToastIdentity } 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"; @@ -264,6 +264,7 @@ export function setupLiveEventsWebSocketServer( ) { const wss = new WebSocketServer({ noServer: true, maxPayload: 64 * 1024 }); const redactRunEvent = createLiveRunEventRedactor(db); + const readActivityIdentity = createActivityToastIdentity(db); const cleanupByClient = new Map void>(); const aliveByClient = new Map(); @@ -291,9 +292,16 @@ export function setupLiveEventsWebSocketServer( || !(await canActorReadCase(db, context!.actor, { id: event.payload.entityId, companyId: event.companyId })))) return null; if (context!.actor.source === "local_implicit") { if (event.type === "activity.logged" && event.payload.entityType === "issue") { + const identity = await readActivityIdentity(event); + const details = event.payload.details && typeof event.payload.details === "object" && !Array.isArray(event.payload.details) + ? event.payload.details as Record : {}; return { ...event, payload: { ...event.payload, + ...(event.payload.action === "issue.comment_added" ? { details: { ...details, + changes: undefined, + issueTitle: "issueTitle" in identity ? identity.issueTitle : undefined, + bodySnippet: "notificationDetails" in identity ? identity.notificationDetails?.bodySnippet : undefined } } : {}), taskIdentityChanged: issueActivityChangesTaskIdentity(event.payload.action, event.payload.details), - ...await activityToastIdentity(db, event.companyId, event.payload), + ...identity, ...await recentSubtaskParents(db, context!.actor, event.companyId, event.payload, reads) } }; } if (event.type === "heartbeat.run.status" || event.type === "heartbeat.run.queued") { @@ -367,8 +375,6 @@ export function setupLiveEventsWebSocketServer( : 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. if (event.type === "activity.logged") return { ...event, payload: { action: payload.action, entityType: payload.entityType, entityId: payload.entityId, // A handoff can attach the first case to a task. Its already-authorized @@ -379,8 +385,7 @@ export function setupLiveEventsWebSocketServer( ...(payload.entityType === "issue" ? { taskIdentityChanged: issueActivityChangesTaskIdentity(payload.action, payload.details) } : {}), - // The task read check above authorizes attribution, but not arbitrary details. - ...(issueId ? await activityToastIdentity(db, event.companyId, payload) : {}), + ...(issueId ? await readActivityIdentity(event) : {}), ...await recentSubtaskParents(db, context!.actor, event.companyId, payload, reads), } }; if (event.type === "agent.status") return { ...event, payload: { agentId: payload.agentId, status: payload.status } }; diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index a4e55e2d33f..312b58b0d67 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -16497,7 +16497,7 @@ export function issueRoutes( } : {}), ...(interruptedRunId ? { interruptedRunId } : {}), - ...(hasFieldChanges ? { updated: true } : {}), + ...(hasFieldChanges ? { updated: true, changes: issueChanges } : {}), ...summarizeIssueReferenceActivityDetails({ addedReferencedIssues: commentReferenceDiff.addedReferencedIssues.map( diff --git a/server/src/services/run-secret-redaction.ts b/server/src/services/run-secret-redaction.ts index 1cea93cb01c..b0e0398752d 100644 --- a/server/src/services/run-secret-redaction.ts +++ b/server/src/services/run-secret-redaction.ts @@ -1,5 +1,5 @@ import { createHash } from "node:crypto"; -import { and, eq, inArray, or, sql } from "drizzle-orm"; +import { and, desc, eq, inArray, or, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { heartbeatRuns } from "@paperclipai/db"; import { REDACTED_EVENT_VALUE } from "../redaction.js"; @@ -167,6 +167,32 @@ export function createRunSecretRedactionRegistry(db: Db) { return valuesForRuns(rows); } + async function notificationValuesForIssue(companyId: string, issueId: string) { + const maxRuns = 128; + const maxValues = 64; + const maxMaterialBytes = 64 * 1024; + const boundedSnapshot = sql`case when octet_length(coalesce((${heartbeatRuns.contextSnapshot}->'paperclipSecretRedactions')::text, '')) <= 16384 + then ${registrySnapshot} else null end`; + const rowsById = new Map(); + for (const [binding, order] of [ + [sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${issueId}`, desc(heartbeatRuns.createdAt)], + [sql`${heartbeatRuns.contextSnapshot}->'paperclipIssue'->>'id' = ${issueId}`, sql`${heartbeatRuns.createdAt} desc nulls last`], + ]) { + const rows = await db.select({ id: heartbeatRuns.id, contextSnapshot: boundedSnapshot }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.companyId, companyId), binding)) + .orderBy(order).limit(maxRuns + 1); + if (rows.length > maxRuns || rows.some(row => row.contextSnapshot === null)) throw new Error("Task notification redaction budget exceeded"); + for (const row of rows) rowsById.set(row.id, row); + if (rowsById.size > maxRuns) throw new Error("Task notification redaction budget exceeded"); + } + const rows = [...rowsById.values()]; + const entries = new Map(rows.flatMap(row => registryEntries(row.contextSnapshot)).map(entry => [entry.fingerprintSha256, entry])); + if (entries.size > maxValues || [...entries.values()].reduce((bytes, entry) => bytes + Buffer.byteLength(JSON.stringify(entry.material)), 0) > maxMaterialBytes) { + throw new Error("Task notification redaction budget exceeded"); + } + return valuesForRuns(rows); + } + return { redactionValuesForRun: async (companyId: string, runId: string) => valuesForRuns(await db .select({ contextSnapshot: registrySnapshot }).from(heartbeatRuns) @@ -205,6 +231,8 @@ export function createRunSecretRedactionRegistry(db: Db) { const disclosure = await valuesForRun(companyId, runId, viewerUserId); return redactRegisteredSecretValues(withoutSqlRunError(value), disclosure.values, disclosure.credentialConnectionName); }, + redactForIssueNotification: async (companyId: string, issueId: string, value: T): Promise => + redactRegisteredSecretValues(value, await notificationValuesForIssue(companyId, issueId)), redactForIssue: async (companyId: string, issueId: string, value: T): Promise => redactRegisteredSecretValues(value, await valuesForIssue(companyId, issueId)), }; diff --git a/ui/src/context/LiveUpdatesProvider.hook.test.tsx b/ui/src/context/LiveUpdatesProvider.hook.test.tsx index 7a5913fb0ba..4bd0087d041 100644 --- a/ui/src/context/LiveUpdatesProvider.hook.test.tsx +++ b/ui/src/context/LiveUpdatesProvider.hook.test.tsx @@ -204,9 +204,15 @@ describe("LiveUpdatesProvider socket run notification scope", () => { await reactAct(async () => sockets[0]!.onmessage!(new MessageEvent("message", { data: JSON.stringify({ id: 99, companyId: "company-1", type: "activity.logged", createdAt: "2026-09-09T18:00:00.000Z", toastEligible: eligibility, - payload: { entityType: "issue", entityId: "other-task", action: "issue.comment_added", actorType: "user", actorId: "another-user" } }), + payload: { entityType: "issue", entityId: "other-task", action: "issue.comment_added", actorType: "user", actorId: "another-user", + actorName: "Nibbler", issueTitle: "Fix task notifications", issueIdentifier: "PAP-1234", + notificationDetails: { commentId: "comment-1", bodySnippet: "Ready **for review**" } } }), }))); expect(pushToast).toHaveBeenCalledTimes(eligibility === true ? 1 : 0); + if (eligibility === true) expect(pushToast).toHaveBeenCalledWith(expect.objectContaining({ + title: "Fix task notifications", body: "Nibbler: Ready for review", + action: { label: "View task", href: "/issues/PAP-1234" }, + })); }); it("keeps generic agent errors quiet even with eligibility metadata", async () => { diff --git a/ui/src/context/LiveUpdatesProvider.test.ts b/ui/src/context/LiveUpdatesProvider.test.ts index ccf1ebbaaf4..5f522455640 100644 --- a/ui/src/context/LiveUpdatesProvider.test.ts +++ b/ui/src/context/LiveUpdatesProvider.test.ts @@ -2230,30 +2230,74 @@ describe("task subtree notification context", () => { describe("activity toast attribution", () => { const build = __liveUpdatesTestUtils.buildActivityToast; - const payload = { action: "issue.created", entityType: "issue", entityId: "task-1", issueIdentifier: "PAP-1234", actorType: "user", actorId: "user-1", actorName: "Alex Example", actorImage: "/alex.png" }; + const payload = { action: "issue.created", entityType: "issue", entityId: "task-1", issueIdentifier: "PAP-1234", issueTitle: "Fix task notifications", actorType: "user", actorId: "user-1", actorName: "Alex Example", actorImage: "/alex.png" }; + const viewer = { userId: "other-user", agentId: null }; it.each([ - ["issue.created", "Alex Example created PAP-1234"], - ["issue.updated", "Alex Example updated PAP-1234"], - ["issue.comment_added", "Alex Example commented on PAP-1234"], - ])("uses the server task identifier for %s with an empty cache and no activity details", (action, title) => { - const toast = build(new QueryClient(), "company", { ...payload, action }, { userId: "other-user", agentId: null }); - expect(toast?.title).toBe(title); - expect(toast?.action).toEqual({ label: "View PAP-1234", href: "/issues/PAP-1234" }); - if (action === "issue.updated") expect(toast?.body).toBe("PAP-1234"); - expect(JSON.stringify(toast)).not.toContain("Task task-1"); + ["issue.created", {}, "Alex Example created the task"], + ["issue.updated", { status: "in_review", statusFrom: "in_progress" }, "Alex Example changed status from in progress to in review"], + ["issue.comment_added", { commentId: "c", bodySnippet: "## Ready **for review**\nSee [the plan](/plan)." }, "Alex Example: Ready for review See the plan."], + ])("shows the task title and useful content for %s with an empty cache", (action, notificationDetails, body) => { + const toast = build(new QueryClient(), "company", { ...payload, action, notificationDetails }, viewer); + expect(toast?.title).toBe("Fix task notifications"); + expect(toast?.body).toBe(body); + expect(toast?.action).toEqual({ label: "View task", href: "/issues/PAP-1234" }); }); - it("uses a generic task label when the identifier is unavailable", () => { - const toast = build(new QueryClient(), "company", { ...payload, action: "issue.updated", issueIdentifier: undefined }, { userId: "other-user", agentId: null }); - expect(toast?.title).toBe("Alex Example updated Task"); - expect(toast?.body).toBe("Task"); - expect(toast?.action).toEqual({ label: "View Task", href: "/issues/task-1" }); + it("uses a generic task title when the title and identifier are unavailable", () => { + const toast = build(new QueryClient(), "company", { ...payload, issueTitle: undefined, issueIdentifier: undefined }, viewer); + expect(toast?.title).toBe("Task"); + expect(toast?.body).toBe("Alex Example created the task"); + expect(toast?.action).toEqual({ label: "View task", href: "/issues/task-1" }); }); - it("resolves cached task titles by the server identifier", () => { + it("resolves cached task titles for older servers, and prefers a fresh server title", () => { const queryClient = new QueryClient(); - queryClient.setQueryData(queryKeys.issues.detail("PAP-1234"), { id: "task-1", identifier: "PAP-1234", title: "Fix task toasts" }); - const toast = build(queryClient, "company", { ...payload, action: "issue.updated" }, { userId: "other-user", agentId: null }); - expect(toast?.title).toBe("Alex Example updated PAP-1234"); - expect(toast?.body).toBe("Fix task toasts"); + queryClient.setQueryData(queryKeys.issues.detail("PAP-1234"), { id: "task-1", identifier: "PAP-1234", title: "Cached title" }); + expect(build(queryClient, "company", { ...payload, issueTitle: undefined }, viewer)?.title).toBe("Cached title"); + expect(build(queryClient, "company", payload, viewer)?.title).toBe("Fix task notifications"); + }); + it("keeps routine or unspecified updates quiet, even with a cached title", () => { + for (const details of [undefined, {}, { executionRunId: "run" }, { source: "comment", status: "done" }]) { + expect(build(new QueryClient(), "company", { ...payload, action: "issue.updated", notificationDetails: details }, viewer)).toBeNull(); + } + }); + it("does not fall back to raw details when the server projected an empty update", () => { + expect(build(new QueryClient(), "company", { ...payload, action: "issue.updated", notificationDetails: {}, details: { status: "done" } }, viewer)).toBeNull(); + }); + it("keeps actor names, priority and description changes in the body", () => { + const toast = build(new QueryClient(), "company", { ...payload, action: "issue.updated", notificationDetails: { priority: "high", descriptionChanged: true } }, viewer); + expect(toast?.body).toBe("Alex Example set priority to high, changed the description"); + }); + it("combines a comment with its status change without repeating the task title", () => { + const toast = build(new QueryClient(), "company", { ...payload, action: "issue.comment_added", notificationDetails: { commentId: "c", bodySnippet: "Finished the fix", status: "done", statusFrom: "in_progress" } }, viewer); + expect(toast?.title).toBe("Fix task notifications"); + expect(toast?.body).toBe("Alex Example changed status from in progress to done: Finished the fix"); + }); + it("reports a projected reopen once and retains other changes and the comment", () => { + const toast = build(new QueryClient(), "company", { ...payload, action: "issue.comment_added", notificationDetails: { + commentId: "reopen-comment", bodySnippet: "One more fix", reopened: true, reopenedFrom: "done", + status: "todo", statusFrom: "done", priority: "high", descriptionChanged: true, + } }, viewer); + expect(toast?.body).toBe("Alex Example reopened from done to to do, set priority to high, changed the description: One more fix"); + expect(toast?.body).not.toContain("changed status"); + }); + it("includes reopen context and uses a clear fallback when the comment is unavailable", () => { + expect(build(new QueryClient(), "company", { ...payload, action: "issue.comment_added", notificationDetails: { reopened: true, reopenedFrom: "done", bodySnippet: "One more fix" } }, viewer)?.body) + .toBe("Alex Example reopened from done: One more fix"); + expect(build(new QueryClient(), "company", { ...payload, action: "issue.comment_added" }, viewer)?.body).toBe("Alex Example added a comment"); + }); + it("retains legacy comment snippets and change details", () => { + expect(build(new QueryClient(), "company", { ...payload, action: "issue.comment_added", details: { bodySnippet: "Ready" } }, viewer)?.body).toBe("Alex Example: Ready"); + expect(build(new QueryClient(), "company", { ...payload, action: "issue.updated", details: { status: "blocked" } }, viewer)?.body).toBe("Alex Example changed status to blocked"); + }); + it("bounds long titles and comments while retaining the actor", () => { + const toast = build(new QueryClient(), "company", { ...payload, issueTitle: "Title ".repeat(100), action: "issue.comment_added", notificationDetails: { bodySnippet: "Comment ".repeat(100) } }, viewer); + expect(toast?.title.length).toBeLessThanOrEqual(120); + expect(toast?.body?.length).toBeLessThanOrEqual(240); + expect(toast?.body).toMatch(/^Alex Example: Comment/); + expect(toast?.body).toMatch(/…$/); + }); + it("deduplicates by comment ID rather than the task", () => { + const make = (id: string) => build(new QueryClient(), "company", { ...payload, action: "issue.comment_added", notificationDetails: { commentId: id } }, viewer); + expect(make("first")?.dedupeKey).not.toBe(make("second")?.dedupeKey); }); it.each(["issue.created", "issue.updated", "issue.comment_added"])("hides the viewer's own %s", (action) => { expect(build(new QueryClient(), "company", { ...payload, action }, { userId: "user-1", agentId: null })).toBeNull(); @@ -2262,19 +2306,18 @@ describe("activity toast attribution", () => { expect(build(new QueryClient(), "company", { ...payload, actorType: "agent", actorId: "agent-1" }, { userId: null, agentId: "agent-1" })).toBeNull(); }); it("uses the real name and photo with an empty directory cache", () => { - const toast = build(new QueryClient(), "company", payload, { userId: "other-user", agentId: null }); - expect(toast?.title).toBe("Alex Example created PAP-1234"); - expect(toast?.actor).toMatchObject({ type: "user", name: "Alex Example", image: "/alex.png" }); + expect(build(new QueryClient(), "company", payload, viewer)?.actor).toMatchObject({ type: "user", name: "Alex Example", image: "/alex.png" }); }); it("uses the agent's custom avatar with an empty agent cache", () => { const appearance = { schemaVersion: 1, characterVersion: "cap-v1", paletteId: "bubblegum-sky", customAvatarAssetId: "11111111-1111-4111-8111-111111111111" }; - const toast = build(new QueryClient(), "company", { ...payload, actorType: "agent", actorId: "agent-1", actorName: "Coder", actorAppearance: appearance }, { userId: "user-1", agentId: null }); - expect(toast?.title).toBe("Coder created PAP-1234"); + const toast = build(new QueryClient(), "company", { ...payload, actorType: "agent", actorId: "agent-1", actorName: "Coder", actorAppearance: appearance }, viewer); + expect(toast?.body).toBe("Coder created the task"); expect(toast?.actor?.appearance).toEqual(appearance); }); - it("keeps system activity distinct from people", () => { - const toast = build(new QueryClient(), "company", { ...payload, actorType: "system", actorName: undefined }, { userId: "user-1", agentId: null }); - expect(toast?.title).toBe("System created PAP-1234"); + it("keeps system activity distinct from people and explains the change", () => { + const toast = build(new QueryClient(), "company", { ...payload, action: "issue.updated", actorType: "system", actorName: undefined, notificationDetails: { status: "blocked" } }, viewer); + expect(toast?.title).toBe("Fix task notifications"); + expect(toast?.body).toBe("System changed status to blocked"); expect(toast?.actor).toBeUndefined(); }); }); diff --git a/ui/src/context/LiveUpdatesProvider.tsx b/ui/src/context/LiveUpdatesProvider.tsx index ba35d31e285..56465728f32 100644 --- a/ui/src/context/LiveUpdatesProvider.tsx +++ b/ui/src/context/LiveUpdatesProvider.tsx @@ -63,6 +63,7 @@ import { queryKeys } from "../lib/queryKeys"; import { extractCompanyPrefixFromPath, toCompanyRelativePath } from "../lib/company-routes"; import { useLocation } from "../lib/router"; import { agentRouteRef } from "../lib/utils"; +import { markdownToPlainText } from "../lib/markdown-plain-text"; import { buildSameOriginWebSocketUrl } from "../lib/websocket-url"; import { tryCreateWebSocket } from "../lib/websocket"; @@ -1143,32 +1144,25 @@ function describeIssueUpdate( ): string | null { if (!details) return null; const changes: string[] = []; - if (typeof details.status === "string") - changes.push(`status -> ${details.status.replace(/_/g, " ")}`); - if (typeof details.priority === "string") - changes.push(`priority -> ${details.priority}`); - if ( - typeof details.assigneeAgentId === "string" || - typeof details.assigneeUserId === "string" - ) { - changes.push("reassigned"); - } else if ( - details.assigneeAgentId === null || - details.assigneeUserId === null - ) { - changes.push("unassigned"); - } + const statusLabel = (status: string) => status === "todo" ? "to do" : status.replace(/_/g, " "); if (details.reopened === true) { - const from = readString(details.reopenedFrom); - changes.push( - from ? `reopened from ${from.replace(/_/g, " ")}` : "reopened", - ); + const from = readString(details.reopenedFrom) ?? readString(details.statusFrom); + const to = readString(details.status); + changes.push(`reopened${from ? ` from ${statusLabel(from)}` : " the task"}${to ? ` to ${statusLabel(to)}` : ""}`); + } else if (typeof details.status === "string") { + changes.push(typeof details.statusFrom === "string" + ? `changed status from ${statusLabel(details.statusFrom)} to ${statusLabel(details.status)}` + : `changed status to ${statusLabel(details.status)}`); } - if (typeof details.title === "string") changes.push("title changed"); - if (typeof details.description === "string") - changes.push("description changed"); - if (changes.length > 0) return changes.join(", "); - return null; + if (typeof details.priority === "string") changes.push(`set priority to ${details.priority}`); + if (details.assignment === "reassigned" || typeof details.assigneeAgentId === "string" || typeof details.assigneeUserId === "string") { + changes.push("reassigned the task"); + } else if (details.assignment === "unassigned" || details.assigneeAgentId === null || details.assigneeUserId === null) { + changes.push("unassigned the task"); + } + if (details.titleChanged === true || typeof details.title === "string") changes.push("changed the title"); + if (details.descriptionChanged === true || typeof details.description === "string") changes.push("changed the description"); + return changes.length > 0 ? changes.join(", ") : null; } function buildActivityToast( @@ -1180,7 +1174,8 @@ function buildActivityToast( const entityType = readString(payload.entityType); const entityId = readString(payload.entityId); const action = readString(payload.action); - const details = readRecord(payload.details); + const activityDetails = readRecord(payload.details); + const details = readRecord(payload.notificationDetails) ?? activityDetails; const actorId = readString(payload.actorId); const actorType = readString(payload.actorType); @@ -1198,8 +1193,9 @@ function buildActivityToast( companyId, entityId, { - ...details, - identifier: readString(payload.issueIdentifier) ?? readString(details?.identifier), + ...activityDetails, + title: readString(payload.issueTitle) ?? readString(activityDetails?.title), + identifier: readString(payload.issueIdentifier) ?? readString(activityDetails?.identifier), }, ); const actor = readString(readString(payload.actorName)?.trim()) ?? resolveActorLabel(queryClient, companyId, actorType, actorId); @@ -1226,70 +1222,41 @@ function buildActivityToast( actorId === currentActor.agentId); if (isSelfActivity) return null; + const title = truncate((issue.title?.trim() || "Task").replace(/\s+/g, " "), 120); + const actionLink = { label: "View task", href: issue.href }; if (action === "issue.created") { return { actor: toastActor, - title: `${actor} created ${issue.ref}`, - body: issue.title ? truncate(issue.title, 96) : undefined, + title, + body: truncate(`${actor} created the task`, 240), tone: "success", - action: { label: `View ${issue.ref}`, href: issue.href }, + action: actionLink, dedupeKey: `activity:${action}:${entityId}`, }; } + const changeDesc = describeIssueUpdate(details); if (action === "issue.updated") { - if (readString(details?.source) === "comment") { - // Comment-driven updates emit a paired comment event; show one combined toast on the comment event. - return null; - } - const changeDesc = describeIssueUpdate(details); - const body = changeDesc - ? issue.title - ? `${truncate(issue.title, 64)} - ${changeDesc}` - : changeDesc - : issue.title - ? truncate(issue.title, 96) - : issue.label; + if (details?.source === "comment" || !changeDesc) return null; return { actor: toastActor, - title: `${actor} updated ${issue.ref}`, - body: truncate(body, 100), + title, + body: truncate(`${actor} ${changeDesc}`, 240), tone: "info", - action: { label: `View ${issue.ref}`, href: issue.href }, + action: actionLink, dedupeKey: `activity:${action}:${entityId}`, }; } const commentId = readString(details?.commentId); - const bodySnippet = readString(details?.bodySnippet); - const reopened = details?.reopened === true; - const updated = details?.updated === true; - const reopenedFrom = readString(details?.reopenedFrom); - const reopenedLabel = reopened - ? reopenedFrom - ? `reopened from ${reopenedFrom.replace(/_/g, " ")}` - : "reopened" - : null; - const title = reopened - ? `${actor} reopened and commented on ${issue.ref}` - : updated - ? `${actor} commented and updated ${issue.ref}` - : `${actor} commented on ${issue.ref}`; - const body = bodySnippet - ? reopenedLabel - ? `${reopenedLabel} - ${bodySnippet.replace(/^#+\s*/m, "").replace(/\n/g, " ")}` - : bodySnippet.replace(/^#+\s*/m, "").replace(/\n/g, " ") - : reopenedLabel - ? issue.title - ? `${reopenedLabel} - ${issue.title}` - : reopenedLabel - : (issue.title ?? undefined); + const snippet = markdownToPlainText(readString(details?.bodySnippet) ?? ""); + const summary = changeDesc ? `${actor} ${changeDesc}` : actor; return { actor: toastActor, title, - body: body ? truncate(body, 96) : undefined, + body: truncate(snippet ? `${summary}: ${snippet}` : changeDesc ? summary : `${actor} added a comment`, 240), tone: "info", - action: { label: `View ${issue.ref}`, href: issue.href }, + action: actionLink, dedupeKey: `activity:${action}:${entityId}:${commentId ?? "na"}`, }; }