Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(comments): reply directly from selection annotations (MUL-8702) (#10065)

Multica Eveb3b0fa6420fe
diff --git a/packages/core/drafts/reply-annotation.test.ts b/packages/core/drafts/reply-annotation.test.ts
index ced7d9d393..c59e451cf7 100644
--- a/packages/core/drafts/reply-annotation.test.ts
+++ b/packages/core/drafts/reply-annotation.test.ts
@@ -1,13 +1,32 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import { parseMentions } from "../issues/comment-trigger-outcomes";
-import { composeAnnotatedReply, hasReplyIntent, locateReplyAnnotation, normalizeReplyAnnotations, type ReplyAnnotation } from "./reply-annotation";
+import { composeAnnotatedReply, composeSelectionReply, hasReplyIntent, locateReplyAnnotation, normalizeReplyAnnotations, type ReplyAnnotation } from "./reply-annotation";
const annotation: ReplyAnnotation = {
id: "a", sourceCommentId: "source", sourceActorName: "Emacs", quote: "first\nsecond",
start: 0, prefix: "", suffix: "", note: "Please revise.",
};
+describe("composeSelectionReply", () => {
+ it("keeps captured mentions inert and the new instruction's mention active", () => {
+ const mention = "[@Agent](mention://agent/11111111-1111-1111-1111-111111111111)";
+ const result = composeSelectionReply({ ...annotation, quote: mention }, `${mention} Please revise.`);
+ expect(result).toContain(`\n\n${mention} Please revise.`);
+ expect(result.split("\n\n")[0]).not.toContain("mention://");
+ });
+
+ it.each(["/note", "/NOTE"])('keeps %s before the quote so it cannot invoke an agent', (command) => {
+ expect(composeSelectionReply(annotation, `${command} Keep this note.`)).toBe(`${command}\n\n> first\n> second\n\nKeep this note.`);
+ expect(composeSelectionReply(annotation, command)).toBe("");
+ });
+
+ it("requires an instruction and does not interpret /notes as a command", () => {
+ expect(composeSelectionReply(annotation, " ")).toBe("");
+ expect(composeSelectionReply(annotation, "/notes are ordinary text")).toBe("> first\n> second\n\n/notes are ordinary text");
+ });
+});
+
describe("annotated reply serialization", () => {
it("puts annotations before the overall reply with a section divider", () => {
expect(composeAnnotatedReply("Overall reply", [annotation, { ...annotation, id: "b", quote: "other", note: "" }]))
diff --git a/packages/core/drafts/reply-annotation.ts b/packages/core/drafts/reply-annotation.ts
index 11012b00dd..559e0a81bf 100644
--- a/packages/core/drafts/reply-annotation.ts
+++ b/packages/core/drafts/reply-annotation.ts
@@ -70,6 +70,14 @@ export function composeAnnotatedReply(content: string, annotations: readonly Rep
return command ? `${command}\n\n${sections}` : sections;
}
+/** A selection's instruction is the comment body, including any /note command. */
+export function composeSelectionReply(annotation: ReplyAnnotation, instruction: string): string {
+ const text = instruction.trim();
+ const command = text.match(/^\/note(?=\s|$)/i)?.[0];
+ const note = command ? text.slice(command.length).trim() : text;
+ return note ? composeAnnotatedReply(command ?? "", [{ ...annotation, note }]) : "";
+}
+
/** Relocate only an unambiguous quote with matching context after source edits. */
export function locateReplyAnnotation(text: string, annotation: ReplyAnnotation): number | null {
const matches = (start: number) =>
diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsx
index 0bef5de01d..f51e956e99 100644
--- a/packages/views/editor/content-editor.tsx
+++ b/packages/views/editor/content-editor.tsx
@@ -125,6 +125,7 @@ function isInNodeViewChrome(target: HTMLElement): boolean {
// Types
interface ContentEditorBaseProps {
+ ariaLabel?: string;
/**
* `baseMarkdown` is the last authoritative controlled value this editor
* actually adopted before producing `markdown`. A dirty-editor realtime
@@ -363,6 +364,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
function ContentEditor(
{
defaultValue,
+ ariaLabel,
value,
onUpdate,
placeholder: placeholderText = "",
@@ -689,6 +691,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
},
attributes: {
class: cn("flex-1 rich-text-editor text-body outline-none", className),
+ ...(ariaLabel ? { role: "textbox", "aria-label": ariaLabel, "aria-multiline": "true" } : {}),
},
},
});
diff --git a/packages/views/editor/extensions/suggestion-popup.test.tsx b/packages/views/editor/extensions/suggestion-popup.test.tsx
index c7f040aadd..eb97e79262 100644
--- a/packages/views/editor/extensions/suggestion-popup.test.tsx
+++ b/packages/views/editor/extensions/suggestion-popup.test.tsx
@@ -130,6 +130,14 @@ async function expectPopupClosed() {
}
describe("createSuggestionPopupRender", () => {
+ it("marks its portal with the editor surface owner", async () => {
+ const ed = makeEditor("@");
+ ed.view.dom.parentElement!.setAttribute("data-editor-overlay-owner", "selection-draft");
+ await triggerSuggestion(ed, "@a");
+ expect(screen.getByTestId("suggestion-popup").closest("[data-editor-overlay-owner]"))
+ .toHaveAttribute("data-editor-overlay-owner", "selection-draft");
+ });
+
it.each(["@", "/"] as const)(
"closes the %s popup through a real pluginKey on outside pointerdown",
async (char) => {
diff --git a/packages/views/editor/extensions/suggestion-popup.tsx b/packages/views/editor/extensions/suggestion-popup.tsx
index 2bf7115fba..6a8592bdab 100644
--- a/packages/views/editor/extensions/suggestion-popup.tsx
+++ b/packages/views/editor/extensions/suggestion-popup.tsx
@@ -182,6 +182,8 @@ export function createSuggestionPopupRender<
popup = doc.createElement("div");
popup.style.position = "fixed";
popup.style.zIndex = "50";
+ const owner = props.editor.view.dom.closest("[data-editor-overlay-owner]")?.getAttribute("data-editor-overlay-owner");
+ if (owner) popup.setAttribute("data-editor-overlay-owner", owner);
popup.appendChild(renderer.element);
doc.body.appendChild(popup);
diff --git a/packages/views/editor/link-hover-card.tsx b/packages/views/editor/link-hover-card.tsx
index 6583bde1b3..e314090330 100644
--- a/packages/views/editor/link-hover-card.tsx
+++ b/packages/views/editor/link-hover-card.tsx
@@ -20,6 +20,7 @@ import { useWorkspaceSlug } from "@multica/core/paths";
import { useAppOrigin } from "../navigation";
import { useT } from "../i18n";
import { openLink, isMentionHref } from "./utils/link-handler";
+import { useEditorOverlayOwner } from "./overlay-owner";
function truncateUrl(url: string, max = 48): string {
if (url.length <= max) return url;
@@ -143,6 +144,7 @@ function LinkHoverCard({
const slug = useWorkspaceSlug();
const appOrigin = useAppOrigin();
const { t } = useT("editor");
+ const overlayOwner = useEditorOverlayOwner();
// Position the card when the portal div is mounted (ref callback).
// Using useEffect would race with portal rendering — the div might
@@ -193,6 +195,7 @@ function LinkHoverCard({
<div
ref={setCardRef}
className="link-hover-card"
+ data-editor-overlay-owner={overlayOwner}
style={{
position: "fixed",
top: pos.top,
diff --git a/packages/views/editor/overlay-owner.tsx b/packages/views/editor/overlay-owner.tsx
new file mode 100644
index 0000000000..fdd0a7840e
--- /dev/null
+++ b/packages/views/editor/overlay-owner.tsx
@@ -0,0 +1,7 @@
+"use client";
+
+import { createContext, useContext } from "react";
+
+/** Portaled editor controls remain part of the surface that owns the editor. */
+export const EditorOverlayOwnerContext = createContext<string | undefined>(undefined);
+export const useEditorOverlayOwner = () => useContext(EditorOverlayOwnerContext);
diff --git a/packages/views/issues/components/annotation-composer.tsx b/packages/views/issues/components/annotation-composer.tsx
new file mode 100644
index 0000000000..ef89db74dd
--- /dev/null
+++ b/packages/views/issues/components/annotation-composer.tsx
@@ -0,0 +1,142 @@
+"use client";
+
+import { useEffect, useRef, useState, type RefObject } from "react";
+import { Loader2, Trash2 } from "@multica/ui/icons";
+import { toast } from "sonner";
+import { copyText } from "@multica/ui/lib/clipboard";
+import { Button } from "@multica/ui/components/ui/button";
+import { IconButton } from "@multica/ui/components/common/icon-button";
+import { composeSelectionReply, MAX_REPLY_ANNOTATIONS, type ReplyAnnotation } from "@multica/core/drafts/reply-annotation";
+import type { AgentTask } from "@multica/core/types";
+import { ContentEditor, type ContentEditorRef } from "../../editor";
+import { EditorOverlayOwnerContext } from "../../editor/overlay-owner";
+import { useComposerSubmit } from "../../editor/use-composer-submit";
+import { useUploadGate } from "../../editor/use-upload-gate";
+import { useT } from "../../i18n";
+import { commentTriggerPreviewSignature, useCommentTriggerPreview } from "../hooks/use-comment-trigger-preview";
+import { useRecipientActions } from "../hooks/use-recipient-actions";
+import { CommentTriggerChips } from "./comment-trigger-chips";
+import { useStopRunsBeforeSend } from "./use-stop-runs-before-send";
+
+export interface AnnotationReplyOptions {
+ onSubmit: (sourceId: string, content: string, suppressAgentIds?: string[], steerTaskIds?: string[]) => Promise<string | boolean>;
+ onAccepted?: (commentId: string) => void;
+ steerByDefault: (task: AgentTask) => boolean;
+}
+
+export function AnnotationComposer({
+ issueId, owner, annotation, existing, number, parentId, editorRef, reply,
+ sourceMissing, sourceChanged, canSave, isSourceAvailable,
+ onChange, onSave, onRemove, onBusyChange, onAccepted,
+}: {
+ issueId: string;
+ owner: string;
+ annotation: ReplyAnnotation;
+ existing: boolean;
+ number: number;
+ parentId?: string;
+ editorRef: RefObject<ContentEditorRef | null>;
+ reply?: AnnotationReplyOptions;
+ sourceMissing: boolean;
+ sourceChanged: boolean;
+ canSave: boolean;
+ isSourceAvailable: () => boolean;
+ onChange: (note: string) => void;
+ onSave: (note: string) => void;
+ onRemove?: () => void;
+ onBusyChange: (busy: boolean) => void;
+ onAccepted: () => void;
+}) {
+ const { t } = useT("issues");
+ const [initialNote] = useState(annotation.note);
+ const direct = !existing && !!reply;
+ const composed = composeSelectionReply(annotation, annotation.note);
+ const preview = useCommentTriggerPreview({ issueId, parentId, content: direct ? composed : "" });
+ const { recipients, routing, setAction } = useRecipientActions({
+ issueId, agents: preview.agents, allowSteer: true,
+ steerByDefault: reply?.steerByDefault ?? (() => false), resetKey: `${issueId}:${annotation.id}`,
+ });
+ const stopRuns = useStopRunsBeforeSend(issueId);
+ const uploadGate = useUploadGate(editorRef);
+ const acceptedId = useRef<string | null>(null);
+ const mounted = useRef(true);
+ useEffect(() => {
+ mounted.current = true;
+ return () => { mounted.current = false; };
+ }, []);
+ const { submitting, submit } = useComposerSubmit({
+ editorRef, uploadGate,
+ normalize: (raw) => direct && isSourceAvailable() ? composeSelectionReply(annotation, raw) : "",
+ onSubmit: async (content) => {
+ if (!reply || !isSourceAvailable()) return false;
+ onBusyChange(true);
+ try {
+ const previewMatches = preview.isCurrent && commentTriggerPreviewSignature(content) === commentTriggerPreviewSignature(composed);
+ if (!(await stopRuns(previewMatches ? routing.restartTaskIds : []))) return false;
+ const result = await reply.onSubmit(annotation.sourceCommentId, content,
+ routing.suppressAgentIds.length ? routing.suppressAgentIds : undefined,
+ routing.steerTaskIds.length ? routing.steerTaskIds : undefined);
+ acceptedId.current = typeof result === "string" ? result : null;
+ return !!result;
+ } finally {
+ onBusyChange(false);
+ }
+ },
+ onAccepted: () => {
+ if (!mounted.current) return;
+ onAccepted();
+ if (acceptedId.current) reply?.onAccepted?.(acceptedId.current);
+ },
+ });
+ const save = () => {
+ if (submitting || !canSave) return;
+ const note = editorRef.current?.getMarkdown() ?? "";
+ if (note.trim()) onSave(note);
+ };
+ const saveLabel = t(($) => existing ? $.reply.annotations.save : $.reply.annotations.confirm_add);
+ const copyNote = async () => {
+ const note = editorRef.current?.getMarkdown() ?? "";
+ if (await copyText(note)) toast.success(t(($) => $.reply.annotations.note_copied));
+ else toast.error(t(($) => $.reply.annotations.note_copy_failed));
+ };
+
+ return <EditorOverlayOwnerContext.Provider value={owner}>
+ <div className="flex w-96 max-w-[calc(100vw-26px)] flex-col gap-1" aria-busy={submitting || undefined}>
+ <div className={submitting ? "pointer-events-none opacity-60" : undefined} inert={submitting || undefined}>
+ <ContentEditor ref={editorRef} defaultValue={initialNote}
+ ariaLabel={t(($) => $.reply.annotations.note_label)}
+ placeholder={t(($) => $.reply.annotations.note_placeholder)}
+ className="min-h-8 max-h-32 overflow-y-auto px-2 py-1.5"
+ currentIssueId={issueId} showBubbleMenu={false} debounceMs={100}
+ onUpdate={onChange} onSubmit={direct ? submit : save} />
+ </div>
+ {sourceMissing && <div className="px-2">
+ <p role="alert" className="text-caption text-destructive">{t(($) => $.reply.annotations.direct_target_deleted)}</p>
+ <Button size="sm" variant="ghost" disabled={!annotation.note.trim() || submitting}
+ onClick={copyNote}>{t(($) => $.reply.annotations.copy_note)}</Button>
+ </div>}
+ {!sourceMissing && sourceChanged && <p className="px-2 text-caption text-muted-foreground">{t(($) => $.reply.annotations.source_changed)}</p>}
+ {!canSave && <p className="px-2 text-caption text-muted-foreground">{t(($) => $.reply.annotations.count_limit, { count: MAX_REPLY_ANNOTATIONS })}</p>}
+ <div className="flex flex-wrap items-center gap-1 px-1 pb-1" inert={submitting || undefined}>
+ {existing && onRemove && <IconButton variant="ghost" size="icon-sm"
+ className="text-muted-foreground hover:text-destructive" label={t(($) => $.reply.annotations.remove, { number })}
+ disabled={submitting} onClick={onRemove}><Trash2 /></IconButton>}
+ {direct && <div className="min-w-0 flex-1">
+ <CommentTriggerChips recipients={recipients} blocked={preview.blocked}
+ hasAllMembersMention={preview.hasAllMembersMention} draftContent={composed} onActionChange={setAction} />
+ </div>}
+ <div className="ml-auto flex items-center gap-1">
+ <Button size="sm" variant={direct ? "ghost" : "default"} className={direct ? "text-muted-foreground" : undefined}
+ disabled={!annotation.note.trim() || !canSave || submitting}
+ onClick={save}>{saveLabel}</Button>
+ {direct && <Button size="sm" variant={routing.restartTaskIds.length ? "destructive" : "default"}
+ disabled={!composed || sourceMissing || submitting} onClick={submit} aria-busy={submitting || undefined}>
+ {submitting && <Loader2 className="animate-spin" />}
+ {t(($) => routing.restartTaskIds.length ? $.comment.restart_send
+ : parentId ? $.reply.annotations.direct_reply : $.reply.annotations.direct_comment)}
+ </Button>}
+ </div>
+ </div>
+ </div>
+ </EditorOverlayOwnerContext.Provider>;
+}
diff --git a/packages/views/issues/components/annotation-reply-interactions.test.tsx b/packages/views/issues/components/annotation-reply-interactions.test.tsx
new file mode 100644
index 0000000000..a438e9b01d
--- /dev/null
+++ b/packages/views/issues/components/annotation-reply-interactions.test.tsx
@@ -0,0 +1,145 @@
+import { act, fireEvent, screen, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { useState } from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { Editor } from "@tiptap/core";
+import { useCommentDraftStore } from "@multica/core/issues/stores";
+import { renderWithI18n } from "../../test/i18n";
+import { useCommentAnnotations } from "./use-comment-annotations";
+import { toast } from "sonner";
+
+vi.mock("@multica/core/api", async (original) => {
+ const actual = await original<typeof import("@multica/core/api")>();
+ return { ...actual, api: { ...actual.api,
+ previewCommentTriggers: vi.fn(async () => ({ agents: [], blocked: [] })),
+ listTasksByIssue: vi.fn(async () => []),
+ } };
+});
+
+const writeText = vi.fn(async (_text: string) => {});
+
+const draftKey = "reply:issue:root" as const;
+function Fixture({ deleted = false, onSubmit = async () => false }: {
+ deleted?: boolean; onSubmit?: (sourceId: string, content: string) => Promise<boolean>;
+}) {
+ const [client] = useState(() => new QueryClient({ defaultOptions: { queries: { retry: false } } }));
+ const annotations = useCommentAnnotations({ issueId: "issue", draftKey, enabled: true,
+ sources: [{ id: "root", name: "Root" }, ...(!deleted ? [{ id: "child", name: "Child" }] : [])],
+ reply: { onSubmit, steerByDefault: () => false },
+ });
+ return <QueryClientProvider client={client}><div ref={annotations.cardRef} {...annotations.captureProps}>
+ {annotations.popup}
+ <div data-comment-content="root" tabIndex={0}>Root text</div>
+ {!deleted && <div data-comment-content="child" tabIndex={0}>Child text</div>}
+ </div></QueryClientProvider>;
+}
+
+function selectText(container: HTMLElement, id: string) {
+ const source = container.querySelector<HTMLElement>(`[data-comment-content="${id}"]`)!;
+ fireEvent.pointerDown(source);
+ const range = document.createRange();
+ range.selectNodeContents(source);
+ act(() => { window.getSelection()!.removeAllRanges(); window.getSelection()!.addRange(range); });
+ fireEvent.pointerUp(source);
+ return source;
+}
+
+async function typeNote(value: string) {
+ const input = await screen.findByRole("textbox", { name: "Comment" });
+ await act(async () => { (input as HTMLElement & { editor: Editor }).editor.commands.setContent(value); });
+ await waitFor(() => expect(screen.getByRole("button", { name: "Reply" })).toBeEnabled());
+ return input;
+}
+
+beforeEach(() => {
+ useCommentDraftStore.setState({ drafts: {} });
+ writeText.mockClear();
+ Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } });
+ Object.defineProperty(document.documentElement, "clientWidth", { configurable: true, value: 1024 });
+ Object.defineProperty(document.documentElement, "clientHeight", { configurable: true, value: 768 });
+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue(new DOMRect(10, 10, 600, 400));
+ Range.prototype.getBoundingClientRect = function () {
+ return this.collapsed ? new DOMRect() : new DOMRect(10, 10, 120, 20);
+ };
+ Range.prototype.getClientRects = function () {
+ return [this.getBoundingClientRect()] as unknown as DOMRectList;
+ };
+});
+
+describe("selection replies with the real ContentEditor", () => {
+ it("sends through the real ContentEditor", async () => {
+ const onSubmit = vi.fn(async () => true);
+ const { container } = renderWithI18n(<Fixture onSubmit={onSubmit} />);
+ selectText(container, "child");
+ fireEvent.click(await screen.findByRole("button", { name: "Add to reply" }));
+ await typeNote("Please revise");
+ fireEvent.click(screen.getByRole("button", { name: "Reply" }));
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledWith("child", "> Child text\n\nPlease revise", undefined, undefined));
+ });
+
+ it.each([false, true])("copies the deleted target's latest note before leaving (quota full: %s)", async (full) => {
+ if (full) {
+ for (let i = 0; i < 20; i++) useCommentDraftStore.getState().addAnnotation(draftKey, {
+ id: `saved-${i}`, sourceCommentId: "root", sourceActorName: "Root",
+ quote: "Root", start: i, prefix: "", suffix: " text", note: `Saved ${i}`,
+ });
+ }
+ const view = renderWithI18n(<Fixture />);
+ selectText(view.container, "child");
+ fireEvent.click(await screen.findByRole("button", { name: "Add to reply" }));
+ const input = await typeNote("Do not lose this instruction");
+ view.rerender(<Fixture deleted />);
+ expect(await screen.findByRole("alert")).toHaveTextContent("Copy your note before selecting another comment");
+ expect(screen.getByRole("button", { name: "Reply" })).toBeDisabled();
+ if (full) expect(screen.getByRole("button", { name: "Add annotation" })).toBeDisabled();
+ // Copy reads the editor synchronously, including edits not yet debounced.
+ await act(async () => { (input as HTMLElement & { editor: Editor }).editor.commands.setContent("Latest instruction"); });
+ const copy = screen.getByRole("button", { name: "Copy note" });
+ fireEvent.pointerDown(copy);
+ fireEvent.click(copy);
+ await waitFor(() => expect(writeText).toHaveBeenCalledWith("Latest instruction"));
+ expect(input).toBeInTheDocument();
+ selectText(view.container, "root");
+ fireEvent.click(await screen.findByRole("button", { name: "Add to reply" }));
+ await act(async () => { (screen.getByRole("textbox", { name: "Comment" }) as HTMLElement & { editor: Editor }).editor.commands.setContent(writeText.mock.calls[0]![0]); });
+ expect(screen.getByRole("textbox", { name: "Comment" })).toHaveTextContent("Latest instruction");
+ });
+
+ it("keeps the note and shows manual recovery when clipboard copying fails", async () => {
+ Object.defineProperty(navigator, "clipboard", { configurable: true, value: undefined });
+ Object.defineProperty(document, "execCommand", { configurable: true, value: vi.fn(() => false) });
+ const error = vi.spyOn(toast, "error");
+ const view = renderWithI18n(<Fixture />);
+ selectText(view.container, "child");
+ fireEvent.click(await screen.findByRole("button", { name: "Add to reply" }));
+ const input = await typeNote("Recover manually");
+ view.rerender(<Fixture deleted />);
+ const copy = await screen.findByRole("button", { name: "Copy note" });
+ fireEvent.pointerDown(copy);
+ copy.focus();
+ fireEvent.click(copy);
+ await waitFor(() => expect(error).toHaveBeenCalledWith("Could not copy note. Select and copy the text manually."));
+ expect(input).toBeInTheDocument();
+ expect(input).toHaveTextContent("Recover manually");
+ });
+
+ it.each([false, true])("keeps the unsent note when copying its hovered link (clipboard fallback: %s)", async (fallback) => {
+ if (fallback) {
+ Object.defineProperty(navigator, "clipboard", { configurable: true, value: undefined });
+ Object.defineProperty(document, "execCommand", { configurable: true, value: vi.fn(() => true) });
+ }
+ const view = renderWithI18n(<Fixture />);
+ selectText(view.container, "child");
+ fireEvent.click(await screen.findByRole("button", { name: "Add to reply" }));
+ const input = await typeNote('<p>Please inspect <a href="https://example.com">this page</a></p>');
+ const link = input.querySelector("a")!;
+ fireEvent.mouseOver(link);
+ const copy = await screen.findByRole("button", { name: "Copy link" });
+ fireEvent.pointerDown(copy);
+ copy.focus();
+ fireEvent.click(copy);
+ await waitFor(() => expect(fallback ? document.execCommand : writeText).toHaveBeenCalledWith(fallback ? "copy" : "https://example.com"));
+ expect(input).toBeInTheDocument();
+ expect(input).toHaveTextContent("Please inspect this page");
+ });
+});
diff --git a/packages/views/issues/components/comment-card-edit-gate.test.tsx b/packages/views/issues/components/comment-card-edit-gate.test.tsx
index 57a9242fa1..fd3eac03e5 100644
--- a/packages/views/issues/components/comment-card-edit-gate.test.tsx
+++ b/packages/views/issues/components/comment-card-edit-gate.test.tsx
@@ -78,6 +78,7 @@ vi.mock("../../editor", async () => ({
onUploadingChange,
onSubmit,
placeholder,
+ ariaLabel,
}: {
defaultValue?: string;
onUpdate?: (markdown: string) => void;
@@ -85,6 +86,7 @@ vi.mock("../../editor", async () => ({
onUploadingChange?: (uploading: boolean) => void;
onSubmit?: () => void;
placeholder?: string;
+ ariaLabel?: string;
},
ref: Ref<unknown>,
) {
@@ -133,6 +135,7 @@ vi.mock("../../editor", async () => ({
}));
return (
<textarea
+ aria-label={ariaLabel}
ref={textareaRef}
data-testid="editor"
defaultValue={defaultValue}
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index ffdbd39a59..3b65cd5fa9 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -1043,9 +1043,20 @@ function CommentCardImpl({
// A deleted target's tombstone is as gone as a removed row.
const replyTargetMissing = !!replyTarget && replyTargetId !== entry.id
&& !replies.some((r) => r.id === replyTargetId && !isDeletedComment(r));
+ // A reply here goes into the running turn of a run that belongs to this
+ // thread by default; another thread's turn is only reached by choice.
+ const steerThreadRunByDefault = useCallback(
+ (task: AgentTask) => runs.some((run) => run.task.id === task.id),
+ [runs],
+ );
const annotation = useCommentAnnotations({
+ issueId,
+ reply: {
+ onSubmit: (sourceId, content, suppressAgentIds, steerTaskIds) => onReply(sourceId, content, undefined, suppressAgentIds, steerTaskIds),
+ onAccepted: onReplyAccepted, steerByDefault: steerThreadRunByDefault,
+ },
draftKey: `reply:${issueId}:${entry.id}`,
- sources: [entry, ...replies].filter((e) => e.type === "comment")
+ sources: [entry, ...replies].filter((e) => e.type === "comment" && !isDeletedComment(e))
.map((e) => ({ id: e.id, name: e.actor_name || getActorName(e.actor_type, e.actor_id), revision: e.revision })),
enabled: !!currentUserId,
onAdded: () => { if (replyFolded) onResolvedExpandChange?.(entry.id, true); },
@@ -1065,12 +1076,6 @@ function CommentCardImpl({
const canEditEntry = receipts.length === 0 && (isOwn || (canModerate && entry.actor_type === "member"));
const canDeleteEntry = !receipts.some(isSupplementInFlight) && (isOwn || canModerate);
const [confirmDelete, setConfirmDelete] = useState(false);
- // A reply here goes into the running turn of a run that belongs to this
- // thread by default; another thread's turn is only reached by choice.
- const steerThreadRunByDefault = useCallback(
- (task: AgentTask) => runs.some((run) => run.task.id === task.id),
- [runs],
- );
const allNestedReplies = replies;
// What the thread shows. Tombstones are excluded from display and counts but
diff --git a/packages/views/issues/components/comment-selection-bubble.tsx b/packages/views/issues/components/comment-selection-bubble.tsx
index 2cc5f9e061..876bcdc8ce 100644
--- a/packages/views/issues/components/comment-selection-bubble.tsx
+++ b/packages/views/issues/components/comment-selection-bubble.tsx
@@ -5,7 +5,7 @@ import { createPortal } from "react-dom";
import { autoUpdate, computePosition, flip, hide, offset, shift } from "@floating-ui/dom";
/** Match the description's EditorBubbleMenu geometry for readonly selections. */
-export function CommentSelectionBubble({ range, source, children, owner, markerRanges, onPositioned }: {
+export function CommentSelectionBubble({ range, source, children, owner, markerRanges, onPositioned, keepVisibleWhenDetached = false }: {
range: Range;
source: HTMLElement;
children: ReactNode;
@@ -13,6 +13,7 @@ export function CommentSelectionBubble({ range, source, children, owner, markerR
markerRanges?: Range[];
/** Called after the popup has a visible, usable position. */
onPositioned?: () => void;
+ keepVisibleWhenDetached?: boolean;
}) {
const ref = useRef<HTMLDivElement>(null);
const marker = !!markerRanges;
@@ -27,6 +28,8 @@ export function CommentSelectionBubble({ range, source, children, owner, markerR
let revision = 0;
const update = () => {
const currentRevision = ++revision;
+ // Keep an open note recoverable if realtime removes or replaces its source.
+ if (keepVisibleWhenDetached && (!source.isConnected || !range.startContainer.isConnected)) return;
// Keep visibility tied to the real quote, not a zero-width point outside
// the scroll container. Markers move horizontally but never clamp/flip
// vertically: doing so piles unrelated annotations at the viewport edge.
@@ -63,10 +66,10 @@ export function CommentSelectionBubble({ range, source, children, owner, markerR
// resizing its source element or triggering a window resize.
const cleanup = autoUpdate(anchor, element, update, { animationFrame: true });
return () => { active = false; cleanup(); };
- }, [range, source, marker, markerRanges, onPositioned]);
+ }, [range, source, marker, markerRanges, onPositioned, keepVisibleWhenDetached]);
return createPortal(
- <div ref={ref} data-reply-annotation-overlay={owner}
+ <div ref={ref} data-reply-annotation-overlay={owner} data-editor-overlay-owner={owner}
style={{ position: "fixed", zIndex: marker ? 20 : 50, visibility: "hidden", width: "max-content" }}>
{children}
</div>,
diff --git a/packages/views/issues/components/comment-trigger-chips.tsx b/packages/views/issues/components/comment-trigger-chips.tsx
index 3197abeb6f..ac0c3f06cc 100644
--- a/packages/views/issues/components/comment-trigger-chips.tsx
+++ b/packages/views/issues/components/comment-trigger-chips.tsx
@@ -27,6 +27,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@multica/ui/components/
import { cn } from "@multica/ui/lib/utils";
import { AgentStatusDot } from "../../common/actor-avatar";
import { useT } from "../../i18n";
+import { useEditorOverlayOwner } from "../../editor/overlay-owner";
import { blockedReasonLabel, blockedShortReasonLabel } from "../blocked-trigger-copy";
import type { RecipientEntry } from "../hooks/use-recipient-actions";
@@ -245,12 +246,13 @@ function RecipientActionMenu({
trigger: ReactElement;
t: IssuesT;
}) {
+ const overlayOwner = useEditorOverlayOwner();
const presenceLine = useTriggerPresenceLine(entry.agent.id, t);
const state = stateLabel(entry.state, t);
return (
<DropdownMenu>
<DropdownMenuTrigger render={trigger} />
- <DropdownMenuContent side="top" align="start" className="w-80">
+ <DropdownMenuContent side="top" align="start" className="w-80" data-editor-overlay-owner={overlayOwner}>
<div className="flex min-w-0 items-center gap-2 px-1.5 pt-1 pb-1.5 text-caption text-muted-foreground">
<TriggerAgentAvatar agent={entry.agent} suppressed={false} />
<span className="min-w-0 truncate font-medium text-foreground">{entry.agent.name}</span>
@@ -324,6 +326,7 @@ function MultiRecipientChip({
onActionChange: (agentId: string, action: RecipientAction) => void;
t: IssuesT;
}) {
+ const overlayOwner = useEditorOverlayOwner();
const [open, setOpen] = useState(false);
const [tooltipHover, setTooltipHover] = useState(false);
const activeCount = recipients.filter((r) => r.action !== "skip").length;
@@ -388,7 +391,7 @@ function MultiRecipientChip({
{t(($) => $.comment.trigger_click_to_manage)}
</TooltipContent>
</Tooltip>
- <PopoverContent align="start" className="w-80 p-2">
+ <PopoverContent align="start" className="w-80 p-2" data-editor-overlay-owner={overlayOwner}>
<div className="px-1.5 pb-1 text-caption font-medium text-muted-foreground">
{t(($) => $.comment.trigger_preview_title)}
</div>
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 4a2ec188d3..9f6230e12a 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -1639,6 +1639,12 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
useMarkIssueInboxReadWhileViewing(wsId, issue?.id ?? "", readsInbox);
const descriptionSourceId = `description:${id}`;
const descriptionAnnotations = useCommentAnnotations({
+ issueId: id,
+ reply: {
+ onSubmit: (_sourceId, content, suppressAgentIds, steerTaskIds) => submitComment(content, undefined, suppressAgentIds, steerTaskIds),
+ onAccepted: (commentId) => scrollToTimelineBottom(commentId),
+ steerByDefault: (task) => !task.trigger_comment_id,
+ },
draftKey: `new:${id}`,
sources: [{ id: descriptionSourceId, name: "Description", revision: issue?.revision }],
enabled: !!user && !!issue,
diff --git a/packages/views/issues/components/use-comment-annotations.test.tsx b/packages/views/issues/components/use-comment-annotations.test.tsx
index b7c5116168..e6fbabd8e8 100644
--- a/packages/views/issues/components/use-comment-annotations.test.tsx
+++ b/packages/views/issues/components/use-comment-annotations.test.tsx
@@ -4,39 +4,77 @@ import { useCommentDraftStore } from "@multica/core/issues/stores";
import type { TimelineEntry } from "@multica/core/types";
import { renderWithI18n } from "../../test/i18n";
import { useCommentAnnotations } from "./use-comment-annotations";
-import { Profiler } from "react";
+import { Profiler, useState } from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { AnnotationReplyOptions } from "./annotation-composer";
import { toast } from "sonner";
vi.mock("sonner", () => ({ toast: { error: vi.fn() } }));
+const previewCommentTriggers = vi.hoisted(() => vi.fn(async () => ({ agents: [], blocked: [] })));
+vi.mock("@multica/core/api", async (original) => {
+ const actual = await original<typeof import("@multica/core/api")>();
+ return { ...actual, api: { ...actual.api, previewCommentTriggers, listTasksByIssue: vi.fn(async () => []) } };
+});
+vi.mock("../../editor/content-editor", async () => {
+ const { forwardRef, useRef, useImperativeHandle } = await import("react");
+ return { ContentEditor: forwardRef(function Editor({ defaultValue, ariaLabel, onUpdate, onSubmit }: {
+ defaultValue?: string; ariaLabel?: string; onUpdate?: (value: string) => void; onSubmit?: () => void;
+ }, ref) {
+ const input = useRef<HTMLTextAreaElement>(null);
+ useImperativeHandle(ref, () => ({
+ getMarkdown: () => input.current?.value ?? "",
+ focus: () => input.current?.focus(), hasActiveUploads: () => false,
+ }));
+ return <textarea ref={input} aria-label={ariaLabel} defaultValue={defaultValue}
+ onChange={(event) => onUpdate?.(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && (event.metaKey || event.ctrlKey) && !event.nativeEvent.isComposing && event.keyCode !== 229) {
+ event.preventDefault(); onSubmit?.();
+ }
+ }} />;
+ }) };
+});
+
+
const entry: TimelineEntry = { type: "comment", id: "root", actor_type: "agent", actor_id: "emacs", content: "Selected text", created_at: "2026-09-10T00:00:00Z" };
const key = "reply:issue:root" as const;
-function Fixture({ actorType = "agent", sourceKey = "initial" }: { actorType?: string; sourceKey?: string }) {
+function Fixture({ actorType = "agent", sourceKey = "initial", onSubmit, child = false, deleted = false }: {
+ actorType?: string; sourceKey?: string; onSubmit?: AnnotationReplyOptions["onSubmit"]; child?: boolean; deleted?: boolean;
+}) {
+ const [client] = useState(() => new QueryClient({ defaultOptions: { queries: { retry: false } } }));
const annotation = useCommentAnnotations({
- draftKey: key, sources: [{ id: entry.id, name: actorType }], enabled: true,
+ issueId: "issue", draftKey: key,
+ sources: [{ id: entry.id, name: actorType }, ...(child && !deleted ? [{ id: "child", name: "Child author" }] : [])], enabled: true,
+ reply: onSubmit ? { onSubmit, steerByDefault: () => false } : undefined,
});
- return <div ref={annotation.cardRef} {...annotation.captureProps}>
+ return <QueryClientProvider client={client}><div ref={annotation.cardRef} {...annotation.captureProps}>
{annotation.popup}
<div key={sourceKey} data-comment-content="root" tabIndex={0}>Selected text</div>
- </div>;
+ {child && !deleted && <div data-comment-content="child" tabIndex={0}>Other text</div>}
+ </div></QueryClientProvider>;
}
-function DescriptionFixture({ issueId = "issue", loaded = true }: { issueId?: string; loaded?: boolean }) {
+function DescriptionFixture({ issueId = "issue", loaded = true, onSubmit }: {
+ issueId?: string; loaded?: boolean; onSubmit?: AnnotationReplyOptions["onSubmit"];
+}) {
+ const [client] = useState(() => new QueryClient({ defaultOptions: { queries: { retry: false } } }));
const sourceId = `description:${issueId}`;
const annotations = useCommentAnnotations({
+ issueId, reply: onSubmit ? { onSubmit, steerByDefault: () => false } : undefined,
draftKey: `new:${issueId}`, sources: [{ id: sourceId, name: "Description" }], enabled: loaded, editable: true,
});
if (!loaded) return null;
- return <div ref={annotations.cardRef} {...annotations.captureProps}>
+ return <QueryClientProvider client={client}><div ref={annotations.cardRef} {...annotations.captureProps}>
{annotations.popup}
<div data-comment-content={sourceId}><div contentEditable suppressContentEditableWarning>Selected text</div></div>
<button onMouseDown={(event) => event.preventDefault()} onClick={annotations.addSelection}>Add to comment</button>
- </div>;
+ </div></QueryClientProvider>;
}
-function selectText(container: HTMLElement, input: "mouse" | "keyboard" = "mouse") {
- const source = container.querySelector<HTMLElement>("[data-comment-content]")!;
+function selectText(container: HTMLElement, input: "mouse" | "keyboard" = "mouse", selector = "[data-comment-content]") {
+ const source = container.querySelector<HTMLElement>(selector)!;
if (input === "mouse") {
fireEvent.pointerDown(source, { pointerType: "mouse", button: 0 });
fireEvent.mouseDown(source, { button: 0 });
@@ -61,6 +99,7 @@ function selectText(container: HTMLElement, input: "mouse" | "keyboard" = "mouse
}
beforeEach(() => {
+ previewCommentTriggers.mockClear();
useCommentDraftStore.setState({ drafts: {} });
// jsdom has no layout; give Floating UI a viewport for its real hide middleware.
Object.defineProperty(document.documentElement, "clientWidth", { configurable: true, value: 1024 });
@@ -71,6 +110,113 @@ beforeEach(() => {
});
describe("selection to reply", () => {
+ it("sends only the selected child quote and new instruction, preserving the existing draft", async () => {
+ const store = useCommentDraftStore.getState();
+ store.setDraft(key, "Keep the overall draft");
+ store.addAnnotation(key, { id: "saved", sourceCommentId: "root", sourceActorName: "Root author",
+ quote: "Selected text", note: "Keep the first annotation", start: 0, prefix: "", suffix: "" });
+ const draft = useCommentDraftStore.getState().drafts[key];
+ const onSubmit = vi.fn(async () => "posted");
+ const { container } = renderWithI18n(<Fixture onSubmit={onSubmit} child />);
+ selectText(container, "mouse", '[data-comment-content="child"]');
+ fireEvent.click(await screen.findByRole("button", { name: "Add to reply" }));
+ const mention = "[@Agent](mention://agent/11111111-1111-1111-1111-111111111111)";
+ fireEvent.change(await screen.findByRole("textbox", { name: "Comment" }), { target: { value: `${mention} Please revise.` } });
+ await waitFor(() => expect(previewCommentTriggers).toHaveBeenCalledWith("issue", `> Other text\n\n${mention} Please revise.`, "child", undefined));
+ fireEvent.click(screen.getByRole("button", { name: "Reply" }));
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledWith("child", `> Other text\n\n${mention} Please revise.`, undefined, undefined));
+ await waitFor(() => expect(screen.queryByRole("textbox", { name: "Comment" })).not.toBeInTheDocument());
+ expect(useCommentDraftStore.getState().drafts[key]).toBe(draft);
+ });
+
+ it("previews description replies without a comment parent", async () => {
+ const onSubmit = vi.fn(async () => "posted");
+ const { container } = renderWithI18n(<DescriptionFixture onSubmit={onSubmit} />);
+ selectText(container);
+ fireEvent.click(screen.getByRole("button", { name: "Add to comment" }));
+ fireEvent.change(await screen.findByRole("textbox", { name: "Comment" }), { target: { value: "Please explain" } });
+ await waitFor(() => expect(previewCommentTriggers).toHaveBeenCalledWith("issue", "> Selected text\n\nPlease explain", undefined, undefined));
+ fireEvent.click(screen.getByRole("button", { name: "Post comment" }));
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledWith("description:issue", "> Selected text\n\nPlease explain", undefined, undefined));
+ });
+
+ it("locks dismissal and duplicate submissions in flight, then keeps a failed note for retry", async () => {
+ let finish!: (result: boolean) => void;
+ const onSubmit = vi.fn(() => new Promise<boolean>((resolve) => { finish = resolve; }));
+ const { container } = renderWithI18n(<Fixture onSubmit={onSubmit} />);
+ selectText(container);
+ fireEvent.click(await screen.findByRole("button", { name: "Add to reply" }));
+ const note = await screen.findByRole("textbox", { name: "Comment" });
+ fireEvent.change(note, { target: { value: "Keep on failure" } });
+ const send = screen.getByRole("button", { name: "Reply" });
+ fireEvent.click(send);
+ fireEvent.click(send);
+ fireEvent.pointerDown(document.body);
+ fireEvent.keyDown(note, { key: "Escape" });
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1));
+ expect(note).toBeInTheDocument();
+ expect(send).toBeDisabled();
+ await act(async () => { finish(false); });
+ expect(note).toHaveValue("Keep on failure");
+ expect(send).toBeEnabled();
+ onSubmit.mockResolvedValueOnce(true);
+ fireEvent.click(send);
+ await waitFor(() => expect(screen.queryByRole("textbox", { name: "Comment" })).not.toBeInTheDocument());
+ expect(onSubmit).toHaveBeenCalledTimes(2);
+ });
+
+ it("keeps owned portal controls open and lets their first Escape close only the nested control", async () => {
+ const { container } = renderWithI18n(<Fixture onSubmit={vi.fn(async () => false)} />);
+ selectText(container);
+ fireEvent.click(await screen.findByRole("button", { name: "Add to reply" }));
+ const note = await screen.findByRole("textbox", { name: "Comment" });
+ const portal = document.createElement("button");
+ portal.setAttribute("data-editor-overlay-owner", key);
+ document.body.append(portal);
+ try {
+ fireEvent.pointerDown(portal); portal.focus();
+ fireEvent.keyDown(portal, { key: "Escape" });
+ expect(note).toBeInTheDocument();
+ note.focus();
+ // Tiptap's blur shortcut handles Escape before it bubbles to the host.
+ const escape = new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true });
+ escape.preventDefault();
+ fireEvent(note, escape);
+ expect(note).not.toBeInTheDocument();
+ } finally { portal.remove(); }
+ });
+
+ it("keeps a note visible and disables sending when its selected comment is deleted", async () => {
+ const onSubmit = vi.fn(async () => "posted");
+ const { container, rerender } = renderWithI18n(<Fixture onSubmit={onSubmit} child />);
+ selectText(container, "mouse", '[data-comment-content="child"]');
+ fireEvent.click(await screen.findByRole("button", { name: "Add to reply" }));
+ const note = await screen.findByRole("textbox", { name: "Comment" });
+ fireEvent.change(note, { target: { value: "Keep this instruction" } });
+ rerender(<Fixture onSubmit={onSubmit} child deleted />);
+ expect(await screen.findByRole("alert")).toHaveTextContent("reply target was deleted");
+ expect(note).toBeVisible();
+ expect(note).toHaveValue("Keep this instruction");
+ expect(screen.getByRole("button", { name: "Reply" })).toBeDisabled();
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+
+ it("allows a direct reply when the batch annotation quota is full", async () => {
+ for (let i = 0; i < 20; i++) useCommentDraftStore.getState().addAnnotation(key, {
+ id: `saved-${i}`, sourceCommentId: "root", sourceActorName: "Author", quote: `Other quote ${i}`,
+ note: "Keep saved", start: i, prefix: "", suffix: "",
+ });
+ const onSubmit = vi.fn(async () => "posted");
+ const { container } = renderWithI18n(<Fixture onSubmit={onSubmit} />);
+ selectText(container);
+ fireEvent.click(await screen.findByRole("button", { name: "Add to reply" }));
+ fireEvent.change(await screen.findByRole("textbox", { name: "Comment" }), { target: { value: "Direct instruction" } });
+ expect(screen.getByRole("button", { name: "Add annotation" })).toBeDisabled();
+ fireEvent.click(screen.getByRole("button", { name: "Reply" }));
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1));
+ expect(useCommentDraftStore.getState().getAnnotations(key)).toHaveLength(20);
+ });
+
it.each([false, true])("does not rerender the host when unannotated source text changes (description: %s)", async (description) => {
const onRender = vi.fn();
const { container } = renderWithI18n(<Profiler id="host" onRender={onRender}>
@@ -241,7 +387,7 @@ describe("selection to reply", () => {
expect(useCommentDraftStore.getState().getAnnotations(draftKey)).toHaveLength(1);
});
- it.each([false, true])("uses Enter to confirm and Shift + Enter for newlines (description: %s)", async (description) => {
+ it.each([false, true])("uses the editor submit shortcut and keeps plain Enter for newlines (description: %s)", async (description) => {
const draftKey = description ? "new:issue" as const : key;
const { container } = renderWithI18n(description ? <DescriptionFixture /> : <Fixture />);
selectText(container);
@@ -258,7 +404,7 @@ describe("selection to reply", () => {
fireEvent.keyDown(input, { key: "Enter", keyCode: 229 });
expect(input).toBeInTheDocument();
fireEvent.change(input, { target: { value: "First line\nSecond line" } });
- fireEvent.keyDown(input, { key: "Enter" });
+ fireEvent.keyDown(input, { key: "Enter", metaKey: true });
expect(screen.queryByRole("textbox", { name: "Comment" })).not.toBeInTheDocument();
expect(useCommentDraftStore.getState().getAnnotations(draftKey)[0]?.note).toBe("First line\nSecond line");
});
diff --git a/packages/views/issues/components/use-comment-annotations.tsx b/packages/views/issues/components/use-comment-annotations.tsx
index 7147e9e280..0340fe65af 100644
--- a/packages/views/issues/components/use-comment-annotations.tsx
+++ b/packages/views/issues/components/use-comment-annotations.tsx
@@ -1,7 +1,7 @@
"use client";
import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
-import { MessageSquarePlus, Trash2 } from "@multica/ui/icons";
+import { MessageSquarePlus } from "@multica/ui/icons";
import { toast } from "sonner";
import { isImeComposing } from "@multica/core/utils";
import { Button } from "@multica/ui/components/ui/button";
@@ -11,21 +11,26 @@ import { MAX_ANNOTATION_QUOTE_LENGTH, MAX_REPLY_ANNOTATIONS, type ReplyAnnotatio
import { useT } from "../../i18n";
import { annotationRange, captureCommentSelection, findAnnotationSource } from "./comment-annotation-selection";
import { CommentSelectionBubble } from "./comment-selection-bubble";
+import { AnnotationComposer, type AnnotationReplyOptions } from "./annotation-composer";
+import type { ContentEditorRef } from "../../editor/content-editor";
type CapturedSelection = NonNullable<ReturnType<typeof captureCommentSelection>>;
type SourceAnchor = { id: string; range: Range; root: HTMLElement };
-export function useCommentAnnotations({ draftKey, sources, enabled, onAdded, editable = false }: {
+export function useCommentAnnotations({ issueId, draftKey, sources, enabled, onAdded, editable = false, reply }: {
+ issueId: string;
draftKey: CommentDraftKey;
sources: { id: string; name: string; revision?: number }[];
enabled: boolean;
onAdded?: () => void;
/** Editable descriptions use their existing toolbar to call addSelection. */
editable?: boolean;
+ reply?: AnnotationReplyOptions;
}) {
const { t } = useT("issues");
const cardRef = useRef<HTMLDivElement>(null);
- const inputRef = useRef<HTMLTextAreaElement>(null);
+ const inputRef = useRef<ContentEditorRef>(null);
+ const submittingRef = useRef(false);
const pendingFocusId = useRef<string | null>(null);
const actionRef = useRef<HTMLButtonElement>(null);
const [selection, setSelection] = useState<CapturedSelection | null>(null);
@@ -56,6 +61,7 @@ export function useCommentAnnotations({ draftKey, sources, enabled, onAdded, edi
const highlightName = `reply-annotation-${useId().replace(/[^a-zA-Z0-9-]/g, "")}`;
const close = (restoreFocus = false) => {
+ if (submittingRef.current) return;
if (restoreFocus && selection?.root.isConnected) {
const target = editable ? selection.root.querySelector<HTMLElement>("[contenteditable=true]") ?? selection.root : selection.root;
target.focus({ preventScroll: true });
@@ -63,7 +69,7 @@ export function useCommentAnnotations({ draftKey, sources, enabled, onAdded, edi
setSelection(null); setEditor(null); setError(false);
};
const readSelection = useCallback(() => {
- if (!enabled || !cardRef.current) return null;
+ if (!enabled || submittingRef.current || !cardRef.current) return null;
const captured = captureCommentSelection(cardRef.current, window.getSelection(), editable);
return captured && sourcesRef.current.some((source) => source.id === captured.sourceCommentId) ? captured : null;
}, [enabled, editable]);
@@ -72,18 +78,23 @@ export function useCommentAnnotations({ draftKey, sources, enabled, onAdded, edi
if (captured) { setSelection(captured); setEditor(null); setError(false); }
};
- useEffect(() => { setSelection(null); setEditor(null); setError(false); }, [draftKey, enabled]);
+ useEffect(() => { setSelection(null); setEditor(null); setError(false); submittingRef.current = false; }, [draftKey, enabled]);
// Dismiss on the next press, never on the click completing the opening drag.
useEffect(() => {
if (!selection) return;
const onPointerDown = (event: PointerEvent) => {
+ if (submittingRef.current) return;
if (event.target instanceof Element &&
- event.target.closest("[data-reply-annotation-overlay]")?.getAttribute("data-reply-annotation-overlay") === draftKey) return;
+ event.target.closest("[data-editor-overlay-owner]")?.getAttribute("data-editor-overlay-owner") === draftKey) return;
setSelection(null); setEditor(null); setError(false);
};
const onKeyDown = (event: KeyboardEvent) => {
- if (event.key !== "Escape" || isImeComposing(event)) return;
+ if (event.key !== "Escape" || isImeComposing(event) || submittingRef.current) return;
+ // A nested menu owns its first Escape; its portal is outside this DOM tree.
+ if (event.target instanceof Element &&
+ event.target.closest("[data-editor-overlay-owner]")?.getAttribute("data-editor-overlay-owner") === draftKey &&
+ !event.target.closest("[data-reply-annotation-overlay]")) return;
if (selection.root.isConnected) {
const target = editable ? selection.root.querySelector<HTMLElement>("[contenteditable=true]") ?? selection.root : selection.root;
target.focus({ preventScroll: true });
@@ -91,9 +102,17 @@ export function useCommentAnnotations({ draftKey, sources, enabled, onAdded, edi
setSelection(null); setEditor(null); setError(false);
};
const onFocusIn = (event: FocusEvent) => {
+ if (submittingRef.current) return;
if (!(event.target instanceof Element) || selection.root.contains(event.target) ||
- event.target.closest("[data-reply-annotation-overlay]")?.getAttribute("data-reply-annotation-overlay") === draftKey) return;
- setSelection(null); setEditor(null); setError(false);
+ event.target.closest("[data-editor-overlay-owner]")?.getAttribute("data-editor-overlay-owner") === draftKey) return;
+ // Clipboard fallback briefly focuses a hidden textarea, then restores
+ // the owned control synchronously. Only dismiss if focus stays outside.
+ queueMicrotask(() => {
+ const target = document.activeElement;
+ if (submittingRef.current || selection.root.contains(target) ||
+ target?.closest("[data-editor-overlay-owner]")?.getAttribute("data-editor-overlay-owner") === draftKey) return;
+ setSelection(null); setEditor(null); setError(false);
+ });
};
document.addEventListener("pointerdown", onPointerDown);
document.addEventListener("keydown", onKeyDown);
@@ -108,7 +127,7 @@ export function useCommentAnnotations({ draftKey, sources, enabled, onAdded, edi
const focusNote = useCallback(() => {
if (!editingId || pendingFocusId.current !== editingId) return;
pendingFocusId.current = null;
- if (window.matchMedia("(pointer: fine)").matches) inputRef.current?.focus({ preventScroll: true });
+ if (window.matchMedia("(pointer: fine)").matches) inputRef.current?.focus();
}, [editingId]);
useEffect(() => {
@@ -138,9 +157,9 @@ export function useCommentAnnotations({ draftKey, sources, enabled, onAdded, edi
if (!saved && pending?.sourceCommentId === current.sourceCommentId) {
const root = findAnnotationSource(card, pending.sourceCommentId);
const range = root && annotationRange(root, pending, editable);
- return root && range ? { ...current, root, range } : null;
+ return root && range ? { ...current, root, range } : current;
}
- if (saved) return null;
+ if (saved) return editingRef.current?.id === saved.id ? current : null;
return current.root.isConnected && current.range.startContainer.isConnected ? current : null;
});
if (canHighlight) CSS.highlights.set(highlightName, new Highlight(...next.map((a) => a.range)));
@@ -166,6 +185,7 @@ export function useCommentAnnotations({ draftKey, sources, enabled, onAdded, edi
}, [annotations, editor?.existing, editingId, selection]);
const editAnnotation = (id: string, scrollToSource = false): boolean => {
+ if (submittingRef.current) return false;
const annotation = annotationsRef.current.find((a) => a.id === id);
const root = cardRef.current && annotation && findAnnotationSource(cardRef.current, annotation.sourceCommentId);
const range = root && annotation && annotationRange(root, annotation, editable);
@@ -180,6 +200,7 @@ export function useCommentAnnotations({ draftKey, sources, enabled, onAdded, edi
};
const add = useCallback((captured: CapturedSelection | null) => {
+ if (submittingRef.current) return false;
const source = captured && sourcesRef.current.find((e) => e.id === captured.sourceCommentId);
if (!captured || !source) {
toast.error(t(($) => $.reply.annotations.selection_failed));
@@ -188,11 +209,9 @@ export function useCommentAnnotations({ draftKey, sources, enabled, onAdded, edi
const { quote, start, prefix, suffix, sourceCommentId } = captured;
const duplicate = annotationsRef.current.find((a) => a.sourceCommentId === sourceCommentId &&
a.start === start && a.quote === quote && a.prefix === prefix && a.suffix === suffix);
- if (quote.length > MAX_ANNOTATION_QUOTE_LENGTH || (!duplicate && annotationsRef.current.length >= MAX_REPLY_ANNOTATIONS)) {
+ if (quote.length > MAX_ANNOTATION_QUOTE_LENGTH) {
setError(true);
- toast.error(quote.length > MAX_ANNOTATION_QUOTE_LENGTH
- ? t(($) => $.reply.annotations.quote_limit, { count: MAX_ANNOTATION_QUOTE_LENGTH })
- : t(($) => $.reply.annotations.count_limit, { count: MAX_REPLY_ANNOTATIONS }));
+ toast.error(t(($) => $.reply.annotations.quote_limit, { count: MAX_ANNOTATION_QUOTE_LENGTH }));
return false;
}
setSelection(captured);
@@ -208,11 +227,11 @@ export function useCommentAnnotations({ draftKey, sources, enabled, onAdded, edi
}, [t]);
const addSelection = useCallback(() => add(readSelection()), [add, readSelection]);
- const confirmNote = () => {
- if (!editing?.note.trim()) return;
+ const confirmNote = (note: string) => {
+ if (!editing || !note.trim()) return;
const store = useCommentDraftStore.getState();
- if (editingExisting) store.updateAnnotation(draftKey, editing.id, editing.note);
- else if (!store.addAnnotation(draftKey, editing)) {
+ if (editingExisting) store.updateAnnotation(draftKey, editing.id, note);
+ else if (!store.addAnnotation(draftKey, { ...editing, note })) {
setError(true);
return;
}
@@ -228,7 +247,6 @@ export function useCommentAnnotations({ draftKey, sources, enabled, onAdded, edi
CSS.highlights.set(name, new Highlight(selection.range));
return () => { CSS.highlights.delete(name); };
}, [enabled, selection, editingId, highlightName]);
- const confirmLabel = t(($) => editor?.existing ? $.reply.annotations.save : $.reply.annotations.confirm_add);
return {
cardRef,
@@ -263,36 +281,27 @@ export function useCommentAnnotations({ draftKey, sources, enabled, onAdded, edi
onClick={() => editAnnotation(anchor.id)}>{index + 1}</IconButton>
</CommentSelectionBubble>;
})}
- {enabled && selection && <CommentSelectionBubble range={selection.range} source={selection.root} owner={draftKey} onPositioned={focusNote}>
+ {enabled && selection && <CommentSelectionBubble range={selection.range} source={selection.root} owner={draftKey} onPositioned={focusNote} keepVisibleWhenDetached={!!editing}>
<div className="bubble-menu max-w-[calc(100vw-16px)] focus-within:outline-1 focus-within:outline-ring">
- {editing ? <div className="flex w-80 max-w-[calc(100vw-26px)] flex-col gap-1"><textarea ref={inputRef} value={editing.note} rows={Math.min(4, Math.max(1, editing.note.split("\n").length))}
- aria-label={t(($) => $.reply.annotations.note_label)}
- placeholder={t(($) => $.reply.annotations.note_placeholder)}
- className="min-h-8 max-h-[calc(4lh+0.75rem)] w-full min-w-0 resize-none field-sizing-content rounded-sm bg-transparent px-2 py-1.5 text-body outline-none placeholder:text-muted-foreground"
- onChange={(event) => {
- setEditor({ annotation: { ...editing, note: event.target.value }, existing: editingExisting });
- setError(false);
+ {editing ? <AnnotationComposer key={editing.id} issueId={issueId} owner={draftKey}
+ annotation={editing} existing={editingExisting}
+ number={annotations.findIndex((a) => a.id === editing.id) + 1}
+ editorRef={inputRef} parentId={editable ? undefined : editing.sourceCommentId} reply={reply}
+ sourceMissing={!sources.some((source) => source.id === editing.sourceCommentId)}
+ sourceChanged={sources.some((source) => source.id === editing.sourceCommentId &&
+ source.revision !== undefined && editing.sourceRevision !== undefined && source.revision !== editing.sourceRevision)}
+ canSave={editingExisting || annotations.length < MAX_REPLY_ANNOTATIONS}
+ isSourceAvailable={() => sourcesRef.current.some((source) => source.id === editing.sourceCommentId) &&
+ !!cardRef.current && !!findAnnotationSource(cardRef.current, editing.sourceCommentId)}
+ onChange={(note) => { setEditor({ annotation: { ...editing, note }, existing: editingExisting }); setError(false); }}
+ onSave={confirmNote} onBusyChange={(busy) => {
+ if (editingRef.current?.id === editing.id) submittingRef.current = busy;
}}
- onKeyDown={(event) => {
- if (event.key === "Enter" && !isImeComposing(event) &&
- !event.shiftKey && !event.metaKey && !event.ctrlKey && !event.altKey) {
- event.preventDefault(); event.stopPropagation(); confirmNote();
- } else if (event.key === "Escape" && !isImeComposing(event)) {
- event.preventDefault(); event.stopPropagation(); close(true);
- }
- }} />
- <div className="flex items-center justify-end gap-1 px-1 pb-1">
- {editingExisting && <IconButton variant="ghost" size="icon-sm" className="mr-auto text-muted-foreground hover:text-destructive"
- label={t(($) => $.reply.annotations.remove, { number: annotations.findIndex((a) => a.id === editing.id) + 1 })}
- onClick={() => {
- useCommentDraftStore.getState().removeAnnotation(draftKey, editing.id);
- close(true);
- }}><Trash2 /></IconButton>}
- <Button size="sm" disabled={!editing.note.trim()}
- aria-label={confirmLabel} aria-keyshortcuts="Enter"
- onClick={confirmNote}>{confirmLabel}</Button>
- </div>
- </div> : <Button ref={actionRef} variant="ghost" size="sm"
+ onAccepted={() => { if (editingRef.current?.id === editing.id) close(); }}
+ onRemove={editingExisting ? () => {
+ useCommentDraftStore.getState().removeAnnotation(draftKey, editing.id);
+ close(true);
+ } : undefined} /> : <Button ref={actionRef} variant="ghost" size="sm"
onMouseDown={(event) => event.preventDefault()} onClick={() => add(selection)}>
<MessageSquarePlus />{t(($) => editable ? $.reply.annotations.add_comment : $.reply.annotations.add)}
</Button>}
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index c047a11d6b..6426f4b1b3 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -751,6 +751,12 @@
"reply": {
"placeholder": "Leave a reply...",
"annotations": {
+ "direct_reply": "Reply",
+ "direct_comment": "Post comment",
+ "direct_target_deleted": "The reply target was deleted. Copy your note before selecting another comment.",
+ "copy_note": "Copy note",
+ "note_copied": "Note copied",
+ "note_copy_failed": "Could not copy note. Select and copy the text manually.",
"confirm_add": "Add annotation",
"save": "Save annotation",
"add_comment": "Add to comment",
diff --git a/packages/views/locales/es/issues.json b/packages/views/locales/es/issues.json
index a9af2b0656..b05f0ff507 100644
--- a/packages/views/locales/es/issues.json
+++ b/packages/views/locales/es/issues.json
@@ -734,6 +734,12 @@
"reply": {
"placeholder": "Deja una respuesta...",
"annotations": {
+ "direct_reply": "Responder",
+ "direct_comment": "Publicar comentario",
+ "direct_target_deleted": "Se eliminó el destino de la respuesta. Copia tu nota antes de seleccionar otro comentario.",
+ "copy_note": "Copiar nota",
+ "note_copied": "Nota copiada",
+ "note_copy_failed": "No se pudo copiar la nota. Selecciona y copia el texto manualmente.",
"confirm_add": "Añadir anotación",
"save": "Guardar anotación",
"add_comment": "Añadir al comentario",
diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.json
index 68eb45d47a..df51416d68 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -751,6 +751,12 @@
"reply": {
"placeholder": "Laisser une réponse...",
"annotations": {
+ "direct_reply": "Répondre",
+ "direct_comment": "Publier le commentaire",
+ "direct_target_deleted": "Le commentaire ciblé a été supprimé. Copiez votre note avant de sélectionner un autre commentaire.",
+ "copy_note": "Copier la note",
+ "note_copied": "Note copiée",
+ "note_copy_failed": "Impossible de copier la note. Sélectionnez et copiez le texte manuellement.",
"confirm_add": "Ajouter une annotation",
"save": "Enregistrer l'annotation",
"add_comment": "Ajouter au commentaire",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 71c6201abb..fc4780b9f4 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -729,6 +729,12 @@
"reply": {
"placeholder": "返信を残す...",
"annotations": {
+ "direct_reply": "返信",
+ "direct_comment": "コメントを投稿",
+ "direct_target_deleted": "返信先が削除されました。別のコメントを選ぶ前に、意見をコピーしてください。",
+ "copy_note": "意見をコピー",
+ "note_copied": "意見をコピーしました",
+ "note_copy_failed": "コピーできませんでした。テキストを選択して手動でコピーしてください。",
"confirm_add": "注釈を追加",
"save": "注釈を保存",
"add_comment": "コメントに追加",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index d9656ebcf3..8a3782434d 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -729,6 +729,12 @@
"reply": {
"placeholder": "답글 남기기...",
"annotations": {
+ "direct_reply": "답글",
+ "direct_comment": "댓글 게시",
+ "direct_target_deleted": "답글 대상이 삭제되었습니다. 다른 댓글을 선택하기 전에 의견을 복사하세요.",
+ "copy_note": "의견 복사",
+ "note_copied": "의견을 복사했습니다",
+ "note_copy_failed": "의견을 복사하지 못했습니다. 텍스트를 선택해 직접 복사하세요.",
"confirm_add": "주석 추가",
"save": "주석 저장",
"add_comment": "댓글에 추가",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 2c72423099..c08ce27c1c 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -729,6 +729,12 @@
"reply": {
"placeholder": "回复...",
"annotations": {
+ "direct_reply": "回复",
+ "direct_comment": "发表评论",
+ "direct_target_deleted": "回复目标已删除。请先复制意见,再选择其他评论。",
+ "copy_note": "复制意见",
+ "note_copied": "意见已复制",
+ "note_copy_failed": "复制失败,请选中意见文字手动复制。",
"confirm_add": "添加批注",
"save": "保存批注",
"add_comment": "加入评论",
diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.json
index 3ddb04eb53..7ae419bf3c 100644
--- a/packages/views/locales/zh-Hant/issues.json
+++ b/packages/views/locales/zh-Hant/issues.json
@@ -729,6 +729,12 @@
"reply": {
"placeholder": "回覆...",
"annotations": {
+ "direct_reply": "回覆",
+ "direct_comment": "發表評論",
+ "direct_target_deleted": "回覆對象已刪除。請先複製意見,再選擇其他評論。",
+ "copy_note": "複製意見",
+ "note_copied": "意見已複製",
+ "note_copy_failed": "複製失敗,請選取意見文字手動複製。",
"confirm_add": "新增批註",
"save": "儲存批註",
"add_comment": "加入評論",