mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
## 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>
353 lines
11 KiB
TypeScript
353 lines
11 KiB
TypeScript
import { and, asc, eq, inArray, sql } from "drizzle-orm";
|
|
import type { Db } from "@paperclipai/db";
|
|
import {
|
|
issueComments,
|
|
issueLabels,
|
|
issues,
|
|
labels,
|
|
primeDatabaseWorkTransactionId,
|
|
} from "@paperclipai/db";
|
|
import type {
|
|
BoardEventView,
|
|
CommentView,
|
|
SchemaBlock,
|
|
} from "@paperclipai/shared";
|
|
import { notFound } from "../errors.js";
|
|
import { logger } from "../middleware/logger.js";
|
|
import {
|
|
createActivityDetailsRedactor,
|
|
logActivitiesBatch,
|
|
publishActivity,
|
|
type ActivityPublication,
|
|
type LogActivityInput,
|
|
} from "./activity-log.js";
|
|
import {
|
|
createAdaptiveCompanyBatcher,
|
|
type PendingEntry,
|
|
} from "./adaptive-company-batcher.js";
|
|
import { forEachPostCommitSafely } from "./headless-board-events-write.js";
|
|
import {
|
|
appendBoardEvents,
|
|
mintTimeOrderedUuid,
|
|
publishCommittedBoardEvent,
|
|
serializeCommentView,
|
|
touchChannelsLastActivity,
|
|
type AppendBoardEventInput,
|
|
type HeadlessActorContext,
|
|
} from "./headless-common.js";
|
|
|
|
export interface CoalescedCommentInput {
|
|
actor: HeadlessActorContext;
|
|
targetIssue: {
|
|
id: string;
|
|
identifier: string | null;
|
|
companyId: string;
|
|
channelId: string | null;
|
|
kvLabels: Record<string, string> | null;
|
|
};
|
|
channelPath: string | null;
|
|
authorUserId: string | null;
|
|
bodyText: string;
|
|
mergedKvLabels: Record<string, string>;
|
|
validatedBlocks: SchemaBlock[];
|
|
internal: boolean;
|
|
}
|
|
|
|
export interface CoalescedCommentResult {
|
|
comment: CommentView;
|
|
created: boolean;
|
|
}
|
|
|
|
async function runCoalescedCommentsBatch(
|
|
db: Db,
|
|
companyId: string,
|
|
entries: Array<PendingEntry<CoalescedCommentInput, CoalescedCommentResult>>,
|
|
allowFallback: boolean,
|
|
): Promise<void> {
|
|
const publications: ActivityPublication[] = [];
|
|
const committedEvents: BoardEventView[] = [];
|
|
const rejectedEntries: Array<{
|
|
entry: PendingEntry<CoalescedCommentInput, CoalescedCommentResult>;
|
|
error: unknown;
|
|
}> = [];
|
|
|
|
let outcomes: Array<{
|
|
entry: PendingEntry<CoalescedCommentInput, CoalescedCommentResult>;
|
|
result: CoalescedCommentResult;
|
|
}>;
|
|
|
|
try {
|
|
const activityRedactor = await createActivityDetailsRedactor(db);
|
|
|
|
outcomes = await db.transaction(async (tx) => {
|
|
const distinctIssueIds = Array.from(
|
|
new Set(entries.map((e) => e.item.targetIssue.id)),
|
|
).sort();
|
|
|
|
const lockedIssues =
|
|
distinctIssueIds.length === 1
|
|
? await tx
|
|
.select({ id: issues.id, kvLabels: issues.kvLabels })
|
|
.from(issues)
|
|
.where(
|
|
and(
|
|
eq(issues.companyId, companyId),
|
|
eq(issues.id, distinctIssueIds[0]!),
|
|
),
|
|
)
|
|
.for("no key update")
|
|
: await tx
|
|
.select({ id: issues.id, kvLabels: issues.kvLabels })
|
|
.from(issues)
|
|
.where(
|
|
and(
|
|
eq(issues.companyId, companyId),
|
|
inArray(issues.id, distinctIssueIds),
|
|
),
|
|
)
|
|
.orderBy(asc(issues.id))
|
|
.for("no key update");
|
|
|
|
const currentKvByIssueId = new Map<string, Record<string, string>>();
|
|
for (const row of lockedIssues) {
|
|
currentKvByIssueId.set(
|
|
row.id,
|
|
(row.kvLabels ?? {}) as Record<string, string>,
|
|
);
|
|
}
|
|
|
|
const activeEntries: Array<
|
|
PendingEntry<CoalescedCommentInput, CoalescedCommentResult>
|
|
> = [];
|
|
for (const entry of entries) {
|
|
if (!currentKvByIssueId.has(entry.item.targetIssue.id)) {
|
|
rejectedEntries.push({ entry, error: notFound("Issue not found") });
|
|
} else {
|
|
activeEntries.push(entry);
|
|
}
|
|
}
|
|
|
|
if (activeEntries.length === 0) {
|
|
return [];
|
|
}
|
|
|
|
const activeIssueIds = Array.from(
|
|
new Set(activeEntries.map((e) => e.item.targetIssue.id)),
|
|
);
|
|
|
|
const tagsByIssueId = new Map<string, string[]>();
|
|
const tagRows = await tx
|
|
.select({ issueId: issueLabels.issueId, name: labels.name })
|
|
.from(issueLabels)
|
|
.innerJoin(labels, eq(issueLabels.labelId, labels.id))
|
|
.where(
|
|
and(
|
|
eq(issueLabels.companyId, companyId),
|
|
inArray(issueLabels.issueId, activeIssueIds),
|
|
),
|
|
)
|
|
.orderBy(asc(labels.name));
|
|
for (const r of tagRows) {
|
|
let arr = tagsByIssueId.get(r.issueId);
|
|
if (!arr) {
|
|
arr = [];
|
|
tagsByIssueId.set(r.issueId, arr);
|
|
}
|
|
arr.push(r.name);
|
|
}
|
|
|
|
const now = new Date();
|
|
const nowMs = now.getTime();
|
|
const plannedComments = activeEntries.map((entry) => ({
|
|
entry,
|
|
commentId: mintTimeOrderedUuid(nowMs),
|
|
createdAt: now,
|
|
}));
|
|
|
|
if (activeIssueIds.length === 1) {
|
|
await tx
|
|
.update(issues)
|
|
.set({ updatedAt: now })
|
|
.where(
|
|
and(
|
|
eq(issues.companyId, companyId),
|
|
eq(issues.id, activeIssueIds[0]!),
|
|
),
|
|
);
|
|
} else {
|
|
await tx
|
|
.update(issues)
|
|
.set({ updatedAt: now })
|
|
.where(
|
|
and(
|
|
eq(issues.companyId, companyId),
|
|
inArray(issues.id, activeIssueIds),
|
|
),
|
|
);
|
|
}
|
|
|
|
const insertedRows = await tx
|
|
.insert(issueComments)
|
|
.values(
|
|
plannedComments.map(({ entry: { item }, commentId, createdAt }) => ({
|
|
id: commentId,
|
|
companyId,
|
|
issueId: item.targetIssue.id,
|
|
authorAgentId: item.actor.agentId,
|
|
authorUserId: item.authorUserId,
|
|
authorType: item.actor.agentId ? ("agent" as const) : ("user" as const),
|
|
actorProfile: item.actor.actorProfile,
|
|
body: item.bodyText,
|
|
kvLabels: item.mergedKvLabels,
|
|
schemaBlocks: item.validatedBlocks,
|
|
noSync: item.internal,
|
|
clientRequestId: null,
|
|
createdAt,
|
|
updatedAt: createdAt,
|
|
})),
|
|
)
|
|
.returning({
|
|
id: issueComments.id,
|
|
issueId: issueComments.issueId,
|
|
body: issueComments.body,
|
|
authorType: issueComments.authorType,
|
|
authorUserId: issueComments.authorUserId,
|
|
authorAgentId: issueComments.authorAgentId,
|
|
actorProfile: issueComments.actorProfile,
|
|
kvLabels: issueComments.kvLabels,
|
|
schemaBlocks: issueComments.schemaBlocks,
|
|
noSync: issueComments.noSync,
|
|
createdAt: issueComments.createdAt,
|
|
xid: sql<string>`pg_current_xact_id()::text`,
|
|
});
|
|
|
|
const insertedById = new Map(insertedRows.map((row) => [row.id, row]));
|
|
const firstXid = insertedRows[0]?.xid;
|
|
if (firstXid) {
|
|
primeDatabaseWorkTransactionId(tx, firstXid);
|
|
}
|
|
|
|
await touchChannelsLastActivity(
|
|
tx,
|
|
plannedComments.map((p) => p.entry.item.targetIssue.channelId),
|
|
now,
|
|
);
|
|
|
|
const activityInputs: LogActivityInput[] = plannedComments.map(
|
|
({ entry: { item }, commentId }) => {
|
|
const identifier = item.targetIssue.identifier ?? item.targetIssue.id;
|
|
return {
|
|
companyId,
|
|
actorType: item.actor.principalType === "agent" ? "agent" : "user",
|
|
actorId:
|
|
item.actor.principalType === "agent"
|
|
? item.actor.agentId!
|
|
: (item.actor.userId ?? "local-board"),
|
|
agentId: item.actor.agentId,
|
|
issueId: item.targetIssue.id,
|
|
responsibleUserIdOverride: item.actor.responsibleUserId,
|
|
action: "issue.comment_added",
|
|
entityType: "issue",
|
|
entityId: item.targetIssue.id,
|
|
details: {
|
|
commentId,
|
|
identifier,
|
|
internal: item.internal,
|
|
source: "headless",
|
|
...(item.actor.actorProfile
|
|
? { actorProfile: item.actor.actorProfile }
|
|
: {}),
|
|
},
|
|
};
|
|
},
|
|
);
|
|
|
|
await logActivitiesBatch(tx as unknown as Db, activityInputs, publications, {
|
|
redactor: activityRedactor,
|
|
});
|
|
|
|
const eventInputs: AppendBoardEventInput[] = plannedComments.map(
|
|
({ entry: { item }, commentId }) => {
|
|
const identifier = item.targetIssue.identifier ?? item.targetIssue.id;
|
|
return {
|
|
companyId,
|
|
type: "comment.posted",
|
|
channelId: item.targetIssue.channelId,
|
|
channelPath: item.channelPath,
|
|
issueId: item.targetIssue.id,
|
|
identifier,
|
|
actor: item.actor,
|
|
payload: {
|
|
commentId,
|
|
body: item.bodyText.slice(0, 4000),
|
|
blocks: item.validatedBlocks,
|
|
labels: item.mergedKvLabels,
|
|
kvLabels:
|
|
currentKvByIssueId.get(item.targetIssue.id) ??
|
|
item.targetIssue.kvLabels ??
|
|
{},
|
|
tagLabels: tagsByIssueId.get(item.targetIssue.id) ?? [],
|
|
internal: item.internal,
|
|
},
|
|
};
|
|
},
|
|
);
|
|
|
|
const appendedEvents = await appendBoardEvents(tx, eventInputs);
|
|
committedEvents.push(...appendedEvents);
|
|
|
|
return plannedComments.map((plan, idx) => {
|
|
const inserted = insertedById.get(plan.commentId)!;
|
|
const evt = appendedEvents[idx]!;
|
|
const identifier =
|
|
plan.entry.item.targetIssue.identifier ?? plan.entry.item.targetIssue.id;
|
|
return {
|
|
entry: plan.entry,
|
|
result: {
|
|
comment: serializeCommentView(inserted, identifier, evt.cursor),
|
|
created: true,
|
|
},
|
|
};
|
|
});
|
|
});
|
|
} catch (err) {
|
|
if (allowFallback && entries.length > 1) {
|
|
for (const single of entries) {
|
|
await runCoalescedCommentsBatch(db, companyId, [single], false);
|
|
}
|
|
return;
|
|
}
|
|
for (const rej of rejectedEntries) {
|
|
rej.entry.reject(rej.error);
|
|
}
|
|
const unsettled = new Set(
|
|
entries.filter((e) => !rejectedEntries.some((r) => r.entry === e)),
|
|
);
|
|
for (const entry of unsettled) {
|
|
entry.reject(err);
|
|
}
|
|
return;
|
|
}
|
|
|
|
for (const rej of rejectedEntries) {
|
|
rej.entry.reject(rej.error);
|
|
}
|
|
forEachPostCommitSafely(publications, publishActivity, (pub, err) => {
|
|
logger.warn({ err, companyId: pub.companyId }, "post-commit activity listener failed");
|
|
});
|
|
forEachPostCommitSafely(committedEvents, publishCommittedBoardEvent, (evt, err) => {
|
|
logger.warn({ err, companyId: evt.companyId, seq: evt.seq }, "post-commit board event listener failed");
|
|
});
|
|
for (const outcome of outcomes) {
|
|
outcome.entry.resolve(outcome.result);
|
|
}
|
|
}
|
|
|
|
export const executeCoalescedHeadlessComment = createAdaptiveCompanyBatcher<
|
|
CoalescedCommentInput,
|
|
CoalescedCommentResult
|
|
>(runCoalescedCommentsBatch, {
|
|
backpressureMessage:
|
|
"Too many concurrent channel replies queued for this company; retry shortly",
|
|
});
|