Files
PaperClipAI/server/src/__tests__/document-annotation-routes.test.ts
T
87fadcb108 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>
2026-11-25 15:33:38 -06:00

584 lines
22 KiB
TypeScript

import express from "express";
import request from "supertest";
import { beforeEach, describe, expect, it, vi } from "vitest";
const issueId = "11111111-1111-4111-8111-111111111111";
const companyId = "22222222-2222-4222-8222-222222222222";
const otherCompanyId = "33333333-3333-4333-8333-333333333333";
const mockIssueService = vi.hoisted(() => ({
getById: vi.fn(),
assertCheckoutOwner: vi.fn(),
listReviewAttention: vi.fn(),
}));
const mockDocumentService = vi.hoisted(() => ({
getIssueDocumentByKey: vi.fn(),
upsertIssueDocument: vi.fn(),
}));
const mockAnnotationService = vi.hoisted(() => ({
listThreadsForIssueDocument: vi.fn(),
getThreadForIssueDocument: vi.fn(),
createThread: vi.fn(),
addComment: vi.fn(),
updateThread: vi.fn(),
setCommentReaction: vi.fn(),
remapOpenThreadsForDocument: vi.fn(),
}));
const mockIssueReferenceService = vi.hoisted(() => ({
diffIssueReferenceSummary: vi.fn(() => ({
addedReferencedIssues: [],
removedReferencedIssues: [],
currentReferencedIssues: [],
})),
emptySummary: vi.fn(() => ({ outbound: [], inbound: [] })),
listIssueReferenceSummary: vi.fn(async () => ({ outbound: [], inbound: [] })),
syncAnnotationComment: vi.fn(async () => undefined),
syncComment: vi.fn(async () => undefined),
syncDocument: vi.fn(async () => undefined),
syncIssue: vi.fn(async () => undefined),
}));
const mockHeartbeatService = vi.hoisted(() => ({
wakeup: vi.fn(async (): Promise<{ id: string } | undefined> => undefined),
reportRunActivity: vi.fn(async () => undefined),
}));
const mockIssueThreadInteractionService = vi.hoisted(() => ({
expireRequestConfirmationsSupersededByComment: vi.fn(async () => []),
expireStaleRequestConfirmationsForIssueDocument: vi.fn(async (): Promise<Array<{ id: string; kind: string; status: string }>> => []),
}));
const mockLogActivity = vi.hoisted(() => vi.fn(async () => undefined));
const documentPayload = {
id: "document-1",
companyId,
issueId,
key: "plan",
title: "Plan",
format: "markdown",
body: "Alpha selected text omega",
latestRevisionId: "44444444-4444-4444-8444-444444444444",
latestRevisionNumber: 1,
createdByAgentId: null,
createdByUserId: "board-user",
updatedByAgentId: null,
updatedByUserId: "board-user",
createdAt: new Date("2026-05-14T12:00:00.000Z"),
updatedAt: new Date("2026-05-14T12:00:00.000Z"),
};
const annotationThread = {
id: "55555555-5555-4555-8555-555555555555",
companyId,
issueId,
documentId: "document-1",
documentKey: "plan",
status: "open",
anchorState: "active",
anchorConfidence: "exact",
originalRevisionId: documentPayload.latestRevisionId,
originalRevisionNumber: 1,
currentRevisionId: documentPayload.latestRevisionId,
currentRevisionNumber: 1,
selectedText: "selected text",
prefixText: "Alpha ",
suffixText: " omega",
normalizedStart: 6,
normalizedEnd: 19,
markdownStart: 6,
markdownEnd: 19,
anchorSelector: {
quote: { exact: "selected text", prefix: "Alpha ", suffix: " omega" },
position: { normalizedStart: 6, normalizedEnd: 19, markdownStart: 6, markdownEnd: 19 },
},
createdByAgentId: null,
createdByUserId: "board-user",
resolvedByAgentId: null,
resolvedByUserId: null,
resolvedAt: null,
createdAt: new Date("2026-05-14T12:01:00.000Z"),
updatedAt: new Date("2026-05-14T12:01:00.000Z"),
};
const annotationComment = {
id: "66666666-6666-4666-8666-666666666666",
companyId,
threadId: annotationThread.id,
issueId,
documentId: "document-1",
body: "Please review PAP-1",
authorType: "user",
authorAgentId: null,
authorUserId: "board-user",
createdByRunId: null,
createdAt: new Date("2026-05-14T12:01:00.000Z"),
updatedAt: new Date("2026-05-14T12:01:00.000Z"),
};
function registerModuleMocks() {
vi.doMock("../services/index.js", () => ({
accessService: () => ({
canUser: vi.fn(),
decide: vi.fn(async (input: { action?: string }) => ({
allowed: true,
action: input.action,
reason: "allow_test",
explanation: "Allowed by test mock.",
})),
hasPermission: vi.fn(async () => false),
}),
agentService: () => ({ getById: vi.fn(), list: vi.fn(async () => []) }),
companySkillService: () => ({
completeTestRunForIssue: vi.fn(async () => null),
}),
companyService: () => ({ getById: vi.fn(async () => ({ id: companyId })) }),
documentAnnotationService: () => mockAnnotationService,
documentService: () => mockDocumentService,
environmentService: () => ({}),
executionWorkspaceService: () => ({}),
feedbackService: () => ({}),
goalService: () => ({}),
heartbeatService: () => mockHeartbeatService,
instanceSettingsService: () => ({
get: vi.fn(async () => ({ id: "settings", general: {} })),
getExperimental: vi.fn(async () => ({})),
getGeneral: vi.fn(async () => ({})),
listCompanyIds: vi.fn(async () => [companyId]),
}),
issueApprovalService: () => ({}),
issueRecoveryActionService: () => ({
getActiveForIssue: vi.fn(async () => null),
listActiveForIssues: vi.fn(async () => new Map()),
}),
issueReferenceService: () => mockIssueReferenceService,
issueService: () => mockIssueService,
issueThreadInteractionService: () => mockIssueThreadInteractionService,
logActivity: mockLogActivity,
projectService: () => ({}),
routineService: () => ({ syncRunStatusForIssue: vi.fn(async () => undefined) }),
workProductService: () => ({}),
}));
}
async function createApp(actor: "board" | "agent" = "board", actorCompanyId = companyId) {
const [{ issueRoutes }, { errorHandler }] = await Promise.all([
vi.importActual<typeof import("../routes/issues.js")>("../routes/issues.js"),
vi.importActual<typeof import("../middleware/index.js")>("../middleware/index.js"),
]);
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
(req as any).actor = actor === "agent"
? {
type: "agent",
agentId: "77777777-7777-4777-8777-777777777777",
companyId: actorCompanyId,
runId: "88888888-8888-4888-8888-888888888888",
}
: {
type: "board",
userId: "board-user",
companyIds: [actorCompanyId],
source: "local_implicit",
isInstanceAdmin: false,
};
next();
});
app.use("/api", issueRoutes({} as any, {} as any));
app.use(errorHandler);
return app;
}
describe("document annotation routes", () => {
beforeEach(async () => {
vi.resetModules();
vi.doUnmock("../routes/issues.js");
vi.doUnmock("../middleware/index.js");
registerModuleMocks();
vi.clearAllMocks();
mockIssueService.getById.mockResolvedValue({
id: issueId,
companyId,
title: "Annotation API",
status: "in_progress",
assigneeAgentId: null,
});
mockIssueService.assertCheckoutOwner.mockResolvedValue({});
mockIssueService.listReviewAttention.mockResolvedValue(new Map());
mockDocumentService.getIssueDocumentByKey.mockResolvedValue(documentPayload);
mockDocumentService.upsertIssueDocument.mockResolvedValue({
created: false,
document: {
...documentPayload,
body: "Alpha updated selected text omega",
latestRevisionId: "99999999-9999-4999-8999-999999999999",
latestRevisionNumber: 2,
},
});
mockAnnotationService.listThreadsForIssueDocument.mockImplementation(async (
_issueId: string,
_key: string,
options?: { includeComments?: boolean },
) => (
options?.includeComments
? [{ ...annotationThread, comments: [annotationComment] }]
: [annotationThread]
));
mockAnnotationService.getThreadForIssueDocument.mockResolvedValue({ ...annotationThread, comments: [annotationComment] });
mockAnnotationService.createThread.mockResolvedValue({ ...annotationThread, comments: [annotationComment] });
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"),
vi.importActual("../middleware/index.js"),
]);
});
it("includes compact open annotations without comment bodies by default for agent document reads", async () => {
const res = await request(await createApp("agent"))
.get(`/api/issues/${issueId}/documents/plan`)
.expect(200);
expect(res.body.annotations).toHaveLength(1);
expect(res.body.annotations[0].comments).toBeUndefined();
expect(mockAnnotationService.listThreadsForIssueDocument).toHaveBeenCalledWith(issueId, "plan", {
status: "open",
includeComments: false,
viewer: { actorType: "agent", actorId: "77777777-7777-4777-8777-777777777777" },
});
});
it("includes annotation comment bodies on document reads only when explicitly requested", async () => {
const res = await request(await createApp("agent"))
.get(`/api/issues/${issueId}/documents/plan?includeAnnotationComments=true`)
.expect(200);
expect(res.body.annotations[0].comments[0].body).toBe("Please review PAP-1");
expect(mockAnnotationService.listThreadsForIssueDocument).toHaveBeenCalledWith(issueId, "plan", {
status: "open",
includeComments: true,
viewer: { actorType: "agent", actorId: "77777777-7777-4777-8777-777777777777" },
});
});
it("updates issue documents without waking the assignee through the issue-comment path", async () => {
mockIssueService.getById.mockResolvedValue({
id: issueId,
companyId,
title: "Document API",
status: "in_progress",
assigneeAgentId: "99999999-9999-4999-8999-999999999999",
});
const res = await request(await createApp())
.put(`/api/issues/${issueId}/documents/plan`)
.send({
title: "Plan",
format: "markdown",
body: "Alpha updated selected text omega",
changeSummary: "Document feedback only",
baseRevisionId: documentPayload.latestRevisionId,
})
.expect(200);
expect(res.body.latestRevisionNumber).toBe(2);
expect(mockIssueReferenceService.syncDocument).toHaveBeenCalledWith(documentPayload.id);
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
action: "issue.document_updated",
}));
expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled();
});
it("queues one bounded recovery when a board document revision expires the final review interactions", async () => {
const assigneeAgentId = "99999999-9999-4999-8999-999999999999";
mockIssueService.getById.mockResolvedValue({
id: issueId,
companyId,
title: "Document API",
status: "in_review",
assigneeAgentId,
});
mockIssueThreadInteractionService.expireStaleRequestConfirmationsForIssueDocument.mockResolvedValueOnce([
{ id: "interaction-b", kind: "request_confirmation", status: "expired" },
{ id: "interaction-a", kind: "request_confirmation", status: "expired" },
]);
mockIssueService.listReviewAttention.mockResolvedValueOnce(new Map([[issueId, {
state: "stalled",
paths: [],
reason: "Final document-bound review paths expired",
}]]));
mockHeartbeatService.wakeup.mockResolvedValueOnce({ id: "recovery-run" });
await request(await createApp())
.put(`/api/issues/${issueId}/documents/plan`)
.send({
title: "Plan",
format: "markdown",
body: "Alpha updated selected text omega",
changeSummary: "Board revision",
baseRevisionId: documentPayload.latestRevisionId,
})
.expect(200);
expect(mockHeartbeatService.wakeup).toHaveBeenCalledTimes(1);
expect(mockHeartbeatService.wakeup).toHaveBeenCalledWith(assigneeAgentId, expect.objectContaining({
reason: "issue_review_path_lost",
idempotencyKey: expect.stringMatching(new RegExp(`^issue_review_path_lost:${issueId}:`)),
payload: expect.objectContaining({
issueId,
reviewPathConsumedRef: "interactions:interaction-a,interaction-b",
reviewPathRecoveryAttempt: 1,
maxReviewPathRecoveryAttempts: 1,
}),
contextSnapshot: expect.objectContaining({
source: "issue.document_updated",
wakeReason: "issue_review_path_lost",
}),
}));
});
it("creates annotation threads, syncs references, logs activity, and does not wake the assignee", async () => {
mockIssueService.getById.mockResolvedValue({
id: issueId,
companyId,
title: "Annotation API",
status: "todo",
assigneeAgentId: "99999999-9999-4999-8999-999999999999",
});
const res = await request(await createApp())
.post(`/api/issues/${issueId}/documents/plan/annotations`)
.send({
baseRevisionId: documentPayload.latestRevisionId,
baseRevisionNumber: 1,
selector: annotationThread.anchorSelector,
body: "Please review PAP-1",
})
.expect(201);
expect(res.body.id).toBe(annotationThread.id);
expect(mockIssueReferenceService.syncAnnotationComment).toHaveBeenCalledWith(annotationComment.id);
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
action: "issue.document_annotation_thread_created",
details: expect.objectContaining({
key: "plan",
documentKey: "plan",
}),
}));
expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled();
});
it("rejects agent cross-company annotation reads with a uniform 404", async () => {
await request(await createApp("agent", otherCompanyId))
.get(`/api/issues/${issueId}/documents/plan/annotations`)
.expect(404);
});
it("adds annotation comments without waking the assignee and resolves threads", async () => {
mockIssueService.getById.mockResolvedValue({
id: issueId,
companyId,
title: "Annotation API",
status: "todo",
assigneeAgentId: "99999999-9999-4999-8999-999999999999",
});
await request(await createApp())
.post(`/api/issues/${issueId}/documents/plan/annotations/${annotationThread.id}/comments`)
.send({ body: "Reply with PAP-2" })
.expect(201);
expect(mockIssueReferenceService.syncAnnotationComment).toHaveBeenCalledWith(annotationComment.id);
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
action: "issue.document_annotation_comment_added",
details: expect.objectContaining({
key: "plan",
documentKey: "plan",
}),
}));
expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled();
const resolved = await request(await createApp())
.patch(`/api/issues/${issueId}/documents/plan/annotations/${annotationThread.id}`)
.send({ status: "resolved" })
.expect(200);
expect(resolved.body.status).toBe("resolved");
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
action: "issue.document_annotation_thread_resolved",
details: expect.objectContaining({
key: "plan",
documentKey: "plan",
}),
}));
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();
});
});
});