Skip to content

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

Go

feat(docs): comment on selected text in docs (MUL-8370) (#10981)

Multica Eve787e284cd8bb
diff --git a/apps/mobile/components/inbox/detail-label.tsx b/apps/mobile/components/inbox/detail-label.tsx
index 7b8cd66b74..9ab6b2f805 100644
--- a/apps/mobile/components/inbox/detail-label.tsx
+++ b/apps/mobile/components/inbox/detail-label.tsx
@@ -46,6 +46,8 @@ const TYPE_KEY: Record<InboxItemType, string> = {
due_date_changed: "type.due_date_changed",
new_comment: "type.new_comment",
mentioned: "type.mentioned",
+ doc_comment: "type.doc_comment",
+ doc_mentioned: "type.doc_mentioned",
review_requested: "type.review_requested",
task_completed: "type.task_completed",
task_failed: "type.task_failed",
diff --git a/apps/mobile/locales/en/inbox.json b/apps/mobile/locales/en/inbox.json
index 8e8227820e..9efdc45b9c 100644
--- a/apps/mobile/locales/en/inbox.json
+++ b/apps/mobile/locales/en/inbox.json
@@ -55,6 +55,8 @@
"due_date_changed": "Due date changed",
"new_comment": "New comment",
"mentioned": "Mentioned",
+ "doc_comment": "New comment on a doc",
+ "doc_mentioned": "Mentioned in a doc",
"review_requested": "Review requested",
"task_completed": "Task completed",
"task_failed": "Task failed",
diff --git a/apps/mobile/locales/zh-Hans/inbox.json b/apps/mobile/locales/zh-Hans/inbox.json
index e8ed5f1609..ec6a34372a 100644
--- a/apps/mobile/locales/zh-Hans/inbox.json
+++ b/apps/mobile/locales/zh-Hans/inbox.json
@@ -55,6 +55,8 @@
"due_date_changed": "截止日期已更改",
"new_comment": "新评论",
"mentioned": "提到了你",
+ "doc_comment": "文档有新评论",
+ "doc_mentioned": "在文档中提到了你",
"review_requested": "请求审查",
"task_completed": "运行完成",
"task_failed": "运行失败",
diff --git a/apps/mobile/locales/zh-Hant/inbox.json b/apps/mobile/locales/zh-Hant/inbox.json
index 76663b1883..eac88dffc2 100644
--- a/apps/mobile/locales/zh-Hant/inbox.json
+++ b/apps/mobile/locales/zh-Hant/inbox.json
@@ -55,6 +55,8 @@
"due_date_changed": "截止日期已更改",
"new_comment": "新評論",
"mentioned": "提到了你",
+ "doc_comment": "文件有新評論",
+ "doc_mentioned": "在文件中提到了你",
"review_requested": "請求審查",
"task_completed": "執行完成",
"task_failed": "執行失敗",
diff --git a/e2e/docs.spec.ts b/e2e/docs.spec.ts
index 68502afe7f..5cc0e27397 100644
--- a/e2e/docs.spec.ts
+++ b/e2e/docs.spec.ts
@@ -327,3 +327,67 @@ test("Cmd+K finds a doc by words that only appear in its content", async ({ page
await hit.click();
await expect(page).toHaveURL(new RegExp(`/docs/${doc.id}$`));
});
+
+test("comment on selected text, reply, find it again after reload, resolve and reopen", async ({ page }, info) => {
+ const doc = await api.createDoc(
+ "Release runbook",
+ "# Before release\n\nMigrations must rehearse a day ahead in staging.\n\nConfirm the rollback owner.",
+ );
+ await page.goto(`/${slug}/docs/${doc.id}`);
+ const editor = page.locator('.ProseMirror[contenteditable="true"]').first();
+ await expect(editor).toBeVisible();
+
+ // Select a word, then "Comment" in the selection toolbar.
+ await editor.getByText("Migrations must rehearse", { exact: false }).dblclick({ position: { x: 150, y: 8 } });
+ const selected = await page.evaluate(() => window.getSelection()?.toString().trim());
+ expect(selected).toBeTruthy();
+ await page.getByRole("button", { name: "Comment", exact: true }).click();
+ const panel = page.getByRole("complementary", { name: "Comments" });
+ await expect(panel).toBeVisible();
+ // The new discussion's composer takes focus once it has mounted.
+ await expect(panel.locator('.ProseMirror[contenteditable="true"]').first()).toBeFocused();
+ await page.keyboard.type("Can index-only migrations rehearse the same day?");
+ await panel.getByRole("button", { name: "Comment", exact: true }).click();
+
+ const thread = panel.getByRole("group", { name: selected! });
+ await expect(thread).toContainText("Can index-only migrations rehearse the same day?");
+ await expect(page.getByRole("button", { name: /^Comments\s*1$/ })).toBeVisible();
+ await expect.poll(() => page.evaluate(() => CSS.highlights.has("doc-comment") || CSS.highlights.has("doc-comment-active"))).toBe(true);
+
+ await thread.click();
+ await panel.getByRole("button", { name: "Reply", exact: true }).waitFor();
+ const replyBox = thread.locator('.ProseMirror[contenteditable="true"]');
+ await replyBox.click();
+ await expect(replyBox).toBeFocused();
+ await page.keyboard.type("Yes, with CONCURRENTLY.");
+ await panel.getByRole("button", { name: "Reply", exact: true }).click();
+ // Sent: the composer clears and the reply renders as a message.
+ await expect(replyBox).toHaveText("");
+ await expect(thread.getByText("Yes, with CONCURRENTLY.", { exact: true })).toBeVisible();
+ await page.screenshot({ path: info.outputPath("doc-comments.png"), animations: "disabled", style: "nextjs-portal { display: none; }" });
+
+ // After a reload the highlight is found again by text; clicking it opens the discussion.
+ await page.reload();
+ await expect(page.getByRole("button", { name: /^Comments\s*1$/ })).toBeVisible();
+ await expect.poll(() => page.evaluate(() => CSS.highlights.get("doc-comment")?.size ?? 0)).toBe(1);
+ await editor.getByText("Migrations must rehearse", { exact: false }).click({ position: { x: 150, y: 8 } });
+ await expect(panel.getByRole("group", { name: selected! }).getByText("Yes, with CONCURRENTLY.", { exact: true })).toBeVisible();
+
+ // Clicking into the open discussion's reply box leaves the doc where it is.
+ await panel.getByRole("group", { name: selected! }).locator('.ProseMirror[contenteditable="true"]').click();
+ await expect(panel.getByRole("group", { name: selected! }).locator('.ProseMirror[contenteditable="true"]')).toBeFocused();
+
+ // Resolving keeps the open list in view and clears the highlight.
+ await panel.getByRole("button", { name: "Resolve", exact: true }).click();
+ await expect(panel.getByRole("tab", { name: "Open 0" })).toHaveAttribute("aria-selected", "true");
+ await expect(panel.getByRole("tab", { name: "Resolved 1" })).toBeVisible();
+ await expect
+ .poll(() => page.evaluate(() => (CSS.highlights.get("doc-comment")?.size ?? 0) + (CSS.highlights.get("doc-comment-active")?.size ?? 0)))
+ .toBe(0);
+
+ // Reopening brings it back to the open list.
+ await panel.getByRole("tab", { name: "Resolved 1" }).click();
+ await panel.getByRole("button", { name: "Reopen", exact: true }).click();
+ await expect(panel.getByRole("tab", { name: "Open 1" })).toHaveAttribute("aria-selected", "true");
+ await expect(panel.getByRole("group", { name: selected! })).toBeVisible();
+});
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 1184ada364..455aa49687 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -8,12 +8,16 @@ import {
DocVersionSchema,
DocVersionListSchema,
DocSearchResponseSchema,
+ DocCommentSchema,
+ DocCommentListSchema,
} from "../docs/schemas";
import type {
Doc,
DocSummary,
DocFolder,
SearchDocsResponse,
+ DocComment,
+ CreateDocCommentRequest,
DocTree,
DocVersion,
CreateDocRequest,
@@ -1011,6 +1015,38 @@ export class ApiClient {
async deleteDoc(id: string): Promise<void> {
await this.fetch(`/api/docs/${id}`, { method: "DELETE" });
}
+ async listDocComments(docId: string): Promise<DocComment[]> {
+ return parseWithFallback(
+ await this.fetch<unknown>(`/api/docs/${docId}/comments`),
+ DocCommentListSchema,
+ { comments: [] },
+ { endpoint: "GET /api/docs/{id}/comments" },
+ ).comments;
+ }
+ // Writes reject a malformed body instead of inventing a comment.
+ async createDocComment(docId: string, data: CreateDocCommentRequest): Promise<DocComment> {
+ const raw = await this.fetch<unknown>(`/api/docs/${docId}/comments`, {
+ method: "POST",
+ body: JSON.stringify({
+ content: data.content,
+ ...(data.parentId ? { parent_id: data.parentId } : {}),
+ ...(data.anchorQuote !== undefined
+ ? { anchor_quote: data.anchorQuote, anchor_prefix: data.anchorPrefix ?? "", anchor_suffix: data.anchorSuffix ?? "" }
+ : {}),
+ }),
+ });
+ return DocCommentSchema.parse(raw);
+ }
+ async setDocCommentResolved(docId: string, commentId: string, resolved: boolean): Promise<DocComment> {
+ const raw = await this.fetch<unknown>(
+ `/api/docs/${docId}/comments/${commentId}/${resolved ? "resolve" : "reopen"}`,
+ { method: "POST" },
+ );
+ return DocCommentSchema.parse(raw);
+ }
+ async deleteDocComment(docId: string, commentId: string): Promise<void> {
+ await this.fetch(`/api/docs/${docId}/comments/${commentId}`, { method: "DELETE" });
+ }
async listDocVersions(id: string): Promise<DocVersion[]> {
return parseWithFallback(
await this.fetch<unknown>(`/api/docs/${id}/versions`),
diff --git a/packages/core/docs/mutations.ts b/packages/core/docs/mutations.ts
index 49dca2af12..3b7e6f44c8 100644
--- a/packages/core/docs/mutations.ts
+++ b/packages/core/docs/mutations.ts
@@ -2,6 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { api } from "../api";
import { useWorkspaceId } from "../hooks";
import type {
+ CreateDocCommentRequest,
CreateDocFolderRequest,
CreateDocRequest,
Doc,
@@ -130,3 +131,35 @@ export function useDeleteDocFolder() {
},
});
}
+
+/** Comment writes refetch the doc's discussions; the server is the source of truth. */
+function useDocCommentsInvalidate() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return (docId: string) => qc.invalidateQueries({ queryKey: docKeys.comments(wsId, docId) });
+}
+
+export function useCreateDocComment(docId: string) {
+ const invalidate = useDocCommentsInvalidate();
+ return useMutation({
+ mutationFn: (data: CreateDocCommentRequest) => api.createDocComment(docId, data),
+ onSettled: () => invalidate(docId),
+ });
+}
+
+export function useSetDocCommentResolved(docId: string) {
+ const invalidate = useDocCommentsInvalidate();
+ return useMutation({
+ mutationFn: ({ commentId, resolved }: { commentId: string; resolved: boolean }) =>
+ api.setDocCommentResolved(docId, commentId, resolved),
+ onSettled: () => invalidate(docId),
+ });
+}
+
+export function useDeleteDocComment(docId: string) {
+ const invalidate = useDocCommentsInvalidate();
+ return useMutation({
+ mutationFn: (commentId: string) => api.deleteDocComment(docId, commentId),
+ onSettled: () => invalidate(docId),
+ });
+}
diff --git a/packages/core/docs/queries.ts b/packages/core/docs/queries.ts
index 8aab28e653..699561a580 100644
--- a/packages/core/docs/queries.ts
+++ b/packages/core/docs/queries.ts
@@ -10,8 +10,17 @@ export const docKeys = {
[...docKeys.all(wsId), "versions", id] as const,
version: (wsId: string, id: string, number: number) =>
[...docKeys.all(wsId), "version", id, number] as const,
+ comments: (wsId: string, id: string) =>
+ [...docKeys.all(wsId), "comments", id] as const,
};
+export function docCommentsOptions(wsId: string, docId: string) {
+ return queryOptions({
+ queryKey: docKeys.comments(wsId, docId),
+ queryFn: () => api.listDocComments(docId),
+ });
+}
+
export function docTreeOptions(wsId: string) {
return queryOptions({
queryKey: docKeys.tree(wsId),
diff --git a/packages/core/docs/schemas.ts b/packages/core/docs/schemas.ts
index 66e2a4f280..46d3b55de9 100644
--- a/packages/core/docs/schemas.ts
+++ b/packages/core/docs/schemas.ts
@@ -81,6 +81,48 @@ export const DocSearchResponseSchema = z.object({
}),
),
});
+export const DocCommentSchema = z
+ .object({
+ id: z.string().min(1),
+ doc_id: z.string(),
+ parent_id: z.string().nullable().default(null),
+ author_type: actor,
+ author_id: z.string(),
+ content: z.string(),
+ anchor_quote: z.string().default(""),
+ anchor_prefix: z.string().default(""),
+ anchor_suffix: z.string().default(""),
+ resolved_at: z.string().nullable().default(null),
+ resolved_by_type: actor.nullable().default(null),
+ resolved_by_id: z.string().nullable().default(null),
+ created_at: z.string(),
+ updated_at: z.string(),
+ })
+ .transform((c) => ({
+ id: c.id,
+ docId: c.doc_id,
+ parentId: c.parent_id,
+ authorType: c.author_type,
+ authorId: c.author_id,
+ content: c.content,
+ anchorQuote: c.anchor_quote,
+ anchorPrefix: c.anchor_prefix,
+ anchorSuffix: c.anchor_suffix,
+ resolvedAt: c.resolved_at,
+ resolvedByType: c.resolved_by_type,
+ resolvedById: c.resolved_by_id,
+ createdAt: c.created_at,
+ updatedAt: c.updated_at,
+ }));
+// One unreadable comment is dropped instead of emptying the discussion list.
+export const DocCommentListSchema = z.object({
+ comments: z.array(z.unknown()).transform((rows) =>
+ rows.flatMap((row) => {
+ const comment = DocCommentSchema.safeParse(row);
+ return comment.success ? [comment.data] : [];
+ }),
+ ),
+});
export const DocVersionSchema = z
.object({
doc_id: z.string(),
diff --git a/packages/core/inbox/filters.ts b/packages/core/inbox/filters.ts
index 1d6f3ec169..dd1018aaea 100644
--- a/packages/core/inbox/filters.ts
+++ b/packages/core/inbox/filters.ts
@@ -35,7 +35,9 @@ export const INBOX_TYPE_GROUPS: readonly InboxTypeGroup[] = [
const TYPE_GROUP: Partial<Record<InboxItemType, InboxTypeGroup>> = {
mentioned: "mention",
+ doc_mentioned: "mention",
new_comment: "comment",
+ doc_comment: "comment",
reaction_added: "comment",
issue_assigned: "assign",
unassigned: "assign",
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 3da5e0f947..635c4eb45c 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -1430,6 +1430,12 @@ export function useRealtimeSync(
const wsId = getCurrentWsId();
if (wsId) void qc.invalidateQueries({ queryKey: docKeys.all(wsId) });
}));
+ // A discussion changed on one doc: refetch that doc's comments only.
+ docUnsubs.push(ws.on("doc_comment:changed", (p) => {
+ const wsId = getCurrentWsId();
+ const docId = (p as { doc_id?: string } | undefined)?.doc_id;
+ if (wsId && docId) void qc.invalidateQueries({ queryKey: docKeys.comments(wsId, docId) });
+ }));
const unsubCommentCreated = ws.on("comment:created", (p) => {
const { comment, issue_revision: issueRevision } = p as CommentCreatedPayload;
if (!comment?.issue_id) return;
diff --git a/packages/core/types/doc.ts b/packages/core/types/doc.ts
index 43bef6e796..dabd84d2fa 100644
--- a/packages/core/types/doc.ts
+++ b/packages/core/types/doc.ts
@@ -13,6 +13,34 @@ export interface DocSummary {
createdAt: string;
updatedAt: string;
}
+/**
+ * A comment in a discussion on a doc's text. The discussion's first comment
+ * (parentId null) carries the anchor: the quoted text and up to 64 characters
+ * of context on each side, re-located by text in the rendered doc.
+ */
+export interface DocComment {
+ id: string;
+ docId: string;
+ parentId: string | null;
+ authorType: DocAuthorType;
+ authorId: string;
+ content: string;
+ anchorQuote: string;
+ anchorPrefix: string;
+ anchorSuffix: string;
+ resolvedAt: string | null;
+ resolvedByType: DocAuthorType | null;
+ resolvedById: string | null;
+ createdAt: string;
+ updatedAt: string;
+}
+export interface CreateDocCommentRequest {
+ content: string;
+ parentId?: string;
+ anchorQuote?: string;
+ anchorPrefix?: string;
+ anchorSuffix?: string;
+}
/** A doc search hit: where the query matched, with an excerpt for content hits. */
export interface SearchDocResult extends DocSummary {
matchSource: "title" | "content";
diff --git a/packages/core/types/events.ts b/packages/core/types/events.ts
index 0e0dd2460f..9bf818ebf2 100644
--- a/packages/core/types/events.ts
+++ b/packages/core/types/events.ts
@@ -16,6 +16,7 @@ export type WSEventType =
| "doc_folder:created"
| "doc_folder:updated"
| "doc_folder:deleted"
+ | "doc_comment:changed"
| "issue:created"
| "issue:updated"
| "issue_attachments:changed"
diff --git a/packages/core/types/inbox.ts b/packages/core/types/inbox.ts
index 998215b022..a5e01e0817 100644
--- a/packages/core/types/inbox.ts
+++ b/packages/core/types/inbox.ts
@@ -15,6 +15,10 @@ export type InboxItemType =
| "due_date_changed"
| "new_comment"
| "mentioned"
+ // A new comment in a doc discussion the recipient wrote in, or one that
+ // mentions them. Details carry doc_id, thread_id and the quoted text.
+ | "doc_comment"
+ | "doc_mentioned"
| "task_failed"
| "reaction_added"
// No longer written, but older servers wrote them and those rows remain;
diff --git a/packages/ui/styles/base.css b/packages/ui/styles/base.css
index 5f8a094bed..5754df79b9 100644
--- a/packages/ui/styles/base.css
+++ b/packages/ui/styles/base.css
@@ -524,3 +524,11 @@ html[data-sidebar-resizing="true"] {
background-color: var(--find-match-active);
color: var(--find-match-foreground);
}
+/* Doc discussions (packages/views/docs): the quoted text of each open
+ discussion, and a stronger tint for the one being read. */
+::highlight(doc-comment) {
+ background-color: color-mix(in oklch, var(--warning) 22%, transparent);
+}
+::highlight(doc-comment-active) {
+ background-color: color-mix(in oklch, var(--warning) 42%, transparent);
+}
diff --git a/packages/views/docs/components/doc-comment-anchors.test.ts b/packages/views/docs/components/doc-comment-anchors.test.ts
new file mode 100644
index 0000000000..cb18929119
--- /dev/null
+++ b/packages/views/docs/components/doc-comment-anchors.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from "vitest";
+import type { DocComment } from "@multica/core/types";
+import { captureDocAnchor, docAnchorRange, locateDocAnchor } from "./doc-comment-anchors";
+import { groupDocThreads } from "./doc-comments-panel";
+
+function editorWith(html: string) {
+ const root = document.createElement("div");
+ root.className = "ProseMirror";
+ root.setAttribute("contenteditable", "true");
+ root.innerHTML = html;
+ document.body.append(root);
+ return root;
+}
+
+describe("locateDocAnchor", () => {
+ const anchor = { quote: "rehearse", prefix: "Migrations must ", suffix: " a day ahead" };
+
+ it("finds the quote again after the text around it moved", () => {
+ const text = "Intro added later.\nMigrations must rehearse a day ahead.";
+ expect(locateDocAnchor(text, anchor)).toBe(text.indexOf("rehearse"));
+ });
+
+ it("picks the occurrence whose context matches when the quote repeats", () => {
+ const text = "Teams rehearse often.\nMigrations must rehearse a day ahead.";
+ expect(locateDocAnchor(text, anchor)).toBe(text.lastIndexOf("rehearse"));
+ });
+
+ it("reports a quote that was edited away", () => {
+ expect(locateDocAnchor("Migrations need a dry run first.", anchor)).toBeNull();
+ });
+});
+
+describe("captureDocAnchor and docAnchorRange", () => {
+ it("round-trips a selection across blocks into a range over the same text", () => {
+ const root = editorWith("<p>Before release</p><ul><li>Migrations must rehearse a day ahead</li></ul>");
+ const text = root.querySelector("li")!.firstChild!;
+ const range = document.createRange();
+ range.setStart(text, "Migrations must ".length);
+ range.setEnd(text, "Migrations must rehearse".length);
+ const selection = window.getSelection()!;
+ selection.removeAllRanges();
+ selection.addRange(range);
+
+ const anchor = captureDocAnchor(root, selection);
+ expect(anchor).toEqual({ quote: "rehearse", prefix: "Before release\nMigrations must ", suffix: " a day ahead\n" });
+ expect(docAnchorRange(root, anchor!)?.toString()).toBe("rehearse");
+ root.remove();
+ });
+});
+
+describe("groupDocThreads", () => {
+ const comment = (id: string, parentId: string | null): DocComment => ({
+ id, docId: "d", parentId, authorType: "member", authorId: "u", content: id,
+ anchorQuote: parentId ? "" : "quote", anchorPrefix: "", anchorSuffix: "",
+ resolvedAt: null, resolvedByType: null, resolvedById: null,
+ createdAt: "2026-11-19T00:00:00Z", updatedAt: "2026-11-19T00:00:00Z",
+ });
+
+ it("keeps discussions in order with their replies, dropping orphan replies", () => {
+ const threads = groupDocThreads([comment("a", null), comment("b", null), comment("a1", "a"), comment("x1", "gone")]);
+ expect(threads.map((t) => [t.root.id, t.replies.map((r) => r.id)])).toEqual([["a", ["a1"]], ["b", []]]);
+ });
+});
diff --git a/packages/views/docs/components/doc-comment-anchors.ts b/packages/views/docs/components/doc-comment-anchors.ts
new file mode 100644
index 0000000000..31efc2aebc
--- /dev/null
+++ b/packages/views/docs/components/doc-comment-anchors.ts
@@ -0,0 +1,89 @@
+import { indexCommentText } from "../../issues/components/comment-annotation-selection";
+
+/**
+ * Where a discussion sits in a doc: the quoted text and some context on each
+ * side, in the rendered text of the editor (block boundaries as newlines).
+ * The anchor lives beside the Markdown, never in it, so agents read a clean
+ * doc; after every save it is found again by text.
+ */
+export interface DocAnchor {
+ quote: string;
+ prefix: string;
+ suffix: string;
+}
+
+const CONTEXT = 64;
+
+/** The anchor for the current selection inside `root`, or null. */
+export function captureDocAnchor(root: HTMLElement, selection: Selection | null): DocAnchor | null {
+ if (!selection || selection.isCollapsed || selection.rangeCount !== 1) return null;
+ const range = selection.getRangeAt(0);
+ if (!root.contains(range.startContainer) || !root.contains(range.endContainer)) return null;
+ const { text, nodes } = indexCommentText(root, true);
+ 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);
+ const quote = text.slice(start, end);
+ if (!quote.trim()) return null;
+ return {
+ quote,
+ prefix: text.slice(Math.max(0, start - CONTEXT), start),
+ suffix: text.slice(end, end + CONTEXT),
+ };
+}
+
+/**
+ * Where `anchor` is in `text`, or null when its quote is gone. An occurrence
+ * whose context still matches wins; otherwise the only occurrence; otherwise
+ * the occurrence whose surrounding text agrees most with the saved context.
+ */
+export function locateDocAnchor(text: string, anchor: DocAnchor): number | null {
+ if (!anchor.quote) return null;
+ const starts: number[] = [];
+ for (let at = text.indexOf(anchor.quote); at !== -1; at = text.indexOf(anchor.quote, at + 1)) {
+ starts.push(at);
+ }
+ if (starts.length <= 1) return starts[0] ?? null;
+ let best = starts[0]!;
+ let bestScore = -1;
+ for (const start of starts) {
+ const before = text.slice(Math.max(0, start - anchor.prefix.length), start);
+ const after = text.slice(start + anchor.quote.length, start + anchor.quote.length + anchor.suffix.length);
+ const score = sharedSuffix(before, anchor.prefix) + sharedPrefix(after, anchor.suffix);
+ if (score > bestScore) {
+ best = start;
+ bestScore = score;
+ }
+ }
+ return best;
+}
+
+function sharedSuffix(a: string, b: string): number {
+ let n = 0;
+ while (n < a.length && n < b.length && a[a.length - 1 - n] === b[b.length - 1 - n]) n++;
+ return n;
+}
+
+function sharedPrefix(a: string, b: string): number {
+ let n = 0;
+ while (n < a.length && n < b.length && a[n] === b[n]) n++;
+ return n;
+}
+
+/** A DOM range over `anchor` in `root`, or null when the quote is gone. */
+export function docAnchorRange(root: HTMLElement, anchor: DocAnchor): Range | null {
+ const { text, nodes } = indexCommentText(root, true);
+ const start = locateDocAnchor(text, anchor);
+ if (start === null) return null;
+ const end = start + anchor.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;
+}
diff --git a/packages/views/docs/components/doc-comments-panel.tsx b/packages/views/docs/components/doc-comments-panel.tsx
new file mode 100644
index 0000000000..fd1b47afe1
--- /dev/null
+++ b/packages/views/docs/components/doc-comments-panel.tsx
@@ -0,0 +1,382 @@
+"use client";
+import { useEffect, useRef, useState } from "react";
+import { toast } from "sonner";
+import { AlertTriangle, Check, MessageSquare, RotateCcw, Trash2, X } from "@multica/ui/icons";
+import { Button } from "@multica/ui/components/ui/button";
+import { cn } from "@multica/ui/lib/utils";
+import { useAuthStore } from "@multica/core/auth";
+import {
+ useCreateDocComment,
+ useDeleteDocComment,
+ useSetDocCommentResolved,
+} from "@multica/core/docs";
+import type { DocComment } from "@multica/core/types";
+import { useActorName } from "@multica/core/workspace/hooks";
+import { ContentEditor, ReadonlyContent, type ContentEditorRef } from "../../editor";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { useT, useTimeAgo } from "../../i18n";
+import type { DocAnchor } from "./doc-comment-anchors";
+
+export interface DocThread {
+ root: DocComment;
+ replies: DocComment[];
+}
+
+/** Discussions in creation order, each with its replies in order. */
+export function groupDocThreads(comments: readonly DocComment[]): DocThread[] {
+ const threads = new Map<string, DocThread>();
+ for (const c of comments) if (!c.parentId) threads.set(c.id, { root: c, replies: [] });
+ for (const c of comments) if (c.parentId) threads.get(c.parentId)?.replies.push(c);
+ return [...threads.values()];
+}
+
+function Composer({
+ placeholder,
+ submitLabel,
+ autoFocus,
+ onSubmit,
+ onCancel,
+}: {
+ placeholder: string;
+ submitLabel: string;
+ autoFocus?: boolean;
+ onSubmit: (content: string) => Promise<unknown>;
+ onCancel?: () => void;
+}) {
+ const { t } = useT("docs");
+ const ref = useRef<ContentEditorRef>(null);
+ const [empty, setEmpty] = useState(true);
+ const [pending, setPending] = useState(false);
+ useEffect(() => {
+ if (autoFocus) ref.current?.focus();
+ }, [autoFocus]);
+ const submit = () => {
+ const content = ref.current?.getMarkdown().trim() ?? "";
+ if (!content || pending) return;
+ setPending(true);
+ onSubmit(content).then(
+ () => {
+ ref.current?.clearContent();
+ setEmpty(true);
+ setPending(false);
+ },
+ () => {
+ toast.error(t(($) => $.comments.errors.save));
+ setPending(false);
+ },
+ );
+ };
+ return (
+ <div className="mt-2 rounded-md border bg-background px-2 py-1.5">
+ <ContentEditor
+ ref={ref}
+ defaultValue=""
+ placeholder={placeholder}
+ mentionHideGuests
+ onUpdate={(md) => setEmpty(!md.trim())}
+ onSubmit={submit}
+ debounceMs={0}
+ className="min-h-6 text-body"
+ />
+ <div className="mt-1 flex justify-end gap-1.5">
+ {onCancel && (
+ <Button size="xs" variant="ghost" onClick={onCancel}>
+ {t(($) => $.comments.cancel)}
+ </Button>
+ )}
+ <Button size="xs" disabled={empty || pending} onClick={submit}>
+ {submitLabel}
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+function Message({ comment, onDelete }: { comment: DocComment; onDelete?: () => void }) {
+ const { t } = useT("docs");
+ const timeAgo = useTimeAgo();
+ const { getActorName } = useActorName();
+ return (
+ <div className="group/message mt-2 flex gap-2 first:mt-0">
+ <ActorAvatar actorType={comment.authorType} actorId={comment.authorId} size="sm" />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-1.5 text-caption">
+ <span className="font-medium text-foreground">
+ {getActorName(comment.authorType, comment.authorId)}
+ </span>
+ <span className="text-muted-foreground">{timeAgo(comment.createdAt)}</span>
+ {onDelete && (
+ <button
+ type="button"
+ aria-label={t(($) => $.comments.delete)}
+ title={t(($) => $.comments.delete)}
+ className="ml-auto rounded-sm p-0.5 text-muted-foreground opacity-0 hover:text-destructive focus-visible:opacity-100 group-hover/message:opacity-100"
+ onClick={(e) => {
+ e.stopPropagation();
+ onDelete();
+ }}
+ >
+ <Trash2 className="size-3.5" />
+ </button>
+ )}
+ </div>
+ <div className="text-body">
+ <ReadonlyContent content={comment.content} />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function Quote({ text, missing }: { text: string; missing?: boolean }) {
+ const { t } = useT("docs");
+ return (
+ <>
+ {missing && (
+ <div className="mb-1 flex items-center gap-1.5 text-caption text-muted-foreground">
+ <AlertTriangle className="size-3.5 text-warning" />
+ {t(($) => $.comments.quote_missing)}
+ </div>
+ )}
+ <p
+ className={cn(
+ "mb-2 line-clamp-2 border-l-2 pl-2 text-caption text-muted-foreground",
+ missing ? "border-border line-through" : "border-warning",
+ )}
+ >
+ {text}
+ </p>
+ </>
+ );
+}
+
+function ThreadCard({
+ docId,
+ thread,
+ active,
+ missing,
+ onActivate,
+ onResolvedChange,
+}: {
+ docId: string;
+ thread: DocThread;
+ active: boolean;
+ missing: boolean;
+ onActivate: () => void;
+ onResolvedChange: (resolved: boolean) => void;
+}) {
+ const { t } = useT("docs");
+ const { getActorName } = useActorName();
+ const userId = useAuthStore((s) => s.user?.id);
+ const reply = useCreateDocComment(docId);
+ const resolve = useSetDocCommentResolved(docId);
+ const remove = useDeleteDocComment(docId);
+ const ref = useRef<HTMLDivElement>(null);
+ const resolved = !!thread.root.resolvedAt;
+ useEffect(() => {
+ if (active) ref.current?.scrollIntoView({ block: "nearest", behavior: "smooth" });
+ }, [active]);
+ const own = (c: DocComment) => c.authorType === "member" && c.authorId === userId;
+ const del = (c: DocComment) =>
+ remove.mutateAsync(c.id).catch(() => toast.error(t(($) => $.comments.errors.delete)));
+ // The card moves to the other tab once this settles, so the follow-up hangs
+ // off the request rather than this component.
+ const setResolved = (value: boolean) =>
+ resolve.mutateAsync({ commentId: thread.root.id, resolved: value }).then(
+ () => onResolvedChange(value),
+ () => toast.error(t(($) => $.comments.errors.resolve)),
+ );
+ return (
+ <div
+ ref={ref}
+ role="group"
+ aria-label={thread.root.anchorQuote}
+ data-thread-id={thread.root.id}
+ // Clicks inside the open discussion (its reply box, its buttons) must not
+ // scroll the doc back to the quote.
+ onClick={() => {
+ if (!active) onActivate();
+ }}
+ className={cn(
+ "rounded-lg border bg-card px-3 py-2.5 transition-colors",
+ active ? "border-warning shadow-sm" : "hover:border-input",
+ )}
+ >
+ <Quote text={thread.root.anchorQuote} missing={missing} />
+ {[thread.root, ...thread.replies].map((c) => (
+ <Message key={c.id} comment={c} onDelete={own(c) ? () => void del(c) : undefined} />
+ ))}
+ {resolved ? (
+ <div className="mt-2 flex items-center gap-2 border-t pt-2 text-caption text-muted-foreground">
+ {t(($) => $.comments.resolved_by, {
+ name: getActorName(thread.root.resolvedByType ?? "member", thread.root.resolvedById ?? ""),
+ })}
+ <Button
+ size="xs"
+ variant="outline"
+ className="ml-auto"
+ disabled={resolve.isPending}
+ onClick={(e) => {
+ e.stopPropagation();
+ void setResolved(false);
+ }}
+ >
+ <RotateCcw />
+ {t(($) => $.comments.reopen)}
+ </Button>
+ </div>
+ ) : (
+ active && (
+ <>
+ <Composer
+ placeholder={t(($) => $.comments.reply_placeholder)}
+ submitLabel={t(($) => $.comments.reply)}
+ onSubmit={(content) => reply.mutateAsync({ content, parentId: thread.root.id })}
+ />
+ <div className="mt-2 flex justify-end">
+ <Button
+ size="xs"
+ variant="outline"
+ disabled={resolve.isPending}
+ onClick={(e) => {
+ e.stopPropagation();
+ void setResolved(true);
+ }}
+ >
+ <Check />
+ {t(($) => $.comments.resolve)}
+ </Button>
+ </div>
+ </>
+ )
+ )}
+ {!resolved && !active && thread.replies.length > 0 && (
+ <div className="mt-2 text-caption text-muted-foreground">
+ {t(($) => $.comments.replies, { count: thread.replies.length })}
+ </div>
+ )}
+ </div>
+ );
+}
+
+/**
+ * The doc's discussions, beside the text. Open and resolved discussions sit
+ * on separate tabs; a discussion being started from a selection appears on
+ * top until it is sent or cancelled.
+ */
+export function DocCommentsPanel({
+ docId,
+ threads,
+ missing,
+ activeId,
+ draft,
+ onActivate,
+ onDeactivate,
+ onDraftDone,
+ onClose,
+}: {
+ docId: string;
+ threads: DocThread[];
+ missing: ReadonlySet<string>;
+ activeId: string | null;
+ draft: DocAnchor | null;
+ onActivate: (id: string) => void;
+ onDeactivate: () => void;
+ onDraftDone: (createdId: string | null) => void;
+ onClose: () => void;
+}) {
+ const { t } = useT("docs");
+ const create = useCreateDocComment(docId);
+ const [tab, setTab] = useState<"open" | "resolved">("open");
+ const open = threads.filter((th) => !th.root.resolvedAt);
+ const resolved = threads.filter((th) => th.root.resolvedAt);
+ const activeResolved = !!activeId && resolved.some((th) => th.root.id === activeId);
+ useEffect(() => {
+ if (activeResolved) setTab("resolved");
+ }, [activeResolved]);
+ useEffect(() => {
+ if (draft) setTab("open");
+ }, [draft]);
+ const shown = tab === "open" ? open : resolved;
+ return (
+ <aside
+ aria-label={t(($) => $.comments.title)}
+ className="flex w-[360px] shrink-0 flex-col border-l bg-background"
+ >
+ <div className="flex h-11 shrink-0 items-center gap-1.5 border-b px-3">
+ <MessageSquare className="size-4 text-muted-foreground" />
+ <span className="text-body font-medium">{t(($) => $.comments.title)}</span>
+ <div role="tablist" className="ml-auto flex gap-0.5 text-caption">
+ {(["open", "resolved"] as const).map((key) => (
+ <button
+ key={key}
+ type="button"
+ role="tab"
+ aria-selected={tab === key}
+ onClick={() => setTab(key)}
+ className={cn(
+ "rounded-md px-2 py-1",
+ tab === key ? "bg-surface-selected text-foreground" : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ {key === "open"
+ ? t(($) => $.comments.open, { count: open.length })
+ : t(($) => $.comments.resolved, { count: resolved.length })}
+ </button>
+ ))}
+ </div>
+ <Button size="icon-xs" variant="ghost" aria-label={t(($) => $.comments.close)} onClick={onClose}>
+ <X className="size-3.5" />
+ </Button>
+ </div>
+ <div className="min-h-0 flex-1 space-y-2.5 overflow-y-auto p-3">
+ {draft && tab === "open" && (
+ <div className="rounded-lg border border-warning bg-card px-3 py-2.5 shadow-sm">
+ <Quote text={draft.quote} />
+ <Composer
+ autoFocus
+ placeholder={t(($) => $.comments.new_placeholder)}
+ submitLabel={t(($) => $.comments.submit)}
+ onCancel={() => onDraftDone(null)}
+ onSubmit={(content) =>
+ create
+ .mutateAsync({
+ content,
+ anchorQuote: draft.quote,
+ anchorPrefix: draft.prefix,
+ anchorSuffix: draft.suffix,
+ })
+ .then((c) => onDraftDone(c.id))
+ }
+ />
+ </div>
+ )}
+ {shown.map((thread) => (
+ <ThreadCard
+ key={thread.root.id}
+ docId={docId}
+ thread={thread}
+ active={thread.root.id === activeId}
+ missing={missing.has(thread.root.id)}
+ onActivate={() => onActivate(thread.root.id)}
+ onResolvedChange={(resolved) => {
+ // Resolving keeps you on the open list for the next discussion;
+ // reopening brings the discussion back to it.
+ if (!resolved) {
+ setTab("open");
+ onActivate(thread.root.id);
+ } else if (thread.root.id === activeId) {
+ onDeactivate();
+ }
+ }}
+ />
+ ))}
+ {!draft && shown.length === 0 && (
+ <p className="px-1 py-6 text-center text-caption text-muted-foreground">
+ {tab === "open" ? t(($) => $.comments.empty_open) : t(($) => $.comments.empty_resolved)}
+ </p>
+ )}
+ </div>
+ </aside>
+ );
+}
diff --git a/packages/views/docs/components/doc-not-found.test.tsx b/packages/views/docs/components/doc-not-found.test.tsx
index dd020e2ba9..2d40abceed 100644
--- a/packages/views/docs/components/doc-not-found.test.tsx
+++ b/packages/views/docs/components/doc-not-found.test.tsx
@@ -29,7 +29,7 @@ const { apiMock, ApiError } = vi.hoisted(() => {
ApiError,
apiMock: {
getDoc: vi.fn(), updateDoc: vi.fn(), listDocTree: vi.fn(),
- listDocVersions: vi.fn(), getDocVersion: vi.fn(),
+ listDocVersions: vi.fn(), getDocVersion: vi.fn(), listDocComments: vi.fn(),
listMembers: vi.fn(), listAgents: vi.fn(),
},
};
@@ -55,7 +55,7 @@ vi.mock("@multica/core/workspace/hooks", () => ({
useActorName: () => ({ getActorName: () => "Reviewer" }),
}));
vi.mock("../../navigation", () => ({
- useNavigation: () => ({ pathname: "/review/docs/runbook", push: vi.fn(), getShareableUrl: (path: string) => path }),
+ useNavigation: () => ({ pathname: "/review/docs/runbook", push: vi.fn(), getShareableUrl: (path: string) => path, searchParams: new URLSearchParams() }),
AppLink: ({ children, href, className }: { children: React.ReactNode; href: string; className?: string }) => (
<a href={href} className={className}>{children}</a>
),
@@ -95,6 +95,7 @@ beforeEach(() => {
useDocDraftStore.getState().clearDraft();
qc = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
apiMock.listDocTree.mockResolvedValue({ folders: [], docs: [] });
+ apiMock.listDocComments.mockResolvedValue([]);
apiMock.listMembers.mockResolvedValue([]);
apiMock.listAgents.mockResolvedValue([]);
});
diff --git a/packages/views/docs/components/doc-page.tsx b/packages/views/docs/components/doc-page.tsx
index c88810da91..b445028642 100644
--- a/packages/views/docs/components/doc-page.tsx
+++ b/packages/views/docs/components/doc-page.tsx
@@ -1,9 +1,10 @@
"use client";
-import { useCallback, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import {
History,
Link as LinkIcon,
+ MessageSquare,
MoreHorizontal,
FolderInput,
Trash2,
@@ -25,6 +26,7 @@ import {
import {
docDetailOptions,
docTreeOptions,
+ docCommentsOptions,
folderAncestry,
isDocNotFound,
} from "@multica/core/docs";
@@ -39,6 +41,9 @@ import { AppLink, useNavigation } from "../../navigation";
import { useT, useTimeAgo } from "../../i18n";
import { useDocDraft } from "./use-doc-draft";
import { DocOutline, MIN_OUTLINE_HEADINGS, useDocOutline } from "./doc-outline";
+import { DocCommentsPanel, groupDocThreads } from "./doc-comments-panel";
+import { captureDocAnchor, type DocAnchor } from "./doc-comment-anchors";
+import { useDocCommentHighlights } from "./use-doc-comment-highlights";
import { MoveDialog } from "./move-dialog";
import { DeleteDocDialog } from "./doc-tree";
import { useCanDeleteDoc } from "./use-can-delete-doc";
@@ -86,7 +91,7 @@ function DocEditor({ doc }: { doc: Doc }) {
const canDelete = useCanDeleteDoc()(doc);
const ancestors = folderAncestry(tree?.folders ?? [], doc.folderId);
const author = getActorName(doc.updatedByType, doc.updatedById);
- const { getShareableUrl } = useNavigation();
+ const { getShareableUrl, searchParams } = useNavigation();
const copyLink = () => {
void copyText(getShareableUrl(p.docDetail(doc.id))).then((ok) => {
if (ok) toast.success(t(($) => $.link_copied));
@@ -98,6 +103,63 @@ function DocEditor({ doc }: { doc: Doc }) {
const bodyRef = useRef<HTMLDivElement>(null);
const outline = useDocOutline(bodyRef, scrollRef);
const showOutline = outline.headings.length >= MIN_OUTLINE_HEADINGS;
+
+ // Discussions. A link from the inbox names one with ?thread=.
+ const { data: comments } = useQuery(docCommentsOptions(wsId, doc.id));
+ const threads = useMemo(() => groupDocThreads(comments ?? []), [comments]);
+ const linkedThread = searchParams.get("thread");
+ const [commentsOpen, setCommentsOpen] = useState(!!linkedThread);
+ const [activeThread, setActiveThread] = useState<string | null>(linkedThread);
+ const [newAnchor, setNewAnchor] = useState<DocAnchor | null>(null);
+ useEffect(() => {
+ if (!linkedThread) return;
+ setCommentsOpen(true);
+ setActiveThread(linkedThread);
+ }, [linkedThread]);
+ const openThreads = threads.filter((th) => !th.root.resolvedAt);
+ const anchored = useMemo(
+ () =>
+ threads
+ .filter((th) => !th.root.resolvedAt || th.root.id === activeThread)
+ .map((th) => ({
+ id: th.root.id,
+ quote: th.root.anchorQuote,
+ prefix: th.root.anchorPrefix,
+ suffix: th.root.anchorSuffix,
+ })),
+ [threads, activeThread],
+ );
+ const highlights = useDocCommentHighlights(bodyRef, anchored, activeThread);
+ const activateThread = (id: string) => {
+ setActiveThread(id);
+ setCommentsOpen(true);
+ highlights.reveal(id);
+ };
+ const commentAction = useMemo(
+ () => ({
+ label: t(($) => $.comments.add),
+ onSelect: () => {
+ const root = bodyRef.current?.querySelector<HTMLElement>(".ProseMirror");
+ const anchor = root ? captureDocAnchor(root, window.getSelection()) : null;
+ if (!anchor) return false;
+ setNewAnchor(anchor);
+ setActiveThread(null);
+ setCommentsOpen(true);
+ return true;
+ },
+ }),
+ [t],
+ );
+ // A click inside highlighted text opens its discussion.
+ const onBodyClick = () => {
+ const selection = window.getSelection();
+ if (!selection?.isCollapsed || !selection.anchorNode) return;
+ const id = highlights.threadAt(selection.anchorNode, selection.anchorOffset);
+ if (id) {
+ setActiveThread(id);
+ setCommentsOpen(true);
+ }
+ };
return (
<div className="flex h-full min-h-0 flex-col">
<BreadcrumbHeader
@@ -133,6 +195,19 @@ function DocEditor({ doc }: { doc: Doc }) {
>
<LinkIcon className="size-4" />
</Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ aria-pressed={commentsOpen}
+ className={commentsOpen ? "bg-surface-selected" : undefined}
+ onClick={() => setCommentsOpen((open) => !open)}
+ >
+ <MessageSquare className="size-4" />
+ {t(($) => $.comments.title)}
+ {openThreads.length > 0 && (
+ <span className="text-caption text-muted-foreground">{openThreads.length}</span>
+ )}
+ </Button>
<AppLink
href={p.docHistory(doc.id)}
className="flex items-center gap-1 rounded-md px-2 py-1 text-caption hover:bg-surface-hover"
@@ -184,7 +259,8 @@ function DocEditor({ doc }: { doc: Doc }) {
</Button>
</div>
)}
- <div ref={scrollRef} className="@container min-h-0 flex-1 overflow-auto">
+ <div className="flex min-h-0 flex-1">
+ <div ref={scrollRef} className="@container min-h-0 min-w-0 flex-1 overflow-auto">
<div className="flex min-h-full">
<div className="min-w-0 flex-1">
<div className="mx-auto max-w-4xl px-6 py-8 @3xl:px-16">
@@ -230,8 +306,9 @@ function DocEditor({ doc }: { doc: Doc }) {
</TooltipContent>
</Tooltip>
</div>
- <div ref={bodyRef}>
+ <div ref={bodyRef} onClick={onBodyClick}>
<ContentEditor
+ selectionAction={commentAction}
value={draft.content}
onUpdate={(content) => change({ content })}
debounceMs={0}
@@ -246,7 +323,8 @@ function DocEditor({ doc }: { doc: Doc }) {
</div>
</div>
</div>
- {showOutline && (
+ {/* The discussions panel takes the right side; the outline yields. */}
+ {showOutline && !commentsOpen && (
<aside className="hidden w-56 shrink-0 py-8 pr-6 @5xl:block">
<DocOutline
headings={outline.headings}
@@ -257,6 +335,26 @@ function DocEditor({ doc }: { doc: Doc }) {
)}
</div>
</div>
+ {commentsOpen && (
+ <DocCommentsPanel
+ docId={doc.id}
+ threads={threads}
+ missing={highlights.missing}
+ activeId={activeThread}
+ draft={newAnchor}
+ onActivate={activateThread}
+ onDeactivate={() => setActiveThread(null)}
+ onDraftDone={(id) => {
+ setNewAnchor(null);
+ if (id) setActiveThread(id);
+ }}
+ onClose={() => {
+ setCommentsOpen(false);
+ setNewAnchor(null);
+ }}
+ />
+ )}
+ </div>
<MoveDialog
target={moving ? { kind: "doc", id: doc.id, title: doc.title } : null}
onOpenChange={setMoving}
diff --git a/packages/views/docs/components/use-doc-comment-highlights.ts b/packages/views/docs/components/use-doc-comment-highlights.ts
new file mode 100644
index 0000000000..88bcabdf13
--- /dev/null
+++ b/packages/views/docs/components/use-doc-comment-highlights.ts
@@ -0,0 +1,96 @@
+"use client";
+import { useEffect, useRef, useState, type RefObject } from "react";
+import { docAnchorRange, type DocAnchor } from "./doc-comment-anchors";
+
+export interface AnchoredThread extends DocAnchor {
+ id: string;
+}
+
+/** Highlight names styled in packages/ui/styles/base.css. */
+const HIGHLIGHT = "doc-comment";
+const ACTIVE_HIGHLIGHT = "doc-comment-active";
+
+function canHighlight() {
+ return typeof Highlight !== "undefined" && typeof CSS !== "undefined" && !!CSS.highlights;
+}
+
+/**
+ * Paints each open discussion's quoted text in the doc and keeps the ranges
+ * current while the doc is edited. Returns which discussions could not be
+ * found (their text was edited away) and a lookup from a DOM point to the
+ * discussion it sits in, for clicking a highlight.
+ */
+export function useDocCommentHighlights(
+ rootRef: RefObject<HTMLElement | null>,
+ threads: AnchoredThread[],
+ activeId: string | null,
+) {
+ const rangesRef = useRef(new Map<string, Range>());
+ const [missing, setMissing] = useState<ReadonlySet<string>>(new Set());
+ const threadsKey = threads.map((t) => `${t.id}:${t.quote}`).join("\n");
+ const threadsRef = useRef(threads);
+ threadsRef.current = threads;
+
+ useEffect(() => {
+ const host = rootRef.current;
+ if (!host) return;
+ let frame = 0;
+ const paint = () => {
+ const root = host.querySelector<HTMLElement>(".ProseMirror");
+ if (!root) return;
+ const ranges = new Map<string, Range>();
+ const gone = new Set<string>();
+ for (const thread of threadsRef.current) {
+ const range = docAnchorRange(root, thread);
+ if (range) ranges.set(thread.id, range);
+ else gone.add(thread.id);
+ }
+ rangesRef.current = ranges;
+ setMissing((prev) =>
+ prev.size === gone.size && [...gone].every((id) => prev.has(id)) ? prev : gone,
+ );
+ if (canHighlight()) {
+ const active = activeId ? ranges.get(activeId) : undefined;
+ CSS.highlights.set(HIGHLIGHT, new Highlight(...[...ranges].filter(([id]) => id !== activeId).map(([, r]) => r)));
+ if (active) CSS.highlights.set(ACTIVE_HIGHLIGHT, new Highlight(active));
+ else CSS.highlights.delete(ACTIVE_HIGHLIGHT);
+ }
+ };
+ const schedule = () => {
+ cancelAnimationFrame(frame);
+ frame = requestAnimationFrame(paint);
+ };
+ schedule();
+ const observer = new MutationObserver(schedule);
+ observer.observe(host, { childList: true, subtree: true, characterData: true });
+ return () => {
+ observer.disconnect();
+ cancelAnimationFrame(frame);
+ if (canHighlight()) {
+ CSS.highlights.delete(HIGHLIGHT);
+ CSS.highlights.delete(ACTIVE_HIGHLIGHT);
+ }
+ };
+ }, [rootRef, threadsKey, activeId]);
+
+ /** The discussion whose quoted text contains this point, if any. */
+ const threadAt = (node: Node, offset: number): string | null => {
+ for (const [id, range] of rangesRef.current) {
+ try {
+ if (range.isPointInRange(node, offset)) return id;
+ } catch {
+ // A point in another document or a detached node is in no range.
+ }
+ }
+ return null;
+ };
+
+ /** Scrolls the discussion's quoted text into view. */
+ const reveal = (id: string) => {
+ const range = rangesRef.current.get(id);
+ const target = range?.startContainer.parentElement;
+ target?.scrollIntoView({ block: "center", behavior: "smooth" });
+ };
+
+ return { missing, threadAt, reveal };
+}
diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsx
index a3878b4cc1..63d0846077 100644
--- a/packages/views/editor/content-editor.tsx
+++ b/packages/views/editor/content-editor.tsx
@@ -201,6 +201,8 @@ interface ContentEditorBaseProps {
/** Chat can surface current/recent issue/project suggestions. Other editors use default mention behavior. */
mentionMode?: "default" | "context";
mentionContextItems?: MentionItem[];
+ /** Leave guests out of the @ list, for places guests cannot open (docs). */
+ mentionHideGuests?: boolean;
/** Enable the `/` command picker. Defaults false. */
enableSlashCommands?: boolean;
/**
@@ -403,6 +405,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
disableMentions = false,
mentionMode = "default",
mentionContextItems,
+ mentionHideGuests = false,
enableSlashCommands = false,
slashCommandMode = "skill",
showBlockHandles = false,
@@ -657,6 +660,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
disableMentions,
mentionMode,
getMentionContextItems: () => mentionContextItemsRef.current,
+ mentionHideGuests,
enableSlashCommands,
slashCommandMode,
quickActionMenu: {
diff --git a/packages/views/editor/extensions/index.ts b/packages/views/editor/extensions/index.ts
index 2c9e15a645..f947f1e10e 100644
--- a/packages/views/editor/extensions/index.ts
+++ b/packages/views/editor/extensions/index.ts
@@ -170,6 +170,7 @@ export interface EditorExtensionsOptions {
/** Override @ behavior for chat context suggestions. */
mentionMode?: "default" | "context";
getMentionContextItems?: () => MentionItem[];
+ mentionHideGuests?: boolean;
/** When true, attach the `/` picker. Default false. */
enableSlashCommands?: boolean;
/**
@@ -280,7 +281,7 @@ export function createEditorExtensions(
...(options.disableMentions
? { suggestion: { allow: () => false } }
: options.queryClient
- ? { suggestion: createMentionSuggestion(options.queryClient, { mode: options.mentionMode, getContextItems: options.getMentionContextItems }) }
+ ? { suggestion: createMentionSuggestion(options.queryClient, { mode: options.mentionMode, getContextItems: options.getMentionContextItems, hideGuests: options.mentionHideGuests }) }
: {}),
}),
// Linear-style bare identifier → issue mention. Attached only when a
diff --git a/packages/views/editor/extensions/mention-suggestion.test.tsx b/packages/views/editor/extensions/mention-suggestion.test.tsx
index 6d414ca9c6..78f6072475 100644
--- a/packages/views/editor/extensions/mention-suggestion.test.tsx
+++ b/packages/views/editor/extensions/mention-suggestion.test.tsx
@@ -486,6 +486,20 @@ describe("createMentionSuggestion", () => {
expect(screen.queryByText("No results")).not.toBeInTheDocument();
});
+ it("leaves guests out of the member list where they cannot follow the mention", () => {
+ const qc = fakeQc({
+ members: [
+ { user_id: "u1", name: "Alice", role: "member" },
+ { user_id: "u2", name: "Alan", role: "guest" },
+ ],
+ });
+ const members = (config: ReturnType<typeof createMentionSuggestion>) =>
+ (config.items!(itemArgs("al")) as MentionItem[]).filter((i) => i.type === "member").map((i) => i.id).sort();
+
+ expect(members(createMentionSuggestion(qc))).toEqual(["u1", "u2"]);
+ expect(members(createMentionSuggestion(qc, { hideGuests: true }))).toEqual(["u1"]);
+ });
+
it("matches cached live projects synchronously and leaves archived ones to the server", () => {
const qc = fakeQc({
projects: [
diff --git a/packages/views/editor/extensions/mention-suggestion.tsx b/packages/views/editor/extensions/mention-suggestion.tsx
index 7430f2f66c..034bc2e36f 100644
--- a/packages/views/editor/extensions/mention-suggestion.tsx
+++ b/packages/views/editor/extensions/mention-suggestion.tsx
@@ -836,6 +836,8 @@ function matchesMentionQuery(item: MentionItem, query: string): boolean {
interface MentionSuggestionOptions {
mode?: "default" | "context";
getContextItems?: () => MentionItem[];
+ /** Leave guests out of the member list, where the mention leads somewhere they cannot open. */
+ hideGuests?: boolean;
}
export function createMentionSuggestion(
@@ -883,6 +885,7 @@ export function createMentionSuggestion(
: [];
const memberItems: MentionItem[] = members
+ .filter((m) => !(options.hideGuests && m.role === "guest"))
.filter((m) => m.name.toLowerCase().includes(q) || matchesPinyin(m.name, q))
.map((m) => ({
id: m.user_id,
diff --git a/packages/views/inbox/components/inbox-detail-label.tsx b/packages/views/inbox/components/inbox-detail-label.tsx
index 4a5c9e6b8f..9e335c8412 100644
--- a/packages/views/inbox/components/inbox-detail-label.tsx
+++ b/packages/views/inbox/components/inbox-detail-label.tsx
@@ -27,6 +27,8 @@ export function useTypeLabels(): Record<InboxItemType, string> {
due_date_changed: t(($) => $.types.due_date_changed),
new_comment: t(($) => $.types.new_comment),
mentioned: t(($) => $.types.mentioned),
+ doc_comment: t(($) => $.types.doc_comment),
+ doc_mentioned: t(($) => $.types.doc_mentioned),
review_requested: t(($) => $.types.review_requested),
task_completed: t(($) => $.types.task_completed),
task_failed: t(($) => $.types.task_failed),
diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsx
index ff3ff76504..1e684da8dc 100644
--- a/packages/views/inbox/components/inbox-page.tsx
+++ b/packages/views/inbox/components/inbox-page.tsx
@@ -1073,6 +1073,25 @@ export function InboxPage() {
</div>
)}
<div className="mt-4 flex gap-2">
+ {(detailItem.type === "doc_comment" || detailItem.type === "doc_mentioned") &&
+ detailItem.details?.doc_id && (
+ <Button
+ size="sm"
+ variant="outline"
+ render={
+ <AppLink
+ href={`${wsPaths.docDetail(detailItem.details.doc_id)}${
+ detailItem.details.thread_id
+ ? `?thread=${encodeURIComponent(detailItem.details.thread_id)}`
+ : ""
+ }`}
+ />
+ }
+ nativeButton={false}
+ >
+ {t(($) => $.detail.open_doc)}
+ </Button>
+ )}
{detailItem.type === "project_owner_joined" && detailItem.details?.project_id && (
<Button
size="sm"
diff --git a/packages/views/locales/en/docs.json b/packages/views/locales/en/docs.json
index 05573dff87..1dbaa796c1 100644
--- a/packages/views/locales/en/docs.json
+++ b/packages/views/locales/en/docs.json
@@ -66,5 +66,31 @@
"unavailable": {
"title": "Docs isn't available here",
"description": "This workspace doesn't have Docs turned on."
+ },
+ "comments": {
+ "title": "Comments",
+ "add": "Comment",
+ "open": "Open {{count}}",
+ "resolved": "Resolved {{count}}",
+ "close": "Close comments",
+ "quote_missing": "The commented text was changed",
+ "reply_placeholder": "Reply, or @ someone…",
+ "new_placeholder": "Add a comment, @ to mention…",
+ "submit": "Comment",
+ "reply": "Reply",
+ "cancel": "Cancel",
+ "resolve": "Resolve",
+ "reopen": "Reopen",
+ "delete": "Delete comment",
+ "resolved_by": "Resolved by {{name}}",
+ "replies_one": "{{count}} reply",
+ "replies_other": "{{count}} replies",
+ "empty_open": "No open comments. Select text and choose Comment to start one.",
+ "empty_resolved": "No resolved comments.",
+ "errors": {
+ "save": "Could not post the comment",
+ "delete": "Could not delete the comment",
+ "resolve": "Could not update the discussion"
+ }
}
}
diff --git a/packages/views/locales/en/inbox.json b/packages/views/locales/en/inbox.json
index c17bfc4122..2071a46a78 100644
--- a/packages/views/locales/en/inbox.json
+++ b/packages/views/locales/en/inbox.json
@@ -75,7 +75,8 @@
"open_project": "Open project",
"autopilot_quota_upgrade": "View upgrade options",
"archive": "Archive",
- "unarchive": "Unarchive"
+ "unarchive": "Unarchive",
+ "open_doc": "Open doc"
},
"types": {
"issue_assigned": "Assigned",
@@ -105,7 +106,9 @@
"app_action_requested": "Needs your confirmation",
"app_action_reminder": "Confirmation expiring soon",
"app_connect_requested": "Connect an app",
- "app_action_result": "App action result"
+ "app_action_result": "App action result",
+ "doc_comment": "New comment on a doc",
+ "doc_mentioned": "Mentioned in a doc"
},
"labels": {
"set_status_to": "Set status to",
diff --git a/packages/views/locales/es/docs.json b/packages/views/locales/es/docs.json
index 5224edd8bd..2b43ef2e41 100644
--- a/packages/views/locales/es/docs.json
+++ b/packages/views/locales/es/docs.json
@@ -66,5 +66,31 @@
"unavailable": {
"title": "Documentos no está disponible",
"description": "Este espacio de trabajo no tiene Documentos activado."
+ },
+ "comments": {
+ "title": "Comentarios",
+ "add": "Comentar",
+ "open": "Abiertos {{count}}",
+ "resolved": "Resueltos {{count}}",
+ "close": "Cerrar comentarios",
+ "quote_missing": "El texto comentado cambió",
+ "reply_placeholder": "Responde o menciona con @…",
+ "new_placeholder": "Escribe un comentario, @ para mencionar…",
+ "submit": "Comentar",
+ "reply": "Responder",
+ "cancel": "Cancelar",
+ "resolve": "Resolver",
+ "reopen": "Reabrir",
+ "delete": "Eliminar comentario",
+ "resolved_by": "Resuelto por {{name}}",
+ "replies_one": "{{count}} respuesta",
+ "replies_other": "{{count}} respuestas",
+ "empty_open": "No hay comentarios abiertos. Selecciona texto y elige Comentar para empezar uno.",
+ "empty_resolved": "No hay comentarios resueltos.",
+ "errors": {
+ "save": "No se pudo publicar el comentario",
+ "delete": "No se pudo eliminar el comentario",
+ "resolve": "No se pudo actualizar la conversación"
+ }
}
}
diff --git a/packages/views/locales/es/inbox.json b/packages/views/locales/es/inbox.json
index 5ae46ae5f7..c0bad1139e 100644
--- a/packages/views/locales/es/inbox.json
+++ b/packages/views/locales/es/inbox.json
@@ -75,7 +75,8 @@
"open_project": "Abrir proyecto",
"autopilot_quota_upgrade": "Ver opciones de mejora del plan",
"archive": "Archivar",
- "unarchive": "Desarchivar"
+ "unarchive": "Desarchivar",
+ "open_doc": "Abrir documento"
},
"types": {
"issue_assigned": "Asignada",
@@ -105,7 +106,9 @@
"app_action_requested": "Necesita tu confirmación",
"app_action_reminder": "La confirmación caduca pronto",
"app_connect_requested": "Conectar una aplicación",
- "app_action_result": "Resultado de la acción de la aplicación"
+ "app_action_result": "Resultado de la acción de la aplicación",
+ "doc_comment": "Nuevo comentario en un documento",
+ "doc_mentioned": "Te mencionaron en un documento"
},
"labels": {
"set_status_to": "Establecer estado en",
diff --git a/packages/views/locales/fr/docs.json b/packages/views/locales/fr/docs.json
index b981f5ac22..682f65ecdb 100644
--- a/packages/views/locales/fr/docs.json
+++ b/packages/views/locales/fr/docs.json
@@ -66,5 +66,31 @@
"unavailable": {
"title": "Documents n'est pas disponible",
"description": "Documents n'est pas activé dans cet espace de travail."
+ },
+ "comments": {
+ "title": "Commentaires",
+ "add": "Commenter",
+ "open": "Ouverts {{count}}",
+ "resolved": "Résolus {{count}}",
+ "close": "Fermer les commentaires",
+ "quote_missing": "Le texte commenté a été modifié",
+ "reply_placeholder": "Répondre, ou mentionner avec @…",
+ "new_placeholder": "Ajouter un commentaire, @ pour mentionner…",
+ "submit": "Commenter",
+ "reply": "Répondre",
+ "cancel": "Annuler",
+ "resolve": "Résoudre",
+ "reopen": "Rouvrir",
+ "delete": "Supprimer le commentaire",
+ "resolved_by": "Résolu par {{name}}",
+ "replies_one": "{{count}} réponse",
+ "replies_other": "{{count}} réponses",
+ "empty_open": "Aucun commentaire ouvert. Sélectionnez du texte et choisissez Commenter pour en lancer un.",
+ "empty_resolved": "Aucun commentaire résolu.",
+ "errors": {
+ "save": "Impossible de publier le commentaire",
+ "delete": "Impossible de supprimer le commentaire",
+ "resolve": "Impossible de mettre à jour la discussion"
+ }
}
}
diff --git a/packages/views/locales/fr/inbox.json b/packages/views/locales/fr/inbox.json
index b31755db7d..35cac43433 100644
--- a/packages/views/locales/fr/inbox.json
+++ b/packages/views/locales/fr/inbox.json
@@ -75,7 +75,8 @@
"open_project": "Ouvrir le projet",
"autopilot_quota_upgrade": "Voir les options de mise à niveau",
"archive": "Archiver",
- "unarchive": "Désarchiver"
+ "unarchive": "Désarchiver",
+ "open_doc": "Ouvrir le document"
},
"types": {
"issue_assigned": "Assigné",
@@ -105,7 +106,9 @@
"app_action_requested": "Confirmation requise",
"app_action_reminder": "Confirmation bientôt expirée",
"app_connect_requested": "Connecter une app",
- "app_action_result": "Résultat d'action d'app"
+ "app_action_result": "Résultat d'action d'app",
+ "doc_comment": "Nouveau commentaire sur un document",
+ "doc_mentioned": "Mentionné dans un document"
},
"labels": {
"set_status_to": "Statut défini sur",
diff --git a/packages/views/locales/ja/docs.json b/packages/views/locales/ja/docs.json
index 2df0037f8e..2f55931ea9 100644
--- a/packages/views/locales/ja/docs.json
+++ b/packages/views/locales/ja/docs.json
@@ -66,5 +66,30 @@
"unavailable": {
"title": "ドキュメントはまだ利用できません",
"description": "このワークスペースではドキュメントが有効になっていません。"
+ },
+ "comments": {
+ "title": "コメント",
+ "add": "コメント",
+ "open": "未解決 {{count}}",
+ "resolved": "解決済み {{count}}",
+ "close": "コメントを閉じる",
+ "quote_missing": "コメントされたテキストが変更されました",
+ "reply_placeholder": "返信、または @ でメンション…",
+ "new_placeholder": "コメントを入力、@ でメンション…",
+ "submit": "コメント",
+ "reply": "返信",
+ "cancel": "キャンセル",
+ "resolve": "解決",
+ "reopen": "再開",
+ "delete": "コメントを削除",
+ "resolved_by": "{{name}} が解決",
+ "replies_other": "{{count}} 件の返信",
+ "empty_open": "未解決のコメントはありません。テキストを選択して「コメント」で始められます。",
+ "empty_resolved": "解決済みのコメントはありません。",
+ "errors": {
+ "save": "コメントを投稿できませんでした",
+ "delete": "コメントを削除できませんでした",
+ "resolve": "スレッドを更新できませんでした"
+ }
}
}
diff --git a/packages/views/locales/ja/inbox.json b/packages/views/locales/ja/inbox.json
index 5a16e9c34c..f43e0eb0ad 100644
--- a/packages/views/locales/ja/inbox.json
+++ b/packages/views/locales/ja/inbox.json
@@ -73,7 +73,8 @@
"open_project": "プロジェクトを開く",
"autopilot_quota_upgrade": "アップグレード方法を見る",
"archive": "アーカイブ",
- "unarchive": "アーカイブ解除"
+ "unarchive": "アーカイブ解除",
+ "open_doc": "ドキュメントを開く"
},
"types": {
"issue_assigned": "割り当て済み",
@@ -103,7 +104,9 @@
"app_action_requested": "確認が必要",
"app_action_reminder": "確認の期限が近い",
"app_connect_requested": "アプリの接続依頼",
- "app_action_result": "アプリ操作の結果"
+ "app_action_result": "アプリ操作の結果",
+ "doc_comment": "ドキュメントへの新しいコメント",
+ "doc_mentioned": "ドキュメントでメンションされました"
},
"labels": {
"set_status_to": "ステータスを変更:",
diff --git a/packages/views/locales/ko/docs.json b/packages/views/locales/ko/docs.json
index 2a7d4b2309..b64108aa58 100644
--- a/packages/views/locales/ko/docs.json
+++ b/packages/views/locales/ko/docs.json
@@ -66,5 +66,30 @@
"unavailable": {
"title": "문서를 아직 사용할 수 없습니다",
"description": "이 워크스페이스에서는 문서가 켜져 있지 않습니다."
+ },
+ "comments": {
+ "title": "댓글",
+ "add": "댓글",
+ "open": "미해결 {{count}}",
+ "resolved": "해결됨 {{count}}",
+ "close": "댓글 닫기",
+ "quote_missing": "댓글을 단 텍스트가 변경되었습니다",
+ "reply_placeholder": "답글 또는 @ 멘션…",
+ "new_placeholder": "댓글 입력, @로 멘션…",
+ "submit": "댓글",
+ "reply": "답글",
+ "cancel": "취소",
+ "resolve": "해결",
+ "reopen": "다시 열기",
+ "delete": "댓글 삭제",
+ "resolved_by": "{{name}} 님이 해결함",
+ "replies_other": "답글 {{count}}개",
+ "empty_open": "미해결 댓글이 없습니다. 텍스트를 선택하고 '댓글'을 눌러 시작하세요.",
+ "empty_resolved": "해결된 댓글이 없습니다.",
+ "errors": {
+ "save": "댓글을 게시하지 못했습니다",
+ "delete": "댓글을 삭제하지 못했습니다",
+ "resolve": "토론을 업데이트하지 못했습니다"
+ }
}
}
diff --git a/packages/views/locales/ko/inbox.json b/packages/views/locales/ko/inbox.json
index 5d2f74aa9c..6b7dba8fcd 100644
--- a/packages/views/locales/ko/inbox.json
+++ b/packages/views/locales/ko/inbox.json
@@ -73,7 +73,8 @@
"open_project": "프로젝트 열기",
"autopilot_quota_upgrade": "업그레이드 옵션 보기",
"archive": "보관",
- "unarchive": "보관 해제"
+ "unarchive": "보관 해제",
+ "open_doc": "문서 열기"
},
"types": {
"issue_assigned": "할당됨",
@@ -103,7 +104,9 @@
"app_action_requested": "확인 필요",
"app_action_reminder": "확인 곧 만료",
"app_connect_requested": "앱 연결 요청",
- "app_action_result": "앱 작업 결과"
+ "app_action_result": "앱 작업 결과",
+ "doc_comment": "문서에 새 댓글",
+ "doc_mentioned": "문서에서 멘션됨"
},
"labels": {
"set_status_to": "상태 변경:",
diff --git a/packages/views/locales/ru/docs.json b/packages/views/locales/ru/docs.json
index 554c765013..faa98deede 100644
--- a/packages/views/locales/ru/docs.json
+++ b/packages/views/locales/ru/docs.json
@@ -66,5 +66,33 @@
"unavailable": {
"title": "Документы недоступны",
"description": "В этом рабочем пространстве документы не включены."
+ },
+ "comments": {
+ "title": "Комментарии",
+ "add": "Комментировать",
+ "open": "Открытые {{count}}",
+ "resolved": "Решённые {{count}}",
+ "close": "Закрыть комментарии",
+ "quote_missing": "Прокомментированный текст изменён",
+ "reply_placeholder": "Ответьте или упомяните через @…",
+ "new_placeholder": "Напишите комментарий, @ для упоминания…",
+ "submit": "Комментировать",
+ "reply": "Ответить",
+ "cancel": "Отмена",
+ "resolve": "Решить",
+ "reopen": "Открыть снова",
+ "delete": "Удалить комментарий",
+ "resolved_by": "Решено: {{name}}",
+ "replies_one": "{{count}} ответ",
+ "replies_few": "{{count}} ответа",
+ "replies_many": "{{count}} ответов",
+ "replies_other": "{{count}} ответа",
+ "empty_open": "Открытых комментариев нет. Выделите текст и нажмите «Комментировать».",
+ "empty_resolved": "Решённых комментариев нет.",
+ "errors": {
+ "save": "Не удалось отправить комментарий",
+ "delete": "Не удалось удалить комментарий",
+ "resolve": "Не удалось обновить обсуждение"
+ }
}
}
diff --git a/packages/views/locales/ru/inbox.json b/packages/views/locales/ru/inbox.json
index b9bbf643d7..a2a3e80315 100644
--- a/packages/views/locales/ru/inbox.json
+++ b/packages/views/locales/ru/inbox.json
@@ -79,7 +79,8 @@
"open_project": "Открыть проект",
"autopilot_quota_upgrade": "Посмотреть варианты обновления",
"archive": "Архивировать",
- "unarchive": "Восстановить из архива"
+ "unarchive": "Восстановить из архива",
+ "open_doc": "Открыть документ"
},
"types": {
"issue_assigned": "Назначено",
@@ -109,7 +110,9 @@
"app_action_requested": "Требуется ваше подтверждение",
"app_action_reminder": "Срок подтверждения скоро истечёт",
"app_connect_requested": "Подключить приложение",
- "app_action_result": "Результат действия приложения"
+ "app_action_result": "Результат действия приложения",
+ "doc_comment": "Новый комментарий в документе",
+ "doc_mentioned": "Вас упомянули в документе"
},
"labels": {
"set_status_to": "Установлен статус",
diff --git a/packages/views/locales/zh-Hans/docs.json b/packages/views/locales/zh-Hans/docs.json
index 57a35f27ed..4c2fff630b 100644
--- a/packages/views/locales/zh-Hans/docs.json
+++ b/packages/views/locales/zh-Hans/docs.json
@@ -66,5 +66,30 @@
"unavailable": {
"title": "知识库暂未开放",
"description": "当前工作区尚未开启知识库。"
+ },
+ "comments": {
+ "title": "评论",
+ "add": "评论",
+ "open": "未解决 {{count}}",
+ "resolved": "已解决 {{count}}",
+ "close": "关闭评论",
+ "quote_missing": "原文已修改,找不到划线位置",
+ "reply_placeholder": "回复,或 @ 某人…",
+ "new_placeholder": "写下评论,@ 提及某人…",
+ "submit": "评论",
+ "reply": "回复",
+ "cancel": "取消",
+ "resolve": "解决",
+ "reopen": "重新打开",
+ "delete": "删除评论",
+ "resolved_by": "{{name}} 已解决",
+ "replies_other": "{{count}} 条回复",
+ "empty_open": "没有未解决的评论。选中文字后点「评论」即可发起。",
+ "empty_resolved": "没有已解决的评论。",
+ "errors": {
+ "save": "评论发送失败",
+ "delete": "评论删除失败",
+ "resolve": "无法更新讨论"
+ }
}
}
diff --git a/packages/views/locales/zh-Hans/inbox.json b/packages/views/locales/zh-Hans/inbox.json
index 99e37f9fb5..6cb246b30d 100644
--- a/packages/views/locales/zh-Hans/inbox.json
+++ b/packages/views/locales/zh-Hans/inbox.json
@@ -73,7 +73,8 @@
"open_project": "打开项目",
"autopilot_quota_upgrade": "查看升级方案",
"archive": "归档",
- "unarchive": "取消归档"
+ "unarchive": "取消归档",
+ "open_doc": "打开文档"
},
"types": {
"issue_assigned": "已分配",
@@ -103,7 +104,9 @@
"app_action_requested": "等待你确认",
"app_action_reminder": "确认即将过期",
"app_connect_requested": "请连接应用",
- "app_action_result": "应用操作结果"
+ "app_action_result": "应用操作结果",
+ "doc_comment": "文档有新评论",
+ "doc_mentioned": "在文档中提到了你"
},
"labels": {
"set_status_to": "状态设为",
diff --git a/packages/views/locales/zh-Hant/docs.json b/packages/views/locales/zh-Hant/docs.json
index 0a8f481ead..871f64b450 100644
--- a/packages/views/locales/zh-Hant/docs.json
+++ b/packages/views/locales/zh-Hant/docs.json
@@ -66,5 +66,30 @@
"unavailable": {
"title": "知識庫暫未開放",
"description": "目前工作區尚未開啟知識庫。"
+ },
+ "comments": {
+ "title": "評論",
+ "add": "評論",
+ "open": "未解決 {{count}}",
+ "resolved": "已解決 {{count}}",
+ "close": "關閉評論",
+ "quote_missing": "原文已修改,找不到劃線位置",
+ "reply_placeholder": "回覆,或 @ 某人…",
+ "new_placeholder": "寫下評論,@ 提及某人…",
+ "submit": "評論",
+ "reply": "回覆",
+ "cancel": "取消",
+ "resolve": "解決",
+ "reopen": "重新開啟",
+ "delete": "刪除評論",
+ "resolved_by": "{{name}} 已解決",
+ "replies_other": "{{count}} 則回覆",
+ "empty_open": "沒有未解決的評論。選取文字後點「評論」即可發起。",
+ "empty_resolved": "沒有已解決的評論。",
+ "errors": {
+ "save": "評論送出失敗",
+ "delete": "評論刪除失敗",
+ "resolve": "無法更新討論"
+ }
}
}
diff --git a/packages/views/locales/zh-Hant/inbox.json b/packages/views/locales/zh-Hant/inbox.json
index 8678352140..ac20c9fd3a 100644
--- a/packages/views/locales/zh-Hant/inbox.json
+++ b/packages/views/locales/zh-Hant/inbox.json
@@ -73,7 +73,8 @@
"open_project": "開啟專案",
"autopilot_quota_upgrade": "檢視升級方案",
"archive": "歸檔",
- "unarchive": "取消歸檔"
+ "unarchive": "取消歸檔",
+ "open_doc": "開啟文件"
},
"types": {
"issue_assigned": "已分配",
@@ -103,7 +104,9 @@
"app_action_requested": "等待你確認",
"app_action_reminder": "確認即將過期",
"app_connect_requested": "請連線應用",
- "app_action_result": "應用操作結果"
+ "app_action_result": "應用操作結果",
+ "doc_comment": "文件有新評論",
+ "doc_mentioned": "在文件中提到了你"
},
"labels": {
"set_status_to": "狀態設為",
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index 347fe454e2..b26b554c20 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -155,6 +155,9 @@ var concurrentIndexCleanups = map[string]string{
"696_inbox_item_active_shown_idx": "idx_inbox_active_shown",
"698_autopilot_run_idempotency_key_idx": "uq_autopilot_run_idempotency_key",
"701_member_search_access_pkey_index": "member_search_access_pkey_idx",
+ "704_doc_comment_pkey_index": "doc_comment_pkey_idx",
+ "706_doc_comment_doc_idx": "doc_comment_doc_idx",
+ "707_doc_comment_workspace_idx": "doc_comment_workspace_idx",
"671_weixin_account_state_unique_index": "weixin_account_state_pkey",
"669_weixin_login_session_unique_index": "weixin_login_session_pkey",
"666_weixin_login_expiry_idx": "weixin_login_expiry_idx",
diff --git a/server/cmd/server/private_project_routes_test.go b/server/cmd/server/private_project_routes_test.go
index 5771ee8e15..3ae7ccb20c 100644
--- a/server/cmd/server/private_project_routes_test.go
+++ b/server/cmd/server/private_project_routes_test.go
@@ -109,6 +109,7 @@ var routeParamsOutsideProjects = map[string]outsideProjectParam{
"project-folders/{id}": {why: "a workspace folder of projects"},
"docs/{id}": {why: "a workspace doc"},
"doc-folders/{id}": {why: "a workspace folder of docs"},
+ "comments/{docCommentId}": {why: "a discussion on a workspace doc"},
"versions/{number}": {why: "a version of a workspace doc; the run that wrote it is recorded by id only"},
"metadata/{key}": {why: "a metadata key", value: func(*privateRouteFixture) string { return "route-probe" }},
"system-wakeups/{rule}": {why: "a system wakeup rule name", value: func(*privateRouteFixture) string { return "child_done" }},
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 6daf193afb..f03657376d 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -2347,6 +2347,17 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Post("/move", h.MoveDoc)
r.Get("/versions", h.ListDocVersions)
r.Get("/versions/{number}", h.GetDocVersion)
+ r.Route("/comments", func(r chi.Router) {
+ r.Get("/", h.ListDocComments)
+ // Writing in discussions is human-only until agents can take part.
+ r.Group(func(r chi.Router) {
+ r.Use(handler.RequireHumanActor)
+ r.Post("/", h.CreateDocComment)
+ r.Post("/{docCommentId}/resolve", h.ResolveDocComment)
+ r.Post("/{docCommentId}/reopen", h.ReopenDocComment)
+ r.Delete("/{docCommentId}", h.DeleteDocComment)
+ })
+ })
})
})
r.Route("/api/doc-folders", func(r chi.Router) {
diff --git a/server/internal/handler/doc_comment.go b/server/internal/handler/doc_comment.go
new file mode 100644
index 0000000000..d05ea2866a
--- /dev/null
+++ b/server/internal/handler/doc_comment.go
@@ -0,0 +1,351 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "log/slog"
+ "net/http"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/inbox"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// Doc comments are discussions on a doc's text (MUL-8370). A root comment
+// carries the anchor — the quoted text and a little context on each side,
+// which clients re-locate by text after every save — and replies hang off the
+// root, one level deep. Writing is human-only for now; agents join in a later
+// change.
+
+const (
+ docCommentMaxContent = 20000
+ docCommentMaxQuote = 4000
+ docCommentMaxContext = 64
+
+ inboxTypeDocComment = "doc_comment"
+ inboxTypeDocMentioned = "doc_mentioned"
+)
+
+type DocCommentResponse struct {
+ ID string `json:"id"`
+ DocID string `json:"doc_id"`
+ ParentID *string `json:"parent_id"`
+ AuthorType string `json:"author_type"`
+ AuthorID string `json:"author_id"`
+ Content string `json:"content"`
+ AnchorQuote string `json:"anchor_quote"`
+ AnchorPrefix string `json:"anchor_prefix"`
+ AnchorSuffix string `json:"anchor_suffix"`
+ ResolvedAt *string `json:"resolved_at"`
+ ResolvedByType *string `json:"resolved_by_type"`
+ ResolvedByID *string `json:"resolved_by_id"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
+}
+
+func docCommentToResponse(c db.DocComment) DocCommentResponse {
+ return DocCommentResponse{
+ ID: uuidToString(c.ID),
+ DocID: uuidToString(c.DocID),
+ ParentID: uuidToPtr(c.ParentID),
+ AuthorType: c.AuthorType,
+ AuthorID: uuidToString(c.AuthorID),
+ Content: c.Content,
+ AnchorQuote: c.AnchorQuote,
+ AnchorPrefix: c.AnchorPrefix,
+ AnchorSuffix: c.AnchorSuffix,
+ ResolvedAt: timestampToPtr(c.ResolvedAt),
+ ResolvedByType: textToPtr(c.ResolvedByType),
+ ResolvedByID: uuidToPtr(c.ResolvedByID),
+ CreatedAt: timestampToString(c.CreatedAt),
+ UpdatedAt: timestampToString(c.UpdatedAt),
+ }
+}
+
+func (h *Handler) ListDocComments(w http.ResponseWriter, r *http.Request) {
+ _, wsUUID, _, ok := h.docWorkspace(w, r)
+ if !ok {
+ return
+ }
+ doc, ok := h.loadDoc(w, r, wsUUID)
+ if !ok {
+ return
+ }
+ rows, err := h.Queries.ListDocComments(r.Context(), db.ListDocCommentsParams{DocID: doc.ID, WorkspaceID: wsUUID})
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list comments")
+ return
+ }
+ resp := make([]DocCommentResponse, len(rows))
+ for i, c := range rows {
+ resp[i] = docCommentToResponse(c)
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"comments": resp})
+}
+
+type CreateDocCommentRequest struct {
+ Content string `json:"content"`
+ ParentID *string `json:"parent_id"`
+ AnchorQuote string `json:"anchor_quote"`
+ AnchorPrefix string `json:"anchor_prefix"`
+ AnchorSuffix string `json:"anchor_suffix"`
+}
+
+func (h *Handler) CreateDocComment(w http.ResponseWriter, r *http.Request) {
+ userID, wsUUID, workspaceID, ok := h.docWorkspace(w, r)
+ if !ok {
+ return
+ }
+ doc, ok := h.loadDoc(w, r, wsUUID)
+ if !ok {
+ return
+ }
+ var req CreateDocCommentRequest
+ r.Body = http.MaxBytesReader(w, r.Body, 256<<10)
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ content := strings.TrimSpace(strings.ReplaceAll(req.Content, "\x00", ""))
+ if content == "" || utf8.RuneCountInString(content) > docCommentMaxContent {
+ writeError(w, http.StatusBadRequest, "content must be 1 to 20000 characters")
+ return
+ }
+
+ params := db.CreateDocCommentParams{
+ ID: dbid.NewV7(), WorkspaceID: wsUUID, DocID: doc.ID, Content: content,
+ }
+ var root db.DocComment
+ if req.ParentID != nil {
+ parentUUID, ok := parseUUIDOrBadRequest(w, *req.ParentID, "parent_id")
+ if !ok {
+ return
+ }
+ parent, err := h.Queries.GetDocComment(r.Context(), db.GetDocCommentParams{ID: parentUUID, DocID: doc.ID, WorkspaceID: wsUUID})
+ if err != nil {
+ if isNotFound(err) {
+ writeError(w, http.StatusBadRequest, "parent comment not found")
+ } else {
+ writeError(w, http.StatusInternalServerError, "failed to create comment")
+ }
+ return
+ }
+ // One level of replies: answering a reply joins its discussion.
+ if parent.ParentID.Valid {
+ parent, err = h.Queries.GetDocComment(r.Context(), db.GetDocCommentParams{ID: parent.ParentID, DocID: doc.ID, WorkspaceID: wsUUID})
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "parent comment not found")
+ return
+ }
+ }
+ root = parent
+ params.ParentID = parent.ID
+ } else {
+ quote := strings.ReplaceAll(req.AnchorQuote, "\x00", "")
+ if strings.TrimSpace(quote) == "" || utf8.RuneCountInString(quote) > docCommentMaxQuote {
+ writeError(w, http.StatusBadRequest, "anchor_quote must be 1 to 4000 characters")
+ return
+ }
+ params.AnchorQuote = quote
+ params.AnchorPrefix = lastRunes(strings.ReplaceAll(req.AnchorPrefix, "\x00", ""), docCommentMaxContext)
+ params.AnchorSuffix = firstRunes(strings.ReplaceAll(req.AnchorSuffix, "\x00", ""), docCommentMaxContext)
+ }
+
+ actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ params.AuthorType = actorType
+ params.AuthorID = parseUUID(actorID)
+ comment, err := h.Queries.CreateDocComment(r.Context(), params)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to create comment")
+ return
+ }
+ if !params.ParentID.Valid {
+ root = comment
+ }
+ h.publish(protocol.EventDocCommentChanged, workspaceID, actorType, actorID, map[string]any{
+ "doc_id": uuidToString(doc.ID), "comment_id": uuidToString(comment.ID),
+ })
+ h.notifyDocComment(r.Context(), doc, root, comment, actorType, actorID)
+ writeJSON(w, http.StatusCreated, docCommentToResponse(comment))
+}
+
+// notifyDocComment tells the members a new comment is for: everyone it
+// @mentions, and everyone who already wrote in the discussion. The author and
+// guests are never notified, and a member gets one item even when both apply.
+func (h *Handler) notifyDocComment(ctx context.Context, doc db.Doc, root, comment db.DocComment, actorType, actorID string) {
+ author := uuidToString(comment.AuthorID)
+ mentioned := map[string]bool{}
+ for _, m := range util.ParseMentions(comment.Content) {
+ if m.Type == "member" && m.ID != author {
+ mentioned[m.ID] = true
+ }
+ }
+ participants := map[string]bool{}
+ if ids, err := h.Queries.ListDocThreadParticipants(ctx, db.ListDocThreadParticipantsParams{
+ WorkspaceID: doc.WorkspaceID, DocID: doc.ID, RootID: root.ID,
+ }); err == nil {
+ for _, id := range ids {
+ if s := uuidToString(id); s != author && !mentioned[s] {
+ participants[s] = true
+ }
+ }
+ }
+ details, _ := json.Marshal(map[string]string{
+ "doc_id": uuidToString(doc.ID),
+ "thread_id": uuidToString(root.ID),
+ "comment_id": uuidToString(comment.ID),
+ "quote": firstRunes(root.AnchorQuote, 200),
+ })
+ body := firstRunes(comment.Content, 500)
+ deliver := func(recipient, kind string) {
+ recipientUUID, err := util.ParseUUID(recipient)
+ if err != nil {
+ return
+ }
+ // Docs are closed to guests (and to anyone outside the workspace), so
+ // a notification carrying the doc's title and text must not reach them.
+ member, err := h.Queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
+ UserID: recipientUUID, WorkspaceID: doc.WorkspaceID,
+ })
+ if err != nil || projectaccess.IsGuestRole(member.Role) {
+ return
+ }
+ if _, _, err := inbox.Deliver(ctx, h.Queries, h.Bus, inbox.Notification{Params: db.CreateInboxItemParams{
+ ID: dbid.NewV7(),
+ WorkspaceID: doc.WorkspaceID,
+ RecipientType: "member",
+ RecipientID: recipientUUID,
+ Type: kind,
+ Severity: "info",
+ Title: doc.Title,
+ Body: pgtype.Text{String: body, Valid: true},
+ ActorType: pgtype.Text{String: actorType, Valid: true},
+ ActorID: parseUUID(actorID),
+ Details: details,
+ }}); err != nil {
+ slog.Warn("doc comment notification failed", "doc_id", uuidToString(doc.ID), "recipient_id", recipient, "error", err)
+ }
+ }
+ for id := range mentioned {
+ deliver(id, inboxTypeDocMentioned)
+ }
+ for id := range participants {
+ deliver(id, inboxTypeDocComment)
+ }
+}
+
+func (h *Handler) loadDocComment(w http.ResponseWriter, r *http.Request, doc db.Doc) (db.DocComment, bool) {
+ commentUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "docCommentId"), "comment id")
+ if !ok {
+ return db.DocComment{}, false
+ }
+ comment, err := h.Queries.GetDocComment(r.Context(), db.GetDocCommentParams{ID: commentUUID, DocID: doc.ID, WorkspaceID: doc.WorkspaceID})
+ if err != nil {
+ if isNotFound(err) {
+ writeError(w, http.StatusNotFound, "comment not found")
+ } else {
+ writeError(w, http.StatusInternalServerError, "failed to load comment")
+ }
+ return db.DocComment{}, false
+ }
+ return comment, true
+}
+
+func (h *Handler) setDocCommentResolution(w http.ResponseWriter, r *http.Request, resolve bool) {
+ userID, wsUUID, workspaceID, ok := h.docWorkspace(w, r)
+ if !ok {
+ return
+ }
+ doc, ok := h.loadDoc(w, r, wsUUID)
+ if !ok {
+ return
+ }
+ comment, ok := h.loadDocComment(w, r, doc)
+ if !ok {
+ return
+ }
+ if comment.ParentID.Valid {
+ writeError(w, http.StatusBadRequest, "only a discussion's first comment can be resolved")
+ return
+ }
+ actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ params := db.SetDocCommentResolutionParams{ID: comment.ID, DocID: doc.ID, WorkspaceID: wsUUID}
+ if resolve {
+ params.ResolvedAt = pgtype.Timestamptz{Time: time.Now(), Valid: true}
+ params.ResolvedByType = pgtype.Text{String: actorType, Valid: true}
+ params.ResolvedByID = parseUUID(actorID)
+ }
+ updated, err := h.Queries.SetDocCommentResolution(r.Context(), params)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update comment")
+ return
+ }
+ h.publish(protocol.EventDocCommentChanged, workspaceID, actorType, actorID, map[string]any{
+ "doc_id": uuidToString(doc.ID), "comment_id": uuidToString(updated.ID),
+ })
+ writeJSON(w, http.StatusOK, docCommentToResponse(updated))
+}
+
+func (h *Handler) ResolveDocComment(w http.ResponseWriter, r *http.Request) {
+ h.setDocCommentResolution(w, r, true)
+}
+
+func (h *Handler) ReopenDocComment(w http.ResponseWriter, r *http.Request) {
+ h.setDocCommentResolution(w, r, false)
+}
+
+// DeleteDocComment removes the caller's own comment; removing a discussion's
+// first comment removes the discussion.
+func (h *Handler) DeleteDocComment(w http.ResponseWriter, r *http.Request) {
+ userID, wsUUID, workspaceID, ok := h.docWorkspace(w, r)
+ if !ok {
+ return
+ }
+ doc, ok := h.loadDoc(w, r, wsUUID)
+ if !ok {
+ return
+ }
+ comment, ok := h.loadDocComment(w, r, doc)
+ if !ok {
+ return
+ }
+ actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ if comment.AuthorType != actorType || uuidToString(comment.AuthorID) != actorID {
+ writeError(w, http.StatusForbidden, "only the author can delete a comment")
+ return
+ }
+ if err := h.Queries.DeleteDocCommentThread(r.Context(), db.DeleteDocCommentThreadParams{
+ WorkspaceID: wsUUID, DocID: doc.ID, ID: comment.ID,
+ }); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to delete comment")
+ return
+ }
+ h.publish(protocol.EventDocCommentChanged, workspaceID, actorType, actorID, map[string]any{
+ "doc_id": uuidToString(doc.ID), "comment_id": uuidToString(comment.ID),
+ })
+ w.WriteHeader(http.StatusNoContent)
+}
+
+func firstRunes(s string, n int) string {
+ if utf8.RuneCountInString(s) <= n {
+ return s
+ }
+ return string([]rune(s)[:n])
+}
+
+func lastRunes(s string, n int) string {
+ runes := []rune(s)
+ if len(runes) <= n {
+ return s
+ }
+ return string(runes[len(runes)-n:])
+}
diff --git a/server/internal/handler/doc_comment_test.go b/server/internal/handler/doc_comment_test.go
new file mode 100644
index 0000000000..766b722dba
--- /dev/null
+++ b/server/internal/handler/doc_comment_test.go
@@ -0,0 +1,121 @@
+package handler
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+func TestDocCommentsDiscussNotifyAndResolve(t *testing.T) {
+ doc := createDocForTest(t)
+ t.Cleanup(func() { testPool.Exec(context.Background(), "DELETE FROM doc_comment WHERE doc_id = $1", doc.ID) })
+ stamp := time.Now().UnixNano()
+ other := dbfx.User(t, "Li Ran", fmt.Sprintf("li-ran-%[email protected]", stamp))
+ dbfx.Member(t, testWorkspaceID, other, "member")
+ third := dbfx.User(t, "Wang Xue", fmt.Sprintf("wang-xue-%[email protected]", stamp))
+ dbfx.Member(t, testWorkspaceID, third, "member")
+ guest := dbfx.User(t, "Zhou Kai", fmt.Sprintf("zhou-kai-%[email protected]", stamp))
+ dbfx.Member(t, testWorkspaceID, guest, "guest")
+ outsider := dbfx.User(t, "Chen Yu", fmt.Sprintf("chen-yu-%[email protected]", stamp))
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), "DELETE FROM inbox_item WHERE recipient_id = ANY($1::uuid[])", []string{other, third, guest, outsider, testUserID})
+ })
+
+ comments := func() []DocCommentResponse {
+ t.Helper()
+ var out struct {
+ Comments []DocCommentResponse `json:"comments"`
+ }
+ testutil.Call(t, testHandler.ListDocComments, withURLParam(newRequest("GET", "/comments", nil), "id", doc.ID)).Want(http.StatusOK).JSON(&out)
+ return out.Comments
+ }
+ post := func(body map[string]any, as string) *http.Request {
+ req := withURLParam(newRequest("POST", "/comments", body), "id", doc.ID)
+ if as != "" {
+ req.Header.Set("X-User-ID", as)
+ }
+ return req
+ }
+ inboxFor := func(user, kind string) int {
+ return dbfx.Count(t, "SELECT count(*) FROM inbox_item WHERE recipient_id = $1 AND type = $2 AND details->>'doc_id' = $3", user, kind, doc.ID)
+ }
+
+ // A discussion needs the text it is about.
+ testutil.Call(t, testHandler.CreateDocComment, post(map[string]any{"content": "Why?"}, "")).Want(http.StatusBadRequest)
+
+ var root DocCommentResponse
+ testutil.Call(t, testHandler.CreateDocComment, post(map[string]any{
+ "content": "Can index-only migrations rehearse the same day? [@Li Ran](mention://member/" + other + ") " +
+ "[@Zhou Kai](mention://member/" + guest + ") [@Chen Yu](mention://member/" + outsider + ")",
+ "anchor_quote": "Original",
+ "anchor_prefix": "# First\n\n",
+ "anchor_suffix": "",
+ }, "")).Want(http.StatusCreated).JSON(&root)
+ if root.ParentID != nil || root.AnchorQuote != "Original" || root.AuthorID != testUserID {
+ t.Fatalf("root comment: %+v", root)
+ }
+ if inboxFor(other, "doc_mentioned") != 1 || inboxFor(testUserID, "doc_mentioned")+inboxFor(testUserID, "doc_comment") != 0 {
+ t.Fatal("a mention notifies the mentioned member, never the author")
+ }
+ // Guests cannot open docs and outsiders are not in the workspace; neither
+ // may read the doc's text in their inbox.
+ if inboxFor(guest, "doc_mentioned")+inboxFor(outsider, "doc_mentioned") != 0 {
+ t.Fatal("a mention must not notify a guest or a non-member")
+ }
+
+ // A reply joins the discussion; answering a reply still lands on the root.
+ var reply DocCommentResponse
+ testutil.Call(t, testHandler.CreateDocComment, post(map[string]any{"content": "Yes, with CONCURRENTLY.", "parent_id": root.ID}, other)).Want(http.StatusCreated).JSON(&reply)
+ var nested DocCommentResponse
+ testutil.Call(t, testHandler.CreateDocComment, post(map[string]any{"content": "Thanks", "parent_id": reply.ID}, third)).Want(http.StatusCreated).JSON(&nested)
+ if reply.ParentID == nil || *reply.ParentID != root.ID || nested.ParentID == nil || *nested.ParentID != root.ID {
+ t.Fatalf("replies must hang off the root: %+v %+v", reply, nested)
+ }
+ // Participants hear about later replies; the third member was neither
+ // mentioned nor in the discussion when the first reply came.
+ if inboxFor(testUserID, "doc_comment") != 2 || inboxFor(other, "doc_comment") != 1 || inboxFor(third, "doc_comment") != 0 {
+ t.Fatalf("participant notifications: author=%d other=%d third=%d",
+ inboxFor(testUserID, "doc_comment"), inboxFor(other, "doc_comment"), inboxFor(third, "doc_comment"))
+ }
+ if got := comments(); len(got) != 3 || got[0].ID != root.ID {
+ t.Fatalf("list: %+v", got)
+ }
+
+ // Anyone can resolve and reopen; replies cannot be resolved.
+ resolve := func(id, action string, as string) *http.Request {
+ req := withURLParams(newRequest("POST", "/"+action, nil), "id", doc.ID, "docCommentId", id)
+ if as != "" {
+ req.Header.Set("X-User-ID", as)
+ }
+ return req
+ }
+ var resolved DocCommentResponse
+ testutil.Call(t, testHandler.ResolveDocComment, resolve(root.ID, "resolve", third)).Want(http.StatusOK).JSON(&resolved)
+ if resolved.ResolvedAt == nil || resolved.ResolvedByID == nil || *resolved.ResolvedByID != third {
+ t.Fatalf("resolve: %+v", resolved)
+ }
+ testutil.Call(t, testHandler.ResolveDocComment, resolve(reply.ID, "resolve", "")).Want(http.StatusBadRequest)
+ testutil.Call(t, testHandler.ReopenDocComment, resolve(root.ID, "reopen", "")).Want(http.StatusOK).JSON(&resolved)
+ if resolved.ResolvedAt != nil {
+ t.Fatalf("reopen: %+v", resolved)
+ }
+
+ // Only the author deletes; deleting the root removes the discussion.
+ testutil.Call(t, testHandler.DeleteDocComment, withURLParams(newRequest("DELETE", "/", nil), "id", doc.ID, "docCommentId", root.ID)).Want(http.StatusNoContent)
+ if got := comments(); len(got) != 0 {
+ t.Fatalf("deleting the root must remove replies: %+v", got)
+ }
+ var again DocCommentResponse
+ testutil.Call(t, testHandler.CreateDocComment, post(map[string]any{"content": "x", "anchor_quote": "Original"}, other)).Want(http.StatusCreated).JSON(&again)
+ testutil.Call(t, testHandler.DeleteDocComment, withURLParams(newRequest("DELETE", "/", nil), "id", doc.ID, "docCommentId", again.ID)).Want(http.StatusForbidden)
+
+ // Deleting the doc removes its discussions.
+ testutil.Call(t, testHandler.DeleteDoc, withURLParam(newRequest("DELETE", "/api/docs", nil), "id", doc.ID)).Want(http.StatusNoContent)
+ if n := dbfx.Count(t, "SELECT count(*) FROM doc_comment WHERE doc_id = $1", doc.ID); n != 0 {
+ t.Fatalf("doc delete left %d comments", n)
+ }
+}
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index cb55d95a1b..b659c469f6 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -66,6 +66,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"dingtalk_bot_identity": workspaceDelete,
"dingtalk_group_route": workspaceDelete,
"doc": workspaceDelete,
+ "doc_comment": workspaceDelete,
"doc_folder": workspaceDelete,
"doc_version": workspaceDelete,
"entitlement_feature_attempt": workspaceDelete,
diff --git a/server/internal/inbox/registry.go b/server/internal/inbox/registry.go
index 2d8f0b22d9..bf9f1e3563 100644
--- a/server/internal/inbox/registry.go
+++ b/server/internal/inbox/registry.go
@@ -39,6 +39,8 @@ var typeGroups = map[string]string{
"status_changed": GroupStatusChanges,
"new_comment": GroupComments,
"mentioned": GroupMentions,
+ "doc_comment": GroupComments,
+ "doc_mentioned": GroupMentions,
"reaction_added": GroupReactions,
"priority_changed": GroupUpdates,
"start_date_changed": GroupUpdates,
diff --git a/server/migrations/703_doc_comment.down.sql b/server/migrations/703_doc_comment.down.sql
new file mode 100644
index 0000000000..f5611de19e
--- /dev/null
+++ b/server/migrations/703_doc_comment.down.sql
@@ -0,0 +1 @@
+DROP TABLE IF EXISTS doc_comment;
diff --git a/server/migrations/703_doc_comment.up.sql b/server/migrations/703_doc_comment.up.sql
new file mode 100644
index 0000000000..36bfd80d35
--- /dev/null
+++ b/server/migrations/703_doc_comment.up.sql
@@ -0,0 +1,21 @@
+-- Discussions on a doc's text (MUL-8370). A root comment carries the anchor
+-- (the quoted text and its surrounding context, re-located by text after each
+-- save); replies point at their root through parent_id. No foreign keys: the
+-- doc and workspace delete paths remove comments in application code.
+CREATE TABLE IF NOT EXISTS doc_comment (
+ id UUID NOT NULL DEFAULT gen_random_uuid(),
+ workspace_id UUID NOT NULL,
+ doc_id UUID NOT NULL,
+ parent_id UUID,
+ author_type TEXT NOT NULL CHECK (author_type IN ('member', 'agent')),
+ author_id UUID NOT NULL,
+ content TEXT NOT NULL CHECK (char_length(content) BETWEEN 1 AND 20000),
+ anchor_quote TEXT NOT NULL DEFAULT '' CHECK (char_length(anchor_quote) <= 4000),
+ anchor_prefix TEXT NOT NULL DEFAULT '' CHECK (char_length(anchor_prefix) <= 64),
+ anchor_suffix TEXT NOT NULL DEFAULT '' CHECK (char_length(anchor_suffix) <= 64),
+ resolved_at TIMESTAMPTZ,
+ resolved_by_type TEXT CHECK (resolved_by_type IN ('member', 'agent')),
+ resolved_by_id UUID,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
diff --git a/server/migrations/704_doc_comment_pkey_index.down.sql b/server/migrations/704_doc_comment_pkey_index.down.sql
new file mode 100644
index 0000000000..7de1ca6045
--- /dev/null
+++ b/server/migrations/704_doc_comment_pkey_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS doc_comment_pkey_idx;
diff --git a/server/migrations/704_doc_comment_pkey_index.up.sql b/server/migrations/704_doc_comment_pkey_index.up.sql
new file mode 100644
index 0000000000..0d1149a193
--- /dev/null
+++ b/server/migrations/704_doc_comment_pkey_index.up.sql
@@ -0,0 +1 @@
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS doc_comment_pkey_idx ON doc_comment (id);
diff --git a/server/migrations/705_doc_comment_pkey.down.sql b/server/migrations/705_doc_comment_pkey.down.sql
new file mode 100644
index 0000000000..c812448720
--- /dev/null
+++ b/server/migrations/705_doc_comment_pkey.down.sql
@@ -0,0 +1 @@
+ALTER TABLE doc_comment DROP CONSTRAINT IF EXISTS doc_comment_pkey;
diff --git a/server/migrations/705_doc_comment_pkey.up.sql b/server/migrations/705_doc_comment_pkey.up.sql
new file mode 100644
index 0000000000..b43517c750
--- /dev/null
+++ b/server/migrations/705_doc_comment_pkey.up.sql
@@ -0,0 +1 @@
+ALTER TABLE doc_comment ADD CONSTRAINT doc_comment_pkey PRIMARY KEY USING INDEX doc_comment_pkey_idx;
diff --git a/server/migrations/706_doc_comment_doc_idx.down.sql b/server/migrations/706_doc_comment_doc_idx.down.sql
new file mode 100644
index 0000000000..2564a53219
--- /dev/null
+++ b/server/migrations/706_doc_comment_doc_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS doc_comment_doc_idx;
diff --git a/server/migrations/706_doc_comment_doc_idx.up.sql b/server/migrations/706_doc_comment_doc_idx.up.sql
new file mode 100644
index 0000000000..48a27fe074
--- /dev/null
+++ b/server/migrations/706_doc_comment_doc_idx.up.sql
@@ -0,0 +1 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS doc_comment_doc_idx ON doc_comment (doc_id, created_at);
diff --git a/server/migrations/707_doc_comment_workspace_idx.down.sql b/server/migrations/707_doc_comment_workspace_idx.down.sql
new file mode 100644
index 0000000000..9a478b9286
--- /dev/null
+++ b/server/migrations/707_doc_comment_workspace_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS doc_comment_workspace_idx;
diff --git a/server/migrations/707_doc_comment_workspace_idx.up.sql b/server/migrations/707_doc_comment_workspace_idx.up.sql
new file mode 100644
index 0000000000..50c770b9a7
--- /dev/null
+++ b/server/migrations/707_doc_comment_workspace_idx.up.sql
@@ -0,0 +1 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS doc_comment_workspace_idx ON doc_comment (workspace_id);
diff --git a/server/pkg/db/generated/doc.sql.go b/server/pkg/db/generated/doc.sql.go
index b080113c63..5d2aa71885 100644
--- a/server/pkg/db/generated/doc.sql.go
+++ b/server/pkg/db/generated/doc.sql.go
@@ -78,6 +78,64 @@ func (q *Queries) CreateDoc(ctx context.Context, arg CreateDocParams) (Doc, erro
return i, err
}
+const createDocComment = `-- name: CreateDocComment :one
+INSERT INTO doc_comment (
+ id, workspace_id, doc_id, parent_id, author_type, author_id, content,
+ anchor_quote, anchor_prefix, anchor_suffix
+) VALUES (
+ $1, $2, $3, $4, $5, $6, $7,
+ $8, $9, $10
+)
+RETURNING id, workspace_id, doc_id, parent_id, author_type, author_id, content, anchor_quote, anchor_prefix, anchor_suffix, resolved_at, resolved_by_type, resolved_by_id, created_at, updated_at
+`
+
+type CreateDocCommentParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ DocID pgtype.UUID `json:"doc_id"`
+ ParentID pgtype.UUID `json:"parent_id"`
+ AuthorType string `json:"author_type"`
+ AuthorID pgtype.UUID `json:"author_id"`
+ Content string `json:"content"`
+ AnchorQuote string `json:"anchor_quote"`
+ AnchorPrefix string `json:"anchor_prefix"`
+ AnchorSuffix string `json:"anchor_suffix"`
+}
+
+func (q *Queries) CreateDocComment(ctx context.Context, arg CreateDocCommentParams) (DocComment, error) {
+ row := q.db.QueryRow(ctx, createDocComment,
+ arg.ID,
+ arg.WorkspaceID,
+ arg.DocID,
+ arg.ParentID,
+ arg.AuthorType,
+ arg.AuthorID,
+ arg.Content,
+ arg.AnchorQuote,
+ arg.AnchorPrefix,
+ arg.AnchorSuffix,
+ )
+ var i DocComment
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.DocID,
+ &i.ParentID,
+ &i.AuthorType,
+ &i.AuthorID,
+ &i.Content,
+ &i.AnchorQuote,
+ &i.AnchorPrefix,
+ &i.AnchorSuffix,
+ &i.ResolvedAt,
+ &i.ResolvedByType,
+ &i.ResolvedByID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
const createDocFolder = `-- name: CreateDocFolder :one
INSERT INTO doc_folder (workspace_id, parent_id, title, created_by_type, created_by_id)
VALUES ($1, $2, $3, $4, $5)
@@ -115,7 +173,8 @@ func (q *Queries) CreateDocFolder(ctx context.Context, arg CreateDocFolderParams
}
const deleteDoc = `-- name: DeleteDoc :exec
-WITH v AS (DELETE FROM doc_version WHERE doc_version.doc_id = $1 AND doc_version.workspace_id = $2)
+WITH v AS (DELETE FROM doc_version WHERE doc_version.doc_id = $1 AND doc_version.workspace_id = $2),
+c AS (DELETE FROM doc_comment WHERE doc_comment.doc_id = $1 AND doc_comment.workspace_id = $2)
DELETE FROM doc WHERE doc.id = $1 AND doc.workspace_id = $2
`
@@ -129,6 +188,24 @@ func (q *Queries) DeleteDoc(ctx context.Context, arg DeleteDocParams) error {
return err
}
+const deleteDocCommentThread = `-- name: DeleteDocCommentThread :exec
+DELETE FROM doc_comment
+WHERE workspace_id = $1 AND doc_id = $2
+ AND (id = $3 OR parent_id = $3)
+`
+
+type DeleteDocCommentThreadParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ DocID pgtype.UUID `json:"doc_id"`
+ ID pgtype.UUID `json:"id"`
+}
+
+// Deletes a comment; deleting a root takes its replies with it.
+func (q *Queries) DeleteDocCommentThread(ctx context.Context, arg DeleteDocCommentThreadParams) error {
+ _, err := q.db.Exec(ctx, deleteDocCommentThread, arg.WorkspaceID, arg.DocID, arg.ID)
+ return err
+}
+
const deleteDocFolder = `-- name: DeleteDocFolder :exec
DELETE FROM doc_folder WHERE id = $1 AND workspace_id = $2
`
@@ -145,6 +222,7 @@ func (q *Queries) DeleteDocFolder(ctx context.Context, arg DeleteDocFolderParams
const deleteWorkspaceDocs = `-- name: DeleteWorkspaceDocs :exec
WITH v AS (DELETE FROM doc_version WHERE doc_version.workspace_id = $1),
+c AS (DELETE FROM doc_comment WHERE doc_comment.workspace_id = $1),
f AS (DELETE FROM doc_folder WHERE doc_folder.workspace_id = $1)
DELETE FROM doc WHERE doc.workspace_id = $1
`
@@ -185,6 +263,40 @@ func (q *Queries) GetDoc(ctx context.Context, arg GetDocParams) (Doc, error) {
return i, err
}
+const getDocComment = `-- name: GetDocComment :one
+SELECT id, workspace_id, doc_id, parent_id, author_type, author_id, content, anchor_quote, anchor_prefix, anchor_suffix, resolved_at, resolved_by_type, resolved_by_id, created_at, updated_at FROM doc_comment
+WHERE id = $1 AND doc_id = $2 AND workspace_id = $3
+`
+
+type GetDocCommentParams struct {
+ ID pgtype.UUID `json:"id"`
+ DocID pgtype.UUID `json:"doc_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) GetDocComment(ctx context.Context, arg GetDocCommentParams) (DocComment, error) {
+ row := q.db.QueryRow(ctx, getDocComment, arg.ID, arg.DocID, arg.WorkspaceID)
+ var i DocComment
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.DocID,
+ &i.ParentID,
+ &i.AuthorType,
+ &i.AuthorID,
+ &i.Content,
+ &i.AnchorQuote,
+ &i.AnchorPrefix,
+ &i.AnchorSuffix,
+ &i.ResolvedAt,
+ &i.ResolvedByType,
+ &i.ResolvedByID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
const getDocFolder = `-- name: GetDocFolder :one
SELECT id, workspace_id, parent_id, title, created_by_type, created_by_id, created_at, updated_at FROM doc_folder
WHERE id = $1 AND workspace_id = $2
@@ -336,6 +448,53 @@ func (q *Queries) InsertDocVersion(ctx context.Context, arg InsertDocVersionPara
return i, err
}
+const listDocComments = `-- name: ListDocComments :many
+SELECT id, workspace_id, doc_id, parent_id, author_type, author_id, content, anchor_quote, anchor_prefix, anchor_suffix, resolved_at, resolved_by_type, resolved_by_id, created_at, updated_at FROM doc_comment
+WHERE doc_id = $1 AND workspace_id = $2
+ORDER BY created_at, id
+`
+
+type ListDocCommentsParams struct {
+ DocID pgtype.UUID `json:"doc_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) ListDocComments(ctx context.Context, arg ListDocCommentsParams) ([]DocComment, error) {
+ rows, err := q.db.Query(ctx, listDocComments, arg.DocID, arg.WorkspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []DocComment{}
+ for rows.Next() {
+ var i DocComment
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.DocID,
+ &i.ParentID,
+ &i.AuthorType,
+ &i.AuthorID,
+ &i.Content,
+ &i.AnchorQuote,
+ &i.AnchorPrefix,
+ &i.AnchorSuffix,
+ &i.ResolvedAt,
+ &i.ResolvedByType,
+ &i.ResolvedByID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listDocFolders = `-- name: ListDocFolders :many
SELECT id, workspace_id, parent_id, title, created_by_type, created_by_id, created_at, updated_at FROM doc_folder
WHERE workspace_id = $1
@@ -371,6 +530,40 @@ func (q *Queries) ListDocFolders(ctx context.Context, workspaceID pgtype.UUID) (
return items, nil
}
+const listDocThreadParticipants = `-- name: ListDocThreadParticipants :many
+SELECT DISTINCT author_id FROM doc_comment
+WHERE workspace_id = $1 AND doc_id = $2
+ AND (id = $3 OR parent_id = $3)
+ AND author_type = 'member'
+`
+
+type ListDocThreadParticipantsParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ DocID pgtype.UUID `json:"doc_id"`
+ RootID pgtype.UUID `json:"root_id"`
+}
+
+// Members who wrote in a discussion: its root author and every reply author.
+func (q *Queries) ListDocThreadParticipants(ctx context.Context, arg ListDocThreadParticipantsParams) ([]pgtype.UUID, error) {
+ rows, err := q.db.Query(ctx, listDocThreadParticipants, arg.WorkspaceID, arg.DocID, arg.RootID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []pgtype.UUID{}
+ for rows.Next() {
+ var author_id pgtype.UUID
+ if err := rows.Scan(&author_id); err != nil {
+ return nil, err
+ }
+ items = append(items, author_id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listDocVersions = `-- name: ListDocVersions :many
SELECT
doc_id, workspace_id, number, title, author_type, author_id, message, action,
@@ -638,6 +831,56 @@ func (q *Queries) RenameDocFolder(ctx context.Context, arg RenameDocFolderParams
return i, err
}
+const setDocCommentResolution = `-- name: SetDocCommentResolution :one
+UPDATE doc_comment SET
+ resolved_at = $1,
+ resolved_by_type = $2,
+ resolved_by_id = $3,
+ updated_at = now()
+WHERE id = $4 AND doc_id = $5 AND workspace_id = $6 AND parent_id IS NULL
+RETURNING id, workspace_id, doc_id, parent_id, author_type, author_id, content, anchor_quote, anchor_prefix, anchor_suffix, resolved_at, resolved_by_type, resolved_by_id, created_at, updated_at
+`
+
+type SetDocCommentResolutionParams struct {
+ ResolvedAt pgtype.Timestamptz `json:"resolved_at"`
+ ResolvedByType pgtype.Text `json:"resolved_by_type"`
+ ResolvedByID pgtype.UUID `json:"resolved_by_id"`
+ ID pgtype.UUID `json:"id"`
+ DocID pgtype.UUID `json:"doc_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Resolves (or, with null fields, reopens) a discussion. Roots only.
+func (q *Queries) SetDocCommentResolution(ctx context.Context, arg SetDocCommentResolutionParams) (DocComment, error) {
+ row := q.db.QueryRow(ctx, setDocCommentResolution,
+ arg.ResolvedAt,
+ arg.ResolvedByType,
+ arg.ResolvedByID,
+ arg.ID,
+ arg.DocID,
+ arg.WorkspaceID,
+ )
+ var i DocComment
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.DocID,
+ &i.ParentID,
+ &i.AuthorType,
+ &i.AuthorID,
+ &i.Content,
+ &i.AnchorQuote,
+ &i.AnchorPrefix,
+ &i.AnchorSuffix,
+ &i.ResolvedAt,
+ &i.ResolvedByType,
+ &i.ResolvedByID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
const updateDocContent = `-- name: UpdateDocContent :one
UPDATE doc SET
title = $1,
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 65174aa917..b7a124a7b6 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -860,6 +860,24 @@ type Doc struct {
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
+type DocComment struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ DocID pgtype.UUID `json:"doc_id"`
+ ParentID pgtype.UUID `json:"parent_id"`
+ AuthorType string `json:"author_type"`
+ AuthorID pgtype.UUID `json:"author_id"`
+ Content string `json:"content"`
+ AnchorQuote string `json:"anchor_quote"`
+ AnchorPrefix string `json:"anchor_prefix"`
+ AnchorSuffix string `json:"anchor_suffix"`
+ ResolvedAt pgtype.Timestamptz `json:"resolved_at"`
+ ResolvedByType pgtype.Text `json:"resolved_by_type"`
+ ResolvedByID pgtype.UUID `json:"resolved_by_id"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
type DocFolder struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
diff --git a/server/pkg/db/queries/doc.sql b/server/pkg/db/queries/doc.sql
index d7544a8eec..10fbe6b8fd 100644
--- a/server/pkg/db/queries/doc.sql
+++ b/server/pkg/db/queries/doc.sql
@@ -82,7 +82,8 @@ WHERE id = @id AND workspace_id = @workspace_id
RETURNING *;
-- name: DeleteDoc :exec
-WITH v AS (DELETE FROM doc_version WHERE doc_version.doc_id = @id AND doc_version.workspace_id = @workspace_id)
+WITH v AS (DELETE FROM doc_version WHERE doc_version.doc_id = @id AND doc_version.workspace_id = @workspace_id),
+c AS (DELETE FROM doc_comment WHERE doc_comment.doc_id = @id AND doc_comment.workspace_id = @workspace_id)
DELETE FROM doc WHERE doc.id = @id AND doc.workspace_id = @workspace_id;
-- name: GetDocVersion :one
@@ -127,5 +128,48 @@ RETURNING *;
-- name: DeleteWorkspaceDocs :exec
WITH v AS (DELETE FROM doc_version WHERE doc_version.workspace_id = @workspace_id),
+c AS (DELETE FROM doc_comment WHERE doc_comment.workspace_id = @workspace_id),
f AS (DELETE FROM doc_folder WHERE doc_folder.workspace_id = @workspace_id)
DELETE FROM doc WHERE doc.workspace_id = @workspace_id;
+
+-- name: ListDocComments :many
+SELECT * FROM doc_comment
+WHERE doc_id = @doc_id AND workspace_id = @workspace_id
+ORDER BY created_at, id;
+
+-- name: GetDocComment :one
+SELECT * FROM doc_comment
+WHERE id = @id AND doc_id = @doc_id AND workspace_id = @workspace_id;
+
+-- name: CreateDocComment :one
+INSERT INTO doc_comment (
+ id, workspace_id, doc_id, parent_id, author_type, author_id, content,
+ anchor_quote, anchor_prefix, anchor_suffix
+) VALUES (
+ @id, @workspace_id, @doc_id, sqlc.narg('parent_id'), @author_type, @author_id, @content,
+ @anchor_quote, @anchor_prefix, @anchor_suffix
+)
+RETURNING *;
+
+-- name: SetDocCommentResolution :one
+-- Resolves (or, with null fields, reopens) a discussion. Roots only.
+UPDATE doc_comment SET
+ resolved_at = sqlc.narg('resolved_at'),
+ resolved_by_type = sqlc.narg('resolved_by_type'),
+ resolved_by_id = sqlc.narg('resolved_by_id'),
+ updated_at = now()
+WHERE id = @id AND doc_id = @doc_id AND workspace_id = @workspace_id AND parent_id IS NULL
+RETURNING *;
+
+-- name: DeleteDocCommentThread :exec
+-- Deletes a comment; deleting a root takes its replies with it.
+DELETE FROM doc_comment
+WHERE workspace_id = @workspace_id AND doc_id = @doc_id
+ AND (id = @id OR parent_id = @id);
+
+-- name: ListDocThreadParticipants :many
+-- Members who wrote in a discussion: its root author and every reply author.
+SELECT DISTINCT author_id FROM doc_comment
+WHERE workspace_id = @workspace_id AND doc_id = @doc_id
+ AND (id = @root_id OR parent_id = @root_id)
+ AND author_type = 'member';
diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.go
index 8d7b9516f7..3b34707135 100644
--- a/server/pkg/protocol/events.go
+++ b/server/pkg/protocol/events.go
@@ -152,12 +152,15 @@ const (
// member: it exists so their other devices follow along.
EventIssueViewPreferenceChanged = "issue_view_preference:changed"
- EventDocCreated = "doc:created"
- EventDocUpdated = "doc:updated"
- EventDocDeleted = "doc:deleted"
- EventDocFolderCreated = "doc_folder:created"
- EventDocFolderUpdated = "doc_folder:updated"
- EventDocFolderDeleted = "doc_folder:deleted"
+ EventDocCreated = "doc:created"
+ EventDocUpdated = "doc:updated"
+ EventDocDeleted = "doc:deleted"
+ // A doc comment was added, resolved, reopened or deleted. Payload:
+ // doc_id, comment_id; clients refetch the doc's comments.
+ EventDocCommentChanged = "doc_comment:changed"
+ EventDocFolderCreated = "doc_folder:created"
+ EventDocFolderUpdated = "doc_folder:updated"
+ EventDocFolderDeleted = "doc_folder:deleted"
// Pin events
EventPinCreated = "pin:created"