mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-04 21:21:27 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - People review agent artifacts (plans, documents, routine descriptions, and case documents) with inline annotation comments > - Today a person must type a full reply to say "done", "checked", "looks good", or "I have a question" > - This slows down quick review feedback, and a question inside a reply does not automatically bring the assignee back > - This pull request adds four one-tap reactions to each annotation comment: Done, Check, Thumbs up, and Question > - A person's first Question reaction on an open task saves a durable wake receipt and wakes the task's assignee in a dedicated follow-up run to reply in that comment's thread (respecting chat ownership and wake rate limits) > - The benefit is fast review feedback without extra typing, while agents can read and set the same reactions through the API ## Linked Issues or Issue Description Refs #21637 (supersedes on current `master` with renumbered Drizzle migration, OpenAPI/experimental route contracts, durable wake receipts, chat ownership and rate-limit hardening, and current UI test suite) Refs #9336 (agent wake notifications for document annotation threads) Refs #9674 (agents cannot read inline document review comments) **What problem does this solve?** A reviewer cannot quickly acknowledge or question an annotation comment on an artifact. A short answer requires a typed reply, and nothing tells the agent that a person has a question about a comment. **Proposed solution** Add four fixed reactions per annotation comment: `done`, `check`, `thumbs_up`, and `question`. One tap adds a reaction and a second tap removes it. Each person or agent can add each reaction once per comment. A person's first `question` reaction on an open task commits a durable wake receipt in the same transaction and wakes the assignee once in a dedicated follow-up turn, with the comment included in the wake context. **Alternatives considered** Free-form emoji reactions. Fixed named reactions keep the API contract stable for agents and avoid storing arbitrary emoji strings on the server. ## What Changed - `packages/db`: Added `document_annotation_comment_reactions` table (`company_id`, `comment_id`, `reaction`, `actor_type`, `actor_id`, `created_at`, `removed_at`) with check constraints, cascade delete on comment deletion, and unique `(comment_id, reaction, actor_type, actor_id)` index. Generated online-compatible migration `0510_clear_speedball.sql`, refreshed Drizzle snapshot `0510_snapshot.json`, and pruned `0505_snapshot.json`. - `packages/shared`: Added `DOCUMENT_ANNOTATION_COMMENT_REACTIONS`, `DocumentAnnotationCommentReactionName`, `DocumentAnnotationCommentReactionActor`, `DocumentAnnotationCommentReactionSummary`, optional `reactions` on `DocumentAnnotationComment`, and `documentAnnotationCommentReactionSchema`. - `server`: Added `setCommentReaction` in `document-annotations.ts` using soft-delete (`removed_at`) and upsert revival (`(xmax = 0)` for `firstAdd`), and attached reaction summaries (`count`, `actors`, `reactedByMe`) to thread/comment reads. - `server` routes & contracts: Added `PUT` and `DELETE .../annotations/:threadId/comments/:commentId/reactions/:reaction` for issues, routines, and cases, registered them in `openapi.ts`, `experimental-api-metadata.ts`, and `experimental-api-paths.ts`, and logged activity (`*.document_annotation_comment_reaction_added` / `_removed`) only when a row changes. - `server` durable wake, chat ownership, rate limits & `packages/adapter-utils`: - A person's first `question` reaction on an open assigned issue inserts a recoverable `deferred_issue_execution` receipt in `agent_wakeup_requests` in the same DB transaction (`annotation-question-reaction:<id>`), passes `executionWaitRequestId` to `heartbeat.wakeup` (`reason: "issue_commented"`, `allowRunCoalescing: false`), resumes via `resumeDeferredExecutionReceipts` if immediate wake fails, and defers behind busy turns without duplicating receipts. - Recognized human annotation question reactions (`isHumanAnnotationQuestionWake`) as an independent wake cause for idle waiting agent chats while strictly enforcing chat ownership (`!conversationAgentId || conversationUserId === actorId`) across service, route, wake preflight, locked admission, and recovery queries. - Bounded distinct-comment question wakes under `issues ... FOR UPDATE` to at most 1 pending/in-flight wake per `(companyId, issueId, agentId)` and at most 3 original question receipts (`idempotency_key LIKE 'annotation-question-reaction:%'`) per `(companyId, issueId, user)` in a rolling 10-minute window. - `renderPaperclipWakePrompt` instructs the agent to answer the question in the annotation thread. - `ui`: Added four one-tap reaction buttons (`✅`, `✔️`, `👍`, `❓`) under each non-optimistic annotation comment in `DocumentAnnotationPanel` / `DocumentAnnotationPopover`, with counts, `aria-pressed`, hover tooltips naming actors, optimistic updates, client-scoped write serialization across panel/popover remounts (`WeakMap<QueryClient, Map<string, TargetReactionState>>`), live-update refetch overlay preservation, deferred invalidation while writes are pending, and updated Storybook fixture. - `docs/api` & `tests/runner-e2e`: Documented the reaction endpoints and wake bounds in `docs/api/issues.md` and `docs/api/routines.md`, and refreshed `tests/runner-e2e/source-sdk-public-inputs.json`. ## Verification - `pnpm --filter @paperclipai/db run check:migrations` and `migration-compatibility.ts`: `0510_clear_speedball.sql` classified `online_compatible`. - `pnpm --filter @paperclipai/db exec vitest run src/migration-snapshot-drift.test.ts src/migration-compatibility.test.ts`: passed (117/117). - `pnpm --filter @paperclipai/adapter-utils exec vitest run src/server-utils.test.ts -t "question reaction"`: passed. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/document-annotations-service.test.ts` (20/20, embedded Postgres — covering durable wake recovery, idle waiting-chat wake, busy-turn deferral, non-owner chat wake denial, and rolling-window + pending-backlog wake bounds across full queue admission), `src/__tests__/document-annotation-routes.test.ts` (20/20), `src/__tests__/routine-document-annotation-routes.test.ts`, `src/modules/wake-queue/application/issue-wake-admission.test.ts` (15/15), and `src/modules/wake-queue/domain/policy.test.ts`: all passed. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/openapi-routes.test.ts`: passed (59/59). - `pnpm --filter @paperclipai/ui exec vitest run src/hooks/useDocumentAnnotationMutations.test.tsx`: passed (9/9, covering optimistic updates, serialized writes across remounts, live-update refetch preservation, deferred invalidation across comments, and rendered `ThreadCard` DOM buttons/toggles). - Package typechecks (`@paperclipai/shared`, `@paperclipai/db`, `@paperclipai/adapter-utils`, `@paperclipai/server` all 7 layers, `@paperclipai/ui` + Storybook catalog): all passed. - `pnpm check:token-gates`, `node scripts/check-module-boundaries.mjs`, and `node scripts/check-test-budget.mjs`: all passed. - `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse HEAD) --check`: in sync (`inputs: 579, changed: false`). - Full-stack Playwright verification against a throwaway local server + embedded PostgreSQL: created a task, `plan` document, and annotation thread; verified invalid reaction returns `400`; clicked `thumbs_up` and `question` in the real document viewer; reloaded to prove PostgreSQL persistence; toggled `thumbs_up` off and reloaded to verify removal persisted. - PR CI on `4d892c8067`: 83/83 executed checks passing (including `ci / verify`, `ci / e2e` + all 16 E2E shards, all General/Serialized server shards, `Build`, `Typecheck + Release Registry`, `Verify Paperclip Runner`, `Superagent Security Scan`, and `Greptile Review` 5/5 with 0 unresolved threads). ## Risks - Low risk. Migration `0510_clear_speedball.sql` only creates a new table and its indexes (`online_compatible`), so running releases are unaffected. - `reactions` is optional on `DocumentAnnotationComment`, preserving backward compatibility for existing clients. - Question wakes are bounded by soft-delete revival (`firstAdd`), chat ownership enforcement, single pending/in-flight wake per `(companyId, issueId, agentId)`, and at most 3 original question wakes per `(companyId, issueId, user)` per 10-minute window. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Google Gemini (`gemini-3-pro` / Antigravity agentic coding environment with shell execution, file editing, embedded PostgreSQL, and Playwright verification), rebasing and extending prior work originally authored with Claude Opus 5.5 in #21637. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: lucktastic <13757243+lucktastic@users.noreply.github.com> Co-authored-by: Paperclip <noreply@paperclip.ing>
342 lines
17 KiB
TypeScript
342 lines
17 KiB
TypeScript
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";
|
|
import type { PendingAnchor } from "@/components/DocumentAnnotationLayer";
|
|
|
|
interface MutationOptions {
|
|
target: DocumentAnnotationTarget;
|
|
baseRevisionId: string | null;
|
|
baseRevisionNumber: number;
|
|
pendingAnchor: PendingAnchor | null;
|
|
onFocusThread: (threadId: string | null) => void;
|
|
onThreadCreated?: (thread: DocumentAnnotationThreadWithComments) => void;
|
|
onReplyAdded?: (threadId: string) => void;
|
|
}
|
|
|
|
export function useDocumentAnnotationMutations(options: MutationOptions) {
|
|
const queryClient = useQueryClient();
|
|
const [mutationError, setMutationError] = useState<string | null>(null);
|
|
const { data: session } = useQuery({
|
|
queryKey: queryKeys.auth.session,
|
|
queryFn: () => authApi.getSession(),
|
|
staleTime: 5 * 60_000,
|
|
});
|
|
const currentUser = useMemo(() => ({
|
|
id: session?.user?.id ?? null,
|
|
name: session?.user?.name?.trim() || session?.user?.email?.trim() || "You",
|
|
image: session?.user?.image ?? null,
|
|
}), [session]);
|
|
const queryKey = useMemo(() => options.target.kind === "routine"
|
|
? queryKeys.routines.documentAnnotations(options.target.routineId, options.target.documentKey, "all")
|
|
: options.target.kind === "case"
|
|
? queryKeys.cases.documentAnnotations(options.target.caseId, options.target.documentKey, "all")
|
|
: queryKeys.issues.documentAnnotations(options.target.issueId, options.target.documentKey, "all"), [options.target]);
|
|
const invalidateAll = useCallback(() => queryClient.invalidateQueries({
|
|
predicate: (query) => Array.isArray(query.queryKey)
|
|
&& query.queryKey[1] === "document-annotations"
|
|
&& query.queryKey[2] === (options.target.kind === "issue" ? options.target.issueId : options.target.kind === "case" ? options.target.caseId : options.target.routineId)
|
|
&& query.queryKey[3] === options.target.documentKey,
|
|
}), [options.target, queryClient]);
|
|
|
|
const createThread = useMutation({
|
|
mutationFn: async (body: string) => {
|
|
if (!options.pendingAnchor) throw new Error("No selection to anchor to.");
|
|
if (!options.baseRevisionId) throw new Error("Document has no revision yet.");
|
|
return documentAnnotationsApi.createForTarget(options.target, {
|
|
baseRevisionId: options.baseRevisionId,
|
|
baseRevisionNumber: options.baseRevisionNumber,
|
|
selector: options.pendingAnchor.selector,
|
|
body,
|
|
});
|
|
},
|
|
onMutate: async (body) => {
|
|
if (!options.pendingAnchor || !options.baseRevisionId) return undefined;
|
|
setMutationError(null);
|
|
await queryClient.cancelQueries({ queryKey });
|
|
const previous = queryClient.getQueryData<DocumentAnnotationThreadWithComments[]>(queryKey);
|
|
const optimistic = buildOptimisticThread(body, options, currentUser);
|
|
queryClient.setQueryData<DocumentAnnotationThreadWithComments[]>(queryKey, (current) => [...(current ?? []), optimistic]);
|
|
options.onFocusThread(optimistic.id);
|
|
return { previous, optimisticId: optimistic.id };
|
|
},
|
|
onError: (error, _body, context) => {
|
|
if (context?.previous) queryClient.setQueryData(queryKey, context.previous);
|
|
setMutationError(messageFor(error, "Failed to create comment."));
|
|
},
|
|
onSuccess: (thread, _body, context) => {
|
|
queryClient.setQueryData<DocumentAnnotationThreadWithComments[]>(queryKey, (current) =>
|
|
(current ?? []).map((entry) => entry.id === context?.optimisticId ? thread : entry));
|
|
setMutationError(null);
|
|
options.onFocusThread(thread.id);
|
|
options.onThreadCreated?.(thread);
|
|
},
|
|
onSettled: invalidateAll,
|
|
});
|
|
|
|
const addReply = useMutation({
|
|
mutationFn: ({ threadId, body }: { threadId: string; body: string }) => documentAnnotationsApi.addCommentForTarget(options.target, threadId, { body }),
|
|
onMutate: async ({ threadId, body }) => {
|
|
setMutationError(null);
|
|
await queryClient.cancelQueries({ queryKey });
|
|
const previous = queryClient.getQueryData<DocumentAnnotationThreadWithComments[]>(queryKey);
|
|
const optimistic = buildOptimisticComment(body, threadId, options.target, currentUser.id);
|
|
queryClient.setQueryData<DocumentAnnotationThreadWithComments[]>(queryKey, (current) => (current ?? []).map((thread) =>
|
|
thread.id === threadId ? { ...thread, comments: [...thread.comments, optimistic], updatedAt: optimistic.createdAt } : thread));
|
|
return { previous };
|
|
},
|
|
onError: (error, _variables, context) => {
|
|
if (context?.previous) queryClient.setQueryData(queryKey, context.previous);
|
|
setMutationError(messageFor(error, "Failed to add reply."));
|
|
},
|
|
onSuccess: (_comment, variables) => {
|
|
setMutationError(null);
|
|
options.onReplyAdded?.(variables.threadId);
|
|
},
|
|
onSettled: invalidateAll,
|
|
});
|
|
|
|
const updateStatus = useMutation({
|
|
mutationFn: ({ threadId, status }: { threadId: string; status: DocumentAnnotationThreadStatus }) => documentAnnotationsApi.updateStatusForTarget(options.target, threadId, status),
|
|
onMutate: async ({ threadId, status }) => {
|
|
setMutationError(null);
|
|
await queryClient.cancelQueries({ queryKey });
|
|
const previous = queryClient.getQueryData<DocumentAnnotationThreadWithComments[]>(queryKey);
|
|
queryClient.setQueryData<DocumentAnnotationThreadWithComments[]>(queryKey, (current) => (current ?? []).map((thread) => thread.id === threadId ? { ...thread, status } : thread));
|
|
return { previous };
|
|
},
|
|
onError: (error, _variables, context) => {
|
|
if (context?.previous) queryClient.setQueryData(queryKey, context.previous);
|
|
setMutationError(messageFor(error, "Failed to update comment status."));
|
|
},
|
|
onSuccess: () => setMutationError(null),
|
|
onSettled: invalidateAll,
|
|
});
|
|
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<DocumentAnnotationThreadWithComments[]>(queryKey);
|
|
if (!current) return;
|
|
const next = applyPendingReactionChoices(current, reactionState.pendingChoices.values());
|
|
if (next === current) return;
|
|
reapplying = true;
|
|
try {
|
|
queryClient.setQueryData<DocumentAnnotationThreadWithComments[]>(queryKey, next);
|
|
} finally {
|
|
reapplying = false;
|
|
}
|
|
});
|
|
}, [queryClient, queryKey, queryKeyHash]);
|
|
|
|
const updateCommentReactions = useCallback((
|
|
threadId: string,
|
|
commentId: string,
|
|
update: (reactions: DocumentAnnotationCommentReactionSummary[]) => DocumentAnnotationCommentReactionSummary[],
|
|
) => queryClient.setQueryData<DocumentAnnotationThreadWithComments[]>(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<string, Promise<DocumentAnnotationComment>>;
|
|
pendingCounts: Map<string, number>;
|
|
pendingChoices: Map<string, PendingReactionChoice>;
|
|
}
|
|
|
|
const reactionStateByClient = new WeakMap<QueryClient, Map<string, TargetReactionState>>();
|
|
|
|
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<PendingReactionChoice>,
|
|
): DocumentAnnotationThreadWithComments[] {
|
|
const byComment = new Map<string, PendingReactionChoice[]>();
|
|
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; }
|
|
function optimisticId(prefix: string) { return `${prefix}-${typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`}`; }
|
|
function buildOptimisticComment(body: string, threadId: string, target: DocumentAnnotationTarget, userId: string | null): DocumentAnnotationComment {
|
|
const now = new Date();
|
|
return { id: optimisticId("optimistic-comment"), companyId: "", threadId, issueId: target.kind === "issue" ? target.issueId : null, routineId: target.kind === "routine" ? target.routineId : null, caseId: target.kind === "case" ? target.caseId : null, documentId: "", body, authorType: "user", authorAgentId: null, authorUserId: userId, createdByRunId: null, issueCommentId: null, createdAt: now, updatedAt: now };
|
|
}
|
|
function buildOptimisticThread(body: string, options: MutationOptions, user: { id: string | null }): DocumentAnnotationThreadWithComments {
|
|
const id = optimisticId("optimistic-thread");
|
|
const now = new Date();
|
|
return { id, issueId: options.target.kind === "issue" ? options.target.issueId : null, routineId: options.target.kind === "routine" ? options.target.routineId : null, caseId: options.target.kind === "case" ? options.target.caseId : null, documentKey: options.target.documentKey, status: "open", anchorState: "active", selectedText: options.pendingAnchor!.selectedText, normalizedStart: options.pendingAnchor!.selector.position.normalizedStart, markdownStart: options.pendingAnchor!.selector.position.markdownStart, originalRevisionId: options.baseRevisionId!, originalRevisionNumber: options.baseRevisionNumber, currentRevisionId: options.baseRevisionId!, currentRevisionNumber: options.baseRevisionNumber, createdByUserId: user.id, createdAt: now, updatedAt: now, comments: [buildOptimisticComment(body, id, options.target, user.id)] } as unknown as DocumentAnnotationThreadWithComments;
|
|
}
|