Skip to content

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

Go

MUL-7260: annotate comments and descriptions (#8274)

Jiayuan Zhang67bc6686d153
diff --git a/apps/docs/content/docs/comments.ja.mdx b/apps/docs/content/docs/comments.ja.mdx
index 6129a2b3c5..7d1e0b24bc 100644
--- a/apps/docs/content/docs/comments.ja.mdx
+++ b/apps/docs/content/docs/comments.ja.mdx
@@ -13,6 +13,14 @@ import { Callout } from "fumadocs-ui/components/callout";
コメントに返信するとスレッドになります。返信はさらにネストできますが、すべて同じトップレベルのスレッドの下にまとまります。
+## コメントと説明に注釈を付ける
+
+Web と Desktop では、自分を含む誰のコメントでも選択して選択ツールバーの **返信に追加** を押すと、そのスレッドの返信下書きに引用が追加されます。選択箇所の横で任意のコメントを入力すると自動保存され、完了操作は不要です。原文の番号をクリックすると再編集できます。入力欄の横のごみ箱ボタンで、その注釈と原文のマーク、下書きの項目をその場で削除できます。注釈件数にマウスを重ねるとポップアップで引用の確認・削除ができ、引用をクリックすると原文でコメントを編集できます。クリックやキーボードでも開けます。既存の送信ボタンで 1 件の返信として送信し、注釈の間には空行が入ります。タスク説明では選択ツールバーの **コメントに追加** を選びます。説明の注釈は新しいコメントの下書きに入り、送信すると新しいスレッドを作成します。コメントの注釈は元のスレッドへの返信になります。
+
+コメントへの注釈では、最初の引用で返信先が決まります。ネストした返信も対象になり、同じスレッドの別のメッセージからも引用できます。注釈のコメントか全体への返信を入力し、既存の送信ボタンで 1 件のコメントとして投稿します。引用内のメンションは通知や実行を発生させません。自分で入力したメンションには通常のルールが適用されます。
+
+下書きはこのデバイスとワークスペース内だけに保存され、再読み込み後も復元されます。保存期間は 30 日です。返信ごとに最大 20 件の注釈、引用ごとに最大 4,000 文字を追加できます。原文が変更されても引用は残りますが、返信先が削除された場合は送信できません。Chat、モバイルでの注釈入力、デバイス間の下書き同期には対応していません。
+
## スレッドの解決
疑問に結論が出たら、スレッド全体を解決済みにするか、いずれかの返信を結論に設定できます。1 つのスレッドが同時に保持できる結論は 1 つだけです。解決済みのスレッドは折りたたまれますが、展開して確認できます。
diff --git a/apps/docs/content/docs/comments.ko.mdx b/apps/docs/content/docs/comments.ko.mdx
index 216627aeb9..c86c78bc97 100644
--- a/apps/docs/content/docs/comments.ko.mdx
+++ b/apps/docs/content/docs/comments.ko.mdx
@@ -13,6 +13,14 @@ import { Callout } from "fumadocs-ui/components/callout";
댓글에 답글을 달면 논의 스레드가 만들어집니다. 답글은 계속 중첩할 수 있지만 모두 같은 최상위 논의 아래에 속합니다.
+## 댓글과 설명에 주석 달기
+
+Web과 Desktop에서 본인 댓글을 포함한 모든 댓글의 텍스트를 선택하고 선택 도구 모음의 **답글에 추가**를 누르면 해당 스레드의 답글 초안에 인용문이 즉시 추가됩니다. 선택한 위치 옆에서 의견을 입력하면 자동 저장되며 완료 버튼은 필요 없습니다. 원문의 번호 표시를 누르면 다시 편집할 수 있습니다. 입력란 옆의 휴지통 버튼으로 해당 주석과 원문 표시, 초안 항목을 그 자리에서 삭제할 수 있습니다. 주석 개수에 마우스를 올리면 팝업에서 인용문을 확인하거나 삭제하고, 인용문을 눌러 원문에서 의견을 편집할 수 있습니다. 클릭이나 키보드로도 팝업을 열 수 있습니다. 기존 전송 버튼으로 하나의 답글을 보내며 주석 사이에는 빈 줄이 들어갑니다. 작업 설명에서는 선택 도구 모음의 **댓글에 추가**를 누릅니다. 설명 주석은 새 댓글 초안에 추가되며 전송하면 새 스레드를 만듭니다. 댓글 주석은 원래 스레드의 답글로 전송됩니다.
+
+댓글 주석에서는 첫 인용문이 중첩 답글을 포함한 정확한 답글 대상을 결정합니다. 같은 스레드의 다른 메시지에서도 인용할 수 있습니다. 주석에 코멘트를 추가하거나 전체 답글을 작성한 뒤 기존 전송 버튼으로 하나의 댓글을 게시하세요. 인용문 안의 멘션은 알림이나 실행을 발생시키지 않으며, 직접 작성한 멘션에는 일반 규칙이 적용됩니다.
+
+초안은 이 기기와 워크스페이스에만 저장되며 새로고침 후 복원되고 30일 후 만료됩니다. 답글당 주석은 최대 20개, 인용문당 최대 4,000자입니다. 원문이 변경되어도 저장한 인용문은 유지되지만 답글 대상이 삭제되면 전송할 수 없습니다. Chat, 모바일 주석 입력, 기기 간 초안 동기화는 지원하지 않습니다.
+
## 논의 해결
문제에 결론이 나면 전체 논의를 해결됨으로 표시하거나 특정 답글을 결론으로 지정할 수 있습니다. 한 논의에는 한 번에 하나의 결론만 유지됩니다. 해결된 논의는 접히지만 다시 펼쳐서 볼 수 있습니다.
diff --git a/apps/docs/content/docs/comments.mdx b/apps/docs/content/docs/comments.mdx
index 24e40338df..cbcb694245 100644
--- a/apps/docs/content/docs/comments.mdx
+++ b/apps/docs/content/docs/comments.mdx
@@ -13,6 +13,14 @@ Type into the issue's activity area and send to create a comment. Comments suppo
Replying to a comment forms a discussion thread. Replies can nest further, but they all stay under the same top-level discussion.
+## Annotate comments and descriptions
+
+On Web and Desktop, select text in any posted comment, including your own and choose **Add to reply** in the selection toolbar. The quote is immediately added to that thread’s reply draft. Write an optional note beside the selection; it saves as you type, with no Done step. Click the numbered source marker to edit it again. The trash button beside the note removes that annotation directly at the source, including its highlight and draft entry. Hover over the annotation count to inspect or remove quotes in a floating panel, or click a quote to edit its note at the source. You can also open the panel by clicking or using the keyboard. Send everything as one reply with the existing send button, with a blank line between annotations. For an issue description, choose **Add to comment** in its selection toolbar. Description annotations join the new-comment draft and are sent as a new thread; comment annotations stay in their original thread.
+
+For comment annotations, the first quote fixes the reply target, including nested replies. Quotes from other messages in that discussion join the same draft. Add at least one note or an overall reply, then use the existing send button to publish everything as one comment. Quoted mentions do not notify or trigger anyone; mentions you write yourself follow the normal rules.
+
+Drafts are private to this device and workspace, survive reloads, and expire after 30 days. Each reply supports up to 20 annotations, with up to 4,000 characters per quote. If a source changes, its saved quote remains; if the reply target is deleted, sending is blocked. Chat, mobile annotation entry, and cross-device draft sync are not included.
+
## Resolve a discussion
When a question reaches a conclusion, mark the whole discussion as resolved, or set one reply as the conclusion; a discussion keeps only one conclusion at a time. Resolved discussions collapse but can still be expanded.
diff --git a/apps/docs/content/docs/comments.zh.mdx b/apps/docs/content/docs/comments.zh.mdx
index 9bcd0353ad..fa4954098d 100644
--- a/apps/docs/content/docs/comments.zh.mdx
+++ b/apps/docs/content/docs/comments.zh.mdx
@@ -13,6 +13,14 @@ import { Callout } from "fumadocs-ui/components/callout";
回复某条评论会形成一条讨论线程。回复可以继续嵌套,但都归在同一条顶层讨论下。
+## 批注评论与任务描述
+
+在 Web 或 Desktop 中,选中任意已发表的评论文字,包括自己的评论,点击选区工具条中的 **加入回复**,引用即加入当前讨论的 reply 草稿。可在选区旁填写意见,随写随存,无需点击完成;点击原文编号标记可继续编辑,也可点击批注框右侧的删除图标,直接移除该批注及其原文标记和草稿条目。鼠标悬停在批注计数上,即可在浮层中查看、删除引用,或点击引用返回原位编辑意见;也支持点击或使用键盘打开浮层。通过原有发送按钮合并发送为一条回复,各条批注之间保留一个空行,任务描述的选区工具条提供 **加入评论**,批注进入新评论草稿,发送后创建新的讨论;评论批注仍进入原讨论的回复草稿。
+
+评论批注的首次引用会确定具体回复目标,包括嵌套回复。同一讨论中其他消息的引用会加入这份草稿。填写至少一条批注内容或整体回复后,使用原有发送按钮,将全部内容作为一条评论发布。引用中的提及不会通知或触发任何人;你自己填写的提及仍遵循普通规则。
+
+草稿仅保存在当前设备和工作区,刷新后可恢复,30 天后过期。每条回复最多包含 20 条批注,每次引用最多 4,000 个字符。原文更改后仍保留引用快照;回复目标被删除时会阻止发送。首版不包含 Chat、移动端批注输入或跨设备草稿同步。
+
## 解决一条讨论
问题得到结论时,可以把整条讨论标记为已解决,或将某条回复设为结论;一条讨论同时只保留一个结论。已解决的讨论会折叠,仍可展开查看。
diff --git a/packages/core/drafts/reply-annotation.test.ts b/packages/core/drafts/reply-annotation.test.ts
new file mode 100644
index 0000000000..d8c1653f97
--- /dev/null
+++ b/packages/core/drafts/reply-annotation.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from "vitest";
+import { parseMentions } from "../issues/comment-trigger-outcomes";
+import { composeAnnotatedReply, 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("annotated reply serialization", () => {
+ it("publishes only the user body, quotes and notes, without source links or labels", () => {
+ expect(composeAnnotatedReply("Overall reply", [annotation, { ...annotation, id: "b", quote: "other", note: "" }]))
+ .toBe("Overall reply\n\n> first\n> second\n\nPlease revise.\n\n \n\n> other");
+ });
+
+ it("preserves user-authored note Markdown and links without list indentation", () => {
+ expect(composeAnnotatedReply("", [{ ...annotation, note: "See [details](https://example.com).\n\n- First change\n- Second change" }]))
+ .toBe("> first\n> second\n\nSee [details](https://example.com).\n\n- First change\n- Second change");
+ });
+
+ it("keeps quoted raw mentions and markup inert, while preserving deliberate mentions", () => {
+ const mention = "[@Agent](mention://agent/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa)";
+ const content = composeAnnotatedReply("", [{ ...annotation, quote: `\`\`\`\n${mention}\n<script>x</script>\n&colon;\n\`\`\``, sourceActorName: mention, note: mention }]);
+ expect(parseMentions(content)).toHaveLength(1);
+ expect(content.match(/mention:\/\//g)).toHaveLength(1);
+ expect(content).toContain("&#60;script&#62;");
+ expect(content).toContain("&amp;colon;");
+ expect(content).toContain(mention);
+ });
+
+ it("retains /note behavior and does not send quotes alone", () => {
+ expect(composeAnnotatedReply("/note Private", [annotation])).toMatch(/^\/note Private/);
+ expect(hasReplyIntent(" ", [{ ...annotation, note: " " }])).toBe(false);
+ expect(hasReplyIntent("", [annotation])).toBe(true);
+ expect(hasReplyIntent("Overall", [{ ...annotation, note: "" }])).toBe(true);
+ });
+
+ it("normalizes old and corrupt drafts without inventing annotations", () => {
+ expect(normalizeReplyAnnotations(undefined)).toEqual([]);
+ expect(normalizeReplyAnnotations([null, {}, { ...annotation, quote: "x".repeat(4001) }, annotation])).toEqual([annotation]);
+ });
+});
+
+describe("quote anchors", () => {
+ const anchor = { ...annotation, quote: "same", prefix: "left ", suffix: " right", start: 5 };
+ it("relocates a unique quote with unchanged context", () => {
+ expect(locateReplyAnnotation("left same right", anchor)).toBe(5);
+ expect(locateReplyAnnotation("new paragraph left same right", anchor)).toBe(19);
+ });
+ it("does not guess when source text or context changed or the match is ambiguous", () => {
+ expect(locateReplyAnnotation("left different right", anchor)).toBeNull();
+ expect(locateReplyAnnotation("other same right", anchor)).toBeNull();
+ expect(locateReplyAnnotation("left same right / left same right", anchor)).toBeNull();
+ });
+});
diff --git a/packages/core/drafts/reply-annotation.ts b/packages/core/drafts/reply-annotation.ts
new file mode 100644
index 0000000000..0a7461e86e
--- /dev/null
+++ b/packages/core/drafts/reply-annotation.ts
@@ -0,0 +1,81 @@
+/** Private, workspace-scoped reply metadata. Published replies remain Markdown. */
+export interface ReplyAnnotation {
+ id: string;
+ /** Local source key. Descriptions use description:<issueId>, never a reply target. */
+ sourceCommentId: string;
+ sourceActorName: string;
+ sourceRevision?: number;
+ quote: string;
+ note: string;
+ /** Offsets refer to normalized rendered text, never Markdown or a live Range. */
+ start: number;
+ prefix: string;
+ suffix: string;
+}
+
+export const MAX_REPLY_ANNOTATIONS = 20;
+export const MAX_ANNOTATION_QUOTE_LENGTH = 4000;
+export const EMPTY_REPLY_ANNOTATIONS: ReplyAnnotation[] = [];
+
+export function normalizeReplyAnnotations(value: unknown): ReplyAnnotation[] {
+ if (!Array.isArray(value)) return EMPTY_REPLY_ANNOTATIONS;
+ const valid = value.filter((a): a is ReplyAnnotation =>
+ a != null && typeof a === "object" &&
+ typeof a.id === "string" && typeof a.sourceCommentId === "string" &&
+ typeof a.sourceActorName === "string" && typeof a.quote === "string" &&
+ a.quote.trim().length > 0 && a.quote.length <= MAX_ANNOTATION_QUOTE_LENGTH &&
+ typeof a.note === "string" && Number.isInteger(a.start) && a.start >= 0 &&
+ typeof a.prefix === "string" && typeof a.suffix === "string" &&
+ (a.sourceRevision === undefined || Number.isInteger(a.sourceRevision)),
+ ).slice(0, MAX_REPLY_ANNOTATIONS);
+ return valid.length ? valid : EMPTY_REPLY_ANNOTATIONS;
+}
+
+/** A quote alone is not an instruction to the agent. */
+export function hasReplyIntent(content: string, annotations: readonly ReplyAnnotation[]): boolean {
+ return !!content.trim() || annotations.some((a) => !!a.note.trim());
+}
+
+/** Escape visible text, including literal mention:// links in code samples.
+ * The server scans raw Markdown for mentions even inside quotes and fences.
+ * Entity-encoding punctuation keeps snapshots inert without changing their
+ * rendered text. Escape ampersands first so source entities remain literal.
+ */
+function quoteText(text: string): string {
+ return text.replace(/&/g, "&amp;").replace(/[<>\\`*_[\]{}()#!|~:$+.=-]/g,
+ (char) => `&#${char.charCodeAt(0)};`)
+ // Leading spaces must survive HTML whitespace collapsing and must not
+ // become Markdown list nesting or an indented code block. Tabs use 4 stops.
+ .replace(/^[ \t]+/, (indent) => {
+ let columns = 0;
+ for (const char of indent) columns += char === "\t" ? 4 - columns % 4 : 1;
+ return "&nbsp;".repeat(columns);
+ });
+}
+
+export function composeAnnotatedReply(content: string, annotations: readonly ReplyAnnotation[]): string {
+ const body = content.trim();
+ if (!annotations.length) return body;
+ // Keep the user's leading /note command (and explicit mentions) in place.
+ const quotes = annotations.map((a) =>
+ a.quote.split(/\r?\n/).map((line) => `> ${quoteText(line)}`).join("\n") +
+ (a.note.trim() ? `\n\n${a.note.trim()}` : ""),
+ );
+ // Markdown collapses extra newlines. A blank paragraph keeps one visible
+ // empty line between annotations and separates adjacent quote-only blocks.
+ return [body, quotes.join("\n\n&nbsp;\n\n")].filter(Boolean).join("\n\n");
+}
+
+/** Relocate only an unambiguous quote with matching context after source edits. */
+export function locateReplyAnnotation(text: string, annotation: ReplyAnnotation): number | null {
+ const matches = (start: number) =>
+ text.slice(start, start + annotation.quote.length) === annotation.quote &&
+ text.slice(Math.max(0, start - annotation.prefix.length), start) === annotation.prefix &&
+ text.slice(start + annotation.quote.length, start + annotation.quote.length + annotation.suffix.length) === annotation.suffix;
+ const candidates: number[] = [];
+ for (let start = text.indexOf(annotation.quote); start !== -1; start = text.indexOf(annotation.quote, start + 1)) {
+ if (matches(start)) candidates.push(start);
+ if (candidates.length > 1) return null;
+ }
+ return candidates[0] ?? null;
+}
diff --git a/packages/core/issues/stores/comment-draft-store.test.ts b/packages/core/issues/stores/comment-draft-store.test.ts
index c2a9d7b36f..36626ab20b 100644
--- a/packages/core/issues/stores/comment-draft-store.test.ts
+++ b/packages/core/issues/stores/comment-draft-store.test.ts
@@ -328,3 +328,94 @@ describe("comment draft store — upload lifecycle", () => {
expect(first).toBe(second);
});
});
+
+describe("reply annotations", () => {
+ const key = "reply:issue-1:root" as const;
+ const annotation = { id: "a", sourceCommentId: "nested-agent", sourceActorName: "Emacs", quote: "Selected text", note: "", start: 0, prefix: "", suffix: "" };
+ beforeEach(async () => {
+ setCurrentWorkspace("annotation-tests", "ws_annotations");
+ await flush();
+ useCommentDraftStore.setState({ drafts: {} });
+ });
+ afterEach(() => setCurrentWorkspace(null, null));
+
+ it("keeps annotation-only drafts through text/upload changes and preserves the first exact reply target", () => {
+ const store = useCommentDraftStore.getState();
+ store.addAnnotation(key, annotation);
+ store.setDraft(key, "");
+ store.setAttachments(key, [makeAttachment("att")]);
+ store.appendToDraftContent(key, "uploaded link");
+ store.setAttachments(key, []);
+ store.setDraft(key, "");
+ store.addAnnotation(key, { ...annotation, id: "b", sourceCommentId: "another-agent" });
+ store.removeAnnotation(key, "a");
+ expect(store.getAnnotations(key)).toHaveLength(1);
+ expect(useCommentDraftStore.getState().drafts[key]?.replyTarget?.commentId).toBe("nested-agent");
+ store.removeAnnotation(key, "b");
+ expect(store.getDraft(key)).toBeUndefined();
+ });
+
+ it("persists description annotations with the new comment draft without a reply target", async () => {
+ const store = useCommentDraftStore.getState();
+ store.setDraft("new:issue", "Existing draft");
+ store.addAnnotation("new:issue", { ...annotation, sourceCommentId: "description:issue" });
+ store.updateAnnotation("new:issue", annotation.id, "Description note");
+ await flush();
+ useCommentDraftStore.getState().drafts = {};
+ await useCommentDraftStore.persist.rehydrate();
+ expect(useCommentDraftStore.getState().getDraft("new:issue")).toBe("Existing draft");
+ expect(useCommentDraftStore.getState().getAnnotations("new:issue")[0]?.note).toBe("Description note");
+ expect(useCommentDraftStore.getState().drafts["new:issue"]?.replyTarget).toBeUndefined();
+ expect(useCommentDraftStore.getState().addAnnotation("edit:issue:comment", annotation)).toBeUndefined();
+ });
+
+ it("reopens duplicate ranges, bounds collection, and changes identity only on actual edits", () => {
+ const store = useCommentDraftStore.getState();
+ expect(store.addAnnotation(key, annotation)).toBe("a");
+ const snapshot = useCommentDraftStore.getState().drafts[key];
+ expect(store.addAnnotation(key, { ...annotation, id: "duplicate" })).toBe("a");
+ store.updateAnnotation(key, "a", "");
+ store.setDraft(key, "");
+ expect(useCommentDraftStore.getState().drafts[key]).toBe(snapshot);
+ store.updateAnnotation(key, "a", "New intent");
+ expect(useCommentDraftStore.getState().drafts[key]).not.toBe(snapshot);
+ for (let i = 1; i < 20; i++) store.addAnnotation(key, { ...annotation, id: `a${i}`, start: i });
+ expect(store.addAnnotation(key, { ...annotation, id: "overflow", start: 21 })).toBeUndefined();
+ expect(store.addAnnotation("reply:other:root", { ...annotation, quote: "x".repeat(4001) })).toBeUndefined();
+ expect(store.getAnnotations(key)).toHaveLength(20);
+ expect(store.getAnnotations("reply:other:root")).toHaveLength(0);
+ });
+
+ it("restores annotation-only drafts and targets across rehydration", async () => {
+ const store = useCommentDraftStore.getState();
+ store.addAnnotation(key, annotation);
+ store.updateAnnotation(key, "a", "Saved note");
+ await flush();
+ useCommentDraftStore.getState().drafts = {};
+ await useCommentDraftStore.persist.rehydrate();
+ expect(useCommentDraftStore.getState().getAnnotations(key)[0]?.note).toBe("Saved note");
+ expect(useCommentDraftStore.getState().drafts[key]?.replyTarget?.commentId).toBe("nested-agent");
+ });
+ it("isolates annotations by workspace, expires old entries, and clears them on logout", async () => {
+ const { resetAllRegisteredDrafts } = await import("../../drafts/cleanup-registry");
+ setCurrentWorkspace("annotations-a", "ws_a");
+ await flush();
+ useCommentDraftStore.getState().addAnnotation(key, annotation);
+ setCurrentWorkspace("annotations-b", "ws_b");
+ await flush();
+ expect(useCommentDraftStore.getState().getAnnotations(key)).toHaveLength(0);
+ setCurrentWorkspace("annotations-a", "ws_a");
+ await flush();
+ expect(useCommentDraftStore.getState().getAnnotations(key)).toHaveLength(1);
+ const saved = JSON.parse(localStorage.getItem("multica_comment_drafts:annotations-a")!);
+ saved.state.drafts[key].updatedAt = Date.now() - 31 * DAY_MS;
+ localStorage.setItem("multica_comment_drafts:annotations-a", JSON.stringify(saved));
+ await useCommentDraftStore.persist.rehydrate();
+ expect(useCommentDraftStore.getState().getAnnotations(key)).toHaveLength(0);
+ useCommentDraftStore.getState().addAnnotation(key, annotation);
+ resetAllRegisteredDrafts();
+ expect(useCommentDraftStore.getState().getAnnotations(key)).toHaveLength(0);
+ setCurrentWorkspace(null, null);
+ });
+
+});
diff --git a/packages/core/issues/stores/comment-draft-store.ts b/packages/core/issues/stores/comment-draft-store.ts
index e02a748292..28e47cde1f 100644
--- a/packages/core/issues/stores/comment-draft-store.ts
+++ b/packages/core/issues/stores/comment-draft-store.ts
@@ -1,3 +1,4 @@
+import { type ReplyAnnotation, EMPTY_REPLY_ANNOTATIONS, MAX_REPLY_ANNOTATIONS, MAX_ANNOTATION_QUOTE_LENGTH, normalizeReplyAnnotations } from "../../drafts/reply-annotation";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { createWorkspaceAwareStorage, registerForWorkspaceRehydration } from "../../platform/workspace-storage";
@@ -42,6 +43,8 @@ interface CommentDraft {
content: string;
/** Uploads (placeholders + completed) for this composer session. */
attachments: DraftUpload[];
+ annotations?: ReplyAnnotation[];
+ replyTarget?: { commentId: string; actorName: string };
updatedAt: number;
}
@@ -70,6 +73,10 @@ interface CommentDraftStore {
failUpload: (key: CommentDraftKey, clientUploadId: string, error?: string) => void;
/** Drop a placeholder (e.g. a dismissed failure). */
removeUpload: (key: CommentDraftKey, clientUploadId: string) => void;
+ getAnnotations: (key: CommentDraftKey) => ReplyAnnotation[];
+ addAnnotation: (key: CommentDraftKey, annotation: ReplyAnnotation) => string | undefined;
+ updateAnnotation: (key: CommentDraftKey, id: string, note: string) => void;
+ removeAnnotation: (key: CommentDraftKey, id: string) => void;
clearDraft: (key: CommentDraftKey) => void;
}
@@ -102,8 +109,8 @@ function deriveUploaded(uploads: DraftUpload[]): Attachment[] {
// upload (in any state). Upload-only drafts (text deleted, a file still pending
// or failed) are meaningful — pruning or dropping them would silently discard
// the upload the whole persistence exists to protect.
-function isMeaningful(content: string, uploads: DraftUpload[]): boolean {
- return content.trim().length > 0 || uploads.length > 0;
+function isMeaningful(content: string, uploads: DraftUpload[], annotations: ReplyAnnotation[] = EMPTY_REPLY_ANNOTATIONS): boolean {
+ return content.trim().length > 0 || uploads.length > 0 || annotations.length > 0;
}
// Shared writer for setDraft/setAttachments/upload mutations: an entry with
@@ -115,8 +122,10 @@ function writeDraft(
key: string,
content: string,
uploads: DraftUpload[],
+ annotations = drafts[key]?.annotations ?? EMPTY_REPLY_ANNOTATIONS,
+ replyTarget = key.startsWith("reply:") && annotations.length ? drafts[key]?.replyTarget : undefined,
): Record<string, CommentDraft> {
- if (!isMeaningful(content, uploads)) {
+ if (!isMeaningful(content, uploads, annotations)) {
if (!(key in drafts)) return drafts;
const next = { ...drafts };
delete next[key];
@@ -127,10 +136,10 @@ function writeDraft(
// guard compares entry identity — a fresh-but-equal entry would read as "the
// user edited during the request" and wrongly keep a submitted draft alive.
const existing = drafts[key];
- if (existing && existing.content === content && existing.attachments === uploads) {
+ if (existing && existing.content === content && existing.replyTarget === replyTarget && (existing.annotations ?? EMPTY_REPLY_ANNOTATIONS) === annotations && existing.attachments === uploads) {
return drafts;
}
- return { ...drafts, [key]: { content, attachments: uploads, updatedAt: Date.now() } };
+ return { ...drafts, [key]: { content, attachments: uploads, annotations, replyTarget, updatedAt: Date.now() } };
}
function uploadsOf(drafts: Record<string, CommentDraft>, key: string): DraftUpload[] {
@@ -145,8 +154,12 @@ function pruneStaleDrafts(drafts: Record<string, CommentDraft>): Record<string,
// placeholders, and any placeholder still `uploading` is dropped (the bytes
// were never persisted, so the upload cannot resume).
const uploads = normalizeStoredUploads(v.attachments);
- if (v.updatedAt >= cutoff && isMeaningful(v.content, uploads)) {
- out[k] = { ...v, attachments: uploads };
+ const annotations = normalizeReplyAnnotations(v.annotations);
+ if (v.updatedAt >= cutoff && isMeaningful(v.content, uploads, annotations)) {
+ const first = annotations[0];
+ const replyTarget = k.startsWith("reply:") && first ? (v.replyTarget && typeof v.replyTarget.commentId === "string" && typeof v.replyTarget.actorName === "string"
+ ? v.replyTarget : { commentId: first.sourceCommentId, actorName: first.sourceActorName }) : undefined;
+ out[k] = { ...v, attachments: uploads, annotations, replyTarget };
}
}
return out;
@@ -228,6 +241,32 @@ export const useCommentDraftStore = create<CommentDraftStore>()(
drafts: writeDraft(s.drafts, key, s.drafts[key]?.content ?? "", next),
};
}),
+ getAnnotations: (key) => get().drafts[key]?.annotations ?? EMPTY_REPLY_ANNOTATIONS,
+ addAnnotation: (key, annotation) => {
+ if ((!key.startsWith("reply:") && !key.startsWith("new:")) || !annotation.quote.trim() || annotation.quote.length > MAX_ANNOTATION_QUOTE_LENGTH) return undefined;
+ const current = get().getAnnotations(key);
+ const duplicate = current.find((a) => a.sourceCommentId === annotation.sourceCommentId &&
+ a.start === annotation.start && a.quote === annotation.quote && a.prefix === annotation.prefix && a.suffix === annotation.suffix);
+ if (duplicate) return duplicate.id;
+ if (current.length >= MAX_REPLY_ANNOTATIONS) return undefined;
+ set((s) => {
+ const replyTarget = key.startsWith("reply:")
+ ? s.drafts[key]?.replyTarget ?? { commentId: annotation.sourceCommentId, actorName: annotation.sourceActorName }
+ : undefined;
+ return { drafts: writeDraft(s.drafts, key, s.drafts[key]?.content ?? "", uploadsOf(s.drafts, key), [...current, annotation], replyTarget) };
+ });
+ return annotation.id;
+ },
+ updateAnnotation: (key, id, note) => set((s) => {
+ const current = s.drafts[key]?.annotations ?? EMPTY_REPLY_ANNOTATIONS;
+ if (!current.some((a) => a.id === id && a.note !== note)) return s;
+ return { drafts: writeDraft(s.drafts, key, s.drafts[key]?.content ?? "", uploadsOf(s.drafts, key), current.map((a) => a.id === id ? { ...a, note } : a)) };
+ }),
+ removeAnnotation: (key, id) => set((s) => {
+ const current = s.drafts[key]?.annotations ?? EMPTY_REPLY_ANNOTATIONS;
+ if (!current.some((a) => a.id === id)) return s;
+ return { drafts: writeDraft(s.drafts, key, s.drafts[key]?.content ?? "", uploadsOf(s.drafts, key), current.filter((a) => a.id !== id)) };
+ }),
clearDraft: (key) =>
set((s) => {
if (!(key in s.drafts)) return s;
@@ -239,6 +278,13 @@ export const useCommentDraftStore = create<CommentDraftStore>()(
{
name: "multica_comment_drafts",
storage: createJSONStorage(() => createWorkspaceAwareStorage(defaultStorage)),
+ // Zustand's default merge keeps the previous workspace's drafts when
+ // the destination has no storage entry. An empty namespace must mean
+ // an empty draft set, including private annotations and reply targets.
+ merge: (persisted, current) => ({
+ ...current,
+ drafts: (persisted as { drafts?: Record<string, CommentDraft> } | undefined)?.drafts ?? {},
+ }),
onRehydrateStorage: () => (state) => {
if (state) {
state.drafts = pruneStaleDrafts(state.drafts);
diff --git a/packages/views/editor/bubble-menu.test.tsx b/packages/views/editor/bubble-menu.test.tsx
index 89922066eb..248f5a2a40 100644
--- a/packages/views/editor/bubble-menu.test.tsx
+++ b/packages/views/editor/bubble-menu.test.tsx
@@ -1,7 +1,9 @@
-import { fireEvent, render, screen } from "@testing-library/react";
+import { act, fireEvent, render, screen } from "@testing-library/react";
import type { Editor } from "@tiptap/core";
import { beforeEach, describe, expect, it, vi } from "vitest";
+const formatState = vi.hoisted(() => ({ codeBlock: false }));
+
vi.mock("@floating-ui/dom", () => ({
autoUpdate: vi.fn(() => vi.fn()),
computePosition: vi.fn(() =>
@@ -23,6 +25,7 @@ vi.mock("@tiptap/react", () => ({
italic: false,
strike: false,
code: false,
+ codeBlock: formatState.codeBlock,
highlight: false,
link: false,
blockquote: false,
@@ -50,7 +53,7 @@ vi.mock("../i18n", async () => {
import { EditorBubbleMenu } from "./bubble-menu";
-function createEditor(): Editor {
+function createEditor(codeBlock = false): Editor {
const chain = {
focus: vi.fn(),
toggleBold: vi.fn(),
@@ -84,7 +87,7 @@ function createEditor(): Editor {
selection: { empty: false, from: 1, to: 2 },
doc: {
textBetween: () => "selected text",
- resolve: () => ({ parent: { type: { name: "paragraph" } } }),
+ resolve: () => ({ parent: { type: { name: codeBlock ? "codeBlock" : "paragraph" } } }),
},
},
view: {
@@ -93,6 +96,7 @@ function createEditor(): Editor {
},
commands: {
focus: vi.fn(),
+ setTextSelection: vi.fn(),
},
chain: () => chain,
getAttributes: () => ({ href: "https://example.com" }),
@@ -102,7 +106,40 @@ function createEditor(): Editor {
}
describe("EditorBubbleMenu accessibility", () => {
- beforeEach(() => vi.clearAllMocks());
+ beforeEach(() => { vi.clearAllMocks(); formatState.codeBlock = false; });
+
+ it("keeps the selection and toolbar on failed capture without resubscribing for new action objects", () => {
+ const editor = createEditor();
+ Object.defineProperty(editor, "isInitialized", { value: true });
+ const { rerender } = render(<EditorBubbleMenu editor={editor} selectionAction={{ label: "Add to comment", onSelect: () => false }} />);
+ const transaction = vi.mocked(editor.on).mock.calls.find(([event]) => event === "transaction")?.[1] as (() => void);
+ act(() => transaction());
+ const registrations = vi.mocked(editor.on).mock.calls.filter(([event]) => event === "transaction").length;
+ rerender(<EditorBubbleMenu editor={editor} selectionAction={{ label: "Add to comment", onSelect: () => false }} />);
+ expect(vi.mocked(editor.on).mock.calls.filter(([event]) => event === "transaction")).toHaveLength(registrations);
+ fireEvent.click(screen.getByRole("button", { name: "Add to comment" }));
+ expect(editor.commands.setTextSelection).not.toHaveBeenCalled();
+ expect(screen.getByRole("button", { name: "Add to comment" })).toBeVisible();
+ });
+
+ it.each([false, true])("exposes a non-editing selection action, including code (code: %s)", (codeBlock) => {
+ formatState.codeBlock = codeBlock;
+ const editor = createEditor(codeBlock);
+ Object.defineProperty(editor, "isInitialized", { value: true });
+ const onSelect = vi.fn();
+ render(<EditorBubbleMenu editor={editor} selectionAction={{ label: "Add to comment", onSelect }} />);
+ const transaction = vi.mocked(editor.on).mock.calls.find(([event]) => event === "transaction")?.[1] as (() => void);
+ act(() => transaction());
+ const action = screen.getByRole("button", { name: "Add to comment" });
+ expect(action).toBeVisible();
+ fireEvent.mouseDown(action);
+ fireEvent.click(action);
+ expect(onSelect).toHaveBeenCalledOnce();
+ expect(editor.commands.setTextSelection).toHaveBeenCalledWith(2);
+ expect(editor.chain().insertContentAt).not.toHaveBeenCalled();
+ expect(editor.chain().toggleBlockquote).not.toHaveBeenCalled();
+ if (codeBlock) expect(screen.queryByLabelText("Bold")).not.toBeInTheDocument();
+ });
it("gives every icon-only formatting control an accessible name", () => {
render(
diff --git a/packages/views/editor/bubble-menu.tsx b/packages/views/editor/bubble-menu.tsx
index 59833310d8..1acf85ab50 100644
--- a/packages/views/editor/bubble-menu.tsx
+++ b/packages/views/editor/bubble-menu.tsx
@@ -37,7 +37,7 @@ import { useCreateIssue } from "@multica/core/issues/mutations";
import { useT } from "../i18n";
import { createShortcutChord, type ShortcutChord } from "@multica/core/shortcuts";
import { ShortcutKeycaps } from "../common/shortcut-keycaps";
-import { Toggle } from "@multica/ui/components/ui/toggle";
+import { Toggle, toggleVariants } from "@multica/ui/components/ui/toggle";
import { Separator } from "@multica/ui/components/ui/separator";
import {
Tooltip,
@@ -73,13 +73,14 @@ import {
Heading3,
FilePlus,
Loader2,
+ MessageSquarePlus,
} from "lucide-react";
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
-function shouldShowBubbleMenu(editor: Editor): boolean {
+function shouldShowBubbleMenu(editor: Editor, hasSelectionAction = false): boolean {
if (!editor.isEditable) return false;
const { selection } = editor.state;
if (selection.empty) return false;
@@ -87,7 +88,7 @@ function shouldShowBubbleMenu(editor: Editor): boolean {
if (!editor.state.doc.textBetween(from, to).trim().length) return false;
if (selection instanceof NodeSelection) return false;
const $from = editor.state.doc.resolve(from);
- if ($from.parent.type.name === "codeBlock") return false;
+ if ($from.parent.type.name === "codeBlock" && !hasSelectionAction) return false;
return true;
}
@@ -494,14 +495,17 @@ function CreateSubIssueButton({
function EditorBubbleMenu({
editor,
currentIssueId,
+ selectionAction,
}: {
editor: Editor;
currentIssueId?: string;
+ selectionAction?: { label: string; onSelect: () => boolean | void };
}) {
const { t } = useT("editor");
const [visible, setVisible] = useState(false);
const [mode, setMode] = useState<"toolbar" | "link-edit">("toolbar");
const floatingRef = useRef<HTMLDivElement>(null);
+ const hasSelectionAction = !!selectionAction;
// Precise subscription to formatting state — only re-renders when these
// values actually change, not on every transaction.
@@ -512,6 +516,7 @@ function EditorBubbleMenu({
italic: e.isActive("italic"),
strike: e.isActive("strike"),
code: e.isActive("code"),
+ codeBlock: e.isActive("codeBlock"),
highlight: e.isActive("highlight"),
link: e.isActive("link"),
blockquote: e.isActive("blockquote"),
@@ -546,11 +551,11 @@ function EditorBubbleMenu({
useEffect(() => {
const onTransaction = () => {
if (!editor.isInitialized) return;
- setVisible(shouldShowBubbleMenu(editor));
+ setVisible(shouldShowBubbleMenu(editor, hasSelectionAction));
};
editor.on("transaction", onTransaction);
return () => { editor.off("transaction", onTransaction); };
- }, [editor]);
+ }, [editor, hasSelectionAction]);
// Hide on blur — debounced to allow focus to settle (e.g. clicking menu)
useEffect(() => {
@@ -634,6 +639,26 @@ function EditorBubbleMenu({
) : (
<TooltipProvider delay={300}>
<div className="bubble-menu">
+ {selectionAction && <>
+ <Tooltip>
+ <TooltipTrigger render={
+ <button type="button" className={toggleVariants({ size: "sm" })}
+ aria-label={selectionAction.label}
+ onClick={() => {
+ if (selectionAction.onSelect() === false) return;
+ // Keep later editor transactions from reopening the formatting
+ // toolbar over the annotation's note field. The text is untouched.
+ editor.commands.setTextSelection(editor.state.selection.to);
+ setVisible(false);
+ }} />
+ }>
+ <MessageSquarePlus className="size-3.5" />
+ </TooltipTrigger>
+ <TooltipContent side="top" sideOffset={8}>{selectionAction.label}</TooltipContent>
+ </Tooltip>
+ {!fmt.codeBlock && <Separator orientation="vertical" className="mx-0.5 h-5" />}
+ </>}
+ {!fmt.codeBlock && <>
<MarkButton editor={editor} mark="bold" icon={Bold} label={t(($) => $.bubble_menu.bold)} shortcut={createShortcutChord("B", { primary: true })} isActive={fmt.bold} />
<MarkButton editor={editor} mark="italic" icon={Italic} label={t(($) => $.bubble_menu.italic)} shortcut={createShortcutChord("I", { primary: true })} isActive={fmt.italic} />
<MarkButton editor={editor} mark="strike" icon={Strikethrough} label={t(($) => $.bubble_menu.strikethrough)} shortcut={createShortcutChord("S", { primary: true, shift: true })} isActive={fmt.strike} />
@@ -696,6 +721,7 @@ function EditorBubbleMenu({
<CreateSubIssueButton editor={editor} parentIssueId={currentIssueId} />
</>
)}
+ </>}
</div>
</TooltipProvider>
)}
diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsx
index 9063cfff40..595bfde9fa 100644
--- a/packages/views/editor/content-editor.tsx
+++ b/packages/views/editor/content-editor.tsx
@@ -171,6 +171,8 @@ interface ContentEditorBaseProps {
onUploadingChange?: (uploading: boolean) => void;
/** Show the floating formatting toolbar on text selection. Defaults true. */
showBubbleMenu?: boolean;
+ /** Additional non-editing action for the current text selection. */
+ selectionAction?: { label: string; onSelect: () => boolean | void };
/**
* ID of the issue this editor belongs to. When set, the bubble menu exposes
* a "Create sub-issue from selection" action that parents the new issue
@@ -369,6 +371,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
pasteAsFileThreshold,
onUploadingChange,
showBubbleMenu = true,
+ selectionAction,
currentIssueId,
disableMentions = false,
mentionMode = "default",
@@ -999,7 +1002,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
>
<EditorContent className="flex flex-1 flex-col" editor={editor} />
{showBubbleMenu && (
- <EditorBubbleMenu editor={editor} currentIssueId={currentIssueId} />
+ <EditorBubbleMenu editor={editor} currentIssueId={currentIssueId} selectionAction={selectionAction} />
)}
<LinkHoverCard {...hover} />
</div>
diff --git a/packages/views/editor/readonly-content.test.tsx b/packages/views/editor/readonly-content.test.tsx
index ca749fc75d..5fb8fff7c9 100644
--- a/packages/views/editor/readonly-content.test.tsx
+++ b/packages/views/editor/readonly-content.test.tsx
@@ -88,6 +88,7 @@ Object.defineProperty(HTMLCanvasElement.prototype, "getContext", {
import mermaid from "mermaid";
import { ReadonlyContent } from "./readonly-content";
+import { composeAnnotatedReply } from "@multica/core/drafts/reply-annotation";
beforeEach(() => {
vi.clearAllMocks();
@@ -136,6 +137,54 @@ describe("ReadonlyContent line breaks", () => {
});
});
+describe("ReadonlyContent annotated replies", () => {
+ it.each([
+ "steps:\n - name: build\n run: make\n - name: test\n run: make test",
+ "Summary\n---\nDetails\n===",
+ "5. alpha\n6) beta\n+ added\n- removed\n indented code",
+ ])("preserves literal block markers and indentation in a selected quote: %s", (text) => {
+ const { container } = render(<ReadonlyContent content={composeAnnotatedReply("", [{
+ id: "literal", sourceCommentId: "source", sourceActorName: "Agent",
+ quote: text, note: "Keep the source intact", start: 0, prefix: "", suffix: "",
+ }])} />);
+ const quote = container.querySelector("blockquote")!;
+ expect(quote.querySelector("ul, ol, li, h1, h2, hr, pre")).toBeNull();
+ expect(quote.textContent?.replace(/\u00a0/g, " ").trim()).toBe(text);
+ });
+
+ it.each(["A note", ""])("keeps a visible blank paragraph between annotations (note: %s)", (note) => {
+ const first = {
+ id: "first", sourceCommentId: "source", sourceActorName: "Agent",
+ quote: "First quote", note, start: 0, prefix: "", suffix: "",
+ };
+ const { container } = render(<ReadonlyContent content={composeAnnotatedReply("Overall reply", [
+ first, { ...first, id: "second", quote: "Second quote" },
+ ])} />);
+ const quotes = container.querySelectorAll("blockquote");
+ expect(quotes).toHaveLength(2);
+ expect(quotes[1]?.previousElementSibling?.tagName).toBe("P");
+ expect(quotes[1]?.previousElementSibling?.textContent).toBe("\u00a0");
+ expect(container.querySelectorAll("p").length).toBeGreaterThan(2);
+ expect(container.querySelector("a, ol, hr")).toBeNull();
+ });
+
+ it("renders quote snapshots and notes without generated links or numbered lists", () => {
+ const content = composeAnnotatedReply("", [{
+ id: "annotation", sourceCommentId: "source", sourceActorName: "Agent",
+ quote: "First <check>\nSecond line", note: "Please revise this.",
+ start: 0, prefix: "", suffix: "",
+ }]);
+ const { container } = render(<ReadonlyContent content={content} />);
+ const quote = container.querySelector("blockquote");
+ expect(quote?.textContent).toContain("First <check>");
+ expect(quote?.querySelector("br")).not.toBeNull();
+ expect(container.textContent).toContain("Please revise this.");
+ expect(quote?.textContent).not.toContain("Please revise this.");
+ expect(container.querySelector("a, ol, check")).toBeNull();
+ expect(container.textContent).not.toContain("Agent");
+ });
+});
+
describe("ReadonlyContent autolink policy", () => {
it("keeps historical bare filenames and domains as plain text", () => {
const { container } = render(
diff --git a/packages/views/issues/components/comment-annotation-selection.test.ts b/packages/views/issues/components/comment-annotation-selection.test.ts
new file mode 100644
index 0000000000..e07cec922d
--- /dev/null
+++ b/packages/views/issues/components/comment-annotation-selection.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from "vitest";
+import { annotationRange, captureCommentSelection, indexCommentText } from "./comment-annotation-selection";
+import { Editor } from "@tiptap/core";
+import StarterKit from "@tiptap/starter-kit";
+
+function fixture() {
+ document.body.innerHTML = '<div data-annotation-thread="thread"><div data-comment-content="source"><p>Hello <strong>world</strong></p><pre><code>one\ntwo</code><button>Copy</button></pre><p>Last</p></div><div data-comment-content="other">Other reply</div><div data-annotation-thread="nested"><div data-comment-content="nested-source">Nested</div></div></div>';
+ const card = document.body.firstElementChild as HTMLElement;
+ const root = card.firstElementChild as HTMLElement;
+ return { card, root };
+}
+
+function select(start: Node, startOffset: number, end: Node, endOffset: number) {
+ const range = document.createRange();
+ range.setStart(start, startOffset);
+ range.setEnd(end, endOffset);
+ const selection = window.getSelection()!;
+ selection.removeAllRanges(); selection.addRange(range);
+ return selection;
+}
+
+describe("comment annotation selection", () => {
+ it("captures and reanchors real ProseMirror code and paragraph DOM in editable descriptions", () => {
+ document.body.innerHTML = '<div data-annotation-thread="new:issue"><div data-comment-content="description:issue"><div id="editor"></div></div></div>';
+ const card = document.body.firstElementChild as HTMLElement;
+ const root = card.firstElementChild as HTMLElement;
+ const code = "steps:\n - name: build\n run: make";
+ const editor = new Editor({ element: root.firstElementChild as HTMLElement, extensions: [StarterKit], content: {
+ type: "doc", content: [
+ { type: "codeBlock", content: [{ type: "text", text: code }] },
+ { type: "paragraph", content: [{ type: "text", text: "Last" }] },
+ { type: "paragraph" },
+ ],
+ } });
+ try {
+ const first = root.querySelector("code")!.firstChild!;
+ const last = root.querySelector("p")!.firstChild!;
+ const captured = captureCommentSelection(card, select(first, 0, last, 4), true)!;
+ expect(captured.quote).toBe(code + "\nLast");
+ expect(root.querySelector(".ProseMirror-trailingBreak")).not.toBeNull();
+ const range = annotationRange(root, { ...captured, id: "a", sourceActorName: "Description", note: "" }, true)!;
+ expect(range.startContainer).toBe(first);
+ expect(range.endContainer).toBe(last);
+ expect(range.endOffset).toBe(4);
+ } finally { editor.destroy(); }
+ });
+
+ it("captures rendered text and code newlines, excludes controls, and restores the same Range", () => {
+ const { card, root } = fixture();
+ const first = root.querySelector("strong")!.firstChild!;
+ const last = root.querySelector("code")!.firstChild!;
+ const captured = captureCommentSelection(card, select(first, 0, last, 7))!;
+ expect(captured.quote).toBe("world\none\ntwo");
+ expect(indexCommentText(root).text).toBe("Hello world\none\ntwo\nLast\n");
+ const range = annotationRange(root, { ...captured, id: "a", sourceActorName: "Agent", note: "" })!;
+ expect(range.startContainer).toBe(first);
+ expect(range.endContainer).toBe(last);
+ expect(range.endOffset).toBe(7);
+ });
+
+ it("rejects selection spanning comments or owned by a nested card", () => {
+ const { card, root } = fixture();
+ expect(captureCommentSelection(card, select(root.querySelector("strong")!.firstChild!, 0, card.children[1]!.firstChild!, 5))).toBeNull();
+ const nested = card.querySelector('[data-comment-content="nested-source"]')!.firstChild!;
+ expect(captureCommentSelection(card, select(nested, 0, nested, 6))).toBeNull();
+ });
+
+ it("rejects selections in editors, controls, and whitespace", () => {
+ const { card, root } = fixture();
+ const control = root.querySelector("button")!.firstChild!;
+ expect(captureCommentSelection(card, select(control, 0, control, 4))).toBeNull();
+ const first = root.querySelector("p")!.firstChild!;
+ expect(captureCommentSelection(card, select(first, 5, first, 6))).toBeNull();
+ });
+});
diff --git a/packages/views/issues/components/comment-annotation-selection.ts b/packages/views/issues/components/comment-annotation-selection.ts
new file mode 100644
index 0000000000..d8679a5e9f
--- /dev/null
+++ b/packages/views/issues/components/comment-annotation-selection.ts
@@ -0,0 +1,75 @@
+import { locateReplyAnnotation, type ReplyAnnotation } from "@multica/core/drafts/reply-annotation";
+
+const EXCLUDED = 'button, input, textarea, [aria-hidden="true"], [hidden], script, style';
+const BLOCKS = new Set(["P", "DIV", "LI", "PRE", "BLOCKQUOTE", "H1", "H2", "H3", "H4", "H5", "H6", "TR"]);
+
+/** A deterministic visible-text index shared by capture and source navigation.
+ * Block boundaries and code newlines survive; renderer controls are excluded.
+ */
+export function indexCommentText(root: HTMLElement, editable = false) {
+ let text = "";
+ const nodes: { node: Text; start: number; end: number }[] = [];
+ const newline = () => { if (text && !text.endsWith("\n")) text += "\n"; };
+ function visit(node: Node) {
+ if (node.nodeType === Node.TEXT_NODE) {
+ const value = node.textContent ?? "";
+ nodes.push({ node: node as Text, start: text.length, end: text.length + value.length });
+ text += value;
+ } else if (node instanceof HTMLElement) {
+ if (node.matches(EXCLUDED) || (!editable && node.matches('[contenteditable="true"]'))) return;
+ if (node.tagName === "BR") { text += "\n"; return; }
+ const block = BLOCKS.has(node.tagName);
+ if (block) newline();
+ node.childNodes.forEach(visit);
+ if (block) newline();
+ }
+ }
+ root.childNodes.forEach(visit);
+ return { text, nodes };
+}
+
+function contentRoot(node: Node): HTMLElement | null {
+ return (node instanceof Element ? node : node.parentElement)?.closest<HTMLElement>("[data-comment-content]") ?? null;
+}
+
+export function captureCommentSelection(card: HTMLElement, selection: Selection | null, editable = false) {
+ if (!selection || selection.isCollapsed || selection.rangeCount !== 1) return null;
+ const range = selection.getRangeAt(0);
+ const root = contentRoot(range.startContainer);
+ if (!root || root !== contentRoot(range.endContainer) || !card.contains(root) ||
+ root.closest("[data-annotation-thread]") !== card) return null;
+ const { text, nodes } = indexCommentText(root, editable);
+ const selected = nodes.filter(({ node }) => range.intersectsNode(node));
+ const first = selected[0];
+ const last = selected.at(-1);
+ if (!first || !last) return null;
+ const start = first.start + (range.startContainer === first.node ? range.startOffset : 0);
+ const end = last.start + (range.endContainer === last.node ? range.endOffset : last.node.length);
+ if (!text.slice(start, end).trim()) return null;
+ return {
+ sourceCommentId: root.dataset.commentContent!,
+ quote: text.slice(start, end), start,
+ prefix: text.slice(Math.max(0, start - 32), start),
+ suffix: text.slice(end, end + 32),
+ range: range.cloneRange(), root,
+ };
+}
+
+export function annotationRange(root: HTMLElement, annotation: ReplyAnnotation, editable = false): Range | null {
+ const { text, nodes } = indexCommentText(root, editable);
+ const start = locateReplyAnnotation(text, annotation);
+ if (start === null) return null;
+ const end = start + annotation.quote.length;
+ const first = nodes.find((n) => n.start <= start && n.end > start);
+ const last = nodes.find((n) => n.start < end && n.end >= end);
+ if (!first || !last) return null;
+ const range = document.createRange();
+ range.setStart(first.node, start - first.start);
+ range.setEnd(last.node, end - last.start);
+ return range;
+}
+
+export function findAnnotationSource(card: HTMLElement, sourceCommentId: string): HTMLElement | undefined {
+ return Array.from(card.querySelectorAll<HTMLElement>("[data-comment-content]"))
+ .find((node) => node.dataset.commentContent === sourceCommentId && node.closest("[data-annotation-thread]") === card);
+}
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 6385002a9f..337f2d0a2f 100644
--- a/packages/views/issues/components/comment-card-edit-gate.test.tsx
+++ b/packages/views/issues/components/comment-card-edit-gate.test.tsx
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { act, fireEvent, screen, waitFor } from "@testing-library/react";
-import { forwardRef, useEffect, useImperativeHandle, useRef, type ReactNode, type Ref } from "react";
+import { forwardRef, useEffect, useImperativeHandle, useRef, type ComponentProps, type ReactNode, type Ref } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { Attachment, TimelineEntry } from "@multica/core/types";
import type { UploadResult } from "@multica/core/hooks/use-file-upload";
@@ -167,7 +167,7 @@ const entry: TimelineEntry = {
reactions: [],
} as unknown as TimelineEntry;
-function renderCard(onEdit = vi.fn().mockResolvedValue(undefined)) {
+function renderCard(onEdit = vi.fn().mockResolvedValue(undefined), overrides: Partial<ComponentProps<typeof CommentCard>> = {}) {
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const view = renderWithI18n(
<QueryClientProvider client={qc}>
@@ -180,6 +180,7 @@ function renderCard(onEdit = vi.fn().mockResolvedValue(undefined)) {
onEdit={onEdit}
onDelete={vi.fn()}
onToggleReaction={vi.fn()}
+ {...overrides}
/>
</QueryClientProvider>,
);
@@ -363,3 +364,49 @@ describe("comment edit — upload submit gate", () => {
expect(onEdit).not.toHaveBeenCalled();
});
});
+
+// Keep the real card, annotation hook, reply composer and submit wiring together.
+// Source parsing and persistence boundary matrices live in their own suites.
+describe("comment thread — selection reply", () => {
+ it.each([[false, "agent", "agent-1", "comment"], [true, "agent", "agent-1", "comment"], [false, "member", "user-1", "comment"], [false, "member", "other-user", "comment"], [false, "member", "user-1", "note"]] as const)("sends quotes in the source thread and clears overlays (open: %s, author: %s %s, type: %s)", async (keepNoteOpen, actorType, actorId, commentType) => {
+ 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 = vi.fn(() => new DOMRect(20, 30, 120, 20));
+ Range.prototype.getClientRects = vi.fn(() => [] as unknown as DOMRectList);
+ const store = useCommentDraftStore.getState();
+ store.setDraft("new:issue-1", "Task-level draft");
+ store.setDraft("reply:issue-1:other-thread", "Other thread draft");
+ const taskDraft = useCommentDraftStore.getState().drafts["new:issue-1"];
+ const onReply = vi.fn().mockResolvedValue("published-reply");
+ const child: TimelineEntry = { ...entry, id: "agent-child", parent_id: entry.id, actor_type: actorType, actor_id: actorId, comment_type: commentType, content: "Selected agent text" };
+ const { container } = renderCard(undefined, { replies: [child], onReply });
+ const source = container.querySelector<HTMLElement>('[data-comment-content="agent-child"]')!;
+ expect(source).toHaveAttribute("role", "group");
+ expect(source.getAttribute("aria-label")).toMatch(/^Comment by .+/);
+ expect(source).toHaveAttribute("tabindex", "0");
+ fireEvent.pointerDown(source);
+ fireEvent.mouseDown(source);
+ const range = document.createRange();
+ range.selectNodeContents(source);
+ act(() => { window.getSelection()!.removeAllRanges(); window.getSelection()!.addRange(range); });
+ fireEvent.pointerUp(source);
+ fireEvent.mouseUp(source);
+ fireEvent.click(source);
+ fireEvent.click(await screen.findByRole("button", { name: "Add to reply" }));
+ fireEvent.change(await screen.findByRole("textbox", { name: "Comment (optional)" }), { target: { value: "Reply-specific note" } });
+ if (!keepNoteOpen) fireEvent.pointerDown(document.body);
+ expect(container.querySelector('[data-annotation-thread="reply:issue-1:comment-1"]')).toHaveTextContent("1 annotation");
+ expect(screen.queryByRole("button", { name: "Done" })).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Preview reply" })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Send" }));
+ await waitFor(() => expect(onReply).toHaveBeenCalledTimes(1));
+ expect(onReply).toHaveBeenCalledWith("agent-child", "> Selected agent text\n\nReply-specific note", undefined, undefined);
+ await waitFor(() => {
+ expect(useCommentDraftStore.getState().getAnnotations("reply:issue-1:comment-1")).toHaveLength(0);
+ expect(document.querySelector("[data-reply-annotation-overlay]")).not.toBeInTheDocument();
+ });
+ expect(useCommentDraftStore.getState().drafts["new:issue-1"]).toBe(taskDraft);
+ expect(useCommentDraftStore.getState().getDraft("reply:issue-1:other-thread")).toBe("Other thread draft");
+ });
+});
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index b9dee1bf2b..f2fc510ece 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -47,6 +47,7 @@ import { deriveThreadResolution } from "./thread-utils";
import { RevisionConflictCompare } from "./revision-conflict-compare";
import { InlineCommentRun, useInlineCommentRunState, type InlineCommentRunState } from "./inline-comment-run";
import { EMPTY_COMMENT_RUNS, showCommentRunInHeader, type CommentRun } from "./comment-runs";
+import { useCommentAnnotations } from "./use-comment-annotations";
import { useRunCommentMotion } from "./use-run-comment-motion";
const commentActionClassName =
@@ -844,7 +845,9 @@ function CommentRow({
</div>
) : (
<>
- <div data-comment-content={entry.id} className="pl-12 pr-4 max-md:pl-3 max-md:pr-3 text-body leading-relaxed text-foreground">
+ <div tabIndex={currentUserId ? 0 : undefined} role="group"
+ aria-label={t(($) => $.reply.annotations.source_label, { name: entry.actor_name || getActorName(entry.actor_type, entry.actor_id) })}
+ data-comment-content={entry.id} className="pl-12 pr-4 max-md:pl-3 max-md:pr-3 text-body leading-relaxed text-foreground">
<ReadonlyContent content={entry.content ?? ""} attachments={entry.attachments} />
</div>
<AttachmentList attachments={entry.attachments} content={entry.content} className="mt-1.5 pl-12 pr-4 max-md:pl-3 max-md:pr-3" />
@@ -938,6 +941,16 @@ function CommentCardImpl({
const locale = useLocale();
const timeAgo = useTimeAgo();
const { getActorName } = useActorName();
+ const replyTarget = useCommentDraftStore((s) => s.drafts[`reply:${issueId}:${entry.id}`]?.replyTarget);
+ const replyTargetId = replyTarget?.commentId ?? entry.id;
+ const replyTargetMissing = !!replyTarget && replyTargetId !== entry.id && !replies.some((r) => r.id === replyTargetId);
+ const annotation = useCommentAnnotations({
+ draftKey: `reply:${issueId}:${entry.id}`,
+ sources: [entry, ...replies].filter((e) => e.type === "comment")
+ .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); },
+ });
const isCollapsed = useCommentCollapseStore((s) => s.isCollapsed(issueId, entry.id));
const toggleCollapse = useCommentCollapseStore((s) => s.toggle);
const open = !isCollapsed;
@@ -1009,7 +1022,8 @@ function CommentCardImpl({
// overflow-clip (not -hidden) clips the rounded corners WITHOUT creating a
// scroll container, so the sticky collapse affordances below resolve to the
// timeline's scroll parent instead of this card. See PR #3623.
- <Card className="!py-0 !gap-0 overflow-clip transition-colors duration-700">
+ <Card ref={annotation.cardRef} {...annotation.captureProps} className="!py-0 !gap-0 overflow-clip transition-colors duration-700">
+ {annotation.popup}
{onCollapseResolved && (
<button
type="button"
@@ -1257,7 +1271,9 @@ function CommentCardImpl({
</div>
) : (
<>
- <div data-comment-content={entry.id} className="pl-8 max-md:pl-0 text-body leading-relaxed text-foreground">
+ <div tabIndex={currentUserId ? 0 : undefined} role="group"
+ aria-label={t(($) => $.reply.annotations.source_label, { name: entry.actor_name || getActorName(entry.actor_type, entry.actor_id) })}
+ data-comment-content={entry.id} className="pl-8 max-md:pl-0 text-body leading-relaxed text-foreground">
<ReadonlyContent content={entry.content ?? ""} attachments={entry.attachments} />
</div>
<AttachmentList attachments={entry.attachments} content={entry.content} className="mt-1.5 pl-8 max-md:pl-0" />
@@ -1377,13 +1393,15 @@ function CommentCardImpl({
<div className="border-t border-border/50 px-4 max-md:px-3 py-2.5">
<ReplyInput
issueId={issueId}
- parentId={entry.id}
+ parentId={replyTargetId}
+ targetMissing={replyTargetMissing}
placeholder={t(($) => $.reply.placeholder)}
size="sm"
avatarType="member"
avatarId={currentUserId ?? ""}
draftKey={`reply:${issueId}:${entry.id}`}
- onSubmit={(content, attachmentIds, suppressAgentIds) => onReply(entry.id, content, attachmentIds, suppressAgentIds)}
+ onEditAnnotation={(id) => annotation.editAnnotation(id, true)}
+ onSubmit={(content, attachmentIds, suppressAgentIds) => replyTargetMissing ? Promise.resolve(false) : onReply(replyTargetId, content, attachmentIds, suppressAgentIds)}
onAccepted={onReplyAccepted}
/>
</div>
diff --git a/packages/views/issues/components/comment-composers.test.tsx b/packages/views/issues/components/comment-composers.test.tsx
index bd9f6054a3..71e2e3211e 100644
--- a/packages/views/issues/components/comment-composers.test.tsx
+++ b/packages/views/issues/components/comment-composers.test.tsx
@@ -1117,3 +1117,49 @@ describe("sticky composer preference", () => {
expect(screen.getByTestId("editor").parentElement?.className).not.toContain("max-h-[40vh]");
});
});
+
+describe.each(["reply", "description"])("annotations in %s drafts", (source) => {
+ const draftKey = source === "reply" ? "reply:issue-1:comment-1" as const : "new:issue-1" as const;
+ const renderAnnotatedComposer = (onSubmit: Parameters<typeof renderCommentInput>[0]) => source === "reply"
+ ? renderReplyInput({ draftKey: "reply:issue-1:comment-1", onSubmit }) : renderCommentInput(onSubmit);
+ const annotation = { id: "a", sourceCommentId: "agent-source", sourceActorName: "Emacs", quote: "Selected text", note: "Please revise", start: 0, prefix: "", suffix: "" };
+
+ it("sends an annotation-only draft once without requiring a mounted editor", async () => {
+ useCommentDraftStore.getState().addAnnotation(draftKey, annotation);
+ const onSubmit = vi.fn().mockResolvedValue("reply-new");
+ renderAnnotatedComposer(onSubmit);
+ expect(screen.queryByTestId("editor")).not.toBeInTheDocument();
+ const send = screen.getByRole("button", { name: "Send" });
+ fireEvent.click(send);
+ fireEvent.click(send);
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1));
+ expect(onSubmit.mock.calls[0]?.[0]).toContain("> Selected text");
+ expect(onSubmit.mock.calls[0]?.[0]).toContain("Please revise");
+ await waitFor(() => expect(useCommentDraftStore.getState().getAnnotations(draftKey)).toHaveLength(0));
+ });
+
+ it("keeps annotations on failure and blocks quote-only drafts until a note is entered", async () => {
+ useCommentDraftStore.getState().addAnnotation(draftKey, { ...annotation, note: "" });
+ const onSubmit = vi.fn().mockResolvedValue(false);
+ renderAnnotatedComposer(onSubmit);
+ expect(screen.getByRole("button", { name: "Send" })).toBeDisabled();
+ fireEvent.click(screen.getByRole("button", { name: /1 annotation/ }));
+ expect(screen.queryByRole("textbox", { name: "Comment (optional)" })).not.toBeInTheDocument();
+ act(() => useCommentDraftStore.getState().updateAnnotation(draftKey, annotation.id, "New note"));
+ fireEvent.click(screen.getByRole("button", { name: "Send" }));
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1));
+ expect(useCommentDraftStore.getState().getAnnotations(draftKey)[0]?.note).toBe("New note");
+ });
+
+ it("retains new annotations collected while a send is pending", async () => {
+ useCommentDraftStore.getState().addAnnotation(draftKey, annotation);
+ let accept!: (id: string) => void;
+ const onSubmit = vi.fn(() => new Promise<string>((resolve) => { accept = resolve; }));
+ renderAnnotatedComposer(onSubmit);
+ fireEvent.click(screen.getByRole("button", { name: "Send" }));
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1));
+ act(() => { useCommentDraftStore.getState().addAnnotation(draftKey, { ...annotation, id: "b", quote: "Another point" }); });
+ await act(async () => accept("reply-new"));
+ expect(useCommentDraftStore.getState().getAnnotations(draftKey)).toHaveLength(2);
+ });
+});
diff --git a/packages/views/issues/components/comment-input.tsx b/packages/views/issues/components/comment-input.tsx
index 5df8dca227..175a60d84a 100644
--- a/packages/views/issues/components/comment-input.tsx
+++ b/packages/views/issues/components/comment-input.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useRef, useState, useCallback, useEffect } from "react";
+import { useRef, useState, useCallback, useEffect, useMemo } from "react";
import { cn } from "@multica/ui/lib/utils";
import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useUploadGate, useComposerSubmit } from "../../editor";
import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";
@@ -8,6 +8,8 @@ import { SubmitButton } from "@multica/ui/components/common/submit-button";
import { contentReferencesAttachment } from "@multica/core/types";
import { formatShortcut, useShortcut } from "@multica/core/shortcuts";
import { useCommentDraftStore } from "@multica/core/issues/stores";
+import { composeAnnotatedReply, hasReplyIntent } from "@multica/core/drafts/reply-annotation";
+import { ReplyAnnotations } from "./reply-annotations";
import { useT } from "../../i18n";
import { CommentTriggerChips } from "./comment-trigger-chips";
import { useCommentTriggerPreview } from "../hooks/use-comment-trigger-preview";
@@ -23,9 +25,10 @@ interface CommentInputProps {
onSubmit: (content: string, attachmentIds?: string[], suppressAgentIds?: string[]) => Promise<string | boolean>;
/** Called after the server accepts the comment and the composer is cleared. */
onAccepted?: (commentId: string) => void;
+ onEditAnnotation?: (id: string) => boolean;
}
-function CommentInput({ issueId, onSubmit, onAccepted }: CommentInputProps) {
+function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation }: CommentInputProps) {
const { t } = useT("issues");
const { t: tEditor } = useT("editor");
const sendShortcut = useShortcut("send");
@@ -47,7 +50,10 @@ function CommentInput({ issueId, onSubmit, onAccepted }: CommentInputProps) {
const [content, setContent] = useState(initialDraft ?? "");
const [isEmpty, setIsEmpty] = useState(() => !initialDraft?.trim());
const [suppressedAgentIds, setSuppressedAgentIds] = useState<Set<string>>(() => new Set());
- const triggerPreview = useCommentTriggerPreview({ issueId, content });
+ const annotations = useCommentDraftStore((s) => s.getAnnotations(draftKey));
+ const composedContent = useMemo(() => composeAnnotatedReply(content, annotations), [content, annotations]);
+ const canSend = annotations.length ? hasReplyIntent(content, annotations) : !isEmpty;
+ const triggerPreview = useCommentTriggerPreview({ issueId, content: canSend ? composedContent : "" });
// Uploads for this composer session (MUL-5181). Owned by the module-level
// coordinator and persisted in the draft store, so closing/scrolling the
// composer away no longer drops an in-flight upload — its result lands in the
@@ -142,6 +148,10 @@ function CommentInput({ issueId, onSubmit, onAccepted }: CommentInputProps) {
const { submitting, submit } = useComposerSubmit({
editorRef,
uploadGate: gate,
+ normalize: (raw) => {
+ const current = useCommentDraftStore.getState().getAnnotations(draftKey);
+ return hasReplyIntent(raw, current) ? composeAnnotatedReply(raw, current) : "";
+ },
// A top-level comment ends a turn: the caret is dropped rather than kept,
// so the composer stops reading as "still writing" once the comment is
// posted above it. Thread replies are the opposite — see ReplyInput.
@@ -199,6 +209,10 @@ function CommentInput({ issueId, onSubmit, onAccepted }: CommentInputProps) {
{...dropZoneProps}
className="relative flex flex-col rounded-lg bg-card pb-8 ring-1 ring-border"
>
+ {annotations.length > 0 && <div className="px-3 pt-2">
+ <ReplyAnnotations draftKey={draftKey} annotations={annotations} disabled={submitting}
+ onEditAnnotation={onEditAnnotation} />
+ </div>}
{/* Lock the editor while the send is in flight. ContentEditor can't
toggle Tiptap's `editable` post-mount (see its docstring), so the
documented way to make it non-interactive is a pointer-events-none +
@@ -272,7 +286,7 @@ function CommentInput({ issueId, onSubmit, onAccepted }: CommentInputProps) {
<CommentTriggerChips
agents={triggerPreview.agents}
blocked={triggerPreview.blocked}
- draftContent={content}
+ draftContent={composedContent}
suppressedAgentIds={suppressedAgentIds}
onToggle={toggleSuppressedAgent}
/>
@@ -285,12 +299,14 @@ function CommentInput({ issueId, onSubmit, onAccepted }: CommentInputProps) {
/>
<SubmitButton
onClick={submit}
- disabled={isEmpty}
+ disabled={!canSend}
loading={submitting}
busy={gate.uploading}
tooltip={gate.uploading
? tEditor(($) => $.upload.in_progress)
- : sendShortcut
+ : !canSend && annotations.length > 0
+ ? t(($) => $.reply.annotations.intent_hint)
+ : sendShortcut
? `${t(($) => $.comment.send_tooltip)} · ${formatShortcut(sendShortcut)}`
: t(($) => $.comment.send_tooltip)}
ariaLabel={gate.uploading
diff --git a/packages/views/issues/components/comment-selection-bubble.tsx b/packages/views/issues/components/comment-selection-bubble.tsx
new file mode 100644
index 0000000000..22a895921b
--- /dev/null
+++ b/packages/views/issues/components/comment-selection-bubble.tsx
@@ -0,0 +1,60 @@
+"use client";
+
+import { useEffect, useRef, type ReactNode } from "react";
+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 }: {
+ range: Range;
+ source: HTMLElement;
+ children: ReactNode;
+ owner: string;
+ markerRanges?: Range[];
+}) {
+ const ref = useRef<HTMLDivElement>(null);
+ const marker = !!markerRanges;
+ useEffect(() => {
+ const element = ref.current;
+ if (!element) return;
+ let active = true;
+ const anchor = {
+ contextElement: source,
+ getBoundingClientRect: () => {
+ const rect = range.getBoundingClientRect();
+ if (!markerRanges) return rect;
+ // Stack nearby source markers so two quotes on one line remain clickable.
+ const sorted = markerRanges.map((item) => ({ item, top: item.getBoundingClientRect().top }))
+ .sort((a, b) => a.top - b.top);
+ let top = -Infinity;
+ for (const item of sorted) {
+ top = Math.max(top + 28, item.top);
+ if (item.item === range) break;
+ }
+ return new DOMRect(source.getBoundingClientRect().right, top, 0, 24);
+ },
+ };
+ const update = () => {
+ computePosition(anchor, element, {
+ strategy: "fixed",
+ placement: marker ? "right-start" : "top",
+ middleware: [offset(marker ? 4 : 8), flip(), shift({ padding: 8 }), hide()],
+ }).then(({ x, y, middlewareData }) => {
+ if (!active || !element.isConnected) return;
+ element.style.visibility = !source.isConnected || middlewareData.hide?.referenceHidden ? "hidden" : "visible";
+ element.style.left = `${x}px`;
+ element.style.top = `${y}px`;
+ });
+ };
+ const cleanup = autoUpdate(anchor, element, update);
+ return () => { active = false; cleanup(); };
+ }, [range, source, marker, markerRanges]);
+
+ return createPortal(
+ <div ref={ref} data-reply-annotation-overlay={owner}
+ style={{ position: "fixed", zIndex: marker ? 20 : 50, visibility: "hidden", width: "max-content" }}>
+ {children}
+ </div>,
+ document.body,
+ );
+}
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsx
index 734572132a..bbbee12c25 100644
--- a/packages/views/issues/components/issue-detail.test.tsx
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -22,6 +22,7 @@ const mockViewport = vi.hoisted(() => ({ isMobile: false }));
// Counts MockContentEditor mounts. This pins the description to exactly one
// eager editor per issue and catches stale editor reuse across issue switches.
const contentEditorMounts = vi.hoisted(() => ({ count: 0 }));
+const descriptionSelectionAction = vi.hoisted(() => ({ current: undefined as { label: string; onSelect: () => void } | undefined }));
// Stable empty-attachments reference: the real store returns a shared constant
// so the `useCommentDraftStore(s => s.getAttachments(key))` selector keeps a
// stable identity. A fresh `[]` per call would loop useSyncExternalStore.
@@ -177,10 +178,12 @@ vi.mock("../../editor", async () => ({
placeholder,
flushPendingOnUnmount,
onReady,
+ selectionAction,
}: any,
ref: any,
) {
const initialValue = syncedValue ?? defaultValue ?? "";
+ if (syncedValue !== undefined) descriptionSelectionAction.current = selectionAction;
const valueRef = useRef(initialValue);
const baseRef = useRef(initialValue);
const [editorValue, setEditorValue] = useState(initialValue);
@@ -406,6 +409,7 @@ vi.mock("@multica/core/issues/stores", async () => ({
const state = {
drafts: {} as Record<string, { content: string; attachments: unknown[]; updatedAt: number }>,
getDraft: () => undefined,
+ getAnnotations: () => emptyDraftAttachments,
getAttachments: () => emptyDraftAttachments,
getUploads: () => emptyDraftAttachments,
setDraft: () => {},
@@ -422,6 +426,7 @@ vi.mock("@multica/core/issues/stores", async () => ({
getState: () => ({
drafts: {} as Record<string, { content: string; attachments: unknown[]; updatedAt: number }>,
getDraft: () => undefined,
+ getAnnotations: () => emptyDraftAttachments,
getAttachments: () => emptyDraftAttachments,
getUploads: () => emptyDraftAttachments,
setDraft: () => {},
@@ -692,6 +697,7 @@ describe("IssueDetail (shared)", () => {
beforeEach(() => {
vi.clearAllMocks();
contentEditorMounts.count = 0;
+ descriptionSelectionAction.current = undefined;
mockViewport.isMobile = false;
// Default: issue loads successfully
mockApiObj.getIssue.mockResolvedValue(mockIssue);
@@ -810,6 +816,13 @@ describe("IssueDetail (shared)", () => {
);
});
+ it("wires the description selection toolbar to annotation collection", async () => {
+ renderIssueDetail();
+ await screen.findByDisplayValue("Add JWT auth to the backend");
+ expect(descriptionSelectionAction.current?.label).toBe("Add to comment");
+ expect(descriptionSelectionAction.current?.onSelect).toBeTypeOf("function");
+ });
+
it("renders issue title and description after loading", async () => {
renderIssueDetail();
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 022e749c10..12b50c5c1b 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -85,6 +85,7 @@ import { issueTasksOptions } from "@multica/core/issues/queries";
import { SourceContextBadge } from "./source-context-viewer";
import { RevisionConflictCompare } from "./revision-conflict-compare";
import { CommentInput } from "./comment-input";
+import { useCommentAnnotations } from "./use-comment-annotations";
import { CurrentIssueRenderContextProvider } from "../current-issue-render-context";
import { ResolvedThreadBar } from "./resolved-thread-bar";
import { ThreadMinimap, type ThreadMinimapThread } from "./thread-minimap";
@@ -1370,6 +1371,18 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
return cached?.description != null ? cached : undefined;
},
});
+ const descriptionSourceId = `description:${id}`;
+ const descriptionAnnotations = useCommentAnnotations({
+ draftKey: `new:${id}`,
+ sources: [{ id: descriptionSourceId, name: "Description", revision: issue?.revision }],
+ enabled: !!user && !!issue,
+ editable: true,
+ });
+ const canAnnotateDescription = !!user;
+ const descriptionSelectionAction = useMemo(() => canAnnotateDescription ? {
+ label: t(($) => $.reply.annotations.add_comment),
+ onSelect: descriptionAnnotations.addSelection,
+ } : undefined, [canAnnotateDescription, t, descriptionAnnotations.addSelection]);
const openCommentSubIssue = useCallback((commentId: string) => {
if (!issue) return;
openModal("quick-create-issue", {
@@ -3011,6 +3024,8 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
<div
{...descDropZoneProps}
+ {...descriptionAnnotations.captureProps}
+ ref={descriptionAnnotations.cardRef}
className="relative mt-5 rounded-lg"
onFocusCapture={() => {
if (!descriptionEditingRef.current) {
@@ -3023,47 +3038,51 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
}
}}
>
- <ContentEditor
- ref={descEditorRef}
- key={id}
- value={issue.description ?? ""}
- placeholder={t(($) => $.detail.desc_placeholder)}
- onUpdate={(md, baseMarkdown) => {
- // Bind any pending uploads still referenced in the markdown
- // so they appear in `issueAttachments` after refresh and the
- // editor's text/code preview keeps working past reload.
- //
- // Match with `contentReferencesAttachment`, NOT `md.includes(a.url)`:
- // the editor persists the durable `markdownLink`
- // (`/api/attachments/<id>/download` / `markdown_url`) into the
- // body, never the raw storage `a.url`. A bare `md.includes(a.url)`
- // therefore never matches, so the upload is never linked via
- // `attachment_ids`. After reload it's absent from
- // `issueAttachments`, the renderer can't resolve it to a
- // freshly-signed `download_url`, and the persisted auth-gated
- // download endpoint fails to load as a native <img> on clients
- // whose origin isn't the API host (Desktop/Electron, mobile
- // webview) — while still working on web via the cookie/proxy.
- // This mirrors the comment/reply/chat composers, which already
- // bind via `contentReferencesAttachment` (MUL-3130 / MUL-3192).
- const ids = descPendingAttachmentsRef.current
- .filter((a) => contentReferencesAttachment(md, a))
- .map((a) => a.id);
- queueDescriptionSave({
- markdown: md,
- baseMarkdown,
- attachmentIds: ids,
- });
- }}
- onUploadFile={handleDescriptionUpload}
- debounceMs={1500}
- // Closing the issue modal must save what the user last saw —
- // without the flush, a paste followed by a quick close loses
- // the image markdown and its attachment_ids bind (MUL-3254).
- flushPendingOnUnmount
- currentIssueId={id}
- attachments={descEditorAttachments}
- />
+ {descriptionAnnotations.popup}
+ <div data-comment-content={descriptionSourceId}>
+ <ContentEditor
+ ref={descEditorRef}
+ key={id}
+ value={issue.description ?? ""}
+ placeholder={t(($) => $.detail.desc_placeholder)}
+ onUpdate={(md, baseMarkdown) => {
+ // Bind any pending uploads still referenced in the markdown
+ // so they appear in `issueAttachments` after refresh and the
+ // editor's text/code preview keeps working past reload.
+ //
+ // Match with `contentReferencesAttachment`, NOT `md.includes(a.url)`:
+ // the editor persists the durable `markdownLink`
+ // (`/api/attachments/<id>/download` / `markdown_url`) into the
+ // body, never the raw storage `a.url`. A bare `md.includes(a.url)`
+ // therefore never matches, so the upload is never linked via
+ // `attachment_ids`. After reload it's absent from
+ // `issueAttachments`, the renderer can't resolve it to a
+ // freshly-signed `download_url`, and the persisted auth-gated
+ // download endpoint fails to load as a native <img> on clients
+ // whose origin isn't the API host (Desktop/Electron, mobile
+ // webview) — while still working on web via the cookie/proxy.
+ // This mirrors the comment/reply/chat composers, which already
+ // bind via `contentReferencesAttachment` (MUL-3130 / MUL-3192).
+ const ids = descPendingAttachmentsRef.current
+ .filter((a) => contentReferencesAttachment(md, a))
+ .map((a) => a.id);
+ queueDescriptionSave({
+ markdown: md,
+ baseMarkdown,
+ attachmentIds: ids,
+ });
+ }}
+ onUploadFile={handleDescriptionUpload}
+ debounceMs={1500}
+ // Closing the issue modal must save what the user last saw —
+ // without the flush, a paste followed by a quick close loses
+ // the image markdown and its attachment_ids bind (MUL-3254).
+ flushPendingOnUnmount
+ currentIssueId={id}
+ selectionAction={descriptionSelectionAction}
+ attachments={descEditorAttachments}
+ />
+ </div>
<div className="flex items-center gap-1 mt-3">
<ReactionBar
@@ -3431,6 +3450,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
issueId={id}
onSubmit={submitComment}
onAccepted={scrollToTimelineBottom}
+ onEditAnnotation={(annotationId) => descriptionAnnotations.editAnnotation(annotationId, true)}
/>
</div>
</div>
diff --git a/packages/views/issues/components/reply-annotations.test.tsx b/packages/views/issues/components/reply-annotations.test.tsx
new file mode 100644
index 0000000000..c3725c8f26
--- /dev/null
+++ b/packages/views/issues/components/reply-annotations.test.tsx
@@ -0,0 +1,90 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { useCommentDraftStore } from "@multica/core/issues/stores";
+import { renderWithI18n } from "../../test/i18n";
+import { ReplyAnnotations } from "./reply-annotations";
+
+const draftKey = "reply:issue:thread" as const;
+const annotation = { id: "one", sourceCommentId: "source", sourceActorName: "Emacs", quote: "Source text", note: "My note", start: 0, prefix: "", suffix: "" };
+
+function Fixture({ onEdit = () => true }: { onEdit?: (id: string) => boolean }) {
+ const annotations = useCommentDraftStore((s) => s.getAnnotations(draftKey));
+ return annotations.length ? <ReplyAnnotations draftKey={draftKey} annotations={annotations} disabled={false} onEditAnnotation={onEdit} /> : null;
+}
+
+beforeEach(() => {
+ useCommentDraftStore.setState({ drafts: {} });
+ useCommentDraftStore.getState().addAnnotation(draftKey, annotation);
+});
+
+describe("reply annotation summary", () => {
+ it("opens on hover in a portal and returns to the source without expanding the composer", async () => {
+ const user = userEvent.setup();
+ const onEdit = vi.fn(() => true);
+ const { container } = renderWithI18n(<Fixture onEdit={onEdit} />);
+ expect(screen.queryByText("Source text")).not.toBeInTheDocument();
+ await user.hover(screen.getByRole("button", { name: "1 annotation" }));
+ expect(await screen.findByText("Source text")).toBeVisible();
+ expect(container).not.toHaveTextContent("Source text");
+ const popup = screen.getByRole("dialog", { name: "1 annotation" });
+ await user.hover(popup);
+ expect(screen.getByText("My note")).toBeVisible();
+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Preview reply" })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Edit annotation 1" }));
+ expect(onEdit).toHaveBeenCalledWith("one");
+ await waitFor(() => expect(screen.queryByText("Source text")).not.toBeInTheDocument());
+ });
+
+ it("closes after the pointer leaves the trigger and popup", async () => {
+ const user = userEvent.setup();
+ renderWithI18n(<Fixture />);
+ const trigger = screen.getByRole("button", { name: "1 annotation" });
+ await user.hover(trigger);
+ await screen.findByText("Source text");
+ await user.unhover(trigger);
+ await waitFor(() => expect(screen.queryByText("Source text")).not.toBeInTheDocument());
+ });
+
+ it("supports keyboard opening, Escape dismissal and focus return", async () => {
+ const user = userEvent.setup();
+ renderWithI18n(<Fixture />);
+ await user.tab();
+ const trigger = screen.getByRole("button", { name: "1 annotation" });
+ expect(trigger).toHaveFocus();
+ await user.keyboard("{Enter}");
+ await screen.findByText("Source text");
+ await user.tab();
+ expect(screen.getByRole("button", { name: "Edit annotation 1" })).toHaveFocus();
+ await user.keyboard("{Escape}");
+ await waitFor(() => expect(screen.queryByText("Source text")).not.toBeInTheDocument());
+ expect(trigger).toHaveFocus();
+ });
+
+ it("does not steal focus back when a quote opens its source editor", async () => {
+ const user = userEvent.setup();
+ renderWithI18n(<>
+ <textarea aria-label="Source note editor" />
+ <Fixture onEdit={() => {
+ screen.getByRole("textbox", { name: "Source note editor" }).focus();
+ return true;
+ }} />
+ </>);
+ await user.click(screen.getByRole("button", { name: "1 annotation" }));
+ await user.click(await screen.findByRole("button", { name: "Edit annotation 1" }));
+ await waitFor(() => expect(screen.queryByText("Source text")).not.toBeInTheDocument());
+ expect(screen.getByRole("textbox", { name: "Source note editor" })).toHaveFocus();
+ });
+
+ it("keeps an unavailable quote and note readable and removable", async () => {
+ renderWithI18n(<Fixture onEdit={() => false} />);
+ fireEvent.click(screen.getByRole("button", { name: "1 annotation" }));
+ fireEvent.click(await screen.findByRole("button", { name: "Edit annotation 1" }));
+ expect(screen.getByRole("status")).toHaveTextContent("Your saved quote is kept");
+ expect(screen.getByText("My note")).toBeVisible();
+ fireEvent.click(screen.getByRole("button", { name: "Remove annotation 1" }));
+ await waitFor(() => expect(screen.queryByRole("button", { name: "1 annotation" })).not.toBeInTheDocument());
+ expect(useCommentDraftStore.getState().getAnnotations(draftKey)).toHaveLength(0);
+ });
+});
diff --git a/packages/views/issues/components/reply-annotations.tsx b/packages/views/issues/components/reply-annotations.tsx
new file mode 100644
index 0000000000..7c47bcffff
--- /dev/null
+++ b/packages/views/issues/components/reply-annotations.tsx
@@ -0,0 +1,67 @@
+"use client";
+
+import { useRef, useState } from "react";
+import { MessageSquare, X } from "lucide-react";
+import { Button } from "@multica/ui/components/ui/button";
+import { Popover, PopoverContent, PopoverTrigger } from "@multica/ui/components/ui/popover";
+import { useCommentDraftStore, type CommentDraftKey } from "@multica/core/issues/stores";
+import type { ReplyAnnotation } from "@multica/core/drafts/reply-annotation";
+import { useT } from "../../i18n";
+
+export function ReplyAnnotations({ draftKey, annotations, disabled, onEditAnnotation }: {
+ draftKey: CommentDraftKey;
+ annotations: ReplyAnnotation[];
+ disabled: boolean;
+ onEditAnnotation?: (id: string) => boolean;
+}) {
+ const { t } = useT("issues");
+ const [open, setOpen] = useState(false);
+ const [unavailable, setUnavailable] = useState<string | null>(null);
+ const returningToSource = useRef(false);
+ const label = t(($) => $.reply.annotations.count, { count: annotations.length });
+
+ return <div className="mb-2">
+ <Popover open={open} onOpenChange={(next) => {
+ if (next) returningToSource.current = false;
+ setOpen(next);
+ }}>
+ <PopoverTrigger openOnHover delay={150} closeDelay={200}
+ render={<Button variant="outline" size="sm" />}>
+ <MessageSquare />{label}
+ </PopoverTrigger>
+ <PopoverContent side="top" align="start" aria-label={label}
+ className="w-80 max-w-[calc(100vw-16px)]"
+ initialFocus={false}
+ finalFocus={() => !returningToSource.current}
+ onClick={(event) => event.stopPropagation()}>
+ <div className="flex max-h-64 flex-col gap-2 overflow-y-auto">
+ {annotations.map((annotation, index) => <div key={annotation.id} className="flex items-start gap-1">
+ <div className="min-w-0 flex-1">
+ <button type="button" disabled={disabled}
+ aria-label={t(($) => $.reply.annotations.edit, { number: index + 1 })}
+ className="w-full rounded-sm p-1 text-left text-body hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring"
+ onClick={() => {
+ if (onEditAnnotation?.(annotation.id)) {
+ returningToSource.current = true;
+ setOpen(false); setUnavailable(null);
+ }
+ else setUnavailable(annotation.id);
+ }}>
+ <blockquote className="max-h-28 overflow-y-auto whitespace-pre-wrap break-words border-l-2 border-border pl-2 text-muted-foreground">
+ {annotation.quote}
+ </blockquote>
+ {annotation.note && <p className="mt-1 whitespace-pre-wrap break-words">{annotation.note}</p>}
+ </button>
+ {unavailable === annotation.id && <p role="status" className="p-1 text-caption text-muted-foreground">
+ {t(($) => $.reply.annotations.source_changed)}
+ </p>}
+ </div>
+ <Button variant="ghost" size="icon-sm" disabled={disabled}
+ aria-label={t(($) => $.reply.annotations.remove, { number: index + 1 })}
+ onClick={() => useCommentDraftStore.getState().removeAnnotation(draftKey, annotation.id)}><X /></Button>
+ </div>)}
+ </div>
+ </PopoverContent>
+ </Popover>
+ </div>;
+}
diff --git a/packages/views/issues/components/reply-input.tsx b/packages/views/issues/components/reply-input.tsx
index 91642aa764..6c231556b5 100644
--- a/packages/views/issues/components/reply-input.tsx
+++ b/packages/views/issues/components/reply-input.tsx
@@ -1,6 +1,8 @@
"use client";
-import { useRef, useState, useCallback, useEffect } from "react";
+import { composeAnnotatedReply, EMPTY_REPLY_ANNOTATIONS, hasReplyIntent } from "@multica/core/drafts/reply-annotation";
+import { ReplyAnnotations } from "./reply-annotations";
+import { useRef, useState, useCallback, useEffect, useMemo } from "react";
import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useUploadGate, useComposerSubmit } from "../../editor";
import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";
import { SubmitButton } from "@multica/ui/components/common/submit-button";
@@ -36,6 +38,8 @@ interface ReplyInputProps {
* Required for replies inside virtualized timeline threads, where the
* enclosing CommentCard may unmount on scroll-out. */
draftKey?: CommentDraftKey;
+ targetMissing?: boolean;
+ onEditAnnotation?: (id: string) => boolean;
}
// ---------------------------------------------------------------------------
@@ -52,6 +56,8 @@ function ReplyInput({
onAccepted,
size = "default",
draftKey,
+ onEditAnnotation,
+ targetMissing = false,
}: ReplyInputProps) {
const { t } = useT("issues");
const { t: tEditor } = useT("editor");
@@ -74,7 +80,10 @@ function ReplyInput({
const setDraft = useCommentDraftStore((s) => s.setDraft);
const [isEmpty, setIsEmpty] = useState(!initialDraft?.trim());
const [suppressedAgentIds, setSuppressedAgentIds] = useState<Set<string>>(() => new Set());
- const triggerPreview = useCommentTriggerPreview({ issueId, parentId, content });
+ const annotations = useCommentDraftStore((s) => draftKey ? s.getAnnotations(draftKey) : EMPTY_REPLY_ANNOTATIONS);
+ const composedContent = useMemo(() => composeAnnotatedReply(content, annotations), [content, annotations]);
+ const canSend = !targetMissing && (annotations.length ? hasReplyIntent(content, annotations) : !isEmpty);
+ const triggerPreview = useCommentTriggerPreview({ issueId, parentId, content: canSend ? composedContent : "" });
// Uploads for this reply session (MUL-5181) — owned by the coordinator. With
// a draftKey they persist in the draft store so scroll-out/close no longer
// drops an in-flight upload; without one (no persistence context) they fall
@@ -156,6 +165,10 @@ function ReplyInput({
editorRef,
uploadGate: gate,
containerRef: composerRef,
+ normalize: (raw) => {
+ const current = draftKey ? useCommentDraftStore.getState().getAnnotations(draftKey) : EMPTY_REPLY_ANNOTATIONS;
+ return !targetMissing && hasReplyIntent(raw, current) ? composeAnnotatedReply(raw, current) : "";
+ },
// A thread reply is rarely the last thing the user has to say, so the caret
// stays in the box for the next one. Unlike a top-level comment, the posted
// reply lands directly above the box that is still focused — nothing needs
@@ -226,9 +239,14 @@ function ReplyInput({
ref={composerRef}
className={cn(
"relative min-w-0 flex-1 flex flex-col",
- !isEmpty && "pb-9",
+ (!isEmpty || annotations.length > 0) && "pb-9",
)}
>
+ {draftKey && annotations.length > 0 && <>
+ {targetMissing && <p role="alert" className="mb-2 text-caption text-destructive">{t(($) => $.reply.annotations.target_deleted)}</p>}
+ <ReplyAnnotations draftKey={draftKey} annotations={annotations}
+ disabled={submitting} onEditAnnotation={onEditAnnotation} />
+ </>}
{/* Lock the editor while the reply is in flight — see CommentInput. */}
{lazy.active && (
<div
@@ -289,7 +307,7 @@ function ReplyInput({
<CommentTriggerChips
agents={triggerPreview.agents}
blocked={triggerPreview.blocked}
- draftContent={content}
+ draftContent={composedContent}
suppressedAgentIds={suppressedAgentIds}
onToggle={toggleSuppressedAgent}
/>
@@ -302,11 +320,13 @@ function ReplyInput({
/>
<SubmitButton
onClick={submit}
- disabled={isEmpty}
+ disabled={!canSend}
loading={submitting}
busy={gate.uploading}
tooltip={gate.uploading
? tEditor(($) => $.upload.in_progress)
+ : !canSend && annotations.length > 0 && !targetMissing
+ ? t(($) => $.reply.annotations.intent_hint)
: sendShortcut
? `${t(($) => $.comment.send_tooltip)} · ${formatShortcut(sendShortcut)}`
: t(($) => $.comment.send_tooltip)}
diff --git a/packages/views/issues/components/use-comment-annotations.test.tsx b/packages/views/issues/components/use-comment-annotations.test.tsx
new file mode 100644
index 0000000000..f0a7172b80
--- /dev/null
+++ b/packages/views/issues/components/use-comment-annotations.test.tsx
@@ -0,0 +1,221 @@
+import { act, fireEvent, screen, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+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 { toast } from "sonner";
+
+vi.mock("sonner", () => ({ toast: { error: vi.fn() } }));
+
+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 }) {
+ const annotation = useCommentAnnotations({
+ draftKey: key, sources: [{ id: entry.id, name: actorType }], enabled: true,
+ });
+ return <div ref={annotation.cardRef} {...annotation.captureProps}>
+ {annotation.popup}
+ <div key={sourceKey} data-comment-content="root" tabIndex={0}>Selected text</div>
+ </div>;
+}
+
+function DescriptionFixture({ issueId = "issue", loaded = true }: { issueId?: string; loaded?: boolean }) {
+ const sourceId = `description:${issueId}`;
+ const annotations = useCommentAnnotations({
+ draftKey: `new:${issueId}`, sources: [{ id: sourceId, name: "Description" }], enabled: loaded, editable: true,
+ });
+ if (!loaded) return null;
+ return <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>;
+}
+
+function selectText(container: HTMLElement, input: "mouse" | "keyboard" = "mouse") {
+ const source = container.querySelector<HTMLElement>("[data-comment-content]")!;
+ if (input === "mouse") {
+ fireEvent.pointerDown(source, { pointerType: "mouse", button: 0 });
+ fireEvent.mouseDown(source, { button: 0 });
+ } else {
+ source.focus();
+ fireEvent.keyDown(source, { key: "ArrowRight", shiftKey: true });
+ }
+ const range = document.createRange();
+ range.selectNodeContents(source);
+ act(() => {
+ window.getSelection()!.removeAllRanges();
+ window.getSelection()!.addRange(range);
+ });
+ if (input === "mouse") {
+ fireEvent.pointerUp(source);
+ fireEvent.mouseUp(source, { button: 0 });
+ fireEvent.click(source, { button: 0 });
+ } else {
+ fireEvent.keyUp(source, { key: "ArrowRight", shiftKey: true });
+ }
+ return source;
+}
+
+beforeEach(() => {
+ 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 });
+ Object.defineProperty(document.documentElement, "clientHeight", { configurable: true, value: 768 });
+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue(new DOMRect(10, 10, 600, 400));
+ Range.prototype.getBoundingClientRect = vi.fn(() => new DOMRect(10, 10, 120, 20));
+ Range.prototype.getClientRects = vi.fn(() => [] as unknown as DOMRectList);
+});
+
+describe("selection to reply", () => {
+ 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}>
+ {description ? <DescriptionFixture /> : <Fixture />}
+ </Profiler>);
+ const count = onRender.mock.calls.length;
+ const source = container.querySelector(description ? "[contenteditable]" : "[data-comment-content]")!;
+ for (let i = 0; i < 10; i++) {
+ await act(async () => { source.firstChild!.textContent += "x"; });
+ }
+ expect(onRender).toHaveBeenCalledTimes(count);
+ });
+
+ it("reports an uncapturable description selection without adding a draft", () => {
+ renderWithI18n(<DescriptionFixture />);
+ window.getSelection()?.removeAllRanges();
+ fireEvent.click(screen.getByRole("button", { name: "Add to comment" }));
+ expect(toast.error).toHaveBeenCalledWith("Could not capture the selection. Select text within one comment or description and try again.");
+ expect(useCommentDraftStore.getState().getAnnotations("new:issue")).toHaveLength(0);
+ });
+
+ it.each([false, true])("removes a saved annotation at its source and preserves the rest of the draft (description: %s)", async (description) => {
+ const draftKey = description ? "new:issue" as const : key;
+ const sourceId = description ? "description:issue" : "root";
+ const store = useCommentDraftStore.getState();
+ store.setDraft(draftKey, "Keep my overall reply");
+ for (const [id, quote, start] of [["first", "Selected", 0], ["second", "text", 9]] as const) {
+ store.addAnnotation(draftKey, { id, sourceCommentId: sourceId, sourceActorName: "Author",
+ quote, start, prefix: "", suffix: "", note: `Note ${id}` });
+ }
+ const { container } = renderWithI18n(description ? <DescriptionFixture /> : <Fixture />);
+ const source = container.querySelector<HTMLElement>(description ? "[contenteditable]" : "[data-comment-content]")!;
+ fireEvent.click(await screen.findByRole("button", { name: "Edit annotation 1" }));
+ expect(await screen.findByRole("textbox", { name: "Comment (optional)" })).toHaveValue("Note first");
+ const remove = screen.getByRole("button", { name: "Remove annotation 1" });
+ fireEvent.pointerDown(remove);
+ fireEvent.click(remove);
+ await waitFor(() => expect(screen.queryByRole("textbox")).not.toBeInTheDocument());
+ expect(source).toHaveFocus();
+ expect(source).toHaveTextContent("Selected text");
+ expect(store.getAnnotations(draftKey).map((a) => a.id)).toEqual(["second"]);
+ expect(store.getDraft(draftKey)).toBe("Keep my overall reply");
+ expect(screen.queryByRole("button", { name: "Edit annotation 2" })).not.toBeInTheDocument();
+
+ fireEvent.click(await screen.findByRole("button", { name: "Edit annotation 1" }));
+ expect(await screen.findByRole("textbox", { name: "Comment (optional)" })).toHaveValue("Note second");
+ fireEvent.click(screen.getByRole("button", { name: "Remove annotation 1" }));
+ await waitFor(() => expect(screen.queryByRole("button", { name: "Edit annotation 1" })).not.toBeInTheDocument());
+ expect(store.getAnnotations(draftKey)).toHaveLength(0);
+ expect(store.getDraft(draftKey)).toBe("Keep my overall reply");
+ expect(useCommentDraftStore.getState().drafts[draftKey]?.replyTarget).toBeUndefined();
+ });
+ it("restores saved source markers when the description loads asynchronously", async () => {
+ useCommentDraftStore.getState().addAnnotation("new:issue", {
+ id: "saved", sourceCommentId: "description:issue", sourceActorName: "Description",
+ quote: "Selected text", note: "Saved note", start: 0, prefix: "", suffix: "\n",
+ });
+ const { rerender } = renderWithI18n(<DescriptionFixture loaded={false} />);
+ rerender(<DescriptionFixture />);
+ fireEvent.click(await screen.findByRole("button", { name: "Edit annotation 1" }));
+ expect(await screen.findByRole("textbox", { name: "Comment (optional)" })).toHaveValue("Saved note");
+ });
+ it("captures editable descriptions into a new thread draft and clears the popup on issue switch", async () => {
+ const { container, rerender } = renderWithI18n(<DescriptionFixture />);
+ selectText(container);
+ expect(screen.queryByRole("button", { name: "Add to reply" })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Add to comment" }));
+ fireEvent.change(await screen.findByRole("textbox", { name: "Comment (optional)" }), { target: { value: "Question about description" } });
+ expect(useCommentDraftStore.getState().getAnnotations("new:issue")[0]).toMatchObject({ quote: "Selected text", note: "Question about description" });
+ expect(useCommentDraftStore.getState().drafts["new:issue"]?.replyTarget).toBeUndefined();
+ expect(container.querySelector("[contenteditable]")).toHaveTextContent("Selected text");
+ rerender(<DescriptionFixture issueId="other" />);
+ await waitFor(() => expect(screen.queryByRole("textbox", { name: "Comment (optional)" })).not.toBeInTheDocument());
+ expect(useCommentDraftStore.getState().getAnnotations("new:other")).toHaveLength(0);
+ expect(useCommentDraftStore.getState().getAnnotations("new:issue")).toHaveLength(1);
+ });
+ it("keeps the source note usable when expanding the thread remounts its body", async () => {
+ const view = renderWithI18n(<Fixture />);
+ selectText(view.container);
+ fireEvent.click(await screen.findByRole("button", { name: "Add to reply" }));
+ fireEvent.change(await screen.findByRole("textbox", { name: "Comment (optional)" }), { target: { value: "Keep this note" } });
+ view.rerender(<Fixture sourceKey="expanded" />);
+ await waitFor(() => expect(screen.getByRole("textbox", { name: "Comment (optional)" })).toBeVisible());
+ expect(screen.getByRole("textbox", { name: "Comment (optional)" })).toHaveValue("Keep this note");
+ });
+ it("saves before typing, autosaves the note, and reopens duplicates without erasing it", async () => {
+ const { container } = renderWithI18n(<Fixture />);
+ selectText(container);
+ fireEvent.click(await screen.findByRole("button", { name: "Add to reply" }));
+ const note = await screen.findByRole("textbox", { name: "Comment (optional)" });
+ expect(useCommentDraftStore.getState().getAnnotations(key)).toHaveLength(1);
+ fireEvent.change(note, { target: { value: "Please explain" } });
+ expect(screen.queryByRole("button", { name: "Done" })).not.toBeInTheDocument();
+ fireEvent.pointerDown(document.body);
+ await waitFor(() => expect(screen.queryByRole("textbox")).not.toBeInTheDocument());
+ selectText(container);
+ fireEvent.click(await screen.findByRole("button", { name: "Add to reply" }));
+ expect(await screen.findByRole("textbox", { name: "Comment (optional)" })).toHaveValue("Please explain");
+ expect(useCommentDraftStore.getState().getAnnotations(key)).toHaveLength(1);
+ fireEvent.keyDown(screen.getByRole("textbox"), { key: "Escape" });
+ await waitFor(() => expect(screen.queryByRole("textbox")).not.toBeInTheDocument());
+ expect(useCommentDraftStore.getState().getAnnotations(key)[0]?.note).toBe("Please explain");
+ fireEvent.click(await screen.findByRole("button", { name: "Edit annotation 1" }));
+ expect(await screen.findByRole("textbox", { name: "Comment (optional)" })).toHaveValue("Please explain");
+ });
+
+ it("offers annotations on member comments", async () => {
+ const { container } = renderWithI18n(<Fixture actorType="member" />);
+ selectText(container);
+ expect(await screen.findByRole("button", { name: "Add to reply" })).toBeInTheDocument();
+ });
+
+ it("keeps the action open through the mouseup and click that finish a drag", async () => {
+ const { container } = renderWithI18n(<Fixture />);
+ selectText(container);
+ expect(await screen.findByRole("button", { name: "Add to reply" })).toBeVisible();
+ fireEvent.pointerDown(document.body, { pointerType: "mouse", button: 0 });
+ fireEvent.mouseDown(document.body, { button: 0 });
+ fireEvent.pointerUp(document.body);
+ fireEvent.mouseUp(document.body, { button: 0 });
+ fireEvent.click(document.body, { button: 0 });
+ await waitFor(() => expect(screen.queryByRole("button", { name: "Add to reply" })).not.toBeInTheDocument());
+ });
+
+ it("dismisses when the next gesture clears the selection in the source", async () => {
+ const { container } = renderWithI18n(<Fixture />);
+ const source = selectText(container);
+ expect(await screen.findByRole("button", { name: "Add to reply" })).toBeVisible();
+ fireEvent.pointerDown(source, { pointerType: "mouse", button: 0 });
+ fireEvent.mouseDown(source, { button: 0 });
+ act(() => window.getSelection()!.removeAllRanges());
+ fireEvent.pointerUp(source);
+ fireEvent.mouseUp(source, { button: 0 });
+ fireEvent.click(source, { button: 0 });
+ await waitFor(() => expect(screen.queryByRole("button", { name: "Add to reply" })).not.toBeInTheDocument());
+ });
+
+ it("makes the action reachable from a keyboard selection without trapping Tab", async () => {
+ const { container } = renderWithI18n(<Fixture />);
+ const source = selectText(container, "keyboard");
+ const action = await screen.findByRole("button", { name: "Add to reply" });
+ fireEvent.keyDown(source, { key: "Tab" });
+ expect(action).toHaveFocus();
+ const event = new KeyboardEvent("keydown", { key: "Tab", bubbles: true, cancelable: true });
+ action.dispatchEvent(event);
+ expect(event.defaultPrevented).toBe(false);
+ });
+});
diff --git a/packages/views/issues/components/use-comment-annotations.tsx b/packages/views/issues/components/use-comment-annotations.tsx
new file mode 100644
index 0000000000..d46bdf0f87
--- /dev/null
+++ b/packages/views/issues/components/use-comment-annotations.tsx
@@ -0,0 +1,251 @@
+"use client";
+
+import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
+import { MessageSquarePlus, Trash2 } from "lucide-react";
+import { toast } from "sonner";
+import { Button } from "@multica/ui/components/ui/button";
+import { useCommentDraftStore, type CommentDraftKey } from "@multica/core/issues/stores";
+import { MAX_ANNOTATION_QUOTE_LENGTH, MAX_REPLY_ANNOTATIONS } from "@multica/core/drafts/reply-annotation";
+import { useT } from "../../i18n";
+import { annotationRange, captureCommentSelection, findAnnotationSource } from "./comment-annotation-selection";
+import { CommentSelectionBubble } from "./comment-selection-bubble";
+
+type CapturedSelection = NonNullable<ReturnType<typeof captureCommentSelection>>;
+type SourceAnchor = { id: string; range: Range; root: HTMLElement };
+
+export function useCommentAnnotations({ draftKey, sources, enabled, onAdded, editable = false }: {
+ draftKey: CommentDraftKey;
+ sources: { id: string; name: string; revision?: number }[];
+ enabled: boolean;
+ onAdded?: () => void;
+ /** Editable descriptions use their existing toolbar to call addSelection. */
+ editable?: boolean;
+}) {
+ const { t } = useT("issues");
+ const cardRef = useRef<HTMLDivElement>(null);
+ const inputRef = useRef<HTMLTextAreaElement>(null);
+ const actionRef = useRef<HTMLButtonElement>(null);
+ const [selection, setSelection] = useState<CapturedSelection | null>(null);
+ const [editingId, setEditingId] = useState<string | null>(null);
+ const [error, setError] = useState(false);
+ const [anchors, setAnchors] = useState<SourceAnchor[]>([]);
+ const markerRanges = useMemo(() => {
+ const groups = new Map<HTMLElement, Range[]>();
+ for (const anchor of anchors) {
+ const group = groups.get(anchor.root) ?? [];
+ group.push(anchor.range); groups.set(anchor.root, group);
+ }
+ return groups;
+ }, [anchors]);
+ const annotations = useCommentDraftStore((s) => s.getAnnotations(draftKey));
+ const annotationsRef = useRef(annotations);
+ annotationsRef.current = annotations;
+ const sourcesRef = useRef(sources);
+ sourcesRef.current = sources;
+ const onAddedRef = useRef(onAdded);
+ onAddedRef.current = onAdded;
+ const anchorKey = annotations.map((a) => a.id).join(",");
+ const editing = annotations.find((a) => a.id === editingId);
+ const highlightName = `reply-annotation-${useId().replace(/[^a-zA-Z0-9-]/g, "")}`;
+
+ const close = (restoreFocus = false) => {
+ if (restoreFocus && selection?.root.isConnected) {
+ const target = editable ? selection.root.querySelector<HTMLElement>("[contenteditable=true]") ?? selection.root : selection.root;
+ target.focus({ preventScroll: true });
+ }
+ setSelection(null); setEditingId(null); setError(false);
+ };
+ const readSelection = useCallback(() => {
+ if (!enabled || !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]);
+ const capture = () => {
+ const captured = readSelection();
+ if (captured) { setSelection(captured); setEditingId(null); setError(false); }
+ };
+
+ useEffect(() => { setSelection(null); setEditingId(null); setError(false); }, [draftKey]);
+
+ // Dismiss on the next press, never on the click completing the opening drag.
+ useEffect(() => {
+ if (!selection) return;
+ const onPointerDown = (event: PointerEvent) => {
+ if (event.target instanceof Element &&
+ event.target.closest("[data-reply-annotation-overlay]")?.getAttribute("data-reply-annotation-overlay") === draftKey) return;
+ setSelection(null); setEditingId(null); setError(false);
+ };
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key !== "Escape") return;
+ if (selection.root.isConnected) selection.root.focus({ preventScroll: true });
+ setSelection(null); setEditingId(null); setError(false);
+ };
+ const onFocusIn = (event: FocusEvent) => {
+ 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); setEditingId(null); setError(false);
+ };
+ document.addEventListener("pointerdown", onPointerDown);
+ document.addEventListener("keydown", onKeyDown);
+ document.addEventListener("focusin", onFocusIn);
+ return () => {
+ document.removeEventListener("pointerdown", onPointerDown);
+ document.removeEventListener("keydown", onKeyDown);
+ document.removeEventListener("focusin", onFocusIn);
+ };
+ }, [selection, draftKey]);
+
+ useEffect(() => {
+ if (editingId && window.matchMedia("(pointer: fine)").matches) inputRef.current?.focus({ preventScroll: true });
+ }, [editingId]);
+
+ useEffect(() => {
+ if (!anchorKey) {
+ setAnchors((current) => current.length ? [] : current);
+ return;
+ }
+ if (!enabled || !cardRef.current) return;
+ const card = cardRef.current;
+ const canHighlight = typeof Highlight !== "undefined" && typeof CSS !== "undefined" && !!CSS.highlights;
+ const update = () => {
+ const next = annotationsRef.current.flatMap((a) => {
+ const root = findAnnotationSource(card, a.sourceCommentId);
+ const range = root && annotationRange(root, a, editable);
+ return root && range ? [{ id: a.id, range, root }] : [];
+ });
+ setAnchors((current) => !current.length && !next.length ? current : next);
+ // Expanding a resolved thread may remount the selected comment's body.
+ // Keep the note editor attached to its saved quote, never a detached Range.
+ setSelection((current) => {
+ if (!current || current.root.isConnected) return current;
+ const saved = annotationsRef.current.find((a) => a.sourceCommentId === current.sourceCommentId &&
+ a.start === current.start && a.quote === current.quote);
+ const anchor = saved && next.find((a) => a.id === saved.id);
+ return anchor ? { ...current, root: anchor.root, range: anchor.range } : null;
+ });
+ if (canHighlight) CSS.highlights.set(highlightName, new Highlight(...next.map((a) => a.range)));
+ };
+ update();
+ const observer = new MutationObserver((records) => {
+ // Reply typing must not re-index a long source comment.
+ if (records.some((record) => {
+ const target = record.target instanceof Element ? record.target : record.target.parentElement;
+ return target?.closest("[data-comment-content]") ||
+ [...record.addedNodes, ...record.removedNodes].some((node) => node instanceof Element &&
+ (node.matches("[data-comment-content]") || node.querySelector("[data-comment-content]")));
+ })) update();
+ });
+ observer.observe(card, { childList: true, subtree: true, characterData: true });
+ return () => { observer.disconnect(); if (canHighlight) CSS.highlights.delete(highlightName); };
+ }, [anchorKey, highlightName, draftKey, editable, enabled]);
+
+ useEffect(() => {
+ if (editingId && !editing) { setSelection(null); setEditingId(null); }
+ }, [editingId, editing]);
+
+ const editAnnotation = (id: string, scrollToSource = false): boolean => {
+ 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);
+ if (!root || !range || !annotation) return false;
+ if (scrollToSource) {
+ const element = range.startContainer instanceof Element ? range.startContainer : range.startContainer.parentElement;
+ element?.scrollIntoView({ block: "center", behavior: "instant" });
+ }
+ setSelection({ ...annotation, range, root }); setEditingId(id); setError(false);
+ return true;
+ };
+
+ const add = useCallback((captured: CapturedSelection | null) => {
+ const source = captured && sourcesRef.current.find((e) => e.id === captured.sourceCommentId);
+ if (!captured || !source) {
+ toast.error(t(($) => $.reply.annotations.selection_failed));
+ return false;
+ }
+ const { quote, start, prefix, suffix, sourceCommentId } = captured;
+ const id = useCommentDraftStore.getState().addAnnotation(draftKey, {
+ id: crypto.randomUUID(), sourceCommentId,
+ sourceActorName: source.name,
+ sourceRevision: source.revision, quote, start, prefix, suffix, note: "",
+ });
+ if (!id) {
+ setError(true);
+ toast.error(captured.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 }));
+ return false;
+ }
+ setSelection(captured);
+ setEditingId(id);
+ setError(false);
+ window.getSelection()?.removeAllRanges();
+ onAddedRef.current?.();
+ return true;
+ }, [draftKey, t]);
+ const addSelection = useCallback(() => add(readSelection()), [add, readSelection]);
+
+ return {
+ cardRef,
+ editAnnotation,
+ addSelection,
+ captureProps: {
+ "data-annotation-thread": draftKey,
+ onPointerUp: (event: React.PointerEvent) => {
+ if (!editable && event.target instanceof Element && event.target.closest("[data-comment-content]") &&
+ !event.target.closest("button, [contenteditable=true]")) capture();
+ },
+ onKeyUp: (event: React.KeyboardEvent) => {
+ if (!editable && event.shiftKey && event.key.startsWith("Arrow")) capture();
+ },
+ onKeyDown: (event: React.KeyboardEvent) => {
+ if (event.key === "Tab" && !event.shiftKey && selection && !editingId &&
+ event.target instanceof Element && event.target.closest("[data-comment-content]")) {
+ event.preventDefault(); actionRef.current?.focus();
+ }
+ },
+ },
+ popup: <>
+ {annotations.length > 0 && <style>{`::highlight(${highlightName}) { background: color-mix(in srgb, var(--brand) 20%, transparent); }`}</style>}
+ {enabled && anchors.map((anchor) => {
+ const index = annotations.findIndex((a) => a.id === anchor.id);
+ if (index < 0) return null;
+ return <CommentSelectionBubble key={anchor.id} range={anchor.range} source={anchor.root} owner={draftKey}
+ markerRanges={markerRanges.get(anchor.root)}>
+ <Button variant="brandSubtle" size="icon-sm" className="size-6 rounded-full text-caption"
+ aria-label={t(($) => $.reply.annotations.edit, { number: index + 1 })}
+ onClick={() => editAnnotation(anchor.id)}>{index + 1}</Button>
+ </CommentSelectionBubble>;
+ })}
+ {enabled && selection && <CommentSelectionBubble range={selection.range} source={selection.root} owner={draftKey}>
+ <div className="bubble-menu max-w-[calc(100vw-16px)]">
+ {editing ? <><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 w-72 min-w-0 resize-none rounded-sm bg-transparent px-2 py-1 text-body outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring"
+ onChange={(event) => useCommentDraftStore.getState().updateAnnotation(draftKey, editing.id, event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && !event.nativeEvent.isComposing && !event.shiftKey && !event.metaKey && !event.ctrlKey) {
+ event.preventDefault(); close(true);
+ }
+ }} />
+ <Button variant="ghost" size="icon-sm" className="self-start text-muted-foreground hover:text-destructive"
+ aria-label={t(($) => $.reply.annotations.remove, { number: annotations.indexOf(editing) + 1 })}
+ title={t(($) => $.reply.annotations.remove, { number: annotations.indexOf(editing) + 1 })}
+ onClick={() => {
+ useCommentDraftStore.getState().removeAnnotation(draftKey, editing.id);
+ close(true);
+ }}><Trash2 /></Button>
+ </> : <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>}
+ </div>
+ {error && <p role="alert" className="mt-1 max-w-72 rounded-lg bg-popover p-2 text-caption text-destructive shadow-[var(--menu-shadow)]">
+ {selection.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 })}
+ </p>}
+ </CommentSelectionBubble>}
+ </>,
+ };
+}
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 7725555998..f4fa793574 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -569,7 +569,24 @@
}
},
"reply": {
- "placeholder": "Leave a reply..."
+ "placeholder": "Leave a reply...",
+ "annotations": {
+ "add_comment": "Add to comment",
+ "add": "Add to reply",
+ "note_label": "Comment (optional)",
+ "count_one": "{{count}} annotation",
+ "count_other": "{{count}} annotations",
+ "quote_limit": "Select up to {{count}} characters at a time.",
+ "count_limit": "A comment can contain up to {{count}} annotations.",
+ "remove": "Remove annotation {{number}}",
+ "source_changed": "The source changed or is unavailable. Your saved quote is kept.",
+ "intent_hint": "Add a note to an annotation or write a message before sending.",
+ "target_deleted": "The reply target was deleted. Remove all annotations in this draft, then annotate a remaining comment to start a new reply.",
+ "selection_failed": "Could not capture the selection. Select text within one comment or description and try again.",
+ "source_label": "Comment by {{name}}",
+ "edit": "Edit annotation {{number}}",
+ "note_placeholder": "Add an optional comment…"
+ }
},
"agent_activity": {
"hover_header_one": "{{count}} active agent",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 8e377631ef..dbaf537cec 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -554,7 +554,23 @@
}
},
"reply": {
- "placeholder": "返信を残す..."
+ "placeholder": "返信を残す...",
+ "annotations": {
+ "add_comment": "コメントに追加",
+ "add": "返信に追加",
+ "note_label": "コメント(任意)",
+ "count_other": "{{count}} 件の注釈",
+ "quote_limit": "一度に選択できるのは {{count}} 文字までです。",
+ "count_limit": "コメントに追加できる注釈は {{count}} 件までです。",
+ "remove": "注釈 {{number}} を削除",
+ "source_changed": "原文が変更されたか、利用できません。保存した引用は保持されます。",
+ "intent_hint": "注釈のコメントか本文を入力してから送信してください。",
+ "target_deleted": "返信先が削除されました。この下書きの注釈をすべて削除し、残っているコメントの文字を選択して注釈を追加し直してください。",
+ "selection_failed": "選択範囲を取得できませんでした。同じコメントまたは説明の中で文字を選び直してください。",
+ "source_label": "{{name}} のコメント",
+ "edit": "注釈 {{number}} を編集",
+ "note_placeholder": "コメントを追加(任意)…"
+ }
},
"agent_activity": {
"hover_header_other": "作業中のエージェント {{count}} 件",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index ca6f7a1fda..0e9d6500e4 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -554,7 +554,23 @@
}
},
"reply": {
- "placeholder": "답글 남기기..."
+ "placeholder": "답글 남기기...",
+ "annotations": {
+ "add_comment": "댓글에 추가",
+ "add": "답글에 추가",
+ "note_label": "코멘트 (선택 사항)",
+ "count_other": "주석 {{count}}개",
+ "quote_limit": "한 번에 최대 {{count}}자까지 선택할 수 있습니다.",
+ "count_limit": "댓글에 주석을 최대 {{count}}개까지 추가할 수 있습니다.",
+ "remove": "주석 {{number}} 삭제",
+ "source_changed": "원문이 변경되었거나 사용할 수 없습니다. 저장한 인용문은 유지됩니다.",
+ "intent_hint": "주석에 의견을 추가하거나 본문을 작성한 후 전송하세요.",
+ "target_deleted": "답글 대상이 삭제되었습니다. 이 초안의 주석을 모두 삭제한 뒤, 남아 있는 댓글의 텍스트를 선택해 주석을 다시 추가하세요.",
+ "selection_failed": "선택한 텍스트를 가져오지 못했습니다. 같은 댓글이나 설명 안에서 텍스트를 다시 선택하세요.",
+ "source_label": "{{name}}의 댓글",
+ "edit": "주석 {{number}} 편집",
+ "note_placeholder": "의견 추가 (선택 사항)…"
+ }
},
"agent_activity": {
"hover_header_other": "작업 중인 에이전트 {{count}}개",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index bb60771583..2e12fe99c9 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -554,7 +554,23 @@
}
},
"reply": {
- "placeholder": "回复..."
+ "placeholder": "回复...",
+ "annotations": {
+ "add_comment": "加入评论",
+ "add": "加入回复",
+ "note_label": "批注(可选)",
+ "count_other": "{{count}} 条批注",
+ "quote_limit": "每次最多选择 {{count}} 个字符。",
+ "count_limit": "一条评论最多包含 {{count}} 条批注。",
+ "remove": "移除第 {{number}} 条批注",
+ "source_changed": "原文已更改或不可用,已保留你保存的引用。",
+ "intent_hint": "请填写至少一条批注意见或评论正文后再发送。",
+ "target_deleted": "回复目标已删除。请移除此草稿中的全部批注,再选择仍存在的评论文字重新添加批注。",
+ "selection_failed": "未能获取选中文字。请在同一条评论或任务描述内重新选择后再试。",
+ "source_label": "{{name}} 的评论",
+ "edit": "编辑批注 {{number}}",
+ "note_placeholder": "添加意见(可选)…"
+ }
},
"agent_activity": {
"hover_header_other": "{{count}} 个智能体工作中",