Files
PaperClipAI/server/src/services/headless-board-events-write.ts
T
DottaandPaperclip a30b1be565 fix(realtime): live-sync open web UI windows on headless pc mutations (#23532)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Headless channel and task commands (`pc post`, `pc reply`, `pc
claim`, `pc complete`, `pc dep`, `pc ask`, etc.) let scripts, operators,
and agents update threads and tasks from the CLI while the Web UI stays
open
> - When an operator kept an issue detail page open and ran `pc reply`
(or other `pc` mutations) from a terminal, the open Web UI page did not
live-update without a manual page refresh
> - Three gaps caused this: `publishCommittedBoardEvent` emitted
`activity.logged` events without `entityType`, `entityId`, or `action`
(so `LiveUpdatesProvider` ignored them and authenticated WebSocket
delivery stripped the custom fields); `pc reply` logged
`issue.comment_added` under the same `userId` (`local-board` in local
mode or the signed-in user in authenticated mode), which
`selfCommentActivity` downgraded to `refetchType: "inactive"` while
`hydrateVisibleIssueComment` skipped unfocused windows; and
`resolveIssueQueryRefs` missed identifier-keyed `issues.detail` cache
entries when `details` was omitted and the window was unfocused
> - This pull request maps committed headless board events onto
structured `activity.logged` payloads, tags headless comment activities
as external (`source: "headless"` / `actorProfile`), and updates
`LiveUpdatesProvider` to resolve cached detail identifiers and actively
refresh issue, comment, interaction, relation, and attention queries for
headless board events
> - The benefit is immediate live updates in open (focused or unfocused)
Web UI windows for all `pc` commands without refreshing the page, in
both local and authenticated deployments

## Linked Issues or Issue Description

**What happened?**

Running `pc reply "<ID>" "unit tests brown" --as ci-bot` or other `pc`
task/workflow/interaction commands while the issue detail page is open
in a browser window does not update the page until the user manually
refreshes.

**Expected behavior**

Commands executed through `pc` (such as `pc reply`, `pc claim`, `pc
release`, `pc complete`, `pc fail`, `pc assign`, `pc handoff`, `pc
cancel`, `pc reopen`, `pc deps`, `pc ask`, `pc approve`, `pc reject`,
`pc label`, `pc post`) should live-update open Web UI windows
automatically without a page refresh, matching the live SSE behavior of
the experimental channels viewer.

**Steps to reproduce**

1. Start a local board with `pc up --local` and open an issue detail
page in the Web UI.
2. Focus a terminal window and run `pc reply "<ID>" "unit tests brown"
--as ci-bot` (or `pc tasks claim` / `pc tasks complete`).
3. Observe that the open issue detail page does not show the new reply
or updated task state until manually refreshed.

**Paperclip version or commit**

`4db307d53c` (`origin/master`)

**Deployment mode**

Local dev (`pc up --local`) and authenticated deployments

## What Changed

- **`server/src/services/headless-board-events-write.ts`**: Added
`buildBoardEventLiveActivityPayload` and updated
`publishCommittedBoardEvent` so every committed headless
`BoardEventView` publishes a structured `activity.logged` live event
with `entityType` (`issue`, `approval`, or `channel`), `entityId`,
`action` (`issue.thread_interaction_created`,
`issue.thread_interaction_resolved`, `approval.decided`, or
`board.<type>`), `actorType`, `actorId`, and `details` (preserving
existing top-level `boardEvent*` fields).
- **`server/src/services/headless-comment-group-commit.ts`** and
**`server/src/routes/headless-channels-schemas.ts`**: Added `source:
"headless"` (and `actorProfile` when present) to `issue.comment_added`
activity details for headless replies.
- **`ui/src/context/LiveUpdatesProvider.tsx`**:
- Extended `resolveIssueQueryRefs` to scan cached `["issues", "detail"]`
queries so identifier-keyed detail routes resolve from UUID-only events
even when unfocused or in authenticated mode.
- Exempted headless comments (`source: "headless"` or `actorProfile`)
from `selfCommentActivity` suppression.
- Actively invalidated `issues.comments(ref)` on `board.comment.posted`
and added `board.task.*` actions to
`ISSUE_RELATION_SUMMARY_ACTIVITY_ACTIONS` and
`BOARD_DECISION_PROJECTION_ACTIONS`.
- **`server/src/__tests__/headless-board-events-live-sync.test.ts`** and
**`ui/src/context/LiveUpdatesProvider.test.ts`**: Added regression tests
covering structured board-event live payloads, unfocused `pc reply --as
ci-bot` as `local-board`, authenticated `board.comment.posted` with
stripped details, and `board.task.completed` relation/attention
invalidation.

## Verification

- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/headless-board-events-live-sync.test.ts
src/__tests__/live-events-ws.test.ts` (2 files, 11/11 passed)
- `pnpm --filter @paperclipai/ui exec vitest run
src/context/LiveUpdatesProvider.test.ts` (1 file, 138/138 passed)
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/headless-channels-schemas-batch.test.ts
src/__tests__/headless-queues-leases-events.test.ts` (2 files, 24/24
passed)
- `cd server && node scripts/typecheck-layers.mjs` (0 errors across all
7 layers)
- `pnpm --filter @paperclipai/ui typecheck` (0 errors)

## Risks

- Low risk. Structured `board.<type>` actions do not overlap with
`ISSUE_TOAST_ACTIONS`, so headless mutations do not emit duplicate
browser toasts when `logActivity` also fires. Authenticated WebSocket
delivery continues to authorize every `entityType: "issue"` event
against `issueId` via `getHeartbeatRunReadDecisions`, failing closed for
private issues. Existing browser-composer `selfCommentActivity`
suppression is unchanged.
- Note on file length: `ui/src/context/LiveUpdatesProvider.tsx` was
already over 1,000 lines; this PR adds a focused 68-line diff directly
inside the existing activity-invalidation and issue-ref resolution
functions rather than introducing an unrelated refactor.

## Model Used

- Google Gemini (Antigravity agentic coding assistant, medium reasoning
mode with shell, file inspection, and test execution tools)

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-02 14:47:56 -06:00

455 lines
14 KiB
TypeScript

import { randomBytes } from "node:crypto";
import { EventEmitter } from "node:events";
import { and, asc, desc, eq, inArray, lt, sql, type SQL } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
boardEvents,
channels,
issueLabels,
issues,
labels,
} from "@paperclipai/db";
import {
formatEventCursor,
type BoardEventType,
type BoardEventView,
} from "@paperclipai/shared";
import { logger } from "../middleware/logger.js";
import { publishLiveEvent } from "./live-events.js";
export type DbOrTx = Db | Parameters<Parameters<Db["transaction"]>[0]>[0];
const MAX_SUB_MS_SEQ = 0x3ffffff;
let lastUuidWallMs = -1;
let subMsSeq = 0;
export function mintTimeOrderedUuid(wallMs = Date.now()): string {
const ms = Math.max(0, Math.floor(wallMs));
const effectiveMs = Math.max(ms, lastUuidWallMs);
if (effectiveMs === lastUuidWallMs && subMsSeq < MAX_SUB_MS_SEQ) {
subMsSeq += 1;
} else {
lastUuidWallMs = effectiveMs;
subMsSeq = 0;
}
const timeHighHex = Math.floor(effectiveMs / 0x10000)
.toString(16)
.padStart(8, "0");
const timeLowHex = (effectiveMs & 0xffff).toString(16).padStart(4, "0");
const versionAndSeqHighHex = (0x4000 | ((subMsSeq >>> 14) & 0x0fff))
.toString(16)
.padStart(4, "0");
const variantAndSeqLowHex = (0x8000 | (subMsSeq & 0x3fff))
.toString(16)
.padStart(4, "0");
const randomTailHex = randomBytes(6).toString("hex");
return `${timeHighHex}-${timeLowHex}-${versionAndSeqHighHex}-${variantAndSeqLowHex}-${randomTailHex}`;
}
export function forEachPostCommitSafely<T>(
items: readonly T[],
publish: (item: T) => void,
onError: (item: T, err: unknown) => void,
): void {
for (const item of items) {
try {
publish(item);
} catch (err) {
onError(item, err);
}
}
}
const boardEventEmitter = new EventEmitter();
boardEventEmitter.setMaxListeners(0);
export function subscribeCompanyBoardEvents(
companyId: string,
listener: (event: BoardEventView) => void,
): () => void {
const safeListener = (event: BoardEventView) => {
try {
listener(event);
} catch (err) {
logger.warn({ err, companyId, seq: event.seq }, "board event listener failed");
}
};
boardEventEmitter.on(companyId, safeListener);
return () => boardEventEmitter.off(companyId, safeListener);
}
function mapBoardEventTypeToActivityAction(type: BoardEventType): string {
switch (type) {
case "interaction.created":
return "issue.thread_interaction_created";
case "interaction.resolved":
return "issue.thread_interaction_resolved";
case "approval.resolved":
return "approval.decided";
default:
return `board.${type}`;
}
}
export function buildBoardEventLiveActivityPayload(
event: BoardEventView,
): Record<string, unknown> {
const approvalId =
event.type === "approval.resolved" &&
typeof event.payload.approvalId === "string"
? event.payload.approvalId
: null;
const entityType = event.issueId
? "issue"
: event.type === "approval.resolved"
? "approval"
: "channel";
const entityId = event.issueId ?? approvalId ?? event.channel ?? null;
const commentId =
typeof event.payload.commentId === "string" ? event.payload.commentId : null;
return {
action: mapBoardEventTypeToActivityAction(event.type),
entityType,
entityId,
actorType: event.actor.type,
actorId: event.actor.id ?? null,
details: {
...(event.identifier ? { identifier: event.identifier } : {}),
...(event.channel ? { channel: event.channel } : {}),
...(event.actor.profile ? { actorProfile: event.actor.profile } : {}),
...(commentId ? { commentId } : {}),
boardEventType: event.type,
boardEventSeq: event.seq,
boardEventCursor: event.cursor,
source: "headless",
},
boardEventSeq: event.seq,
boardEventCursor: event.cursor,
boardEventType: event.type,
channel: event.channel,
issueId: event.issueId,
identifier: event.identifier,
};
}
export function publishCommittedBoardEvent(event: BoardEventView): void {
boardEventEmitter.emit(event.companyId, event);
publishLiveEvent({
companyId: event.companyId,
type: "activity.logged",
payload: buildBoardEventLiveActivityPayload(event),
});
}
const CHANNEL_ACTIVITY_DEBOUNCE_MS = 250;
export async function touchChannelsLastActivity(
dbOrTx: DbOrTx,
channelIds: Array<string | null | undefined>,
now: Date,
): Promise<void> {
const uniqueIds = Array.from(
new Set(channelIds.filter((id): id is string => Boolean(id))),
).sort();
if (uniqueIds.length === 0) return;
const cutoff = new Date(now.getTime() - CHANNEL_ACTIVITY_DEBOUNCE_MS);
if (uniqueIds.length === 1) {
await dbOrTx
.update(channels)
.set({ lastActivityAt: now, updatedAt: now })
.where(and(eq(channels.id, uniqueIds[0]!), lt(channels.lastActivityAt, cutoff)));
return;
}
const staleChannels = await dbOrTx
.select({ id: channels.id })
.from(channels)
.where(and(inArray(channels.id, uniqueIds), lt(channels.lastActivityAt, cutoff)))
.orderBy(asc(channels.id))
.for("no key update");
if (staleChannels.length > 0) {
await dbOrTx
.update(channels)
.set({ lastActivityAt: now, updatedAt: now })
.where(
inArray(
channels.id,
staleChannels.map((ch) => ch.id),
),
);
}
}
function isPlainObjectRecord(val: unknown): val is Record<string, unknown> {
return Boolean(val) && typeof val === "object" && !Array.isArray(val);
}
export interface AppendBoardEventActor {
principalType: "local_trusted" | "user" | "agent" | "system";
userId?: string | null;
agentId?: string | null;
agentName?: string | null;
actorProfile?: string | null;
}
export interface AppendBoardEventInput {
companyId: string;
type: BoardEventType;
channelId?: string | null;
channelPath?: string | null;
issueId?: string | null;
identifier?: string | null;
actor: AppendBoardEventActor;
payload?: Record<string, unknown>;
}
export async function appendBoardEvents(
dbOrTx: DbOrTx,
inputs: AppendBoardEventInput[],
): Promise<BoardEventView[]> {
if (inputs.length === 0) return [];
const companyId = inputs[0]!.companyId;
const prepared = inputs.map((input, idx) => {
if (input.companyId !== companyId) {
throw new Error("appendBoardEvents requires all events to share companyId");
}
const actorType: "user" | "agent" | "system" =
input.actor.principalType === "agent"
? "agent"
: input.actor.principalType === "system"
? "system"
: "user";
const actorId =
input.actor.principalType === "agent"
? input.actor.agentId ?? null
: input.actor.principalType === "system"
? "system"
: input.actor.userId ?? null;
const actorName =
input.actor.principalType === "agent"
? input.actor.agentName ?? null
: null;
const actorProfile = input.actor.actorProfile ?? null;
const payloadObj = input.payload ?? {};
const payloadJson = JSON.stringify(payloadObj);
const issueIdVal = input.issueId ?? null;
const hasExplicitIssueKv =
isPlainObjectRecord(payloadObj.kvLabels) ||
(input.type === "labels.changed" && isPlainObjectRecord(payloadObj.current)) ||
((input.type === "thread.posted" ||
input.type === "task.created" ||
input.type === "task.ready") &&
isPlainObjectRecord(payloadObj.labels));
const hasExplicitTagLabels = Array.isArray(payloadObj.tagLabels);
let payloadExpr: SQL = sql`${payloadJson}::jsonb`;
if (issueIdVal && (!hasExplicitIssueKv || !hasExplicitTagLabels)) {
const kvSelectSql = sql`coalesce((select ${issues.kvLabels} from ${issues} where ${issues.id} = ${issueIdVal}::uuid and ${issues.companyId} = ${input.companyId}::uuid), '{}'::jsonb)`;
const tagSelectSql = sql`coalesce((select jsonb_agg(${labels.name} order by ${labels.name}) from ${issueLabels} inner join ${labels} on ${labels.id} = ${issueLabels.labelId} where ${issueLabels.issueId} = ${issueIdVal}::uuid and ${issueLabels.companyId} = ${input.companyId}::uuid), '[]'::jsonb)`;
if (!hasExplicitIssueKv && !hasExplicitTagLabels) {
payloadExpr = sql`(${payloadJson}::jsonb || jsonb_build_object('kvLabels', ${kvSelectSql}, 'tagLabels', ${tagSelectSql}))`;
} else if (!hasExplicitIssueKv) {
payloadExpr = sql`(${payloadJson}::jsonb || jsonb_build_object('kvLabels', ${kvSelectSql}))`;
} else {
payloadExpr = sql`(${payloadJson}::jsonb || jsonb_build_object('tagLabels', ${tagSelectSql}))`;
}
}
const rowSql = sql`(
${idx}::int,
${input.companyId}::uuid,
${input.type}::text,
${input.channelId ?? null}::uuid,
${input.channelPath ?? null}::text,
${issueIdVal}::uuid,
${input.identifier ?? null}::text,
${actorType}::text,
${actorId}::text,
${actorName}::text,
${actorProfile}::text,
${payloadExpr}::jsonb
)`;
return {
input,
issueIdVal,
actorType,
actorId,
actorName,
actorProfile,
payloadObj,
payloadExpr,
rowSql,
};
});
const insertedRows =
prepared.length === 1
? await dbOrTx.execute<{
seq: string | number;
created_at: Date | string;
payload: Record<string, unknown> | string;
}>(sql`
INSERT INTO ${boardEvents} (
${sql.raw(boardEvents.companyId.name)},
${sql.raw(boardEvents.eventType.name)},
${sql.raw(boardEvents.channelId.name)},
${sql.raw(boardEvents.channelPath.name)},
${sql.raw(boardEvents.issueId.name)},
${sql.raw(boardEvents.identifier.name)},
${sql.raw(boardEvents.actorType.name)},
${sql.raw(boardEvents.actorId.name)},
${sql.raw(boardEvents.actorName.name)},
${sql.raw(boardEvents.actorProfile.name)},
${sql.raw(boardEvents.payload.name)}
)
SELECT
${companyId}::uuid,
${prepared[0]!.input.type},
${prepared[0]!.input.channelId ?? null}::uuid,
${prepared[0]!.input.channelPath ?? null},
${prepared[0]!.issueIdVal}::uuid,
${prepared[0]!.input.identifier ?? null},
${prepared[0]!.actorType},
${prepared[0]!.actorId},
${prepared[0]!.actorName},
${prepared[0]!.actorProfile},
${prepared[0]!.payloadExpr}
FROM (
SELECT pg_advisory_xact_lock(hashtext('board_events'), hashtext(${companyId}))
) AS _lock
RETURNING
${sql.raw(boardEvents.seq.name)},
${sql.raw(boardEvents.createdAt.name)},
${sql.raw(boardEvents.payload.name)}
`)
: await dbOrTx.execute<{
seq: string | number;
created_at: Date | string;
payload: Record<string, unknown> | string;
}>(sql`
INSERT INTO ${boardEvents} (
${sql.raw(boardEvents.companyId.name)},
${sql.raw(boardEvents.eventType.name)},
${sql.raw(boardEvents.channelId.name)},
${sql.raw(boardEvents.channelPath.name)},
${sql.raw(boardEvents.issueId.name)},
${sql.raw(boardEvents.identifier.name)},
${sql.raw(boardEvents.actorType.name)},
${sql.raw(boardEvents.actorId.name)},
${sql.raw(boardEvents.actorName.name)},
${sql.raw(boardEvents.actorProfile.name)},
${sql.raw(boardEvents.payload.name)}
)
SELECT
v.company_id,
v.event_type,
v.channel_id,
v.channel_path,
v.issue_id,
v.identifier,
v.actor_type,
v.actor_id,
v.actor_name,
v.actor_profile,
v.payload
FROM (
SELECT pg_advisory_xact_lock(hashtext('board_events'), hashtext(${companyId}))
) AS _lock
CROSS JOIN (
VALUES ${sql.join(
prepared.map((p) => p.rowSql),
sql`, `,
)}
) AS v(
ord,
company_id,
event_type,
channel_id,
channel_path,
issue_id,
identifier,
actor_type,
actor_id,
actor_name,
actor_profile,
payload
)
ORDER BY v.ord ASC
RETURNING
${sql.raw(boardEvents.seq.name)},
${sql.raw(boardEvents.createdAt.name)},
${sql.raw(boardEvents.payload.name)}
`);
const orderedInserted =
insertedRows.length <= 1
? insertedRows
: [...insertedRows].sort((a, b) => Number(a.seq) - Number(b.seq));
if (orderedInserted.length !== prepared.length) {
throw new Error(
`appendBoardEvents expected ${prepared.length} returned rows, got ${orderedInserted.length}`,
);
}
return prepared.map((meta, idx) => {
const inserted = orderedInserted[idx]!;
const seq = Number(inserted.seq);
const createdAtIso =
inserted.created_at instanceof Date
? inserted.created_at.toISOString()
: new Date(inserted.created_at).toISOString();
const persistedPayload: Record<string, unknown> =
typeof inserted.payload === "string"
? (JSON.parse(inserted.payload) as Record<string, unknown>)
: isPlainObjectRecord(inserted.payload)
? inserted.payload
: meta.payloadObj;
return {
cursor: formatEventCursor(seq),
seq,
type: meta.input.type,
companyId: meta.input.companyId,
channel: meta.input.channelPath ?? null,
issueId: meta.issueIdVal,
identifier: meta.input.identifier ?? null,
actor: {
type: meta.actorType,
id: meta.actorId,
name: meta.actorName,
profile: meta.actorProfile,
},
payload: persistedPayload,
createdAt: createdAtIso,
};
});
}
export async function appendBoardEvent(
dbOrTx: DbOrTx,
input: AppendBoardEventInput,
): Promise<BoardEventView> {
const [single] = await appendBoardEvents(dbOrTx, [input]);
return single!;
}
export async function getLatestCompanyEventCursor(
dbOrTx: DbOrTx,
companyId: string,
): Promise<string> {
const [latest] = await dbOrTx
.select({ seq: boardEvents.seq })
.from(boardEvents)
.where(eq(boardEvents.companyId, companyId))
.orderBy(desc(boardEvents.seq))
.limit(1);
return formatEventCursor(latest ? Number(latest.seq) : 0);
}