Files
PaperClipAI/ui/src/hooks/useDocumentAnnotationMutations.test.tsx
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

468 lines
20 KiB
TypeScript

// @vitest-environment jsdom
import { act } from "react";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";
import { describe, expect, it, vi } from "vitest";
import type { DocumentAnnotationThreadWithComments } from "@paperclipai/shared";
import { ThreadCard } from "@/components/DocumentAnnotationPanel";
import { ThemeProvider } from "@/context/ThemeContext";
import { applyOptimisticReaction, useDocumentAnnotationMutations } from "./useDocumentAnnotationMutations";
const setReaction = vi.hoisted(() => vi.fn());
vi.mock("@/api/document-annotations", () => ({ documentAnnotationsApi: { setReactionForTarget: setReaction } }));
vi.mock("@/api/auth", () => ({ authApi: { getSession: vi.fn(() => new Promise(() => {})) } }));
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
describe("applyOptimisticReaction", () => {
it("adds my reaction in the fixed reaction order", () => {
const next = applyOptimisticReaction(
[{ reaction: "question", count: 1, reactedByMe: false, actors: [{ actorType: "agent", agentId: "agent-1", userId: null }] }],
"done",
true,
"user-1",
);
expect(next.map((entry) => [entry.reaction, entry.count, entry.reactedByMe])).toEqual([
["done", 1, true],
["question", 1, false],
]);
});
it("removes my reaction and drops an empty summary", () => {
const next = applyOptimisticReaction(
[{ reaction: "thumbs_up", count: 1, reactedByMe: true, actors: [{ actorType: "user", agentId: null, userId: "user-1" }] }],
"thumbs_up",
false,
"user-1",
);
expect(next).toEqual([]);
});
it("leaves the list unchanged when the toggle repeats my current state", () => {
const current = [{ reaction: "check" as const, count: 1, reactedByMe: true, actors: [] }];
expect(applyOptimisticReaction(current, "check", true, "user-1")).toBe(current);
});
});
describe("toggleReaction", () => {
it("sends a remove only after the add for the same reaction finishes", async () => {
let finishAdd!: () => void;
setReaction
.mockReset()
.mockImplementationOnce(() => new Promise((resolve) => { finishAdd = () => resolve({ id: "comment-1", reactions: [] }); }))
.mockResolvedValueOnce({ id: "comment-1", reactions: [] });
const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });
let toggle!: ReturnType<typeof useDocumentAnnotationMutations>["toggleReaction"];
function Harness() {
toggle = useDocumentAnnotationMutations({
target: { kind: "issue", issueId: "issue-1", documentKey: "plan" },
baseRevisionId: "rev-1",
baseRevisionNumber: 1,
pendingAnchor: null,
onFocusThread: () => undefined,
}).toggleReaction;
return null;
}
const host = document.createElement("div");
const root = createRoot(host);
await act(async () => root.render(<QueryClientProvider client={client}><Harness /></QueryClientProvider>));
await act(async () => {
toggle.mutate({ threadId: "thread-1", commentId: "comment-1", reaction: "done", present: true });
toggle.mutate({ threadId: "thread-1", commentId: "comment-1", reaction: "done", present: false });
});
await vi.waitFor(() => expect(setReaction).toHaveBeenCalledTimes(1));
expect(setReaction).toHaveBeenLastCalledWith(expect.anything(), "thread-1", "comment-1", "done", true);
await act(async () => finishAdd());
await vi.waitFor(() => expect(setReaction).toHaveBeenCalledTimes(2));
expect(setReaction).toHaveBeenLastCalledWith(expect.anything(), "thread-1", "comment-1", "done", false);
await act(async () => root.unmount());
client.clear();
});
it("keeps a pending reaction when another reaction on the same comment finishes first", async () => {
let finishDone!: () => void;
let finishQuestion!: () => void;
const doneSummary = { reaction: "done" as const, count: 1, reactedByMe: true, actors: [{ actorType: "user" as const, agentId: null, userId: null }] };
const questionSummary = { reaction: "question" as const, count: 1, reactedByMe: true, actors: [{ actorType: "user" as const, agentId: null, userId: null }] };
setReaction
.mockReset()
.mockImplementationOnce(() => new Promise((resolve) => { finishDone = () => resolve({ id: "comment-1", reactions: [doneSummary] }); }))
.mockImplementationOnce(() => new Promise((resolve) => { finishQuestion = () => resolve({ id: "comment-1", reactions: [doneSummary, questionSummary] }); }));
const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });
const queryKey = ["issues", "document-annotations", "issue-1", "plan", "all"];
client.setQueryData(queryKey, [{ id: "thread-1", comments: [{ id: "comment-1", reactions: [] }] }]);
const invalidate = vi.spyOn(client, "invalidateQueries");
let toggle!: ReturnType<typeof useDocumentAnnotationMutations>["toggleReaction"];
function Harness() {
toggle = useDocumentAnnotationMutations({
target: { kind: "issue", issueId: "issue-1", documentKey: "plan" },
baseRevisionId: "rev-1",
baseRevisionNumber: 1,
pendingAnchor: null,
onFocusThread: () => undefined,
}).toggleReaction;
return null;
}
const reactionsInCache = () => (client.getQueryData(queryKey) as Array<{ comments: Array<{ reactions: Array<{ reaction: string; reactedByMe: boolean }> }> }>)[0].comments[0].reactions
.map((entry) => [entry.reaction, entry.reactedByMe]);
const host = document.createElement("div");
const root = createRoot(host);
await act(async () => root.render(<QueryClientProvider client={client}><Harness /></QueryClientProvider>));
await act(async () => {
toggle.mutate({ threadId: "thread-1", commentId: "comment-1", reaction: "done", present: true });
toggle.mutate({ threadId: "thread-1", commentId: "comment-1", reaction: "question", present: true });
});
await vi.waitFor(() => expect(setReaction).toHaveBeenCalledTimes(2));
invalidate.mockClear();
await act(async () => finishDone());
expect(reactionsInCache()).toEqual([["done", true], ["question", true]]);
expect(invalidate).not.toHaveBeenCalled();
await act(async () => finishQuestion());
await vi.waitFor(() => expect(invalidate).toHaveBeenCalled());
expect(reactionsInCache()).toEqual([["done", true], ["question", true]]);
await act(async () => root.unmount());
client.clear();
});
it("preserves a queued reaction removal when a live-update refetch returns the earlier add", async () => {
let finishAdd!: () => void;
let finishRemove!: () => void;
const doneSummary = { reaction: "done" as const, count: 1, reactedByMe: true, actors: [{ actorType: "user" as const, agentId: null, userId: null }] };
setReaction
.mockReset()
.mockImplementationOnce(() => new Promise((resolve) => { finishAdd = () => resolve({ id: "comment-1", reactions: [doneSummary] }); }))
.mockImplementationOnce(() => new Promise((resolve) => { finishRemove = () => resolve({ id: "comment-1", reactions: [] }); }));
const queryKey = ["issues", "document-annotations", "issue-1", "plan", "all"];
let serverReactions: Array<typeof doneSummary> = [];
const fetchAnnotations = vi.fn(async () => [{ id: "thread-1", comments: [{ id: "comment-1", reactions: serverReactions }] }]);
const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
let toggle!: ReturnType<typeof useDocumentAnnotationMutations>["toggleReaction"];
function Harness() {
useQuery({ queryKey, queryFn: fetchAnnotations });
toggle = useDocumentAnnotationMutations({
target: { kind: "issue", issueId: "issue-1", documentKey: "plan" },
baseRevisionId: "rev-1",
baseRevisionNumber: 1,
pendingAnchor: null,
onFocusThread: () => undefined,
}).toggleReaction;
return null;
}
const reactionsInCache = () =>
(client.getQueryData(queryKey) as Array<{ comments: Array<{ reactions: Array<{ reaction: string; reactedByMe: boolean }> }> }>)[0]!
.comments[0]!.reactions.map((entry) => [entry.reaction, entry.reactedByMe]);
const host = document.createElement("div");
const root = createRoot(host);
await act(async () => root.render(<QueryClientProvider client={client}><Harness /></QueryClientProvider>));
await vi.waitFor(() => expect(fetchAnnotations).toHaveBeenCalledTimes(1));
await act(async () => {
toggle.mutate({ threadId: "thread-1", commentId: "comment-1", reaction: "done", present: true });
toggle.mutate({ threadId: "thread-1", commentId: "comment-1", reaction: "done", present: false });
});
await vi.waitFor(() => expect(setReaction).toHaveBeenCalledTimes(1));
expect(reactionsInCache()).toEqual([]);
// Simulate LiveUpdatesProvider invalidating the annotation query right after
// the server commits the add, while the queued removal has not run yet.
serverReactions = [doneSummary];
await act(async () => {
await client.invalidateQueries({ queryKey });
});
await vi.waitFor(() => expect(fetchAnnotations).toHaveBeenCalledTimes(2));
expect(reactionsInCache()).toEqual([]);
await act(async () => finishAdd());
await vi.waitFor(() => expect(setReaction).toHaveBeenCalledTimes(2));
expect(reactionsInCache()).toEqual([]);
serverReactions = [];
await act(async () => finishRemove());
await vi.waitFor(() => expect(fetchAnnotations).toHaveBeenCalledTimes(3));
expect(reactionsInCache()).toEqual([]);
await act(async () => root.unmount());
client.clear();
});
it("defers invalidation while a reaction write on another comment is still pending", async () => {
let finishFirst!: () => void;
let finishSecond!: () => void;
const doneSummary = { reaction: "done" as const, count: 1, reactedByMe: true, actors: [{ actorType: "user" as const, agentId: null, userId: null }] };
const questionSummary = { reaction: "question" as const, count: 1, reactedByMe: true, actors: [{ actorType: "user" as const, agentId: null, userId: null }] };
setReaction
.mockReset()
.mockImplementationOnce(() => new Promise((resolve) => { finishFirst = () => resolve({ id: "comment-1", reactions: [doneSummary] }); }))
.mockImplementationOnce(() => new Promise((resolve) => { finishSecond = () => resolve({ id: "comment-2", reactions: [questionSummary] }); }));
const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });
const queryKey = ["issues", "document-annotations", "issue-1", "plan", "all"];
client.setQueryData(queryKey, [{
id: "thread-1",
comments: [
{ id: "comment-1", reactions: [] },
{ id: "comment-2", reactions: [] },
],
}]);
const invalidate = vi.spyOn(client, "invalidateQueries");
let toggle!: ReturnType<typeof useDocumentAnnotationMutations>["toggleReaction"];
function Harness() {
toggle = useDocumentAnnotationMutations({
target: { kind: "issue", issueId: "issue-1", documentKey: "plan" },
baseRevisionId: "rev-1",
baseRevisionNumber: 1,
pendingAnchor: null,
onFocusThread: () => undefined,
}).toggleReaction;
return null;
}
const commentReactions = (idx: number) =>
(client.getQueryData(queryKey) as Array<{ comments: Array<{ reactions: Array<{ reaction: string; reactedByMe: boolean }> }> }>)[0]!
.comments[idx]!.reactions.map((entry) => [entry.reaction, entry.reactedByMe]);
const host = document.createElement("div");
const root = createRoot(host);
await act(async () => root.render(<QueryClientProvider client={client}><Harness /></QueryClientProvider>));
await act(async () => {
toggle.mutate({ threadId: "thread-1", commentId: "comment-1", reaction: "done", present: true });
toggle.mutate({ threadId: "thread-1", commentId: "comment-2", reaction: "question", present: true });
});
await vi.waitFor(() => expect(setReaction).toHaveBeenCalledTimes(2));
invalidate.mockClear();
await act(async () => finishFirst());
expect(invalidate).not.toHaveBeenCalled();
expect(commentReactions(0)).toEqual([["done", true]]);
expect(commentReactions(1)).toEqual([["question", true]]);
await act(async () => finishSecond());
await vi.waitFor(() => expect(invalidate).toHaveBeenCalled());
expect(commentReactions(0)).toEqual([["done", true]]);
expect(commentReactions(1)).toEqual([["question", true]]);
await act(async () => root.unmount());
client.clear();
});
it("serializes reaction writes and preserves latest choice across panel remounts", async () => {
let finishAdd!: () => void;
let finishRemove!: () => void;
const doneSummary = { reaction: "done" as const, count: 1, reactedByMe: true, actors: [{ actorType: "user" as const, agentId: null, userId: null }] };
setReaction
.mockReset()
.mockImplementationOnce(() => new Promise((resolve) => { finishAdd = () => resolve({ id: "comment-1", reactions: [doneSummary] }); }))
.mockImplementationOnce(() => new Promise((resolve) => { finishRemove = () => resolve({ id: "comment-1", reactions: [] }); }));
const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });
const queryKey = ["issues", "document-annotations", "issue-1", "plan", "all"];
client.setQueryData(queryKey, [{ id: "thread-1", comments: [{ id: "comment-1", reactions: [] }] }]);
const invalidate = vi.spyOn(client, "invalidateQueries");
let toggle!: ReturnType<typeof useDocumentAnnotationMutations>["toggleReaction"];
function Harness() {
toggle = useDocumentAnnotationMutations({
target: { kind: "issue", issueId: "issue-1", documentKey: "plan" },
baseRevisionId: "rev-1",
baseRevisionNumber: 1,
pendingAnchor: null,
onFocusThread: () => undefined,
}).toggleReaction;
return null;
}
const reactionsInCache = () =>
(client.getQueryData(queryKey) as Array<{ comments: Array<{ reactions: Array<{ reaction: string; reactedByMe: boolean }> }> }>)[0]!
.comments[0]!.reactions.map((entry) => [entry.reaction, entry.reactedByMe]);
const host = document.createElement("div");
const root = createRoot(host);
await act(async () => root.render(<QueryClientProvider client={client}><Harness key="open-1" /></QueryClientProvider>));
await act(async () => {
toggle.mutate({ threadId: "thread-1", commentId: "comment-1", reaction: "done", present: true });
});
await vi.waitFor(() => expect(setReaction).toHaveBeenCalledTimes(1));
expect(reactionsInCache()).toEqual([["done", true]]);
// Close and reopen the panel while the add request is still in flight.
await act(async () => root.render(<QueryClientProvider client={client}><Harness key="open-2" /></QueryClientProvider>));
await act(async () => {
toggle.mutate({ threadId: "thread-1", commentId: "comment-1", reaction: "done", present: false });
});
// The DELETE must wait behind the in-flight PUT rather than racing ahead of it.
expect(setReaction).toHaveBeenCalledTimes(1);
expect(reactionsInCache()).toEqual([]);
invalidate.mockClear();
await act(async () => finishAdd());
await vi.waitFor(() => expect(setReaction).toHaveBeenCalledTimes(2));
expect(setReaction).toHaveBeenNthCalledWith(
2,
{ kind: "issue", issueId: "issue-1", documentKey: "plan" },
"thread-1",
"comment-1",
"done",
false,
);
expect(reactionsInCache()).toEqual([]);
expect(invalidate).not.toHaveBeenCalled();
await act(async () => finishRemove());
await vi.waitFor(() => expect(invalidate).toHaveBeenCalled());
expect(reactionsInCache()).toEqual([]);
await act(async () => root.unmount());
client.clear();
});
});
describe("ThreadCard comment reactions", () => {
it("renders four one-tap reactions with counts, hover names, and toggle handlers while hiding optimistic comments", async () => {
const onToggleReaction = vi.fn();
const onFocus = vi.fn();
const thread: DocumentAnnotationThreadWithComments = {
id: "thread-1",
companyId: "company-1",
documentId: "doc-1",
issueId: "issue-1",
routineId: null,
caseId: null,
documentKey: "plan",
status: "open",
anchorState: "active",
anchorConfidence: "exact",
originalRevisionId: "rev-1",
originalRevisionNumber: 1,
currentRevisionId: "rev-1",
currentRevisionNumber: 1,
selectedText: "Ship it",
prefixText: "",
suffixText: "",
normalizedStart: 0,
normalizedEnd: 7,
markdownStart: 0,
markdownEnd: 7,
anchorSelector: {
quote: { exact: "Ship it", prefix: "", suffix: "" },
position: { normalizedStart: 0, normalizedEnd: 7, markdownStart: 0, markdownEnd: 7 },
},
resolvedAt: null,
resolvedByAgentId: null,
resolvedByUserId: null,
createdByAgentId: null,
createdByUserId: "user-1",
createdAt: new Date("2026-05-12T10:00:00Z"),
updatedAt: new Date("2026-05-12T10:01:00Z"),
comments: [
{
id: "comment-1",
companyId: "company-1",
threadId: "thread-1",
issueId: "issue-1",
documentId: "doc-1",
body: "Ready for review.",
authorType: "agent",
authorAgentId: "agent-1",
authorUserId: null,
createdByRunId: "run-1",
reactions: [
{
reaction: "done",
count: 2,
reactedByMe: true,
actors: [
{ actorType: "user", agentId: null, userId: "user-1" },
{ actorType: "agent", agentId: "agent-1", userId: null },
],
},
],
createdAt: new Date("2026-05-12T10:00:00Z"),
updatedAt: new Date("2026-05-12T10:00:00Z"),
},
{
id: "optimistic-comment-2",
companyId: "company-1",
threadId: "thread-1",
issueId: "issue-1",
documentId: "doc-1",
body: "Sending...",
authorType: "user",
authorAgentId: null,
authorUserId: "user-1",
createdByRunId: null,
reactions: [],
createdAt: new Date("2026-05-12T10:01:00Z"),
updatedAt: new Date("2026-05-12T10:01:00Z"),
},
],
};
const host = document.createElement("div");
const root = createRoot(host);
await act(async () => {
root.render(
<ThemeProvider>
<ul>
<ThreadCard
thread={thread}
expanded
focusedCommentId={null}
onFocus={onFocus}
replyDraft=""
onReplyChange={() => undefined}
onSubmitReply={() => undefined}
onResolveToggle={() => undefined}
onCopyLink={() => undefined}
pendingReply={false}
pendingStatus={false}
onToggleReaction={onToggleReaction}
agentMap={new Map([["agent-1", { id: "agent-1", name: "Engineering" }]])}
/>
</ul>
</ThemeProvider>,
);
});
const group = host.querySelector('[data-testid="document-annotation-reactions-comment-1"]') as HTMLElement;
expect(group).not.toBeNull();
expect(host.querySelector('[data-testid="document-annotation-reactions-optimistic-comment-2"]')).toBeNull();
const buttons = Array.from(group.querySelectorAll("button"));
expect(buttons.map((button) => button.dataset.reaction)).toEqual(["done", "check", "thumbs_up", "question"]);
const done = buttons[0]!;
expect(done.getAttribute("aria-pressed")).toBe("true");
expect(done.textContent).toBe("✅2");
expect(done.title).toBe("Done: user-1, Engineering");
const question = buttons[3]!;
expect(question.getAttribute("aria-pressed")).toBe("false");
expect(question.textContent).toBe("❓");
await act(async () => {
question.click();
done.click();
});
expect(onToggleReaction).toHaveBeenNthCalledWith(1, "comment-1", "question", true);
expect(onToggleReaction).toHaveBeenNthCalledWith(2, "comment-1", "done", false);
expect(onFocus).not.toHaveBeenCalled();
await act(async () => root.unmount());
});
});