diff --git a/doc/SPEC-implementation.md b/doc/SPEC-implementation.md index 9d029961800..bd4b0738ec2 100644 --- a/doc/SPEC-implementation.md +++ b/doc/SPEC-implementation.md @@ -1130,6 +1130,10 @@ identity shows no failed runs. All retains company-wide failed-run visibility. Company health alerts do not contribute to the personal inbox badge. Run list responses, including summaries, retain `responsibleUserId`. +Live task and run toasts require personal task participation or an explicit user +mention, independently of read access. Agent ownership and responsible-user +attribution alone do not qualify. See [toast semantics](TOASTS.md). + Ownership split: - **Core / Free:** permission key and scoped-grant enforcement; responsible-user resolution; default-open, disabled, and allowlist policy modes; archive/unarchive APIs; per-user archive persistence; resurfacing behavior; activity audit records; and stable denial codes. diff --git a/doc/TOASTS.md b/doc/TOASTS.md new file mode 100644 index 00000000000..5831cc6cb67 --- /dev/null +++ b/doc/TOASTS.md @@ -0,0 +1,75 @@ +# Toast semantics + +Toasts are transient feedback, not a company activity feed. Live task notifications +are personal to the connected human, including in multiplayer and `local_trusted` +mode (`local-board`). Access to a task does not subscribe someone to notifications. + +## Which tasks qualify + +A task qualifies when the viewer created it, is its current human assignee, +authored a comment, or performed a deliberate action included in the existing +Mine participation allowlist in +[`issue-participation.ts`](../server/src/services/issue-participation.ts). +Read receipts, denied requests, and automatic read-time recovery cleanup do not +count. Comment authorship follows Mine's existing historical participation rule. + +A task also qualifies when its current description or a non-deleted comment +contains an explicit mention of the viewer: `[Name](user://USER_ID)`. The shared +user-mention parser resolves the exact user ID; plain names and bare URLs do not +count. Existing comments are checked, so users need not have opened the task. +The event introducing the first mention can notify immediately. Removing the +only mention removes that qualification unless another participation rule holds. +Historical comment lookup uses an exact viewer-link regex backed by the existing +comment-body trigram index and returns at most one body for the shared parser. + +Agent ownership, primary-agent preference, task/run `responsibleUserId`, company +membership, and involvement in a parent task do not qualify on their own. +Activity by any person or agent can notify a qualifying viewer. These rules do +not change Mine membership, task permissions, assignment, or inbox archive state. + +## Events and suppression + +| Event | Toast behavior | +| --- | --- | +| Task created, updated, or commented on | Requires personal task eligibility. The viewer's own activity stays quiet. | +| Run failed, timed out, or cancelled | Requires eligibility for the persisted run's task. An event's task hint or agent identity is not sufficient. | +| Agent error without a task, or run without a task | No live toast. Status remains available in company views. | +| Run started or succeeded | No live toast. | +| Save, Copy, and other direct action feedback | Existing caller-owned feedback is unchanged. | +| Company join request | Existing join-request notification behavior is unchanged. | + +Eligibility is an additional gate, not a promise that every event produces a +toast. Existing rules still suppress activity for the task in view and run +outcomes already represented by the visible task/run tree. Comment-driven updates +can be combined with their paired comment event when that metadata is available. +Intentional operator interruptions and workspace contention do not announce run +failures. Duplicate terminal outcomes and failures older than five minutes (when +timestamps are available) remain quiet. Reconnect suppression, per-category rate +limits, content deduplication, and toast lifetime limits remain in effect. Hidden +pages reconcile their data on return without replaying a notification backlog. +Archiving a task is not a notification unsubscribe. + +## Delivery contract + +The company WebSocket authorizes each event before evaluating relevance. Its +viewer-specific copy of the shared `LiveEvent` envelope contains `toastEligible`. +Only `true` permits a live task/run toast. Missing/false values, unresolved viewer +identity, and relevance lookup failures stay quiet. Agent-authenticated sockets +do not receive human toast eligibility. This field is computed per connection, +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. +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. +No client-side task-list cache or new database migration is required. During a +mixed-version rollout, a new client receiving events from an older server stays +quiet until the server provides eligibility. + +## Verification + +See [`inbox-search/toasts`](../maps/feature-map/inbox-search.md#toasts) for the +two-user browser recipe and linked regression suites. The map describes coverage; +it is not evidence that a particular deployment passed that journey. diff --git a/maps/agent-access-map/inbox-search.md b/maps/agent-access-map/inbox-search.md index 84ada459d12..60e3265de7a 100644 --- a/maps/agent-access-map/inbox-search.md +++ b/maps/agent-access-map/inbox-search.md @@ -119,3 +119,29 @@ remaining operations before qualifying the whole capability. Gaps: General company search and dedicated task search are different result sets; use the appropriate one. + + +## `toasts` + +Review: `baseline`. + +API: `present` — GET /api/companies/{companyId}/events/ws (WebSocket upgrade); viewer-specific +`toastEligible` metadata on authorized events. No notification mutation endpoint. + +Agent access: `not-applicable` — toast presentation is a human browser concern. +Agent-authenticated event subscriptions retain authorization but do not qualify +for human toasts. Agent task mutations may notify participating humans. + +Policy: Company membership and task/run read checks precede human participation +checks. Creator, current human assignee, commenter, deliberate actor, or explicit +user mention qualifies; agent ownership and responsible-user attribution alone do +not. See [toast semantics](../../doc/TOASTS.md). + +Evidence: `source-only` — [socket projection](../../server/src/realtime/live-events-ws.ts) +and [eligibility](../../server/src/realtime/task-toast-eligibility.ts). + +Verification: `not-run` — Connect two users and an agent; assert per-user eligibility without +losing authorized cache updates. Deny revoked membership and private task access. +Confirm relevance lookup failure yields a quiet authorized event. + +Gaps: Browser recipes and regression sources are not deployment acceptance proof. diff --git a/maps/feature-map/README.md b/maps/feature-map/README.md index 0ac2ab9a5b9..94aae4ea71c 100644 --- a/maps/feature-map/README.md +++ b/maps/feature-map/README.md @@ -31,7 +31,7 @@ manual verification steps, and gotchas. | --- | --- | | [Task creation and lifecycle](./tasks.md) | Creation, assignment, lists, properties, comments, and completion. | | [Delegation, dependencies, and signoff](./task-coordination.md) | Child work, prerequisites, reviewers, and task-tree controls. | -| [Inbox, decisions, and search](./inbox-search.md) | Personal triage, decision queues, unread/blocked views, and search. | +| [Inbox, decisions, and search](./inbox-search.md) | Personal triage, decision queues, unread/blocked views, search, and personal task toasts. | | [Agent conversations and project handoff](./agent-chat.md) | Persistent conversations, discovery, handoff, and gated board chat. | | [Questions and approvals](./questions-and-approvals.md) | Question/plan responses, formal approvals, and app-tool review. | | [Steering and queued messages](./steering.md) | Follow-ups, queue edits, interruption, and pause/resume. | diff --git a/maps/feature-map/inbox-search.md b/maps/feature-map/inbox-search.md index 14df9295962..687ec84534b 100644 --- a/maps/feature-map/inbox-search.md +++ b/maps/feature-map/inbox-search.md @@ -12,6 +12,7 @@ Agent access: [companion](../agent-access-map/inbox-search.md). - `triage`: read or archive attention items without pretending the underlying task is complete. - `decisions`: open the source of a decision and act in the right context. - `search`: query company work and follow a result to its original record. +- `toasts`: receive live task notifications only for personal participation or explicit mentions. ## How to get to it (user POV) @@ -27,6 +28,11 @@ Open `/decisions`, then a queue at `/decisions/queues/:key` and its source item. Open `/search` or the navigation search entry. +### `toasts` + +Keep a company page open while another person or agent updates a task. +See [toast semantics](../../doc/TOASTS.md) for eligibility and suppression rules. + ## Driving it with Playwright and the Paperclip CLI Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Seed assigned, unread, blocked, and resolved tasks plus a pending decision. Record the combined Inbox/Tasks experimental setting. @@ -60,8 +66,38 @@ Automated: [search page](../../ui/src/pages/Search.test.tsx) and [company search Manual: Search a unique task title and content phrase, open the result, and compare the actual record. Test filters, no results, and a second company. Verify stale results do not expose inaccessible data. +### `toasts` + +Automated: [persisted eligibility](../../server/src/__tests__/task-toast-eligibility.test.ts) +checks creation, assignment, comments, mentions, deliberate edits, excluded read +activity, company isolation, local-board, and persisted run-task attribution. +[Socket delivery](../../server/src/__tests__/live-events-toast.test.ts) checks +viewer-specific projection; [UI delivery](../../ui/src/context/LiveUpdatesProvider.hook.test.tsx) +checks eligibility gating, cache updates, stale callbacks, and existing suppression. +[UI cache handling](../../ui/src/context/LiveUpdatesProvider.test.ts) checks visible +comment refresh when authenticated events omit hydration metadata. +The `task toasts follow personal involvement in multiplayer` case in the +[authenticated browser suite](../../tests/e2e/multi-user-authenticated.spec.ts) +exercises quiet unrelated updates, read-only visits, first/historical mentions, +self-activity, and visible-task suppression against persisted data. + +Manual: Use two authenticated browser sessions in the same isolated company. +Create separate tasks for each person and use one shared agent. From a company +task list, verify that the other person's unrelated task updates produce no +toast but still refresh the list. Comment on one of their tasks, then have them +update it: a toast should appear. Repeat using assignment, a deliberate edit, +and a first explicit user mention in a comment or description. Reload before a +later update to prove eligibility does not depend on browser history. Mere +viewing, agent ownership, responsible-user attribution, and parent participation +must remain quiet. Task-linked failures follow the same participation rule; +generic agent errors remain quiet. Repeat while viewing the relevant task and +after switching company/account to verify suppression and isolation. + ## Gotchas +- Notifications do not grant task access or change Mine membership. +- A feature-map recipe and mocked UI tests do not prove live multiplayer behavior. + - Combined Inbox/Tasks requires both `enableCombinedInboxTasks` and `enableStreamlinedUi`. [Standalone Inbox tests](../../ui/src/pages/Inbox.test.tsx) render archive/read controls and toolbars; this is not live multi-user evidence. diff --git a/packages/shared/src/types/live.ts b/packages/shared/src/types/live.ts index 805db173bb8..b4da9a874b9 100644 --- a/packages/shared/src/types/live.ts +++ b/packages/shared/src/types/live.ts @@ -5,5 +5,7 @@ export interface LiveEvent { companyId: string; type: LiveEventType; createdAt: string; + /** Viewer-specific WebSocket projection; absent/false means no task toast. */ + toastEligible?: boolean; payload: Record; } diff --git a/server/src/__tests__/live-events-toast.test.ts b/server/src/__tests__/live-events-toast.test.ts index 5cddd929a9a..68c00feaca0 100644 --- a/server/src/__tests__/live-events-toast.test.ts +++ b/server/src/__tests__/live-events-toast.test.ts @@ -7,6 +7,9 @@ import { WebSocket } from "ws"; import { describe, expect, it, vi } from "vitest"; import { setupLiveEventsWebSocketServer } from "../realtime/live-events-ws.js"; import { publishLiveEvent } from "../services/live-events.js"; +import { taskToastEligible } from "../realtime/task-toast-eligibility.js"; + +vi.mock("../realtime/task-toast-eligibility.js", () => ({ taskToastEligible: vi.fn(async () => false) })); vi.mock("../services/authorization.js", () => ({ authorizationService: () => ({ decide: async ({ resource }: { resource: { issueId: string } }) => ({ allowed: resource.issueId !== "hidden" }) }), @@ -30,6 +33,65 @@ function database(onPredicate: (kind: "where" | "join", condition: SQL) => void } }; } describe("authenticated activity notifications", () => { + it("uses the persisted local-board user identity for local task eligibility", async () => { + vi.mocked(taskToastEligible).mockImplementation(async (_db, _event, userId) => userId === "local-board"); + const server = createServer(); + setupLiveEventsWebSocketServer(server, database() as never, { deploymentMode: "local_trusted" }); + 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 delivery = once(socket, "message"); + publishLiveEvent({ companyId: "company", type: "activity.logged", payload: { + action: "issue.updated", entityType: "issue", entityId: "visible", actorType: "agent", actorId: "agent", + } }); + const [data] = await delivery; + expect(JSON.parse(data.toString()).toastEligible).toBe(true); + expect(taskToastEligible).toHaveBeenLastCalledWith(expect.anything(), expect.anything(), "local-board"); + } finally { + socket.terminate(); + await new Promise((resolve) => server.close(() => resolve())); + vi.mocked(taskToastEligible).mockReset().mockResolvedValue(false); + } + }); + + it("projects eligibility per viewer and keeps authorized updates on lookup failure", async () => { + vi.mocked(taskToastEligible).mockImplementation(async (_db, event, userId) => { + if (event.payload.entityId === "lookup-failure") throw new Error("Relevance unavailable"); + return userId === "alice"; + }); + const server = createServer(); + setupLiveEventsWebSocketServer(server, database() as never, { + deploymentMode: "authenticated", + resolveCloudActor: async (req) => ({ userId: String(req.headers["x-test-viewer"]), companyIds: ["company"] }), + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const url = `ws://127.0.0.1:${(server.address() as { port: number }).port}/api/companies/company/events/ws`; + const alice = new WebSocket(url, { headers: { "x-test-viewer": "alice" } }); + const bob = new WebSocket(url, { headers: { "x-test-viewer": "bob" } }); + try { + await Promise.all([once(alice, "open"), once(bob, "open")]); + for (const entityId of ["visible", "lookup-failure"]) { + const deliveries = Promise.all([once(alice, "message"), once(bob, "message")]); + const original = publishLiveEvent({ companyId: "company", type: "activity.logged", payload: { + action: "issue.comment_added", entityType: "issue", entityId, actorType: "agent", actorId: "agent", + } }); + const [a, b] = (await deliveries).map(([data]) => JSON.parse(data.toString())); + expect(a.toastEligible).toBe(entityId === "visible"); + expect(b.toastEligible).toBe(false); + expect(a.payload.entityId).toBe(entityId); + expect(b.payload.entityId).toBe(entityId); + expect(original).not.toHaveProperty("toastEligible"); + } + } finally { + alice.terminate(); bob.terminate(); + await new Promise((resolve) => server.close(() => resolve())); + vi.mocked(taskToastEligible).mockReset().mockResolvedValue(false); + } + }); + it("keeps actor identity after authorization and excludes hidden tasks and private details", async () => { const server = createServer(); setupLiveEventsWebSocketServer(server, database() as never, { deploymentMode: "authenticated", diff --git a/server/src/__tests__/task-toast-eligibility.test.ts b/server/src/__tests__/task-toast-eligibility.test.ts new file mode 100644 index 00000000000..41540873ddf --- /dev/null +++ b/server/src/__tests__/task-toast-eligibility.test.ts @@ -0,0 +1,112 @@ +import { randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { activityLog, agents, companies, createDb, heartbeatRuns, issueComments, issues } from "@paperclipai/db"; +import type { LiveEvent } from "@paperclipai/shared"; +import { taskToastEligible } from "../realtime/task-toast-eligibility.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; + +const support = await getEmbeddedPostgresTestSupport(); +describe.skipIf(!support.supported)("personal task toast eligibility (persisted data)", () => { + let temp: Awaited>; + let db: ReturnType; + const companyId = randomUUID(); + const agentId = randomUUID(); + beforeAll(async () => { + temp = await startEmbeddedPostgresTestDatabase("paperclip-task-toasts-"); + db = createDb(temp.connectionString); + await db.insert(companies).values({ id: companyId, name: "Toast test", issuePrefix: "TST" }); + await db.insert(agents).values({ id: agentId, companyId, name: "Shared agent", role: "engineer", adapterType: "process" }); + }, 120_000); + afterAll(async () => { await temp?.cleanup(); }); + + async function task(overrides: Partial = {}) { + const id = randomUUID(); + await db.insert(issues).values({ id, companyId, title: "Task", ...overrides }); + return id; + } + function event(issueId: string): LiveEvent { + return { id: 1, companyId, type: "activity.logged", createdAt: new Date().toISOString(), + payload: { entityType: "issue", entityId: issueId, action: "issue.comment_added", actorType: "agent", actorId: agentId } }; + } + async function onlyAlice(id: string) { + expect(await taskToastEligible(db, event(id), "alice")).toBe(true); + expect(await taskToastEligible(db, event(id), "bob")).toBe(false); + } + + it("qualifies creators and current human assignees independently", async () => { + await onlyAlice(await task({ createdByUserId: "alice" })); + await onlyAlice(await task({ assigneeUserId: "alice" })); + await onlyAlice(await task({ description: "Please ask [Alice](user://alice)." })); + }); + it("qualifies a commenter without relying on browser caches", async () => { + const id = await task(); + await db.insert(issueComments).values({ companyId, issueId: id, authorUserId: "alice", body: "Following this." }); + await onlyAlice(id); + }); + it("qualifies the first mention and subsequent events, excluding deleted mentions and plain names", async () => { + const id = await task({ description: "alice user://alice" }); + expect(await taskToastEligible(db, event(id), "alice")).toBe(false); + const [comment] = await db.insert(issueComments).values({ companyId, issueId: id, authorAgentId: agentId, + body: "[Alice](user://alice) please review" }).returning(); + await onlyAlice(id); + await db.insert(issueComments).values({ companyId, issueId: id, authorAgentId: agentId, body: "A later update" }); + await onlyAlice(id); + await db.update(issueComments).set({ deletedAt: new Date() }).where(eq(issueComments.id, comment.id)); + expect(await taskToastEligible(db, event(id), "alice")).toBe(false); + }); + it("counts deliberate edits but not reads, rejected requests, or automatic cleanup", async () => { + const id = await task(); + for (const action of ["issue.read_marked", "issue.resource_access_denied", "issue.recovery_action_resolved"]) { + await db.insert(activityLog).values({ companyId, entityType: "issue", entityId: id, actorType: "user", actorId: "alice", + action, details: { source: "source_revalidation", trigger: "read_projection" } }); + } + expect(await taskToastEligible(db, event(id), "alice")).toBe(false); + await db.insert(activityLog).values({ companyId, entityType: "issue", entityId: id, actorType: "user", actorId: "alice", action: "issue.updated" }); + await onlyAlice(id); + }); + it("finds an exact historical mention without loading unrelated mention history", async () => { + const id = await task(); + await db.insert(issueComments).values(Array.from({ length: 500 }, (_, index) => ({ + companyId, issueId: id, authorAgentId: agentId, + body: `[Another viewer](user://someone-${index}) alice user://alice [Similar](user://alice-extra)`, + }))); + expect(await taskToastEligible(db, event(id), "alice")).toBe(false); + await db.insert(issueComments).values({ companyId, issueId: id, authorAgentId: agentId, + body: "[Alice](user://alice?source=review#note)" }); + await onlyAlice(id); + }); + it("escapes regex syntax in viewer IDs and preserves parsed href forms", async () => { + const id = await task(); + await db.insert(issueComments).values({ companyId, issueId: id, authorAgentId: agentId, + body: "[Different user](user://aliceXX)" }); + expect(await taskToastEligible(db, event(id), "alice.+")).toBe(false); + await db.insert(issueComments).values({ companyId, issueId: id, authorAgentId: agentId, + body: "[Alice](user:///alice.+) [Bob](user://name@bob)" }); + expect(await taskToastEligible(db, event(id), "alice.+")).toBe(true); + expect(await taskToastEligible(db, event(id), "bob")).toBe(true); + }); + it("does not inherit involvement from responsibility, a shared agent, or a parent", async () => { + const parentId = await task({ createdByUserId: "alice" }); + const id = await task({ parentId, createdByAgentId: agentId, assigneeAgentId: agentId, responsibleUserId: "alice" }); + await db.insert(issueComments).values({ companyId, issueId: id, authorAgentId: agentId, body: "Agent update" }); + expect(await taskToastEligible(db, event(id), "alice")).toBe(false); + }); + it("uses the persisted run task, never an event task hint or responsible user", async () => { + const mine = await task({ createdByUserId: "alice" }); + const other = await task({ createdByUserId: "bob" }); + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, issueId: other, scopeKind: "issue", responsibleUserId: "alice", status: "failed" }).returning(); + const e: LiveEvent = { ...event(mine), type: "heartbeat.run.status", payload: { runId: run.id, issueId: mine, status: "failed" } }; + expect(await taskToastEligible(db, e, "alice")).toBe(false); + expect(await taskToastEligible(db, e, "bob")).toBe(true); + await db.update(heartbeatRuns).set({ issueId: null, scopeKind: "company" }).where(eq(heartbeatRuns.id, run.id)); + expect(await taskToastEligible(db, e, "bob")).toBe(false); + }); + it("fails closed for missing identity, company mismatch, and generic agent errors; supports local-board", async () => { + const id = await task({ createdByUserId: "local-board" }); + expect(await taskToastEligible(db, event(id), "local-board")).toBe(true); + expect(await taskToastEligible(db, event(id), null)).toBe(false); + expect(await taskToastEligible(db, { ...event(id), companyId: randomUUID() }, "local-board")).toBe(false); + expect(await taskToastEligible(db, { ...event(id), type: "agent.status" }, "local-board")).toBe(false); + }); +}); diff --git a/server/src/realtime/live-events-ws.ts b/server/src/realtime/live-events-ws.ts index 9351d54d1e7..7fe53906e35 100644 --- a/server/src/realtime/live-events-ws.ts +++ b/server/src/realtime/live-events-ws.ts @@ -9,6 +9,7 @@ import type { DeploymentMode, 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 { taskToastEligible } from "./task-toast-eligibility.js"; import { subscribeCompanyLiveEvents } from "../services/live-events.js"; import { trackIdleWork } from "../services/task-admission.js"; @@ -338,7 +339,18 @@ export function setupLiveEventsWebSocketServer( // Check at delivery time, including after a grant is revoked while the // subscription remains open. Never cache successful privacy decisions. const visible = await visibleEvent(event); - if (visible && socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify(visible)); + if (visible) { + // Relevance is independent of authorization and cache delivery. A + // failed relevance lookup must keep the authorized update flowing. + let toastEligible = false; + try { + toastEligible = await taskToastEligible(db, visible, + context.actor.type === "board" ? context.actor.userId ?? null : null); + } catch (err) { + logger.warn({ err, companyId: context.companyId }, "task toast eligibility failed"); + } + if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ ...visible, toastEligible })); + } }).catch(err => logger.warn({ err, companyId: context.companyId }, "live event authorization failed")) .finally(() => { pending -= 1; }); }); diff --git a/server/src/realtime/task-toast-eligibility.ts b/server/src/realtime/task-toast-eligibility.ts new file mode 100644 index 00000000000..9aeb45e68c2 --- /dev/null +++ b/server/src/realtime/task-toast-eligibility.ts @@ -0,0 +1,47 @@ +import { and, eq, isNull, sql } from "drizzle-orm"; +import { heartbeatRuns, issueComments, issues, type Db } from "@paperclipai/db"; +import { extractUserMentionIds, type LiveEvent } from "@paperclipai/shared"; +import { touchedByUserCondition } from "../services/issue-participation.js"; + +const TASK_ACTIONS = new Set(["issue.created", "issue.updated", "issue.comment_added"]); +const RUN_STATUSES = new Set(["failed", "timed_out", "cancelled"]); + +/** Relevance only: the caller must authorize the event before invoking this. */ +export async function taskToastEligible(db: Db, event: LiveEvent, userId: string | null): Promise { + if (!userId) return false; + const { payload, companyId } = event; + let issueId: string | null = null; + if (event.type === "activity.logged" && payload.entityType === "issue" && TASK_ACTIONS.has(String(payload.action))) { + issueId = typeof payload.entityId === "string" ? payload.entityId : null; + } else if (event.type === "heartbeat.run.status" && RUN_STATUSES.has(String(payload.status))) { + if (typeof payload.runId !== "string") return false; + const [run] = await db.select({ issueId: heartbeatRuns.issueId }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, payload.runId))).limit(1); + issueId = run?.issueId ?? null; + } + if (!issueId) return false; + + const [issue] = await db.select({ + description: issues.description, + }).from(issues).where(and(eq(issues.companyId, companyId), eq(issues.id, issueId))).limit(1); + if (!issue) return false; + if (extractUserMentionIds(issue.description ?? "").includes(userId)) return true; + // Keep the correlated predicate in WHERE, as in Mine. Drizzle strips table + // qualifiers from SQL selections, which would bind inner IDs incorrectly. + const [participation] = await db.select({ id: issues.id }).from(issues).where(and( + eq(issues.companyId, companyId), eq(issues.id, issueId), touchedByUserCondition(companyId, userId), + )).limit(1); + if (participation) return true; + + // Match a complete link for this exact viewer in PostgreSQL. The existing + // body_search GIN trigram index supports this regex; LIMIT 1 bounds the + // history returned to each connection instead of parsing every comment. + const exactId = userId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const href = `user://(?:[^/\\s?#)]+@)?${exactId}|user:///+${exactId}`; + const mentionLink = `\\[[^\\]]*\\]\\((?:${href})(?:[?#][^\\s)]*)?\\)`; + const [comment] = await db.select({ body: issueComments.body }).from(issueComments).where(and( + eq(issueComments.companyId, companyId), eq(issueComments.issueId, issueId), + isNull(issueComments.deletedAt), sql`${issueComments.body} ~ ${mentionLink}`, + )).limit(1); + return !!comment && extractUserMentionIds(comment.body).includes(userId); +} diff --git a/server/src/services/issue-participation.ts b/server/src/services/issue-participation.ts new file mode 100644 index 00000000000..27b9899041c --- /dev/null +++ b/server/src/services/issue-participation.ts @@ -0,0 +1,103 @@ +import { sql } from "drizzle-orm"; +import { activityLog, issueComments, issues } from "@paperclipai/db"; + +// Mine participation fails closed. Add new user-authored issue mutation actions +// here instead of admitting every issue activity, because reads, previews, and +// denied resource requests are audited too. +const ISSUE_USER_PARTICIPATION_ACTIVITY_ACTIONS = [ + "issue.accepted_plan_decomposition_updated", + "issue.admin_force_release", + "issue.approval_linked", + "issue.approval_unlinked", + "issue.approvers_updated", + "issue.assigned", + "issue.attachment_added", + "issue.attachment_removed", + "issue.blockers.updated", + "issue.blockers_updated", + "issue.checked_out", + "issue.checkout", + "issue.child_created", + "issue.comment_cancelled", + "issue.document_annotation_comment_added", + "issue.document_annotation_remapped", + "issue.document_annotation_thread_created", + "issue.document_annotation_thread_resolved", + "issue.document_deleted", + "issue.document_locked", + "issue.document_restored", + "issue.document_unlocked", + "issue.document_updated", + "issue.document_upserted", + "issue.feedback_vote_saved", + "issue.inbox_touched", + "issue.low_trust_output_promoted", + "issue.monitor_cleared", + "issue.monitor_scheduled", + "issue.recovery_action_resolved", + "issue.relations.updated", + "issue.released", + "issue.reviewers_updated", + "issue.scheduled_retry_retry_now", + "issue.successful_run_handoff_resolved", + "issue.task_watchdog_fingerprint_reviewed", + "issue.thread_interaction_accepted", + "issue.thread_interaction_answered", + "issue.thread_interaction_cancelled", + "issue.thread_interaction_created", + "issue.thread_interaction_item_verdicts_submitted", + "issue.thread_interaction_withdrawn", + "issue.tree_cancel_status_updated", + "issue.tree_hold_created", + "issue.tree_hold_released", + "issue.tree_restore_status_updated", + "issue.updated", + "issue.watchdog_created", + "issue.watchdog_removed", + "issue.work_product_created", + "issue.work_product_deleted", + "issue.work_product_updated", +] as const; + +// Old read projections attributed this automatic cleanup to the reader. Keep +// the audit rows, but do not count them as participation or issue activity. +export function automaticReadRecoveryCleanupCondition() { + return sql`( + ${activityLog.action} = 'issue.recovery_action_resolved' + AND COALESCE(${activityLog.details}->>'source', '') = 'source_revalidation' + AND COALESCE(${activityLog.details}->>'trigger', '') = 'read_projection' + )`; +} + +export function touchedByUserCondition(companyId: string, userId: string) { + return sql` + ( + ${issues.createdByUserId} = ${userId} + OR ${issues.assigneeUserId} = ${userId} + OR EXISTS ( + SELECT 1 + FROM ${activityLog} + WHERE ${activityLog.entityType} = 'issue' + AND ${activityLog.entityId} = ${issues.id}::text + AND ${activityLog.companyId} = ${companyId} + AND ${activityLog.actorType} = 'user' + AND ${activityLog.actorId} = ${userId} + AND NOT ${automaticReadRecoveryCleanupCondition()} + AND ${activityLog.action} IN (${sql.join( + ISSUE_USER_PARTICIPATION_ACTIVITY_ACTIONS.map( + (action) => sql`${action}`, + ), + sql`, `, + )}) + ) + OR EXISTS ( + SELECT 1 + FROM ${issueComments} + WHERE ${issueComments.issueId} = ${issues.id} + AND ${issueComments.companyId} = ${companyId} + AND ${issueComments.authorUserId} = ${userId} + ) + ) + `; +} + diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index 3149a777035..7c627f7b49f 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -1,3 +1,4 @@ +import { automaticReadRecoveryCleanupCondition, touchedByUserCondition } from "./issue-participation.js"; import { resolveProjectDefaultWorkspaceId } from "./project-default-workspace.js"; import { type AuthorizationActor, executionWorkspaceReadSqlCondition, projectReadSqlCondition } from "./authorization.js"; import { assertTaskWorkspaceAccess, assertTaskWorkspaceSourceProjectAccess } from "./task-workspace-source-access.js"; @@ -2785,106 +2786,6 @@ async function getWorkspaceInheritanceIssue( return issue; } -// Mine participation fails closed. Add new user-authored issue mutation actions -// here instead of admitting every issue activity, because reads, previews, and -// denied resource requests are audited too. -const ISSUE_USER_PARTICIPATION_ACTIVITY_ACTIONS = [ - "issue.accepted_plan_decomposition_updated", - "issue.admin_force_release", - "issue.approval_linked", - "issue.approval_unlinked", - "issue.approvers_updated", - "issue.assigned", - "issue.attachment_added", - "issue.attachment_removed", - "issue.blockers.updated", - "issue.blockers_updated", - "issue.checked_out", - "issue.checkout", - "issue.child_created", - "issue.comment_cancelled", - "issue.document_annotation_comment_added", - "issue.document_annotation_remapped", - "issue.document_annotation_thread_created", - "issue.document_annotation_thread_resolved", - "issue.document_deleted", - "issue.document_locked", - "issue.document_restored", - "issue.document_unlocked", - "issue.document_updated", - "issue.document_upserted", - "issue.feedback_vote_saved", - "issue.inbox_touched", - "issue.low_trust_output_promoted", - "issue.monitor_cleared", - "issue.monitor_scheduled", - "issue.recovery_action_resolved", - "issue.relations.updated", - "issue.released", - "issue.reviewers_updated", - "issue.scheduled_retry_retry_now", - "issue.successful_run_handoff_resolved", - "issue.task_watchdog_fingerprint_reviewed", - "issue.thread_interaction_accepted", - "issue.thread_interaction_answered", - "issue.thread_interaction_cancelled", - "issue.thread_interaction_created", - "issue.thread_interaction_item_verdicts_submitted", - "issue.thread_interaction_withdrawn", - "issue.tree_cancel_status_updated", - "issue.tree_hold_created", - "issue.tree_hold_released", - "issue.tree_restore_status_updated", - "issue.updated", - "issue.watchdog_created", - "issue.watchdog_removed", - "issue.work_product_created", - "issue.work_product_deleted", - "issue.work_product_updated", -] as const; - -// Old read projections attributed this automatic cleanup to the reader. Keep -// the audit rows, but do not count them as participation or issue activity. -function automaticReadRecoveryCleanupCondition() { - return sql`( - ${activityLog.action} = 'issue.recovery_action_resolved' - AND COALESCE(${activityLog.details}->>'source', '') = 'source_revalidation' - AND COALESCE(${activityLog.details}->>'trigger', '') = 'read_projection' - )`; -} - -function touchedByUserCondition(companyId: string, userId: string) { - return sql` - ( - ${issues.createdByUserId} = ${userId} - OR ${issues.assigneeUserId} = ${userId} - OR EXISTS ( - SELECT 1 - FROM ${activityLog} - WHERE ${activityLog.entityType} = 'issue' - AND ${activityLog.entityId} = ${issues.id}::text - AND ${activityLog.companyId} = ${companyId} - AND ${activityLog.actorType} = 'user' - AND ${activityLog.actorId} = ${userId} - AND NOT ${automaticReadRecoveryCleanupCondition()} - AND ${activityLog.action} IN (${sql.join( - ISSUE_USER_PARTICIPATION_ACTIVITY_ACTIONS.map( - (action) => sql`${action}`, - ), - sql`, `, - )}) - ) - OR EXISTS ( - SELECT 1 - FROM ${issueComments} - WHERE ${issueComments.issueId} = ${issues.id} - AND ${issueComments.companyId} = ${companyId} - AND ${issueComments.authorUserId} = ${userId} - ) - ) - `; -} - function participatedByAgentCondition(companyId: string, agentId: string) { return sql` ( diff --git a/tests/e2e/multi-user-authenticated.spec.ts b/tests/e2e/multi-user-authenticated.spec.ts index 4f291a40209..0a9611e81e3 100644 --- a/tests/e2e/multi-user-authenticated.spec.ts +++ b/tests/e2e/multi-user-authenticated.spec.ts @@ -383,3 +383,112 @@ test("agent chats keep personal identity and ordinary company visibility", async } } finally { await invited.context.close(); } }); + +test("task toasts follow personal involvement in multiplayer", async ({ browser, page }, testInfo) => { + test.setTimeout(180_000); + page.setDefaultTimeout(15_000); + // Observe the real socket handshake so mutations after navigation do not + // race subscription setup. No network responses or event payloads are mocked. + await page.addInitScript(() => { + const NativeWebSocket = window.WebSocket; + const sockets: WebSocket[] = []; + (window as unknown as { toastTestSockets: WebSocket[] }).toastTestSockets = sockets; + window.WebSocket = class extends NativeWebSocket { + constructor(url: string | URL, protocols?: string | string[]) { + super(url, protocols); + sockets.push(this); + } + }; + }); + await signUp(page, { ...ownerUser, email: `toasts-${ownerUser.email}` }); + const bootstrapToken = new URL(createBootstrapInvite()).pathname.split("/").at(-1); + expect((await sessionJsonRequest(page, `${BASE}/api/invites/${bootstrapToken}/accept`, { + method: "POST", data: { requestType: "human" }, + })).ok).toBe(true); + const company = await createCompanyForSession(page, `Personal notifications ${runId}`); + const prefix = company.issuePrefix ?? company.id; + const invite = await sessionJsonRequest<{ inviteUrl: string }>(page, `${BASE}/api/companies/${company.id}/invites`, { + method: "POST", data: { allowedJoinTypes: "human", humanRole: "operator" }, + }); + expect(invite.ok).toBe(true); + const other = await newPage(browser); + try { + await signUp(other.page, { ...invitedUser, email: `toasts-${invitedUser.email}` }); + const token = new URL(invite.json!.inviteUrl, BASE).pathname.split("/").at(-1); + expect((await sessionJsonRequest(other.page, `${BASE}/api/invites/${token}/accept`, { + method: "POST", data: { requestType: "human" }, + })).ok).toBe(true); + const session = await sessionJsonRequest<{ user: { id: string } }>(page, `${BASE}/api/auth/get-session`); + const viewerId = session.json!.user.id; + const task = await sessionJsonRequest<{ id: string; identifier: string }>(other.page, `${BASE}/api/companies/${company.id}/issues`, { + method: "POST", data: { title: "Another person's task", status: "backlog" }, + }); + expect(task.ok).toBe(true); + const id = task.json!.id; + const frames: Array<{ toastEligible?: boolean; payload: { entityId?: string; action?: string } }> = []; + page.on("websocket", socket => socket.on("framereceived", frame => { + try { frames.push(JSON.parse(String(frame.payload))); } catch { /* ignore control frames */ } + })); + await page.goto(`${BASE}/${prefix}/issues?view=all`); + await expect(page.getByText("Another person's task", { exact: true }).first()).toBeVisible(); + await other.page.goto(`${BASE}/${prefix}/issues?view=all`); + const toasts = page.locator('aside[aria-live="polite"]'); + async function waitForSocket() { + await page.waitForFunction((companyId) => + (window as unknown as { toastTestSockets: WebSocket[] }).toastTestSockets.some(socket => + socket.url.includes(`/companies/${companyId}/events/ws`) && socket.readyState === WebSocket.OPEN), company.id); + } + async function update(title: string, eligible: boolean) { + await waitForSocket(); + // Let the existing two-second server list cache expire after navigation. + // This case tests steady-state notification scoping, not cache TTL policy. + await page.waitForTimeout(2200); + const before = frames.length; + expect((await sessionJsonRequest(other.page, `${BASE}/api/issues/${id}`, { + method: "PATCH", data: { title }, + })).ok).toBe(true); + await expect.poll(() => frames.slice(before).find(e => e.payload.entityId === id && e.payload.action === "issue.updated")?.toastEligible) + .toBe(eligible); + await expect(page.getByText(title, { exact: true }).first()).toBeVisible(); + if (eligible) { + await expect(toasts).toContainText("Invited User updated"); + await testInfo.attach(title, { body: await page.screenshot(), contentType: "image/png" }); + await page.getByRole("button", { name: "Dismiss notification" }).click(); + } else { + await expect(toasts).toHaveCount(0); + } + // Each qualifying update is a distinct observation, outside deduplication. + await page.waitForTimeout(3600); + } + await update("Unrelated update still refreshes the list", false); + // Visiting alone must not subscribe the user. + await page.getByRole("link", { name: `Open ${task.json!.identifier}: Unrelated update still refreshes the list`, exact: true }).click(); + await expect(page).toHaveURL(new RegExp(`/issues/(${id}|${task.json!.identifier})`)); + await page.goto(`${BASE}/${prefix}/issues?view=all`); + await update("Viewing is still quiet", false); + // Use persisted API fixtures to vary participation, observing actual live UI. + expect((await sessionJsonRequest(other.page, `${BASE}/api/issues/${id}/comments`, { + method: "POST", data: { body: `Please review [Owner](user://${viewerId}).` }, + })).ok).toBe(true); + await expect(toasts).toContainText("Invited User commented on"); + await testInfo.attach("First mention notifies", { body: await page.screenshot(), contentType: "image/png" }); + await page.getByRole("button", { name: "Dismiss notification" }).click(); + await page.reload(); + await expect(page.getByText("Viewing is still quiet", { exact: true }).first()).toBeVisible(); + await update("Historical mention survives reload", true); + // Same event must not toast to its author in the second authenticated session. + await expect(other.page.locator('aside[aria-live="polite"]')).toHaveCount(0); + // Viewing the qualifying task suppresses redundant notifications. + await page.getByRole("link", { name: `Open ${task.json!.identifier}: Historical mention survives reload`, exact: true }).click(); + await expect(page.getByRole("heading", { name: "Historical mention survives reload", exact: true })).toBeVisible(); + await waitForSocket(); + const beforeComment = frames.length; + expect((await sessionJsonRequest(other.page, `${BASE}/api/issues/${id}/comments`, { + method: "POST", data: { body: "Already visible in the task." }, + })).ok).toBe(true); + await expect.poll(() => frames.slice(beforeComment).find(e => e.payload.entityId === id && e.payload.action === "issue.comment_added")?.toastEligible) + .toBe(true); + await expect(page.getByText("Already visible in the task.", { exact: true }).first()).toBeVisible(); + await expect(toasts).toHaveCount(0); + } finally { await other.context.close(); } +}); diff --git a/ui/src/context/LiveUpdatesProvider.hook.test.tsx b/ui/src/context/LiveUpdatesProvider.hook.test.tsx index 8650bfc355a..7ebe3c6dae5 100644 --- a/ui/src/context/LiveUpdatesProvider.hook.test.tsx +++ b/ui/src/context/LiveUpdatesProvider.hook.test.tsx @@ -8,9 +8,12 @@ import type { LiveEvent } from "@paperclipai/shared"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { queryKeys } from "../lib/queryKeys"; -const { pushToast } = vi.hoisted(() => ({ pushToast: vi.fn(() => "toast-id") })); +const { pushToast, companySelection } = vi.hoisted(() => ({ + pushToast: vi.fn(() => "toast-id"), + companySelection: { id: "company-1" }, +})); vi.mock("./CompanyContext", () => ({ - useCompany: () => ({ selectedCompanyId: "company-1", selectedCompany: { id: "company-1" } }), + useCompany: () => ({ selectedCompanyId: companySelection.id, selectedCompany: { id: companySelection.id } }), })); vi.mock("./ToastContext", () => ({ useToastActions: () => ({ pushToast }) })); vi.mock("../lib/router", () => ({ useLocation: () => ({ pathname: "/PAP/issues/PAP-204" }) })); @@ -133,6 +136,7 @@ describe("LiveUpdatesProvider socket run notification scope", () => { beforeEach(() => { pushToast.mockClear(); + companySelection.id = "company-1"; queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity } } }); queryClient.setQueryData(queryKeys.auth.session, { user: { id: "viewer" }, session: { id: "session", userId: "viewer" } }); queryClient.setQueryData(queryKeys.issues.detail("PAP-204"), { @@ -170,17 +174,87 @@ describe("LiveUpdatesProvider socket run notification scope", () => { vi.unstubAllGlobals(); }); - async function receiveStatus(payload: Record, createdAt = "2026-09-09T18:00:00.000Z") { + async function receiveStatus(payload: Record, createdAt = "2026-09-09T18:00:00.000Z", toastEligible: boolean | undefined = true) { await reactAct(async () => { root!.render(Visible task); }); await vi.waitFor(() => expect(sockets).toHaveLength(1)); expect(sockets[0]?.onmessage).toBeTypeOf("function"); await reactAct(async () => sockets[0]!.onmessage!(new MessageEvent("message", { - data: JSON.stringify({ id: Date.now(), companyId: "company-1", type: "heartbeat.run.status", createdAt, payload }), + data: JSON.stringify({ id: Date.now(), companyId: "company-1", type: "heartbeat.run.status", createdAt, payload, toastEligible }), }))); } + it.each([false, undefined])("keeps ineligible runs quiet (%s) while updating their cache", async (eligibility) => { + queryClient.setQueryData(queryKeys.runDetail("other-run"), { id: "other-run", status: "running" }); + // Pass an event directly to exercise a missing property, not the helper default. + await receiveStatus({ runId: "setup", agentId: "other-agent", status: "running" }); + await reactAct(async () => sockets[0]!.onmessage!(new MessageEvent("message", { + data: JSON.stringify({ id: 99, companyId: "company-1", type: "heartbeat.run.status", + createdAt: "2026-09-09T18:00:00.000Z", toastEligible: eligibility, + payload: { runId: "other-run", agentId: "other-agent", status: "failed" } }), + }))); + expect(pushToast).not.toHaveBeenCalled(); + expect(queryClient.getQueryData(queryKeys.runDetail("other-run"))).toMatchObject({ status: "failed" }); + }); + + it.each([true, false, undefined])("gates task activity (%s)", async (eligibility) => { + await receiveStatus({ runId: "setup", agentId: "other-agent", status: "running" }); + 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" } }), + }))); + expect(pushToast).toHaveBeenCalledTimes(eligibility === true ? 1 : 0); + }); + + it("keeps generic agent errors quiet even with eligibility metadata", async () => { + await receiveStatus({ runId: "setup", agentId: "other-agent", status: "running" }); + const invalidate = vi.spyOn(queryClient, "invalidateQueries"); + await reactAct(async () => sockets[0]!.onmessage!(new MessageEvent("message", { + data: JSON.stringify({ id: 99, companyId: "company-1", type: "agent.status", toastEligible: true, + createdAt: "2026-09-09T18:00:00.000Z", payload: { agentId: "other-agent", status: "error" } }), + }))); + expect(pushToast).not.toHaveBeenCalled(); + await vi.waitFor(() => expect(invalidate).toHaveBeenCalledWith(expect.objectContaining({ + queryKey: queryKeys.agents.detail("other-agent"), + }))); + }); + + it("ignores a callback retained from a closed socket", async () => { + await receiveStatus({ runId: "setup", agentId: "other-agent", status: "running" }); + const staleCallback = sockets[0]!.onmessage!; + await reactAct(async () => root!.unmount()); + root = null; + staleCallback(new MessageEvent("message", { data: JSON.stringify({ + id: 99, companyId: "company-1", type: "heartbeat.run.status", toastEligible: true, + createdAt: "2026-09-09T18:00:00.000Z", payload: { runId: "stale-run", agentId: "other-agent", status: "failed" }, + }) })); + expect(pushToast).not.toHaveBeenCalled(); + }); + + it.each(["account", "company"])("ignores old socket messages after switching %s", async (scope) => { + await receiveStatus({ runId: "setup", agentId: "other-agent", status: "running" }); + const staleCallback = sockets[0]!.onmessage!; + await reactAct(async () => { + if (scope === "account") { + queryClient.setQueryData(queryKeys.auth.session, { + user: { id: "new-viewer" }, session: { id: "new-session", userId: "new-viewer" }, + }); + } else { + companySelection.id = "company-2"; + } + root!.render(New scope); + }); + await vi.waitFor(() => expect(sockets).toHaveLength(2)); + await reactAct(async () => staleCallback(new MessageEvent("message", { data: JSON.stringify({ + id: 99, companyId: "company-1", type: "heartbeat.run.status", toastEligible: true, + createdAt: "2026-09-09T18:00:00.000Z", payload: { runId: "stale-run", agentId: "other-agent", status: "failed" }, + }) }))); + expect(pushToast).not.toHaveBeenCalled(); + expect(queryClient.getQueryData(queryKeys.runDetail("stale-run"))).toBeUndefined(); + }); + it("announces a run outcome once across minute-apart redeliveries but still refreshes caches", async () => { const clock = vi.spyOn(Date, "now"); const payload = { runId: "unrelated-run", agentId: "other-agent", status: "failed", finishedAt: "2026-09-09T18:00:00.000Z" }; @@ -223,7 +297,7 @@ describe("LiveUpdatesProvider socket run notification scope", () => { }); await vi.waitFor(() => expect(sockets).toHaveLength(2)); await reactAct(async () => sockets[1]!.onmessage!(new MessageEvent("message", { - data: JSON.stringify({ id: 2, companyId: "company-1", type: "heartbeat.run.status", createdAt: "2026-09-09T18:01:00.000Z", payload }), + data: JSON.stringify({ id: 2, companyId: "company-1", toastEligible: true, type: "heartbeat.run.status", createdAt: "2026-09-09T18:01:00.000Z", payload }), }))); expect(pushToast).toHaveBeenCalledTimes(1); }); diff --git a/ui/src/context/LiveUpdatesProvider.test.ts b/ui/src/context/LiveUpdatesProvider.test.ts index 0e35df6486c..49ef0cf07a6 100644 --- a/ui/src/context/LiveUpdatesProvider.test.ts +++ b/ui/src/context/LiveUpdatesProvider.test.ts @@ -867,6 +867,25 @@ describe("LiveUpdatesProvider issue invalidation", () => { }); }); + it("refetches visible comments when an authenticated event omits hydration details", () => { + const client = new QueryClient(); + client.setQueryData(queryKeys.issues.detail("PAP-759"), { + id: "issue-1", companyId: "company-1", identifier: "PAP-759", + }); + const invalidate = vi.spyOn(client, "invalidateQueries"); + __liveUpdatesTestUtils.invalidateActivityQueries(client, "company-1", { + entityType: "issue", entityId: "issue-1", action: "issue.comment_added", + actorType: "user", actorId: "another-user", + }, { userId: "viewer", agentId: null }, { + pathname: "/PAP/issues/PAP-759", isForegrounded: true, + }); + expect(invalidate).toHaveBeenCalledWith({ queryKey: queryKeys.issues.comments("PAP-759") }); + expect(invalidate).not.toHaveBeenCalledWith({ + queryKey: queryKeys.issues.comments("PAP-759"), refetchType: "inactive", + }); + client.clear(); + }); + it("refreshes visible issue run queries when the displayed run changes status", () => { const invalidations: unknown[] = []; const cache = new Map([ diff --git a/ui/src/context/LiveUpdatesProvider.tsx b/ui/src/context/LiveUpdatesProvider.tsx index 21f4c278b2a..fe26a868fb8 100644 --- a/ui/src/context/LiveUpdatesProvider.tsx +++ b/ui/src/context/LiveUpdatesProvider.tsx @@ -773,6 +773,9 @@ function shouldDeferVisibleIssueCommentActivity( if (entityType !== "issue" || !entityId) return false; if (action !== "issue.comment_added") return false; + // Authenticated events omit comment details. Only defer a refetch when + // the event contains the ID needed to hydrate the new comment separately. + if (!readString(details?.commentId)) return false; const context = resolveVisibleIssueRouteContext( queryClient, @@ -1367,6 +1370,20 @@ function invalidateActivityQueries( entityId, details, ); + const visibleContext = options?.pathname + ? resolveVisibleIssueRouteContext(queryClient, options.pathname, { + isForegrounded: options.isForegrounded, + }) + : null; + if ( + visibleContext && + overlaps(visibleContext.issueRefs, buildIssueRefsForPayload(entityId, details)) && + !issueRefs.includes(visibleContext.routeIssueRef) + ) { + // Authenticated payloads omit the identifier. Include the visible + // route's cache key when its loaded task matches the event's UUID. + issueRefs.push(visibleContext.routeIssueRef); + } for (const ref of issueRefs) { const invalidationOptions = selfCommentActivity || @@ -1729,7 +1746,7 @@ function handleLiveEvent( invalidateVisibleIssueRunQueries(queryClient, pathname, payload); if (event.type === "heartbeat.run.status") { const toast = buildRunStatusToast(payload, nameOf); - if (toast && !suppressRunToast) { + if (toast && event.toastEligible === true && !suppressRunToast) { gatedPushToast(gate, pushToast, "run-status", toast); } } @@ -1761,22 +1778,8 @@ function handleLiveEvent( queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agentId), }); - const toast = buildAgentStatusToast( - payload, - nameOf, - queryClient, - expectedCompanyId, - ); - if ( - toast && - !shouldSuppressAgentStatusToastForVisibleIssue( - queryClient, - pathname, - payload, - ) - ) { - gatedPushToast(gate, pushToast, "agent-status", toast); - } + // Agent-wide errors have no task participation context. Task-linked + // failures are announced through the personally scoped run-status event. return; } @@ -1795,12 +1798,12 @@ function handleLiveEvent( } const action = readString(payload.action); const toast = - buildActivityToast( + (event.toastEligible === true ? buildActivityToast( queryClient, expectedCompanyId, payload, currentActor, - ) ?? buildJoinRequestToast(payload); + ) : null) ?? buildJoinRequestToast(payload); if ( toast && !shouldSuppressActivityToastForVisibleIssue( @@ -2031,6 +2034,7 @@ export function LiveUpdatesProvider({ children }: { children: ReactNode }) { }; nextSocket.onmessage = (message) => { + if (closed || socket !== nextSocket) return; if (!getPageVisibility().visible) return; const raw = typeof message.data === "string" ? message.data : ""; if (!raw) return;