feat(annotations): one-tap reactions on artifact comments (#22989)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - People review agent artifacts (plans, documents, routine
descriptions, and case documents) with inline annotation comments
> - Today a person must type a full reply to say "done", "checked",
"looks good", or "I have a question"
> - This slows down quick review feedback, and a question inside a reply
does not automatically bring the assignee back
> - This pull request adds four one-tap reactions to each annotation
comment: Done, Check, Thumbs up, and Question
> - A person's first Question reaction on an open task saves a durable
wake receipt and wakes the task's assignee in a dedicated follow-up run
to reply in that comment's thread (respecting chat ownership and wake
rate limits)
> - The benefit is fast review feedback without extra typing, while
agents can read and set the same reactions through the API

## Linked Issues or Issue Description

Refs #21637 (supersedes on current `master` with renumbered Drizzle
migration, OpenAPI/experimental route contracts, durable wake receipts,
chat ownership and rate-limit hardening, and current UI test suite)
Refs #9336 (agent wake notifications for document annotation threads)
Refs #9674 (agents cannot read inline document review comments)

**What problem does this solve?**
A reviewer cannot quickly acknowledge or question an annotation comment
on an artifact. A short answer requires a typed reply, and nothing tells
the agent that a person has a question about a comment.

**Proposed solution**
Add four fixed reactions per annotation comment: `done`, `check`,
`thumbs_up`, and `question`. One tap adds a reaction and a second tap
removes it. Each person or agent can add each reaction once per comment.
A person's first `question` reaction on an open task commits a durable
wake receipt in the same transaction and wakes the assignee once in a
dedicated follow-up turn, with the comment included in the wake context.

**Alternatives considered**
Free-form emoji reactions. Fixed named reactions keep the API contract
stable for agents and avoid storing arbitrary emoji strings on the
server.

## What Changed

- `packages/db`: Added `document_annotation_comment_reactions` table
(`company_id`, `comment_id`, `reaction`, `actor_type`, `actor_id`,
`created_at`, `removed_at`) with check constraints, cascade delete on
comment deletion, and unique `(comment_id, reaction, actor_type,
actor_id)` index. Generated online-compatible migration
`0510_clear_speedball.sql`, refreshed Drizzle snapshot
`0510_snapshot.json`, and pruned `0505_snapshot.json`.
- `packages/shared`: Added `DOCUMENT_ANNOTATION_COMMENT_REACTIONS`,
`DocumentAnnotationCommentReactionName`,
`DocumentAnnotationCommentReactionActor`,
`DocumentAnnotationCommentReactionSummary`, optional `reactions` on
`DocumentAnnotationComment`, and
`documentAnnotationCommentReactionSchema`.
- `server`: Added `setCommentReaction` in `document-annotations.ts`
using soft-delete (`removed_at`) and upsert revival (`(xmax = 0)` for
`firstAdd`), and attached reaction summaries (`count`, `actors`,
`reactedByMe`) to thread/comment reads.
- `server` routes & contracts: Added `PUT` and `DELETE
.../annotations/:threadId/comments/:commentId/reactions/:reaction` for
issues, routines, and cases, registered them in `openapi.ts`,
`experimental-api-metadata.ts`, and `experimental-api-paths.ts`, and
logged activity (`*.document_annotation_comment_reaction_added` /
`_removed`) only when a row changes.
- `server` durable wake, chat ownership, rate limits &
`packages/adapter-utils`:
- A person's first `question` reaction on an open assigned issue inserts
a recoverable `deferred_issue_execution` receipt in
`agent_wakeup_requests` in the same DB transaction
(`annotation-question-reaction:<id>`), passes `executionWaitRequestId`
to `heartbeat.wakeup` (`reason: "issue_commented"`, `allowRunCoalescing:
false`), resumes via `resumeDeferredExecutionReceipts` if immediate wake
fails, and defers behind busy turns without duplicating receipts.
- Recognized human annotation question reactions
(`isHumanAnnotationQuestionWake`) as an independent wake cause for idle
waiting agent chats while strictly enforcing chat ownership
(`!conversationAgentId || conversationUserId === actorId`) across
service, route, wake preflight, locked admission, and recovery queries.
- Bounded distinct-comment question wakes under `issues ... FOR UPDATE`
to at most 1 pending/in-flight wake per `(companyId, issueId, agentId)`
and at most 3 original question receipts (`idempotency_key LIKE
'annotation-question-reaction:%'`) per `(companyId, issueId, user)` in a
rolling 10-minute window.
- `renderPaperclipWakePrompt` instructs the agent to answer the question
in the annotation thread.
- `ui`: Added four one-tap reaction buttons (`✅`, `✔️`, `👍`, `❓`) under
each non-optimistic annotation comment in `DocumentAnnotationPanel` /
`DocumentAnnotationPopover`, with counts, `aria-pressed`, hover tooltips
naming actors, optimistic updates, client-scoped write serialization
across panel/popover remounts (`WeakMap<QueryClient, Map<string,
TargetReactionState>>`), live-update refetch overlay preservation,
deferred invalidation while writes are pending, and updated Storybook
fixture.
- `docs/api` & `tests/runner-e2e`: Documented the reaction endpoints and
wake bounds in `docs/api/issues.md` and `docs/api/routines.md`, and
refreshed `tests/runner-e2e/source-sdk-public-inputs.json`.

## Verification

- `pnpm --filter @paperclipai/db run check:migrations` and
`migration-compatibility.ts`: `0510_clear_speedball.sql` classified
`online_compatible`.
- `pnpm --filter @paperclipai/db exec vitest run
src/migration-snapshot-drift.test.ts
src/migration-compatibility.test.ts`: passed (117/117).
- `pnpm --filter @paperclipai/adapter-utils exec vitest run
src/server-utils.test.ts -t "question reaction"`: passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/document-annotations-service.test.ts` (20/20, embedded
Postgres — covering durable wake recovery, idle waiting-chat wake,
busy-turn deferral, non-owner chat wake denial, and rolling-window +
pending-backlog wake bounds across full queue admission),
`src/__tests__/document-annotation-routes.test.ts` (20/20),
`src/__tests__/routine-document-annotation-routes.test.ts`,
`src/modules/wake-queue/application/issue-wake-admission.test.ts`
(15/15), and `src/modules/wake-queue/domain/policy.test.ts`: all passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/openapi-routes.test.ts`: passed (59/59).
- `pnpm --filter @paperclipai/ui exec vitest run
src/hooks/useDocumentAnnotationMutations.test.tsx`: passed (9/9,
covering optimistic updates, serialized writes across remounts,
live-update refetch preservation, deferred invalidation across comments,
and rendered `ThreadCard` DOM buttons/toggles).
- Package typechecks (`@paperclipai/shared`, `@paperclipai/db`,
`@paperclipai/adapter-utils`, `@paperclipai/server` all 7 layers,
`@paperclipai/ui` + Storybook catalog): all passed.
- `pnpm check:token-gates`, `node scripts/check-module-boundaries.mjs`,
and `node scripts/check-test-budget.mjs`: all passed.
- `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse
HEAD) --check`: in sync (`inputs: 579, changed: false`).
- Full-stack Playwright verification against a throwaway local server +
embedded PostgreSQL: created a task, `plan` document, and annotation
thread; verified invalid reaction returns `400`; clicked `thumbs_up` and
`question` in the real document viewer; reloaded to prove PostgreSQL
persistence; toggled `thumbs_up` off and reloaded to verify removal
persisted.
- PR CI on `4d892c8067`: 83/83 executed checks passing (including `ci /
verify`, `ci / e2e` + all 16 E2E shards, all General/Serialized server
shards, `Build`, `Typecheck + Release Registry`, `Verify Paperclip
Runner`, `Superagent Security Scan`, and `Greptile Review` 5/5 with 0
unresolved threads).

## Risks

- Low risk. Migration `0510_clear_speedball.sql` only creates a new
table and its indexes (`online_compatible`), so running releases are
unaffected.
- `reactions` is optional on `DocumentAnnotationComment`, preserving
backward compatibility for existing clients.
- Question wakes are bounded by soft-delete revival (`firstAdd`), chat
ownership enforcement, single pending/in-flight wake per `(companyId,
issueId, agentId)`, and at most 3 original question wakes per
`(companyId, issueId, user)` per 10-minute window.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Google Gemini (`gemini-3-pro` / Antigravity agentic coding environment
with shell execution, file editing, embedded PostgreSQL, and Playwright
verification), rebasing and extending prior work originally authored
with Claude Opus 5.5 in #21637.

## 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: lucktastic <13757243+lucktastic@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
authored and GitHub committed 2026-11-25 15:33:38 -06:00
1 parent 0f52d90993
commit 87fadcb108
40 files changed
+2717 -38

No files matched your search

@@ -21,6 +21,7 @@ const mockAnnotationService = vi.hoisted(() => ({
createThread: vi.fn(),
addComment: vi.fn(),
updateThread: vi.fn(),
setCommentReaction: vi.fn(),
remapOpenThreadsForDocument: vi.fn(),
}));
const mockIssueReferenceService = vi.hoisted(() => ({
@@ -226,6 +227,19 @@ describe("document annotation routes", () => {
mockAnnotationService.addComment.mockResolvedValue(annotationComment);
mockAnnotationService.updateThread.mockResolvedValue({ ...annotationThread, status: "resolved" });
mockAnnotationService.remapOpenThreadsForDocument.mockResolvedValue([]);
mockAnnotationService.setCommentReaction.mockImplementation(async (input: { reaction: string; present: boolean }) => ({
thread: annotationThread,
comment: {
...annotationComment,
reactions: input.present
? [{ reaction: input.reaction, count: 1, reactedByMe: true, actors: [{ actorType: "user", agentId: null, userId: "board-user" }] }]
: [],
},
changed: true,
firstAdd: input.present,
questionWakeRequestId: input.present && input.reaction === "question" ? "wake-req-1" : null,
questionWakeAgentId: input.present && input.reaction === "question" ? "99999999-9999-4999-8999-999999999999" : null,
}));
// Cold route transforms belong to fixture setup, not the request timeout.
await Promise.all([
vi.importActual("../routes/issues.js"),
@@ -243,6 +257,7 @@ describe("document annotation routes", () => {
expect(mockAnnotationService.listThreadsForIssueDocument).toHaveBeenCalledWith(issueId, "plan", {
status: "open",
includeComments: false,
viewer: { actorType: "agent", actorId: "77777777-7777-4777-8777-777777777777" },
});
});
@@ -255,6 +270,7 @@ describe("document annotation routes", () => {
expect(mockAnnotationService.listThreadsForIssueDocument).toHaveBeenCalledWith(issueId, "plan", {
status: "open",
includeComments: true,
viewer: { actorType: "agent", actorId: "77777777-7777-4777-8777-777777777777" },
});
});
@@ -408,4 +424,160 @@ describe("document annotation routes", () => {
}));
expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled();
});
describe("comment reactions", () => {
const assigneeAgentId = "99999999-9999-4999-8999-999999999999";
const reactionPath = (reaction: string) =>
`/api/issues/${issueId}/documents/plan/annotations/${annotationThread.id}/comments/${annotationComment.id}/reactions/${reaction}`;
beforeEach(() => {
mockIssueService.getById.mockResolvedValue({
id: issueId,
companyId,
title: "Annotation API",
status: "in_progress",
assigneeAgentId,
});
});
it("adds a reaction, returns counts and reacted-by-me, and logs activity", async () => {
const res = await request(await createApp()).put(reactionPath("thumbs_up")).expect(200);
expect(res.body.reactions).toEqual([
{ reaction: "thumbs_up", count: 1, reactedByMe: true, actors: [{ actorType: "user", agentId: null, userId: "board-user" }] },
]);
expect(mockAnnotationService.setCommentReaction).toHaveBeenCalledWith({
target: { kind: "issue", issueId, key: "plan" },
threadId: annotationThread.id,
commentId: annotationComment.id,
reaction: "thumbs_up",
present: true,
actor: expect.objectContaining({ actorType: "user", actorId: "board-user", userId: "board-user" }),
});
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
action: "issue.document_annotation_comment_reaction_added",
details: expect.objectContaining({ commentId: annotationComment.id, reaction: "thumbs_up" }),
}));
expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled();
});
it("removes a reaction and logs the removal", async () => {
const res = await request(await createApp()).delete(reactionPath("done")).expect(200);
expect(res.body.reactions).toEqual([]);
expect(mockAnnotationService.setCommentReaction).toHaveBeenCalledWith(expect.objectContaining({
reaction: "done",
present: false,
}));
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
action: "issue.document_annotation_comment_reaction_removed",
}));
});
it("treats a repeated reaction as a quiet no-op", async () => {
mockAnnotationService.setCommentReaction.mockResolvedValueOnce({
thread: annotationThread,
comment: { ...annotationComment, reactions: [] },
changed: false,
});
await request(await createApp()).put(reactionPath("question")).expect(200);
expect(mockLogActivity).not.toHaveBeenCalled();
expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled();
});
it("wakes the assignee once when a person adds a question", async () => {
await request(await createApp()).put(reactionPath("question")).expect(200);
expect(mockHeartbeatService.wakeup).toHaveBeenCalledTimes(1);
expect(mockHeartbeatService.wakeup).toHaveBeenCalledWith(assigneeAgentId, expect.objectContaining({
reason: "issue_commented",
allowRunCoalescing: false,
executionWaitRequestId: "wake-req-1",
requestedByActorType: "user",
requestedByActorId: "board-user",
contextSnapshot: expect.objectContaining({
issueId,
annotationCommentId: annotationComment.id,
annotationThreadId: annotationThread.id,
annotationReaction: "question",
annotationReactionUserId: "board-user",
source: "issue.document_annotation_reaction",
}),
}));
});
it("does not wake the assignee again when a person re-adds a removed question", async () => {
mockAnnotationService.setCommentReaction.mockResolvedValueOnce({
thread: annotationThread,
comment: { ...annotationComment, reactions: [] },
changed: true,
firstAdd: false,
});
await request(await createApp()).put(reactionPath("question")).expect(200);
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
action: "issue.document_annotation_comment_reaction_added",
}));
expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled();
});
it.each(["done", "check", "thumbs_up"])("does not wake the assignee for %s", async (reaction) => {
await request(await createApp()).put(reactionPath(reaction)).expect(200);
expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled();
});
it("does not wake the assignee for a question on a closed task", async () => {
mockIssueService.getById.mockResolvedValue({
id: issueId,
companyId,
title: "Annotation API",
status: "done",
assigneeAgentId,
});
await request(await createApp()).put(reactionPath("question")).expect(200);
expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled();
});
it("does not wake another user's agent chat from a non-owner question", async () => {
mockIssueService.getById.mockResolvedValue({
id: issueId,
companyId,
title: "Annotation API",
status: "in_review",
assigneeAgentId,
conversationAgentId: assigneeAgentId,
conversationUserId: "chat-owner",
});
await request(await createApp()).put(reactionPath("question")).expect(200);
expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled();
});
it("does not wake the assignee when the service suppresses a capped question wake", async () => {
mockAnnotationService.setCommentReaction.mockResolvedValueOnce({
thread: annotationThread,
comment: { ...annotationComment, reactions: [] },
changed: true,
firstAdd: true,
questionWakeRequestId: null,
questionWakeAgentId: null,
questionWakeSuppressed: true,
});
await request(await createApp()).put(reactionPath("question")).expect(200);
expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled();
});
it("rejects an unknown reaction name", async () => {
await request(await createApp()).put(reactionPath("party")).expect(400);
expect(mockAnnotationService.setCommentReaction).not.toHaveBeenCalled();
});
it("returns 404 for another company's task", async () => {
await request(await createApp("agent", otherCompanyId)).put(reactionPath("done")).expect(404);
await request(await createApp("agent", otherCompanyId)).delete(reactionPath("done")).expect(404);
expect(mockAnnotationService.setCommentReaction).not.toHaveBeenCalled();
});
});
});
@@ -2,13 +2,19 @@ import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import {
agents,
agentWakeupRequests,
authUsers,
companies,
companyMemberships,
createDb,
documentAnnotationAnchorSnapshots,
documentAnnotationCommentReactions,
documentAnnotationComments,
documentAnnotationThreads,
documentRevisions,
documents,
heartbeatRuns,
issueComments,
issueDocuments,
issueThreadInteractions,
@@ -18,9 +24,11 @@ import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import { createHeartbeatQueueTestDependencies } from "./helpers/heartbeat-queue.js";
import { documentAnnotationService } from "../services/document-annotations.js";
import { documentService } from "../services/documents.js";
import { buildPaperclipWakePayload } from "../services/heartbeat.js";
import { createHeartbeatQueue } from "../services/heartbeat/queue.js";
import { buildDocumentReviewContext, buildPlanReviewContext, PLAN_REVIEW_CONTEXT_LIMITS } from "../services/plan-review-context.js";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
@@ -57,6 +65,7 @@ describeEmbeddedPostgres("documentAnnotationService", () => {
afterEach(async () => {
await db.delete(documentAnnotationAnchorSnapshots);
await db.delete(documentAnnotationCommentReactions);
await db.delete(documentAnnotationComments);
await db.delete(documentAnnotationThreads);
await db.delete(issueThreadInteractions);
@@ -64,8 +73,14 @@ describeEmbeddedPostgres("documentAnnotationService", () => {
await db.delete(issueDocuments);
await db.delete(documents);
await db.delete(issueComments);
await db.update(issues).set({ executionRunId: null });
await db.delete(heartbeatRuns);
await db.delete(agentWakeupRequests);
await db.delete(issues);
await db.delete(agents);
await db.delete(companyMemberships);
await db.delete(companies);
await db.delete(authUsers);
});
afterAll(async () => {
@@ -630,6 +645,543 @@ describeEmbeddedPostgres("documentAnnotationService", () => {
});
});
async function createAnnotatedIssue() {
const created = await createIssueWithDocument("standard");
const thread = await annotations.createThread(
created.issueId,
"plan",
{
baseRevisionId: created.document.latestRevisionId!,
baseRevisionNumber: created.document.latestRevisionNumber,
selector: {
quote: { exact: "selected text", prefix: "Alpha ", suffix: " omega" },
position: { normalizedStart: 6, normalizedEnd: 19, markdownStart: 6, markdownEnd: 19 },
},
body: "Is this step ready?",
},
{ actorType: "user", actorId: "board-user", userId: "board-user" },
);
return { ...created, thread, comment: thread.comments[0]! };
}
it("adds, repeats safely, and removes comment reactions with counts and reacted-by-me", async () => {
const { companyId, issueId, thread, comment } = await createAnnotatedIssue();
const user = { actorType: "user" as const, actorId: "board-user", userId: "board-user" };
const agentId = randomUUID();
await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer", role: "worker", adapterType: "process", adapterConfig: {} });
const agent = { actorType: "agent" as const, actorId: agentId, agentId };
const target = { kind: "issue" as const, issueId, key: "plan" };
const react = (actor: typeof user | typeof agent, reaction: "done" | "question", present: boolean) =>
annotations.setCommentReaction({ target, threadId: thread.id, commentId: comment.id, reaction, present, actor });
const added = await react(user, "question", true);
expect(added.changed).toBe(true);
expect(added.firstAdd).toBe(true);
expect(added.comment.reactions).toEqual([
{ reaction: "question", count: 1, reactedByMe: true, actors: [{ actorType: "user", agentId: null, userId: "board-user" }] },
]);
expect((await react(user, "question", true)).changed).toBe(false);
await react(agent, "question", true);
await react(agent, "done", true);
const [listed] = await annotations.listThreadsForIssueDocument(issueId, "plan", {
includeComments: true,
viewer: { actorType: "user", actorId: "board-user" },
}) as unknown as Array<{ comments: Array<{ reactions?: unknown[] }> }>;
expect(listed!.comments[0]!.reactions).toEqual([
{ reaction: "done", count: 1, reactedByMe: false, actors: [{ actorType: "agent", agentId, userId: null }] },
expect.objectContaining({ reaction: "question", count: 2, reactedByMe: true }),
]);
const asAgent = await annotations.getThreadForIssueDocument(issueId, "plan", thread.id, { actorType: "agent", actorId: agentId });
expect(asAgent!.comments[0]!.reactions).toEqual([
expect.objectContaining({ reaction: "done", reactedByMe: true }),
expect.objectContaining({ reaction: "question", count: 2, reactedByMe: true }),
]);
const removed = await react(user, "question", false);
expect(removed.changed).toBe(true);
expect(removed.comment.reactions).toEqual([
expect.objectContaining({ reaction: "done", count: 1, reactedByMe: false }),
expect.objectContaining({ reaction: "question", count: 1, reactedByMe: false }),
]);
expect((await react(user, "question", false)).changed).toBe(false);
const readded = await react(user, "question", true);
expect(readded.changed).toBe(true);
expect(readded.firstAdd).toBe(false);
expect(readded.comment.reactions).toEqual([
expect.objectContaining({ reaction: "done", count: 1 }),
expect.objectContaining({ reaction: "question", count: 2, reactedByMe: true }),
]);
});
it("rejects a reaction on a comment that belongs to another issue's thread", async () => {
const { issueId, thread } = await createAnnotatedIssue();
const other = await createAnnotatedIssue();
await expect(annotations.setCommentReaction({
target: { kind: "issue", issueId, key: "plan" },
threadId: thread.id,
commentId: other.comment.id,
reaction: "done",
present: true,
actor: { actorType: "user", actorId: "board-user", userId: "board-user" },
})).rejects.toMatchObject({ status: 404 });
await expect(annotations.setCommentReaction({
target: { kind: "issue", issueId, key: "plan" },
threadId: other.thread.id,
commentId: other.comment.id,
reaction: "done",
present: true,
actor: { actorType: "user", actorId: "board-user", userId: "board-user" },
})).rejects.toMatchObject({ status: 404 });
});
it("marks a question reaction wake on the annotation delta", async () => {
const { companyId, issueId, thread, comment } = await createAnnotatedIssue();
const payload = await buildPaperclipWakePayload({
db,
companyId,
contextSnapshot: {
issueId,
annotationCommentId: comment.id,
annotationThreadId: thread.id,
annotationReaction: "question",
annotationReactionUserId: "board-user",
wakeReason: "issue_commented",
},
});
expect(payload?.annotationDeltas).toMatchObject([
expect.objectContaining({
id: comment.id,
threadId: thread.id,
reaction: { name: "question", author: { type: "user", id: "board-user" } },
}),
]);
});
async function setupAssignedAnnotatedIssue(opts: { waitingChat?: boolean } = {}) {
const created = await createAnnotatedIssue();
const agentId = randomUUID();
const userId = `user-${randomUUID()}`;
const now = new Date();
await db.insert(authUsers).values({
id: userId,
name: "Reviewer",
email: `${userId}@example.test`,
emailVerified: true,
createdAt: now,
updatedAt: now,
});
await db.insert(companyMemberships).values({
companyId: created.companyId,
principalType: "user",
principalId: userId,
status: "active",
membershipRole: "owner",
});
const [agent] = await db.insert(agents).values({
id: agentId,
companyId: created.companyId,
name: "Reviewer Agent",
role: "engineer",
adapterType: "process",
adapterConfig: {},
runtimeConfig: { heartbeat: { enabled: true } },
}).returning();
await db.update(issues).set({
assigneeAgentId: agentId,
...(opts.waitingChat
? {
status: "in_review",
conversationAgentId: agentId,
conversationUserId: userId,
conversationState: "waiting",
}
: { status: "in_progress" }),
}).where(eq(issues.id, created.issueId));
const deps = createHeartbeatQueueTestDependencies(db);
deps.getAgent.mockResolvedValue(agent!);
deps.instanceSettings.getExperimental.mockResolvedValue({ enableIsolatedWorkspaces: false } as never);
deps.issuesSvc.getDependencyReadiness.mockResolvedValue({
issueId: created.issueId,
isDependencyBlocked: false,
unresolvedBlockerCount: 0,
unresolvedBlockers: [],
blockedBy: [],
blocking: [],
} as never);
const queue = createHeartbeatQueue(db, deps);
return { ...created, agentId, userId, queue };
}
it("saves a recoverable wake request with a person's first question and resumes it if immediate wakeup fails", async () => {
const { companyId, issueId, thread, comment, agentId, userId, queue } = await setupAssignedAnnotatedIssue();
const actor = { actorType: "user" as const, actorId: userId, userId };
const added = await annotations.setCommentReaction({
target: { kind: "issue", issueId, key: "plan" },
threadId: thread.id,
commentId: comment.id,
reaction: "question",
present: true,
actor,
});
expect(added.firstAdd).toBe(true);
expect(added.questionWakeRequestId).toEqual(expect.any(String));
// Removing and re-adding must not create a second durable wake request.
await annotations.setCommentReaction({
target: { kind: "issue", issueId, key: "plan" },
threadId: thread.id,
commentId: comment.id,
reaction: "question",
present: false,
actor,
});
const readded = await annotations.setCommentReaction({
target: { kind: "issue", issueId, key: "plan" },
threadId: thread.id,
commentId: comment.id,
reaction: "question",
present: true,
actor,
});
expect(readded.firstAdd).toBe(false);
expect(readded.questionWakeRequestId).toBeNull();
const savedWakes = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, companyId));
expect(savedWakes).toHaveLength(1);
expect(savedWakes[0]).toMatchObject({
id: added.questionWakeRequestId,
agentId,
status: "deferred_issue_execution",
requestedByActorType: "user",
requestedByActorId: userId,
});
// Simulate the route crashing or wakeup failing before dispatch: recovery promotes the saved receipt once.
await queue.resumeDeferredExecutionReceipts({ companyId, requestId: added.questionWakeRequestId! });
await queue.resumeDeferredExecutionReceipts({ companyId, requestId: added.questionWakeRequestId! });
const runs = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, companyId));
expect(runs).toHaveLength(1);
expect(["queued", "running"]).toContain(runs[0]!.status);
expect(runs[0]).toMatchObject({
agentId,
issueId,
responsibleUserId: userId,
contextSnapshot: expect.objectContaining({
issueId,
annotationCommentId: comment.id,
annotationThreadId: thread.id,
annotationReaction: "question",
annotationReactionUserId: userId,
source: "issue.document_annotation_reaction",
}),
});
const [recoveredReceipt] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, added.questionWakeRequestId!));
expect(recoveredReceipt).toMatchObject({ status: "coalesced", runId: runs[0]!.id });
});
it("wakes an idle waiting agent chat when a person adds a question reaction", async () => {
const { companyId, issueId, thread, comment, agentId, userId, queue } = await setupAssignedAnnotatedIssue({ waitingChat: true });
const added = await annotations.setCommentReaction({
target: { kind: "issue", issueId, key: "plan" },
threadId: thread.id,
commentId: comment.id,
reaction: "question",
present: true,
actor: { actorType: "user", actorId: userId, userId },
});
expect(added.questionWakeRequestId).toEqual(expect.any(String));
const run = await queue.trackWakeup(agentId, {
source: "automation",
triggerDetail: "system",
reason: "issue_commented",
payload: {
issueId,
annotationCommentId: comment.id,
annotationThreadId: thread.id,
annotationReaction: "question",
mutation: "annotation_reaction",
},
allowRunCoalescing: false,
executionWaitRequestId: added.questionWakeRequestId!,
requestedByActorType: "user",
requestedByActorId: userId,
contextSnapshot: {
issueId,
taskId: issueId,
annotationCommentId: comment.id,
annotationThreadId: thread.id,
annotationReaction: "question",
annotationReactionUserId: userId,
source: "issue.document_annotation_reaction",
wakeReason: "issue_commented",
},
});
expect(run).not.toBeNull();
expect(run).toMatchObject({
agentId,
issueId,
status: "queued",
contextSnapshot: expect.objectContaining({
annotationCommentId: comment.id,
annotationReaction: "question",
}),
});
const [receipt] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, added.questionWakeRequestId!));
expect(receipt).toMatchObject({ status: "coalesced", runId: run!.id });
const allRuns = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, companyId));
expect(allRuns).toHaveLength(1);
});
it("defers a question reaction behind a running turn without coalescing or duplicating the saved receipt", async () => {
const { companyId, issueId, thread, comment, agentId, userId, queue } = await setupAssignedAnnotatedIssue();
const activeRunId = randomUUID();
await db.insert(heartbeatRuns).values({
id: activeRunId,
companyId,
agentId,
scopeKind: "issue",
issueId,
invocationSource: "assignment",
status: "running",
contextSnapshot: { issueId },
});
await db.update(issues).set({ executionRunId: activeRunId }).where(eq(issues.id, issueId));
const added = await annotations.setCommentReaction({
target: { kind: "issue", issueId, key: "plan" },
threadId: thread.id,
commentId: comment.id,
reaction: "question",
present: true,
actor: { actorType: "user", actorId: userId, userId },
});
const result = await queue.trackWakeup(agentId, {
source: "automation",
triggerDetail: "system",
reason: "issue_commented",
payload: {
issueId,
annotationCommentId: comment.id,
annotationThreadId: thread.id,
annotationReaction: "question",
mutation: "annotation_reaction",
},
allowRunCoalescing: false,
executionWaitRequestId: added.questionWakeRequestId!,
requestedByActorType: "user",
requestedByActorId: userId,
contextSnapshot: {
issueId,
taskId: issueId,
annotationCommentId: comment.id,
annotationThreadId: thread.id,
annotationReaction: "question",
annotationReactionUserId: userId,
source: "issue.document_annotation_reaction",
wakeReason: "issue_commented",
},
});
expect(result).toBeNull();
const deferredRows = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, companyId));
expect(deferredRows).toHaveLength(1);
expect(deferredRows[0]).toMatchObject({
id: added.questionWakeRequestId,
status: "deferred_issue_execution",
runId: null,
});
expect(deferredRows[0]!.payload?.executionWait).toBeUndefined();
});
it("refuses to wake another user's agent chat from a non-owner question reaction", async () => {
const { companyId, issueId, thread, comment, agentId, queue } = await setupAssignedAnnotatedIssue({ waitingChat: true });
const otherUserId = `other-${randomUUID()}`;
const now = new Date();
await db.insert(authUsers).values({
id: otherUserId,
name: "Other Member",
email: `${otherUserId}@example.test`,
emailVerified: true,
createdAt: now,
updatedAt: now,
});
await db.insert(companyMemberships).values({
companyId,
principalType: "user",
principalId: otherUserId,
status: "active",
membershipRole: "member",
});
const added = await annotations.setCommentReaction({
target: { kind: "issue", issueId, key: "plan" },
threadId: thread.id,
commentId: comment.id,
reaction: "question",
present: true,
actor: { actorType: "user", actorId: otherUserId, userId: otherUserId },
});
expect(added.changed).toBe(true);
expect(added.questionWakeRequestId).toBeNull();
expect(added.questionWakeSuppressed).toBe(true);
const savedWakes = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, companyId));
expect(savedWakes).toHaveLength(0);
// Even direct wake admission as a non-owner is rejected by preflight and locked admission.
const directRun = await queue.trackWakeup(agentId, {
source: "automation",
triggerDetail: "system",
reason: "issue_commented",
payload: {
issueId,
annotationCommentId: comment.id,
annotationThreadId: thread.id,
annotationReaction: "question",
mutation: "annotation_reaction",
},
allowRunCoalescing: false,
requestedByActorType: "user",
requestedByActorId: otherUserId,
contextSnapshot: {
issueId,
taskId: issueId,
annotationCommentId: comment.id,
annotationThreadId: thread.id,
annotationReaction: "question",
annotationReactionUserId: otherUserId,
source: "issue.document_annotation_reaction",
wakeReason: "issue_commented",
},
});
expect(directRun).toBeNull();
const runs = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, companyId));
expect(runs).toHaveLength(0);
});
it("bounds question reaction wakes across many distinct comments by pending backlog and per-window cap", async () => {
const { companyId, issueId, thread, comment, agentId, userId, queue } = await setupAssignedAnnotatedIssue();
const actor = { actorType: "user" as const, actorId: userId, userId };
const comments = [comment];
for (let i = 0; i < 4; i += 1) {
comments.push(await annotations.addComment(issueId, "plan", thread.id, { body: `Follow-up ${i + 1}` }, actor));
}
async function admitAndFinishQuestionWake(commentId: string, requestId: string) {
const run = await queue.trackWakeup(agentId, {
source: "automation",
triggerDetail: "system",
reason: "issue_commented",
payload: {
issueId,
annotationCommentId: commentId,
annotationThreadId: thread.id,
annotationReaction: "question",
mutation: "annotation_reaction",
},
allowRunCoalescing: false,
executionWaitRequestId: requestId,
requestedByActorType: "user",
requestedByActorId: userId,
contextSnapshot: {
issueId,
taskId: issueId,
annotationCommentId: commentId,
annotationThreadId: thread.id,
annotationReaction: "question",
annotationReactionUserId: userId,
source: "issue.document_annotation_reaction",
wakeReason: "issue_commented",
},
});
expect(run).not.toBeNull();
await db.update(heartbeatRuns)
.set({ status: "succeeded", finishedAt: new Date() })
.where(eq(heartbeatRuns.id, run!.id));
await db.update(agentWakeupRequests)
.set({ status: "completed", finishedAt: new Date() })
.where(eq(agentWakeupRequests.runId, run!.id));
await db.update(issues)
.set({ executionRunId: null, executionAgentNameKey: null, executionLockedAt: null })
.where(eq(issues.id, issueId));
}
// While the first question wake is still pending, questioning additional distinct comments creates no extra wakes.
const first = await annotations.setCommentReaction({
target: { kind: "issue", issueId, key: "plan" },
threadId: thread.id,
commentId: comments[0]!.id,
reaction: "question",
present: true,
actor,
});
expect(first.questionWakeRequestId).toEqual(expect.any(String));
const secondWhilePending = await annotations.setCommentReaction({
target: { kind: "issue", issueId, key: "plan" },
threadId: thread.id,
commentId: comments[1]!.id,
reaction: "question",
present: true,
actor,
});
expect(secondWhilePending.changed).toBe(true);
expect(secondWhilePending.questionWakeRequestId).toBeNull();
expect(secondWhilePending.questionWakeSuppressed).toBe(true);
// Normal admission coalesces the original receipt into a new primary wake row; both rows must count as ONE wake
// so the rolling 3-per-10-minute allowance still permits 3 full question wakes before suppressing the 4th.
await admitAndFinishQuestionWake(comments[0]!.id, first.questionWakeRequestId!);
const secondWake = await annotations.setCommentReaction({
target: { kind: "issue", issueId, key: "plan" },
threadId: thread.id,
commentId: comments[2]!.id,
reaction: "question",
present: true,
actor,
});
expect(secondWake.questionWakeRequestId).toEqual(expect.any(String));
await admitAndFinishQuestionWake(comments[2]!.id, secondWake.questionWakeRequestId!);
const thirdWake = await annotations.setCommentReaction({
target: { kind: "issue", issueId, key: "plan" },
threadId: thread.id,
commentId: comments[3]!.id,
reaction: "question",
present: true,
actor,
});
expect(thirdWake.questionWakeSuppressed).toBe(false);
expect(thirdWake.questionWakeRequestId).toEqual(expect.any(String));
await admitAndFinishQuestionWake(comments[3]!.id, thirdWake.questionWakeRequestId!);
const fourthCapped = await annotations.setCommentReaction({
target: { kind: "issue", issueId, key: "plan" },
threadId: thread.id,
commentId: comments[4]!.id,
reaction: "question",
present: true,
actor,
});
expect(fourthCapped.changed).toBe(true);
expect(fourthCapped.questionWakeRequestId).toBeNull();
expect(fourthCapped.questionWakeSuppressed).toBe(true);
const originalReceipts = (await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, companyId)))
.filter((row) => row.idempotencyKey?.startsWith("annotation-question-reaction:"));
expect(originalReceipts).toHaveLength(3);
});
it("fails closed when an annotation delta comment id points at a different issue", async () => {
const { companyId, issueId, document } = await createIssueWithDocument("standard");
const { issueId: otherIssueId, document: otherDocument } = await createIssueWithDocument("standard");
@@ -21,6 +21,7 @@ const mockAnnotationService = vi.hoisted(() => ({
createRoutineThread: vi.fn(),
addRoutineComment: vi.fn(),
updateRoutineThread: vi.fn(),
setCommentReaction: vi.fn(),
remapOpenThreadsForRoutineDocument: vi.fn(),
}));
const mockLogActivity = vi.hoisted(() => vi.fn(async () => undefined));
@@ -294,6 +295,34 @@ describe("routine description annotation routes", () => {
}));
});
it("adds and removes routine annotation comment reactions with activity", async () => {
const app = await createApp();
const path = `/api/routines/${routineId}/description/annotations/${annotationThread.id}/comments/${annotationComment.id}/reactions/check`;
mockAnnotationService.setCommentReaction.mockResolvedValue({
thread: annotationThread,
comment: { ...annotationComment, reactions: [] },
changed: true,
});
await request(app).put(path).expect(200);
expect(mockAnnotationService.setCommentReaction).toHaveBeenCalledWith(expect.objectContaining({
target: { kind: "routine", routineId, key: "description" },
commentId: annotationComment.id,
reaction: "check",
present: true,
}));
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
action: "routine.document_annotation_comment_reaction_added",
entityType: "routine",
entityId: routineId,
}));
await request(app).delete(path).expect(200);
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
action: "routine.document_annotation_comment_reaction_removed",
}));
});
it("rejects agent cross-company routine annotation reads", async () => {
// Cross-tenant requests return 404 (not 403) so the status code cannot be
// used as an existence oracle for other tenants' routine ids.
@@ -20,6 +20,7 @@ export function createIssueWakePreflight(readIssue: (companyId: string, issueId:
manualUserWake?: boolean;
taskRetryActorId: string | null;
hasIndependentConversationWakeCause: boolean;
annotationQuestionReaction?: boolean;
}): Promise<
| { kind: "eligible"; onboardingCompletion: boolean }
| { kind: "skipped" }
@@ -36,6 +37,9 @@ export function createIssueWakePreflight(readIssue: (companyId: string, issueId:
if (input.manualUserWake && issue.conversationUserId !== input.requestedByActorId) {
return { kind: "conversation_owner_required", action: "start" };
}
if (input.annotationQuestionReaction && issue.conversationUserId !== input.requestedByActorId) {
return { kind: "skipped" };
}
if (isConversationExecutionWake(issue, input.reason ?? input.wakeReason)
|| input.agentId !== issue.conversationAgentId
|| (isWaitingConversation(issue) && !input.hasIndependentConversationWakeCause)) {
@@ -583,6 +583,11 @@ describe("decideWakeAdmission", () => {
facts: baseWakeAdmissionFacts,
expected: { kind: "coalesce" },
},
{
name: "defer: a wake that refuses run coalescing, such as a question reaction, waits for its own turn",
facts: { ...baseWakeAdmissionFacts, allowRunCoalescing: false },
expected: { kind: "defer" },
},
{
name: "defer: same execution agent, but the running agent needs a fresh session",
facts: { ...baseWakeAdmissionFacts, shouldDeferFollowupWake: true },
+62
View File
@@ -43,6 +43,7 @@ import {
} from "@paperclipai/db";
import {
createDocumentAnnotationCommentSchema,
documentAnnotationCommentReactionSchema,
createDocumentAnnotationThreadSchema,
updateDocumentAnnotationThreadSchema,
isUuidLike,
@@ -115,6 +116,11 @@ function parseQueryList(value: string | string[] | undefined): string[] {
return values.flatMap((item) => item.split(",")).map((item) => item.trim()).filter(Boolean);
}
function annotationReactionViewer(req: Request) {
const actor = getActorInfo(req);
return { actorType: actor.actorType, actorId: actor.actorId };
}
function annotationActorInput(req: Request) {
const actor = getActorInfo(req);
return {
@@ -889,6 +895,7 @@ export function caseRoutes(db: Db, storage: StorageService) {
const threads = await documentAnnotationsSvc.listThreadsForCaseDocument(caseRow.id, key, {
status,
includeComments: parseBooleanQuery(req.query.includeComments),
viewer: annotationReactionViewer(req),
});
res.json(threads);
});
@@ -901,6 +908,7 @@ export function caseRoutes(db: Db, storage: StorageService) {
caseRow.id,
key,
req.params.threadId as string,
annotationReactionViewer(req),
);
if (!thread) throw notFound("Annotation thread not found");
res.json(thread);
@@ -1021,6 +1029,60 @@ export function caseRoutes(db: Db, storage: StorageService) {
},
);
async function setCaseAnnotationCommentReaction(req: Request, res: Response, present: boolean) {
await assertCasesEnabled(db);
const caseRow = await assertCaseAccess(db, req, req.params.id as string);
const key = parseDocumentKey(req.params.key as string);
const reactionParsed = documentAnnotationCommentReactionSchema.safeParse(req.params.reaction);
if (!reactionParsed.success) {
res.status(400).json({ error: "Invalid reaction", details: reactionParsed.error.issues });
return;
}
const { actor, annotationActor } = annotationActorInput(req);
const result = await mutateCase(req, caseRow, tx => documentAnnotationService(tx as unknown as Db).setCommentReaction({
target: { kind: "case", caseId: caseRow.id, key },
threadId: req.params.threadId as string,
commentId: req.params.commentId as string,
reaction: reactionParsed.data,
present,
actor: annotationActor,
}));
if (result.changed) {
await logActivity(db, {
companyId: caseRow.companyId,
actorType: actor.actorType,
actorId: actor.actorId,
agentId: actor.agentId,
runId: actor.runId,
agentApiKeyId: actor.agentApiKeyId,
action: present
? "case.document_annotation_comment_reaction_added"
: "case.document_annotation_comment_reaction_removed",
entityType: "case",
entityId: caseRow.id,
details: {
key,
documentKey: key,
documentId: result.thread.documentId,
threadId: result.thread.id,
commentId: result.comment.id,
reaction: reactionParsed.data,
},
});
}
res.json(result.comment);
}
router.put(
"/cases/:id/documents/:key/annotations/:threadId/comments/:commentId/reactions/:reaction",
async (req, res) => setCaseAnnotationCommentReaction(req, res, true),
);
router.delete(
"/cases/:id/documents/:key/annotations/:threadId/comments/:commentId/reactions/:reaction",
async (req, res) => setCaseAnnotationCommentReaction(req, res, false),
);
router.put("/cases/:id/documents/:key", async (req, res) => {
await assertCasesEnabled(db);
const caseRow = await assertCaseAccess(db, req, req.params.id as string);
@@ -63,6 +63,20 @@ export const experimentalApiMetadata: Record<string, { successStatuses: number[]
"boardOnly": false,
"source": "server/src/routes/cases.ts"
},
"PUT /api/cases/{id}/documents/{key}/annotations/{threadId}/comments/{commentId}/reactions/{reaction}": {
"successStatuses": [
200
],
"boardOnly": false,
"source": "server/src/routes/cases.ts"
},
"DELETE /api/cases/{id}/documents/{key}/annotations/{threadId}/comments/{commentId}/reactions/{reaction}": {
"successStatuses": [
200
],
"boardOnly": false,
"source": "server/src/routes/cases.ts"
},
"PUT /api/cases/{id}/documents/{key}": {
"successStatuses": [
200
@@ -13,6 +13,8 @@ export const experimentalApiPaths: readonly [string, string, z.ZodTypeAny | unde
["post", "/api/cases/{id}/documents/{key}/annotations", sharedSchemas.createDocumentAnnotationThreadSchema],
["post", "/api/cases/{id}/documents/{key}/annotations/{threadId}/comments", sharedSchemas.createDocumentAnnotationCommentSchema],
["patch", "/api/cases/{id}/documents/{key}/annotations/{threadId}", sharedSchemas.updateDocumentAnnotationThreadSchema],
["put", "/api/cases/{id}/documents/{key}/annotations/{threadId}/comments/{commentId}/reactions/{reaction}", undefined],
["delete", "/api/cases/{id}/documents/{key}/annotations/{threadId}/comments/{commentId}/reactions/{reaction}", undefined],
["put", "/api/cases/{id}/documents/{key}", caseSchemas.upsertCaseDocumentSchema],
["post", "/api/cases/{id}/documents/{key}/lock", undefined],
["post", "/api/cases/{id}/documents/{key}/unlock", undefined],
+138
View File
@@ -127,6 +127,7 @@ import {
checkoutIssueSchema,
createDocumentAnnotationCommentSchema,
createDocumentAnnotationThreadSchema,
documentAnnotationCommentReactionSchema,
createChildIssueSchema,
createIssueSchema,
resolveCreateIssueStatusDefault,
@@ -4824,6 +4825,11 @@ export function issueRoutes(
};
}
function annotationReactionViewer(req: Request) {
const actor = getActorInfo(req);
return { actorType: actor.actorType, actorId: actor.actorId };
}
async function canonicalizePaperclipArtifactMetadata(input: {
issue: { id: string; companyId: string };
metadata: Record<string, unknown> | null | undefined;
@@ -11181,6 +11187,7 @@ export function issueRoutes(
{
status: "open",
includeComments: shouldIncludeDocumentAnnotationComments(req),
viewer: annotationReactionViewer(req),
},
);
res.json({ ...doc, annotations });
@@ -11218,6 +11225,7 @@ export function issueRoutes(
{
status,
includeComments: parseBooleanQuery(req.query.includeComments),
viewer: annotationReactionViewer(req),
},
);
res.json(threads);
@@ -11337,6 +11345,7 @@ export function issueRoutes(
issue.id,
keyParsed.data,
req.params.threadId as string,
annotationReactionViewer(req),
);
if (!thread) {
res.status(404).json({ error: "Annotation thread not found" });
@@ -11482,6 +11491,135 @@ export function issueRoutes(
},
);
async function setIssueAnnotationCommentReaction(
req: Request,
res: Response,
present: boolean,
) {
const id = req.params.id as string;
const issue = await getAccessibleResource(
req,
res,
svc.getById(id),
"Issue not found",
);
if (!issue) return;
if (!(await assertAgentIssueMutationAllowed(req, res, issue))) return;
const keyParsed = issueDocumentKeySchema.safeParse(
String(req.params.key ?? "")
.trim()
.toLowerCase(),
);
if (!keyParsed.success) {
res.status(400).json({
error: "Invalid document key",
details: keyParsed.error.issues,
});
return;
}
const reactionParsed = documentAnnotationCommentReactionSchema.safeParse(
req.params.reaction,
);
if (!reactionParsed.success) {
res.status(400).json({
error: "Invalid reaction",
details: reactionParsed.error.issues,
});
return;
}
const { actor, annotationActor } = annotationActorInput(req);
const result = await documentAnnotationsSvc.setCommentReaction({
target: { kind: "issue", issueId: issue.id, key: keyParsed.data },
threadId: req.params.threadId as string,
commentId: req.params.commentId as string,
reaction: reactionParsed.data,
present,
actor: annotationActor,
});
if (result.changed) {
await logActivity(db, {
companyId: issue.companyId,
actorType: actor.actorType,
actorId: actor.actorId,
agentId: actor.agentId,
runId: actor.runId,
agentApiKeyId: actor.agentApiKeyId,
action: present
? "issue.document_annotation_comment_reaction_added"
: "issue.document_annotation_comment_reaction_removed",
entityType: "issue",
entityId: issue.id,
details: {
key: keyParsed.data,
documentKey: keyParsed.data,
documentId: result.thread.documentId,
threadId: result.thread.id,
commentId: result.comment.id,
reaction: reactionParsed.data,
},
});
}
const questionWakeAgentId = result.questionWakeAgentId ?? issue.assigneeAgentId;
const chatOwnerAllowed =
!issue.conversationAgentId || issue.conversationUserId === actor.actorId;
if (
present &&
result.firstAdd &&
!result.questionWakeSuppressed &&
reactionParsed.data === "question" &&
actor.actorType === "user" &&
questionWakeAgentId &&
chatOwnerAllowed &&
!isClosedIssueStatus(issue.status)
) {
await heartbeat.wakeup(questionWakeAgentId, {
source: "automation",
triggerDetail: "system",
reason: "issue_commented",
payload: {
issueId: issue.id,
annotationCommentId: result.comment.id,
annotationThreadId: result.thread.id,
annotationReaction: "question",
mutation: "annotation_reaction",
},
allowRunCoalescing: false,
...(result.questionWakeRequestId ? { executionWaitRequestId: result.questionWakeRequestId } : {}),
requestedByActorType: actor.actorType,
requestedByActorId: actor.actorId,
contextSnapshot: {
issueId: issue.id,
taskId: issue.id,
annotationCommentId: result.comment.id,
annotationThreadId: result.thread.id,
annotationReaction: "question",
annotationReactionUserId: actor.actorId,
source: "issue.document_annotation_reaction",
wakeReason: "issue_commented",
},
}).catch((err: unknown) => {
logger.warn(
{ err, issueId: issue.id, annotationCommentId: result.comment.id },
"failed to wake assignee for an annotation question reaction",
);
});
}
res.json(result.comment);
}
router.put(
"/issues/:id/documents/:key/annotations/:threadId/comments/:commentId/reactions/:reaction",
async (req, res) => setIssueAnnotationCommentReaction(req, res, true),
);
router.delete(
"/issues/:id/documents/:key/annotations/:threadId/comments/:commentId/reactions/:reaction",
async (req, res) => setIssueAnnotationCommentReaction(req, res, false),
);
router.put(
"/issues/:id/documents/:key",
validate(upsertIssueDocumentSchema),
+52
View File
@@ -11815,6 +11815,32 @@ registerCurrentRoute({
body: updateDocumentAnnotationThreadSchema,
});
registerCurrentRoute({
method: "put",
path: "/api/issues/{id}/documents/{key}/annotations/{threadId}/comments/{commentId}/reactions/{reaction}",
tags: ["issues"],
summary: "Add a reaction on a document annotation comment",
responses: {
200: r.ok(),
400: r.badRequest,
401: r.unauthorized,
404: r.notFound,
},
});
registerCurrentRoute({
method: "delete",
path: "/api/issues/{id}/documents/{key}/annotations/{threadId}/comments/{commentId}/reactions/{reaction}",
tags: ["issues"],
summary: "Remove a reaction on a document annotation comment",
responses: {
200: r.ok(),
400: r.badRequest,
401: r.unauthorized,
404: r.notFound,
},
});
for (const route of [
[
"get",
@@ -11871,6 +11897,32 @@ registerCurrentRoute({
body: updateDocumentAnnotationThreadSchema,
});
registerCurrentRoute({
method: "put",
path: "/api/routines/{id}/description/annotations/{threadId}/comments/{commentId}/reactions/{reaction}",
tags: ["routines"],
summary: "Add a reaction on a routine description annotation comment",
responses: {
200: r.ok(),
400: r.badRequest,
401: r.unauthorized,
404: r.notFound,
},
});
registerCurrentRoute({
method: "delete",
path: "/api/routines/{id}/description/annotations/{threadId}/comments/{commentId}/reactions/{reaction}",
tags: ["routines"],
summary: "Remove a reaction on a routine description annotation comment",
responses: {
200: r.ok(),
400: r.badRequest,
401: r.unauthorized,
404: r.notFound,
},
});
registerCurrentRoute({
method: "get",
path: "/api/issues/{id}/diagnostics/blockers",
+65 -1
View File
@@ -1,4 +1,4 @@
import { Router, type Request } from "express";
import { Router, type Request, type Response } from "express";
import { z } from "zod";
import { triggerUpdateActivityAction } from "../services/routine-trigger-update-plan.js";
import { listProtectedEnvironmentKeyHolders, protectedEnvironmentKeyWarnings } from "../services/protected-environment-keys.js";
@@ -8,6 +8,7 @@ import {
createDocumentAnnotationCommentSchema,
createDocumentAnnotationThreadSchema,
createRoutineTriggerSchema,
documentAnnotationCommentReactionSchema,
ROUTINE_STATUSES,
rotateRoutineTriggerSecretSchema,
runRoutineSchema,
@@ -68,6 +69,11 @@ export function routineRoutes(
};
}
function annotationReactionViewer(req: Request) {
const actor = getActorInfo(req);
return { actorType: actor.actorType, actorId: actor.actorId };
}
async function remapRoutineDescriptionAnnotations(req: Request, routineId: string) {
const doc = await svc.getDescriptionDocument(routineId);
if (!doc) return;
@@ -279,6 +285,7 @@ export function routineRoutes(
const threads = await documentAnnotationsSvc.listThreadsForRoutineDocument(routine.id, routineDocumentKey, {
status,
includeComments: parseBooleanQuery(req.query.includeComments),
viewer: annotationReactionViewer(req),
});
res.json(threads);
});
@@ -293,6 +300,7 @@ export function routineRoutes(
routine.id,
routineDocumentKey,
req.params.threadId as string,
annotationReactionViewer(req),
);
if (!thread) {
res.status(404).json({ error: "Annotation thread not found" });
@@ -422,6 +430,62 @@ export function routineRoutes(
},
);
async function setRoutineAnnotationCommentReaction(req: Request, res: Response, present: boolean) {
const routine = await assertCanManageExistingRoutine(req, req.params.id as string);
if (!routine) {
res.status(404).json({ error: "Routine not found" });
return;
}
const reactionParsed = documentAnnotationCommentReactionSchema.safeParse(req.params.reaction);
if (!reactionParsed.success) {
res.status(400).json({ error: "Invalid reaction", details: reactionParsed.error.issues });
return;
}
const { actor, annotationActor } = annotationActorInput(req);
const result = await documentAnnotationsSvc.setCommentReaction({
target: { kind: "routine", routineId: routine.id, key: routineDocumentKey },
threadId: req.params.threadId as string,
commentId: req.params.commentId as string,
reaction: reactionParsed.data,
present,
actor: annotationActor,
});
if (result.changed) {
await logActivity(db, {
companyId: routine.companyId,
actorType: actor.actorType,
actorId: actor.actorId,
agentId: actor.agentId,
runId: actor.runId,
agentApiKeyId: actor.agentApiKeyId,
action: present
? "routine.document_annotation_comment_reaction_added"
: "routine.document_annotation_comment_reaction_removed",
entityType: "routine",
entityId: routine.id,
details: {
key: routineDocumentKey,
documentKey: routineDocumentKey,
documentId: result.thread.documentId,
threadId: result.thread.id,
commentId: result.comment.id,
reaction: reactionParsed.data,
},
});
}
res.json(result.comment);
}
router.put(
"/routines/:id/description/annotations/:threadId/comments/:commentId/reactions/:reaction",
async (req, res) => setRoutineAnnotationCommentReaction(req, res, true),
);
router.delete(
"/routines/:id/description/annotations/:threadId/comments/:commentId/reactions/:reaction",
async (req, res) => setRoutineAnnotationCommentReaction(req, res, false),
);
router.patch("/routines/:id", validate(updateRoutineSchema), async (req, res) => {
const routine = await assertCanManageExistingRoutine(req, req.params.id as string);
if (!routine) {
+296 -15
View File
@@ -1,23 +1,32 @@
import { and, asc, desc, eq, inArray, isNull, sql } from "drizzle-orm";
import { randomUUID } from "node:crypto";
import { and, asc, desc, eq, gte, inArray, isNull, sql } from "drizzle-orm";
import { assertAgentInteraction } from "./agent-interaction-policy.js";
import type { Db } from "@paperclipai/db";
import {
agentWakeupRequests,
documentAnnotationAnchorSnapshots,
documentAnnotationCommentReactions,
documentAnnotationComments,
documentAnnotationThreads,
documents,
caseDocuments,
issueComments,
issueDocuments,
issues,
routineDocuments,
} from "@paperclipai/db";
import { notifyDeferredExecutionWork } from "./deferred-execution-notifications.js";
import { deferredWorkIntentWait } from "./work-intent-outbox.js";
import {
anchorSnapshotToSelector,
remapDocumentAnchor,
selectorToAnchorSnapshot,
verifyDocumentAnchorSelector,
type DocumentAnnotationAnchorSnapshot,
DOCUMENT_ANNOTATION_COMMENT_REACTIONS,
type DocumentAnnotationComment,
type DocumentAnnotationCommentReactionName,
type DocumentAnnotationCommentReactionSummary,
type DocumentAnnotationThread,
CreateDocumentAnnotationComment,
CreateDocumentAnnotationThread,
@@ -25,6 +34,10 @@ import {
} from "@paperclipai/shared";
import { conflict, notFound, unprocessable } from "../errors.js";
const ANNOTATION_QUESTION_WAKE_WINDOW_MS = 10 * 60 * 1000;
const ANNOTATION_QUESTION_WAKE_MAX_PER_WINDOW = 3;
const ANNOTATION_QUESTION_REACTION_KEY_PREFIX = "annotation-question-reaction:";
type ActorInput = {
actorType: "agent" | "user";
actorId: string;
@@ -33,6 +46,19 @@ type ActorInput = {
runId?: string | null;
};
type ReactionViewer = { actorType: "agent" | "user"; actorId: string } | null | undefined;
type ListThreadOptions = {
status?: "open" | "resolved" | "all";
includeComments?: boolean;
viewer?: ReactionViewer;
};
export type DocumentAnnotationReactionTarget =
| { kind: "issue"; issueId: string; key: string }
| { kind: "routine"; routineId: string; key: string }
| { kind: "case"; caseId: string; key: string };
type IssueDocumentRow = {
issueId: string;
companyId: string;
@@ -252,13 +278,91 @@ export function documentAnnotationService(db: Db) {
.then((rows: DocumentAnnotationThread[]) => rows[0] ?? null);
}
async function commentsForThreads(threadIds: string[], dbOrTx: any = db): Promise<DocumentAnnotationComment[]> {
async function reactionsForComments(
commentIds: string[],
viewer: ReactionViewer,
dbOrTx: any = db,
): Promise<Map<string, DocumentAnnotationCommentReactionSummary[]>> {
const byComment = new Map<string, DocumentAnnotationCommentReactionSummary[]>();
if (commentIds.length === 0) return byComment;
const rows: Array<{
commentId: string;
reaction: DocumentAnnotationCommentReactionName;
actorType: "agent" | "user";
actorId: string;
}> = await dbOrTx
.select({
commentId: documentAnnotationCommentReactions.commentId,
reaction: documentAnnotationCommentReactions.reaction,
actorType: documentAnnotationCommentReactions.actorType,
actorId: documentAnnotationCommentReactions.actorId,
})
.from(documentAnnotationCommentReactions)
.where(and(
inArray(documentAnnotationCommentReactions.commentId, commentIds),
isNull(documentAnnotationCommentReactions.removedAt),
))
.orderBy(asc(documentAnnotationCommentReactions.createdAt), asc(documentAnnotationCommentReactions.id));
const grouped = new Map<string, Map<DocumentAnnotationCommentReactionName, DocumentAnnotationCommentReactionSummary>>();
for (const row of rows) {
const perComment = grouped.get(row.commentId) ?? new Map();
grouped.set(row.commentId, perComment);
const summary = perComment.get(row.reaction) ?? { reaction: row.reaction, count: 0, reactedByMe: false, actors: [] };
perComment.set(row.reaction, summary);
summary.count += 1;
summary.actors.push({
actorType: row.actorType,
agentId: row.actorType === "agent" ? row.actorId : null,
userId: row.actorType === "user" ? row.actorId : null,
});
if (viewer && viewer.actorType === row.actorType && viewer.actorId === row.actorId) summary.reactedByMe = true;
}
for (const [commentId, perComment] of grouped) {
byComment.set(
commentId,
DOCUMENT_ANNOTATION_COMMENT_REACTIONS.flatMap((reaction) => perComment.get(reaction) ?? []),
);
}
return byComment;
}
async function withReactions(
comments: DocumentAnnotationComment[],
viewer: ReactionViewer,
dbOrTx: any = db,
): Promise<DocumentAnnotationComment[]> {
const reactions = await reactionsForComments(comments.map((comment) => comment.id), viewer, dbOrTx);
return comments.map((comment) => ({ ...comment, reactions: reactions.get(comment.id) ?? [] }));
}
async function commentsForThreads(
threadIds: string[],
dbOrTx: any = db,
viewer?: ReactionViewer,
): Promise<DocumentAnnotationComment[]> {
if (threadIds.length === 0) return [];
return dbOrTx
const comments: DocumentAnnotationComment[] = await dbOrTx
.select(commentSelect)
.from(documentAnnotationComments)
.where(inArray(documentAnnotationComments.threadId, threadIds))
.orderBy(asc(documentAnnotationComments.createdAt), asc(documentAnnotationComments.id));
return withReactions(comments, viewer, dbOrTx);
}
async function getThreadForReactionTarget(
target: DocumentAnnotationReactionTarget,
threadId: string,
dbOrTx: any,
): Promise<DocumentAnnotationThread | null> {
if (target.kind === "issue") return getThreadForIssue(target.issueId, target.key, threadId, dbOrTx);
if (target.kind === "routine") {
const doc = await getRoutineDocument(target.routineId, target.key, dbOrTx);
if (!doc) throw notFound("Document not found");
return getThreadForRoutine(target.routineId, target.key, threadId, doc.companyId, doc.documentId, dbOrTx);
}
const doc = await getCaseDocument(target.caseId, target.key, dbOrTx);
if (!doc) throw notFound("Document not found");
return getThreadForCase(target.caseId, target.key, threadId, doc.companyId, doc.documentId, dbOrTx);
}
async function assertLinkedIssueComment(
@@ -286,7 +390,7 @@ export function documentAnnotationService(db: Db) {
listThreadsForIssueDocument: async (
issueId: string,
key: string,
options: { status?: "open" | "resolved" | "all"; includeComments?: boolean } = {},
options: ListThreadOptions = {},
) => {
const doc = await getIssueDocument(issueId, key);
if (!doc) throw notFound("Document not found");
@@ -303,7 +407,7 @@ export function documentAnnotationService(db: Db) {
.where(and(...conditions))
.orderBy(desc(documentAnnotationThreads.updatedAt), desc(documentAnnotationThreads.id));
if (!options.includeComments) return threads;
const comments = await commentsForThreads(threads.map((thread) => thread.id));
const comments = await commentsForThreads(threads.map((thread) => thread.id), db, options.viewer);
const commentsByThread = new Map<string, DocumentAnnotationComment[]>();
for (const comment of comments) {
const existing = commentsByThread.get(comment.threadId) ?? [];
@@ -319,7 +423,7 @@ export function documentAnnotationService(db: Db) {
listThreadsForRoutineDocument: async (
routineId: string,
key: string,
options: { status?: "open" | "resolved" | "all"; includeComments?: boolean } = {},
options: ListThreadOptions = {},
) => {
const doc = await getRoutineDocument(routineId, key);
if (!doc) throw notFound("Document not found");
@@ -337,7 +441,7 @@ export function documentAnnotationService(db: Db) {
.where(and(...conditions))
.orderBy(desc(documentAnnotationThreads.updatedAt), desc(documentAnnotationThreads.id));
if (!options.includeComments) return threads;
const comments = await commentsForThreads(threads.map((thread) => thread.id));
const comments = await commentsForThreads(threads.map((thread) => thread.id), db, options.viewer);
const commentsByThread = new Map<string, DocumentAnnotationComment[]>();
for (const comment of comments) {
const existing = commentsByThread.get(comment.threadId) ?? [];
@@ -353,7 +457,7 @@ export function documentAnnotationService(db: Db) {
listThreadsForCaseDocument: async (
caseId: string,
key: string,
options: { status?: "open" | "resolved" | "all"; includeComments?: boolean } = {},
options: ListThreadOptions = {},
) => {
const doc = await getCaseDocument(caseId, key);
if (!doc) throw notFound("Document not found");
@@ -371,7 +475,7 @@ export function documentAnnotationService(db: Db) {
.where(and(...conditions))
.orderBy(desc(documentAnnotationThreads.updatedAt), desc(documentAnnotationThreads.id));
if (!options.includeComments) return threads;
const comments = await commentsForThreads(threads.map((thread) => thread.id));
const comments = await commentsForThreads(threads.map((thread) => thread.id), db, options.viewer);
const commentsByThread = new Map<string, DocumentAnnotationComment[]>();
for (const comment of comments) {
const existing = commentsByThread.get(comment.threadId) ?? [];
@@ -384,28 +488,28 @@ export function documentAnnotationService(db: Db) {
}));
},
getThreadForIssueDocument: async (issueId: string, key: string, threadId: string) => {
getThreadForIssueDocument: async (issueId: string, key: string, threadId: string, viewer?: ReactionViewer) => {
const thread = await getThreadForIssue(issueId, key, threadId);
if (!thread) return null;
const comments = await commentsForThreads([thread.id]);
const comments = await commentsForThreads([thread.id], db, viewer);
return { ...thread, comments };
},
getThreadForRoutineDocument: async (routineId: string, key: string, threadId: string) => {
getThreadForRoutineDocument: async (routineId: string, key: string, threadId: string, viewer?: ReactionViewer) => {
const doc = await getRoutineDocument(routineId, key);
if (!doc) return null;
const thread = await getThreadForRoutine(routineId, key, threadId, doc.companyId, doc.documentId);
if (!thread) return null;
const comments = await commentsForThreads([thread.id]);
const comments = await commentsForThreads([thread.id], db, viewer);
return { ...thread, comments };
},
getThreadForCaseDocument: async (caseId: string, key: string, threadId: string) => {
getThreadForCaseDocument: async (caseId: string, key: string, threadId: string, viewer?: ReactionViewer) => {
const doc = await getCaseDocument(caseId, key);
if (!doc) return null;
const thread = await getThreadForCase(caseId, key, threadId, doc.companyId, doc.documentId);
if (!thread) return null;
const comments = await commentsForThreads([thread.id]);
const comments = await commentsForThreads([thread.id], db, viewer);
return { ...thread, comments };
},
@@ -788,6 +892,183 @@ export function documentAnnotationService(db: Db) {
return comment;
}),
setCommentReaction: async (input: {
target: DocumentAnnotationReactionTarget;
threadId: string;
commentId: string;
reaction: DocumentAnnotationCommentReactionName;
present: boolean;
actor: ActorInput;
}) => db.transaction(async (tx) => {
const thread = await getThreadForReactionTarget(input.target, input.threadId, tx);
if (!thread) throw notFound("Annotation thread not found");
if (input.target.kind === "issue") {
await assertAgentInteraction(tx, { companyId: thread.companyId, actorAgentId: input.actor.agentId,
operation: "comment", issueId: input.target.issueId, texts: [], lock: true });
}
const [comment]: DocumentAnnotationComment[] = await tx
.select(commentSelect)
.from(documentAnnotationComments)
.where(and(
eq(documentAnnotationComments.id, input.commentId),
eq(documentAnnotationComments.threadId, thread.id),
eq(documentAnnotationComments.companyId, thread.companyId),
));
if (!comment) throw notFound("Annotation comment not found");
const changedRows: Array<{ id: string; firstAdd: boolean }> = input.present
? await tx
.insert(documentAnnotationCommentReactions)
.values({
companyId: thread.companyId,
commentId: comment.id,
reaction: input.reaction,
actorType: input.actor.actorType,
actorId: input.actor.actorId,
})
.onConflictDoUpdate({
target: [
documentAnnotationCommentReactions.commentId,
documentAnnotationCommentReactions.reaction,
documentAnnotationCommentReactions.actorType,
documentAnnotationCommentReactions.actorId,
],
set: { removedAt: null },
setWhere: sql`${documentAnnotationCommentReactions.removedAt} is not null`,
})
.returning({ id: documentAnnotationCommentReactions.id, firstAdd: sql<boolean>`(xmax = 0)` })
: await tx
.update(documentAnnotationCommentReactions)
.set({ removedAt: new Date() })
.where(and(
eq(documentAnnotationCommentReactions.commentId, comment.id),
eq(documentAnnotationCommentReactions.reaction, input.reaction),
eq(documentAnnotationCommentReactions.actorType, input.actor.actorType),
eq(documentAnnotationCommentReactions.actorId, input.actor.actorId),
isNull(documentAnnotationCommentReactions.removedAt),
))
.returning({ id: documentAnnotationCommentReactions.id, firstAdd: sql<boolean>`false` });
const changed = changedRows.length > 0;
const firstAdd = changedRows[0]?.firstAdd === true;
let questionWakeRequestId: string | null = null;
let questionWakeAgentId: string | null = null;
let questionWakeSuppressed = false;
if (
input.present &&
firstAdd &&
input.reaction === "question" &&
input.actor.actorType === "user" &&
input.target.kind === "issue"
) {
const [issue] = await tx
.select({
id: issues.id,
status: issues.status,
assigneeAgentId: issues.assigneeAgentId,
conversationAgentId: issues.conversationAgentId,
conversationUserId: issues.conversationUserId,
})
.from(issues)
.where(and(eq(issues.companyId, thread.companyId), eq(issues.id, input.target.issueId)))
.for("update");
const chatOwnerAllowed =
!issue?.conversationAgentId ||
(issue.assigneeAgentId === issue.conversationAgentId &&
issue.conversationUserId === input.actor.actorId);
if (
issue &&
issue.assigneeAgentId &&
issue.status !== "done" &&
issue.status !== "cancelled" &&
chatOwnerAllowed
) {
const [existingPending] = await tx
.select({ id: agentWakeupRequests.id })
.from(agentWakeupRequests)
.where(and(
eq(agentWakeupRequests.companyId, thread.companyId),
eq(agentWakeupRequests.agentId, issue.assigneeAgentId),
inArray(agentWakeupRequests.status, ["deferred_issue_execution", "queued", "claimed"]),
sql`${agentWakeupRequests.payload}->>'issueId' = ${issue.id}`,
sql`${agentWakeupRequests.payload}->>'mutation' = 'annotation_reaction'`,
))
.limit(1);
const windowStart = new Date(Date.now() - ANNOTATION_QUESTION_WAKE_WINDOW_MS);
const recentActorWakes = existingPending
? []
: await tx
.select({ id: agentWakeupRequests.id })
.from(agentWakeupRequests)
.where(and(
eq(agentWakeupRequests.companyId, thread.companyId),
eq(agentWakeupRequests.requestedByActorType, "user"),
eq(agentWakeupRequests.requestedByActorId, input.actor.actorId),
gte(agentWakeupRequests.requestedAt, windowStart),
sql`${agentWakeupRequests.idempotencyKey} like ${ANNOTATION_QUESTION_REACTION_KEY_PREFIX + "%"}`,
sql`${agentWakeupRequests.payload}->>'issueId' = ${issue.id}`,
sql`${agentWakeupRequests.payload}->>'mutation' = 'annotation_reaction'`,
))
.limit(ANNOTATION_QUESTION_WAKE_MAX_PER_WINDOW);
if (existingPending || recentActorWakes.length >= ANNOTATION_QUESTION_WAKE_MAX_PER_WINDOW) {
questionWakeSuppressed = true;
} else {
const wakeRequestId = randomUUID();
await notifyDeferredExecutionWork(tx, {
companyId: thread.companyId,
requestId: wakeRequestId,
});
await tx.insert(agentWakeupRequests).values({
id: wakeRequestId,
companyId: thread.companyId,
agentId: issue.assigneeAgentId,
source: "automation",
triggerDetail: "system",
reason: "issue_commented",
status: "deferred_issue_execution",
requestedByActorType: "user",
requestedByActorId: input.actor.actorId,
idempotencyKey: `${ANNOTATION_QUESTION_REACTION_KEY_PREFIX}${changedRows[0]!.id}`,
payload: {
issueId: issue.id,
annotationCommentId: comment.id,
annotationThreadId: thread.id,
annotationReaction: "question",
mutation: "annotation_reaction",
executionWait: deferredWorkIntentWait(
"wake_lost",
"Waiting to deliver annotation question reaction.",
),
_paperclipWakeContext: {
issueId: issue.id,
taskId: issue.id,
annotationCommentId: comment.id,
annotationThreadId: thread.id,
annotationReaction: "question",
annotationReactionUserId: input.actor.actorId,
source: "issue.document_annotation_reaction",
wakeReason: "issue_commented",
},
},
});
questionWakeRequestId = wakeRequestId;
questionWakeAgentId = issue.assigneeAgentId;
}
} else {
questionWakeSuppressed = true;
}
}
const [withSummary] = await withReactions([comment], input.actor, tx);
return {
thread,
comment: withSummary!,
changed,
firstAdd,
questionWakeRequestId,
questionWakeAgentId,
questionWakeSuppressed,
};
}),
cleanupForIssueCommentDeletion: async (
issueId: string,
issueCommentId: string,
+1
View File
@@ -4624,6 +4624,7 @@ export function heartbeatService(
}),
wakeup: trackWakeup,
resumeDeferredExecutionReceipts: heartbeatQueue.resumeDeferredExecutionReceipts,
dispatchPendingNativeStatusWakeups,
triggerIssueMonitor,
@@ -88,6 +88,7 @@ export function registerDeferredReceiptWork(
sql`jsonb_typeof(${agentWakeupRequests.payload}#>'{_paperclipWakeContext,wakeCommentIds}') = 'array'
and ${agentWakeupRequests.payload}#>'{_paperclipWakeContext,wakeCommentIds}' <> '[]'::jsonb`,
sql`${agentWakeupRequests.payload}->>'mutation' = 'interaction'`,
sql`${agentWakeupRequests.payload}->>'mutation' = 'annotation_reaction'`,
dependencyResolvedWakePayloadSql,
assignmentWakePayloadSql,
sql`exists (select 1 from heartbeat_runs r where r.company_id = ${agentWakeupRequests.companyId}
+39 -5
View File
@@ -2166,6 +2166,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
sql`${agentWakeupRequests.payload}->'executionWait'->>'trigger' in ('pause_lifted', 'reconciler_backstop')`,
sql`${agentWakeupRequests.payload}->'executionWait'->>'reason' in ('company.inactive', 'agent.not_invokable', 'wake_lost')`,
eq(agentWakeupRequests.requestedByActorType, "user"),
sql`(${issues.conversationAgentId} is null or ${issues.conversationUserId} = ${agentWakeupRequests.requestedByActorId} or coalesce(${agentWakeupRequests.payload}->>'mutation', '') <> 'annotation_reaction')`,
sql`coalesce(${agentWakeupRequests.idempotencyKey}, '') not like 'chat-inbound:%'`,
sql`exists (select 1 from agents pause_agent where pause_agent.id = ${agentWakeupRequests.agentId}
and pause_agent.status not in ('paused', 'terminated', 'pending_approval'))`,
@@ -2212,6 +2213,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
reason: wake.reason ?? undefined, payload, contextSnapshot: context,
requestedByActorType: wake.requestedByActorType as WakeupOptions["requestedByActorType"],
requestedByActorId: wake.requestedByActorId ?? undefined,
...(payload.mutation === "annotation_reaction" ? { allowRunCoalescing: false } : {}),
}, wake.id, wake.payload?.interactionOrigin).catch(err => {
if (err instanceof PersistedExecutionWaitRefusal) return;
scope.onError?.(err);
@@ -2258,6 +2260,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
sql`jsonb_typeof(${agentWakeupRequests.payload} #> '{_paperclipWakeContext,wakeCommentIds}') = 'array'`,
sql`${agentWakeupRequests.payload} #> '{_paperclipWakeContext,wakeCommentIds}' <> '[]'::jsonb`,
), sql`${agentWakeupRequests.payload}->>'mutation' = 'interaction'`,
sql`${agentWakeupRequests.payload}->>'mutation' = 'annotation_reaction'`,
dependencyResolvedWakePayloadSql, assignmentWakePayloadSql),
sql`${agentWakeupRequests.payload}->'queuedCommentInterrupt' is null`,
scope.requestId ? undefined : sql`coalesce((${agentWakeupRequests.payload} #>> ${`{${DEFERRED_CHAT_WAKE_RETRY_KEY},nextAttemptAt}`})::timestamptz <= now(), true)`,
@@ -2270,7 +2273,8 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
.orderBy(asc(agentWakeupRequests.updatedAt)).limit(50);
const releasedNativeSources = new Set<string>();
for (const { wake } of strandedQueues) {
const ownerWake = isDependencyResolvedWakePayload(wake.payload) || isAssignmentWakePayload(wake.payload);
const ownerWake = isDependencyResolvedWakePayload(wake.payload) || isAssignmentWakePayload(wake.payload)
|| wake.payload?.mutation === "annotation_reaction";
if (!ownerWake && !queuedCommentIdsFromWakePayload(wake.payload).length &&
!await readQueuedInteractionResponse(db, wake.companyId, String(wake.payload?.issueId), wake.payload)) continue;
const [latest] = await db.select({
@@ -2767,7 +2771,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
// Until its wake and run commit, this admission exists only in this process.
const unsaved = {};
unsavedWakeAdmissions.add(unsaved);
const promise = enqueueWakeup(agentId, opts, undefined, undefined, { saved: () => { unsavedWakeAdmissions.delete(unsaved); } });
const promise = enqueueWakeup(agentId, opts, opts.executionWaitRequestId, undefined, { saved: () => { unsavedWakeAdmissions.delete(unsaved); } });
activeWakeupPromises.add(promise);
void promise
.catch(() => {})
@@ -2823,12 +2827,23 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
&& readNonEmptyString(payload.requestId) !== null
&& readContextCompactionRequest(enrichedContextSnapshot)?.requestId === payload.requestId,
);
const isHumanAnnotationQuestionWake = () => Boolean(
reason === "issue_commented"
&& opts.requestedByActorType === "user"
&& Boolean(opts.requestedByActorId)
&& opts.allowRunCoalescing === false
&& readNonEmptyString(enrichedContextSnapshot.annotationCommentId) !== null
&& readNonEmptyString(enrichedContextSnapshot.annotationReaction) === "question"
&& readNonEmptyString(enrichedContextSnapshot.annotationReactionUserId) === opts.requestedByActorId
&& readNonEmptyString(enrichedContextSnapshot.source) === "issue.document_annotation_reaction",
);
const hasIndependentConversationWakeCause = () => Boolean(
wakeCommentId || opts.taskRetryRequestId ||
(reason === "onboarding_chat_greeting" && opts.manualUserWake === true
&& opts.requestedByActorType === "user" && source === "on_demand") ||
hasInteractionContinuationWakeContext(enrichedContextSnapshot) ||
reason === CHAT_COMPLETION_WAKE_REASON || isManualContextCompactionWake(),
reason === CHAT_COMPLETION_WAKE_REASON || isManualContextCompactionWake() ||
isHumanAnnotationQuestionWake(),
);
// Keep each request's own server-derived origin, including coalesced wakes.
// A run's merged context cannot establish which caller authored one receipt.
@@ -2890,6 +2905,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
manualUserWake: opts.manualUserWake,
taskRetryActorId,
hasIndependentConversationWakeCause: hasIndependentConversationWakeCause(),
annotationQuestionReaction: isHumanAnnotationQuestionWake(),
});
if (preflight.kind === "skipped") return null;
if (preflight.onboardingCompletion) enrichedContextSnapshot.onboardingCompletion = true;
@@ -3573,7 +3589,10 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
));
// The issue lock serializes cleanup callbacks and periodic workers.
// An adopted, discarded, or edited receipt is no longer authority.
if (!pending || (!opts.taskRetryRequestId && !(wakeCommentId && queuedCommentIdsFromWakePayload(pending.payload).includes(wakeCommentId)) &&
const isAnnotationQuestionReceipt = isHumanAnnotationQuestionWake()
&& pending?.payload?.mutation === "annotation_reaction"
&& readNonEmptyString(pending.payload.annotationCommentId) === readNonEmptyString(enrichedContextSnapshot.annotationCommentId);
if (!pending || (!opts.taskRetryRequestId && !isAnnotationQuestionReceipt && !(wakeCommentId && queuedCommentIdsFromWakePayload(pending.payload).includes(wakeCommentId)) &&
!(opts.queuedCommentInterruptId && await readQueuedInteractionResponse(tx as unknown as Db,
agent.companyId, issueId, pending.payload)))) {
return { kind: "deferred" as const };
@@ -3833,7 +3852,10 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
// Completion can settle the conversation while admission is outside
// the issue lock. Recheck the current state before persisting a wake.
if (isWaitingConversation(issue) && !hasIndependentConversationWakeCause()) {
if (
(isHumanAnnotationQuestionWake() && isConversation(issue) && issue.conversationUserId !== opts.requestedByActorId) ||
(isWaitingConversation(issue) && !hasIndependentConversationWakeCause())
) {
return { kind: "skipped" as const };
}
@@ -4916,6 +4938,18 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
return { kind: "coalesced" as const, run: activeExecutionRun };
}
if (executionWaitRequestId && isHumanAnnotationQuestionWake()) {
await tx.update(agentWakeupRequests).set({
payload: sql`coalesce(${agentWakeupRequests.payload}, '{}'::jsonb) - 'executionWait'`,
updatedAt: new Date(),
}).where(and(
eq(agentWakeupRequests.id, executionWaitRequestId),
eq(agentWakeupRequests.companyId, agent.companyId),
eq(agentWakeupRequests.status, "deferred_issue_execution"),
));
return { kind: "deferred" as const };
}
const admission = await busyRecovery.admitBusy({
companyId: agent.companyId,
issueId: issue.id,
@@ -845,6 +845,8 @@ export interface WakeupOptions {
};
/** Keep causally distinct external chat continuations out of an existing run. */
allowRunCoalescing?: boolean;
/** Durable deferred wake request already saved with the triggering domain write. */
executionWaitRequestId?: string;
}
function sanitizeAgentSessionMessageText(value: unknown): string | null {
@@ -2316,6 +2318,15 @@ export async function buildPaperclipWakePayload(input: {
const annotationCommentId = readNonEmptyString(
input.contextSnapshot.annotationCommentId,
);
const annotationReaction = readNonEmptyString(
input.contextSnapshot.annotationReaction,
);
const annotationReactionUserId = readNonEmptyString(
input.contextSnapshot.annotationReactionUserId,
);
const annotationReactionAuthor = annotationReactionUserId
? { type: "user", id: annotationReactionUserId }
: null;
const issueId = readNonEmptyString(input.contextSnapshot.issueId);
const conversationMode = input.contextSnapshot.conversationMode === true;
const continuationSummary = conversationMode ? null : input.continuationSummary ?? null;
@@ -2573,6 +2584,9 @@ export async function buildPaperclipWakePayload(input: {
: row.authorUserId
? { type: "user", id: row.authorUserId }
: { type: row.authorType, id: null },
reaction: annotationReaction
? { name: annotationReaction, author: annotationReactionAuthor }
: null,
})),
)
: [];
@@ -23,6 +23,8 @@ const ISSUE_USER_PARTICIPATION_ACTIVITY_ACTIONS = [
"issue.child_created",
"issue.comment_cancelled",
"issue.document_annotation_comment_added",
"issue.document_annotation_comment_reaction_added",
"issue.document_annotation_comment_reaction_removed",
"issue.document_annotation_remapped",
"issue.document_annotation_thread_created",
"issue.document_annotation_thread_resolved",