diff --git a/docs/api/issues.md b/docs/api/issues.md index f34c1883ba7..bab03cc0776 100644 --- a/docs/api/issues.md +++ b/docs/api/issues.md @@ -458,6 +458,47 @@ DELETE /api/issues/{issueId}/documents/{key} Delete is board-only in the current implementation. +### Comment Reactions + +Each annotation comment on a document can carry four fixed reactions: `done`, `check`, `thumbs_up` and `question`. Each person or agent can add each reaction once per comment. + +``` +PUT /api/issues/{issueId}/documents/{key}/annotations/{threadId}/comments/{commentId}/reactions/{reaction} +DELETE /api/issues/{issueId}/documents/{key}/annotations/{threadId}/comments/{commentId}/reactions/{reaction} +``` + +Rules: + +- `PUT` adds the reaction and `DELETE` removes it. Both calls are safe to repeat. A repeated call changes nothing and logs no activity. +- An unknown reaction name returns `400`. A thread or comment that is not on this document returns `404`. +- The response is the comment with its `reactions` array. +- Annotation comments returned by the annotation list, thread read and document read (`includeAnnotationComments=true`) include the same `reactions` array. +- A `question` reaction that a person adds wakes the issue assignee once, in its own follow-up run, to answer in that annotation thread. It does not wake an agent on a `done` or `cancelled` issue, or on another person's agent chat. Only the first `question` from each person on a comment wakes the assignee (removing it and adding it again does not), at most one annotation question wake is queued per issue at a time, and each person is capped at 3 question wakes per issue per 10-minute window. `done`, `check` and `thumbs_up`, agent reactions and repeated calls start no agent work. +- Resolving a thread stays a separate action. A `done` reaction does not resolve the thread. + +Each entry in `reactions`: + +```json +{ + "reaction": "question", + "count": 2, + "reactedByMe": true, + "actors": [ + { "actorType": "user", "agentId": null, "userId": "user-1" }, + { "actorType": "agent", "agentId": "agent-1", "userId": null } + ] +} +``` + +`reactedByMe` is true when the caller added that reaction. Entries with a zero count are omitted, and entries come in the order `done`, `check`, `thumbs_up`, `question`. + +Routine descriptions and case documents use the same contract at these paths. These reactions do not wake an agent: + +``` +PUT|DELETE /api/routines/{routineId}/description/annotations/{threadId}/comments/{commentId}/reactions/{reaction} +PUT|DELETE /api/cases/{caseId}/documents/{key}/annotations/{threadId}/comments/{commentId}/reactions/{reaction} +``` + ## Attachments ### Upload diff --git a/docs/api/routines.md b/docs/api/routines.md index b31da462a1b..de5916a0899 100644 --- a/docs/api/routines.md +++ b/docs/api/routines.md @@ -103,6 +103,15 @@ GET /api/routines/{routineId}/revisions Returns append-only routine definition revisions newest first. Snapshots include routine fields and safe trigger metadata only; webhook secret values and `secretId` are never returned. +## Description Comment Reactions + +``` +PUT /api/routines/{routineId}/description/annotations/{threadId}/comments/{commentId}/reactions/{reaction} +DELETE /api/routines/{routineId}/description/annotations/{threadId}/comments/{commentId}/reactions/{reaction} +``` + +Adds or removes a `done`, `check`, `thumbs_up` or `question` reaction on a routine description annotation comment. See [Comment Reactions](issues.md#comment-reactions) for the response shape and rules. Routine reactions do not wake an agent. + ## Restore Revision ``` diff --git a/packages/adapter-utils/src/server-utils.test.ts b/packages/adapter-utils/src/server-utils.test.ts index 63078d6d5d9..5de6d580430 100644 --- a/packages/adapter-utils/src/server-utils.test.ts +++ b/packages/adapter-utils/src/server-utils.test.ts @@ -2663,6 +2663,32 @@ describe("renderPaperclipWakePrompt", () => { expect(prompt).not.toContain("Update the plan only"); }); + it("tells the agent to answer a question reaction in the annotation thread", () => { + const prompt = renderPaperclipWakePrompt({ + reason: "issue_commented", + issue: { id: "issue-1", identifier: "PAP-1", title: "Plan", status: "in_progress" }, + annotationDeltas: [ + { + id: "annotation-comment-1", + threadId: "thread-1", + documentKey: "plan", + quote: "Ship it", + body: "This step is ready.", + author: { type: "agent", id: "agent-1" }, + reaction: { name: "question", author: { type: "user", id: "user-1" } }, + }, + ], + commentWindow: { requestedCount: 0, includedCount: 0, missingCount: 0 }, + comments: [], + fallbackFetchNeeded: false, + }); + + expect(prompt).toContain("- annotation annotation-comment-1"); + expect(prompt).toContain( + "reacted with a question to this comment. Answer it with a reply in this annotation thread.", + ); + }); + it("renders accepted plan review context with annotation text and comments", () => { const payload = { reason: "issue_commented", diff --git a/packages/adapter-utils/src/server-utils.ts b/packages/adapter-utils/src/server-utils.ts index f600e5b1e6f..49d0e7d3cf8 100644 --- a/packages/adapter-utils/src/server-utils.ts +++ b/packages/adapter-utils/src/server-utils.ts @@ -588,6 +588,7 @@ type PaperclipWakeAnnotationDelta = { bodyTruncated: boolean; createdAt: string | null; author: PaperclipWakePlanReviewAuthor | null; + reaction: { name: string; author: PaperclipWakePlanReviewAuthor | null } | null; }; type PaperclipWakePlanReviewComment = { @@ -980,6 +981,11 @@ function normalizePaperclipWakeAnnotationDelta( const body = asString(delta.body, ""); const createdAt = asString(delta.createdAt, "").trim() || null; const author = normalizePaperclipWakePlanReviewAuthor(delta.author); + const reactionValue = parseObject(delta.reaction); + const reactionName = asString(reactionValue.name, "").trim(); + const reaction = reactionName + ? { name: reactionName, author: normalizePaperclipWakePlanReviewAuthor(reactionValue.author) } + : null; if (!id && !threadId && !documentKey && !quote.trim() && !body.trim()) return null; return { @@ -998,6 +1004,7 @@ function normalizePaperclipWakeAnnotationDelta( bodyTruncated: asBoolean(delta.bodyTruncated, false), createdAt, author, + reaction, }; } @@ -2838,6 +2845,11 @@ function renderPaperclipWakePromptBody( if (delta.bodyTruncated) { lines.push("[annotation comment body truncated]"); } + if (delta.reaction?.name === "question") { + lines.push( + ` ${delta.reaction.author ? planReviewAuthorLabel(delta.reaction.author) : "A person"} reacted with a question to this comment. Answer it with a reply in this annotation thread.`, + ); + } } } diff --git a/packages/db/src/migrations/0510_clear_speedball.sql b/packages/db/src/migrations/0510_clear_speedball.sql new file mode 100644 index 00000000000..8a646cff528 --- /dev/null +++ b/packages/db/src/migrations/0510_clear_speedball.sql @@ -0,0 +1,17 @@ +CREATE TABLE "document_annotation_comment_reactions" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "company_id" uuid NOT NULL, + "comment_id" uuid NOT NULL, + "reaction" text NOT NULL, + "actor_type" text NOT NULL, + "actor_id" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "removed_at" timestamp with time zone, + CONSTRAINT "document_annotation_comment_reactions_reaction_chk" CHECK ("document_annotation_comment_reactions"."reaction" in ('done', 'check', 'thumbs_up', 'question')), + CONSTRAINT "document_annotation_comment_reactions_actor_type_chk" CHECK ("document_annotation_comment_reactions"."actor_type" in ('agent', 'user')) +); +--> statement-breakpoint +ALTER TABLE "document_annotation_comment_reactions" ADD CONSTRAINT "document_annotation_comment_reactions_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "document_annotation_comment_reactions" ADD CONSTRAINT "document_annotation_comment_reactions_comment_id_document_annotation_comments_id_fk" FOREIGN KEY ("comment_id") REFERENCES "public"."document_annotation_comments"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "document_annotation_comment_reactions_company_comment_idx" ON "document_annotation_comment_reactions" USING btree ("company_id","comment_id");--> statement-breakpoint +CREATE UNIQUE INDEX "document_annotation_comment_reactions_comment_reaction_actor_idx" ON "document_annotation_comment_reactions" USING btree ("comment_id","reaction","actor_type","actor_id"); \ No newline at end of file diff --git a/packages/db/src/migrations/meta/0505_snapshot.json b/packages/db/src/migrations/meta/0510_snapshot.json similarity index 99% rename from packages/db/src/migrations/meta/0505_snapshot.json rename to packages/db/src/migrations/meta/0510_snapshot.json index c2723b7dd0e..529b1ab23cb 100644 --- a/packages/db/src/migrations/meta/0505_snapshot.json +++ b/packages/db/src/migrations/meta/0510_snapshot.json @@ -1,6 +1,6 @@ { - "id": "001ed6d5-4cc4-4f05-91ec-f3031c94bc98", - "prevId": "5d1d8cc7-e7f6-40ce-94c5-dc84dd4210b9", + "id": "bd7706ab-f548-43f0-9dbb-4f1d52d9c135", + "prevId": "01f5b33d-2353-4095-8b32-86aec4f8df2c", "version": "7", "dialect": "postgresql", "tables": { @@ -26298,6 +26298,160 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.document_annotation_comment_reactions": { + "name": "document_annotation_comment_reactions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "comment_id": { + "name": "comment_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "reaction": { + "name": "reaction", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_type": { + "name": "actor_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "removed_at": { + "name": "removed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "document_annotation_comment_reactions_company_comment_idx": { + "name": "document_annotation_comment_reactions_company_comment_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "comment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "document_annotation_comment_reactions_comment_reaction_actor_idx": { + "name": "document_annotation_comment_reactions_comment_reaction_actor_idx", + "columns": [ + { + "expression": "comment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "reaction", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "actor_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "actor_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "document_annotation_comment_reactions_company_id_companies_id_fk": { + "name": "document_annotation_comment_reactions_company_id_companies_id_fk", + "tableFrom": "document_annotation_comment_reactions", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "document_annotation_comment_reactions_comment_id_document_annotation_comments_id_fk": { + "name": "document_annotation_comment_reactions_comment_id_document_annotation_comments_id_fk", + "tableFrom": "document_annotation_comment_reactions", + "tableTo": "document_annotation_comments", + "columnsFrom": [ + "comment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "document_annotation_comment_reactions_reaction_chk": { + "name": "document_annotation_comment_reactions_reaction_chk", + "value": "\"document_annotation_comment_reactions\".\"reaction\" in ('done', 'check', 'thumbs_up', 'question')" + }, + "document_annotation_comment_reactions_actor_type_chk": { + "name": "document_annotation_comment_reactions_actor_type_chk", + "value": "\"document_annotation_comment_reactions\".\"actor_type\" in ('agent', 'user')" + } + }, + "isRLSEnabled": false + }, "public.document_annotation_comments": { "name": "document_annotation_comments", "schema": "", @@ -36739,6 +36893,62 @@ "method": "btree", "with": {} }, + "heartbeat_runs_attention_resumed_idx": { + "name": "heartbeat_runs_attention_resumed_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"issue_id\"::text, \"native_issue_id\"::text,\n \"context_snapshot\"->>'issueId', \"context_snapshot\"->>'taskId')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"heartbeat_runs\".\"status\" in ('running', 'succeeded')", + "concurrently": true, + "method": "btree", + "with": {} + }, + "heartbeat_runs_attention_history_idx": { + "name": "heartbeat_runs_attention_history_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": false, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"heartbeat_runs\".\"status\" in ('failed', 'timed_out') or \"heartbeat_runs\".\"error_code\" = 'provider_limit_wait'", + "concurrently": true, + "method": "btree", + "with": {} + }, "heartbeat_runs_company_ctx_issue_created_idx": { "name": "heartbeat_runs_company_ctx_issue_created_idx", "columns": [ @@ -60159,6 +60369,28 @@ "concurrently": false, "method": "btree", "with": {} + }, + "tool_call_events_connection_error_idx": { + "name": "tool_call_events_connection_error_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"tool_call_events\".\"error_message\" is not null", + "concurrently": false, + "method": "btree", + "with": {} } }, "foreignKeys": { @@ -61000,6 +61232,13 @@ "notNull": true, "default": "'pending'" }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'requested'" + }, "requested_by_actor_type": { "name": "requested_by_actor_type", "type": "text", @@ -61039,6 +61278,12 @@ "primaryKey": false, "notNull": false }, + "not_before": { + "name": "not_before", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, "completed_at": { "name": "completed_at", "type": "timestamp with time zone", @@ -62598,6 +62843,28 @@ "method": "btree", "with": {} }, + "tool_invocations_connection_error_idx": { + "name": "tool_invocations_connection_error_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"tool_invocations\".\"error_message\" is not null", + "concurrently": false, + "method": "btree", + "with": {} + }, "tool_invocations_company_idempotency_uq": { "name": "tool_invocations_company_idempotency_uq", "columns": [ diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index b379deff6c7..2e760e9fa7e 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -3557,6 +3557,13 @@ "when": 1795602445143, "tag": "0509_recover_exhausted_github_responses", "breakpoints": true + }, + { + "idx": 510, + "version": "7", + "when": 1795635927842, + "tag": "0510_clear_speedball", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/document_annotation_comment_reactions.ts b/packages/db/src/schema/document_annotation_comment_reactions.ts new file mode 100644 index 00000000000..3783561844c --- /dev/null +++ b/packages/db/src/schema/document_annotation_comment_reactions.ts @@ -0,0 +1,39 @@ +import type { DocumentAnnotationCommentReactionName } from "@paperclipai/shared"; +import { sql } from "drizzle-orm"; +import { check, index, pgTable, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core"; +import { companies } from "./companies.js"; +import { documentAnnotationComments } from "./document_annotation_comments.js"; + +export const documentAnnotationCommentReactions = pgTable( + "document_annotation_comment_reactions", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + commentId: uuid("comment_id").notNull().references(() => documentAnnotationComments.id, { onDelete: "cascade" }), + reaction: text("reaction").$type().notNull(), + actorType: text("actor_type").$type<"agent" | "user">().notNull(), + actorId: text("actor_id").notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + removedAt: timestamp("removed_at", { withTimezone: true }), + }, + (table) => ({ + companyCommentIdx: index("document_annotation_comment_reactions_company_comment_idx").on( + table.companyId, + table.commentId, + ), + commentReactionActorUniqueIdx: uniqueIndex("document_annotation_comment_reactions_comment_reaction_actor_idx").on( + table.commentId, + table.reaction, + table.actorType, + table.actorId, + ), + reactionChk: check( + "document_annotation_comment_reactions_reaction_chk", + sql`${table.reaction} in ('done', 'check', 'thumbs_up', 'question')`, + ), + actorTypeChk: check( + "document_annotation_comment_reactions_actor_type_chk", + sql`${table.actorType} in ('agent', 'user')`, + ), + }), +); diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.ts index c7b5688aad6..caad881194d 100644 --- a/packages/db/src/schema/index.ts +++ b/packages/db/src/schema/index.ts @@ -148,6 +148,7 @@ export { statusCards, statusCardUpdates } from "./status_cards.js"; export { routineDocuments } from "./routine_documents.js"; export { documentAnnotationThreads } from "./document_annotation_threads.js"; export { documentAnnotationComments } from "./document_annotation_comments.js"; +export { documentAnnotationCommentReactions } from "./document_annotation_comment_reactions.js"; export { documentAnnotationAnchorSnapshots } from "./document_annotation_anchor_snapshots.js"; export { heartbeatRuns, workspaceRestoreFailureCodesSql } from "./heartbeat_runs.js"; export { heartbeatRunEvents } from "./heartbeat_run_events.js"; diff --git a/packages/shared/src/constants.ts b/packages/shared/src/constants.ts index b38786d0ab7..3f1500b7050 100644 --- a/packages/shared/src/constants.ts +++ b/packages/shared/src/constants.ts @@ -534,6 +534,9 @@ export type IssueReferenceSourceKind = (typeof ISSUE_REFERENCE_SOURCE_KINDS)[num export const DOCUMENT_ANNOTATION_THREAD_STATUSES = ["open", "resolved"] as const; export type DocumentAnnotationThreadStatus = (typeof DOCUMENT_ANNOTATION_THREAD_STATUSES)[number]; +export const DOCUMENT_ANNOTATION_COMMENT_REACTIONS = ["done", "check", "thumbs_up", "question"] as const; +export type DocumentAnnotationCommentReactionName = (typeof DOCUMENT_ANNOTATION_COMMENT_REACTIONS)[number]; + export const DOCUMENT_ANNOTATION_ANCHOR_STATES = ["active", "stale", "orphaned"] as const; export type DocumentAnnotationAnchorState = (typeof DOCUMENT_ANNOTATION_ANCHOR_STATES)[number]; diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 46b77dd3c9d..f1f6eb0b615 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -495,6 +495,7 @@ export { isSystemIssueDocumentKey, ISSUE_REFERENCE_SOURCE_KINDS, DOCUMENT_ANNOTATION_THREAD_STATUSES, + DOCUMENT_ANNOTATION_COMMENT_REACTIONS, DOCUMENT_ANNOTATION_ANCHOR_STATES, DOCUMENT_ANNOTATION_ANCHOR_CONFIDENCES, EXTERNAL_OBJECT_STATUS_CATEGORIES, @@ -705,6 +706,7 @@ export { type SystemIssueDocumentKey, type IssueReferenceSourceKind, type DocumentAnnotationThreadStatus, + type DocumentAnnotationCommentReactionName, type DocumentAnnotationAnchorState, type DocumentAnnotationAnchorConfidence, type ExternalObjectStatusCategory, @@ -1159,6 +1161,8 @@ export type { DocumentAnnotationAnchorSelector, DocumentAnnotationAnchorSnapshot, DocumentAnnotationComment, + DocumentAnnotationCommentReactionActor, + DocumentAnnotationCommentReactionSummary, DocumentAnnotationTextPositionSelector, DocumentAnnotationTextQuoteSelector, DocumentAnnotationThread, @@ -2113,6 +2117,7 @@ export { type UpdateProjectWorkspace, projectExecutionWorkspacePolicySchema, createDocumentAnnotationCommentSchema, + documentAnnotationCommentReactionSchema, createDocumentAnnotationThreadSchema, documentAnnotationAnchorConfidenceSchema, documentAnnotationAnchorSelectorSchema, diff --git a/packages/shared/src/types/document-annotation.ts b/packages/shared/src/types/document-annotation.ts index 7769a42f1cc..f497883bf8e 100644 --- a/packages/shared/src/types/document-annotation.ts +++ b/packages/shared/src/types/document-annotation.ts @@ -1,6 +1,7 @@ import type { DocumentAnnotationAnchorConfidence, DocumentAnnotationAnchorState, + DocumentAnnotationCommentReactionName, DocumentAnnotationThreadStatus, IssueCommentAuthorType, IssueThreadInteractionContinuationPolicy, @@ -101,10 +102,24 @@ export interface DocumentAnnotationComment { authorUserId: string | null; createdByRunId: string | null; issueCommentId?: string | null; + reactions?: DocumentAnnotationCommentReactionSummary[]; createdAt: Date; updatedAt: Date; } +export interface DocumentAnnotationCommentReactionActor { + actorType: "agent" | "user"; + agentId: string | null; + userId: string | null; +} + +export interface DocumentAnnotationCommentReactionSummary { + reaction: DocumentAnnotationCommentReactionName; + count: number; + reactedByMe: boolean; + actors: DocumentAnnotationCommentReactionActor[]; +} + export interface DocumentAnnotationAnchorRemapSnapshot { id: string; companyId: string; diff --git a/packages/shared/src/types/index.ts b/packages/shared/src/types/index.ts index e566109a838..44184c2bada 100644 --- a/packages/shared/src/types/index.ts +++ b/packages/shared/src/types/index.ts @@ -384,6 +384,8 @@ export type { DocumentAnnotationAnchorSelector, DocumentAnnotationAnchorSnapshot, DocumentAnnotationComment, + DocumentAnnotationCommentReactionActor, + DocumentAnnotationCommentReactionSummary, DocumentAnnotationTextPositionSelector, DocumentAnnotationTextQuoteSelector, DocumentAnnotationThread, diff --git a/packages/shared/src/validators/document-annotation.ts b/packages/shared/src/validators/document-annotation.ts index d60dca3192d..1b7088f56bc 100644 --- a/packages/shared/src/validators/document-annotation.ts +++ b/packages/shared/src/validators/document-annotation.ts @@ -2,11 +2,13 @@ import { z } from "zod"; import { DOCUMENT_ANNOTATION_ANCHOR_CONFIDENCES, DOCUMENT_ANNOTATION_ANCHOR_STATES, + DOCUMENT_ANNOTATION_COMMENT_REACTIONS, DOCUMENT_ANNOTATION_THREAD_STATUSES, } from "../constants.js"; import { multilineTextSchema } from "./text.js"; export const documentAnnotationThreadStatusSchema = z.enum(DOCUMENT_ANNOTATION_THREAD_STATUSES); +export const documentAnnotationCommentReactionSchema = z.enum(DOCUMENT_ANNOTATION_COMMENT_REACTIONS); export const documentAnnotationAnchorStateSchema = z.enum(DOCUMENT_ANNOTATION_ANCHOR_STATES); export const documentAnnotationAnchorConfidenceSchema = z.enum(DOCUMENT_ANNOTATION_ANCHOR_CONFIDENCES); diff --git a/packages/shared/src/validators/index.ts b/packages/shared/src/validators/index.ts index c6d21d8635e..25a142aeffc 100644 --- a/packages/shared/src/validators/index.ts +++ b/packages/shared/src/validators/index.ts @@ -409,6 +409,7 @@ export { export { createDocumentAnnotationCommentSchema, + documentAnnotationCommentReactionSchema, createDocumentAnnotationThreadSchema, documentAnnotationAnchorConfidenceSchema, documentAnnotationAnchorSelectorSchema, diff --git a/server/src/__tests__/document-annotation-routes.test.ts b/server/src/__tests__/document-annotation-routes.test.ts index 9beee70209c..49e98f0b4e2 100644 --- a/server/src/__tests__/document-annotation-routes.test.ts +++ b/server/src/__tests__/document-annotation-routes.test.ts @@ -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(); + }); + }); }); diff --git a/server/src/__tests__/document-annotations-service.test.ts b/server/src/__tests__/document-annotations-service.test.ts index 35b13e23349..7368cbf791f 100644 --- a/server/src/__tests__/document-annotations-service.test.ts +++ b/server/src/__tests__/document-annotations-service.test.ts @@ -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"); diff --git a/server/src/__tests__/routine-document-annotation-routes.test.ts b/server/src/__tests__/routine-document-annotation-routes.test.ts index 9f2bdc83602..6c736d66803 100644 --- a/server/src/__tests__/routine-document-annotation-routes.test.ts +++ b/server/src/__tests__/routine-document-annotation-routes.test.ts @@ -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. diff --git a/server/src/modules/wake-queue/application/issue-wake-admission.ts b/server/src/modules/wake-queue/application/issue-wake-admission.ts index 6f57462ee0c..9e39f8a43d3 100644 --- a/server/src/modules/wake-queue/application/issue-wake-admission.ts +++ b/server/src/modules/wake-queue/application/issue-wake-admission.ts @@ -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)) { diff --git a/server/src/modules/wake-queue/domain/policy.test.ts b/server/src/modules/wake-queue/domain/policy.test.ts index 9745144ac71..886ad08c083 100644 --- a/server/src/modules/wake-queue/domain/policy.test.ts +++ b/server/src/modules/wake-queue/domain/policy.test.ts @@ -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 }, diff --git a/server/src/routes/cases.ts b/server/src/routes/cases.ts index ef318a6e835..feb78be1ae7 100644 --- a/server/src/routes/cases.ts +++ b/server/src/routes/cases.ts @@ -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); diff --git a/server/src/routes/experimental-api-metadata.ts b/server/src/routes/experimental-api-metadata.ts index 5202220ea62..f37b5639fc0 100644 --- a/server/src/routes/experimental-api-metadata.ts +++ b/server/src/routes/experimental-api-metadata.ts @@ -63,6 +63,20 @@ export const experimentalApiMetadata: Record | 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), diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index d99f33a2de0..ff7aa741c8c 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -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", diff --git a/server/src/routes/routines.ts b/server/src/routes/routines.ts index fd05deeb6e1..5992da72b77 100644 --- a/server/src/routes/routines.ts +++ b/server/src/routes/routines.ts @@ -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) { diff --git a/server/src/services/document-annotations.ts b/server/src/services/document-annotations.ts index c596cc23527..b506a6f94fb 100644 --- a/server/src/services/document-annotations.ts +++ b/server/src/services/document-annotations.ts @@ -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 { + async function reactionsForComments( + commentIds: string[], + viewer: ReactionViewer, + dbOrTx: any = db, + ): Promise> { + const byComment = new Map(); + 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>(); + 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 { + 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 { 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 { + 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(); 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(); 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(); 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`(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`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, diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index f515043aa5d..dcdc06a6447 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -4624,6 +4624,7 @@ export function heartbeatService( }), wakeup: trackWakeup, + resumeDeferredExecutionReceipts: heartbeatQueue.resumeDeferredExecutionReceipts, dispatchPendingNativeStatusWakeups, triggerIssueMonitor, diff --git a/server/src/services/heartbeat/deferred-receipt-work.ts b/server/src/services/heartbeat/deferred-receipt-work.ts index e8507e0346a..e9768c4be9e 100644 --- a/server/src/services/heartbeat/deferred-receipt-work.ts +++ b/server/src/services/heartbeat/deferred-receipt-work.ts @@ -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} diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts index 6040acd1968..bfa9c1be7aa 100644 --- a/server/src/services/heartbeat/queue.ts +++ b/server/src/services/heartbeat/queue.ts @@ -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(); 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, diff --git a/server/src/services/heartbeat/run-preparation.ts b/server/src/services/heartbeat/run-preparation.ts index 8677f511545..4d2d8f50e65 100644 --- a/server/src/services/heartbeat/run-preparation.ts +++ b/server/src/services/heartbeat/run-preparation.ts @@ -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, })), ) : []; diff --git a/server/src/services/issue-participation.ts b/server/src/services/issue-participation.ts index be270433fad..be1d6d8a117 100644 --- a/server/src/services/issue-participation.ts +++ b/server/src/services/issue-participation.ts @@ -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", diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index fd921e599ce..350fd9c1ddd 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -237,7 +237,7 @@ "packages/shared/src/connector-availability.ts": "82aec0dfb2e9b8cb04e21c4bcd9aab74b087c76a", "packages/shared/src/connector-identity.test.ts": "d58357707faefa7c98bb906cdaeb4db39d31081a", "packages/shared/src/connector-identity.ts": "5ede83c9c5225dbe8af9cf3a49c74e477ef5b955", - "packages/shared/src/constants.ts": "b38786d0ab71d31a1745067e6b7a07c90f9c3c01", + "packages/shared/src/constants.ts": "3f1500b70505cd586f5430ad1acb1851bf053fb1", "packages/shared/src/crash-point-registry.ts": "3cbf2d290bc111061376b43020848623e493737c", "packages/shared/src/crash-points.test.ts": "3564a1f62d22f54a3c2fb0a72b3a6cde17c957d2", "packages/shared/src/crash-points.ts": "c15259f39610e352eac5423a491548ec1bae94fe", @@ -279,7 +279,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "46b77dd3c9da46aa8fa8fd98e0649dc10a556578", + "packages/shared/src/index.ts": "f1f6eb0b6156bbdaa6d1da8973bf567245831744", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", @@ -424,7 +424,7 @@ "packages/shared/src/types/decision-queue.ts": "029b8c252913700287892b277d5353f00d2ef484", "packages/shared/src/types/decision-training.ts": "23a6485b82e1cd1125ec2002285e0a29cd73d485", "packages/shared/src/types/decision.ts": "b0d40077d481ce6180de6b02bad6df5bb0fbf977", - "packages/shared/src/types/document-annotation.ts": "7769a42f1ccd707a2259774e7fe6aa536b5d183f", + "packages/shared/src/types/document-annotation.ts": "f497883bf8e65e6141c1561c4ee603729f5ef387", "packages/shared/src/types/email.ts": "556ff6a0dcefa01eb704d6d00d3b191de81ff4dc", "packages/shared/src/types/environment.ts": "62e62afcb3d5b7f246db1e8910a34fb0091f54db", "packages/shared/src/types/execution-continuation.ts": "5afe62afd227efa03ff847d8f73291c14707ab5b", @@ -439,7 +439,7 @@ "packages/shared/src/types/inbox-agent-policy.ts": "cb9d41d9681e80b834889268ad96015a39df92f6", "packages/shared/src/types/inbox-dismissal.ts": "58fb7013847396ac9971eb5799dd0bf0486e0371", "packages/shared/src/types/inbox-mine.ts": "1d302b531d34842189704abd2f75f8743d09490d", - "packages/shared/src/types/index.ts": "e566109a838995a8b14cb2a4d47394aea0b9a752", + "packages/shared/src/types/index.ts": "44184c2badaf7cdf46ab5f574e85e0e3fa7a0b60", "packages/shared/src/types/instance.ts": "ba01ade6bf1071ab19419b4c60bc062f05f09212", "packages/shared/src/types/issue-tree-control.ts": "75489fffd491b8350b05caf57d7796419797d9df", "packages/shared/src/types/issue.ts": "fe78765782a50faf24e91e76e39846a4ace2cfc5", @@ -506,7 +506,7 @@ "packages/shared/src/validators/cost.ts": "d5a5d6e29a7156cdb1be4140fc88bd4760a25fdb", "packages/shared/src/validators/decision-queue.ts": "0d686360f577c7a7738ff85e29f23ab423be4d09", "packages/shared/src/validators/decision.ts": "02af23ad448183bc7fc023d80885067cfb4756f6", - "packages/shared/src/validators/document-annotation.ts": "d60dca3192d61a42aff5503915fed954b7aeac72", + "packages/shared/src/validators/document-annotation.ts": "1b7088f56bcc37c7ab253378e5badd02b2e24caa", "packages/shared/src/validators/email.ts": "661624d121772acfc7376ad7d933d6d54c56f4eb", "packages/shared/src/validators/environment-custom-images.ts": "f79a98e19c5398a29c9932c89898379a5fd95c78", "packages/shared/src/validators/environment.ts": "2639bb5c43a8017ad147b35a6f99f1f031ebbf62", @@ -517,7 +517,7 @@ "packages/shared/src/validators/folder.ts": "b486444ab09ec3d5a9afec7dbd2e71c1bc2beb67", "packages/shared/src/validators/goal.ts": "602724134915e1e83c50115abba36b288c0abd3d", "packages/shared/src/validators/inbox-agent-policy.ts": "29cef157f4d9b564fd813868038aa8c813df4a7b", - "packages/shared/src/validators/index.ts": "c6d21d8635e39e269774d4d893b69bc76192e14a", + "packages/shared/src/validators/index.ts": "25a142aeffc3b395993347c2d7bb0538738fefc3", "packages/shared/src/validators/instance.test.ts": "3faa9593a9a05f74429d9b1d2251906a03e9a903", "packages/shared/src/validators/instance.ts": "edde733b1d1b91023321c6c59b17b65aadf5dfa1", "packages/shared/src/validators/issue-chat-bootstrap.test.ts": "e1ebb9aa94da22c825bc3ddd32ce2cfc98bfe645", diff --git a/ui/src/api/document-annotations.ts b/ui/src/api/document-annotations.ts index 7292d730561..b64684e2a93 100644 --- a/ui/src/api/document-annotations.ts +++ b/ui/src/api/document-annotations.ts @@ -2,6 +2,7 @@ import type { CreateDocumentAnnotationCommentRequest, CreateDocumentAnnotationThreadRequest, DocumentAnnotationComment, + DocumentAnnotationCommentReactionName, DocumentAnnotationThread, DocumentAnnotationThreadStatus, DocumentAnnotationThreadWithComments, @@ -76,6 +77,18 @@ export const documentAnnotationsApi = { `${targetBasePath(target)}/${threadId}/comments`, data, ), + setReactionForTarget: ( + target: DocumentAnnotationTarget, + threadId: string, + commentId: string, + reaction: DocumentAnnotationCommentReactionName, + present: boolean, + ) => { + const path = `${targetBasePath(target)}/${threadId}/comments/${commentId}/reactions/${reaction}`; + return present + ? api.put(path, {}) + : api.delete(path); + }, updateStatus: ( issueId: string, key: string, diff --git a/ui/src/components/DocumentAnnotationPanel.tsx b/ui/src/components/DocumentAnnotationPanel.tsx index 5de460de6b8..3df2de1350c 100644 --- a/ui/src/components/DocumentAnnotationPanel.tsx +++ b/ui/src/components/DocumentAnnotationPanel.tsx @@ -1,8 +1,11 @@ import { AgentAvatar } from "./AgentAvatar"; import { useCallback, useMemo, useRef, useState, useEffect } from "react"; -import type { - DocumentAnnotationComment, - DocumentAnnotationThreadWithComments, +import { + DOCUMENT_ANNOTATION_COMMENT_REACTIONS, + type DocumentAnnotationComment, + type DocumentAnnotationCommentReactionName, + type DocumentAnnotationCommentReactionSummary, + type DocumentAnnotationThreadWithComments, } from "@paperclipai/shared"; import { Check, @@ -114,7 +117,7 @@ export function AnnotationPanelBody(props: AnnotationPanelProps) { return { kind: "issue", issueId: props.issueId, documentKey: props.documentKey }; }, [props.documentKey, props.issueId, props.target]); - const { createThread, addReply, updateStatus, mutationError, currentUser } = useDocumentAnnotationMutations({ + const { createThread, addReply, updateStatus, toggleReaction, mutationError, currentUser } = useDocumentAnnotationMutations({ target: annotationTarget, baseRevisionId: props.baseRevisionId, baseRevisionNumber: props.baseRevisionNumber, @@ -238,6 +241,9 @@ export function AnnotationPanelBody(props: AnnotationPanelProps) { onCopyLink={() => copyAnnotationLink(props.documentKey, thread.id)} pendingReply={addReply.isPending && addReply.variables?.threadId === thread.id} pendingStatus={updateStatus.isPending && updateStatus.variables?.threadId === thread.id} + onToggleReaction={(commentId, reaction, present) => + toggleReaction.mutate({ threadId: thread.id, commentId, reaction, present }) + } agentMap={props.agentMap} userProfileMap={props.userProfileMap} /> @@ -325,6 +331,11 @@ export function ThreadCard(props: { onCopyLink: () => void; pendingReply: boolean; pendingStatus: boolean; + onToggleReaction?: ( + commentId: string, + reaction: DocumentAnnotationCommentReactionName, + present: boolean, + ) => void; agentMap?: ReadonlyMap & Partial>>; userProfileMap?: ReadonlyMap; }) { @@ -364,6 +375,7 @@ export function ThreadCard(props: { key={comment.id} comment={comment} focused={props.focusedCommentId === comment.id} + onToggleReaction={props.onToggleReaction} agentMap={props.agentMap} userProfileMap={props.userProfileMap} /> @@ -455,11 +467,17 @@ export function ThreadCard(props: { function CommentRow({ comment, focused, + onToggleReaction, agentMap, userProfileMap, }: { comment: DocumentAnnotationComment; focused: boolean; + onToggleReaction?: ( + commentId: string, + reaction: DocumentAnnotationCommentReactionName, + present: boolean, + ) => void; agentMap?: ReadonlyMap & Partial>>; userProfileMap?: ReadonlyMap; }) { @@ -488,10 +506,90 @@ function CommentRow({ {relativeTime(comment.createdAt)} {comment.body} + {onToggleReaction && !comment.id.startsWith("optimistic-") ? ( + onToggleReaction(comment.id, reaction, present)} + agentMap={agentMap} + userProfileMap={userProfileMap} + /> + ) : null} ); } +const REACTION_DISPLAY: Record = { + done: { emoji: "✅", label: "Done" }, + check: { emoji: "✔️", label: "Check" }, + thumbs_up: { emoji: "👍", label: "Thumbs up" }, + question: { emoji: "❓", label: "Question" }, +}; + +function CommentReactions({ + comment, + onToggle, + agentMap, + userProfileMap, +}: { + comment: DocumentAnnotationComment; + onToggle: (reaction: DocumentAnnotationCommentReactionName, present: boolean) => void; + agentMap?: ReadonlyMap & Partial>>; + userProfileMap?: ReadonlyMap; +}) { + const byName = new Map((comment.reactions ?? []).map((entry) => [entry.reaction, entry])); + return ( +
event.stopPropagation()} + > + {DOCUMENT_ANNOTATION_COMMENT_REACTIONS.map((reaction) => { + const summary = byName.get(reaction); + const display = REACTION_DISPLAY[reaction]; + const reacted = summary?.reactedByMe === true; + const count = summary?.count ?? 0; + const who = summary ? reactionActorNames(summary, { agentMap, userProfileMap }) : []; + return ( + + ); + })} +
+ ); +} + +function reactionActorNames( + summary: DocumentAnnotationCommentReactionSummary, + maps: { + agentMap?: ReadonlyMap & Partial>>; + userProfileMap?: ReadonlyMap; + }, +): string[] { + return summary.actors.map((actor) => { + if (actor.agentId) return maps.agentMap?.get(actor.agentId)?.name ?? actor.agentId.slice(0, 8); + if (actor.userId) return maps.userProfileMap?.get(actor.userId)?.label ?? actor.userId.slice(0, 8); + return actor.actorType === "agent" ? "Agent" : "Board"; + }); +} + /** ⌘/Ctrl + Enter submits the composer or reply. */ function isSubmitShortcut(event: React.KeyboardEvent): boolean { return event.key === "Enter" && (event.metaKey || event.ctrlKey); diff --git a/ui/src/components/DocumentAnnotationPopover.tsx b/ui/src/components/DocumentAnnotationPopover.tsx index 274c1ed38b9..6eecc59acbb 100644 --- a/ui/src/components/DocumentAnnotationPopover.tsx +++ b/ui/src/components/DocumentAnnotationPopover.tsx @@ -33,7 +33,7 @@ export function DocumentAnnotationPopover(props: DocumentAnnotationPopoverProps) const [composer, setComposer] = useState(""); const [reply, setReply] = useState(""); const target = useMemo(() => props.target, [props.target]); - const { createThread, addReply, updateStatus, mutationError } = useDocumentAnnotationMutations({ + const { createThread, addReply, updateStatus, toggleReaction, mutationError } = useDocumentAnnotationMutations({ target, baseRevisionId: props.baseRevisionId, baseRevisionNumber: props.baseRevisionNumber, @@ -130,6 +130,9 @@ export function DocumentAnnotationPopover(props: DocumentAnnotationPopoverProps) onCopyLink={() => copyAnnotationLink(props.documentKey, props.thread!.id)} pendingReply={addReply.isPending} pendingStatus={updateStatus.isPending} + onToggleReaction={(commentId, reaction, present) => + toggleReaction.mutate({ threadId: props.thread!.id, commentId, reaction, present }) + } agentMap={props.agentMap} userProfileMap={props.userProfileMap} /> diff --git a/ui/src/context/LiveUpdatesProvider.tsx b/ui/src/context/LiveUpdatesProvider.tsx index dcbef61d96f..7941de1a09d 100644 --- a/ui/src/context/LiveUpdatesProvider.tsx +++ b/ui/src/context/LiveUpdatesProvider.tsx @@ -1118,6 +1118,8 @@ const ISSUE_CASE_WORK_ACTIVITY_ACTIONS = new Set([ const ISSUE_DOCUMENT_ANNOTATION_ACTIVITY_ACTIONS = new Set([ "issue.document_annotation_thread_created", "issue.document_annotation_comment_added", + "issue.document_annotation_comment_reaction_added", + "issue.document_annotation_comment_reaction_removed", "issue.document_annotation_thread_resolved", "issue.document_annotation_thread_reopened", "issue.document_annotation_remapped", @@ -1125,6 +1127,8 @@ const ISSUE_DOCUMENT_ANNOTATION_ACTIVITY_ACTIONS = new Set([ const ROUTINE_DOCUMENT_ANNOTATION_ACTIVITY_ACTIONS = new Set([ "routine.document_annotation_thread_created", "routine.document_annotation_comment_added", + "routine.document_annotation_comment_reaction_added", + "routine.document_annotation_comment_reaction_removed", "routine.document_annotation_thread_resolved", "routine.document_annotation_thread_reopened", "routine.document_annotation_remapped", @@ -1132,6 +1136,8 @@ const ROUTINE_DOCUMENT_ANNOTATION_ACTIVITY_ACTIONS = new Set([ const CASE_DOCUMENT_ANNOTATION_ACTIVITY_ACTIONS = new Set([ "case.document_annotation_thread_created", "case.document_annotation_comment_added", + "case.document_annotation_comment_reaction_added", + "case.document_annotation_comment_reaction_removed", "case.document_annotation_thread_resolved", "case.document_annotation_thread_reopened", "case.document_annotation_remapped", diff --git a/ui/src/hooks/useDocumentAnnotationMutations.test.tsx b/ui/src/hooks/useDocumentAnnotationMutations.test.tsx new file mode 100644 index 00000000000..783547091fe --- /dev/null +++ b/ui/src/hooks/useDocumentAnnotationMutations.test.tsx @@ -0,0 +1,467 @@ +// @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["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()); + + 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["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()); + + 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 = []; + 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["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()); + 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["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()); + + 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["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()); + + 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()); + 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( + +
    + undefined} + onSubmitReply={() => undefined} + onResolveToggle={() => undefined} + onCopyLink={() => undefined} + pendingReply={false} + pendingStatus={false} + onToggleReaction={onToggleReaction} + agentMap={new Map([["agent-1", { id: "agent-1", name: "Engineering" }]])} + /> +
+
, + ); + }); + + 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()); + }); +}); diff --git a/ui/src/hooks/useDocumentAnnotationMutations.ts b/ui/src/hooks/useDocumentAnnotationMutations.ts index e5105b3e6c4..2acbfebdc1b 100644 --- a/ui/src/hooks/useDocumentAnnotationMutations.ts +++ b/ui/src/hooks/useDocumentAnnotationMutations.ts @@ -1,6 +1,7 @@ -import { useCallback, useMemo, useState } from "react"; -import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import type { DocumentAnnotationComment, DocumentAnnotationThreadStatus, DocumentAnnotationThreadWithComments } from "@paperclipai/shared"; +import { useCallback, useEffect, useMemo, useState } from "react"; +import { useMutation, useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query"; +import type { DocumentAnnotationComment, DocumentAnnotationCommentReactionName, DocumentAnnotationCommentReactionSummary, DocumentAnnotationThreadStatus, DocumentAnnotationThreadWithComments } from "@paperclipai/shared"; +import { DOCUMENT_ANNOTATION_COMMENT_REACTIONS } from "@paperclipai/shared"; import { authApi } from "@/api/auth"; import { documentAnnotationsApi, type DocumentAnnotationTarget } from "@/api/document-annotations"; import { queryKeys } from "@/lib/queryKeys"; @@ -114,7 +115,217 @@ export function useDocumentAnnotationMutations(options: MutationOptions) { onSuccess: () => setMutationError(null), onSettled: invalidateAll, }); - return { createThread, addReply, updateStatus, mutationError, currentUser }; + const queryKeyHash = useMemo(() => JSON.stringify(queryKey), [queryKey]); + + useEffect(() => { + let reapplying = false; + return queryClient.getQueryCache().subscribe((event) => { + if (reapplying) return; + if (event.type !== "updated" || event.action.type !== "success" || event.action.manual) return; + const reactionState = peekTargetReactionState(queryClient, queryKeyHash); + if (!reactionState || reactionState.pendingChoices.size === 0) return; + if (JSON.stringify(event.query.queryKey) !== queryKeyHash) return; + const current = queryClient.getQueryData(queryKey); + if (!current) return; + const next = applyPendingReactionChoices(current, reactionState.pendingChoices.values()); + if (next === current) return; + reapplying = true; + try { + queryClient.setQueryData(queryKey, next); + } finally { + reapplying = false; + } + }); + }, [queryClient, queryKey, queryKeyHash]); + + const updateCommentReactions = useCallback(( + threadId: string, + commentId: string, + update: (reactions: DocumentAnnotationCommentReactionSummary[]) => DocumentAnnotationCommentReactionSummary[], + ) => queryClient.setQueryData(queryKey, (current) => (current ?? []).map((thread) => + thread.id !== threadId ? thread : { + ...thread, + comments: thread.comments.map((comment) => comment.id === commentId + ? { ...comment, reactions: update(comment.reactions ?? []) } + : comment), + })), [queryClient, queryKey]); + const toggleReaction = useMutation({ + mutationFn: ({ threadId, commentId, reaction, present }: ReactionToggle) => { + const reactionState = getTargetReactionState(queryClient, queryKeyHash); + const key = reactionWriteKey(commentId, reaction); + const previous = reactionState.writes.get(key); + const write = (previous ? previous.catch(() => undefined) : Promise.resolve()) + .then(() => documentAnnotationsApi.setReactionForTarget(options.target, threadId, commentId, reaction, present)); + reactionState.writes.set(key, write); + return write.finally(() => { + if (reactionState.writes.get(key) === write) reactionState.writes.delete(key); + cleanupTargetReactionState(queryClient, queryKeyHash, reactionState); + }); + }, + onMutate: async ({ threadId, commentId, reaction, present }) => { + const reactionState = getTargetReactionState(queryClient, queryKeyHash); + const key = reactionWriteKey(commentId, reaction); + reactionState.pendingCounts.set(key, (reactionState.pendingCounts.get(key) ?? 0) + 1); + reactionState.pendingChoices.set(key, { threadId, commentId, reaction, present, userId: currentUser.id }); + setMutationError(null); + await queryClient.cancelQueries({ queryKey }); + let previous: DocumentAnnotationCommentReactionSummary | undefined; + updateCommentReactions(threadId, commentId, (reactions) => { + previous = reactions.find((entry) => entry.reaction === reaction); + return applyOptimisticReaction(reactions, reaction, present, currentUser.id); + }); + return { previous }; + }, + onError: (error, { threadId, commentId, reaction }, context) => { + const reactionState = peekTargetReactionState(queryClient, queryKeyHash); + const key = reactionWriteKey(commentId, reaction); + if ((reactionState?.pendingCounts.get(key) ?? 0) <= 1 && context) { + updateCommentReactions(threadId, commentId, (reactions) => replaceReaction(reactions, reaction, context.previous)); + } + setMutationError(messageFor(error, "Failed to update reaction.")); + }, + onSuccess: (comment, { threadId, commentId, reaction }) => { + setMutationError(null); + const reactionState = peekTargetReactionState(queryClient, queryKeyHash); + const key = reactionWriteKey(commentId, reaction); + if ((reactionState?.pendingCounts.get(key) ?? 0) > 1) return; + const otherPending = Array.from(reactionState?.pendingChoices.values() ?? []).filter( + (choice) => choice.commentId === commentId && choice.reaction !== reaction, + ); + updateCommentReactions(threadId, commentId, () => otherPending.reduce( + (merged, choice) => applyOptimisticReaction(merged, choice.reaction, choice.present, choice.userId), + comment.reactions ?? [], + )); + }, + onSettled: (_comment, _error, { commentId, reaction }) => { + const reactionState = peekTargetReactionState(queryClient, queryKeyHash); + if (!reactionState) return invalidateAll(); + const key = reactionWriteKey(commentId, reaction); + const remaining = (reactionState.pendingCounts.get(key) ?? 1) - 1; + if (remaining > 0) { + reactionState.pendingCounts.set(key, remaining); + } else { + reactionState.pendingCounts.delete(key); + reactionState.pendingChoices.delete(key); + } + const hasPending = reactionState.pendingCounts.size > 0; + cleanupTargetReactionState(queryClient, queryKeyHash, reactionState); + if (hasPending) return; + return invalidateAll(); + }, + }); + return { createThread, addReply, updateStatus, toggleReaction, mutationError, currentUser }; +} + +interface TargetReactionState { + writes: Map>; + pendingCounts: Map; + pendingChoices: Map; +} + +const reactionStateByClient = new WeakMap>(); + +function peekTargetReactionState(queryClient: QueryClient, queryKeyHash: string): TargetReactionState | undefined { + return reactionStateByClient.get(queryClient)?.get(queryKeyHash); +} + +function getTargetReactionState(queryClient: QueryClient, queryKeyHash: string): TargetReactionState { + let byTarget = reactionStateByClient.get(queryClient); + if (!byTarget) { + byTarget = new Map(); + reactionStateByClient.set(queryClient, byTarget); + } + let state = byTarget.get(queryKeyHash); + if (!state) { + state = { + writes: new Map(), + pendingCounts: new Map(), + pendingChoices: new Map(), + }; + byTarget.set(queryKeyHash, state); + } + return state; +} + +function cleanupTargetReactionState(queryClient: QueryClient, queryKeyHash: string, state: TargetReactionState) { + if (state.writes.size > 0 || state.pendingCounts.size > 0 || state.pendingChoices.size > 0) return; + const byTarget = reactionStateByClient.get(queryClient); + if (byTarget?.get(queryKeyHash) === state) byTarget.delete(queryKeyHash); +} + +interface PendingReactionChoice extends ReactionToggle { + userId: string | null; +} + +function applyPendingReactionChoices( + threads: DocumentAnnotationThreadWithComments[], + choices: Iterable, +): DocumentAnnotationThreadWithComments[] { + const byComment = new Map(); + for (const choice of choices) { + const list = byComment.get(choice.commentId) ?? []; + list.push(choice); + byComment.set(choice.commentId, list); + } + if (byComment.size === 0) return threads; + let changed = false; + const nextThreads = threads.map((thread) => { + let threadChanged = false; + const comments = thread.comments.map((comment) => { + const pending = byComment.get(comment.id); + if (!pending) return comment; + const current = comment.reactions ?? []; + const merged = pending.reduce( + (acc, choice) => applyOptimisticReaction(acc, choice.reaction, choice.present, choice.userId), + current, + ); + if (merged === current) return comment; + threadChanged = true; + return { ...comment, reactions: merged }; + }); + if (!threadChanged) return thread; + changed = true; + return { ...thread, comments }; + }); + return changed ? nextThreads : threads; +} + +function reactionWriteKey(commentId: string, reaction: DocumentAnnotationCommentReactionName) { + return `${commentId}:${reaction}`; +} + +export interface ReactionToggle { + threadId: string; + commentId: string; + reaction: DocumentAnnotationCommentReactionName; + present: boolean; +} + +export function applyOptimisticReaction( + reactions: DocumentAnnotationCommentReactionSummary[], + reaction: DocumentAnnotationCommentReactionName, + present: boolean, + userId: string | null, +): DocumentAnnotationCommentReactionSummary[] { + const existing = reactions.find((entry) => entry.reaction === reaction); + if (Boolean(existing?.reactedByMe) === present) return reactions; + const actors = (existing?.actors ?? []).filter((actor) => !(actor.actorType === "user" && actor.userId === userId)); + const next: DocumentAnnotationCommentReactionSummary = { + reaction, + count: Math.max(0, (existing?.count ?? 0) + (present ? 1 : -1)), + reactedByMe: present, + actors: present ? [...actors, { actorType: "user", agentId: null, userId }] : actors, + }; + return replaceReaction(reactions, reaction, next.count > 0 ? next : undefined); +} + +function replaceReaction( + reactions: DocumentAnnotationCommentReactionSummary[], + reaction: DocumentAnnotationCommentReactionName, + entry: DocumentAnnotationCommentReactionSummary | undefined, +): DocumentAnnotationCommentReactionSummary[] { + const merged = [...reactions.filter((existing) => existing.reaction !== reaction), ...(entry ? [entry] : [])]; + return DOCUMENT_ANNOTATION_COMMENT_REACTIONS.flatMap((name) => merged.filter((existing) => existing.reaction === name)); } function messageFor(error: unknown, fallback: string) { return error instanceof Error && error.message ? error.message : fallback; } diff --git a/ui/storybook/stories/documents-artifacts/document-annotations.stories.tsx b/ui/storybook/stories/documents-artifacts/document-annotations.stories.tsx index 0326a4cca6f..06f2bafec10 100644 --- a/ui/storybook/stories/documents-artifacts/document-annotations.stories.tsx +++ b/ui/storybook/stories/documents-artifacts/document-annotations.stories.tsx @@ -107,6 +107,13 @@ function makeThread( authorAgentId: "agent-uxdesigner", authorUserId: null, createdByRunId: "run-1", + reactions: [ + { reaction: "thumbs_up", count: 2, reactedByMe: true, actors: [ + { actorType: "user", agentId: null, userId: "user-1" }, + { actorType: "agent", agentId: "agent-uxdesigner", userId: null }, + ] }, + { reaction: "question", count: 1, reactedByMe: true, actors: [{ actorType: "user", agentId: null, userId: "user-1" }] }, + ], createdAt: new Date("2026-05-12T10:01:00Z"), updatedAt: new Date("2026-05-12T10:01:00Z"), },