Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(docs): add lightweight Docs with version history (MUL-8370) (#10176)
Bohan Jiang820594f2d3b4
diff --git a/apps/desktop/src/renderer/src/pages/doc-pages.tsx b/apps/desktop/src/renderer/src/pages/doc-pages.tsxnew file mode 100644index 0000000000..972da4a5d5--- /dev/null+++ b/apps/desktop/src/renderer/src/pages/doc-pages.tsx@@ -0,0 +1,11 @@+import { useParams } from "react-router-dom";+import { DocPage, DocHistoryPage, DocsHomePage } from "@multica/views/docs";+export function DocRoute() {+ return <DocPage docId={useParams().id ?? ""} />;+}+export function DocHistoryRoute() {+ return <DocHistoryPage docId={useParams().id ?? ""} />;+}+export function DocFolderRoute() {+ return <DocsHomePage folderId={useParams().id ?? ""} />;+}diff --git a/apps/desktop/src/renderer/src/routes.tsx b/apps/desktop/src/renderer/src/routes.tsxindex eaefe1378f..2f7e62c0a5 100644--- a/apps/desktop/src/renderer/src/routes.tsx+++ b/apps/desktop/src/renderer/src/routes.tsx@@ -1,3 +1,5 @@+import { DocsHomePage } from "@multica/views/docs";+import { DocRoute, DocHistoryRoute, DocFolderRoute } from "./pages/doc-pages";import { useEffect, useLayoutEffect } from "react";import { createMemoryRouter, Outlet, useLocation, useMatches } from "react-router-dom";import type { RouteObject } from "react-router-dom";@@ -209,6 +211,10 @@ export const appRoutes: RouteObject[] = [element: <RuntimeSettingsPage />,handle: { title: "Runtime" },},+ {path: "docs", element: <DocsHomePage />, handle: {title: "Docs"}},+ {path: "docs/folders/:id", element: <DocFolderRoute />, handle: {title: "Folder"}},+ {path: "docs/:id", element: <DocRoute />, handle: {title: "Doc"}},+ {path: "docs/:id/history", element: <DocHistoryRoute />, handle: {title: "History"}},{ path: "skills", element: <SkillsPage />, handle: { title: "Skills" } },{path: "skills/:id",diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/docs/[id]/history/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/docs/[id]/history/page.tsxnew file mode 100644index 0000000000..5a4d61f8cf--- /dev/null+++ b/apps/web/app/[workspaceSlug]/(dashboard)/docs/[id]/history/page.tsx@@ -0,0 +1,4 @@+"use client";+import { use } from "react";+import { DocHistoryPage } from "@multica/views/docs";+export default function DocHistoryRoute({params}: {params: Promise<{id: string}>}) { return <DocHistoryPage docId={use(params).id} />; }diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/docs/[id]/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/docs/[id]/page.tsxnew file mode 100644index 0000000000..0b90ce2f2f--- /dev/null+++ b/apps/web/app/[workspaceSlug]/(dashboard)/docs/[id]/page.tsx@@ -0,0 +1,4 @@+"use client";+import { use } from "react";+import { DocPage } from "@multica/views/docs";+export default function DocRoute({params}: {params: Promise<{id: string}>}) { return <DocPage docId={use(params).id} />; }diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/docs/folders/[id]/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/docs/folders/[id]/page.tsxnew file mode 100644index 0000000000..9d0d95c5fd--- /dev/null+++ b/apps/web/app/[workspaceSlug]/(dashboard)/docs/folders/[id]/page.tsx@@ -0,0 +1,4 @@+"use client";+import { use } from "react";+import { DocsHomePage } from "@multica/views/docs";+export default function FolderRoute({params}: {params: Promise<{id: string}>}) { return <DocsHomePage folderId={use(params).id} />; }diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/docs/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/docs/page.tsxnew file mode 100644index 0000000000..cf542b4fcb--- /dev/null+++ b/apps/web/app/[workspaceSlug]/(dashboard)/docs/page.tsx@@ -0,0 +1,3 @@+"use client";+import { DocsHomePage } from "@multica/views/docs";+export default function DocsRoute() { return <DocsHomePage />; }diff --git a/apps/web/config/google-analytics.ts b/apps/web/config/google-analytics.tsindex c16785b1e4..b838f478fb 100644--- a/apps/web/config/google-analytics.ts+++ b/apps/web/config/google-analytics.ts@@ -79,6 +79,7 @@ const WORKSPACE_SECTIONS = new Set(["autopilots","billing","chat",+ "docs","inbox","issues","members",diff --git a/e2e/docs.spec.ts b/e2e/docs.spec.tsnew file mode 100644index 0000000000..295c914f99--- /dev/null+++ b/e2e/docs.spec.ts@@ -0,0 +1,312 @@+import { test, expect, type FileChooser } from "@playwright/test";+import { TestApiClient } from "./fixtures";++let api: TestApiClient;+let slug: string;+test.beforeEach(async ({ page }) => {+ page.on("pageerror", (error) => {+ throw error;+ });+ api = new TestApiClient();+ const suffix = `${Date.now()}-${test.info().workerIndex}`;+ await api.login(`docs-${suffix}@multica.ai`, "Alex Morgan");+ const ws = await api.ensureWorkspace("Product team", `docs-${suffix}`);+ slug = ws.slug;+ await api.markUserOnboarded();+ await page.addInitScript((token) => {+ localStorage.setItem("multica_token", token!);+ localStorage.setItem("multica:chat:isOpen", "false");+ }, api.getToken());+ await page.setViewportSize({ width: 1440, height: 1000 });+});+test.afterEach(async () => {+ await api.cleanup();+ await api.deleteWorkspace();+});++test("Markdown autosave, folder move, immutable history and restore", async ({+ page,+}, info) => {+ const folder = await api.createDocFolder("Engineering");+ const original =+ "# Release checklist\n\nBefore each release, the owner verifies the following steps.\n\n## Before release\n\n- Run the tests\n- Review the migration plan\n- Confirm the rollback owner\n\n## After release\n\nCheck the health dashboard and write down the outcome.";+ const doc = await api.createDoc("Release runbook", original);+ await page.goto(`/${slug}/docs/${doc.id}`);+ const title = page.getByRole("textbox", { name: "Title", exact: true });+ await expect(title).toHaveValue("Release runbook");+ await title.fill("Release runbook — updated");+ await expect+ .poll(async () => (await api.getDoc(doc.id)).title)+ .toBe("Release runbook — updated");+ await page.getByRole("button", { name: "More", exact: true }).click();+ await page.getByRole("menuitem", { name: "Move to" }).click();+ await page.getByRole("option", { name: "Engineering", exact: true }).click();+ await page.getByRole("button", { name: "Move", exact: true }).click();+ await expect+ .poll(async () => (await api.getDoc(doc.id)).folder_id)+ .toBe(folder.id);+ await expect(page.getByRole("dialog")).toHaveCount(0);+ await page.screenshot({+ path: info.outputPath("docs-editor.png"),+ animations: "disabled",+ style: "nextjs-portal { display: none; }",+ });+ await page.getByRole("link", { name: "History", exact: true }).click();+ await page.getByRole("button", { name: /^v1 / }).click();+ await expect(+ page.getByRole("heading", { name: "Release runbook", exact: true }),+ ).toBeVisible();+ await page.screenshot({+ path: info.outputPath("docs-history.png"),+ animations: "disabled",+ style: "nextjs-portal { display: none; }",+ });+ await page.getByRole("button", { name: "Restore this version" }).click();+ await expect(title).toHaveValue("Release runbook");+ const restored = await api.getDoc(doc.id);+ expect(restored.content).toBe(original);+ expect(restored.version_count).toBe(3);+ await page.getByRole("button", { name: "More", exact: true }).click();+ await page.getByRole("menuitem", { name: "Delete", exact: true }).click();+ await expect(page.getByRole("alertdialog")).toBeVisible();+ await page.getByRole("button", { name: "Cancel", exact: true }).click();+ expect((await api.getDoc(doc.id)).title).toBe("Release runbook");+});++test("navigating to history saves the last title and Markdown before the debounce", async ({ page }) => {+ const doc = await api.createDoc("Quick edit", "Original");+ // Warm the destination so this checks leaving the editor, not route compilation.+ await page.goto(`/${slug}/docs/${doc.id}/history`);+ await expect(page.getByRole("button", { name: /^v1/ })).toBeVisible();+ await page.goto(`/${slug}/docs/${doc.id}`);+ const title = page.getByRole("textbox", { name: "Title", exact: true });+ const editor = page.locator('[contenteditable="true"]').first();+ await expect(title).toHaveValue("Quick edit");+ await expect(editor).toBeVisible();+ await page.clock.install({ time: new Date("2026-11-09T12:00:00Z") });+ await page.clock.pauseAt(new Date("2026-11-09T12:00:01Z"));++ const saving = page.waitForRequest((request) =>+ request.method() === "PATCH" && request.url().endsWith(`/api/docs/${doc.id}`),+ );+ await title.fill("Final title");+ await editor.fill("Last Markdown edit before leaving.");+ await page.getByRole("link", { name: "History", exact: true }).click();+ await expect(page).toHaveURL(new RegExp(`/${doc.id}/history$`));+ expect((await saving).postDataJSON()).toMatchObject({+ title: "Final title", content: "Last Markdown edit before leaving.", base_revision: 1,+ });+ await expect.poll(async () => api.getDoc(doc.id)).toMatchObject({+ title: "Final title", content: "Last Markdown edit before leaving.", revision: 2, version_count: 2,+ });+});++test("stale save keeps a draft across reload and lets the human load the latest", async ({+ page,+}, info) => {+ const doc = await api.createDoc("Design notes", "Original shared content");+ await page.goto(`/${slug}/docs/${doc.id}`);+ const title = page.getByRole("textbox", { name: "Title", exact: true });+ await expect(title).toHaveValue("Design notes");+ await title.fill("My unsaved title");+ await api.updateDoc(doc.id, 1, "A colleague's newer content");+ await expect(+ page.getByRole("alert").filter({ hasText: "Your draft is kept" }),+ ).toBeVisible();+ await page.reload();+ await expect(title).toHaveValue("My unsaved title");+ await expect(+ page.getByRole("alert").filter({ hasText: "Your draft is kept" }),+ ).toBeVisible();+ await page.screenshot({+ path: info.outputPath("docs-conflict.png"),+ animations: "disabled",+ style: "nextjs-portal { display: none; }",+ });+ await page.getByRole("button", { name: "Reload latest" }).click();+ await expect(title).toHaveValue("Design notes");+ await page.getByText("Your saved draft", { exact: true }).click();+ await expect(+ page.getByRole("textbox", { name: "Your saved draft" }),+ ).toHaveValue(/My unsaved title/);+ expect((await api.getDoc(doc.id)).content).toBe(+ "A colleague's newer content",+ );+});++test("create a nested doc, edit Markdown, and delete it with confirmation", async ({page}) => {+ await page.goto(`/${slug}/docs`);+ await page.getByRole("button", {name: "New", exact: true}).click();+ await page.getByRole("menuitem", {name: "New folder", exact: true}).click();+ await page.getByRole("dialog").getByRole("textbox", {name: "Title", exact: true}).fill("Product");+ await page.getByRole("dialog").getByRole("button", {name: "New", exact: true}).click();+ await page.getByRole("button", {name: "More actions for Product", exact: true}).click();+ await page.getByRole("menuitem", {name: "New doc", exact: true}).click();+ await expect(page).toHaveURL(/\/docs\/[0-9a-f-]{36}$/);+ await expect(page.getByRole("textbox", {name: "Title", exact: true})).toBeFocused();+ await page.keyboard.type("Architecture notes");+ const id = page.url().split("/").at(-1)!;+ const editor = page.locator('[contenteditable="true"]').first();+ await editor.fill("A shared architecture decision.");+ await expect.poll(async () => (await api.getDoc(id)).content).toContain("A shared architecture decision.");+ expect((await api.getDoc(id)).folder_id).not.toBeNull();+ await page.getByRole("button", {name: "More", exact: true}).click();+ await page.getByRole("menuitem", {name: "Delete", exact: true}).click();+ await page.getByRole("alertdialog").getByRole("button", {name: "Delete", exact: true}).click();+ await expect(page).toHaveURL(new RegExp(`/${slug}/docs$`));+ await expect(api.getDoc(id)).rejects.toThrow(/404/);+ await page.getByRole("button", {name: "More actions for Product", exact: true}).click();+ await page.getByRole("menuitem", {name: "Delete", exact: true}).click();+ await page.getByRole("alertdialog").getByRole("button", {name: "Delete", exact: true}).click();+ await expect(page.getByRole("button", {name: "More actions for Product", exact: true})).toHaveCount(0);+});++test("block menu, block handle and outline shape a document", async ({ page }, info) => {+ const doc = await api.createDoc(+ "Launch plan",+ "# Goals\n\nShip Docs.\n\n## Scope\n\n- Editor\n- Outline\n\n## Risks\n\nNone yet.",+ );+ // Registered up front: the file-chooser hook must be armed before the key+ // press that opens the picker, or the dialog slips past it.+ const choosers: FileChooser[] = [];+ page.on("filechooser", (chooser) => choosers.push(chooser));+ await page.goto(`/${slug}/docs/${doc.id}`);+ const content = async () => (await api.getDoc(doc.id)).content;+ await expect(page.getByRole("status").filter({ hasText: "Saved" })).toBeVisible();+ await expect(page.locator("time")).toHaveText(/^Edited /);++ const outline = page.getByRole("navigation", { name: "Outline" });+ await expect(outline.getByRole("button")).toHaveText(["Goals", "Scope", "Risks"]);++ // `/` opens the block menu; Enter inserts the highlighted block.+ // The chat composer is the second editor on the page.+ const editor = page.locator('.ProseMirror[contenteditable="true"]').first();+ // An instant synthetic click can land before ProseMirror reads the DOM+ // selection; retry until the editor's own selection is in the paragraph.+ await expect(async () => {+ await page.getByText("None yet.", { exact: true }).click();+ expect(+ await editor.evaluate(+ (dom) =>+ (dom as unknown as { editor: { state: { selection: { $from: { parent: { textContent: string } } } } } })+ .editor.state.selection.$from.parent.textContent,+ ),+ ).toBe("None yet.");+ }).toPass();+ await page.keyboard.press("End");+ await page.keyboard.press("Enter");+ await page.keyboard.type("/h2");+ await expect(page.getByRole("listbox", { name: "Insert block" })).toBeVisible();+ // Pausing past the autosave must keep the caret and the open menu.+ await expect.poll(content).toContain("/h2");+ await expect(page.getByRole("listbox", { name: "Insert block" })).toBeVisible();+ await page.keyboard.press("Enter");+ await page.keyboard.type("Timeline");+ await expect.poll(content).toContain("## Timeline");+ await expect(outline.getByRole("button")).toHaveText(["Goals", "Scope", "Risks", "Timeline"]);++ // The handle's grip opens turn-into. Glide to it like a person: the path+ // crosses the margin between the text and the handle.+ const line = (await page.getByText("Ship Docs.", { exact: true }).boundingBox())!;+ await page.mouse.move(line.x + line.width / 2, line.y + line.height - 2);+ const grip = page.getByRole("button", { name: "Drag to move, click for options" });+ const gripBox = (await grip.boundingBox())!;+ await page.mouse.move(gripBox.x + gripBox.width / 2, gripBox.y + gripBox.height / 2, {+ steps: 40,+ });+ await page.waitForTimeout(400);+ await expect(grip).toBeVisible();+ await page.mouse.down();+ await page.mouse.up();+ await expect(page.getByRole("group", { name: "Turn into" })).toBeVisible();+ await page.getByRole("menuitem", { name: "Quote", exact: true }).click();+ await expect.poll(content).toContain("> Ship Docs.");++ // Dragging the grip moves the block.+ await page.getByText("None yet.", { exact: true }).hover();+ await page+ .getByRole("button", { name: "Drag to move, click for options" })+ .dragTo(editor.getByRole("heading", { name: "Goals" }), {+ targetPosition: { x: 4, y: 2 },+ });+ await expect.poll(content).toMatch(/^None yet\.\n\n# Goals/);++ // "+" opens the menu on a new line; Image uploads through the file picker.+ await page.getByRole("heading", { name: "Timeline" }).hover();+ await page.getByRole("button", { name: "Add below" }).click();+ await expect(page.getByRole("listbox", { name: "Insert block" })).toBeVisible();+ await page.keyboard.type("image");+ await page.keyboard.press("Enter");+ await expect.poll(() => choosers.length).toBe(1);+ await choosers[0]!.setFiles({+ name: "diagram.png",+ mimeType: "image/png",+ buffer: Buffer.from(+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",+ "base64",+ ),+ });+ await expect.poll(content).toMatch(/!\[diagram\.png\]\([^)]*\/api\/attachments\/[0-9a-f-]{36}\/download\)/);++ await page.mouse.move(0, 0);+ await page.screenshot({+ path: info.outputPath("docs-blocks.png"),+ animations: "disabled",+ style: "nextjs-portal { display: none; }",+ });+});++test("docs link from issues, show up in Cmd+K, and reorganize from the tree", async ({+ page,+}, info) => {+ const folder = await api.createDocFolder("Engineering");+ const doc = await api.createDoc("Release runbook", "Steps for every release.");+ const issue = await api.createIssue("Ship the release", {+ description: `See [Release runbook](mention://doc/${doc.id}).`,+ });++ // A doc mention renders as a chip that opens the doc.+ await page.goto(`/${slug}/issues/${issue.id}`);+ const chip = page.locator("a.doc-mention").filter({ hasText: "Release runbook" }).first();+ await expect(chip).toHaveAttribute("href", new RegExp(`/${slug}/docs/${doc.id}$`));++ // `@` offers docs in their own section.+ await expect(page.locator("text=Properties")).toBeVisible();+ const composer = page+ .locator('.ProseMirror[data-placeholder="Leave a comment..."], .ProseMirror:has([data-placeholder="Leave a comment..."])')+ .first();+ await expect(async () => {+ await page.getByTestId("comment-composer-shell").click({ timeout: 2000 });+ await composer.click({ force: true, timeout: 2000 });+ }).toPass();+ await page.keyboard.type("@runbook");+ await page.getByRole("button", { name: "Release runbook" }).click();+ await page.keyboard.press("ControlOrMeta+Enter");+ await expect(page.locator("a.doc-mention")).toHaveCount(2);+ await page.screenshot({ path: info.outputPath("docs-mention.png"), animations: "disabled", style: "nextjs-portal { display: none; }" });++ // Cmd+K finds the doc by title.+ await page.getByRole("button", { name: "Search..." }).click();+ await page.getByRole("combobox", { name: "Command bar" }).fill("runbook");+ await page.getByRole("group", { name: "Docs" }).getByRole("option", { name: /Release runbook/ }).click();+ await expect(page).toHaveURL(new RegExp(`/docs/${doc.id}$`));++ // Drag the doc onto the folder in the tree.+ await page+ .getByRole("link", { name: "Release runbook", exact: true })+ .dragTo(page.getByText("Engineering", { exact: true }));+ await expect.poll(async () => (await api.getDoc(doc.id)).folder_id).toBe(folder.id);++ // The folder's "+" opens a new untitled doc inside it, caret in the title.+ await page.getByRole("complementary").getByText("Engineering", { exact: true }).hover();+ await page.getByRole("button", { name: "New doc in Engineering" }).click();+ await expect(page).not.toHaveURL(new RegExp(doc.id));+ await expect(page).toHaveURL(/\/docs\/[0-9a-f-]{36}$/);+ const created = page.url().split("/").at(-1)!;+ const title = page.getByRole("textbox", { name: "Title", exact: true });+ await expect(title).toBeFocused();+ await page.keyboard.type("On-call handbook");+ await expect.poll(async () => (await api.getDoc(created)).title).toBe("On-call handbook");+ expect((await api.getDoc(created)).folder_id).toBe(folder.id);+ await page.screenshot({ path: info.outputPath("docs-tree.png"), animations: "disabled", style: "nextjs-portal { display: none; }" });+});diff --git a/e2e/fixtures.ts b/e2e/fixtures.tsindex c558b74297..425ceab2d1 100644--- a/e2e/fixtures.ts+++ b/e2e/fixtures.ts@@ -52,6 +52,8 @@ export class TestApiClient {private email: string | null = null;private createdIssueIds: string[] = [];private createdProjectIds: string[] = [];+ private createdDocIds: string[] = [];+ private createdDocFolderIds: string[] = [];private seededIssueIds: string[] = [];private createdPropertyIds: string[] = [];@@ -186,6 +188,28 @@ export class TestApiClient {}}+ async createDoc(title: string, content: string, folderId?: string) {+ const res = await this.authedFetch("/api/docs", {method: "POST", body: JSON.stringify({title, content, folder_id: folderId})});+ if (!res.ok) throw new Error(`create doc: ${res.status} ${await res.text()}`);+ const doc = await res.json() as {id: string; revision: number; title: string; content: string};+ this.createdDocIds.push(doc.id); return doc;+ }+ async getDoc(id: string) {+ const res = await this.authedFetch(`/api/docs/${id}`);+ if (!res.ok) throw new Error(`get doc: ${res.status}`);+ return await res.json() as {id: string; revision: number; title: string; content: string; folder_id: string | null; version_count: number};+ }+ async updateDoc(id: string, base: number, content: string) {+ const res = await this.authedFetch(`/api/docs/${id}`, {method: "PATCH", body: JSON.stringify({base_revision: base, content})});+ if (!res.ok) throw new Error(`update doc: ${res.status} ${await res.text()}`);+ return await res.json() as {revision: number};+ }+ async createDocFolder(title: string) {+ const res = await this.authedFetch("/api/doc-folders", {method: "POST", body: JSON.stringify({title})});+ if (!res.ok) throw new Error(`create folder: ${res.status}`);+ const folder = await res.json() as {id: string}; this.createdDocFolderIds.push(folder.id); return folder;+ }+/** Create a project and register it for cleanup. */async createProject(title: string, opts?: Record<string, unknown>) {const res = await this.authedFetch("/api/projects", {@@ -451,6 +475,11 @@ export class TestApiClient {/** Clean up all issues created during this test. */async cleanup() {+ for (const id of this.createdDocIds) await this.authedFetch(`/api/docs/${id}`, {method: "DELETE"});+ this.createdDocIds = [];+ for (const id of this.createdDocFolderIds.reverse()) await this.authedFetch(`/api/doc-folders/${id}`, {method: "DELETE"});+ this.createdDocFolderIds = [];+if (this.seededIssueIds.length > 0 && this.workspaceId) {const client = new pg.Client(DATABASE_URL);await client.connect();diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 990508c00f..1ab8e68523 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -1,5 +1,23 @@import type { ListWeixinInstallationsResponse, WeixinLogin } from "../types/weixin";import { ListWeixinInstallationsSchema, WeixinLoginSchema, EMPTY_WEIXIN_INSTALLATIONS, INVALID_WEIXIN_LOGIN } from "../weixin/schema";+import {+ DocSchema,+ DocSummarySchema,+ DocFolderSchema,+ DocTreeSchema,+ DocVersionSchema,+ DocVersionListSchema,+} from "../docs/schemas";+import type {+ Doc,+ DocSummary,+ DocFolder,+ DocTree,+ DocVersion,+ CreateDocRequest,+ UpdateDocRequest,+ CreateDocFolderRequest,+} from "../types/doc";import type { ZodType } from "zod";import { AgentRuntimeSchema, EMPTY_RUNTIME } from "../runtimes/schema";import type { IssueWakeup, IssueWakeupInput, IssueWakeupSummaryRow, PausedWakeup, SystemWakeup, WakeupRun, WorkspaceSystemWakeup } from "../types/issue-wakeup";@@ -893,6 +911,116 @@ function isReplayableBody(body: BodyInit | null | undefined): boolean {}export class ApiClient {+ private parseDoc(raw: unknown, endpoint: string): Doc {+ const doc = parseWithFallback<Doc | null>(raw, DocSchema, null, {+ endpoint,+ });+ if (!doc) throw new Error(`Malformed response from ${endpoint}`);+ return doc;+ }+ async listDocTree(): Promise<DocTree> {+ return parseWithFallback(+ await this.fetch<unknown>("/api/docs"),+ DocTreeSchema,+ { folders: [], docs: [] },+ { endpoint: "GET /api/docs" },+ );+ }+ async getDoc(id: string): Promise<Doc> {+ return this.parseDoc(+ await this.fetch<unknown>(`/api/docs/${id}`),+ "GET /api/docs/{id}",+ );+ }+ async createDoc({ folderId, ...data }: CreateDocRequest): Promise<Doc> {+ return this.parseDoc(+ await this.fetch<unknown>("/api/docs", {+ method: "POST",+ body: JSON.stringify({ ...data, folder_id: folderId }),+ }),+ "POST /api/docs",+ );+ }+ async updateDoc(+ id: string,+ { baseRevision, actionRef, ...data }: UpdateDocRequest,+ ): Promise<Doc> {+ return this.parseDoc(+ await this.fetch<unknown>(`/api/docs/${id}`, {+ method: "PATCH",+ body: JSON.stringify({+ ...data,+ base_revision: baseRevision,+ action_ref: actionRef,+ }),+ }),+ "PATCH /api/docs/{id}",+ );+ }+ async moveDoc(id: string, folderId: string | null): Promise<DocSummary> {+ const raw = await this.fetch<unknown>(`/api/docs/${id}/move`, {+ method: "POST",+ body: JSON.stringify({ folder_id: folderId }),+ });+ const doc = parseWithFallback<DocSummary | null>(+ raw,+ DocSummarySchema,+ null,+ { endpoint: "POST /api/docs/{id}/move" },+ );+ if (!doc) throw new Error("Malformed document response");+ return doc;+ }+ async deleteDoc(id: string): Promise<void> {+ await this.fetch(`/api/docs/${id}`, { method: "DELETE" });+ }+ async listDocVersions(id: string): Promise<DocVersion[]> {+ return parseWithFallback(+ await this.fetch<unknown>(`/api/docs/${id}/versions`),+ DocVersionListSchema,+ { versions: [] },+ { endpoint: "GET /api/docs/{id}/versions" },+ ).versions;+ }+ async getDocVersion(id: string, number: number): Promise<DocVersion | null> {+ return parseWithFallback<DocVersion | null>(+ await this.fetch<unknown>(`/api/docs/${id}/versions/${number}`),+ DocVersionSchema,+ null,+ { endpoint: "GET /api/docs/{id}/versions/{number}" },+ );+ }+ private async writeDocFolder(+ path: string,+ method: string,+ data: unknown,+ ): Promise<DocFolder> {+ const folder = parseWithFallback<DocFolder | null>(+ await this.fetch<unknown>(path, { method, body: JSON.stringify(data) }),+ DocFolderSchema,+ null,+ { endpoint: `${method} ${path}` },+ );+ if (!folder) throw new Error("Malformed folder response");+ return folder;+ }+ createDocFolder({ parentId, title }: CreateDocFolderRequest) {+ return this.writeDocFolder("/api/doc-folders", "POST", {+ parent_id: parentId,+ title,+ });+ }+ renameDocFolder(id: string, title: string) {+ return this.writeDocFolder(`/api/doc-folders/${id}`, "PATCH", { title });+ }+ moveDocFolder(id: string, parentId: string | null) {+ return this.writeDocFolder(`/api/doc-folders/${id}/move`, "POST", {+ parent_id: parentId,+ });+ }+ async deleteDocFolder(id: string): Promise<void> {+ await this.fetch(`/api/doc-folders/${id}`, { method: "DELETE" });+ }private baseUrl: string;private token: string | null = null;private logger: Logger;diff --git a/packages/core/diagnostics/diagnostic-context.ts b/packages/core/diagnostics/diagnostic-context.tsindex ad3cd43453..ddd84e03d7 100644--- a/packages/core/diagnostics/diagnostic-context.ts+++ b/packages/core/diagnostics/diagnostic-context.ts@@ -79,6 +79,10 @@ const WORKSPACE_ROUTES: readonly RoutePattern[] = [["runtimes"],["runtimes", ":id"],["runtimes", ":id", "runtime", ":runtimeId"],+ ["docs"],+ ["docs", ":id"],+ ["docs", ":id", "history"],+ ["docs", "folders", ":id"],["skills"],["skills", ":id"],["settings"],diff --git a/packages/core/docs/client.test.ts b/packages/core/docs/client.test.tsnew file mode 100644index 0000000000..6439972bd2--- /dev/null+++ b/packages/core/docs/client.test.ts@@ -0,0 +1,103 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { ApiClient, ApiError } from "../api/client";+import { isDocRevisionConflict } from "./queries";++afterEach(() => {+ vi.unstubAllGlobals();+});++function respond(body: unknown, status = 200) {+ const fetchMock = vi+ .fn()+ .mockResolvedValue(+ new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" },+ }),+ );+ vi.stubGlobal("fetch", fetchMock);+ return fetchMock;+}++const validDoc = {+ id: "d1",+ workspace_id: "ws",+ folder_id: null,+ title: "Runbook",+ revision: 4,+ version_count: 2,+ created_by_type: "member",+ created_by_id: "u1",+ updated_by_type: "agent",+ updated_by_id: "a1",+ created_at: "2026-10-29T10:00:00Z",+ updated_at: "2026-10-29T11:00:00Z",+ content: "# Runbook",+};++describe("knowledge base client", () => {+ it("parses a doc and tolerates unknown enum values", async () => {+ respond({+ ...validDoc,+ format: "pdf",+ updated_by_type: "robot",+ extra: true,+ });+ const doc = await new ApiClient("https://api.example.test").getDoc("d1");+ expect(doc).toMatchObject({+ id: "d1",+ revision: 4,+ updatedByType: "member",+ workspaceId: "ws",+ });+ });++ it("rejects a response missing content or a valid revision", async () => {+ const client = new ApiClient("https://api.example.test");+ respond({...validDoc, content: undefined});+ await expect(client.getDoc("d1")).rejects.toThrow(/Malformed response/);+ respond({...validDoc, revision: 0});+ await expect(client.getDoc("d1")).rejects.toThrow(/Malformed response/);+ });++ it("rejects a malformed doc instead of handing the editor an empty body", async () => {+ respond({ id: "d1", content: 42 });+ await expect(+ new ApiClient("https://api.example.test").getDoc("d1"),+ ).rejects.toThrow(/Malformed response/);+ });++ it("falls back to an empty tree and versions on malformed responses", async () => {+ const client = new ApiClient("https://api.example.test");+ respond({ folders: "nope" });+ expect(await client.listDocTree()).toEqual({ folders: [], docs: [] });+ respond({ versions: [{ number: "x" }] });+ expect(await client.listDocVersions("d1")).toEqual([]);+ });++ it("sends the base revision and surfaces a stale write as a revision conflict", async () => {+ const fetchMock = respond(+ {+ error: "resource changed since it was loaded",+ code: "revision_conflict",+ expected_revision: 3,+ actual_revision: 4,+ },+ 409,+ );+ const error = await new ApiClient("https://api.example.test")+ .updateDoc("d1", { baseRevision: 3, content: "x" })+ .catch((e: unknown) => e);+ expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toEqual({+ base_revision: 3,+ content: "x",+ });+ expect(error).toBeInstanceOf(ApiError);+ expect(isDocRevisionConflict(error)).toBe(true);+ expect(+ isDocRevisionConflict(+ new ApiError("x", 409, "Conflict", { code: "folder_not_empty" }),+ ),+ ).toBe(false);+ });+});diff --git a/packages/core/docs/draft-store.ts b/packages/core/docs/draft-store.tsnew file mode 100644index 0000000000..1879994814--- /dev/null+++ b/packages/core/docs/draft-store.ts@@ -0,0 +1,26 @@+import { createDraftStore } from "../drafts";+export interface DocDraft {+ title: string;+ content: string;+ baseRevision: number;+ baseTitle: string;+ baseContent: string;+ backup?: { title: string; content: string };+}+export const useDocDraftStore = createDraftStore<{+ entries: Record<string, DocDraft>;+}>({+ storageKey: "doc-drafts",+ emptyData: { entries: {} },+ hasMeaningful: (d) => Object.keys(d.entries).length > 0,+});+export function setDocDraft(id: string, draft: DocDraft) {+ const state = useDocDraftStore.getState();+ state.setDraft({ entries: { ...state.draft.entries, [id]: draft } });+}+export function removeDocDraft(id: string) {+ const state = useDocDraftStore.getState();+ const entries = { ...state.draft.entries };+ delete entries[id];+ state.setDraft({ entries });+}diff --git a/packages/core/docs/index.ts b/packages/core/docs/index.tsnew file mode 100644index 0000000000..1c3a298664--- /dev/null+++ b/packages/core/docs/index.ts@@ -0,0 +1,4 @@+export * from "./queries";+export * from "./mutations";+export * from "./tree";+export * from "./draft-store";diff --git a/packages/core/docs/mutations.ts b/packages/core/docs/mutations.tsnew file mode 100644index 0000000000..49dca2af12--- /dev/null+++ b/packages/core/docs/mutations.ts@@ -0,0 +1,132 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { api } from "../api";+import { useWorkspaceId } from "../hooks";+import type {+ CreateDocFolderRequest,+ CreateDocRequest,+ Doc,+ DocTree,+ UpdateDocRequest,+} from "../types";+import { docKeys } from "./queries";++function useDocTreeCache() {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();+ const update = (fn: (tree: DocTree) => DocTree) =>+ qc.setQueryData<DocTree>(docKeys.tree(wsId), (old) =>+ old ? fn(old) : old,+ );+ return { qc, wsId, update };+}++export function useCreateDoc() {+ const { qc, wsId, update } = useDocTreeCache();+ return useMutation({+ mutationFn: (data: CreateDocRequest) => api.createDoc(data),+ onSuccess: (doc) => {+ qc.invalidateQueries({ queryKey: docKeys.all(wsId) });+ qc.setQueryData(docKeys.detail(wsId, doc.id), doc);+ update((tree) => ({+ ...tree,+ docs: [...tree.docs.filter((d) => d.id !== doc.id), doc],+ }));+ },+ });+}++export function useUpdateDoc() {+ const { qc, wsId, update } = useDocTreeCache();+ return useMutation({+ mutationFn: ({ id, ...data }: { id: string } & UpdateDocRequest) =>+ api.updateDoc(id, data),+ onSuccess: (doc) => {+ qc.invalidateQueries({ queryKey: docKeys.all(wsId) });+ qc.setQueryData<Doc>(docKeys.detail(wsId, doc.id), doc);+ update((tree) => ({+ ...tree,+ docs: tree.docs.map((d) => (d.id === doc.id ? { ...d, ...doc } : d)),+ }));+ },+ });+}++export function useMoveDoc() {+ const { qc, wsId } = useDocTreeCache();+ return useMutation({+ onSuccess: () => {+ qc.invalidateQueries({ queryKey: docKeys.all(wsId) });+ },+ mutationFn: ({ id, folderId }: { id: string; folderId: string | null }) =>+ api.moveDoc(id, folderId),+ });+}++export function useDeleteDoc() {+ const { qc, wsId, update } = useDocTreeCache();+ return useMutation({+ mutationFn: (id: string) => api.deleteDoc(id),+ onSuccess: (_data, id) => {+ qc.invalidateQueries({ queryKey: docKeys.all(wsId) });+ update((tree) => ({+ ...tree,+ docs: tree.docs.filter((d) => d.id !== id),+ }));+ qc.removeQueries({ queryKey: docKeys.detail(wsId, id) });+ },+ });+}++export function useCreateDocFolder() {+ const { qc, wsId, update } = useDocTreeCache();+ return useMutation({+ mutationFn: (data: CreateDocFolderRequest) => api.createDocFolder(data),+ onSuccess: (folder) => {+ qc.invalidateQueries({ queryKey: docKeys.all(wsId) });+ update((tree) => ({+ ...tree,+ folders: [...tree.folders.filter((f) => f.id !== folder.id), folder],+ }));+ },+ });+}++export function useRenameDocFolder() {+ const { qc, wsId, update } = useDocTreeCache();+ return useMutation({+ mutationFn: ({ id, title }: { id: string; title: string }) =>+ api.renameDocFolder(id, title),+ onSuccess: (folder) => {+ qc.invalidateQueries({ queryKey: docKeys.all(wsId) });+ update((tree) => ({+ ...tree,+ folders: tree.folders.map((f) => (f.id === folder.id ? folder : f)),+ }));+ },+ });+}++export function useMoveDocFolder() {+ const { qc, wsId } = useDocTreeCache();+ return useMutation({+ onSuccess: () => {+ qc.invalidateQueries({ queryKey: docKeys.all(wsId) });+ },+ mutationFn: ({ id, parentId }: { id: string; parentId: string | null }) =>+ api.moveDocFolder(id, parentId),+ });+}++export function useDeleteDocFolder() {+ const { qc, wsId, update } = useDocTreeCache();+ return useMutation({+ mutationFn: (id: string) => api.deleteDocFolder(id),+ onSuccess: (_data, id) => {+ qc.invalidateQueries({ queryKey: docKeys.all(wsId) });+ update((tree) => ({+ ...tree,+ folders: tree.folders.filter((f) => f.id !== id),+ }));+ },+ });+}diff --git a/packages/core/docs/queries.ts b/packages/core/docs/queries.tsnew file mode 100644index 0000000000..e9f7abc779--- /dev/null+++ b/packages/core/docs/queries.ts@@ -0,0 +1,49 @@+import { queryOptions } from "@tanstack/react-query";+import { api, ApiError } from "../api";++export const docKeys = {+ all: (wsId: string) => ["docs", wsId] as const,+ tree: (wsId: string) => [...docKeys.all(wsId), "tree"] as const,+ detail: (wsId: string, id: string) =>+ [...docKeys.all(wsId), "detail", id] as const,+ versions: (wsId: string, id: string) =>+ [...docKeys.all(wsId), "versions", id] as const,+ version: (wsId: string, id: string, number: number) =>+ [...docKeys.all(wsId), "version", id, number] as const,+};++export function docTreeOptions(wsId: string) {+ return queryOptions({+ queryKey: docKeys.tree(wsId),+ queryFn: () => api.listDocTree(),+ staleTime: 30_000,+ });+}++export function docDetailOptions(wsId: string, id: string) {+ return queryOptions({+ queryKey: docKeys.detail(wsId, id),+ queryFn: () => api.getDoc(id),+ });+}++export function docVersionsOptions(wsId: string, id: string) {+ return queryOptions({+ queryKey: docKeys.versions(wsId, id),+ queryFn: () => api.listDocVersions(id),+ });+}++export function docVersionOptions(wsId: string, id: string, number: number) {+ return queryOptions({+ queryKey: docKeys.version(wsId, id, number),+ queryFn: () => api.getDocVersion(id, number),+ staleTime: Infinity,+ });+}++export function isDocRevisionConflict(error: unknown): boolean {+ if (!(error instanceof ApiError) || error.status !== 409) return false;+ const body = error.body as { code?: unknown } | undefined;+ return body?.code === "revision_conflict";+}diff --git a/packages/core/docs/schemas.ts b/packages/core/docs/schemas.tsnew file mode 100644index 0000000000..4d886a4ae0--- /dev/null+++ b/packages/core/docs/schemas.ts@@ -0,0 +1,96 @@+import { z } from "zod";+const actor = z.enum(["member", "agent"]).catch("member");+const summary = z.object({+ id: z.string().min(1),+ workspace_id: z.string(),+ folder_id: z.string().nullable(),+ title: z.string(),+ revision: z.number().int().positive(),+ version_count: z.number().int().positive(),+ created_by_type: actor,+ created_by_id: z.string(),+ updated_by_type: actor,+ updated_by_id: z.string(),+ created_at: z.string(),+ updated_at: z.string(),+});+function mapSummary(d: z.infer<typeof summary>) {+ return {+ id: d.id,+ workspaceId: d.workspace_id,+ folderId: d.folder_id,+ title: d.title,+ revision: d.revision,+ versionCount: d.version_count,+ createdByType: d.created_by_type,+ createdById: d.created_by_id,+ updatedByType: d.updated_by_type,+ updatedById: d.updated_by_id,+ createdAt: d.created_at,+ updatedAt: d.updated_at,+ };+}+export const DocSummarySchema = summary.transform(mapSummary);+// Never default missing content or revision: a malformed fetch must not erase a doc on autosave.+export const DocSchema = summary+ .extend({ content: z.string() })+ .transform((d) => ({ ...mapSummary(d), content: d.content }));+export const DocFolderSchema = z+ .object({+ id: z.string().min(1),+ workspace_id: z.string(),+ parent_id: z.string().nullable(),+ title: z.string(),+ created_by_type: actor,+ created_by_id: z.string(),+ created_at: z.string(),+ updated_at: z.string(),+ })+ .transform((d) => ({+ id: d.id,+ workspaceId: d.workspace_id,+ parentId: d.parent_id,+ title: d.title,+ createdByType: d.created_by_type,+ createdById: d.created_by_id,+ createdAt: d.created_at,+ updatedAt: d.updated_at,+ }));+export const DocTreeSchema = z.object({+ folders: z.array(DocFolderSchema),+ docs: z.array(DocSummarySchema),+});+export const DocVersionSchema = z+ .object({+ doc_id: z.string(),+ number: z.number().int().positive(),+ title: z.string(),+ author_type: actor,+ author_id: z.string(),+ message: z.string().default(""),+ action: z.enum(["create", "edit", "restore"]).catch("edit"),+ action_ref: z.number().nullable().default(null),+ task_id: z.string().nullable().default(null),+ issue_id: z.string().nullable().default(null),+ created_at: z.string(),+ updated_at: z.string(),+ content: z.string().optional(),+ })+ .transform((d) => ({+ docId: d.doc_id,+ number: d.number,+ title: d.title,+ authorType: d.author_type,+ authorId: d.author_id,+ message: d.message,+ action: d.action,+ actionRef: d.action_ref,+ taskId: d.task_id,+ issueId: d.issue_id,+ createdAt: d.created_at,+ updatedAt: d.updated_at,+ content: d.content,+ }));+export const DocVersionListSchema = z.object({+ versions: z.array(DocVersionSchema),+});diff --git a/packages/core/docs/tree.test.ts b/packages/core/docs/tree.test.tsnew file mode 100644index 0000000000..1aca135fa5--- /dev/null+++ b/packages/core/docs/tree.test.ts@@ -0,0 +1,28 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import { canMoveFolder, folderAncestry } from "./tree";+import type { DocFolder } from "../types";+const folder = (id: string, parentId: string | null): DocFolder => ({+ id,+ parentId,+ title: id,+ workspaceId: "ws",+ createdByType: "member",+ createdById: "m",+ createdAt: "",+ updatedAt: "",+});+describe("doc folder moves", () => {+ const folders = [folder("a", null), folder("b", "a"), folder("c", "b")];+ it("rejects self and descendants, permits root and ancestors", () => {+ expect(canMoveFolder(folders, "a", "a")).toBe(false);+ expect(canMoveFolder(folders, "a", "c")).toBe(false);+ expect(canMoveFolder(folders, "c", "a")).toBe(true);+ expect(canMoveFolder(folders, "b", null)).toBe(true);+ expect(folderAncestry(folders, "c").map((f) => f.id)).toEqual([+ "a",+ "b",+ "c",+ ]);+ });+});diff --git a/packages/core/docs/tree.ts b/packages/core/docs/tree.tsnew file mode 100644index 0000000000..bc8733bddf--- /dev/null+++ b/packages/core/docs/tree.ts@@ -0,0 +1,26 @@+import type { DocFolder } from "../types";++/** Folders from the root down to `folderId` (inclusive). */+export function folderAncestry(+ folders: readonly DocFolder[],+ folderId: string | null,+): DocFolder[] {+ const byId = new Map(folders.map((f) => [f.id, f]));+ const chain: DocFolder[] = [];+ let cur = folderId ? byId.get(folderId) : undefined;+ while (cur && chain.length <= folders.length) {+ chain.unshift(cur);+ cur = cur.parentId ? byId.get(cur.parentId) : undefined;+ }+ return chain;+}++/** Whether `folderId` may move under `parentId` without becoming its own ancestor. */+export function canMoveFolder(+ folders: readonly DocFolder[],+ folderId: string,+ parentId: string | null,+): boolean {+ if (parentId === null) return true;+ return !folderAncestry(folders, parentId).some((f) => f.id === folderId);+}diff --git a/packages/core/drafts/register-all-drafts.ts b/packages/core/drafts/register-all-drafts.tsindex 1f7e399d6c..0d3106f622 100644--- a/packages/core/drafts/register-all-drafts.ts+++ b/packages/core/drafts/register-all-drafts.ts@@ -20,6 +20,7 @@ import "../issues/stores/comment-draft-store";import "../projects/draft-store";import "../feedback/draft-store";import "../agents/manual-draft-store";+import "../docs/draft-store";import { registerDraftCleanup } from "./cleanup-registry";// Retired: drafts for a running turn now live in the thread's reply draft.diff --git a/packages/core/navigation/rail-order-store.test.ts b/packages/core/navigation/rail-order-store.test.tsindex 78d429e85d..192a5338ba 100644--- a/packages/core/navigation/rail-order-store.test.ts+++ b/packages/core/navigation/rail-order-store.test.ts@@ -1,3 +1,4 @@+// @vitest-environment nodeimport { beforeEach, describe, expect, it } from "vitest";import { RAIL_SPACES } from "../paths/spaces";import { resolveRailOrder, useRailOrderStore } from "./rail-order-store";@@ -7,27 +8,36 @@ describe("resolveRailOrder", () => {expect(resolveRailOrder(null)).toEqual(RAIL_SPACES);});+ it("inserts Docs into a saved layout from before Docs existed", () => {+ expect(+ resolveRailOrder(["chat", "inbox", "work", "team", "autopilots"]),+ ).toEqual(["chat", "work", "docs", "team", "autopilots"]);+ });+it("keeps a saved order", () => {- const saved = ["chat", "work", "team", "autopilots"];+ const saved = ["chat", "work", "docs", "team", "autopilots"];expect(resolveRailOrder(saved)).toEqual(saved);});it("drops unknown and repeated ids", () => {- expect(resolveRailOrder(["chat", "settings", 3, "chat", "work", "team", "autopilots"])).toEqual([- "chat",- "work",- "team",- "autopilots",- ]);+ expect(+ resolveRailOrder([+ "chat",+ "settings",+ 3,+ "chat",+ "work",+ "docs",+ "team",+ "autopilots",+ ]),+ ).toEqual(["chat", "work", "docs", "team", "autopilots"]);});it("drops the retired Inbox space from an order saved before it moved into Work", () => {- expect(resolveRailOrder(["chat", "inbox", "work", "team", "autopilots"])).toEqual([- "chat",- "work",- "team",- "autopilots",- ]);+ expect(+ resolveRailOrder(["chat", "inbox", "work", "docs", "team", "autopilots"]),+ ).toEqual(["chat", "work", "docs", "team", "autopilots"]);});it("puts a space missing from the saved order after its default neighbour", () => {@@ -35,10 +45,12 @@ describe("resolveRailOrder", () => {"chat","autopilots","work",+ "docs","team",]);expect(resolveRailOrder(["chat", "team", "autopilots"])).toEqual(["work",+ "docs","chat","team","autopilots",@@ -52,13 +64,15 @@ describe("useRailOrderStore", () => {});it("saves a custom order", () => {- const order = ["chat", "work", "team", "autopilots"] as const;+ const order = ["chat", "work", "docs", "team", "autopilots"] as const;useRailOrderStore.getState().setOrder(order);expect(useRailOrderStore.getState().order).toEqual(order);});it("forgets the order once it is back to the default", () => {- useRailOrderStore.getState().setOrder(["team", "work", "chat", "autopilots"]);+ useRailOrderStore+ .getState()+ .setOrder(["team", "work", "docs", "chat", "autopilots"]);useRailOrderStore.getState().setOrder(RAIL_SPACES);expect(useRailOrderStore.getState().order).toBeNull();});diff --git a/packages/core/package.json b/packages/core/package.jsonindex 8a0f4e2130..36bf4a5180 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -211,7 +211,8 @@"./skills/pack-archive": "./skills/pack-archive.ts","./skills/stores": "./skills/stores/index.ts","./autopilots/stores": "./autopilots/stores/index.ts",- "./runtimes/qoder": "./runtimes/qoder.ts"+ "./runtimes/qoder": "./runtimes/qoder.ts",+ "./docs": "./docs/index.ts"},"dependencies": {"@formatjs/intl-localematcher": "catalog:",diff --git a/packages/core/paths/paths.ts b/packages/core/paths/paths.tsindex 991cdcbb28..9a8dd63c98 100644--- a/packages/core/paths/paths.ts+++ b/packages/core/paths/paths.ts@@ -85,6 +85,10 @@ function workspaceScoped(slug: string) {runtimeDetail: (id: string) => `${ws}/runtimes/${encode(id)}`,runtimeSettings: (machineId: string, runtimeId: string) =>`${ws}/runtimes/${encode(machineId)}/runtime/${encode(runtimeId)}`,+ docs: () => `${ws}/docs`,+ docDetail: (id: string) => `${ws}/docs/${encode(id)}`,+ docHistory: (id: string) => `${ws}/docs/${encode(id)}/history`,+ docFolder: (id: string) => `${ws}/docs/folders/${encode(id)}`,skills: () => `${ws}/skills`,skillDetail: (id: string) => `${ws}/skills/${encode(id)}`,settings: () => `${ws}/settings`,diff --git a/packages/core/paths/route-icons.ts b/packages/core/paths/route-icons.tsindex f63206127f..7e8d028963 100644--- a/packages/core/paths/route-icons.ts+++ b/packages/core/paths/route-icons.ts@@ -56,6 +56,7 @@ export type NavLabelKey =| "squads"| "usage"| "runtimes"+ | "docs"| "skills"| "settings";@@ -72,6 +73,7 @@ export type WorkspacePageKey =| "squads"| "usage"| "runtimes"+ | "docs"| "skills"| "settings";@@ -100,6 +102,7 @@ export const WORKSPACE_PAGES: Record<WorkspacePageKey, WorkspacePage> = {squads: { segment: "squads", icon: "Users", navKey: "squads" },usage: { segment: "usage", icon: "BarChart3", navKey: "usage" },runtimes: { segment: "runtimes", icon: "Monitor", navKey: "runtimes" },+ docs: { segment: "docs", icon: "FileText", navKey: "docs" },skills: { segment: "skills", icon: "BookOpenText", navKey: "skills" },settings: { segment: "settings", icon: "Settings", navKey: "settings" },};diff --git a/packages/core/paths/spaces.ts b/packages/core/paths/spaces.tsindex dca772b033..dada61af7b 100644--- a/packages/core/paths/spaces.ts+++ b/packages/core/paths/spaces.ts@@ -8,6 +8,7 @@export type AppSpaceId =| "work"+ | "docs"| "team"| "chat"| "autopilots"@@ -19,6 +20,7 @@ export type RailSpaceId = Exclude<AppSpaceId, "settings">;/** Spaces in rail order. */export const RAIL_SPACES: readonly RailSpaceId[] = ["work",+ "docs","team","chat","autopilots",@@ -35,6 +37,7 @@ const SPACE_BY_SEGMENT: Record<string, AppSpaceId> = {squads: "team",members: "team",skills: "team",+ docs: "docs",runtimes: "team",usage: "team",chat: "chat",diff --git a/packages/core/paths/tab-presentation.ts b/packages/core/paths/tab-presentation.tsindex fc1aab3f47..b8464a40ff 100644--- a/packages/core/paths/tab-presentation.ts+++ b/packages/core/paths/tab-presentation.ts@@ -46,6 +46,8 @@ export type TabLabelKey =| "agent"| "member"| "squad"+ | "doc"+ | "docFolder"| "skill"| "machine"| "runtime"@@ -85,6 +87,8 @@ export interface TabEntityData {/** Resolved display name for an actor subject. */actorName?: string;skill?: { name: string };+ doc?: {title: string};+ docFolder?: {title: string};machine?: { name: string };runtime?: { name: string };/** Resolved chat session title (already includes the "New chat" fallback). */@@ -187,6 +191,10 @@ export function resolveTabPresentation(visual: { kind: "actor", actorType: subject.actorType, id: subject.id },title: textOr(data.actorName, ACTOR_LABEL[subject.actorType]),};+ case "doc":+ return { visual: { kind: "icon", icon: "FileText" }, title: textOr(data.doc?.title, "doc") };+ case "docFolder":+ return { visual: { kind: "icon", icon: "FolderKanban" }, title: textOr(data.docFolder?.title, "docFolder") };case "skill":return {visual: { kind: "icon", icon: "BookOpenText" },diff --git a/packages/core/paths/tab-subject.ts b/packages/core/paths/tab-subject.tsindex b7453d75c6..4fb1a1bc6c 100644--- a/packages/core/paths/tab-subject.ts+++ b/packages/core/paths/tab-subject.ts@@ -33,6 +33,8 @@ export type TabSubject =| { kind: "actor"; actorType: TabActorType; id: string }/** A single skill detail. */| { kind: "skill"; id: string }+ | { kind: "doc"; id: string }+ | { kind: "docFolder"; id: string }/** A runtime machine detail. */| { kind: "machine"; machineId: string }/** A runtime nested under a machine. */@@ -118,6 +120,11 @@ export function parseTabSubject(url: string): TabSubject {return { kind: "runtime", machineId: id, runtimeId: segments[4] };}return { kind: "machine", machineId: id };+ case "docs":+ if (id === "folders") {+ return segments[3] ? { kind: "docFolder", id: segments[3] } : { kind: "unknown" };+ }+ return id ? { kind: "doc", id } : { kind: "page", page: "docs" };case "skills":return id ? { kind: "skill", id } : { kind: "page", page: "skills" };case "settings":@@ -158,6 +165,10 @@ export function tabSubjectKey(subject: TabSubject): string {return `actor:${subject.actorType}:${subject.id}`;case "skill":return `skill:${subject.id}`;+ case "doc":+ return `doc:${subject.id}`;+ case "docFolder":+ return `docFolder:${subject.id}`;case "machine":return `machine:${subject.machineId}`;case "runtime":diff --git a/packages/core/platform/doc-session-cleanup.test.ts b/packages/core/platform/doc-session-cleanup.test.tsnew file mode 100644index 0000000000..77d074b616--- /dev/null+++ b/packages/core/platform/doc-session-cleanup.test.ts@@ -0,0 +1,53 @@+// @vitest-environment jsdom+import { QueryClient } from "@tanstack/react-query";+import { afterEach, expect, it } from "vitest";+import { clearClientSessionData } from "./session-cleanup";+import { setCurrentWorkspace } from "./workspace-storage";++afterEach(() => {+ setCurrentWorkspace(null, null);+ localStorage.clear();+});++it("clears document drafts on an expired-session cold start before opening Docs", async () => {+ // Do not import the Docs store here: cleanup must preload it itself.+ const privateDraft = JSON.stringify({+ state: {+ draft: { entries: { "ws:doc": { content: "Previous user's draft" } } },+ },+ version: 0,+ });+ localStorage.setItem("doc-drafts:acme", privateDraft);+ localStorage.setItem("doc-drafts:globex", privateDraft);+ localStorage.setItem("multica_locale", "zh-Hans");+ const client = new QueryClient(); // No cached workspace list at cold start.++ clearClientSessionData(client);++ expect(localStorage.getItem("doc-drafts:acme")).toBeNull();+ expect(localStorage.getItem("doc-drafts:globex")).toBeNull();+ expect(localStorage.getItem("multica_locale")).toBe("zh-Hans");++ // A second account entering the same workspace cannot hydrate A's draft.+ setCurrentWorkspace("acme", "ws");+ const { useDocDraftStore } = await import("../docs/draft-store");+ expect(useDocDraftStore.getState().draft.entries).toEqual({});+});++it("clears the loaded document store in memory as well as persisted storage", async () => {+ setCurrentWorkspace("acme", "ws");+ const { useDocDraftStore, setDocDraft } = await import("../docs/draft-store");+ setDocDraft("ws:doc", {+ title: "Private",+ content: "A's unsaved edit",+ baseTitle: "Private",+ baseContent: "Original",+ baseRevision: 1,+ backup: { title: "Old title", content: "A's conflict backup" },+ });++ clearClientSessionData(new QueryClient());++ expect(useDocDraftStore.getState().draft.entries).toEqual({});+ expect(localStorage.getItem("doc-drafts:acme")).toBeNull();+});diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsxindex cc3d34a0af..d491b5825f 100644--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx@@ -150,16 +150,16 @@ describe("useRealtimeSync — ws instance change", () => {rerender({ ws: ws2 });// Should have called invalidateQueries for all workspace-scoped keys- // (19 workspace-scoped [incl. property definitions, workflows, saved views- // and view preferences] + 6 per-issue prefixes + the workspace+ // (20 workspace-scoped [incl. property definitions, workflows, saved views+ // view preferences, and docs] + 6 per-issue prefixes + the workspace// working-agents projection + 6 per-chat prefixes + 1 workspaceKeys.list()// + 1 cross-workspace inbox unread summary + 1 issue unread marks + 1- // subscribed issue ids + 1 account invitation list = 38 calls).+ // subscribed issue ids + 1 account invitation list = 39 calls).//// Awaited rather than counted synchronously: the inbox unread summary// refresh cancels any in-flight request before invalidating (see// onInboxSummaryInvalidate), so that one lands after the synchronous ones.- await waitFor(() => expect(invalidateSpy).toHaveBeenCalledTimes(38));+ await waitFor(() => expect(invalidateSpy).toHaveBeenCalledTimes(39));});it("does not re-invalidate when rerendered with the same ws instance", () => {diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 6396d66e53..556a788cad 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -1,4 +1,5 @@"use client";+import { docKeys } from "../docs/queries";import { weixinKeys } from "../weixin/queries";@@ -719,6 +720,7 @@ function invalidateWorkspaceScopedQueries(qc: QueryClient): void {qc.invalidateQueries({ queryKey: issueWorkflowKeys.all(wsId) });qc.invalidateQueries({ queryKey: issueViewKeys.all(wsId) });qc.invalidateQueries({ queryKey: issueViewPrefKeys.all(wsId) });+ qc.invalidateQueries({ queryKey: docKeys.all(wsId) });}// Cross-workspace, so outside the wsId guard: a reconnect may have missed// inbox events from any workspace, so re-pull the switcher-dot summary.@@ -1421,6 +1423,13 @@ export function useRealtimeSync(qc.invalidateQueries({ queryKey: issueKeys.attachments(issueId) });};+ const docUnsubs = ([+ "doc:created", "doc:updated", "doc:deleted",+ "doc_folder:created", "doc_folder:updated", "doc_folder:deleted",+ ] as const).map((event) => ws.on(event, () => {+ const wsId = getCurrentWsId();+ if (wsId) void qc.invalidateQueries({ queryKey: docKeys.all(wsId) });+ }));const unsubCommentCreated = ws.on("comment:created", (p) => {const { comment, issue_revision: issueRevision } = p as CommentCreatedPayload;if (!comment?.issue_id) return;@@ -2109,6 +2118,7 @@ export function useRealtimeSync(unsubIssuePropertiesChanged();unsubPropertyChanged.forEach((unsub) => unsub());unsubInboxNew();+ docUnsubs.forEach(unsub => unsub());unsubCommentCreated();unsubCommentUpdated();unsubCommentDeleted();diff --git a/packages/core/types/doc.ts b/packages/core/types/doc.tsnew file mode 100644index 0000000000..c0e8f469f7--- /dev/null+++ b/packages/core/types/doc.ts@@ -0,0 +1,65 @@+export type DocAuthorType = "member" | "agent";+export interface DocSummary {+ id: string;+ workspaceId: string;+ folderId: string | null;+ title: string;+ revision: number;+ versionCount: number;+ createdByType: DocAuthorType;+ createdById: string;+ updatedByType: DocAuthorType;+ updatedById: string;+ createdAt: string;+ updatedAt: string;+}+export interface Doc extends DocSummary {+ content: string;+}+export interface DocFolder {+ id: string;+ workspaceId: string;+ parentId: string | null;+ title: string;+ createdByType: DocAuthorType;+ createdById: string;+ createdAt: string;+ updatedAt: string;+}+export interface DocTree {+ folders: DocFolder[];+ docs: DocSummary[];+}+export interface DocVersion {+ docId: string;+ number: number;+ title: string;+ authorType: DocAuthorType;+ authorId: string;+ message: string;+ action: "create" | "edit" | "restore";+ actionRef: number | null;+ taskId: string | null;+ issueId: string | null;+ createdAt: string;+ updatedAt: string;+ content?: string;+}+export interface CreateDocRequest {+ title: string;+ content?: string;+ folderId?: string | null;+ message?: string;+}+export interface UpdateDocRequest {+ baseRevision: number;+ title?: string;+ content?: string;+ message?: string;+ action?: "edit" | "restore";+ actionRef?: number;+}+export interface CreateDocFolderRequest {+ title: string;+ parentId?: string | null;+}diff --git a/packages/core/types/events.ts b/packages/core/types/events.tsindex b50baa780f..0e0dd2460f 100644--- a/packages/core/types/events.ts+++ b/packages/core/types/events.ts@@ -10,6 +10,12 @@ import type { Label } from "./label";// WebSocket event types (matching Go server protocol/events.go)export type WSEventType =+ | "doc:created"+ | "doc:updated"+ | "doc:deleted"+ | "doc_folder:created"+ | "doc_folder:updated"+ | "doc_folder:deleted"| "issue:created"| "issue:updated"| "issue_attachments:changed"diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex cd8c143b88..29ea25d004 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -431,3 +431,5 @@ export type { IssueWakeup, IssueWakeupInput, SystemWakeup, WorkspaceSystemWakeupexport type { WorkspaceWakeup, WorkspaceWakeupPage, WorkspaceWakeupFilters, WakeupScope } from "./issue-wakeup";export type { WeixinInstallation, ListWeixinInstallationsResponse, WeixinLogin } from "./weixin";++export * from "./doc";diff --git a/packages/ui/markdown/Markdown.tsx b/packages/ui/markdown/Markdown.tsxindex b2e65fcf83..ca4fa7d208 100644--- a/packages/ui/markdown/Markdown.tsx+++ b/packages/ui/markdown/Markdown.tsx@@ -151,9 +151,9 @@ function createComponents(},// Links: Make clickable with callbacks, or render as mentiona: ({ href, children }) => {- // Mention links: mention://member/id, mention://agent/id, mention://issue/id, mention://project/id, mention://all/all+ // Mention links: mention://member/id, mention://agent/id, mention://issue/id, mention://project/id, mention://doc/id, mention://all/allif (href?.startsWith('mention://')) {- const mentionMatch = href.match(/^mention:\/\/(member|agent|issue|project|all)\/(.+)$/)+ const mentionMatch = href.match(/^mention:\/\/(member|agent|issue|project|doc|all)\/(.+)$/)if (mentionMatch?.[1] && mentionMatch[2]) {const type = mentionMatch[1]const id = mentionMatch[2]diff --git a/packages/views/docs/components/doc-history-page.tsx b/packages/views/docs/components/doc-history-page.tsxnew file mode 100644index 0000000000..16c214524e--- /dev/null+++ b/packages/views/docs/components/doc-history-page.tsx@@ -0,0 +1,132 @@+"use client";+import { useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { toast } from "sonner";+import { Button } from "@multica/ui/components/ui/button";+import {+ docDetailOptions,+ docVersionsOptions,+ docVersionOptions,+ useUpdateDoc,+} from "@multica/core/docs";+import { useWorkspaceId } from "@multica/core/hooks";+import { useWorkspacePaths } from "@multica/core/paths";+import { useActorName } from "@multica/core/workspace/hooks";+import { ReadonlyContent } from "../../editor";+import { BreadcrumbHeader } from "../../layout/breadcrumb-header";+import { useNavigation } from "../../navigation";+import { useT } from "../../i18n";+export function DocHistoryPage({ docId }: { docId: string }) {+ const { t } = useT("docs");+ const wsId = useWorkspaceId();+ const p = useWorkspacePaths();+ const { push } = useNavigation();+ const { getActorName } = useActorName();+ const doc = useQuery(docDetailOptions(wsId, docId));+ const versions = useQuery(docVersionsOptions(wsId, docId));+ const [selected, setSelected] = useState<number | null>(null);+ const number = selected ?? versions.data?.[0]?.number ?? 1;+ const version = useQuery({+ ...docVersionOptions(wsId, docId, number),+ enabled: !!versions.data?.length,+ });+ const update = useUpdateDoc();+ const restore = async () => {+ if (!doc.data || !version.data) return;+ try {+ await update.mutateAsync({+ id: docId,+ baseRevision: doc.data.revision,+ action: "restore",+ actionRef: number,+ });+ push(p.docDetail(docId));+ } catch (error) {+ toast.error(+ error instanceof Error ? error.message : t(($) => $.errors.save),+ );+ void doc.refetch();+ }+ };+ return (+ <div className="flex h-full min-h-0 flex-col">+ <BreadcrumbHeader+ segments={[+ { href: p.docs(), label: t(($) => $.kb) },+ {+ href: p.docDetail(docId),+ label: doc.data?.title || t(($) => $.untitled),+ },+ ]}+ leaf={t(($) => $.history.title)}+ />+ <div className="flex min-h-0 flex-1 flex-col md:flex-row">+ <div className="max-h-52 shrink-0 overflow-auto border-b p-3 md:max-h-none md:w-60 md:border-r md:border-b-0">+ {versions.isError ? (+ <Button onClick={() => void versions.refetch()}>+ {t(($) => $.editor.retry)}+ </Button>+ ) : (+ versions.data?.map((v) => (+ <button+ type="button"+ key={v.number}+ onClick={() => setSelected(v.number)}+ aria-pressed={number === v.number}+ className={`mb-1 block w-full rounded-md p-3 text-left text-body ${number === v.number ? "bg-surface-selected text-surface-selected-foreground" : "hover:bg-surface-hover"}`}+ >+ <span className="font-medium">+ {t(($) => $.version_number, { number: v.number })}+ </span>+ <span className="ml-2 text-caption">+ {v.number === doc.data?.versionCount+ ? t(($) => $.history.current)+ : ""}+ </span>+ <span className="mt-1 block truncate text-caption">+ {getActorName(v.authorType, v.authorId)}+ </span>+ <span className="block text-caption text-muted-foreground">+ {new Date(v.updatedAt).toLocaleString()}+ </span>+ </button>+ ))+ )}+ </div>+ <div className="min-h-0 min-w-0 flex-1 overflow-auto p-6">+ <div className="mx-auto max-w-3xl">+ {version.isError || (!version.isPending && !version.data) ? (+ <Button onClick={() => void version.refetch()}>+ {t(($) => $.editor.retry)}+ </Button>+ ) : version.data ? (+ <>+ <div className="mb-6 flex items-center justify-between gap-3">+ <h1 className="text-display-sm font-semibold">+ {version.data.title || t(($) => $.untitled)}+ </h1>+ <Button+ variant="outline"+ size="sm"+ disabled={+ update.isPending ||+ !doc.data ||+ number === doc.data.versionCount ||+ version.data.content === undefined+ }+ onClick={() => void restore()}+ >+ {t(($) => $.history.restore)}+ </Button>+ </div>+ <ReadonlyContent content={version.data.content ?? ""} />+ </>+ ) : (+ t(($) => $.history.loading)+ )}+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/packages/views/docs/components/doc-mention-card.tsx b/packages/views/docs/components/doc-mention-card.tsxnew file mode 100644index 0000000000..9c172deceb--- /dev/null+++ b/packages/views/docs/components/doc-mention-card.tsx@@ -0,0 +1,53 @@+"use client";++import { useQuery } from "@tanstack/react-query";+import { FileText } from "@multica/ui/icons";+import { cn } from "@multica/ui/lib/utils";+import { docTreeOptions } from "@multica/core/docs";+import { useWorkspaceId } from "@multica/core/hooks";+import { useWorkspacePaths } from "@multica/core/paths";+import { AppLink } from "../../navigation";+import { useT } from "../../i18n";++/**+ * Navigable doc chip for `mention://doc/<id>` and pasted doc URLs. Same shape+ * and width cap as ProjectChip, so an issue that cites a doc and a project+ * reads as one family. The title comes from the doc tree, so a rename shows+ * everywhere the doc is cited; the label written into the Markdown is only the+ * fallback for a doc this workspace no longer has.+ */+export function DocMentionCard({+ docId,+ fallbackLabel,+}: {+ docId: string;+ fallbackLabel?: string;+}) {+ const wsId = useWorkspaceId();+ const p = useWorkspacePaths();+ const { t } = useT("docs");+ const { data: tree } = useQuery(docTreeOptions(wsId));+ const doc = tree?.docs.find((d) => d.id === docId);+ const title = doc+ ? doc.title || t(($) => $.untitled)+ : fallbackLabel || t(($) => $.untitled);+ return (+ <AppLink+ href={p.docDetail(docId)}+ newTabTitle={title}+ className="doc-mention inline-flex"+ >+ <span className="doc-chip mx-0.5 inline-flex min-w-0 max-w-[min(18rem,100%)] items-center gap-1.5 rounded-md border px-2 py-0.5 text-caption">+ <FileText className="size-3.5 shrink-0 text-muted-foreground" />+ <span+ className={cn(+ "min-w-0 truncate",+ doc ? "text-foreground" : "text-muted-foreground",+ )}+ >+ {title}+ </span>+ </span>+ </AppLink>+ );+}diff --git a/packages/views/docs/components/doc-outline.test.tsx b/packages/views/docs/components/doc-outline.test.tsxnew file mode 100644index 0000000000..531d0c60a7--- /dev/null+++ b/packages/views/docs/components/doc-outline.test.tsx@@ -0,0 +1,52 @@+import { fireEvent, render, screen } from "@testing-library/react";+import type { ReactNode } from "react";+import { describe, expect, it, vi } from "vitest";+import { I18nProvider } from "@multica/core/i18n/react";+import enDocs from "../../locales/en/docs.json";+import { DocOutline, readOutline } from "./doc-outline";++function I18nWrapper({ children }: { children: ReactNode }) {+ return (+ <I18nProvider locale="en" resources={{ en: { docs: enDocs } }}>+ {children}+ </I18nProvider>+ );+}++function renderedDoc(html: string) {+ const root = document.createElement("div");+ root.innerHTML = `<div class="ProseMirror">${html}</div>`;+ return root;+}++describe("readOutline", () => {+ it("lists top-level H1–H3 in order and skips empty headings", () => {+ const root = renderedDoc(+ "<h1>Overview</h1><p>x</p><h2>Setup</h2><h4>Deep</h4><h3> </h3><blockquote><h2>Quoted</h2></blockquote><h3>Verify</h3>",+ );+ expect(readOutline(root).map(({ level, text }) => ({ level, text }))).toEqual([+ { level: 1, text: "Overview" },+ { level: 2, text: "Setup" },+ { level: 3, text: "Verify" },+ ]);+ });+});++describe("DocOutline", () => {+ it("marks the current heading and reports clicks", () => {+ const headings = readOutline(+ renderedDoc("<h2>Goals</h2><h3>Scope</h3><h2>Plan</h2>"),+ );+ const onSelect = vi.fn();+ render(<DocOutline headings={headings} activeIndex={1} onSelect={onSelect} />, {+ wrapper: I18nWrapper,+ });+ expect(screen.getByRole("navigation", { name: "Outline" })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Scope" })).toHaveAttribute(+ "aria-current",+ "location",+ );+ fireEvent.click(screen.getByRole("button", { name: "Plan" }));+ expect(onSelect).toHaveBeenCalledWith(headings[2]);+ });+});diff --git a/packages/views/docs/components/doc-outline.tsx b/packages/views/docs/components/doc-outline.tsxnew file mode 100644index 0000000000..348038d0af--- /dev/null+++ b/packages/views/docs/components/doc-outline.tsx@@ -0,0 +1,148 @@+"use client";+import { useEffect, useState, type RefObject } from "react";+import { cn } from "@multica/ui/lib/utils";+import { useT } from "../../i18n";++export interface OutlineHeading {+ level: number;+ text: string;+ element: HTMLElement;+}++/** The outline shows only when a document has at least this many headings. */+export const MIN_OUTLINE_HEADINGS = 3;+/** Distance below the scroll top at which a heading counts as the current one. */+const ACTIVE_OFFSET = 96;+/** Space kept above a heading the outline scrolls to. */+const SCROLL_MARGIN = 24;++/** Top-level H1–H3 of the rendered document, in order; empty headings skipped. */+export function readOutline(root: ParentNode): OutlineHeading[] {+ return Array.from(+ root.querySelectorAll<HTMLElement>(+ ".ProseMirror > h1, .ProseMirror > h2, .ProseMirror > h3",+ ),+ )+ .map((element) => ({+ level: Number(element.tagName.slice(1)),+ text: element.textContent?.trim() ?? "",+ element,+ }))+ .filter((heading) => heading.text !== "");+}++function sameOutline(a: OutlineHeading[], b: OutlineHeading[]): boolean {+ return (+ a.length === b.length &&+ a.every(+ (heading, i) =>+ heading.level === b[i]!.level &&+ heading.text === b[i]!.text &&+ heading.element === b[i]!.element,+ )+ );+}++/**+ * Headings of the editor under `rootRef`, kept current as the user types, and+ * which one the scroll position of `scrollRef` is in.+ */+export function useDocOutline(+ rootRef: RefObject<HTMLElement | null>,+ scrollRef: RefObject<HTMLElement | null>,+) {+ const [headings, setHeadings] = useState<OutlineHeading[]>([]);+ const [activeIndex, setActiveIndex] = useState(0);++ useEffect(() => {+ const root = rootRef.current;+ if (!root) return;+ let frame = 0;+ const refresh = () => {+ cancelAnimationFrame(frame);+ frame = requestAnimationFrame(() => {+ const next = readOutline(root);+ setHeadings((prev) => (sameOutline(prev, next) ? prev : next));+ });+ };+ refresh();+ // The editor mounts after first paint and re-renders headings in place, so+ // watch the DOM rather than the Markdown.+ const observer = new MutationObserver(refresh);+ observer.observe(root, { childList: true, subtree: true, characterData: true });+ return () => {+ observer.disconnect();+ cancelAnimationFrame(frame);+ };+ }, [rootRef]);++ useEffect(() => {+ const scroller = scrollRef.current;+ if (!scroller || headings.length === 0) return;+ const update = () => {+ const line = scroller.getBoundingClientRect().top + ACTIVE_OFFSET;+ let active = 0;+ headings.forEach((heading, i) => {+ if (heading.element.getBoundingClientRect().top <= line) active = i;+ });+ setActiveIndex(active);+ };+ update();+ scroller.addEventListener("scroll", update, { passive: true });+ return () => scroller.removeEventListener("scroll", update);+ }, [headings, scrollRef]);++ const scrollTo = (heading: OutlineHeading) => {+ const scroller = scrollRef.current;+ if (!scroller) return;+ const offset =+ heading.element.getBoundingClientRect().top -+ scroller.getBoundingClientRect().top;+ scroller.scrollTo({+ top: scroller.scrollTop + offset - SCROLL_MARGIN,+ behavior: "smooth",+ });+ };++ return { headings, activeIndex, scrollTo };+}++export function DocOutline({+ headings,+ activeIndex,+ onSelect,+}: {+ headings: OutlineHeading[];+ activeIndex: number;+ onSelect: (heading: OutlineHeading) => void;+}) {+ const { t } = useT("docs");+ const minLevel = Math.min(...headings.map((heading) => heading.level));+ return (+ <nav+ aria-label={t(($) => $.outline)}+ className="sticky top-8 max-h-[70vh] overflow-y-auto"+ >+ <ul className="border-l">+ {headings.map((heading, i) => (+ <li key={`${i}:${heading.text}`}>+ <button+ type="button"+ aria-current={i === activeIndex ? "location" : undefined}+ onClick={() => onSelect(heading)}+ className={cn(+ "-ml-px block w-full truncate border-l-2 py-1 pr-2 text-left text-caption transition-colors",+ i === activeIndex+ ? "border-foreground text-foreground"+ : "border-transparent text-muted-foreground hover:text-foreground",+ )}+ style={{ paddingLeft: 12 + (heading.level - minLevel) * 12 }}+ >+ {heading.text}+ </button>+ </li>+ ))}+ </ul>+ </nav>+ );+}diff --git a/packages/views/docs/components/doc-page.tsx b/packages/views/docs/components/doc-page.tsxnew file mode 100644index 0000000000..15e1cfa794--- /dev/null+++ b/packages/views/docs/components/doc-page.tsx@@ -0,0 +1,252 @@+"use client";+import { useCallback, useRef, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import {+ History,+ Link as LinkIcon,+ MoreHorizontal,+ FolderInput,+ Trash2,+} from "@multica/ui/icons";+import { toast } from "sonner";+import { copyText } from "@multica/ui/lib/clipboard";+import { Button } from "@multica/ui/components/ui/button";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@multica/ui/components/ui/tooltip";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";+import {+ docDetailOptions,+ docTreeOptions,+ folderAncestry,+} from "@multica/core/docs";+import { useWorkspaceId } from "@multica/core/hooks";+import { useWorkspacePaths } from "@multica/core/paths";+import { useActorName } from "@multica/core/workspace/hooks";+import type { Doc } from "@multica/core/types";+import { ContentEditor, useEditorUpload } from "../../editor";+import { ActorAvatar } from "../../common/actor-avatar";+import { BreadcrumbHeader } from "../../layout/breadcrumb-header";+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 { MoveDialog } from "./move-dialog";+import { DeleteDocDialog } from "./doc-tree";+export function DocPage({ docId }: { docId: string }) {+ const wsId = useWorkspaceId();+ const { t } = useT("docs");+ const query = useQuery(docDetailOptions(wsId, docId));+ if (!query.data)+ return (+ <div className="p-6">+ {query.isError ? (+ <Button onClick={() => void query.refetch()}>+ {t(($) => $.editor.retry)}+ </Button>+ ) : (+ t(($) => $.history.loading)+ )}+ </div>+ );+ return <DocEditor key={`${wsId}:${docId}`} doc={query.data} />;+}+function DocEditor({ doc }: { doc: Doc }) {+ const { t } = useT("docs");+ const p = useWorkspacePaths();+ const wsId = useWorkspaceId();+ const { data: tree } = useQuery(docTreeOptions(wsId));+ const { getActorName } = useActorName();+ const timeAgo = useTimeAgo();+ const { draft, status, dirty, change, retry, reload } = useDocDraft(doc);+ const [moving, setMoving] = useState(false);+ const [deleting, setDeleting] = useState(false);+ const ancestors = folderAncestry(tree?.folders ?? [], doc.folderId);+ const author = getActorName(doc.updatedByType, doc.updatedById);+ const { getShareableUrl } = useNavigation();+ const copyLink = () => {+ void copyText(getShareableUrl(p.docDetail(doc.id))).then((ok) => {+ if (ok) toast.success(t(($) => $.link_copied));+ });+ };+ const { uploadWithToast } = useEditorUpload();+ const uploadFile = useCallback((file: File) => uploadWithToast(file), [uploadWithToast]);+ const scrollRef = useRef<HTMLDivElement>(null);+ const bodyRef = useRef<HTMLDivElement>(null);+ const outline = useDocOutline(bodyRef, scrollRef);+ const showOutline = outline.headings.length >= MIN_OUTLINE_HEADINGS;+ return (+ <div className="flex h-full min-h-0 flex-col">+ <BreadcrumbHeader+ segments={[+ { href: p.docs(), label: t(($) => $.kb) },+ ...ancestors.map((f) => ({+ href: p.docFolder(f.id),+ label: f.title,+ })),+ ]}+ leaf={+ <span className="truncate">{doc.title || t(($) => $.untitled)}</span>+ }+ actions={+ <>+ <span role="status" className="px-1 text-caption text-muted-foreground">+ {status === "error" ? (+ <Button size="xs" variant="ghost" onClick={() => void retry()}>+ {t(($) => $.editor.save_failed)}+ </Button>+ ) : status === "saving" || (dirty && status === "saved") ? (+ t(($) => $.editor.saving)+ ) : status !== "conflict" ? (+ t(($) => $.editor.saved)+ ) : null}+ </span>+ <Button+ size="icon-sm"+ variant="ghost"+ aria-label={t(($) => $.actions.copy_link)}+ title={t(($) => $.actions.copy_link)}+ onClick={copyLink}+ >+ <LinkIcon className="size-4" />+ </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"+ >+ <History className="size-4" />+ {t(($) => $.actions.history)}+ </AppLink>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ size="icon-sm"+ variant="ghost"+ aria-label={t(($) => $.actions.more)}+ />+ }+ >+ <MoreHorizontal className="size-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={() => setMoving(true)}>+ <FolderInput />+ {t(($) => $.actions.move)}+ </DropdownMenuItem>+ <DropdownMenuItem+ variant="destructive"+ onClick={() => setDeleting(true)}+ >+ <Trash2 />+ {t(($) => $.actions.delete)}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </>+ }+ />+ {status === "conflict" && (+ <div+ role="alert"+ className="flex flex-wrap items-center gap-2 border-b bg-warning/10 px-6 py-2 text-body"+ >+ <span className="flex-1">+ {t(($) => $.editor.conflict, { name: author })}+ </span>+ <Button size="sm" onClick={() => void reload()}>+ {t(($) => $.editor.reload)}+ </Button>+ </div>+ )}+ <div ref={scrollRef} className="@container min-h-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">+ {draft.backup && (+ <details className="mb-5 rounded-md border p-3 text-body">+ <summary className="cursor-pointer">+ {t(($) => $.editor.draft)}+ </summary>+ <textarea+ aria-label={t(($) => $.editor.draft)}+ readOnly+ value={`${draft.backup.title}\n\n${draft.backup.content}`}+ className="mt-2 min-h-40 w-full resize-y rounded-md bg-muted p-2 font-mono text-caption"+ />+ </details>+ )}+ <input+ aria-label={t(($) => $.editor.title_label)}+ value={draft.title}+ // A doc just created from the tree is blank: start in its title.+ autoFocus={!doc.title && !doc.content}+ maxLength={300}+ placeholder={t(($) => $.untitled)}+ onChange={(e) => change({ title: e.target.value })}+ className="w-full bg-transparent text-display-sm font-semibold outline-none"+ />+ <div className="mt-3 mb-8 flex items-center gap-2 text-caption text-muted-foreground">+ <ActorAvatar+ actorType={doc.updatedByType}+ actorId={doc.updatedById}+ size="xs"+ />+ <span className="truncate">{author}</span>+ <span aria-hidden>·</span>+ <Tooltip>+ <TooltipTrigger+ render={<time dateTime={doc.updatedAt} className="shrink-0" />}+ >+ {t(($) => $.edited, { time: timeAgo(doc.updatedAt) })}+ </TooltipTrigger>+ <TooltipContent>+ {new Date(doc.updatedAt).toLocaleString()}+ </TooltipContent>+ </Tooltip>+ </div>+ <div ref={bodyRef}>+ <ContentEditor+ value={draft.content}+ onUpdate={(content) => change({ content })}+ debounceMs={0}+ flushPendingOnUnmount+ placeholder={t(($) => $.editor.placeholder)}+ enableSlashCommands+ slashCommandMode="blocks"+ showBlockHandles+ onUploadFile={uploadFile}+ className="min-h-80"+ />+ </div>+ </div>+ </div>+ {showOutline && (+ <aside className="hidden w-56 shrink-0 py-8 pr-6 @5xl:block">+ <DocOutline+ headings={outline.headings}+ activeIndex={outline.activeIndex}+ onSelect={outline.scrollTo}+ />+ </aside>+ )}+ </div>+ </div>+ <MoveDialog+ target={moving ? { kind: "doc", id: doc.id, title: doc.title } : null}+ onOpenChange={setMoving}+ />+ <DeleteDocDialog+ target={deleting ? { kind: "doc", item: doc } : null}+ onOpenChange={setDeleting}+ />+ </div>+ );+}diff --git a/packages/views/docs/components/doc-tree.dnd.test.tsx b/packages/views/docs/components/doc-tree.dnd.test.tsxnew file mode 100644index 0000000000..7fa4f5cc6e--- /dev/null+++ b/packages/views/docs/components/doc-tree.dnd.test.tsx@@ -0,0 +1,96 @@+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { I18nProvider } from "@multica/core/i18n/react";+import { docKeys } from "@multica/core/docs";+import { DocTree } from "./doc-tree";+import enDocs from "../../locales/en/docs.json";+import enEditor from "../../locales/en/editor.json";+import enIssues from "../../locales/en/issues.json";++// Real drag events through the tree: a refused drop must not bubble to the+// top-level drop zone and move the item to the root (PR #10926 review).+const apiMock = vi.hoisted(() => ({+ listDocTree: vi.fn(), moveDoc: vi.fn(), moveDocFolder: vi.fn(),+ searchIssues: vi.fn(), searchProjects: vi.fn(),+}));+vi.mock("@multica/core/api", () => ({ api: apiMock }));+vi.mock("@multica/core/hooks", async (original) => ({+ ...await original<object>(), useWorkspaceId: () => "review-ws",+}));+vi.mock("@multica/core/platform", async (original) => ({+ ...await original<object>(), getCurrentWsId: () => "review-ws",+}));+vi.mock("@multica/core/auth", () => ({+ useAuthStore: Object.assign(vi.fn(), { getState: () => ({ user: { id: "reviewer" } }) }),+}));+vi.mock("@multica/core/paths", async (original) => ({+ ...await original<object>(), useWorkspacePaths: () => ({+ docs: () => "/review/docs", docDetail: (id: string) => `/review/docs/${id}`,+ docFolder: (id: string) => `/review/docs/folders/${id}`,+ }),+}));+vi.mock("../../navigation", () => ({+ useNavigation: () => ({ pathname: "/review/docs", push: vi.fn() }),+ AppLink: ({ children, href }: { children: React.ReactNode; href: string }) => <a href={href}>{children}</a>,+}));+vi.mock("@multica/core/issue-statuses/hooks", () => ({+ useIssueStatuses: () => ({ iconOf: () => null, colorOf: () => null }),+}));+vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));++const tree = {+ folders: [+ { id: "parent", title: "Parent", parentId: null },+ { id: "child", title: "Child", parentId: "parent" },+ { id: "grandchild", title: "Grandchild", parentId: "child" },+ { id: "other", title: "Other", parentId: null },+ ],+ docs: [{ id: "runbook", title: "Release runbook", folderId: "child", updatedAt: "2026-11-18T00:00:00Z" }],+};+let qc: QueryClient;+beforeEach(() => {+ vi.clearAllMocks();+ qc = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });+ apiMock.listDocTree.mockResolvedValue(tree);+ apiMock.moveDoc.mockResolvedValue({});+ apiMock.moveDocFolder.mockResolvedValue({});+ apiMock.searchIssues.mockResolvedValue({ issues: [] });+ apiMock.searchProjects.mockResolvedValue({ projects: [] });+});+afterEach(() => { cleanup(); qc.clear(); });++function mount(children: React.ReactNode) {+ return render(<QueryClientProvider client={qc}><I18nProvider locale="en" resources={{ en: { docs: enDocs, editor: enEditor, issues: enIssues } }}>{children}</I18nProvider></QueryClientProvider>);+}+function folder(title: string) { return screen.getByText(title, { exact: true }).closest("summary")!; }+function dragDrop(source: Element, target: Element) {+ const dataTransfer = { setData: vi.fn(), effectAllowed: "", dropEffect: "" };+ fireEvent.dragStart(source, { dataTransfer });+ fireEvent.dragOver(target, { dataTransfer });+ fireEvent.drop(target, { dataTransfer });+ fireEvent.dragEnd(source, { dataTransfer });+}++it("control: a doc dropped on another folder moves to that folder", async () => {+ qc.setQueryData(docKeys.tree("review-ws"), tree);+ mount(<DocTree />);+ dragDrop(screen.getByRole("link", { name: "Release runbook" }), folder("Other"));+ await waitFor(() => expect(apiMock.moveDoc).toHaveBeenCalledWith("runbook", "other"));+});++it("dropping a doc on its current folder must not move it to the root", async () => {+ qc.setQueryData(docKeys.tree("review-ws"), tree);+ mount(<DocTree />);+ dragDrop(screen.getByRole("link", { name: "Release runbook" }), folder("Child"));+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); });+ expect(apiMock.moveDoc).not.toHaveBeenCalled();+});++it("dropping a nested folder on its descendant must not move the subtree to the root", async () => {+ qc.setQueryData(docKeys.tree("review-ws"), tree);+ mount(<DocTree />);+ dragDrop(folder("Child"), folder("Grandchild"));+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); });+ expect(apiMock.moveDocFolder).not.toHaveBeenCalled();+});diff --git a/packages/views/docs/components/doc-tree.test.ts b/packages/views/docs/components/doc-tree.test.tsnew file mode 100644index 0000000000..89e21aed1b--- /dev/null+++ b/packages/views/docs/components/doc-tree.test.ts@@ -0,0 +1,37 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import type { DocFolder, DocSummary } from "@multica/core/types";+import { canDropInto, folderAndDescendants } from "./doc-tree";++const folders = [+ { id: "eng", parentId: null },+ { id: "eng-api", parentId: "eng" },+ { id: "eng-api-v2", parentId: "eng-api" },+ { id: "ops", parentId: null },+];+const folder = (id: string) =>+ ({ kind: "folder", item: { ...folders.find((f) => f.id === id)!, title: id } as DocFolder }) as const;+const doc = (folderId: string | null) =>+ ({ kind: "doc", item: { id: "d", title: "Runbook", folderId } as DocSummary }) as const;++describe("folderAndDescendants", () => {+ it("collects a folder and every folder beneath it", () => {+ expect([...folderAndDescendants(folders, "eng")].sort()).toEqual(["eng", "eng-api", "eng-api-v2"]);+ });+});++describe("canDropInto", () => {+ it("moves a doc anywhere but where it already is", () => {+ expect(canDropInto(doc("eng"), "ops", folders)).toBe(true);+ expect(canDropInto(doc("eng"), null, folders)).toBe(true);+ expect(canDropInto(doc("eng"), "eng", folders)).toBe(false);+ });++ it("never moves a folder into itself or beneath itself", () => {+ expect(canDropInto(folder("eng"), "ops", folders)).toBe(true);+ expect(canDropInto(folder("eng"), "eng", folders)).toBe(false);+ expect(canDropInto(folder("eng"), "eng-api-v2", folders)).toBe(false);+ expect(canDropInto(folder("eng-api"), null, folders)).toBe(true);+ expect(canDropInto(folder("eng-api"), "eng", folders)).toBe(false);+ });+});diff --git a/packages/views/docs/components/doc-tree.tsx b/packages/views/docs/components/doc-tree.tsxnew file mode 100644index 0000000000..56305b8a7f--- /dev/null+++ b/packages/views/docs/components/doc-tree.tsx@@ -0,0 +1,517 @@+"use client";+import { useMemo, useState, type DragEvent } from "react";+import { useQuery } from "@tanstack/react-query";+import { toast } from "sonner";+import {+ FileText,+ Folder,+ FolderInput,+ MoreHorizontal,+ Pencil,+ Plus,+ Trash2,+} from "@multica/ui/icons";+import { Button } from "@multica/ui/components/ui/button";+import { Input } from "@multica/ui/components/ui/input";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogFooter,+} from "@multica/ui/components/ui/dialog";+import {+ AlertDialog,+ AlertDialogContent,+ AlertDialogHeader,+ AlertDialogTitle,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogCancel,+} from "@multica/ui/components/ui/alert-dialog";+import {+ DropdownMenu,+ DropdownMenuTrigger,+ DropdownMenuContent,+ DropdownMenuItem,+} from "@multica/ui/components/ui/dropdown-menu";+import {+ docTreeOptions,+ useCreateDoc,+ useCreateDocFolder,+ useMoveDoc,+ useMoveDocFolder,+ useRenameDocFolder,+ useUpdateDoc,+ useDeleteDoc,+ useDeleteDocFolder,+ removeDocDraft,+} from "@multica/core/docs";+import { useWorkspaceId } from "@multica/core/hooks";+import { useWorkspacePaths } from "@multica/core/paths";+import type { DocSummary, DocFolder } from "@multica/core/types";+import { AppLink, useNavigation } from "../../navigation";+import { useT } from "../../i18n";+import { MoveDialog, type MoveTarget } from "./move-dialog";++type Item =+ | { kind: "doc"; item: DocSummary }+ | { kind: "folder"; item: DocFolder };++/** Folders a folder cannot move into: itself and everything beneath it. */+export function folderAndDescendants(+ folders: readonly Pick<DocFolder, "id" | "parentId">[],+ id: string,+): Set<string> {+ const blocked = new Set([id]);+ let grew = true;+ while (grew) {+ grew = false;+ for (const f of folders) {+ if (f.parentId && blocked.has(f.parentId) && !blocked.has(f.id)) {+ blocked.add(f.id);+ grew = true;+ }+ }+ }+ return blocked;+}++/** Where a dragged item may land: a folder id, or `null` for the top level. */+export function canDropInto(+ dragged: Item,+ destination: string | null,+ folders: readonly Pick<DocFolder, "id" | "parentId">[],+): boolean {+ if (dragged.kind === "doc") return dragged.item.folderId !== destination;+ if (dragged.item.parentId === destination) return false;+ return destination === null || !folderAndDescendants(folders, dragged.item.id).has(destination);+}+export function DeleteDocDialog({+ target,+ onOpenChange,+}: {+ target: Item | null;+ onOpenChange: (open: boolean) => void;+}) {+ const { t } = useT("docs");+ const p = useWorkspacePaths();+ const wsId = useWorkspaceId();+ const { pathname, push } = useNavigation();+ const docDelete = useDeleteDoc();+ const folderDelete = useDeleteDocFolder();+ const pending = docDelete.isPending || folderDelete.isPending;+ const confirm = async () => {+ if (!target) return;+ try {+ if (target.kind === "doc") {+ await docDelete.mutateAsync(target.item.id);+ removeDocDraft(`${wsId}:${target.item.id}`);+ } else await folderDelete.mutateAsync(target.item.id);+ onOpenChange(false);+ if (+ pathname === p.docFolder(target.item.id) ||+ pathname.startsWith(p.docDetail(target.item.id))+ )+ push(p.docs());+ } catch (error) {+ toast.error(+ error instanceof Error ? error.message : t(($) => $.errors.delete),+ );+ }+ };+ return (+ <AlertDialog+ open={!!target}+ onOpenChange={(open) => {+ if (!pending) onOpenChange(open);+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>+ {target?.kind === "folder"+ ? t(($) => $.delete.folder_title)+ : t(($) => $.delete.title)}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {target?.kind === "folder"+ ? t(($) => $.delete.folder_description)+ : t(($) => $.delete.description, {+ title: target?.item.title ?? "",+ })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={pending}>+ {t(($) => $.actions.cancel)}+ </AlertDialogCancel>+ <Button+ variant="destructive"+ disabled={pending}+ onClick={() => void confirm()}+ >+ {t(($) => $.delete.confirm)}+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+}++export function DocTree() {+ const { t } = useT("docs");+ const p = useWorkspacePaths();+ const wsId = useWorkspaceId();+ const { pathname, push } = useNavigation();+ const tree = useQuery(docTreeOptions(wsId));+ const createDoc = useCreateDoc();+ const createFolder = useCreateDocFolder();+ const renameFolder = useRenameDocFolder();+ const updateDoc = useUpdateDoc();+ const moveDoc = useMoveDoc();+ const moveFolder = useMoveDocFolder();+ const [dragged, setDragged] = useState<Item | null>(null);+ // `undefined`: no drop target; `null`: the top level; otherwise a folder id.+ const [dropTarget, setDropTarget] = useState<string | null | undefined>(undefined);+ const folders = useMemo(() => tree.data?.folders ?? [], [tree.data]);+ const [form, setForm] = useState<{+ kind: "doc" | "folder";+ parentId: string | null;+ target?: Item;+ } | null>(null);+ const [name, setName] = useState("");+ const [moving, setMoving] = useState<MoveTarget | null>(null);+ const [deleting, setDeleting] = useState<Item | null>(null);+ const pending =+ createDoc.isPending ||+ createFolder.isPending ||+ renameFolder.isPending ||+ updateDoc.isPending;+ // A new doc opens straight away, untitled; its page puts the caret in the+ // title, so naming it is just typing.+ const newDoc = async (folderId: string | null) => {+ try {+ const doc = await createDoc.mutateAsync({ title: "", folderId });+ push(p.docDetail(doc.id));+ } catch (error) {+ toast.error(+ error instanceof Error ? error.message : t(($) => $.errors.save),+ );+ }+ };+ const dragProps = (item: Item) => ({+ draggable: true,+ onDragStart: (event: DragEvent) => {+ event.stopPropagation();+ event.dataTransfer.effectAllowed = "move";+ event.dataTransfer.setData("text/plain", item.item.title);+ setDragged(item);+ },+ onDragEnd: () => {+ setDragged(null);+ setDropTarget(undefined);+ },+ });+ // Every row is the drop target its position means: a folder row is that+ // folder, a doc row is the doc's folder, the blank tree is the top level.+ // The innermost target always answers and stops the event, even to refuse:+ // a refusal that bubbled would reach the top-level zone and move the item+ // to the root.+ const dropProps = (destination: string | null) => ({+ onDragOver: (event: DragEvent) => {+ if (!dragged) return;+ event.stopPropagation();+ if (!canDropInto(dragged, destination, folders)) {+ setDropTarget(undefined);+ return;+ }+ event.preventDefault();+ event.dataTransfer.dropEffect = "move";+ setDropTarget(destination);+ },+ onDragLeave: (event: DragEvent) => {+ if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;+ setDropTarget((current) => (current === destination ? undefined : current));+ },+ onDrop: (event: DragEvent) => {+ if (!dragged) return;+ event.preventDefault();+ event.stopPropagation();+ if (!canDropInto(dragged, destination, folders)) {+ setDragged(null);+ setDropTarget(undefined);+ return;+ }+ const item = dragged;+ setDragged(null);+ setDropTarget(undefined);+ const move =+ item.kind === "doc"+ ? moveDoc.mutateAsync({ id: item.item.id, folderId: destination })+ : moveFolder.mutateAsync({ id: item.item.id, parentId: destination });+ move.catch((error: unknown) => {+ toast.error(+ error instanceof Error ? error.message : t(($) => $.errors.move),+ );+ });+ },+ });+ const openForm = (+ kind: "doc" | "folder",+ parentId: string | null,+ target?: Item,+ ) => {+ setName(target?.item.title ?? "");+ setForm({ kind, parentId, target });+ };+ const submit = async (event: React.FormEvent) => {+ event.preventDefault();+ if (!form || !name.trim()) return;+ try {+ if (form.target?.kind === "doc")+ await updateDoc.mutateAsync({+ id: form.target.item.id,+ title: name.trim(),+ baseRevision: form.target.item.revision,+ });+ else if (form.target?.kind === "folder")+ await renameFolder.mutateAsync({+ id: form.target.item.id,+ title: name.trim(),+ });+ else+ await createFolder.mutateAsync({+ title: name.trim(),+ parentId: form.parentId,+ });+ setForm(null);+ } catch (error) {+ toast.error(+ error instanceof Error ? error.message : t(($) => $.errors.save),+ );+ }+ };+ const menu = (target: Item) => (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={t(($) => $.tree.more, { title: target.item.title })}+ />+ }+ >+ <MoreHorizontal className="size-3.5" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ {target.kind === "folder" && (+ <>+ <DropdownMenuItem onClick={() => void newDoc(target.item.id)}>+ <Plus />+ {t(($) => $.actions.new_doc)}+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => openForm("folder", target.item.id)}+ >+ <Folder />+ {t(($) => $.actions.new_folder)}+ </DropdownMenuItem>+ </>+ )}+ <DropdownMenuItem onClick={() => openForm(target.kind, null, target)}>+ <Pencil />+ {t(($) => $.actions.rename)}+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() =>+ setMoving({+ kind: target.kind,+ id: target.item.id,+ title: target.item.title,+ })+ }+ >+ <FolderInput />+ {t(($) => $.actions.move)}+ </DropdownMenuItem>+ <DropdownMenuItem+ variant="destructive"+ onClick={() => setDeleting(target)}+ >+ <Trash2 />+ {t(($) => $.actions.delete)}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+ const branch = (+ parent: string | null,+ ancestors: Set<string>,+ ): React.ReactNode => (+ <ul className="space-y-0.5">+ {tree.data?.folders+ .filter((f) => f.parentId === parent && !ancestors.has(f.id))+ .map((folder) => (+ <li key={folder.id}>+ <details open>+ <summary+ {...dragProps({ kind: "folder", item: folder })}+ {...dropProps(folder.id)}+ className={`group flex cursor-pointer items-center gap-1 rounded-md px-1 py-1 text-body hover:bg-surface-hover ${dropTarget === folder.id ? "bg-surface-hover ring-1 ring-ring" : ""}`}+ >+ <Folder className="size-4 shrink-0 text-muted-foreground" />+ <span className="min-w-0 flex-1 truncate">{folder.title}</span>+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={t(($) => $.tree.new_doc_in, { title: folder.title })}+ title={t(($) => $.actions.new_doc)}+ className="opacity-0 group-hover:opacity-100 focus-visible:opacity-100"+ disabled={createDoc.isPending}+ onClick={(event) => {+ // Inside <summary>: a click would also fold the folder.+ event.preventDefault();+ void newDoc(folder.id);+ }}+ >+ <Plus className="size-3.5" />+ </Button>+ {menu({ kind: "folder", item: folder })}+ </summary>+ <div className="ml-3 border-l pl-2" {...dropProps(folder.id)}>+ {branch(folder.id, new Set([...ancestors, folder.id]))}+ </div>+ </details>+ </li>+ ))}+ {tree.data?.docs+ .filter((d) => d.folderId === parent)+ .map((doc) => (+ <li+ key={doc.id}+ {...dragProps({ kind: "doc", item: doc })}+ {...dropProps(doc.folderId)}+ className={`flex items-center gap-1 rounded-md px-1 py-1 text-body ${pathname === p.docDetail(doc.id) ? "bg-surface-selected text-surface-selected-foreground" : "hover:bg-surface-hover"}`}+ >+ <FileText className="size-4 shrink-0 text-muted-foreground" />+ <AppLink+ href={p.docDetail(doc.id)}+ className="min-w-0 flex-1 truncate"+ >+ {doc.title || t(($) => $.untitled)}+ </AppLink>+ {menu({ kind: "doc", item: doc })}+ </li>+ ))}+ </ul>+ );+ return (+ <>+ <div className="flex h-12 shrink-0 items-center justify-between px-3">+ <AppLink href={p.docs()} className="text-body font-medium">+ {t(($) => $.kb)}+ </AppLink>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={t(($) => $.actions.new)}+ />+ }+ >+ <Plus className="size-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContent>+ <DropdownMenuItem onClick={() => void newDoc(null)}>+ {t(($) => $.actions.new_doc)}+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => openForm("folder", null)}>+ {t(($) => $.actions.new_folder)}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ <div+ {...dropProps(null)}+ className={`min-h-0 flex-1 overflow-auto px-2 pb-3 ${dropTarget === null ? "bg-surface-hover/50" : ""}`}+ >+ {tree.isError ? (+ <Button variant="ghost" onClick={() => void tree.refetch()}>+ {t(($) => $.editor.retry)}+ </Button>+ ) : tree.isPending ? (+ <span className="text-caption text-muted-foreground">+ {t(($) => $.history.loading)}+ </span>+ ) : (+ branch(null, new Set())+ )}+ {tree.data && !tree.data.docs.length && !tree.data.folders.length && (+ <p className="p-2 text-caption text-muted-foreground">+ {t(($) => $.tree.empty)}+ </p>+ )}+ </div>+ <Dialog+ open={!!form}+ onOpenChange={(open) => {+ if (!open && !pending) setForm(null);+ }}+ >+ <DialogContent>+ <form onSubmit={submit}>+ <DialogHeader>+ <DialogTitle>+ {form?.target+ ? t(($) => $.actions.rename)+ : form?.kind === "folder"+ ? t(($) => $.actions.new_folder)+ : t(($) => $.actions.new_doc)}+ </DialogTitle>+ </DialogHeader>+ <label className="my-4 block text-body">+ {t(($) => $.editor.title_label)}+ <Input+ autoFocus+ value={name}+ onChange={(e) => setName(e.target.value)}+ maxLength={form?.kind === "folder" ? 200 : 300}+ />+ </label>+ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ disabled={pending}+ onClick={() => setForm(null)}+ >+ {t(($) => $.actions.cancel)}+ </Button>+ <Button type="submit" disabled={pending || !name.trim()}>+ {form?.target+ ? t(($) => $.actions.rename)+ : t(($) => $.actions.new)}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ <MoveDialog+ target={moving}+ onOpenChange={(open) => {+ if (!open) setMoving(null);+ }}+ />+ <DeleteDocDialog+ target={deleting}+ onOpenChange={(open) => {+ if (!open) setDeleting(null);+ }}+ />+ </>+ );+}diff --git a/packages/views/docs/components/docs-home-page.tsx b/packages/views/docs/components/docs-home-page.tsxnew file mode 100644index 0000000000..e0c49eb1a0--- /dev/null+++ b/packages/views/docs/components/docs-home-page.tsx@@ -0,0 +1,76 @@+"use client";+import { useQuery } from "@tanstack/react-query";+import { useWorkspaceId } from "@multica/core/hooks";+import { useWorkspacePaths } from "@multica/core/paths";+import { docTreeOptions } from "@multica/core/docs";+import { FileText, Folder } from "@multica/ui/icons";+import { Button } from "@multica/ui/components/ui/button";+import { PageHeader } from "../../layout/page-header";+import { AppLink } from "../../navigation";+import { useT } from "../../i18n";+export function DocsHomePage({+ folderId = null,+}: {+ folderId?: string | null;+}) {+ const { t } = useT("docs");+ const wsId = useWorkspaceId();+ const p = useWorkspacePaths();+ const tree = useQuery(docTreeOptions(wsId));+ const folders =+ tree.data?.folders.filter((f) => f.parentId === folderId) ?? [];+ const docs = tree.data?.docs.filter((d) => d.folderId === folderId) ?? [];+ return (+ <div className="flex h-full min-h-0 flex-col">+ <PageHeader>+ <h1 className="text-body font-medium">+ {folderId+ ? tree.data?.folders.find((f) => f.id === folderId)?.title+ : t(($) => $.kb)}+ </h1>+ </PageHeader>+ <div className="min-h-0 flex-1 overflow-auto p-6">+ <div className="mx-auto max-w-3xl">+ {tree.isError ? (+ <Button onClick={() => void tree.refetch()}>+ {t(($) => $.editor.retry)}+ </Button>+ ) : tree.isPending ? (+ t(($) => $.history.loading)+ ) : !folders.length && !docs.length ? (+ <p className="text-body text-muted-foreground">+ {t(($) => $.tree.empty)}+ </p>+ ) : (+ <ul>+ {folders.map((f) => (+ <li key={f.id}>+ <AppLink+ href={p.docFolder(f.id)}+ className="flex items-center gap-3 rounded-md p-3 text-body hover:bg-surface-hover"+ >+ <Folder className="size-4" />+ <span className="truncate">{f.title}</span>+ </AppLink>+ </li>+ ))}+ {docs.map((d) => (+ <li key={d.id}>+ <AppLink+ href={p.docDetail(d.id)}+ className="flex items-center gap-3 rounded-md p-3 text-body hover:bg-surface-hover"+ >+ <FileText className="size-4" />+ <span className="truncate">+ {d.title || t(($) => $.untitled)}+ </span>+ </AppLink>+ </li>+ ))}+ </ul>+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/packages/views/docs/components/move-dialog.tsx b/packages/views/docs/components/move-dialog.tsxnew file mode 100644index 0000000000..a16dbb1442--- /dev/null+++ b/packages/views/docs/components/move-dialog.tsx@@ -0,0 +1,187 @@+"use client";++import { useMemo, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { toast } from "sonner";+import { BookOpen, Folder } from "@multica/ui/icons";+import { Button } from "@multica/ui/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import { cn } from "@multica/ui/lib/utils";+import {+ canMoveFolder,+ docTreeOptions,+ useMoveDoc,+ useMoveDocFolder,+} from "@multica/core/docs";+import { useWorkspaceId } from "@multica/core/hooks";+import type { DocFolder } from "@multica/core/types";+import { useT } from "../../i18n";++export type MoveTarget =+ | { kind: "doc"; id: string; title: string }+ | { kind: "folder"; id: string; title: string };++/** Folders in tree order with their depth, for a flat indented picker. */+function flattenFolders(+ folders: readonly DocFolder[],+): { folder: DocFolder; depth: number }[] {+ const ids = new Set(folders.map((f) => f.id));+ const byParent = new Map<string | null, DocFolder[]>();+ for (const f of folders) {+ const parent = f.parentId && ids.has(f.parentId) ? f.parentId : null;+ byParent.set(parent, [...(byParent.get(parent) ?? []), f]);+ }+ const out: { folder: DocFolder; depth: number }[] = [];+ const seen = new Set<string>();+ const walk = (parent: string | null, depth: number) => {+ const kids = [...(byParent.get(parent) ?? [])].sort((a, b) =>+ a.title.localeCompare(b.title, undefined, {+ sensitivity: "base",+ numeric: true,+ }),+ );+ for (const f of kids) {+ if (seen.has(f.id)) continue;+ seen.add(f.id);+ out.push({ folder: f, depth });+ walk(f.id, depth + 1);+ }+ };+ walk(null, 0);+ return out;+}++export function MoveDialog({+ target,+ onOpenChange,+}: {+ target: MoveTarget | null;+ onOpenChange: (open: boolean) => void;+}) {+ const { t } = useT("docs");+ const wsId = useWorkspaceId();+ const { data: tree } = useQuery(docTreeOptions(wsId));+ const moveDoc = useMoveDoc();+ const moveFolder = useMoveDocFolder();+ const [selected, setSelected] = useState<string | null | undefined>(+ undefined,+ );++ const folders = useMemo(() => tree?.folders ?? [], [tree]);+ const rows = useMemo(() => flattenFolders(folders), [folders]);+ const current =+ target?.kind === "doc"+ ? (tree?.docs.find((d) => d.id === target.id)?.folderId ?? null)+ : target+ ? (folders.find((f) => f.id === target.id)?.parentId ?? null)+ : null;++ const allowed = (folderId: string | null) =>+ !target ||+ target.kind === "doc" ||+ (folderId !== target.id && canMoveFolder(folders, target.id, folderId));++ const close = () => {+ setSelected(undefined);+ onOpenChange(false);+ };++ const submit = () => {+ if (!target || selected === undefined || selected === current)+ return close();+ const onError = (error: unknown) =>+ toast.error(+ error instanceof Error ? error.message : t(($) => $.errors.move),+ );+ const options = { onError, onSuccess: close };+ if (target.kind === "doc")+ moveDoc.mutate({ id: target.id, folderId: selected }, options);+ else moveFolder.mutate({ id: target.id, parentId: selected }, options);+ };++ const choice = selected === undefined ? current : selected;+ const option = (+ id: string | null,+ label: string,+ icon: React.ReactNode,+ depth = 0,+ ) => {+ const disabled = !allowed(id);+ return (+ <button+ key={id ?? "root"}+ type="button"+ role="option"+ aria-selected={choice === id}+ disabled={disabled}+ onClick={() => setSelected(id)}+ style={{ paddingLeft: 8 + depth * 16 }}+ className={cn(+ "flex h-8 w-full items-center gap-2 rounded-md pr-2 text-left text-body outline-none transition-colors focus-visible:outline-2 focus-visible:outline-ring disabled:cursor-not-allowed disabled:opacity-40",+ choice === id+ ? "bg-surface-selected text-surface-selected-foreground"+ : "hover:bg-surface-hover",+ )}+ >+ <span className="text-muted-foreground [&_svg]:size-4">{icon}</span>+ <span className="min-w-0 flex-1 truncate">{label}</span>+ {id === current && (+ <span className="shrink-0 text-caption text-faint-foreground">+ {t(($) => $.move.current)}+ </span>+ )}+ </button>+ );+ };++ return (+ <Dialog+ open={!!target}+ onOpenChange={(open) => (open ? onOpenChange(true) : close())}+ >+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle className="truncate">+ {t(($) => $.move.title, { title: target?.title ?? "" })}+ </DialogTitle>+ </DialogHeader>+ <div+ role="listbox"+ aria-label={t(($) => $.move.destination)}+ className="max-h-80 overflow-y-auto"+ >+ {option(+ null,+ t(($) => $.move.root),+ <BookOpen />,+ )}+ {rows.map(({ folder, depth }) =>+ option(folder.id, folder.title, <Folder />, depth + 1),+ )}+ </div>+ <DialogFooter>+ <Button variant="ghost" onClick={close}>+ {t(($) => $.actions.cancel)}+ </Button>+ <Button+ onClick={submit}+ disabled={+ selected === undefined ||+ selected === current ||+ moveDoc.isPending ||+ moveFolder.isPending+ }+ >+ {t(($) => $.move.confirm)}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/packages/views/docs/components/use-doc-draft.test.tsx b/packages/views/docs/components/use-doc-draft.test.tsxnew file mode 100644index 0000000000..36c7917df8--- /dev/null+++ b/packages/views/docs/components/use-doc-draft.test.tsx@@ -0,0 +1,362 @@+import { act, renderHook, cleanup } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { StrictMode, useEffect, type ReactNode } from "react";+import type { Doc } from "@multica/core/types";+import { api } from "@multica/core/api";+import { setDocDraft, useDocDraftStore } from "@multica/core/docs";+import {+ clearClientSessionData,+ setCurrentWorkspace,+} from "@multica/core/platform";+import { useDocDraft } from "./use-doc-draft";++vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-review" }));+const auth = vi.hoisted(() => ({+ user: { id: "u1" } as { id: string } | null,+}));+vi.mock("@multica/core/auth", () => ({+ useAuthStore: Object.assign(vi.fn(), { getState: () => auth }),+}));+vi.mock("@multica/core/api", () => ({+ api: { updateDoc: vi.fn(), getDoc: vi.fn() },+ ApiError: class ApiError extends Error {+ constructor(+ message: string,+ public status: number,+ public statusText: string,+ public body: unknown,+ ) {+ super(message);+ }+ },+}));++const doc: Doc = {+ id: "doc-review",+ workspaceId: "ws-review",+ folderId: null,+ title: "Runbook",+ content: "Original",+ revision: 1,+ versionCount: 1,+ createdByType: "member",+ createdById: "u1",+ updatedByType: "member",+ updatedById: "u1",+ createdAt: "2026-11-09T00:00:00Z",+ updatedAt: "2026-11-09T00:00:00Z",+};++beforeEach(async () => {+ vi.useFakeTimers();+ vi.clearAllMocks();+ auth.user = { id: "u1" };+ setCurrentWorkspace("review", "ws-review");+ await Promise.resolve();+ useDocDraftStore.getState().clearDraft();+ vi.mocked(api.updateDoc).mockImplementation(async (_id, data) => ({+ ...doc,+ ...data,+ revision: data.baseRevision + 1,+ versionCount: data.baseRevision + 1,+ }));+});+afterEach(() => {+ auth.user = null;+ cleanup();+ setCurrentWorkspace(null, null);+ vi.clearAllTimers();+ vi.useRealTimers();+});+function mount(strict = false) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ const view = renderHook(() => useDocDraft(doc), {+ wrapper: ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={client}>+ {strict ? <StrictMode>{children}</StrictMode> : children}+ </QueryClientProvider>+ ),+ });+ return { ...view, client };+}++function deferredSave() {+ let resolve!: (value: Doc) => void;+ const promise = new Promise<Doc>((done) => {+ resolve = done;+ });+ vi.mocked(api.updateDoc).mockReturnValueOnce(promise);+ return resolve;+}++it("saves after the debounce while the editor stays mounted", async () => {+ const view = mount();+ act(() => view.result.current.change({ content: "Edited" }));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1600);+ });+ expect(api.updateDoc).toHaveBeenCalledWith(doc.id, {+ title: doc.title,+ content: "Edited",+ baseRevision: 1,+ });+});++it("saves the last edit when navigating away during the debounce", async () => {+ const view = mount();+ act(() => view.result.current.change({ content: "Edited" }));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(100);+ });+ view.unmount();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(5000);+ });+ expect(api.updateDoc).toHaveBeenCalledWith(doc.id, {+ title: doc.title,+ content: "Edited",+ baseRevision: 1,+ });+ expect(api.updateDoc).toHaveBeenCalledTimes(1);+ expect(useDocDraftStore.getState().draft.entries).toEqual({});+});++it("keeps the debounce while typing and saves both the final title and content on exit", async () => {+ const view = mount(true);+ act(() => view.result.current.change({ title: "Renamed" }));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1000);+ });+ act(() => view.result.current.change({ content: "Final edit" }));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1000);+ });+ expect(api.updateDoc).not.toHaveBeenCalled();+ view.unmount();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0);+ });+ expect(api.updateDoc).toHaveBeenCalledExactlyOnceWith(doc.id, {+ title: "Renamed",+ content: "Final edit",+ baseRevision: 1,+ });+});++it("includes the final update published by child editor cleanup", async () => {+ const client = new QueryClient();+ function EditorCleanup({+ change,+ }: {+ change: ReturnType<typeof useDocDraft>["change"];+ }) {+ useEffect(() => () => change({ content: "Last editor update" }), [change]);+ return null;+ }+ function Editor() {+ const { change } = useDocDraft(doc);+ return <EditorCleanup change={change} />;+ }+ const { render } = await import("@testing-library/react");+ const view = render(+ <QueryClientProvider client={client}>+ <Editor />+ </QueryClientProvider>,+ );+ view.unmount();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0);+ });+ expect(api.updateDoc).toHaveBeenCalledExactlyOnceWith(doc.id, {+ title: doc.title,+ content: "Last editor update",+ baseRevision: 1,+ });+});++it("drains edits made during an in-flight save after navigation using its new revision", async () => {+ const resolve = deferredSave();+ const view = mount();+ act(() => view.result.current.change({ content: "First edit" }));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1500);+ });+ act(() =>+ view.result.current.change({ title: "Renamed", content: "Final edit" }),+ );+ view.unmount();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0);+ });+ expect(api.updateDoc).toHaveBeenCalledTimes(1);++ await act(async () => {+ resolve({ ...doc, content: "First edit", revision: 2 });+ });++ expect(api.updateDoc).toHaveBeenNthCalledWith(2, doc.id, {+ title: "Renamed",+ content: "Final edit",+ baseRevision: 2,+ });+ expect(useDocDraftStore.getState().draft.entries).toEqual({});+});++it.each(["error", "conflict"])(+ "preserves the local draft on %s without retrying on unmount",+ async (kind) => {+ const { ApiError } = await import("@multica/core/api");+ vi.mocked(api.updateDoc).mockRejectedValue(+ kind === "conflict"+ ? new ApiError("Changed", 409, "Conflict", {+ code: "revision_conflict",+ })+ : new Error("Offline"),+ );+ const view = mount();+ act(() => view.result.current.change({ content: "Local edit" }));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1500);+ });+ expect(view.result.current.status).toBe(kind);+ view.unmount();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(5000);+ });+ expect(api.updateDoc).toHaveBeenCalledTimes(1);+ expect(+ useDocDraftStore.getState().draft.entries["ws-review:doc-review"],+ ).toMatchObject({+ content: "Local edit",+ baseContent: "Original",+ baseRevision: 1,+ });+ },+);++it("retains the draft if the navigation flush conflicts and preserves it when reloading", async () => {+ const { ApiError } = await import("@multica/core/api");+ vi.mocked(api.updateDoc).mockRejectedValue(+ new ApiError("Changed", 409, "Conflict", { code: "revision_conflict" }),+ );+ const view = mount();+ act(() => view.result.current.change({ content: "Local edit" }));+ view.unmount();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(5000);+ });+ expect(api.updateDoc).toHaveBeenCalledTimes(1);+ const reopened = mount();+ expect(reopened.result.current.draft.content).toBe("Local edit");+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1500);+ });+ expect(reopened.result.current.status).toBe("conflict");+ vi.mocked(api.getDoc).mockResolvedValue({+ ...doc,+ content: "Remote edit",+ revision: 2,+ });+ await act(async () => {+ await reopened.result.current.reload();+ });+ expect(reopened.result.current.draft).toMatchObject({+ content: "Remote edit",+ baseRevision: 2,+ backup: { title: doc.title, content: "Local edit" },+ });+});++it("does not flush or resurrect drafts after session cleanup", async () => {+ const view = mount();+ act(() => view.result.current.change({ content: "A's draft" }));+ act(() => {+ clearClientSessionData(view.client);+ auth.user = null;+ });+ view.unmount();+ // A pending child editor callback must not restore the erased draft.+ act(() => view.result.current.change({ content: "A's pending update" }));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(5000);+ });+ expect(api.updateDoc).not.toHaveBeenCalled();+ expect(useDocDraftStore.getState().draft.entries).toEqual({});+});++it("does not repopulate another account's cache or draft from a late save response", async () => {+ const resolve = deferredSave();+ const view = mount();+ act(() => view.result.current.change({ content: "A's edit" }));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1500);+ });+ act(() => {+ clearClientSessionData(view.client);+ auth.user = { id: "u2" };+ setDocDraft("ws-review:doc-review", {+ title: doc.title,+ content: "B's edit",+ baseTitle: doc.title,+ baseContent: doc.content,+ baseRevision: 1,+ });+ });+ const nextAccountDrafts = useDocDraftStore.getState().draft.entries;+ view.unmount();+ await act(async () => {+ resolve({ ...doc, content: "A's edit", revision: 2 });+ });+ expect(view.client.getQueryCache().getAll()).toEqual([]);+ expect(useDocDraftStore.getState().draft.entries).toEqual(nextAccountDrafts);+ expect(api.updateDoc).toHaveBeenCalledTimes(1);+});++it("does not send the old document to a different workspace on exit", async () => {+ const view = mount();+ act(() => view.result.current.change({ content: "A's draft" }));+ act(() => setCurrentWorkspace("other", "ws-other"));+ view.unmount();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(5000);+ });+ expect(api.updateDoc).not.toHaveBeenCalled();+});++it("settles an in-flight save without writing the old workspace's draft into the new one", async () => {+ const resolve = deferredSave();+ const view = mount();+ act(() => view.result.current.change({ content: "A's edit" }));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1500);+ });+ act(() => setCurrentWorkspace("other", "ws-other"));+ await act(async () => {+ resolve({ ...doc, content: "A's edit", revision: 2 });+ });+ expect(view.result.current.status).toBe("saved");+ expect(view.client.getQueryCache().getAll()).toEqual([]);+ expect(useDocDraftStore.getState().draft.entries).toEqual({});+});++it("keeps showing the saved content while the doc prop catches up", async () => {+ const view = mount();+ act(() => view.result.current.change({ content: "Edited at the end" }));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1600);+ });+ expect(api.updateDoc).toHaveBeenCalledTimes(1);+ // The hook still receives the pre-save `doc`; the editor must not be handed+ // the old content (it would reset the caret).+ expect(view.result.current.draft.content).toBe("Edited at the end");+ expect(view.result.current.dirty).toBe(false);+ act(() => view.result.current.change({ title: "Renamed" }));+ expect(view.result.current.draft).toMatchObject({+ title: "Renamed",+ content: "Edited at the end",+ baseRevision: 2,+ });+});diff --git a/packages/views/docs/components/use-doc-draft.ts b/packages/views/docs/components/use-doc-draft.tsnew file mode 100644index 0000000000..ef75dd0bc4--- /dev/null+++ b/packages/views/docs/components/use-doc-draft.ts@@ -0,0 +1,168 @@+"use client";+import { useEffect, useRef, useState } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { api } from "@multica/core/api";+import { useAuthStore } from "@multica/core/auth";+import { useWorkspaceId } from "@multica/core/hooks";+import { getCurrentWsId } from "@multica/core/platform";+import {+ docKeys,+ isDocRevisionConflict,+ setDocDraft,+ removeDocDraft,+ useDocDraftStore,+ type DocDraft,+} from "@multica/core/docs";+import type { Doc } from "@multica/core/types";+const fromDoc = (doc: Doc): DocDraft => ({+ title: doc.title,+ content: doc.content,+ baseTitle: doc.title,+ baseContent: doc.content,+ baseRevision: doc.revision,+});+export function useDocDraft(doc: Doc) {+ const wsId = useWorkspaceId();+ const key = `${wsId}:${doc.id}`;+ const draft = useDocDraftStore((s) => s.draft.entries[key]);+ const qc = useQueryClient();+ const [status, setStatus] = useState<+ "saved" | "saving" | "error" | "conflict"+ >("saved");+ const saving = useRef(false);+ const alive = useRef(true);+ const ownerId = useRef(useAuthStore.getState().user?.id).current;+ const statusRef = useRef(status);+ const saveRef = useRef<() => Promise<void>>(async () => {});+ // The response of our last save. Clearing the draft re-renders this hook+ // before the parent passes the refreshed `doc`, so falling back to the prop+ // would briefly hand the editor the pre-save content and reset its caret.+ const savedDoc = useRef<Doc | null>(null);+ const latestDoc =+ savedDoc.current && savedDoc.current.revision > doc.revision+ ? savedDoc.current+ : doc;+ const inScope = () =>+ getCurrentWsId() === wsId && useAuthStore.getState().user?.id === ownerId;+ const updateStatus = (next: typeof status) => {+ statusRef.current = next;+ if (alive.current) setStatus(next);+ };+ useEffect(() => {+ alive.current = true;+ return () => {+ alive.current = false;+ // Child editor cleanup can still publish its final pending update.+ // StrictMode's effect replay remounts before this microtask runs.+ queueMicrotask(() => {+ if (!alive.current && statusRef.current === "saved")+ void saveRef.current();+ });+ };+ }, []);+ useEffect(() => {+ const current = useDocDraftStore.getState().draft.entries[key];+ if (+ current &&+ !saving.current &&+ current.title === current.baseTitle &&+ current.content === current.baseContent+ ) {+ if (!current.backup) removeDocDraft(key);+ else if (current.baseRevision !== doc.revision)+ setDocDraft(key, { ...fromDoc(doc), backup: current.backup });+ }+ }, [doc, key]);+ const value = draft ?? fromDoc(latestDoc);+ const dirty =+ value.title !== value.baseTitle || value.content !== value.baseContent;+ const save = async () => {+ const sent = useDocDraftStore.getState().draft.entries[key];+ if (+ !sent ||+ !inScope() ||+ saving.current ||+ (sent.title === sent.baseTitle && sent.content === sent.baseContent)+ )+ return;+ saving.current = true;+ updateStatus("saving");+ let saved = false;+ try {+ const updated = await api.updateDoc(doc.id, {+ baseRevision: sent.baseRevision,+ title: sent.title,+ content: sent.content,+ });+ const current = useDocDraftStore.getState().draft.entries[key];+ // Session cleanup must stay final even if an older request completes.+ if (!inScope() || !current) {+ updateStatus("saved");+ return;+ }+ qc.setQueryData(docKeys.detail(wsId, doc.id), updated);+ savedDoc.current = updated;+ const next = {+ ...current,+ title: current.title === sent.title ? updated.title : current.title,+ baseRevision: updated.revision,+ baseTitle: updated.title,+ baseContent: updated.content,+ };+ if (+ next.title === next.baseTitle &&+ next.content === next.baseContent &&+ !next.backup+ )+ removeDocDraft(key);+ else setDocDraft(key, next);+ void qc.invalidateQueries({ queryKey: docKeys.all(wsId) });+ saved = true;+ updateStatus("saved");+ } catch (error) {+ if (!inScope()) {+ updateStatus("saved");+ return;+ }+ updateStatus(isDocRevisionConflict(error) ? "conflict" : "error");+ if (isDocRevisionConflict(error))+ void qc.invalidateQueries({ queryKey: docKeys.detail(wsId, doc.id) });+ } finally {+ saving.current = false;+ // Edits made during the request still need saving after navigation.+ if (saved && !alive.current) void save();+ }+ };+ saveRef.current = save;+ useEffect(() => {+ if (!dirty || status !== "saved") return;+ const timer = setTimeout(() => {+ void save();+ }, 1500);+ return () => clearTimeout(timer);+ });+ const change = (patch: Partial<Pick<DocDraft, "title" | "content">>) => {+ if (!inScope()) return;+ const current =+ useDocDraftStore.getState().draft.entries[key] ?? fromDoc(latestDoc);+ setDocDraft(key, { ...current, ...patch });+ };+ const reload = async () => {+ try {+ const latest = await api.getDoc(doc.id);+ if (!inScope()) return;+ const current = useDocDraftStore.getState().draft.entries[key];+ setDocDraft(key, {+ ...fromDoc(latest),+ backup: current+ ? { title: current.title, content: current.content }+ : undefined,+ });+ qc.setQueryData(docKeys.detail(wsId, doc.id), latest);+ updateStatus("saved");+ } catch {+ if (inScope()) updateStatus("error");+ }+ };+ return { draft: value, status, dirty, change, retry: save, reload };+}diff --git a/packages/views/docs/index.ts b/packages/views/docs/index.tsnew file mode 100644index 0000000000..a127c71dc7--- /dev/null+++ b/packages/views/docs/index.ts@@ -0,0 +1,3 @@+export { DocsHomePage } from "./components/docs-home-page";+export { DocPage } from "./components/doc-page";+export { DocHistoryPage } from "./components/doc-history-page";diff --git a/packages/views/editor/block-handle.tsx b/packages/views/editor/block-handle.tsxnew file mode 100644index 0000000000..8d23a7fd7f--- /dev/null+++ b/packages/views/editor/block-handle.tsx@@ -0,0 +1,334 @@+"use client";++import {+ useEffect,+ useRef,+ useState,+ type DragEvent as ReactDragEvent,+ type RefObject,+} from "react";+import type { Editor } from "@tiptap/core";+import type { EditorView } from "@tiptap/pm/view";+import { NodeSelection } from "@tiptap/pm/state";+import {+ Copy,+ GripVertical,+ Plus,+ Trash2,+} from "@multica/ui/icons";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+} from "@multica/ui/components/ui/dropdown-menu";+import { cn } from "@multica/ui/lib/utils";+import { useT } from "../i18n";+import {+ TEXT_BLOCK_KINDS,+ canTurnInto,+ currentTextBlockKind,+ deleteBlock,+ duplicateBlock,+ openInsertMenuBelow,+ resolveBlockTarget,+ turnBlockInto,+ type BlockTarget,+ type TextBlockKind,+} from "./extensions/block-commands";+import { BLOCK_MENU_ITEMS } from "./extensions/block-insert-suggestion";++/** Height of the handle row; it is centered on the block's first line. */+const HANDLE_HEIGHT = 24;+/** Width of "+" and grip together, plus the gap to the block. */+const HANDLE_OFFSET = 48;+/** A bullet or number sits left of its list item's box; clear it. */+const LIST_MARKER_GAP = 20;++interface HandlePosition {+ target: BlockTarget;+ /** Hover area: from the handle to the block's left edge, the block's full height. */+ top: number;+ left: number;+ width: number;+ height: number;+ /** Offset of the buttons inside the area, centered on the first line. */+ buttonTop: number;+}++/** How long the handle survives the pointer leaving the editor on its way over. */+const HIDE_DELAY_MS = 200;++/** Vertical center of the block's first line, so the handle lines up with text. */+function firstLineCenter(view: EditorView, target: BlockTarget): number | null {+ const { node, pos } = target;+ let textStart: number | null = node.isTextblock ? pos + 1 : null;+ if (textStart === null) {+ node.descendants((child, offset) => {+ if (textStart !== null) return false;+ if (child.isTextblock) {+ textStart = pos + 1 + offset + 1;+ return false;+ }+ return true;+ });+ }+ if (textStart === null) return null;+ try {+ const coords = view.coordsAtPos(textStart);+ return (coords.top + coords.bottom) / 2;+ } catch {+ return null;+ }+}++/** Which block sits under the pointer's row, and where its handle goes. */+export function measureBlockHandle(+ editor: Editor,+ container: HTMLElement,+ clientX: number,+ clientY: number,+): HandlePosition | null {+ if (editor.isDestroyed || !editor.isEditable) return null;+ const { view } = editor;+ const editorRect = view.dom.getBoundingClientRect();+ if (clientY < editorRect.top || clientY > editorRect.bottom) return null;+ // Probe inside the text column so a pointer in the margin still finds its row.+ const left = Math.min(Math.max(clientX, editorRect.left + 1), editorRect.right - 1);+ const hit = view.posAtCoords({ left, top: clientY });+ if (!hit) return null;+ const target = resolveBlockTarget(view.state.doc, hit.inside >= 0 ? hit.inside : hit.pos);+ if (!target) return null;+ const dom = view.nodeDOM(target.pos);+ if (!(dom instanceof HTMLElement)) return null;+ const containerRect = container.getBoundingClientRect();+ const blockRect = dom.getBoundingClientRect();+ const center = firstLineCenter(view, target) ?? blockRect.top + HANDLE_HEIGHT / 2;+ const markerGap = target.node.type.name === "listItem" ? LIST_MARKER_GAP : 0;+ // The area runs right up to the block and down its whole height, so moving+ // the pointer left from any line of the block lands on the handle instead of+ // crossing empty margin, which would leave the editor and hide it.+ return {+ target,+ top: blockRect.top - containerRect.top,+ left: blockRect.left - containerRect.left - HANDLE_OFFSET - markerGap,+ width: HANDLE_OFFSET + markerGap,+ height: Math.max(blockRect.height, HANDLE_HEIGHT),+ buttonTop: Math.max(0, center - blockRect.top - HANDLE_HEIGHT / 2),+ };+}++/** The kind a list item reads as is its list's kind. */+function targetKind(editor: Editor, target: BlockTarget): TextBlockKind | null {+ if (target.node.type.name === "listItem") {+ return currentTextBlockKind(editor.state.doc.resolve(target.pos).parent);+ }+ return currentTextBlockKind(target.node);+}++const KIND_ICONS = new Map(BLOCK_MENU_ITEMS.map((item) => [item.kind, item.icon]));++/**+ * Hover handle for document blocks. "+" opens the `/` menu on a new line+ * below; the grip drags the block (ProseMirror moves it on drop) or opens+ * turn-into, duplicate and delete.+ */+export function BlockHandle({+ editor,+ containerRef,+}: {+ editor: Editor;+ containerRef: RefObject<HTMLDivElement | null>;+}) {+ const { t } = useT("editor");+ const [position, setPosition] = useState<HandlePosition | null>(null);+ const [menuOpen, setMenuOpen] = useState(false);+ const gripRef = useRef<HTMLButtonElement>(null);+ // While the menu is open or a drag is in flight the handle must stay on its+ // block; the listeners read these without re-subscribing.+ const pinnedRef = useRef(false);+ pinnedRef.current = menuOpen;+ const draggingRef = useRef(false);++ useEffect(() => {+ const container = containerRef.current;+ if (!container) return;+ let frame = 0;+ let hideTimer: ReturnType<typeof setTimeout> | undefined;+ const cancelHide = () => {+ clearTimeout(hideTimer);+ hideTimer = undefined;+ };+ const hide = () => {+ cancelHide();+ if (pinnedRef.current || draggingRef.current) return;+ cancelAnimationFrame(frame);+ setPosition(null);+ };+ // Leaving the editor is often the pointer heading for the handle along a+ // path that grazes outside it; give it a moment to arrive.+ const hideSoon = () => {+ cancelHide();+ hideTimer = setTimeout(hide, HIDE_DELAY_MS);+ };+ const onMove = (event: MouseEvent) => {+ cancelHide();+ // A held button means a text selection or a drag is under way; moving+ // the handle then would detach the drag source.+ if (pinnedRef.current || draggingRef.current || event.buttons !== 0) return;+ if ((event.target as Element | null)?.closest?.("[data-block-handle]")) return;+ const { clientX, clientY } = event;+ cancelAnimationFrame(frame);+ frame = requestAnimationFrame(() => {+ setPosition(measureBlockHandle(editor, container, clientX, clientY));+ });+ };+ container.addEventListener("mousemove", onMove);+ container.addEventListener("mouseleave", hideSoon);+ // Typing and remote updates move blocks under a handle; hide until the+ // pointer moves again.+ editor.view.dom.addEventListener("keydown", hide);+ editor.on("update", hide);+ return () => {+ cancelAnimationFrame(frame);+ cancelHide();+ container.removeEventListener("mousemove", onMove);+ container.removeEventListener("mouseleave", hideSoon);+ editor.view.dom.removeEventListener("keydown", hide);+ editor.off("update", hide);+ };+ }, [editor, containerRef]);++ if (!position) return null;+ const { target } = position;+ const current = targetKind(editor, target);++ const run = (action: () => void) => {+ action();+ setMenuOpen(false);+ setPosition(null);+ };++ const onDragStart = (event: ReactDragEvent<HTMLButtonElement>) => {+ const { view } = editor;+ // Not dispatched as the editor selection: a selected block would raise the+ // formatting toolbar over the drop targets for the whole drag.+ const selection = NodeSelection.create(view.state.doc, target.pos);+ const slice = selection.content();+ const { dom, text } = view.serializeForClipboard(slice);+ event.dataTransfer.clearData();+ event.dataTransfer.setData("text/html", dom.innerHTML);+ event.dataTransfer.setData("text/plain", text);+ event.dataTransfer.effectAllowed = "copyMove";+ const blockDom = view.nodeDOM(target.pos);+ if (blockDom instanceof HTMLElement) event.dataTransfer.setDragImage(blockDom, 0, 0);+ // ProseMirror's own drop handler reads this: it inserts the slice at the+ // drop point and removes the original through `node`. `node` is part of+ // prosemirror-view's runtime Dragging but missing from its typings.+ view.dragging = { slice, move: true, node: selection } as EditorView["dragging"];+ draggingRef.current = true;+ };++ const onDragEnd = () => {+ draggingRef.current = false;+ setPosition(null);+ };++ return (+ <div+ data-block-handle=""+ className="absolute z-10"+ style={{+ top: position.top,+ left: position.left,+ width: position.width,+ height: position.height,+ }}+ >+ <div+ className="absolute left-0 flex items-center gap-0.5"+ style={{ top: position.buttonTop, height: HANDLE_HEIGHT }}+ >+ <button+ type="button"+ aria-label={t(($) => $.block_handle.add)}+ title={t(($) => $.block_handle.add)}+ className="flex size-6 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"+ // Keep the caret in the editor; the click places it on the new line.+ onMouseDown={(event) => event.preventDefault()}+ onClick={() => run(() => openInsertMenuBelow(editor, target))}+ >+ <Plus className="size-4" />+ </button>+ <button+ ref={gripRef}+ type="button"+ draggable+ aria-label={t(($) => $.block_handle.options)}+ title={t(($) => $.block_handle.options)}+ aria-haspopup="menu"+ aria-expanded={menuOpen}+ className="flex h-6 w-4 cursor-grab items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-accent hover:text-foreground active:cursor-grabbing"+ onClick={() => setMenuOpen(true)}+ onDragStart={onDragStart}+ onDragEnd={onDragEnd}+ >+ <GripVertical className="size-4" />+ </button>+ </div>+ <DropdownMenu+ open={menuOpen}+ onOpenChange={(open) => {+ setMenuOpen(open);+ if (!open) setPosition(null);+ }}+ >+ <DropdownMenuContent anchor={gripRef} align="start" className="min-w-44">+ {canTurnInto(target.node) && (+ <>+ <DropdownMenuGroup>+ <DropdownMenuLabel>{t(($) => $.block_handle.turn_into)}</DropdownMenuLabel>+ {/* A submenu would be closed as a "sibling" of this anchored,+ trigger-less menu, so the block types sit inline as icons. */}+ <div className="grid grid-cols-5 gap-0.5 px-1 pb-1">+ {TEXT_BLOCK_KINDS.map((kind) => {+ const Icon = KIND_ICONS.get(kind);+ const label = t(($) => $.block_menu.blocks[kind]);+ return (+ <DropdownMenuItem+ key={kind}+ aria-label={label}+ title={label}+ className={cn(+ "size-8 justify-center p-0",+ current === kind && "bg-accent text-accent-foreground",+ )}+ onClick={() => run(() => turnBlockInto(editor, target, kind))}+ >+ {Icon && <Icon />}+ </DropdownMenuItem>+ );+ })}+ </div>+ </DropdownMenuGroup>+ <DropdownMenuSeparator />+ </>+ )}+ <DropdownMenuItem onClick={() => run(() => duplicateBlock(editor, target))}>+ <Copy />+ {t(($) => $.block_handle.duplicate)}+ </DropdownMenuItem>+ <DropdownMenuItem+ variant="destructive"+ onClick={() => run(() => deleteBlock(editor, target))}+ >+ <Trash2 />+ {t(($) => $.block_handle.delete)}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+}diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsxindex 992db8578b..a3878b4cc1 100644--- a/packages/views/editor/content-editor.tsx+++ b/packages/views/editor/content-editor.tsx@@ -69,6 +69,7 @@ import { repairEmptyListItems } from "./utils/repair-list-items";import { resolveClickIntent, useAppOrigin, useOptionalNavigation } from "../navigation";import { openLink, isMentionHref } from "./utils/link-handler";import { EditorBubbleMenu } from "./bubble-menu";+import { BlockHandle } from "./block-handle";import { posFromAnchor, type TextAnchor } from "./text-anchor";import { insertDictation } from "./utils/insert-dictation";import { useLinkHover, LinkHoverCard } from "./link-hover-card";@@ -205,9 +206,16 @@ interface ContentEditorBaseProps {/*** Which `/` menu to show when enableSlashCommands is true: "skill" (default)* lists the active agent's skills (chat); "command" merges Issue quick- * actions, skills matching a nonempty query, and built-ins such as /note.+ * actions, skills matching a nonempty query, and built-ins such as /note;+ * "blocks" inserts document blocks (Docs).*/- slashCommandMode?: "skill" | "command";+ slashCommandMode?: "skill" | "command" | "blocks";+ /**+ * Show a hover handle beside each block: "+" opens the block menu on a new+ * line below, and the grip drags the block or opens turn-into, duplicate and+ * delete. For long-form documents; pair it with `slashCommandMode="blocks"`.+ */+ showBlockHandles?: boolean;/*** Quick actions and Issue target-agent skills for the "command" `/` menu,* plus the resolver that turns a quick-action pick into draft text. Read@@ -397,6 +405,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(mentionContextItems,enableSlashCommands = false,slashCommandMode = "skill",+ showBlockHandles = false,quickActionMenu,attachments,flushPendingOnUnmount = false,@@ -1076,6 +1085,9 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(onMouseDown={handleContainerMouseDown}><EditorContent className="flex flex-1 flex-col" editor={editor} />+ {showBlockHandles && editor && (+ <BlockHandle editor={editor} containerRef={wrapperRef} />+ )}{showBubbleMenu && (<EditorBubbleMenu editor={editor} currentIssueId={currentIssueId} selectionAction={selectionAction} />)}diff --git a/packages/views/editor/extensions/block-commands.test.ts b/packages/views/editor/extensions/block-commands.test.tsnew file mode 100644index 0000000000..a4cdf28f49--- /dev/null+++ b/packages/views/editor/extensions/block-commands.test.ts@@ -0,0 +1,222 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { Editor } from "@tiptap/core";+import StarterKit from "@tiptap/starter-kit";+import { Markdown } from "@tiptap/markdown";+import { TaskItem, TaskList } from "@tiptap/extension-list";+import { Table, TableCell, TableHeader, TableRow } from "@tiptap/extension-table";+import { ImageExtension } from "./index";+import { CodeBlockExtension } from "./code-block";+import { codeLowlight } from "../syntax-highlight";+import {+ SuggestionTriggerArmingExtension,+ isTriggerArmedAt,+} from "./suggestion-trigger-arming";+import {+ canTurnInto,+ deleteBlock,+ duplicateBlock,+ insertBlock,+ openInsertMenuBelow,+ resolveBlockTarget,+ turnBlockInto,+} from "./block-commands";++const editors: Editor[] = [];++function makeEditor(markdown: string) {+ const element = document.createElement("div");+ document.body.appendChild(element);+ const editor = new Editor({+ element,+ extensions: [+ StarterKit.configure({ codeBlock: false }),+ CodeBlockExtension.configure({ lowlight: codeLowlight }),+ TaskList,+ TaskItem.configure({ nested: true }),+ Table,+ TableRow,+ TableHeader,+ TableCell,+ ImageExtension,+ Markdown,+ SuggestionTriggerArmingExtension,+ ],+ content: markdown,+ contentType: "markdown",+ });+ editors.push(editor);+ return editor;+}++const md = (editor: Editor) => editor.getMarkdown().trim();++/** Document position of the first occurrence of `text`. */+function posOf(editor: Editor, text: string): number {+ let found = -1;+ editor.state.doc.descendants((node, pos) => {+ if (found !== -1) return false;+ const index = node.isText ? (node.text ?? "").indexOf(text) : -1;+ if (index !== -1) found = pos + index;+ return true;+ });+ if (found === -1) throw new Error(`text not found: ${text}`);+ return found;+}++function targetAt(editor: Editor, text: string) {+ const target = resolveBlockTarget(editor.state.doc, posOf(editor, text));+ if (!target) throw new Error(`no block for ${text}`);+ return target;+}++afterEach(() => {+ for (const editor of editors.splice(0)) editor.destroy();+});++describe("resolveBlockTarget", () => {+ it("returns the top-level block around text", () => {+ const editor = makeEditor("# Title\n\nBody text");+ expect(targetAt(editor, "Body").node.type.name).toBe("paragraph");+ expect(targetAt(editor, "Title").node.type.name).toBe("heading");+ });++ it("returns the innermost list item, so nested items move on their own", () => {+ const editor = makeEditor("- outer\n - inner");+ const inner = targetAt(editor, "inner");+ expect(inner.node.type.name).toBe("listItem");+ expect(inner.node.textContent).toBe("inner");+ });++ it("treats a whole table as one block", () => {+ const editor = makeEditor("| a | b |\n| --- | --- |\n| c | d |");+ expect(targetAt(editor, "d").node.type.name).toBe("table");+ expect(canTurnInto(targetAt(editor, "d").node)).toBe(false);+ });+});++describe("turnBlockInto", () => {+ it("turns a paragraph into a heading", () => {+ const editor = makeEditor("First\n\nSecond");+ turnBlockInto(editor, targetAt(editor, "Second"), "heading2");+ expect(md(editor)).toBe("First\n\n## Second");+ expect(editor.state.selection.empty).toBe(true);+ });++ it("lifts a list item out of its list when it becomes text", () => {+ const editor = makeEditor("- one\n- two");+ turnBlockInto(editor, targetAt(editor, "two"), "paragraph");+ expect(md(editor)).toBe("- one\n\ntwo");+ });++ it("turns a heading into a task list", () => {+ const editor = makeEditor("## Ship it");+ turnBlockInto(editor, targetAt(editor, "Ship"), "taskList");+ expect(md(editor)).toBe("- [ ] Ship it");+ });+});++describe("duplicateBlock and deleteBlock", () => {+ it("duplicates a block right below itself", () => {+ const editor = makeEditor("Keep\n\nCopy me");+ duplicateBlock(editor, targetAt(editor, "Copy"));+ expect(md(editor)).toBe("Keep\n\nCopy me\n\nCopy me");+ });++ it("deletes only the targeted list item", () => {+ const editor = makeEditor("- one\n- two\n- three");+ deleteBlock(editor, targetAt(editor, "two"));+ expect(md(editor)).toBe("- one\n- three");+ });+});++describe("openInsertMenuBelow", () => {+ it("opens an armed `/` on a new line below a non-empty block", () => {+ const editor = makeEditor("Above\n\nBelow");+ openInsertMenuBelow(editor, targetAt(editor, "Above"));+ expect(md(editor)).toBe("Above\n\n/\n\nBelow");+ const slash = editor.state.selection.from - 1;+ expect(editor.state.doc.textBetween(slash, slash + 1)).toBe("/");+ expect(isTriggerArmedAt(editor, slash)).toBe(true);+ });++ it("reuses an empty line instead of adding another", () => {+ const editor = makeEditor("Above");+ editor.commands.insertContentAt(editor.state.doc.content.size, { type: "paragraph" });+ const blocks = editor.state.doc.childCount;+ const empty = resolveBlockTarget(editor.state.doc, editor.state.doc.content.size - 1)!;+ openInsertMenuBelow(editor, empty);+ expect(editor.state.doc.childCount).toBe(blocks);+ expect(md(editor)).toBe("Above\n\n/");+ });++ it("adds a sibling item below a list item", () => {+ const editor = makeEditor("- one\n- two");+ openInsertMenuBelow(editor, targetAt(editor, "one"));+ expect(md(editor)).toBe("- one\n- /\n- two");+ });+});++describe("insertBlock", () => {+ function typedSlash(editor: Editor, query = "") {+ const end = editor.state.doc.content.size - 1;+ editor.commands.insertContentAt(end, `/${query}`);+ const to = editor.state.selection.from;+ return { from: to - query.length - 1, to };+ }++ it("replaces the typed query with the chosen heading", () => {+ const editor = makeEditor("Intro");+ editor.commands.insertContentAt(editor.state.doc.content.size, { type: "paragraph" });+ const range = typedSlash(editor, "h1");+ insertBlock(editor, range, "heading1");+ editor.commands.insertContent("Plan");+ expect(md(editor)).toBe("Intro\n\n# Plan");+ });++ it("inserts a Mermaid code block", () => {+ const editor = makeEditor("");+ const range = typedSlash(editor, "mer");+ insertBlock(editor, range, "mermaid");+ editor.commands.insertContent("graph TD");+ expect(md(editor)).toBe("```mermaid\ngraph TD\n```");+ });++ it("inserts a table with a header row", () => {+ const editor = makeEditor("");+ insertBlock(editor, typedSlash(editor), "table");+ let table = null as null | { rows: number; header: string };+ editor.state.doc.descendants((node) => {+ if (node.type.name === "table") {+ table = { rows: node.childCount, header: node.firstChild!.firstChild!.type.name };+ return false;+ }+ return true;+ });+ expect(table).toEqual({ rows: 3, header: "tableHeader" });+ });++ it("uploads picked images at the caret", async () => {+ const editor = makeEditor("");+ const file = new File(["png"], "shot.png", { type: "image/png" });+ const upload = vi.fn(async () => ({+ id: "att-1",+ filename: "shot.png",+ content_type: "image/png",+ link: "https://files.test/att-1",+ markdownLink: "https://app.test/api/attachments/att-1/download",+ }));+ URL.createObjectURL = vi.fn(() => "blob:shot");+ URL.revokeObjectURL = vi.fn();+ insertBlock(editor, typedSlash(editor, "img"), "image", {+ upload: upload as never,+ pick: async (accept) => {+ expect(accept).toBe("image/*");+ return [file];+ },+ });+ await vi.waitFor(() => expect(upload).toHaveBeenCalledWith(file, expect.any(String)));+ await vi.waitFor(() =>+ expect(md(editor)).toBe(""),+ );+ });+});diff --git a/packages/views/editor/extensions/block-commands.ts b/packages/views/editor/extensions/block-commands.tsnew file mode 100644index 0000000000..366cc27746--- /dev/null+++ b/packages/views/editor/extensions/block-commands.ts@@ -0,0 +1,284 @@+import type { ChainedCommands, Editor, Range } from "@tiptap/core";+import type { Node as ProseMirrorNode } from "@tiptap/pm/model";+import { TextSelection } from "@tiptap/pm/state";+import type { UploadResult } from "@multica/core/hooks/use-file-upload";+import { uploadAndInsertFile } from "./file-upload";+import { armSuggestionTrigger } from "./suggestion-trigger-arming";++/**+ * Block-level authoring commands shared by the `/` insert menu and the block+ * handle. Every block here has a plain Markdown form, so what an agent reads+ * back through `doc get` is exactly what the author saw.+ */++/** Block types a text block can be turned into. */+export type TextBlockKind =+ | "paragraph"+ | "heading1"+ | "heading2"+ | "heading3"+ | "bulletList"+ | "orderedList"+ | "taskList"+ | "blockquote"+ | "codeBlock";++/** Everything the `/` menu can insert. */+export type InsertBlockKind =+ | TextBlockKind+ | "mermaid"+ | "table"+ | "divider"+ | "image"+ | "file";++export const TEXT_BLOCK_KINDS: readonly TextBlockKind[] = [+ "paragraph",+ "heading1",+ "heading2",+ "heading3",+ "bulletList",+ "orderedList",+ "taskList",+ "blockquote",+ "codeBlock",+];++export type UploadHandler = (+ file: File,+ uploadId: string,+) => Promise<UploadResult | null>;++/**+ * Lift the selection out of lists and quotes, then give it `kind`. Clearing+ * first is what makes "turn into" predictable: a list item turned into a+ * heading leaves the list instead of failing on the list's content rule.+ */+function applyTextBlock(chain: ChainedCommands, kind: TextBlockKind): ChainedCommands {+ const cleared = chain.clearNodes();+ switch (kind) {+ case "paragraph":+ return cleared;+ case "heading1":+ return cleared.setHeading({ level: 1 });+ case "heading2":+ return cleared.setHeading({ level: 2 });+ case "heading3":+ return cleared.setHeading({ level: 3 });+ case "bulletList":+ return cleared.toggleBulletList();+ case "orderedList":+ return cleared.toggleOrderedList();+ case "taskList":+ return cleared.toggleTaskList();+ case "blockquote":+ return cleared.toggleBlockquote();+ case "codeBlock":+ return cleared.setCodeBlock();+ }+}++/** Open the platform file picker; resolves with the chosen files (possibly none). */+export function pickFiles(accept?: string): Promise<File[]> {+ return new Promise((resolve) => {+ const input = document.createElement("input");+ input.type = "file";+ input.multiple = true;+ if (accept) input.accept = accept;+ input.addEventListener("change", () => resolve(Array.from(input.files ?? [])), {+ once: true,+ });+ input.addEventListener("cancel", () => resolve([]), { once: true });+ input.click();+ });+}++/**+ * Replace the typed `/query` at `range` with a block of `kind`. Image and file+ * open the file picker and upload at the caret, the same path as a paste.+ */+export function insertBlock(+ editor: Editor,+ range: Range,+ kind: InsertBlockKind,+ options: {+ upload?: UploadHandler;+ pick?: (accept?: string) => Promise<File[]>;+ } = {},+): void {+ const chain = editor.chain().focus().deleteRange(range);+ switch (kind) {+ case "mermaid":+ chain.clearNodes().setCodeBlock({ language: "mermaid" }).run();+ return;+ case "table":+ chain.insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run();+ return;+ case "divider":+ chain.setHorizontalRule().run();+ return;+ case "image":+ case "file": {+ chain.run();+ const upload = options.upload;+ if (!upload) return;+ const pick = options.pick ?? pickFiles;+ void pick(kind === "image" ? "image/*" : undefined).then(async (files) => {+ for (const file of files) {+ if (editor.isDestroyed) return;+ await uploadAndInsertFile(editor, file, upload);+ }+ });+ return;+ }+ default:+ applyTextBlock(chain, kind).run();+ }+}++/** A block the handle acts on: a list item, or a direct child of the document. */+export interface BlockTarget {+ pos: number;+ node: ProseMirrorNode;+}++const LIST_ITEM_TYPES = new Set(["listItem", "taskItem"]);++/**+ * The block the handle should act on for document position `pos`: the+ * innermost list item around it, otherwise the top-level block containing it.+ * List items get their own handle because moving one item is far more common+ * than moving a whole list.+ */+export function resolveBlockTarget(+ doc: ProseMirrorNode,+ pos: number,+): BlockTarget | null {+ if (pos < 0 || pos > doc.content.size) return null;+ const $pos = doc.resolve(pos);+ for (let depth = $pos.depth; depth > 0; depth--) {+ const node = $pos.node(depth);+ if (LIST_ITEM_TYPES.has(node.type.name)) {+ return { pos: $pos.before(depth), node };+ }+ }+ if ($pos.depth >= 1) return { pos: $pos.before(1), node: $pos.node(1) };+ // Depth 0: `pos` sits in front of a top-level leaf such as an image.+ const node = doc.nodeAt(pos);+ return node ? { pos, node } : null;+}++const TURNABLE_TYPES = new Set([+ "paragraph",+ "heading",+ "codeBlock",+ "blockquote",+ "listItem",+ "taskItem",+ "bulletList",+ "orderedList",+ "taskList",+]);++/** Whether "turn into" applies; tables, images and other leaves keep their type. */+export function canTurnInto(node: ProseMirrorNode): boolean {+ return TURNABLE_TYPES.has(node.type.name);+}++/** The text block kind a block currently has, for marking it in the menu. */+export function currentTextBlockKind(node: ProseMirrorNode): TextBlockKind | null {+ switch (node.type.name) {+ case "paragraph":+ return "paragraph";+ case "heading": {+ const level = node.attrs.level as number;+ return level === 1 ? "heading1" : level === 2 ? "heading2" : level === 3 ? "heading3" : null;+ }+ case "codeBlock":+ return "codeBlock";+ case "blockquote":+ return "blockquote";+ case "bulletList":+ return "bulletList";+ case "orderedList":+ return "orderedList";+ case "taskList":+ case "taskItem":+ return "taskList";+ default:+ return null;+ }+}++function selectBlockText(editor: Editor, target: BlockTarget) {+ const { state, view } = editor;+ const selection = TextSelection.between(+ state.doc.resolve(target.pos),+ state.doc.resolve(target.pos + target.node.nodeSize),+ );+ view.dispatch(state.tr.setSelection(selection));+}++export function turnBlockInto(+ editor: Editor,+ target: BlockTarget,+ kind: TextBlockKind,+): void {+ if (!canTurnInto(target.node)) return;+ selectBlockText(editor, target);+ applyTextBlock(editor.chain().focus(), kind).run();+ // Leave a caret, not the selected text: a selection would keep the+ // formatting toolbar open over the block.+ editor.commands.setTextSelection(editor.state.selection.to);+}++export function duplicateBlock(editor: Editor, target: BlockTarget): void {+ const end = target.pos + target.node.nodeSize;+ editor.view.dispatch(editor.state.tr.insert(end, target.node).scrollIntoView());+}++export function deleteBlock(editor: Editor, target: BlockTarget): void {+ editor.view.dispatch(+ editor.state.tr.deleteRange(target.pos, target.pos + target.node.nodeSize),+ );+}++/** Whether a block holds nothing but one empty paragraph's worth of text. */+function emptyTextStart(target: BlockTarget): number | null {+ const { node, pos } = target;+ if (node.isTextblock && node.content.size === 0) return pos + 1;+ if (+ LIST_ITEM_TYPES.has(node.type.name) &&+ node.childCount === 1 &&+ node.firstChild?.isTextblock &&+ node.firstChild.content.size === 0+ ) {+ return pos + 2;+ }+ return null;+}++/**+ * The handle's "+": open the insert menu on a new line below `target` (or on+ * `target` itself when it is already an empty line). A list item gets a sibling+ * item, so adding below an item stays inside its list.+ */+export function openInsertMenuBelow(editor: Editor, target: BlockTarget): void {+ const { state, view } = editor;+ const tr = state.tr;+ let caret = emptyTextStart(target);+ if (caret === null) {+ const end = target.pos + target.node.nodeSize;+ const sibling = LIST_ITEM_TYPES.has(target.node.type.name)+ ? target.node.type.createAndFill()+ : state.schema.nodes.paragraph!.create();+ if (!sibling) return;+ tr.insert(end, sibling);+ caret = sibling.isTextblock ? end + 1 : end + 2;+ }+ tr.setSelection(TextSelection.create(tr.doc, caret));+ tr.insertText("/");+ armSuggestionTrigger(tr, caret);+ view.dispatch(tr.scrollIntoView());+ view.focus();+}diff --git a/packages/views/editor/extensions/block-insert-suggestion.test.tsx b/packages/views/editor/extensions/block-insert-suggestion.test.tsxnew file mode 100644index 0000000000..1157aa7c0b--- /dev/null+++ b/packages/views/editor/extensions/block-insert-suggestion.test.tsx@@ -0,0 +1,125 @@+import { act, render, screen } from "@testing-library/react";+import { createRef, type ReactNode } from "react";+import { beforeAll, describe, expect, it, vi } from "vitest";+import { I18nProvider } from "@multica/core/i18n/react";+import enEditor from "../../locales/en/editor.json";+import zhEditor from "../../locales/zh-Hans/editor.json";+import {+ BLOCK_MENU_ITEMS,+ BlockInsertList,+ type BlockInsertListRef,+ createBlockInsertSuggestion,+ filterBlockMenuItems,+} from "./block-insert-suggestion";+import type { InsertBlockKind } from "./block-commands";++beforeAll(() => {+ Element.prototype.scrollIntoView = vi.fn();+});++function wrapper(locale: "en" | "zh-Hans") {+ return function I18nWrapper({ children }: { children: ReactNode }) {+ return (+ <I18nProvider+ locale={locale}+ resources={{ en: { editor: enEditor }, "zh-Hans": { editor: zhEditor } }}+ >+ {children}+ </I18nProvider>+ );+ };+}++const enLabel = (kind: InsertBlockKind) => enEditor.block_menu.blocks[kind];+const zhLabel = (kind: InsertBlockKind) => zhEditor.block_menu.blocks[kind];+const kinds = (items: { kind: InsertBlockKind }[]) => items.map((item) => item.kind);++describe("filterBlockMenuItems", () => {+ it("returns every block for an empty query", () => {+ expect(filterBlockMenuItems(BLOCK_MENU_ITEMS, "", enLabel)).toHaveLength(+ BLOCK_MENU_ITEMS.length,+ );+ });++ it("matches Markdown-style aliases by prefix", () => {+ expect(kinds(filterBlockMenuItems(BLOCK_MENU_ITEMS, "h2", enLabel))).toEqual([+ "heading2",+ ]);+ expect(kinds(filterBlockMenuItems(BLOCK_MENU_ITEMS, "todo", enLabel))).toEqual([+ "taskList",+ ]);+ });++ it("matches localized labels, including by pinyin", () => {+ expect(kinds(filterBlockMenuItems(BLOCK_MENU_ITEMS, "表格", zhLabel))).toEqual([+ "table",+ ]);+ expect(kinds(filterBlockMenuItems(BLOCK_MENU_ITEMS, "dmk", zhLabel))).toEqual([+ "codeBlock",+ ]);+ });+});++describe("BlockInsertList", () => {+ const items = [...BLOCK_MENU_ITEMS];++ it("filters by the typed query and accepts the highlight on Enter", () => {+ const command = vi.fn();+ const ref = createRef<BlockInsertListRef>();+ render(<BlockInsertList ref={ref} items={items} query="list" command={command} />, {+ wrapper: wrapper("en"),+ });+ expect(screen.getAllByRole("option").map((o) => o.textContent)).toEqual([+ "Bulleted list-",+ "Numbered list1.",+ "Task list[ ]",+ ]);+ act(() => {+ ref.current!.onKeyDown({ event: new KeyboardEvent("keydown", { key: "ArrowDown" }) });+ });+ act(() => {+ ref.current!.onKeyDown({ event: new KeyboardEvent("keydown", { key: "Enter" }) });+ });+ expect(command).toHaveBeenCalledWith(expect.objectContaining({ kind: "orderedList" }));+ });++ it("picks from what was typed when Enter beats the re-render", () => {+ const command = vi.fn();+ const ref = createRef<BlockInsertListRef>();+ render(<BlockInsertList ref={ref} items={items} query="" command={command} />, {+ wrapper: wrapper("en"),+ });+ act(() => {+ ref.current!.onKeyDown({+ event: new KeyboardEvent("keydown", { key: "Enter" }),+ query: "image",+ });+ });+ expect(command).toHaveBeenCalledWith(expect.objectContaining({ kind: "image" }));+ });++ it("renders nothing and lets Enter through when nothing matches", () => {+ const ref = createRef<BlockInsertListRef>();+ const { container } = render(+ <BlockInsertList ref={ref} items={items} query="usr/local" command={vi.fn()} />,+ { wrapper: wrapper("en") },+ );+ expect(container).toBeEmptyDOMElement();+ expect(+ ref.current!.onKeyDown({ event: new KeyboardEvent("keydown", { key: "Enter" }) }),+ ).toBe(false);+ });+});++describe("createBlockInsertSuggestion", () => {+ it("offers image and file only when the host can upload", () => {+ const items = (upload: unknown) =>+ kinds(+ (createBlockInsertSuggestion({ current: upload as never }).items as unknown as (p: {+ query: string;+ }) => { kind: InsertBlockKind }[])({ query: "" }),+ );+ expect(items(undefined)).not.toContain("image");+ expect(items(vi.fn())).toEqual(expect.arrayContaining(["image", "file"]));+ });+});diff --git a/packages/views/editor/extensions/block-insert-suggestion.tsx b/packages/views/editor/extensions/block-insert-suggestion.tsxnew file mode 100644index 0000000000..98ade49edc--- /dev/null+++ b/packages/views/editor/extensions/block-insert-suggestion.tsx@@ -0,0 +1,236 @@+"use client";++import {+ forwardRef,+ useCallback,+ useEffect,+ useImperativeHandle,+ useMemo,+ useRef,+ useState,+ type ComponentType,+ type RefObject,+} from "react";+import type { SuggestionOptions } from "@tiptap/suggestion";+import { PluginKey } from "@tiptap/pm/state";+import {+ Code,+ Heading1,+ Heading2,+ Heading3,+ Image,+ List,+ ListOrdered,+ ListTodo,+ Minus,+ Paperclip,+ Quote,+ Table2,+ Type,+ Workflow,+} from "@multica/ui/icons";+import { cn } from "@multica/ui/lib/utils";+import { isImeComposing } from "@multica/core/utils";+import { useT } from "../../i18n";+import {+ isPickerAcceptKey,+ pickerNavigationDirection,+} from "../../common/picker-keys";+import { createSuggestionPopupRender } from "./suggestion-popup";+import { isTriggerArmedAt } from "./suggestion-trigger-arming";+import { matchesPinyin } from "./pinyin-match";+import { insertBlock, type InsertBlockKind, type UploadHandler } from "./block-commands";++export interface BlockMenuItem {+ kind: InsertBlockKind;+ icon: ComponentType<{ className?: string }>;+ /** The Markdown a writer can type instead of opening the menu. */+ shortcut?: string;+ /** Search aliases, matched by prefix in addition to the localized label. */+ keywords: readonly string[];+ /** Only offered when the editor can upload. */+ needsUpload?: boolean;+}++export const BLOCK_MENU_ITEMS: readonly BlockMenuItem[] = [+ { kind: "paragraph", icon: Type, keywords: ["text", "paragraph", "正文", "文本"] },+ { kind: "heading1", icon: Heading1, shortcut: "#", keywords: ["h1", "heading", "title", "标题"] },+ { kind: "heading2", icon: Heading2, shortcut: "##", keywords: ["h2", "heading", "标题"] },+ { kind: "heading3", icon: Heading3, shortcut: "###", keywords: ["h3", "heading", "标题"] },+ { kind: "bulletList", icon: List, shortcut: "-", keywords: ["bullet", "list", "ul", "列表"] },+ { kind: "orderedList", icon: ListOrdered, shortcut: "1.", keywords: ["numbered", "ordered", "list", "ol", "列表"] },+ { kind: "taskList", icon: ListTodo, shortcut: "[ ]", keywords: ["todo", "task", "checkbox", "checklist", "待办"] },+ { kind: "blockquote", icon: Quote, shortcut: ">", keywords: ["quote", "blockquote", "引用"] },+ { kind: "codeBlock", icon: Code, shortcut: "```", keywords: ["code", "代码"] },+ { kind: "mermaid", icon: Workflow, keywords: ["mermaid", "diagram", "flowchart", "chart", "图表", "流程图"] },+ { kind: "table", icon: Table2, keywords: ["table", "grid", "表格"] },+ { kind: "divider", icon: Minus, shortcut: "---", keywords: ["divider", "hr", "separator", "line", "分割线"] },+ { kind: "image", icon: Image, keywords: ["image", "picture", "photo", "img", "图片"], needsUpload: true },+ { kind: "file", icon: Paperclip, keywords: ["file", "attachment", "upload", "文件", "附件"], needsUpload: true },+];++/** Items matching `query` by localized label, alias prefix, or pinyin. */+export function filterBlockMenuItems(+ items: readonly BlockMenuItem[],+ query: string,+ labelOf: (kind: InsertBlockKind) => string,+): BlockMenuItem[] {+ const q = query.trim().toLowerCase();+ if (!q) return [...items];+ return items.filter((item) => {+ const label = labelOf(item.kind);+ return (+ label.toLowerCase().includes(q) ||+ item.keywords.some((keyword) => keyword.startsWith(q)) ||+ matchesPinyin(label, q)+ );+ });+}++interface BlockInsertListProps {+ items: BlockMenuItem[];+ query: string;+ command: (item: BlockMenuItem) => void;+}++export interface BlockInsertListRef {+ /**+ * `query` is the text typed after `/` as of this key press. It can be ahead+ * of the rendered list when a fast typist hits Enter before React re-renders,+ * and the pick must match what was typed, not what was last drawn.+ */+ onKeyDown: (props: { event: KeyboardEvent; query?: string }) => boolean;+}++export const BlockInsertList = forwardRef<BlockInsertListRef, BlockInsertListProps>(+ function BlockInsertList({ items, query, command }, ref) {+ const { t } = useT("editor");+ const labelOf = useCallback(+ (kind: InsertBlockKind) => t(($) => $.block_menu.blocks[kind]),+ [t],+ );+ const visible = useMemo(+ () => filterBlockMenuItems(items, query, labelOf),+ [items, query, labelOf],+ );+ const [selectedIndex, setSelectedIndex] = useState(0);+ const itemRefs = useRef<(HTMLButtonElement | null)[]>([]);++ useEffect(() => {+ setSelectedIndex(0);+ }, [visible]);++ useEffect(() => {+ itemRefs.current[selectedIndex]?.scrollIntoView({ block: "nearest" });+ }, [selectedIndex]);++ useImperativeHandle(ref, () => ({+ onKeyDown: ({ event, query: liveQuery = query }) => {+ if (isImeComposing(event)) return false;+ const stale = liveQuery !== query;+ const current = stale ? filterBlockMenuItems(items, liveQuery, labelOf) : visible;+ if (current.length === 0) return false;+ const direction = pickerNavigationDirection(event);+ if (direction !== null) {+ const delta = direction === "next" ? 1 : current.length - 1;+ setSelectedIndex((i) => (i + delta) % current.length);+ return true;+ }+ if (isPickerAcceptKey(event)) {+ const item = current[stale ? 0 : selectedIndex];+ if (item) command(item);+ return true;+ }+ return false;+ },+ }));++ // Nothing matched: stay out of the way so a `/` in prose (paths, dates)+ // reads as text and Enter keeps its normal meaning.+ if (visible.length === 0) return null;++ return (+ <div+ data-mc="editor-menu"+ data-kind="block"+ role="listbox"+ aria-label={t(($) => $.block_menu.label)}+ className="w-64 max-h-[min(320px,var(--suggestion-available-height,320px))] overflow-y-auto rounded-md border bg-popover p-1 shadow-md"+ >+ {visible.map((item, index) => {+ const Icon = item.icon;+ return (+ <button+ key={item.kind}+ type="button"+ role="option"+ aria-selected={selectedIndex === index}+ ref={(el) => {+ itemRefs.current[index] = el;+ }}+ className={cn(+ "flex w-full items-center gap-2 rounded-sm px-2 py-1 text-left text-body transition-colors",+ selectedIndex === index ? "bg-accent" : "hover:bg-accent/50",+ )}+ onMouseEnter={() => setSelectedIndex(index)}+ onClick={() => command(item)}+ >+ <span className="flex size-6 shrink-0 items-center justify-center rounded-sm border bg-background text-muted-foreground">+ <Icon className="size-3.5" />+ </span>+ <span className="min-w-0 flex-1 truncate">{labelOf(item.kind)}</span>+ {item.shortcut && (+ <kbd className="shrink-0 font-mono text-caption text-muted-foreground">+ {item.shortcut}+ </kbd>+ )}+ </button>+ );+ })}+ </div>+ );+ },+);++/**+ * The `/` menu for long-form documents: inserts blocks rather than skills or+ * commands. Image and file are offered only when the host can upload.+ */+export function createBlockInsertSuggestion(+ uploadRef: RefObject<UploadHandler | undefined> | undefined,+): Omit<SuggestionOptions<BlockMenuItem>, "editor"> {+ const pluginKey = new PluginKey("blockInsertSuggestion");+ return {+ char: "/",+ pluginKey,+ // Only open over a `/` the user typed (or asked for through the block+ // handle), never over a pasted path (MUL-5429).+ shouldShow: ({ editor, range }) => isTriggerArmedAt(editor, range.from),+ items: () =>+ BLOCK_MENU_ITEMS.filter((item) => !item.needsUpload || !!uploadRef?.current),+ command: ({ editor, range, props }) => {+ insertBlock(editor, range, props.kind, { upload: uploadRef?.current });+ },+ render: createSuggestionPopupRender<+ BlockMenuItem,+ BlockMenuItem,+ BlockInsertListRef,+ BlockInsertListProps+ >({+ pluginKey,+ component: BlockInsertList,+ placement: "bottom-start",+ getProps: (props) => ({+ items: props.items,+ query: props.query,+ command: props.command,+ }),+ onKeyDown: (ref, props) =>+ ref?.onKeyDown({+ event: props.event,+ // The range spans the trigger and the query: `/image`.+ query: props.view.state.doc.textBetween(props.range.from + 1, props.range.to),+ }) ?? false,+ }),+ };+}diff --git a/packages/views/editor/extensions/index.ts b/packages/views/editor/extensions/index.tsindex 0ab0b3372c..2c9e15a645 100644--- a/packages/views/editor/extensions/index.ts+++ b/packages/views/editor/extensions/index.ts@@ -46,6 +46,7 @@ import {import { SlashCommandExtension } from "./slash-command-extension";import { createSlashCommandSuggestion, createBuiltinCommandSuggestion } from "./slash-command-suggestion";import type { BuiltinCommandSuggestionOptions } from "./slash-command-suggestion";+import { createBlockInsertSuggestion } from "./block-insert-suggestion";import { SuggestionTriggerArmingExtension } from "./suggestion-trigger-arming";import { CodeBlockView } from "./code-block-view";import { TableView } from "./table-view";@@ -175,8 +176,9 @@ export interface EditorExtensionsOptions {* Which `/` menu to attach when enableSlashCommands is true:* - "skill" (default) — the chat picker listing the active agent's skills.* - "command" — Issue quick actions, skills matching a nonempty query, and /note.+ * - "blocks" — the document block menu: headings, lists, code, tables, uploads.*/- slashCommandMode?: "skill" | "command";+ slashCommandMode?: "skill" | "command" | "blocks";/*** Quick actions and Issue target-agent skills offered in the "command" `/`* menu, plus the resolver that turns a quick-action pick into draft text.@@ -295,11 +297,13 @@ export function createEditorExtensions(HTMLAttributes: { class: "slash-command" },suggestion: !options.enableSlashCommands? { char: "/", allow: () => false }- : options.slashCommandMode === "command"- ? createBuiltinCommandSuggestion(options.quickActionMenu)- : options.queryClient- ? createSlashCommandSuggestion(options.queryClient)- : { char: "/", allow: () => false },+ : options.slashCommandMode === "blocks"+ ? createBlockInsertSuggestion(options.onUploadFileRef)+ : options.slashCommandMode === "command"+ ? createBuiltinCommandSuggestion(options.quickActionMenu)+ : options.queryClient+ ? createSlashCommandSuggestion(options.queryClient)+ : { char: "/", allow: () => false },}),Typography,Placeholder.configure({ placeholder: placeholderText }),diff --git a/packages/views/editor/extensions/mention-boundary.test.ts b/packages/views/editor/extensions/mention-boundary.test.tsindex 3f759feb3f..cbb05aa657 100644--- a/packages/views/editor/extensions/mention-boundary.test.ts+++ b/packages/views/editor/extensions/mention-boundary.test.ts@@ -63,6 +63,7 @@ function fakeQc(): QueryClient {return undefined;},getQueriesData: () => [],+ prefetchQuery: () => Promise.resolve(),} as unknown as QueryClient;}diff --git a/packages/views/editor/extensions/mention-extension.ts b/packages/views/editor/extensions/mention-extension.tsindex abb8717877..6176c315ac 100644--- a/packages/views/editor/extensions/mention-extension.ts+++ b/packages/views/editor/extensions/mention-extension.ts@@ -44,7 +44,7 @@ function findMentionStart(src: string): number {/** A mention as text, the way its pill reads: issues and projects by name. */export function mentionText(attrs: Record<string, unknown>): string {const type = attrs.type ?? "member";- const prefix = type === "issue" || type === "project" ? "" : "@";+ const prefix = type === "issue" || type === "project" || type === "doc" ? "" : "@";return `${prefix}${String(attrs.label ?? attrs.id ?? "")}`;}@@ -112,7 +112,7 @@ export const BaseMentionExtension = Mention.extend({},renderMarkdown: (node: any) => {const { id, label, type = "member" } = node.attrs || {};- const prefix = type === "issue" || type === "project" ? "" : "@";+ const prefix = type === "issue" || type === "project" || type === "doc" ? "" : "@";// Escape [ ] \ ( ) in the label so the markdown link syntax is not broken// and the label survives the linear tokenizer (which now treats "\" as an// escape lead, not an ordinary char). Must stay in sync with the unescapediff --git a/packages/views/editor/extensions/mention-suggestion.doc-load.test.tsx b/packages/views/editor/extensions/mention-suggestion.doc-load.test.tsxnew file mode 100644index 0000000000..69b2b1247a--- /dev/null+++ b/packages/views/editor/extensions/mention-suggestion.doc-load.test.tsx@@ -0,0 +1,94 @@+import { act, cleanup, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { Editor, Extension } from "@tiptap/core";+import { EditorContent } from "@tiptap/react";+import StarterKit from "@tiptap/starter-kit";+import { Suggestion } from "@tiptap/suggestion";+import { I18nProvider } from "@multica/core/i18n/react";+import { docKeys } from "@multica/core/docs";+import { createMentionSuggestion } from "./mention-suggestion";+import { SuggestionTriggerArmingExtension } from "./suggestion-trigger-arming";+import enDocs from "../../locales/en/docs.json";+import enEditor from "../../locales/en/editor.json";+import enIssues from "../../locales/en/issues.json";++// The first `@` in a session loads the doc tree; the open menu must show the+// docs once it arrives, without another keystroke (PR #10926 review).+const apiMock = vi.hoisted(() => ({+ listDocTree: vi.fn(), moveDoc: vi.fn(), moveDocFolder: vi.fn(),+ searchIssues: vi.fn(), searchProjects: vi.fn(),+}));+vi.mock("@multica/core/api", () => ({ api: apiMock }));+vi.mock("@multica/core/hooks", async (original) => ({+ ...await original<object>(), useWorkspaceId: () => "review-ws",+}));+vi.mock("@multica/core/platform", async (original) => ({+ ...await original<object>(), getCurrentWsId: () => "review-ws",+}));+vi.mock("@multica/core/auth", () => ({+ useAuthStore: Object.assign(vi.fn(), { getState: () => ({ user: { id: "reviewer" } }) }),+}));+vi.mock("@multica/core/paths", async (original) => ({+ ...await original<object>(), useWorkspacePaths: () => ({+ docs: () => "/review/docs", docDetail: (id: string) => `/review/docs/${id}`,+ docFolder: (id: string) => `/review/docs/folders/${id}`,+ }),+}));+vi.mock("../../navigation", () => ({+ useNavigation: () => ({ pathname: "/review/docs", push: vi.fn() }),+ AppLink: ({ children, href }: { children: React.ReactNode; href: string }) => <a href={href}>{children}</a>,+}));+vi.mock("@multica/core/issue-statuses/hooks", () => ({+ useIssueStatuses: () => ({ iconOf: () => null, colorOf: () => null }),+}));+vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));++const tree = {+ folders: [+ { id: "parent", title: "Parent", parentId: null },+ { id: "child", title: "Child", parentId: "parent" },+ { id: "grandchild", title: "Grandchild", parentId: "child" },+ { id: "other", title: "Other", parentId: null },+ ],+ docs: [{ id: "runbook", title: "Release runbook", folderId: "child", updatedAt: "2026-11-18T00:00:00Z" }],+};+let qc: QueryClient;+let editor: Editor | undefined;+beforeEach(() => {+ vi.clearAllMocks();+ qc = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });+ apiMock.listDocTree.mockResolvedValue(tree);+ apiMock.searchIssues.mockResolvedValue({ issues: [] });+ apiMock.searchProjects.mockResolvedValue({ projects: [] });+});+afterEach(() => { act(() => editor?.destroy()); editor = undefined; cleanup(); qc.clear(); });++function mount(children: React.ReactNode) {+ return render(<QueryClientProvider client={qc}><I18nProvider locale="en" resources={{ en: { docs: enDocs, editor: enEditor, issues: enIssues } }}>{children}</I18nProvider></QueryClientProvider>);+}++it("first @ shows recent docs after the request resolves, without another keystroke", async () => {+ let resolve!: (value: typeof tree) => void;+ apiMock.listDocTree.mockReturnValue(new Promise((r) => { resolve = r; }));+ const suggestion = createMentionSuggestion(qc);+ const probe = Extension.create({+ name: "reviewMentionProbe",+ addProseMirrorPlugins() { return [Suggestion({ ...suggestion, editor: this.editor })]; },+ });+ editor = new Editor({ extensions: [StarterKit, SuggestionTriggerArmingExtension, probe], content: "" });+ mount(<EditorContent editor={editor} />);+ await act(async () => {+ editor!.commands.focus("end");+ const { from, to } = editor!.state.selection;+ const handled = editor!.view.someProp("handleTextInput", (fn) =>+ fn(editor!.view, from, to, "@", () => editor!.state.tr.insertText("@", from, to)),+ );+ if (!handled) editor!.view.dispatch(editor!.state.tr.insertText("@", from, to));+ });+ await screen.findByRole("button", { name: "All members" });+ expect(apiMock.listDocTree).toHaveBeenCalledOnce();+ await act(async () => { resolve(tree); });+ await waitFor(() => expect(qc.getQueryData(docKeys.tree("review-ws"))).toEqual(tree));+ expect(await screen.findByRole("button", { name: "Release runbook" })).toBeInTheDocument();+});diff --git a/packages/views/editor/extensions/mention-suggestion.test.tsx b/packages/views/editor/extensions/mention-suggestion.test.tsxindex 1202d27d61..761c5e40a0 100644--- a/packages/views/editor/extensions/mention-suggestion.test.tsx+++ b/packages/views/editor/extensions/mention-suggestion.test.tsx@@ -4,6 +4,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest";import { workspaceKeys } from "@multica/core/workspace/queries";import { issueKeys, PAGINATED_CATEGORIES } from "@multica/core/issues/queries";import { projectKeys } from "@multica/core/projects/queries";+import { docKeys } from "@multica/core/docs";import { statusCategoryOfKey } from "@multica/core/issues";import { I18nProvider } from "@multica/core/i18n/react";import type { IssueStatusCategory, ListIssuesCache } from "@multica/core/types";@@ -123,6 +124,7 @@ function fakeQc(data: {}>;issues?: Array<{ id: string; identifier: string; title: string; status: string }>;projects?: Array<{ id: string; title: string; status: string; archived_at: string | null }>;+ docs?: Array<{ id: string; title: string; updatedAt: string }>;}): QueryClient {const map = new Map<string, unknown>();map.set(JSON.stringify(workspaceKeys.members("ws-1")), data.members ?? []);@@ -160,7 +162,9 @@ function fakeQc(data: {projects: data.projects ?? [],total: data.projects?.length ?? 0,});+ map.set(JSON.stringify(docKeys.tree("ws-1")), { folders: [], docs: data.docs ?? [] });return {+ prefetchQuery: vi.fn(),getQueryData: (key: readonly unknown[]) => map.get(JSON.stringify(key)),getQueriesData: <T,>(filter: { queryKey: readonly unknown[] }) => {const prefix = filter.queryKey as unknown[];@@ -493,6 +497,56 @@ describe("createMentionSuggestion", () => {expect(items.filter((i) => i.type === "project").map((i) => i.id)).toEqual(["p-live"]);});+ it("offers docs by title or pinyin, and recent docs before anything is typed", () => {+ const qc = fakeQc({+ docs: [+ { id: "d-runbook", title: "Release runbook", updatedAt: "2026-11-01T00:00:00Z" },+ { id: "d-arch", title: "架构说明", updatedAt: "2026-11-03T00:00:00Z" },+ { id: "d-blank", title: "", updatedAt: "2026-11-04T00:00:00Z" },+ ],+ });+ const docs = (query: string) =>+ (createMentionSuggestion(qc).items!(itemArgs(query)) as MentionItem[])+ .filter((i) => i.type === "doc")+ .map((i) => i.id);++ expect(docs("runbook")).toEqual(["d-runbook"]);+ expect(docs("jg")).toEqual(["d-arch"]);+ expect(docs("")).toEqual(["d-arch", "d-runbook"]);+ });++ it("loads the doc tree on the first mention when it is not cached", () => {+ const qc = fakeQc({});+ const getQueryData = qc.getQueryData.bind(qc);+ qc.getQueryData = ((key: readonly unknown[]) =>+ JSON.stringify(key) === JSON.stringify(docKeys.tree("ws-1"))+ ? undefined+ : getQueryData(key)) as QueryClient["getQueryData"];++ createMentionSuggestion(qc).items!(itemArgs(""));++ expect(qc.prefetchQuery).toHaveBeenCalledWith(+ expect.objectContaining({ queryKey: docKeys.tree("ws-1") }),+ );+ });++ it("shows docs in their own section", () => {+ render(+ <I18nWrapper>+ <MentionList+ items={[{ id: "d-runbook", label: "Release runbook", type: "doc" }]}+ query="run"+ command={vi.fn()}+ />+ </I18nWrapper>,+ );+ const headings = Array.from(document.querySelectorAll<HTMLElement>("div.uppercase")).map(+ (el) => el.textContent,+ );+ expect(headings).toEqual(["Docs"]);+ expect(screen.getByText("Release runbook")).toBeInTheDocument();+ });+it("does not call searchIssues for an empty query", () => {render(<I18nWrapper><MentionList items={[]} query="" command={vi.fn()} /></I18nWrapper>);diff --git a/packages/views/editor/extensions/mention-suggestion.tsx b/packages/views/editor/extensions/mention-suggestion.tsxindex 742af68ea8..b8da417574 100644--- a/packages/views/editor/extensions/mention-suggestion.tsx+++ b/packages/views/editor/extensions/mention-suggestion.tsx@@ -17,6 +17,7 @@ import { issueStatusCategory } from "@multica/core/issues";import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";import { workspaceKeys } from "@multica/core/workspace/queries";import { projectKeys } from "@multica/core/projects/queries";+import { docKeys, docTreeOptions } from "@multica/core/docs";import { useAuthStore } from "@multica/core/auth";import { canAssignAgentToIssue } from "@multica/core/permissions";import { isAgentRuntimeBound } from "@multica/core/agents";@@ -34,8 +35,10 @@ import type {MemberWithUser,Agent,Squad,+ DocSummary,+ DocTree,} from "@multica/core/types";-import { ListTodo } from "@multica/ui/icons";+import { FileText, ListTodo } from "@multica/ui/icons";import { ActorAvatar } from "../../common/actor-avatar";import { StatusIcon } from "../../issues/components/status-icon";import { ProjectIcon } from "../../projects/components/project-icon";@@ -74,7 +77,7 @@ import { blockedReasonLabel } from "../../issues/blocked-trigger-copy";export interface MentionItem {id: string;label: string;- type: "member" | "agent" | "squad" | "issue" | "project" | "all";+ type: "member" | "agent" | "squad" | "issue" | "project" | "doc" | "all";/** Optional grouping hint for injected context items. */group?: "current" | "recent" | "search";/** Secondary text shown beside the label (e.g. issue title) */@@ -124,6 +127,7 @@ function groupItems(items: MentionItem[], query: string): MentionGroup[] {const users: MentionItem[] = [];const issues: MentionItem[] = [];const projects: MentionItem[] = [];+ const docs: MentionItem[] = [];const cancelled: MentionItem[] = [];for (const item of items) {@@ -139,6 +143,8 @@ function groupItems(items: MentionItem[], query: string): MentionGroup[] {issues.push(item);} else if (item.type === "project") {projects.push(item);+ } else if (item.type === "doc") {+ docs.push(item);} else {users.push(item);}@@ -151,6 +157,7 @@ function groupItems(items: MentionItem[], query: string): MentionGroup[] {if (users.length > 0) groups.push({ label: "Users", items: users });if (issues.length > 0) groups.push({ label: "Issues", items: issues });if (projects.length > 0) groups.push({ label: "Projects", items: projects });+ if (docs.length > 0) groups.push({ label: "Docs", items: docs });// Always last: no cancelled row of any type may precede a live one.if (cancelled.length > 0) groups.push({ label: "Cancelled", items: cancelled });return groups;@@ -160,6 +167,10 @@ function groupItems(items: MentionItem[], query: string): MentionGroup[] {const MAX_ITEMS = 20;const RESERVED_PROJECT_SLOTS = 5;+const RESERVED_DOC_SLOTS = 3;+/** Docs offered before anything is typed: the most recently updated. */+const RECENT_DOC_ITEMS = 5;+const MATCHED_DOC_ITEMS = 8;const SERVER_ISSUE_SEARCH_LIMIT = 20;const SERVER_CONTEXT_SEARCH_LIMIT = 8;const SERVER_PROJECT_SEARCH_LIMIT = 8;@@ -283,11 +294,12 @@ function truncateMentionItems(selectedKey: string | null,): MentionItem[] {if (items.length <= MAX_ITEMS) return items;- const kept = new Set(- items+ const kept = new Set([+ ...items.filter((item) => item.type === "project" && !isDemotedCancelled(item, query)).slice(0, RESERVED_PROJECT_SLOTS),- );+ ...items.filter((item) => item.type === "doc").slice(0, RESERVED_DOC_SLOTS),+ ]);const selected = items.find((item) => mentionItemKey(item) === selectedKey);if (selected) kept.add(selected);let remaining = MAX_ITEMS - kept.size;@@ -506,6 +518,7 @@ export const MentionList = forwardRef<MentionListRef, MentionListProps>(if (label === "Users") return t(($) => $.mention.group_users);if (label === "Issues") return t(($) => $.mention.group_issues);if (label === "Projects") return t(($) => $.mention.group_projects);+ if (label === "Docs") return t(($) => $.mention.group_docs);if (label === "Cancelled") return t(($) => $.mention.group_cancelled);return label;};@@ -662,6 +675,26 @@ function MentionRow({);}+ if (item.type === "doc") {+ return (+ <button+ type="button"+ ref={buttonRef}+ className={`flex w-full items-center gap-2.5 px-3 py-2 text-left text-caption transition-colors ${+ selected ? "bg-accent" : "hover:bg-accent/50"+ }`}+ onClick={onSelect}+ >+ <span className="flex h-7 w-7 shrink-0 items-center justify-center">+ <FileText className="h-3.5 w-3.5 text-muted-foreground" />+ </span>+ <span className="min-w-0 flex-1 truncate font-medium text-foreground">+ {item.label}+ </span>+ </button>+ );+ }+const disabledMessage = item.disabledReason? blockedReasonLabel(item.disabledReason, issuesT): null;@@ -746,6 +779,27 @@ function projectToMention(p: {};}+/**+ * Docs a mention query offers: title matches (substring or pinyin), or the most+ * recently updated docs before anything is typed. Untitled docs are skipped —+ * there is nothing to type to find them, and nothing to show in the chip.+ */+export function matchDocMentions(+ docs: readonly Pick<DocSummary, "id" | "title" | "updatedAt">[],+ query: string,+): MentionItem[] {+ const q = query.trim().toLowerCase();+ const titled = docs.filter((d) => d.title.trim() !== "");+ const picked = q+ ? titled+ .filter((d) => d.title.toLowerCase().includes(q) || matchesPinyin(d.title, q))+ .slice(0, MATCHED_DOC_ITEMS)+ : [...titled]+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))+ .slice(0, RECENT_DOC_ITEMS);+ return picked.map((d) => ({ id: d.id, label: d.title, type: "doc" as const }));+}+/*** True when the `@` at `pos` starts a token instead of continuing one.*@@ -893,7 +947,24 @@ export function createMentionSuggestion().map(projectToMention);- return [...allItem, ...userItems, ...issueItems, ...projectItems];+ // Docs come from the workspace doc tree. A session that has not opened+ // Docs yet loads it on this first `@`; docs join from the next keystroke.+ const docTree = qc.getQueryData<DocTree>(docKeys.tree(wsId));+ if (!docTree) void qc.prefetchQuery(docTreeOptions(wsId));+ const docItems = matchDocMentions(docTree?.docs ?? [], query);++ return [...allItem, ...userItems, ...issueItems, ...projectItems, ...docItems];+ }++ // Adds the cached docs matching `query` that `items` (computed at the last+ // keystroke) predates. Selection survives: MentionList pins it by identity.+ function withCachedDocs(items: MentionItem[], query: string): MentionItem[] {+ const wsId = getCurrentWsId();+ const docTree = wsId ? qc.getQueryData<DocTree>(docKeys.tree(wsId)) : undefined;+ if (!docTree) return items;+ const listed = new Set(items.filter((item) => item.type === "doc").map((item) => item.id));+ const fresh = matchDocMentions(docTree.docs, query).filter((doc) => !listed.has(doc.id));+ return fresh.length > 0 ? [...items, ...fresh] : items;}return {@@ -921,8 +992,20 @@ export function createMentionSuggestion(render: createSuggestionPopupRender<MentionItem, MentionItem, MentionListRef, MentionListProps>({pluginKey,component: MentionList,+ // The doc tree may still be loading when `@` opens the menu (see+ // buildSyncItems); re-render the open menu once it lands so the docs+ // appear without another keystroke.+ subscribe: (refresh) => {+ const wsId = getCurrentWsId();+ const cache = qc.getQueryCache?.();+ if (!wsId || !cache) return () => {};+ const treeKey = JSON.stringify(docKeys.tree(wsId));+ return cache.subscribe((event) => {+ if (event.type === "updated" && JSON.stringify(event.query.queryKey) === treeKey) refresh();+ });+ },getProps: (props) => ({- items: props.items,+ items: withCachedDocs(props.items, props.query),query: props.query,command: props.command,contextSearch: options.mode === "context",diff --git a/packages/views/editor/extensions/mention-view.tsx b/packages/views/editor/extensions/mention-view.tsxindex 8b0fd5f658..73d3065dce 100644--- a/packages/views/editor/extensions/mention-view.tsx+++ b/packages/views/editor/extensions/mention-view.tsx@@ -22,6 +22,7 @@ import { NodeViewWrapper } from "@tiptap/react";import type { NodeViewProps } from "@tiptap/react";import { IssueMentionCard } from "../../issues/components/issue-mention-card";import { ProjectMentionCard } from "../../projects/components/project-mention-card";+import { DocMentionCard } from "../../docs/components/doc-mention-card";export function MentionView({ node }: NodeViewProps) {const { type, id, label } = node.attrs;@@ -52,6 +53,18 @@ export function MentionView({ node }: NodeViewProps) {);}+ if (type === "doc") {+ return (+ <NodeViewWrapper+ as="span"+ className="inline"+ onClick={(e: React.MouseEvent) => e.stopPropagation()}+ >+ <DocMentionCard docId={id} fallbackLabel={label} />+ </NodeViewWrapper>+ );+ }+return (<NodeViewWrapper as="span" className="inline"><span className="mention">@{label ?? id}</span>diff --git a/packages/views/editor/extensions/suggestion-popup.tsx b/packages/views/editor/extensions/suggestion-popup.tsxindex 9e82b0449d..4c46423e5f 100644--- a/packages/views/editor/extensions/suggestion-popup.tsx+++ b/packages/views/editor/extensions/suggestion-popup.tsx@@ -22,6 +22,8 @@ interface SuggestionPopupRenderOptions<ref: TRef | null | undefined,props: SuggestionKeyDownProps,) => boolean;+ /** Preferred side; `flip` still moves it when that side lacks room. */+ placement?: "top-start" | "bottom-start";}export function createSuggestionPopupRender<@@ -35,6 +37,7 @@ export function createSuggestionPopupRender<getProps,subscribe,onKeyDown,+ placement = "top-start",}: SuggestionPopupRenderOptions<TItem, TSelected, TRef, TComponentProps>) {return () => {let renderer: ReactRenderer<TRef> | null = null;@@ -120,7 +123,8 @@ export function createSuggestionPopupRender<// squashed". Document-body editors (issue/project description, agent// instructions) also host this popup; there the caret usually has room// both ways, so `flip` keeps them on-screen regardless of the default.- placement: "top-start",+ // The Docs block menu opts into `bottom-start`: it reads down the page.+ placement,strategy: "fixed",middleware: [offset(6),diff --git a/packages/views/editor/extensions/suggestion-trigger-arming.ts b/packages/views/editor/extensions/suggestion-trigger-arming.tsindex a14d161183..245ba92747 100644--- a/packages/views/editor/extensions/suggestion-trigger-arming.ts+++ b/packages/views/editor/extensions/suggestion-trigger-arming.ts@@ -1,5 +1,5 @@import { Extension, type Editor } from "@tiptap/core";-import { Plugin, PluginKey } from "@tiptap/pm/state";+import { Plugin, PluginKey, type Transaction } from "@tiptap/pm/state";import type { Node as ProseMirrorNode } from "@tiptap/pm/model";/**@@ -55,6 +55,19 @@ const TRIGGER_CHARS = new Set(["@", "/"]);*/const armedPositions = new WeakMap<Editor, number | null>();+/**+ * Transaction meta that arms a trigger the user asked for through a control+ * rather than a keystroke (the block handle's "+" inserts `/` to open the+ * insert menu). The value is the trigger's position in the transaction's+ * resulting document.+ */+const ARM_META = "suggestionTriggerArming:arm";++/** Marks `pos` in `tr`'s resulting document as a trigger the user requested. */+export function armSuggestionTrigger(tr: Transaction, pos: number): Transaction {+ return tr.setMeta(ARM_META, pos);+}+/** True when `from` is where the user typed a trigger character. */export function isTriggerArmedAt(editor: Editor, from: number): boolean {const armed = armedPositions.get(editor);@@ -103,6 +116,8 @@ export const SuggestionTriggerArmingExtension = Extension.create({const next = ((): number | null => {// A trigger character was just typed — arm it unconditionally.if (pendingArm !== null) return pendingArm;+ const requested: unknown = tr.getMeta(ARM_META);+ if (typeof requested === "number") return requested;if (prev === null) return null;// A deliberate caret move (click, arrow key) abandons the trigger.diff --git a/packages/views/editor/link-hover-card.tsx b/packages/views/editor/link-hover-card.tsxindex e0f53e076c..fb2f1d43a9 100644--- a/packages/views/editor/link-hover-card.tsx+++ b/packages/views/editor/link-hover-card.tsx@@ -75,7 +75,8 @@ function useLinkHover(containerRef: React.RefObject<HTMLElement | null>, disable// in-app path rather than the shareable link the user expects.if (link.classList.contains("issue-mention") ||- link.classList.contains("project-mention")+ link.classList.contains("project-mention") ||+ link.classList.contains("doc-mention")) {return;}diff --git a/packages/views/editor/styles/prose.css b/packages/views/editor/styles/prose.cssindex acc9d1825f..b82907d49c 100644--- a/packages/views/editor/styles/prose.css+++ b/packages/views/editor/styles/prose.css@@ -426,7 +426,8 @@max-width: 18rem;}-.rich-text-editor :is(td, th) span.project-chip {+.rich-text-editor :is(td, th) span.project-chip,+.rich-text-editor :is(td, th) span.doc-chip {display: inline-grid;grid-template-columns: auto minmax(0, max-content);max-width: 18rem;@@ -590,13 +591,15 @@link color and underline above would be a second, competing one drawnthrough the card. Every chip-shaped mention belongs here. */.rich-text-editor a.issue-mention,-.rich-text-editor a.project-mention {+.rich-text-editor a.project-mention,+.rich-text-editor a.doc-mention {color: inherit;text-decoration: none;}.rich-text-editor a.issue-mention:hover,-.rich-text-editor a.project-mention:hover {+.rich-text-editor a.project-mention:hover,+.rich-text-editor a.doc-mention:hover {text-decoration: none;}diff --git a/packages/views/editor/utils/link-handler.test.ts b/packages/views/editor/utils/link-handler.test.tsindex 02bbb92990..8383670935 100644--- a/packages/views/editor/utils/link-handler.test.ts+++ b/packages/views/editor/utils/link-handler.test.ts@@ -169,6 +169,15 @@ describe("parseWorkspaceEntityLink", () => {).toEqual({ kind: "issue", id: ISSUE_ID, slug: "acme" });});+ it("parses a doc URL, the shape the doc page's Copy link produces", () => {+ expect(+ parseWorkspaceEntityLink(`${APP_ORIGIN}/acme/docs/${PROJECT_ID}`, APP_ORIGIN),+ ).toEqual({ kind: "doc", id: PROJECT_ID, slug: "acme" });+ // A doc's history page and a folder page are not the doc itself.+ expect(parseWorkspaceEntityLink(`/acme/docs/${PROJECT_ID}/history`)).toBeNull();+ expect(parseWorkspaceEntityLink(`/acme/docs/folders/${PROJECT_ID}`)).toBeNull();+ });+it("parses a site-relative path without needing an app origin", () => {expect(parseWorkspaceEntityLink(`/acme/projects/${PROJECT_ID}`)).toEqual({kind: "project",diff --git a/packages/views/editor/utils/link-handler.ts b/packages/views/editor/utils/link-handler.tsindex a381ea702e..b6b2599e2c 100644--- a/packages/views/editor/utils/link-handler.ts+++ b/packages/views/editor/utils/link-handler.ts@@ -25,6 +25,7 @@ import type { LinkClickIntent } from "../../navigation/click-intent";* as intentional. Only "/issues/..." style paths get auto-prefixed.*/const WORKSPACE_ROUTE_SEGMENTS = new Set([+ "docs","usage","issues","projects",@@ -72,9 +73,9 @@ export function toInternalAppPath(return `${target.pathname}${target.search}${target.hash}`;}-/** An in-app entity page addressed by a link — the two kinds that have a chip. */+/** An in-app entity page addressed by a link — the kinds that have a chip. */export interface WorkspaceEntityRef {- kind: "issue" | "project";+ kind: "issue" | "project" | "doc";/*** Entity id, decoded from the path. A UUID for either kind, or — for an* issue only — a bare identifier (`MUL-123`). Callers dispatch on the shape@@ -95,6 +96,7 @@ export interface WorkspaceEntityRef {const ENTITY_ROUTE_SEGMENTS: Record<string, WorkspaceEntityRef["kind"]> = {issues: "issue",projects: "project",+ docs: "doc",};const UUID_RE =diff --git a/packages/views/i18n/resources-types.ts b/packages/views/i18n/resources-types.tsindex a7a87c2b5c..bedb8f6256 100644--- a/packages/views/i18n/resources-types.ts+++ b/packages/views/i18n/resources-types.ts@@ -1,3 +1,4 @@+import type docs from "../locales/en/docs.json";import "i18next";// Pulls in the `ui` namespace augmentation owned by packages/ui — see// packages/ui/types/i18next.ts. Side-effect import is required for views'@@ -44,6 +45,7 @@ import type billing from "../locales/en/billing.json";// selector form standalone without depending on @multica/views.declare global {interface I18nResources {+ docs: typeof docs;common: typeof common;auth: typeof auth;settings: typeof settings;diff --git a/packages/views/layout/app-rail.test.tsx b/packages/views/layout/app-rail.test.tsxindex a5e3d300f9..b7ab1ce369 100644--- a/packages/views/layout/app-rail.test.tsx+++ b/packages/views/layout/app-rail.test.tsx@@ -165,11 +165,11 @@ describe("AppRail global actions", () => {describe("AppRail order", () => {it("lists the spaces in the default order", () => {renderRail();- expect(railOrder()).toEqual(["work", "team", "chat", "autopilots"]);+ expect(railOrder()).toEqual(["work", "docs", "team", "chat", "autopilots"]);});it("follows the saved order", () => {- const order = ["chat", "work", "team", "autopilots"] as const;+ const order = ["chat", "work", "docs", "team", "autopilots"] as const;useRailOrderStore.getState().setOrder(order);renderRail();expect(railOrder()).toEqual(order);diff --git a/packages/views/layout/app-rail.tsx b/packages/views/layout/app-rail.tsxindex 73fa233920..4588cd3b8e 100644--- a/packages/views/layout/app-rail.tsx+++ b/packages/views/layout/app-rail.tsx@@ -388,6 +388,12 @@ export function AppRail({label: t(($) => $.rail.work),fullLabel: t(($) => $.spaces.work),},+ docs: {+ href: p.docs(),+ icon: routeIconForPath(p.docs()),+ label: t(($) => $.rail.docs),+ fullLabel: t(($) => $.nav.docs),+ },team: {href: p.agents(),icon: Users,diff --git a/packages/views/layout/app-shell-context.tsx b/packages/views/layout/app-shell-context.tsxindex 82fe10baea..3a11c4565f 100644--- a/packages/views/layout/app-shell-context.tsx+++ b/packages/views/layout/app-shell-context.tsx@@ -10,7 +10,7 @@ import { useNavigation } from "../navigation";* list-and-detail pages that already render their own list column in the* same card, so the shell adds no panel for them.*/-export const PANEL_SPACES: ReadonlySet<AppSpaceId> = new Set(["work", "team", "autopilots"]);+export const PANEL_SPACES: ReadonlySet<AppSpaceId> = new Set(["work", "team", "autopilots", "docs"]);// Opening waits for the pointer to settle so sweeping across the rail does// not flash every panel; closing waits long enough to cross the gap betweendiff --git a/packages/views/layout/space-panel.tsx b/packages/views/layout/space-panel.tsxindex c3c92a00de..d1ac2f008a 100644--- a/packages/views/layout/space-panel.tsx+++ b/packages/views/layout/space-panel.tsx@@ -1,4 +1,5 @@"use client";+import { DocTree } from "../docs/components/doc-tree";import { useEffect, useRef } from "react";import type { AppSpaceId } from "@multica/core/paths";@@ -14,6 +15,7 @@ import { KeptRowsRelease, WorkPanel } from "./panels/work-panel";const PANELS: Partial<Record<AppSpaceId, () => React.ReactNode>> = {work: WorkPanel,+ docs: DocTree,team: TeamPanel,autopilots: AutopilotsPanel,};diff --git a/packages/views/layout/tab-presentation.tsx b/packages/views/layout/tab-presentation.tsxindex 55a58741df..1b9f79006e 100644--- a/packages/views/layout/tab-presentation.tsx+++ b/packages/views/layout/tab-presentation.tsx@@ -1,5 +1,6 @@"use client";+import { docDetailOptions, docTreeOptions } from "@multica/core/docs";import { useMemo } from "react";import { useInfiniteQuery, useQuery } from "@tanstack/react-query";import { issueStatusListOptions, buildIssueStatusCatalog } from "@multica/core/issue-statuses/queries";@@ -70,6 +71,8 @@ const PENDING_RESOURCE_KEYS: ReadonlySet<TabLabelKey> = new Set<TabLabelKey>(["member","squad","skill",+ "doc",+ "docFolder","machine","runtime",]);@@ -138,6 +141,11 @@ function useTabEntityData(subject: TabSubject, wsId: string, fetch: boolean): Re),enabled: false,}).data;+ const doc = useQuery({+ ...docDetailOptions(wsId, subject.kind === "doc" ? subject.id : NONE),+ enabled: false,+ }).data;+ const docTree = useQuery({ ...docTreeOptions(wsId), enabled: false }).data;const skill = useQuery({...skillDetailOptions(wsId, subject.kind === "skill" ? subject.id : NONE),enabled: false,@@ -168,6 +176,12 @@ function useTabEntityData(subject: TabSubject, wsId: string, fetch: boolean): Recase "autopilot":if (autopilot) data.autopilot = { title: autopilot.autopilot.title };break;+ case "doc":+ if (doc) data.doc = { title: doc.title };+ break;+ case "docFolder":+ data.docFolder = docTree?.folders.find((f) => f.id === subject.id);+ break;case "skill":if (skill) data.skill = { name: skill.name };break;diff --git a/packages/views/locales/en.ts b/packages/views/locales/en.tsindex 7e0116c056..32bce635a5 100644--- a/packages/views/locales/en.ts+++ b/packages/views/locales/en.ts@@ -1,4 +1,5 @@import type { LocaleResources } from "@multica/core/i18n";+import enDocs from "./en/docs.json";import enCommon from "./en/common.json";import enAuth from "./en/auth.json";import enSettings from "./en/settings.json";@@ -26,6 +27,7 @@ import enSquads from "./en/squads.json";import enBilling from "./en/billing.json";const resources: LocaleResources = {+ docs: enDocs,common: enCommon,auth: enAuth,settings: enSettings,diff --git a/packages/views/locales/en/docs.json b/packages/views/locales/en/docs.jsonnew file mode 100644index 0000000000..e29d3bc1f0--- /dev/null+++ b/packages/views/locales/en/docs.json@@ -0,0 +1,61 @@+{+ "untitled": "Untitled",+ "version_number": "v{{number}}",+ "kb": "Docs",+ "actions": {+ "new": "New",+ "new_doc": "New doc",+ "new_folder": "New folder",+ "rename": "Rename",+ "move": "Move to...",+ "delete": "Delete",+ "cancel": "Cancel",+ "history": "History",+ "more": "More",+ "copy_link": "Copy link"+ },+ "errors": {+ "move": "Couldn't move it",+ "delete": "Couldn't delete it",+ "save": "Couldn't save"+ },+ "move": {+ "title": "Move \"{{title}}\"",+ "destination": "Destination",+ "root": "Knowledge base (top level)",+ "current": "Current",+ "confirm": "Move"+ },+ "delete": {+ "title": "Delete this doc?",+ "description": "\"{{title}}\" and its whole history will be deleted. This can't be undone.",+ "confirm": "Delete",+ "folder_title": "Delete this folder?",+ "folder_description": "Only empty folders can be deleted."+ },+ "tree": {+ "more": "More actions for {{title}}",+ "empty": "No docs yet",+ "new_doc_in": "New doc in {{title}}"+ },+ "editor": {+ "placeholder": "Write, or type / for commands...",+ "title_label": "Title",+ "saving": "Saving...",+ "saved": "Saved",+ "save_failed": "Not saved · Retry",+ "retry": "Retry",+ "conflict": "Updated by {{name}}. Your draft is kept. Reload to continue.",+ "reload": "Reload latest",+ "draft": "Your saved draft"+ },+ "history": {+ "title": "History",+ "current": "Current",+ "restore": "Restore this version",+ "loading": "Loading..."+ },+ "edited": "Edited {{time}}",+ "outline": "Outline",+ "link_copied": "Link copied"+}diff --git a/packages/views/locales/en/editor.json b/packages/views/locales/en/editor.jsonindex c630c5e7bf..a790c712ae 100644--- a/packages/views/locales/en/editor.json+++ b/packages/views/locales/en/editor.json@@ -107,6 +107,7 @@"group_users": "Users","group_issues": "Issues","group_projects": "Projects",+ "group_docs": "Docs","all_members": "All members","agent_badge": "Agent","squad_badge": "Squad",@@ -231,5 +232,31 @@"later": "Not now","start": "Start dictating"}+ },+ "block_menu": {+ "label": "Insert block",+ "blocks": {+ "paragraph": "Text",+ "heading1": "Heading 1",+ "heading2": "Heading 2",+ "heading3": "Heading 3",+ "bulletList": "Bulleted list",+ "orderedList": "Numbered list",+ "taskList": "Task list",+ "blockquote": "Quote",+ "codeBlock": "Code block",+ "mermaid": "Mermaid diagram",+ "table": "Table",+ "divider": "Divider",+ "image": "Image",+ "file": "File"+ }+ },+ "block_handle": {+ "add": "Add below",+ "options": "Drag to move, click for options",+ "turn_into": "Turn into",+ "duplicate": "Duplicate",+ "delete": "Delete"}}diff --git a/packages/views/locales/en/layout.json b/packages/views/locales/en/layout.jsonindex 8800e3b7fc..e768d0d645 100644--- a/packages/views/locales/en/layout.json+++ b/packages/views/locales/en/layout.json@@ -12,7 +12,8 @@"runtimes": "Runtimes","skills": "Skills","settings": "Settings",- "views": "Views"+ "views": "Views",+ "docs": "Docs"},"tab": {"issue": "Issue",@@ -27,7 +28,9 @@"attachment": "Attachment","create_agent": "Create Agent","my_agents": "My agents' work",- "unknown": "Unknown page"+ "unknown": "Unknown page",+ "doc": "Docs",+ "docFolder": "Folder"},"help": {"trigger": "Help",@@ -118,7 +121,8 @@"reset_order": "Reset to default order","copy_workspace_link": "Copy workspace link","workspace_meta_one": "{{slug}} · {{count}} member",- "workspace_meta_other": "{{slug}} · {{count}} members"+ "workspace_meta_other": "{{slug}} · {{count}} members",+ "docs": "Docs"},"bottom_bar": {"label": "Status bar",diff --git a/packages/views/locales/en/search.json b/packages/views/locales/en/search.jsonindex daa86514cd..febed677b8 100644--- a/packages/views/locales/en/search.json+++ b/packages/views/locales/en/search.json@@ -16,6 +16,7 @@"autopilots": "Autopilots","chats": "Chats","skills": "Skills",+ "docs": "Docs","cancelled": "Cancelled","recent": "Recent","workspaces": "Workspaces",diff --git a/packages/views/locales/es.ts b/packages/views/locales/es.tsindex ae4bcc7584..f534cc9956 100644--- a/packages/views/locales/es.ts+++ b/packages/views/locales/es.ts@@ -1,4 +1,5 @@import type { LocaleResources } from "@multica/core/i18n";+import esDocs from "./es/docs.json";import esCommon from "./es/common.json";import esAuth from "./es/auth.json";import esSettings from "./es/settings.json";@@ -26,6 +27,7 @@ import esSquads from "./es/squads.json";import esBilling from "./es/billing.json";const resources: LocaleResources = {+ docs: esDocs,common: esCommon,auth: esAuth,settings: esSettings,diff --git a/packages/views/locales/es/docs.json b/packages/views/locales/es/docs.jsonnew file mode 100644index 0000000000..46981a3dd9--- /dev/null+++ b/packages/views/locales/es/docs.json@@ -0,0 +1,61 @@+{+ "untitled": "Sin título",+ "version_number": "v{{number}}",+ "kb": "Documentos",+ "actions": {+ "new": "Nuevo",+ "new_doc": "Nuevo documento",+ "new_folder": "Nueva carpeta",+ "rename": "Renombrar",+ "move": "Mover a...",+ "delete": "Eliminar",+ "cancel": "Cancelar",+ "history": "Historial",+ "more": "Más",+ "copy_link": "Copiar enlace"+ },+ "errors": {+ "move": "No se pudo mover",+ "delete": "No se pudo eliminar",+ "save": "No se pudo guardar"+ },+ "move": {+ "title": "Mover \"{{title}}\"",+ "destination": "Destino",+ "root": "Documentos (nivel superior)",+ "current": "Actual",+ "confirm": "Mover"+ },+ "delete": {+ "title": "¿Eliminar este documento?",+ "description": "Se eliminará \"{{title}}\" y todo su historial. Esta acción no se puede deshacer.",+ "confirm": "Eliminar",+ "folder_title": "¿Eliminar esta carpeta?",+ "folder_description": "Solo se pueden eliminar carpetas vacías."+ },+ "tree": {+ "more": "Más acciones para {{title}}",+ "empty": "Aún no hay documentos",+ "new_doc_in": "Nuevo documento en {{title}}"+ },+ "editor": {+ "placeholder": "Escribe o pulsa / para ver los comandos...",+ "title_label": "Título",+ "saving": "Guardando...",+ "saved": "Guardado",+ "save_failed": "Sin guardar · Reintentar",+ "retry": "Reintentar",+ "conflict": "{{name}} actualizó el documento. Tu borrador se conserva. Recarga para continuar.",+ "reload": "Cargar última versión",+ "draft": "Tu borrador guardado"+ },+ "history": {+ "title": "Historial",+ "current": "Actual",+ "restore": "Restaurar esta versión",+ "loading": "Cargando..."+ },+ "edited": "Editado {{time}}",+ "outline": "Esquema",+ "link_copied": "Enlace copiado"+}diff --git a/packages/views/locales/es/editor.json b/packages/views/locales/es/editor.jsonindex b54f12bdc1..fbc16e8a5b 100644--- a/packages/views/locales/es/editor.json+++ b/packages/views/locales/es/editor.json@@ -107,6 +107,7 @@"group_users": "Usuarios","group_issues": "Tareas","group_projects": "Proyectos",+ "group_docs": "Documentos","all_members": "Todos los miembros","agent_badge": "Agente","squad_badge": "Squad",@@ -231,5 +232,31 @@"later": "Ahora no","start": "Empezar a dictar"}+ },+ "block_menu": {+ "label": "Insertar bloque",+ "blocks": {+ "paragraph": "Texto",+ "heading1": "Encabezado 1",+ "heading2": "Encabezado 2",+ "heading3": "Encabezado 3",+ "bulletList": "Lista con viñetas",+ "orderedList": "Lista numerada",+ "taskList": "Lista de tareas",+ "blockquote": "Cita",+ "codeBlock": "Bloque de código",+ "mermaid": "Diagrama Mermaid",+ "table": "Tabla",+ "divider": "Separador",+ "image": "Imagen",+ "file": "Archivo"+ }+ },+ "block_handle": {+ "add": "Añadir debajo",+ "options": "Arrastra para mover, haz clic para ver opciones",+ "turn_into": "Convertir en",+ "duplicate": "Duplicar",+ "delete": "Eliminar"}}diff --git a/packages/views/locales/es/layout.json b/packages/views/locales/es/layout.jsonindex 740fcd9b8b..115edd33bf 100644--- a/packages/views/locales/es/layout.json+++ b/packages/views/locales/es/layout.json@@ -12,7 +12,8 @@"runtimes": "Runtimes","skills": "Skills","settings": "Ajustes",- "views": "Vistas"+ "views": "Vistas",+ "docs": "Documentos"},"tab": {"issue": "Tarea",@@ -27,7 +28,9 @@"attachment": "Adjunto","create_agent": "Crear agente","unknown": "Página desconocida",- "my_agents": "Trabajo de mis agentes"+ "my_agents": "Trabajo de mis agentes",+ "doc": "Documentos",+ "docFolder": "Carpeta"},"help": {"trigger": "Ayuda",@@ -118,7 +121,8 @@"reset_order": "Restablecer el orden predeterminado","copy_workspace_link": "Copiar enlace del espacio de trabajo","workspace_meta_one": "{{slug}} · {{count}} miembro",- "workspace_meta_other": "{{slug}} · {{count}} miembros"+ "workspace_meta_other": "{{slug}} · {{count}} miembros",+ "docs": "Documentos"},"bottom_bar": {"label": "Barra de estado",diff --git a/packages/views/locales/es/search.json b/packages/views/locales/es/search.jsonindex 9394225be3..22cfcbf179 100644--- a/packages/views/locales/es/search.json+++ b/packages/views/locales/es/search.json@@ -17,6 +17,7 @@"autopilots": "Automatizaciones","chats": "Chats","skills": "Skills",+ "docs": "Documentos","new": "Nuevo","best_match": "Mejor coincidencia","actions": "Acciones"diff --git a/packages/views/locales/fr.ts b/packages/views/locales/fr.tsindex 9b33105bd3..b1e71cfa66 100644--- a/packages/views/locales/fr.ts+++ b/packages/views/locales/fr.ts@@ -1,4 +1,5 @@import type { LocaleResources } from "@multica/core/i18n";+import frDocs from "./fr/docs.json";import frCommon from "./fr/common.json";import frAuth from "./fr/auth.json";import frSettings from "./fr/settings.json";@@ -26,6 +27,7 @@ import frSquads from "./fr/squads.json";import frBilling from "./fr/billing.json";const resources: LocaleResources = {+ docs: frDocs,common: frCommon,auth: frAuth,settings: frSettings,diff --git a/packages/views/locales/fr/docs.json b/packages/views/locales/fr/docs.jsonnew file mode 100644index 0000000000..fd1f81ce7c--- /dev/null+++ b/packages/views/locales/fr/docs.json@@ -0,0 +1,61 @@+{+ "untitled": "Sans titre",+ "version_number": "v{{number}}",+ "kb": "Documents",+ "actions": {+ "new": "Nouveau",+ "new_doc": "Nouveau document",+ "new_folder": "Nouveau dossier",+ "rename": "Renommer",+ "move": "Déplacer vers...",+ "delete": "Supprimer",+ "cancel": "Annuler",+ "history": "Historique",+ "more": "Plus",+ "copy_link": "Copier le lien"+ },+ "errors": {+ "move": "Impossible de déplacer l'élément",+ "delete": "Impossible de supprimer l'élément",+ "save": "Échec de l'enregistrement"+ },+ "move": {+ "title": "Déplacer « {{title}} »",+ "destination": "Destination",+ "root": "Base de connaissances (racine)",+ "current": "Actuel",+ "confirm": "Déplacer"+ },+ "delete": {+ "title": "Supprimer ce document ?",+ "description": "« {{title}} » et tout son historique seront supprimés. Action irréversible.",+ "confirm": "Supprimer",+ "folder_title": "Supprimer ce dossier ?",+ "folder_description": "Seuls les dossiers vides peuvent être supprimés."+ },+ "tree": {+ "more": "Plus d'actions pour {{title}}",+ "empty": "Aucun document",+ "new_doc_in": "Nouveau document dans {{title}}"+ },+ "editor": {+ "placeholder": "Écrivez, ou tapez / pour les commandes...",+ "title_label": "Titre",+ "saving": "Enregistrement...",+ "saved": "Enregistré",+ "save_failed": "Non enregistré · Réessayer",+ "retry": "Réessayer",+ "conflict": "{{name}} a modifié le document. Votre brouillon est conservé. Rechargez pour continuer.",+ "reload": "Recharger la dernière version",+ "draft": "Votre brouillon conservé"+ },+ "history": {+ "title": "Historique",+ "current": "Actuelle",+ "restore": "Restaurer cette version",+ "loading": "Chargement..."+ },+ "edited": "Modifié {{time}}",+ "outline": "Plan",+ "link_copied": "Lien copié"+}diff --git a/packages/views/locales/fr/editor.json b/packages/views/locales/fr/editor.jsonindex ecd9ec0fb3..2625ebd0df 100644--- a/packages/views/locales/fr/editor.json+++ b/packages/views/locales/fr/editor.json@@ -107,6 +107,7 @@"group_users": "Utilisateurs","group_issues": "Tâches","group_projects": "Projets",+ "group_docs": "Documents","all_members": "Tous les membres","agent_badge": "Agent","squad_badge": "Squad",@@ -231,5 +232,31 @@"later": "Plus tard","start": "Commencer à dicter"}+ },+ "block_menu": {+ "label": "Insérer un bloc",+ "blocks": {+ "paragraph": "Texte",+ "heading1": "Titre 1",+ "heading2": "Titre 2",+ "heading3": "Titre 3",+ "bulletList": "Liste à puces",+ "orderedList": "Liste numérotée",+ "taskList": "Liste de tâches",+ "blockquote": "Citation",+ "codeBlock": "Bloc de code",+ "mermaid": "Diagramme Mermaid",+ "table": "Tableau",+ "divider": "Séparateur",+ "image": "Image",+ "file": "Fichier"+ }+ },+ "block_handle": {+ "add": "Ajouter en dessous",+ "options": "Glisser pour déplacer, cliquer pour les options",+ "turn_into": "Transformer en",+ "duplicate": "Dupliquer",+ "delete": "Supprimer"}}diff --git a/packages/views/locales/fr/layout.json b/packages/views/locales/fr/layout.jsonindex 42de93fe67..fb218c5b13 100644--- a/packages/views/locales/fr/layout.json+++ b/packages/views/locales/fr/layout.json@@ -12,7 +12,8 @@"runtimes": "Runtimes","skills": "Skills","settings": "Paramètres",- "views": "Vues"+ "views": "Vues",+ "docs": "Documents"},"tab": {"issue": "Tâche",@@ -27,7 +28,9 @@"attachment": "Pièce jointe","create_agent": "Créer un agent","my_agents": "Travail de mes agents",- "unknown": "Page inconnue"+ "unknown": "Page inconnue",+ "doc": "Documents",+ "docFolder": "Dossier"},"help": {"trigger": "Aide",@@ -118,7 +121,8 @@"reset_order": "Rétablir l’ordre par défaut","copy_workspace_link": "Copier le lien de l’espace de travail","workspace_meta_one": "{{slug}} · {{count}} membre",- "workspace_meta_other": "{{slug}} · {{count}} membres"+ "workspace_meta_other": "{{slug}} · {{count}} membres",+ "docs": "Documents"},"bottom_bar": {"label": "Barre d'état",diff --git a/packages/views/locales/fr/search.json b/packages/views/locales/fr/search.jsonindex 72cb128b76..eb39bdd806 100644--- a/packages/views/locales/fr/search.json+++ b/packages/views/locales/fr/search.json@@ -16,6 +16,7 @@"autopilots": "Automatisations","chats": "Discussions","skills": "Skills",+ "docs": "Documents","cancelled": "Annulés","recent": "Récents","workspaces": "Espaces de travail",diff --git a/packages/views/locales/ja.ts b/packages/views/locales/ja.tsindex 636f6ce055..3dfaf83b8e 100644--- a/packages/views/locales/ja.ts+++ b/packages/views/locales/ja.ts@@ -1,4 +1,5 @@import type { LocaleResources } from "@multica/core/i18n";+import jaDocs from "./ja/docs.json";import jaCommon from "./ja/common.json";import jaAuth from "./ja/auth.json";import jaSettings from "./ja/settings.json";@@ -26,6 +27,7 @@ import jaSquads from "./ja/squads.json";import jaBilling from "./ja/billing.json";const resources: LocaleResources = {+ docs: jaDocs,common: jaCommon,auth: jaAuth,settings: jaSettings,diff --git a/packages/views/locales/ja/docs.json b/packages/views/locales/ja/docs.jsonnew file mode 100644index 0000000000..2eb00706d4--- /dev/null+++ b/packages/views/locales/ja/docs.json@@ -0,0 +1,61 @@+{+ "untitled": "無題",+ "version_number": "v{{number}}",+ "kb": "ドキュメント",+ "actions": {+ "new": "新規",+ "new_doc": "新規ドキュメント",+ "new_folder": "新規フォルダ",+ "rename": "名前を変更",+ "move": "移動...",+ "delete": "削除",+ "cancel": "キャンセル",+ "history": "履歴",+ "more": "その他",+ "copy_link": "リンクをコピー"+ },+ "errors": {+ "move": "移動できませんでした",+ "delete": "削除できませんでした",+ "save": "保存できませんでした"+ },+ "move": {+ "title": "\"{{title}}\"を移動",+ "destination": "移動先",+ "root": "ナレッジベース(最上位)",+ "current": "現在",+ "confirm": "移動"+ },+ "delete": {+ "title": "このドキュメントを削除しますか?",+ "description": "\"{{title}}\"とその履歴がすべて削除されます。元に戻せません。",+ "confirm": "削除",+ "folder_title": "フォルダーを削除しますか?",+ "folder_description": "空のフォルダーのみ削除できます。"+ },+ "tree": {+ "more": "{{title}} のその他の操作",+ "empty": "ドキュメントはまだありません",+ "new_doc_in": "「{{title}}」にドキュメントを作成"+ },+ "editor": {+ "placeholder": "入力するか / でコマンド...",+ "title_label": "タイトル",+ "saving": "保存中...",+ "saved": "保存済み",+ "save_failed": "未保存 · 再試行",+ "retry": "再試行",+ "conflict": "{{name}} が更新しました。下書きを保持しています。再読み込みして続けてください。",+ "reload": "最新版を読み込む",+ "draft": "保存した下書き"+ },+ "history": {+ "title": "履歴",+ "current": "現在",+ "restore": "このバージョンを復元",+ "loading": "読み込み中..."+ },+ "edited": "最終編集 {{time}}",+ "outline": "目次",+ "link_copied": "リンクをコピーしました"+}diff --git a/packages/views/locales/ja/editor.json b/packages/views/locales/ja/editor.jsonindex 43b4e291df..81b68c97cf 100644--- a/packages/views/locales/ja/editor.json+++ b/packages/views/locales/ja/editor.json@@ -103,6 +103,7 @@"group_users": "ユーザー","group_issues": "タスク","group_projects": "プロジェクト",+ "group_docs": "ドキュメント","all_members": "すべてのメンバー","agent_badge": "エージェント","squad_badge": "スクワッド",@@ -227,5 +228,31 @@"later": "後で","start": "音声入力を開始"}+ },+ "block_menu": {+ "label": "ブロックを挿入",+ "blocks": {+ "paragraph": "テキスト",+ "heading1": "見出し 1",+ "heading2": "見出し 2",+ "heading3": "見出し 3",+ "bulletList": "箇条書きリスト",+ "orderedList": "番号付きリスト",+ "taskList": "チェックリスト",+ "blockquote": "引用",+ "codeBlock": "コードブロック",+ "mermaid": "Mermaid 図",+ "table": "表",+ "divider": "区切り線",+ "image": "画像",+ "file": "ファイル"+ }+ },+ "block_handle": {+ "add": "下に追加",+ "options": "ドラッグで移動、クリックでメニュー",+ "turn_into": "変換",+ "duplicate": "複製",+ "delete": "削除"}}diff --git a/packages/views/locales/ja/layout.json b/packages/views/locales/ja/layout.jsonindex 2730b77433..875e491650 100644--- a/packages/views/locales/ja/layout.json+++ b/packages/views/locales/ja/layout.json@@ -12,7 +12,8 @@"runtimes": "ランタイム","skills": "スキル","settings": "設定",- "views": "ビュー"+ "views": "ビュー",+ "docs": "ドキュメント"},"tab": {"issue": "タスク",@@ -27,7 +28,9 @@"attachment": "添付ファイル","create_agent": "エージェントを作成","my_agents": "マイエージェントの作業",- "unknown": "不明なページ"+ "unknown": "不明なページ",+ "doc": "ドキュメント",+ "docFolder": "フォルダー"},"help": {"trigger": "ヘルプ",@@ -116,7 +119,8 @@"mark_all_read_failed": "すべて既読にできませんでした","reset_order": "デフォルトの順序に戻す","copy_workspace_link": "ワークスペースのリンクをコピー",- "workspace_meta_other": "{{slug}} · メンバー {{count}} 人"+ "workspace_meta_other": "{{slug}} · メンバー {{count}} 人",+ "docs": "ドキュメント"},"bottom_bar": {"label": "ステータスバー",diff --git a/packages/views/locales/ja/search.json b/packages/views/locales/ja/search.jsonindex c2dbf9f2b1..f248b29677 100644--- a/packages/views/locales/ja/search.json+++ b/packages/views/locales/ja/search.json@@ -16,6 +16,7 @@"autopilots": "オートパイロット","chats": "チャット","skills": "スキル",+ "docs": "ドキュメント","cancelled": "キャンセル済み","recent": "最近の項目","workspaces": "ワークスペース",diff --git a/packages/views/locales/ko.ts b/packages/views/locales/ko.tsindex fed8d51f4e..e89c30c47c 100644--- a/packages/views/locales/ko.ts+++ b/packages/views/locales/ko.ts@@ -1,4 +1,5 @@import type { LocaleResources } from "@multica/core/i18n";+import koDocs from "./ko/docs.json";import koCommon from "./ko/common.json";import koAuth from "./ko/auth.json";import koSettings from "./ko/settings.json";@@ -26,6 +27,7 @@ import koSquads from "./ko/squads.json";import koBilling from "./ko/billing.json";const resources: LocaleResources = {+ docs: koDocs,common: koCommon,auth: koAuth,settings: koSettings,diff --git a/packages/views/locales/ko/docs.json b/packages/views/locales/ko/docs.jsonnew file mode 100644index 0000000000..5092a75ecf--- /dev/null+++ b/packages/views/locales/ko/docs.json@@ -0,0 +1,61 @@+{+ "untitled": "제목 없음",+ "version_number": "v{{number}}",+ "kb": "문서",+ "actions": {+ "new": "새로 만들기",+ "new_doc": "새 문서",+ "new_folder": "새 폴더",+ "rename": "이름 변경",+ "move": "이동...",+ "delete": "삭제",+ "cancel": "취소",+ "history": "기록",+ "more": "더 보기",+ "copy_link": "링크 복사"+ },+ "errors": {+ "move": "이동하지 못했습니다",+ "delete": "삭제하지 못했습니다",+ "save": "저장하지 못했습니다"+ },+ "move": {+ "title": "‘{{title}}’ 이동",+ "destination": "대상 위치",+ "root": "지식 베이스(최상위)",+ "current": "현재",+ "confirm": "이동"+ },+ "delete": {+ "title": "이 문서를 삭제할까요?",+ "description": "‘{{title}}’와 전체 기록이 삭제됩니다. 되돌릴 수 없습니다.",+ "confirm": "삭제",+ "folder_title": "폴더를 삭제할까요?",+ "folder_description": "빈 폴더만 삭제할 수 있습니다."+ },+ "tree": {+ "more": "{{title}} 더 보기",+ "empty": "아직 문서가 없습니다",+ "new_doc_in": "'{{title}}'에 새 문서"+ },+ "editor": {+ "placeholder": "입력하거나 /로 명령어...",+ "title_label": "제목",+ "saving": "저장 중...",+ "saved": "저장됨",+ "save_failed": "저장 안 됨 · 다시 시도",+ "retry": "다시 시도",+ "conflict": "{{name}}님이 수정했습니다. 초안이 보존됩니다. 다시 불러와 계속하세요.",+ "reload": "최신 버전 불러오기",+ "draft": "보존된 초안"+ },+ "history": {+ "title": "기록",+ "current": "현재",+ "restore": "이 버전 복원",+ "loading": "불러오는 중..."+ },+ "edited": "{{time}} 편집",+ "outline": "개요",+ "link_copied": "링크를 복사했습니다"+}diff --git a/packages/views/locales/ko/editor.json b/packages/views/locales/ko/editor.jsonindex ae5c2df847..91247b56cb 100644--- a/packages/views/locales/ko/editor.json+++ b/packages/views/locales/ko/editor.json@@ -103,6 +103,7 @@"group_users": "사용자","group_issues": "태스크","group_projects": "프로젝트",+ "group_docs": "문서","all_members": "모든 멤버","agent_badge": "에이전트","squad_badge": "스쿼드",@@ -227,5 +228,31 @@"later": "나중에","start": "받아쓰기 시작"}+ },+ "block_menu": {+ "label": "블록 삽입",+ "blocks": {+ "paragraph": "텍스트",+ "heading1": "제목 1",+ "heading2": "제목 2",+ "heading3": "제목 3",+ "bulletList": "글머리 기호 목록",+ "orderedList": "번호 매기기 목록",+ "taskList": "체크리스트",+ "blockquote": "인용",+ "codeBlock": "코드 블록",+ "mermaid": "Mermaid 다이어그램",+ "table": "표",+ "divider": "구분선",+ "image": "이미지",+ "file": "파일"+ }+ },+ "block_handle": {+ "add": "아래에 추가",+ "options": "드래그하여 이동, 클릭하여 메뉴 열기",+ "turn_into": "변환",+ "duplicate": "복제",+ "delete": "삭제"}}diff --git a/packages/views/locales/ko/layout.json b/packages/views/locales/ko/layout.jsonindex c21d0b0cc1..6e9563de59 100644--- a/packages/views/locales/ko/layout.json+++ b/packages/views/locales/ko/layout.json@@ -12,7 +12,8 @@"runtimes": "런타임","skills": "스킬","settings": "설정",- "views": "뷰"+ "views": "뷰",+ "docs": "문서"},"tab": {"issue": "태스크",@@ -27,7 +28,9 @@"attachment": "첨부파일","create_agent": "에이전트 만들기","my_agents": "내 에이전트의 작업",- "unknown": "알 수 없는 페이지"+ "unknown": "알 수 없는 페이지",+ "doc": "문서",+ "docFolder": "폴더"},"help": {"trigger": "도움말",@@ -116,7 +119,8 @@"mark_all_read_failed": "모두 읽음으로 표시하지 못했습니다","reset_order": "기본 순서로 재설정","copy_workspace_link": "작업 공간 링크 복사",- "workspace_meta_other": "{{slug}} · 멤버 {{count}}명"+ "workspace_meta_other": "{{slug}} · 멤버 {{count}}명",+ "docs": "문서"},"bottom_bar": {"label": "상태 표시줄",diff --git a/packages/views/locales/ko/search.json b/packages/views/locales/ko/search.jsonindex 029ec70905..281421f7f5 100644--- a/packages/views/locales/ko/search.json+++ b/packages/views/locales/ko/search.json@@ -16,6 +16,7 @@"autopilots": "오토파일럿","chats": "채팅","skills": "스킬",+ "docs": "문서","cancelled": "취소됨","recent": "최근 항목","workspaces": "워크스페이스",diff --git a/packages/views/locales/ru.ts b/packages/views/locales/ru.tsindex 2123509474..5e21017454 100644--- a/packages/views/locales/ru.ts+++ b/packages/views/locales/ru.ts@@ -1,4 +1,5 @@import type { LocaleResources } from "@multica/core/i18n";+import ruDocs from "./ru/docs.json";import ruCommon from "./ru/common.json";import ruAuth from "./ru/auth.json";import ruSettings from "./ru/settings.json";@@ -26,6 +27,7 @@ import ruSquads from "./ru/squads.json";import ruBilling from "./ru/billing.json";const resources: LocaleResources = {+ docs: ruDocs,common: ruCommon,auth: ruAuth,settings: ruSettings,diff --git a/packages/views/locales/ru/docs.json b/packages/views/locales/ru/docs.jsonnew file mode 100644index 0000000000..1a1a76d59b--- /dev/null+++ b/packages/views/locales/ru/docs.json@@ -0,0 +1,61 @@+{+ "untitled": "Без названия",+ "version_number": "v{{number}}",+ "kb": "Документы",+ "actions": {+ "new": "Создать",+ "new_doc": "Новый документ",+ "new_folder": "Новая папка",+ "rename": "Переименовать",+ "move": "Переместить в...",+ "delete": "Удалить",+ "cancel": "Отмена",+ "history": "История",+ "more": "Ещё",+ "copy_link": "Копировать ссылку"+ },+ "errors": {+ "move": "Не удалось переместить",+ "delete": "Не удалось удалить",+ "save": "Не удалось сохранить"+ },+ "move": {+ "title": "Переместить \"{{title}}\"",+ "destination": "Расположение",+ "root": "Документы (верхний уровень)",+ "current": "Текущее",+ "confirm": "Переместить"+ },+ "delete": {+ "title": "Удалить документ?",+ "description": "Документ \"{{title}}\" и вся его история будут удалены. Это действие нельзя отменить.",+ "confirm": "Удалить",+ "folder_title": "Удалить папку?",+ "folder_description": "Можно удалять только пустые папки."+ },+ "tree": {+ "more": "Другие действия: {{title}}",+ "empty": "Документов пока нет",+ "new_doc_in": "Новый документ в «{{title}}»"+ },+ "editor": {+ "placeholder": "Введите текст или / для списка команд...",+ "title_label": "Название",+ "saving": "Сохранение...",+ "saved": "Сохранено",+ "save_failed": "Не сохранено · Повторить",+ "retry": "Повторить",+ "conflict": "{{name}} обновил документ. Черновик сохранён. Загрузите последнюю версию.",+ "reload": "Загрузить последнюю версию",+ "draft": "Сохранённый черновик"+ },+ "history": {+ "title": "История",+ "current": "Текущая",+ "restore": "Восстановить эту версию",+ "loading": "Загрузка..."+ },+ "edited": "Изменено {{time}}",+ "outline": "Содержание",+ "link_copied": "Ссылка скопирована"+}diff --git a/packages/views/locales/ru/editor.json b/packages/views/locales/ru/editor.jsonindex 190f5318a4..ff931db69c 100644--- a/packages/views/locales/ru/editor.json+++ b/packages/views/locales/ru/editor.json@@ -115,6 +115,7 @@"group_users": "Пользователи","group_issues": "Задачи","group_projects": "Проекты",+ "group_docs": "Документы","all_members": "Все участники","agent_badge": "Агент","squad_badge": "Команда",@@ -239,5 +240,31 @@"later": "Не сейчас","start": "Начать диктовку"}+ },+ "block_menu": {+ "label": "Вставить блок",+ "blocks": {+ "paragraph": "Текст",+ "heading1": "Заголовок 1",+ "heading2": "Заголовок 2",+ "heading3": "Заголовок 3",+ "bulletList": "Маркированный список",+ "orderedList": "Нумерованный список",+ "taskList": "Список задач",+ "blockquote": "Цитата",+ "codeBlock": "Блок кода",+ "mermaid": "Диаграмма Mermaid",+ "table": "Таблица",+ "divider": "Разделитель",+ "image": "Изображение",+ "file": "Файл"+ }+ },+ "block_handle": {+ "add": "Добавить ниже",+ "options": "Перетащите для перемещения, нажмите для меню",+ "turn_into": "Преобразовать в",+ "duplicate": "Дублировать",+ "delete": "Удалить"}}diff --git a/packages/views/locales/ru/layout.json b/packages/views/locales/ru/layout.jsonindex 8b5385075b..088647d556 100644--- a/packages/views/locales/ru/layout.json+++ b/packages/views/locales/ru/layout.json@@ -12,7 +12,8 @@"runtimes": "Среды выполнения","skills": "Навыки","settings": "Настройки",- "views": "Представления"+ "views": "Представления",+ "docs": "Документы"},"tab": {"issue": "Задача",@@ -27,7 +28,9 @@"attachment": "Вложение","create_agent": "Создать агента","my_agents": "Работа моих агентов",- "unknown": "Неизвестная страница"+ "unknown": "Неизвестная страница",+ "doc": "Документы",+ "docFolder": "Папка"},"help": {"trigger": "Помощь",@@ -90,7 +93,8 @@"workspace_meta_one": "{{slug}} · {{count}} участник","workspace_meta_few": "{{slug}} · {{count}} участника","workspace_meta_many": "{{slug}} · {{count}} участников",- "workspace_meta_other": "{{slug}} · {{count}} участника"+ "workspace_meta_other": "{{slug}} · {{count}} участника",+ "docs": "Документы"},"bottom_bar": {"label": "Строка состояния",diff --git a/packages/views/locales/ru/search.json b/packages/views/locales/ru/search.jsonindex 3113097a8c..d675918f68 100644--- a/packages/views/locales/ru/search.json+++ b/packages/views/locales/ru/search.json@@ -16,6 +16,7 @@"autopilots": "Автопилоты","chats": "Чаты","skills": "Навыки",+ "docs": "Документы","cancelled": "Отменено","recent": "Недавние","workspaces": "Рабочие пространства",diff --git a/packages/views/locales/zh-Hans.ts b/packages/views/locales/zh-Hans.tsindex 0399f15c85..4f81e65bae 100644--- a/packages/views/locales/zh-Hans.ts+++ b/packages/views/locales/zh-Hans.ts@@ -1,4 +1,5 @@import type { LocaleResources } from "@multica/core/i18n";+import zhHansDocs from "./zh-Hans/docs.json";import zhHansCommon from "./zh-Hans/common.json";import zhHansAuth from "./zh-Hans/auth.json";import zhHansSettings from "./zh-Hans/settings.json";@@ -26,6 +27,7 @@ import zhHansSquads from "./zh-Hans/squads.json";import zhHansBilling from "./zh-Hans/billing.json";const resources: LocaleResources = {+ docs: zhHansDocs,common: zhHansCommon,auth: zhHansAuth,settings: zhHansSettings,diff --git a/packages/views/locales/zh-Hans/docs.json b/packages/views/locales/zh-Hans/docs.jsonnew file mode 100644index 0000000000..6e6f4dd959--- /dev/null+++ b/packages/views/locales/zh-Hans/docs.json@@ -0,0 +1,61 @@+{+ "untitled": "未命名",+ "version_number": "v{{number}}",+ "kb": "知识库",+ "actions": {+ "new": "新建",+ "new_doc": "新建文档",+ "new_folder": "新建文件夹",+ "rename": "重命名",+ "move": "移动到...",+ "delete": "删除",+ "cancel": "取消",+ "history": "历史",+ "more": "更多",+ "copy_link": "复制链接"+ },+ "errors": {+ "move": "移动失败",+ "delete": "删除失败",+ "save": "保存失败"+ },+ "move": {+ "title": "移动\"{{title}}\"",+ "destination": "目标位置",+ "root": "知识库(顶层)",+ "current": "当前",+ "confirm": "移动"+ },+ "delete": {+ "title": "删除这篇文档?",+ "description": "\"{{title}}\"及其全部历史都会被删除,无法撤销。",+ "confirm": "删除",+ "folder_title": "删除文件夹?",+ "folder_description": "只能删除空文件夹。"+ },+ "tree": {+ "more": "{{title}} 的更多操作",+ "empty": "还没有文档",+ "new_doc_in": "在“{{title}}”中新建文档"+ },+ "editor": {+ "placeholder": "开始写,或输入 / 调出命令...",+ "title_label": "标题",+ "saving": "保存中...",+ "saved": "已保存",+ "save_failed": "保存失败 · 重试",+ "retry": "重试",+ "conflict": "{{name}} 已更新文档。草稿已保留,刷新后继续编辑。",+ "reload": "刷新最新版本",+ "draft": "保留的草稿"+ },+ "history": {+ "title": "历史",+ "current": "当前",+ "restore": "恢复此版本",+ "loading": "加载中..."+ },+ "edited": "{{time}}编辑",+ "outline": "大纲",+ "link_copied": "链接已复制"+}diff --git a/packages/views/locales/zh-Hans/editor.json b/packages/views/locales/zh-Hans/editor.jsonindex a005177ac5..cd8d088a2b 100644--- a/packages/views/locales/zh-Hans/editor.json+++ b/packages/views/locales/zh-Hans/editor.json@@ -103,6 +103,7 @@"group_users": "用户","group_issues": "任务","group_projects": "项目",+ "group_docs": "文档","all_members": "所有成员","agent_badge": "智能体","squad_badge": "小队",@@ -227,5 +228,31 @@"later": "以后再说","start": "开始口述"}+ },+ "block_menu": {+ "label": "插入内容",+ "blocks": {+ "paragraph": "正文",+ "heading1": "标题 1",+ "heading2": "标题 2",+ "heading3": "标题 3",+ "bulletList": "无序列表",+ "orderedList": "有序列表",+ "taskList": "待办列表",+ "blockquote": "引用",+ "codeBlock": "代码块",+ "mermaid": "Mermaid 图表",+ "table": "表格",+ "divider": "分割线",+ "image": "图片",+ "file": "文件"+ }+ },+ "block_handle": {+ "add": "在下方添加",+ "options": "拖动以移动,点击打开菜单",+ "turn_into": "转换为",+ "duplicate": "创建副本",+ "delete": "删除"}}diff --git a/packages/views/locales/zh-Hans/layout.json b/packages/views/locales/zh-Hans/layout.jsonindex fabaa651d6..3f5acb6b1a 100644--- a/packages/views/locales/zh-Hans/layout.json+++ b/packages/views/locales/zh-Hans/layout.json@@ -12,7 +12,8 @@"runtimes": "运行时","skills": "Skills","settings": "设置",- "views": "视图"+ "views": "视图",+ "docs": "知识库"},"tab": {"issue": "任务",@@ -27,7 +28,9 @@"attachment": "附件","create_agent": "创建智能体","my_agents": "我的智能体在做",- "unknown": "未知页面"+ "unknown": "未知页面",+ "doc": "知识库",+ "docFolder": "文件夹"},"help": {"trigger": "帮助",@@ -116,7 +119,8 @@"mark_all_read_failed": "全部标为已读失败","reset_order": "恢复默认顺序","copy_workspace_link": "复制工作区链接",- "workspace_meta_other": "{{slug}} · {{count}} 位成员"+ "workspace_meta_other": "{{slug}} · {{count}} 位成员",+ "docs": "知识库"},"bottom_bar": {"label": "状态栏",diff --git a/packages/views/locales/zh-Hans/search.json b/packages/views/locales/zh-Hans/search.jsonindex f9a9e8bdba..85898e85e5 100644--- a/packages/views/locales/zh-Hans/search.json+++ b/packages/views/locales/zh-Hans/search.json@@ -16,6 +16,7 @@"autopilots": "自动化","chats": "对话","skills": "Skills",+ "docs": "文档","cancelled": "已取消","recent": "最近","workspaces": "工作区",diff --git a/packages/views/locales/zh-Hant.ts b/packages/views/locales/zh-Hant.tsindex 7587ba007b..c53783e3c0 100644--- a/packages/views/locales/zh-Hant.ts+++ b/packages/views/locales/zh-Hant.ts@@ -1,4 +1,5 @@import type { LocaleResources } from "@multica/core/i18n";+import zhHantDocs from "./zh-Hant/docs.json";import zhHantCommon from "./zh-Hant/common.json";import zhHantAuth from "./zh-Hant/auth.json";import zhHantSettings from "./zh-Hant/settings.json";@@ -26,6 +27,7 @@ import zhHantSquads from "./zh-Hant/squads.json";import zhHantBilling from "./zh-Hant/billing.json";const resources: LocaleResources = {+ docs: zhHantDocs,common: zhHantCommon,auth: zhHantAuth,settings: zhHantSettings,diff --git a/packages/views/locales/zh-Hant/docs.json b/packages/views/locales/zh-Hant/docs.jsonnew file mode 100644index 0000000000..6155d05404--- /dev/null+++ b/packages/views/locales/zh-Hant/docs.json@@ -0,0 +1,61 @@+{+ "untitled": "未命名",+ "version_number": "v{{number}}",+ "kb": "知識庫",+ "actions": {+ "new": "新增",+ "new_doc": "新增文件",+ "new_folder": "新增資料夾",+ "rename": "重新命名",+ "move": "移動到...",+ "delete": "刪除",+ "cancel": "取消",+ "history": "歷史",+ "more": "更多",+ "copy_link": "複製連結"+ },+ "errors": {+ "move": "移動失敗",+ "delete": "刪除失敗",+ "save": "儲存失敗"+ },+ "move": {+ "title": "移動\"{{title}}\"",+ "destination": "目標位置",+ "root": "知識庫(最上層)",+ "current": "目前",+ "confirm": "移動"+ },+ "delete": {+ "title": "刪除這份文件?",+ "description": "\"{{title}}\"及其全部歷史都會被刪除,無法復原。",+ "confirm": "刪除",+ "folder_title": "刪除資料夾?",+ "folder_description": "只能刪除空資料夾。"+ },+ "tree": {+ "more": "{{title}} 的更多操作",+ "empty": "還沒有文件",+ "new_doc_in": "在「{{title}}」中新增文件"+ },+ "editor": {+ "placeholder": "開始寫,或輸入 / 叫出命令...",+ "title_label": "標題",+ "saving": "儲存中...",+ "saved": "已儲存",+ "save_failed": "儲存失敗 · 重試",+ "retry": "重試",+ "conflict": "{{name}} 已更新文件。草稿已保留,重新載入後繼續編輯。",+ "reload": "載入最新版本",+ "draft": "保留的草稿"+ },+ "history": {+ "title": "歷史",+ "current": "目前",+ "restore": "還原此版本",+ "loading": "載入中..."+ },+ "edited": "{{time}}編輯",+ "outline": "大綱",+ "link_copied": "連結已複製"+}diff --git a/packages/views/locales/zh-Hant/editor.json b/packages/views/locales/zh-Hant/editor.jsonindex 04c0ba7c37..6f4c905bee 100644--- a/packages/views/locales/zh-Hant/editor.json+++ b/packages/views/locales/zh-Hant/editor.json@@ -103,6 +103,7 @@"group_users": "使用者","group_issues": "任務","group_projects": "專案",+ "group_docs": "文件","all_members": "所有成員","agent_badge": "AI 代理","squad_badge": "小隊",@@ -227,5 +228,31 @@"later": "稍後再說","start": "開始口述"}+ },+ "block_menu": {+ "label": "插入內容",+ "blocks": {+ "paragraph": "正文",+ "heading1": "標題 1",+ "heading2": "標題 2",+ "heading3": "標題 3",+ "bulletList": "無序列表",+ "orderedList": "有序列表",+ "taskList": "待辦列表",+ "blockquote": "引用",+ "codeBlock": "程式碼區塊",+ "mermaid": "Mermaid 圖表",+ "table": "表格",+ "divider": "分隔線",+ "image": "圖片",+ "file": "檔案"+ }+ },+ "block_handle": {+ "add": "在下方新增",+ "options": "拖曳以移動,點擊開啟選單",+ "turn_into": "轉換為",+ "duplicate": "建立副本",+ "delete": "刪除"}}diff --git a/packages/views/locales/zh-Hant/layout.json b/packages/views/locales/zh-Hant/layout.jsonindex 1589410925..f51398ea0d 100644--- a/packages/views/locales/zh-Hant/layout.json+++ b/packages/views/locales/zh-Hant/layout.json@@ -12,7 +12,8 @@"runtimes": "執行時","skills": "Skills","settings": "設定",- "views": "檢視"+ "views": "檢視",+ "docs": "知識庫"},"tab": {"issue": "任務",@@ -27,7 +28,9 @@"attachment": "附件","create_agent": "建立 AI 代理","my_agents": "我的 AI 代理在做",- "unknown": "未知頁面"+ "unknown": "未知頁面",+ "doc": "知識庫",+ "docFolder": "資料夾"},"help": {"trigger": "幫助",@@ -116,7 +119,8 @@"mark_all_read_failed": "全部標為已讀失敗","reset_order": "恢復預設順序","copy_workspace_link": "複製工作區連結",- "workspace_meta_other": "{{slug}} · {{count}} 位成員"+ "workspace_meta_other": "{{slug}} · {{count}} 位成員",+ "docs": "知識庫"},"bottom_bar": {"label": "狀態列",diff --git a/packages/views/locales/zh-Hant/search.json b/packages/views/locales/zh-Hant/search.jsonindex 8961bc0717..4fb0852c0d 100644--- a/packages/views/locales/zh-Hant/search.json+++ b/packages/views/locales/zh-Hant/search.json@@ -16,6 +16,7 @@"autopilots": "自動化","chats": "對話","skills": "Skills",+ "docs": "文件","cancelled": "已取消","recent": "最近","workspaces": "工作區",diff --git a/packages/views/package.json b/packages/views/package.jsonindex 03fa0fe14e..9598fe8db9 100644--- a/packages/views/package.json+++ b/packages/views/package.json@@ -87,7 +87,8 @@"./locales/fr": "./locales/fr.ts","./locales/es": "./locales/es.ts","./locales/ru": "./locales/ru.ts",- "./locales/*": "./locales/*"+ "./locales/*": "./locales/*",+ "./docs": "./docs/index.ts"},"dependencies": {"@base-ui/react": "catalog:",diff --git a/packages/views/rich-content/rich-content.tsx b/packages/views/rich-content/rich-content.tsxindex 505890cc0b..2277fc4cf5 100644--- a/packages/views/rich-content/rich-content.tsx+++ b/packages/views/rich-content/rich-content.tsx@@ -57,6 +57,7 @@ import {import { IssueMentionCard } from "../issues/components/issue-mention-card";import { useResolveIssueIdentifier } from "../issues/hooks";import { ProjectMentionCard } from "../projects/components/project-mention-card";+import { DocMentionCard } from "../docs/components/doc-mention-card";import { useLinkHover, LinkHoverCard } from "../editor/link-hover-card";import {openLink,@@ -165,6 +166,15 @@ function ProjectMentionLink({ projectId, label }: { projectId: string; label?: s);}+/** Doc mention chip; same click shielding as the issue and project chips. */+function DocMentionLink({ docId, label }: { docId: string; label?: string }) {+ return (+ <span className="inline align-middle" onClick={(e) => e.stopPropagation()}>+ <DocMentionCard docId={docId} fallbackLabel={label} />+ </span>+ );+}+function childrenToLabel(children: ReactNode): string | undefined {if (typeof children === "string") return children;if (Array.isArray(children)) return children.join("");@@ -230,7 +240,7 @@ function RichLink({ href, children }: { href?: string; children?: ReactNode }) {const isAttachmentLink = href ? !!attachmentLink.resolve(href) : false;if (isMentionHref(href)) {- const match = href.match(/^mention:\/\/(member|agent|issue|project|all)\/(.+)$/);+ const match = href.match(/^mention:\/\/(member|agent|issue|project|doc|all)\/(.+)$/);if (match?.[1] === "issue" && match[2]) {// A bare identifier (from the autolink preprocessor) is carried as the id// segment; a real mention carries a UUID. Dispatch on the id shape.@@ -247,6 +257,9 @@ function RichLink({ href, children }: { href?: string; children?: ReactNode }) {if (match?.[1] === "project" && match[2]) {return <ProjectMentionLink projectId={match[2]} label={childrenToLabel(children)} />;}+ if (match?.[1] === "doc" && match[2]) {+ return <DocMentionLink docId={match[2]} label={childrenToLabel(children)} />;+ }// Member / agent / all mentionsreturn <span className="mention">{children}</span>;}@@ -318,6 +331,9 @@ function RichLink({ href, children }: { href?: string; children?: ReactNode }) {if (entity?.kind === "project") {return <ProjectMentionLink projectId={entity.id} />;}+ if (entity?.kind === "doc") {+ return <DocMentionLink docId={entity.id} />;+ }return plainLink;}diff --git a/packages/views/search/result-rows.tsx b/packages/views/search/result-rows.tsxindex 95f3d2e37e..6741d94dfc 100644--- a/packages/views/search/result-rows.tsx+++ b/packages/views/search/result-rows.tsx@@ -25,6 +25,7 @@ import { ArchivedProjectTag } from "../projects/components/project-archive";import { useProjectStatusLabels } from "../projects/components/labels";import { useT } from "../i18n";import { HighlightText } from "./highlight-text";+import { stripMentionMarkdown } from "../issues/utils/strip-mention-markdown";import { ROW_CLASS, RowHint } from "./rows";function IssueAssigneeAvatar({@@ -89,7 +90,7 @@ export function ProjectResultRow({{project.match_source === "description" && project.matched_snippet && (<div className={SNIPPET_CLASS}><span className="truncate text-caption text-muted-foreground">- <HighlightText text={project.matched_snippet} query={query} />+ <HighlightText text={stripMentionMarkdown(project.matched_snippet)} query={query} /></span></div>)}@@ -146,7 +147,7 @@ export function IssueResultRow({<div className={SNIPPET_CLASS}><FileText className="mt-0.5 size-3 shrink-0 text-muted-foreground" /><span className="truncate text-caption text-muted-foreground">- <HighlightText text={descriptionSnippet} query={query} />+ <HighlightText text={stripMentionMarkdown(descriptionSnippet)} query={query} /></span></div>)}@@ -154,7 +155,7 @@ export function IssueResultRow({<div className={SNIPPET_CLASS}><MessageSquare className="mt-0.5 size-3 shrink-0 text-muted-foreground" /><span className="truncate text-caption text-muted-foreground">- <HighlightText text={commentSnippet} query={query} />+ <HighlightText text={stripMentionMarkdown(commentSnippet)} query={query} /></span></div>)}diff --git a/packages/views/search/root-view.tsx b/packages/views/search/root-view.tsxindex c4a3e80f17..b2644e90c6 100644--- a/packages/views/search/root-view.tsx+++ b/packages/views/search/root-view.tsx@@ -1,7 +1,7 @@"use client";import type { ReactNode } from "react";-import { Clock, Layers, Loader2, MessageSquare, Sparkles, SquarePen, UserPlus, Zap, type IconComponent } from "@multica/ui/icons";+import { Clock, FileText, Layers, Loader2, MessageSquare, Sparkles, SquarePen, UserPlus, Zap, type IconComponent } from "@multica/ui/icons";import { Command as CommandPrimitive } from "cmdk";import { useQuery } from "@tanstack/react-query";import { useWorkspaceId } from "@multica/core/hooks";@@ -41,6 +41,7 @@ const TYPE_ORDER = ["squads","members","projects",+ "docs","issues","autopilots","chats",@@ -341,6 +342,28 @@ export function RootView({ model, rawQuery }: { model: RootModel; rawQuery: stri),});}+ if (objects.docs.length > 0) {+ groups.push({+ key: "docs",+ type: "docs",+ score: objects.docs[0]!.score,+ node: (+ <PaletteGroup key="docs" heading={t(($) => $.groups.docs)}>+ {objects.docs.map(({ item: { doc, folder } }) => (+ <ObjectRow+ key={doc.id}+ value={`doc:${doc.id}`}+ icon={<FileText className={ROW_ICON_CLASS} />}+ title={doc.title}+ query={query}+ detail={folder ?? undefined}+ onSelect={() => palette.navigate(p.docDetail(doc.id))}+ />+ ))}+ </PaletteGroup>+ ),+ });+ }if (objects.workspaces.length > 0) {groups.push({key: "workspaces",diff --git a/packages/views/search/search-command.test.tsx b/packages/views/search/search-command.test.tsxindex fd44236bcc..983cdad73a 100644--- a/packages/views/search/search-command.test.tsx+++ b/packages/views/search/search-command.test.tsx@@ -13,6 +13,7 @@ import { inboxUnreadSummaryOptions } from "@multica/core/inbox/queries";import { useActiveIssueViewStore } from "@multica/core/issue-views/active-view-store";import { issueViewEverywhereOptions } from "@multica/core/issue-views/queries";import { projectListOptions } from "@multica/core/projects/queries";+import { docTreeOptions } from "@multica/core/docs";import { I18nProvider } from "@multica/core/i18n/react";import { issueDetailOptions, issueTimelineOptions } from "@multica/core/issues/queries";import { WORKSPACE_PAGES } from "@multica/core/paths";@@ -692,6 +693,26 @@ describe("SearchCommand", () => {expect(renderedValues()).toContain("best-action:chat");});+ it("finds a doc by title, names its folder, and opens it", async () => {+ seed(docTreeOptions("ws-test"), {+ folders: [{ id: "folder-eng", title: "Engineering" }],+ docs: [+ { id: "doc-runbook", title: "Release runbook", folderId: "folder-eng" },+ { id: "doc-blank", title: "", folderId: null },+ ],+ });+ const user = userEvent.setup();+ renderSearch();+ await user.type(input(), "runbook");++ const docs = await screen.findByRole("group", { name: "Docs" });+ const rows = within(docs).getAllByRole("option");+ expect(rows).toHaveLength(1);+ expect(rows[0]).toHaveTextContent("Release runbookEngineering");+ fireEvent.click(rows[0]!);+ expect(mockPush).toHaveBeenCalledWith("/ws-test/docs/doc-runbook");+ });+it("lists workspace members and navigates to the member page", async () => {const user = userEvent.setup();seed(memberListOptions("ws-test"), [@@ -736,7 +757,7 @@ describe("SearchCommand", () => {{...makeIssue({ id: "issue-snippet", identifier: "MUL-99", title: "HTML rendering pipeline" }),match_source: "title",- matched_description_snippet: "...uses HTML templates for rendering...",+ matched_description_snippet: "...uses HTML templates from [Render guide](mention://doc/doc-1) for rendering...",matched_comment_snippet: "...we should migrate away from HTML...",},],@@ -747,7 +768,7 @@ describe("SearchCommand", () => {await waitFor(() => expect(renderedValues()).toContain("issue-snippet"), { timeout: 2000 });expect(- screen.getByText((_, el) => !!el?.textContent?.includes("uses HTML templates") && el?.tagName === "SPAN"),+ screen.getByText((_, el) => !!el?.textContent?.includes("uses HTML templates from Render guide for") && el?.tagName === "SPAN"),).toBeInTheDocument();expect(screen.getByText((_, el) => !!el?.textContent?.includes("migrate away from HTML") && el?.tagName === "SPAN"),diff --git a/packages/views/search/use-object-search.ts b/packages/views/search/use-object-search.tsindex 9573704cc9..783fde582b 100644--- a/packages/views/search/use-object-search.ts+++ b/packages/views/search/use-object-search.ts@@ -3,6 +3,7 @@import { useMemo } from "react";import { useQuery } from "@tanstack/react-query";import { autopilotListOptions } from "@multica/core/autopilots/queries";+import { docTreeOptions } from "@multica/core/docs";import { chatSessionsOptions } from "@multica/core/chat/queries";import { useWorkspaceId } from "@multica/core/hooks";import { issueViewEverywhereOptions } from "@multica/core/issue-views/queries";@@ -12,6 +13,7 @@ import type { IssueView } from "@multica/core/api/schemas";import type {Autopilot,ChatSession,+ DocSummary,MemberWithUser,SkillSummary,Workspace,@@ -38,12 +40,20 @@ export interface ObjectHits {autopilots: Scored<Autopilot>[];chats: Scored<ChatSession>[];skills: Scored<SkillSummary>[];+ docs: Scored<PaletteDoc>[];workspaces: Scored<Workspace>[];}+/** A doc and the folder it sits in, shown as the row's detail. */+export interface PaletteDoc {+ doc: DocSummary;+ folder: string | null;+}+const EMPTY_AUTOPILOTS: Autopilot[] = [];const EMPTY_CHATS: ChatSession[] = [];const EMPTY_SKILLS: SkillSummary[] = [];+const EMPTY_DOC_TREE = { folders: [], docs: [] };const EMPTY_VIEWS: IssueView[] = [];const EMPTY_WORKSPACES: Workspace[] = [];@@ -92,6 +102,13 @@ export function useObjectSearch(query: string, open: boolean): ObjectHits & { diconst { data: autopilots = EMPTY_AUTOPILOTS } = useQuery({ ...autopilotListOptions(wsId), enabled: typing });const { data: chats = EMPTY_CHATS } = useQuery({ ...chatSessionsOptions(wsId), enabled: typing });const { data: skills = EMPTY_SKILLS } = useQuery({ ...skillListOptions(wsId), enabled: typing });+ const { data: docTree = EMPTY_DOC_TREE } = useQuery({ ...docTreeOptions(wsId), enabled: typing && !!wsId });+ const docs = useMemo<PaletteDoc[]>(() => {+ const folders = new Map(docTree.folders.map((f) => [f.id, f.title]));+ return docTree.docs+ .filter((doc) => doc.title.trim() !== "")+ .map((doc) => ({ doc, folder: doc.folderId ? (folders.get(doc.folderId) ?? null) : null }));+ }, [docTree]);// Account-level cache entry the sidebar's workspace switcher already// holds, so the Workspaces group adds no request of its own.const { data: workspaces = EMPTY_WORKSPACES } = useQuery(workspaceListOptions());@@ -106,7 +123,7 @@ export function useObjectSearch(query: string, open: boolean): ObjectHits & { diconst hits = useMemo<ObjectHits>(() => {if (!query) {- return { agents: [], squads: [], members: [], views: [], autopilots: [], chats: [], skills: [], workspaces: [] };+ return { agents: [], squads: [], members: [], views: [], autopilots: [], chats: [], skills: [], docs: [], workspaces: [] };}return {agents: rank(directory.agents, (e) => scoreText(e.agent.name, query), 8),@@ -124,6 +141,7 @@ export function useObjectSearch(query: string, open: boolean): ObjectHits & { di5,),skills: rank(skills, (s) => scoreText(s.name, query), 5),+ docs: rank(docs, (d) => scoreText(d.doc.title, query), 6),// The current workspace is never a switch target, so a single-workspace// user never sees the group. Ties keep the server's created_at order,// the same order as the sidebar switcher.@@ -133,7 +151,7 @@ export function useObjectSearch(query: string, open: boolean): ObjectHits & { di50,),};- }, [autopilots, chats, directory, query, skills, views, workspaces, wsId]);+ }, [autopilots, chats, directory, docs, query, skills, views, workspaces, wsId]);return { ...hits, directory };}diff --git a/packages/views/search/use-root-model.ts b/packages/views/search/use-root-model.tsindex 5f39ca3f53..0abe608f64 100644--- a/packages/views/search/use-root-model.ts+++ b/packages/views/search/use-root-model.ts@@ -42,6 +42,7 @@ const PAGE_KEYWORDS: Record<WorkspacePageKey, string[]> = {squads: ["squads", "teams", "小队", "团队"],usage: ["usage", "analytics", "stats", "metrics", "统计", "分析", "用量"],runtimes: ["runtimes", "environments", "machines", "运行时"],+ docs: ["docs", "knowledge", "知识库"],skills: ["skills", "library", "技能"],settings: ["settings", "config", "preferences", "设置", "配置"],};@@ -233,6 +234,7 @@ export function useRootModel(autopilots: scope === "all" ? objects.autopilots : [],chats: scope === "all" ? objects.chats : [],skills: scope === "all" ? objects.skills : [],+ docs: scope === "all" ? objects.docs : [],workspaces: scope === "all" ? objects.workspaces : [],};@@ -264,6 +266,7 @@ export function useRootModel(visibleObjects.autopilots.length +visibleObjects.chats.length +visibleObjects.skills.length ++ visibleObjects.docs.length +visibleObjects.workspaces.length;const hasResults =objectCount > 0 ||diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex a0990b51a4..45115a248a 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -146,6 +146,12 @@ var concurrentIndexCleanups = map[string]string{"680_entitlement_limit_overage_scope_idx": "uq_entitlement_limit_overage_scope","682_project_folder_name_idx": "uq_project_folder_workspace_name","684_entitlement_feature_attempt_scope_idx": "uq_entitlement_feature_attempt_scope",+ "686_doc_folder_pkey_index": "doc_folder_pkey_idx",+ "688_doc_pkey_index": "doc_pkey_idx",+ "690_doc_version_pkey_index": "doc_version_pkey_idx",+ "692_doc_folder_workspace_idx": "doc_folder_workspace_idx",+ "693_doc_workspace_idx": "doc_workspace_idx",+ "694_doc_version_workspace_idx": "doc_version_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/multica/cmd_doc.go b/server/cmd/multica/cmd_doc.gonew file mode 100644index 0000000000..82c0b78cf1--- /dev/null+++ b/server/cmd/multica/cmd_doc.go@@ -0,0 +1,316 @@+package main++import (+ "context"+ "errors"+ "fmt"+ "net/http"+ "os"+ "sort"+ "strings"++ "github.com/spf13/cobra"++ "github.com/multica-ai/multica/server/internal/cli"+)++// Doc commands — the workspace knowledge base (MUL-8370).+//+// Writes are optimistic: `doc update` must name the revision it edited+// (`--base-revision`, from `doc get`). When someone else saved in between the+// server answers 409 and nothing is written; re-read, merge, retry.++var docCmd = &cobra.Command{+ Use: "doc",+ Short: "Work with knowledge base docs",+ Long: "Read and write docs in the workspace knowledge base.\n\n" ++ "Every update needs --base-revision: the revision you read with `multica doc get`. " ++ "If the doc changed since then the update is refused; re-read it, merge your change, and retry. " ++ "Pass --message to say what changed and why — it shows in the doc's history.",+}++var docListCmd = &cobra.Command{+ Use: "list",+ Short: "List docs and folders",+ RunE: runDocList,+}++var docGetCmd = &cobra.Command{+ Use: "get <doc-id>",+ Short: "Get a doc with its content and current revision",+ Args: exactArgs(1),+ RunE: runDocGet,+}++var docCreateCmd = &cobra.Command{+ Use: "create",+ Short: "Create a doc",+ RunE: runDocCreate,+}++var docUpdateCmd = &cobra.Command{+ Use: "update <doc-id>",+ Short: "Update a doc's title or content",+ Args: exactArgs(1),+ RunE: runDocUpdate,+}++func init() {+ docCmd.AddCommand(docListCmd, docGetCmd, docCreateCmd, docUpdateCmd)+ docListCmd.Flags().String("output", "table", "Output format: table or json")+ docGetCmd.Flags().String("output", "json", "Output format: json or content")+ for _, cmd := range []*cobra.Command{docCreateCmd, docUpdateCmd} {+ cmd.Flags().String("title", "", "Document title")+ cmd.Flags().String("message", "", "Change summary for history")+ cmd.Flags().String("content", "", "Markdown content")+ cmd.Flags().String("content-file", "", "Read Markdown from a UTF-8 file")+ cmd.Flags().Bool("content-stdin", false, "Read Markdown from stdin")+ cmd.Flags().String("output", "json", "Output format: table or json")+ }+ docCreateCmd.Flags().String("folder", "", "Folder id (default: root)")+ docUpdateCmd.Flags().Int64("base-revision", 0, "Revision from doc get (required)")+}++type docTree struct {+ Folders []map[string]any `json:"folders"`+ Docs []map[string]any `json:"docs"`+}++func fetchDocTree(ctx context.Context, client *cli.APIClient) (docTree, error) {+ var tree docTree+ if err := client.GetJSON(ctx, "/api/docs", &tree); err != nil {+ return tree, fmt.Errorf("list docs: %w", err)+ }+ return tree, nil+}++// resolveDocRef accepts a full id or an unambiguous id prefix from `doc list`.+func resolveDocRef(ctx context.Context, client *cli.APIClient, ref string, folders bool) (string, error) {+ if len(ref) == 36 {+ return ref, nil+ }+ tree, err := fetchDocTree(ctx, client)+ if err != nil {+ return "", err+ }+ items := tree.Docs+ kind := "doc"+ if folders {+ items = tree.Folders+ kind = "folder"+ }+ var matches []string+ for _, item := range items {+ if id := strVal(item, "id"); strings.HasPrefix(id, ref) {+ matches = append(matches, id)+ }+ }+ switch len(matches) {+ case 1:+ return matches[0], nil+ case 0:+ return "", fmt.Errorf("no %s matches %q", kind, ref)+ default:+ return "", fmt.Errorf("%q matches %d %ss; use a longer id", ref, len(matches), kind)+ }+}++func resolveDocFolderTarget(ctx context.Context, client *cli.APIClient, ref string) (any, error) {+ if ref == "root" || ref == "" {+ return nil, nil+ }+ return resolveDocRef(ctx, client, ref, true)+}++// docWriteError turns a stale-revision 409 into instructions an agent can act on.+func docWriteError(action string, base int64, err error) error {+ var httpErr *cli.HTTPError+ if errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusConflict && strings.Contains(httpErr.Body, "revision_conflict") {+ return fmt.Errorf("%s: the doc changed since revision %d, so nothing was written. "++ "Run `multica doc get` for the latest content and revision, merge your change into it, and retry with the new --base-revision (%s)",+ action, base, httpErr.Body)+ }+ return fmt.Errorf("%s: %w", action, err)+}++func docFolderPaths(folders []map[string]any) map[string]string {+ byID := make(map[string]map[string]any, len(folders))+ for _, f := range folders {+ byID[strVal(f, "id")] = f+ }+ paths := make(map[string]string, len(folders))+ var pathOf func(id string, depth int) string+ pathOf = func(id string, depth int) string {+ if p, ok := paths[id]; ok {+ return p+ }+ f, ok := byID[id]+ if !ok || depth > len(folders) {+ return ""+ }+ p := strVal(f, "title")+ if parent := strVal(f, "parent_id"); parent != "" {+ if pp := pathOf(parent, depth+1); pp != "" {+ p = pp + "/" + p+ }+ }+ paths[id] = p+ return p+ }+ for id := range byID {+ pathOf(id, 0)+ }+ return paths+}++func printDocSummary(doc map[string]any, output string) error {+ if output == "table" {+ cli.PrintTable(os.Stdout, []string{"ID", "TITLE", "REVISION", "VERSIONS"}, [][]string{{+ strVal(doc, "id"), strVal(doc, "title"),+ strVal(doc, "revision"), strVal(doc, "version_count"),+ }})+ return nil+ }+ return cli.PrintJSON(os.Stdout, doc)+}++func runDocList(cmd *cobra.Command, _ []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ tree, err := fetchDocTree(ctx, client)+ if err != nil {+ return err+ }+ output, _ := cmd.Flags().GetString("output")+ if output == "json" {+ return cli.PrintJSON(os.Stdout, tree)+ }++ paths := docFolderPaths(tree.Folders)+ rows := make([][]string, 0, len(tree.Folders)+len(tree.Docs))+ for _, f := range tree.Folders {+ rows = append(rows, []string{strVal(f, "id"), "folder", paths[strVal(f, "id")] + "/", "", ""})+ }+ for _, d := range tree.Docs {+ path := strVal(d, "title")+ if folder := paths[strVal(d, "folder_id")]; folder != "" {+ path = folder + "/" + path+ }+ updated := strVal(d, "updated_at")+ if len(updated) >= 10 {+ updated = updated[:10]+ }+ rows = append(rows, []string{strVal(d, "id"), "doc", path, strVal(d, "revision"), updated})+ }+ sort.SliceStable(rows, func(i, j int) bool { return rows[i][2] < rows[j][2] })+ cli.PrintTable(os.Stdout, []string{"ID", "TYPE", "PATH", "REVISION", "UPDATED"}, rows)+ return nil+}++func runDocGet(cmd *cobra.Command, args []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ id, err := resolveDocRef(ctx, client, args[0], false)+ if err != nil {+ return err+ }+ var doc map[string]any+ if err := client.GetJSON(ctx, "/api/docs/"+id, &doc); err != nil {+ return fmt.Errorf("get doc: %w", err)+ }+ if output, _ := cmd.Flags().GetString("output"); output == "content" {+ _, err := fmt.Fprint(os.Stdout, strVal(doc, "content"))+ return err+ }+ return cli.PrintJSON(os.Stdout, doc)+}++func runDocCreate(cmd *cobra.Command, _ []string) error {+ title, _ := cmd.Flags().GetString("title")+ if strings.TrimSpace(title) == "" {+ return fmt.Errorf("--title is required")+ }+ content, _, err := resolveSkillContentFlag(cmd)+ if err != nil {+ return err+ }++ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ body := map[string]any{"title": title, "content": content}+ if v, _ := cmd.Flags().GetString("message"); v != "" {+ body["message"] = v+ }+ if v, _ := cmd.Flags().GetString("folder"); v != "" {+ folder, err := resolveDocFolderTarget(ctx, client, v)+ if err != nil {+ return err+ }+ body["folder_id"] = folder+ }+ var doc map[string]any+ if err := client.PostJSON(ctx, "/api/docs", body, &doc); err != nil {+ return fmt.Errorf("create doc: %w", err)+ }+ output, _ := cmd.Flags().GetString("output")+ return printDocSummary(doc, output)+}++func runDocUpdate(cmd *cobra.Command, args []string) error {+ base, _ := cmd.Flags().GetInt64("base-revision")+ if base <= 0 {+ return fmt.Errorf("--base-revision is required: pass the revision from `multica doc get`")+ }+ content, hasContent, err := resolveSkillContentFlag(cmd)+ if err != nil {+ return err+ }+ body := map[string]any{"base_revision": base}+ if hasContent {+ body["content"] = content+ }+ if cmd.Flags().Changed("title") {+ title, _ := cmd.Flags().GetString("title")+ body["title"] = title+ }+ if !hasContent && !cmd.Flags().Changed("title") {+ return fmt.Errorf("nothing to update: pass --title and/or --content, --content-file, --content-stdin")+ }+ if v, _ := cmd.Flags().GetString("message"); v != "" {+ body["message"] = v+ }++ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ id, err := resolveDocRef(ctx, client, args[0], false)+ if err != nil {+ return err+ }+ var doc map[string]any+ if err := client.PatchJSON(ctx, "/api/docs/"+id, body, &doc); err != nil {+ return docWriteError("update doc", base, err)+ }+ delete(doc, "content")+ output, _ := cmd.Flags().GetString("output")+ return printDocSummary(doc, output)+}diff --git a/server/cmd/multica/cmd_doc_test.go b/server/cmd/multica/cmd_doc_test.gonew file mode 100644index 0000000000..63dd3bd78f--- /dev/null+++ b/server/cmd/multica/cmd_doc_test.go@@ -0,0 +1,34 @@+package main++import (+ "errors"+ "net/http"+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/internal/cli"+)++func TestDocCommandsExposeOnlyAgentReadWrite(t *testing.T) {+ expected := map[string]bool{"list": true, "get": true, "create": true, "update": true}+ for _, command := range docCmd.Commands() {+ if !expected[command.Name()] {+ t.Fatalf("unexpected doc command: %s", command.Name())+ }+ delete(expected, command.Name())+ }+ if len(expected) != 0 {+ t.Fatalf("missing commands: %v", expected)+ }+}++func TestDocConflictErrorExplainsRecovery(t *testing.T) {+ err := docWriteError("update doc", 3, &cli.HTTPError{StatusCode: http.StatusConflict, Body: `{"code":"revision_conflict","actual_revision":4}`})+ if !strings.Contains(err.Error(), "nothing was written") || !strings.Contains(err.Error(), "--base-revision") {+ t.Fatalf("missing recovery: %v", err)+ }+ cause := errors.New("connection closed")+ if !errors.Is(docWriteError("update doc", 3, cause), cause) {+ t.Fatal("lost underlying error")+ }+}diff --git a/server/cmd/multica/main.go b/server/cmd/multica/main.goindex 6befee21aa..af9a121347 100644--- a/server/cmd/multica/main.go+++ b/server/cmd/multica/main.go@@ -80,6 +80,7 @@ func init() {rootCmd.AddCommand(issueCmd)rootCmd.AddCommand(inboxCmd)+ rootCmd.AddCommand(docCmd)rootCmd.AddCommand(issueStatusCatalogCmd)rootCmd.AddCommand(projectCmd)rootCmd.AddCommand(workflowCmd)diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex a22f814d1d..29acd59b03 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2328,6 +2328,27 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busextension.MountWorkspaceRoutes(r, h)// Projects+ r.Route("/api/docs", func(r chi.Router) {+ r.Get("/", h.ListDocTree)+ r.Post("/", h.CreateDoc)+ r.Route("/{id}", func(r chi.Router) {+ r.Get("/", h.GetDoc)+ r.Patch("/", h.UpdateDoc)+ r.With(handler.RequireHumanActor).Delete("/", h.DeleteDoc)+ r.Post("/move", h.MoveDoc)+ r.Get("/versions", h.ListDocVersions)+ r.Get("/versions/{number}", h.GetDocVersion)+ })+ })+ r.Route("/api/doc-folders", func(r chi.Router) {+ r.Post("/", h.CreateDocFolder)+ r.Route("/{id}", func(r chi.Router) {+ r.Patch("/", h.UpdateDocFolder)+ r.With(handler.RequireHumanActor).Delete("/", h.DeleteDocFolder)+ r.Post("/move", h.MoveDocFolder)+ })+ })+r.Route("/api/projects", func(r chi.Router) {r.Get("/search", h.SearchProjects)// Workspace owner only: every private project, joined or not.diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.goindex 2a82aa1652..34f5fdc556 100644--- a/server/internal/daemon/execenv/runtime_config_sections.go+++ b/server/internal/daemon/execenv/runtime_config_sections.go@@ -267,6 +267,7 @@ func writeAvailableCommands(b *strings.Builder, ctx TaskContextForEnv) {b.WriteString("## Available Commands\n\n")b.WriteString("Prefer `--output json` for structured data. The default brief lists only the core agent loop and common issue create/update tasks; for everything else run `multica --help` or `multica <command> --help`.\n\n")b.WriteString("`--output json` writes JSON to stdout; confirmations and warnings go to stderr. Do not merge them (`2>&1`) into anything that parses the output — that makes a write that SUCCEEDED look like it failed and invites a duplicate retry.\n\n")+ b.WriteString("Workspace docs are available via `multica doc list|get|create|update`; updates require --base-revision from doc get.\n\n")b.WriteString("### Core\n")b.WriteString("- `multica issue get <id> --output json` — full issue.\n")b.WriteString("- `multica issue comment list <issue-id> [--roots-only] [--summary] [--thread <comment-id> [--tail N] | --recent N] [--since <RFC3339>] [--compact] --output json` — thread-aware comment reads. Read in two bounded steps: scan with `--roots-only --summary`, then expand one thread with `--thread <id> --tail N`. Careful with `--recent N`: it caps THREADS, not comments, and can return the whole history on a small issue. Resolved-thread folding, paging cursors, and full flag semantics: `--help`.\n")@@ -845,6 +846,7 @@ func writeMentions(b *strings.Builder) {// agent writes this form (or pastes the project URL, which the reader's// client unfurls into the same chip) a project reference stays dead text.b.WriteString("- `[Project Name](mention://project/<project-id>)` — clickable link (no side effect)\n")+ b.WriteString("- `[Doc Title](mention://doc/<doc-id>)` — clickable link (no side effect); read it with `multica doc get <doc-id>`\n")b.WriteString("- `[@Name](mention://member/<user-id>)` — **notifies a human**\n")b.WriteString("- `[@Name](mention://agent/<agent-id>)` — **enqueues a new run for that agent**\n\n")// No prescriptive default here (MUL-6417): the mention syntax hides itsdiff --git a/server/internal/handler/doc.go b/server/internal/handler/doc.gonew file mode 100644index 0000000000..18cf5f3896--- /dev/null+++ b/server/internal/handler/doc.go@@ -0,0 +1,927 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "strconv"+ "strings"+ "unicode/utf8"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5/pgtype"++ "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/protocol"+)++const (+ docTitleMaxLen = 300+ docMessageMaxLen = 500+ docContentMaxSize = 2 << 20+ docBodyMaxBytes = 6 << 20+ docVersionsMax = 500+)++var (+ validDocActions = []string{"edit", "restore"}+)++type DocSummaryResponse struct {+ ID string `json:"id"`+ WorkspaceID string `json:"workspace_id"`+ FolderID *string `json:"folder_id"`+ Title string `json:"title"`+ Revision int64 `json:"revision"`+ VersionCount int32 `json:"version_count"`+ CreatedByType string `json:"created_by_type"`+ CreatedByID string `json:"created_by_id"`+ UpdatedByType string `json:"updated_by_type"`+ UpdatedByID string `json:"updated_by_id"`+ CreatedAt string `json:"created_at"`+ UpdatedAt string `json:"updated_at"`+}++type DocResponse struct {+ DocSummaryResponse+ Content string `json:"content"`+}++type DocFolderResponse struct {+ ID string `json:"id"`+ WorkspaceID string `json:"workspace_id"`+ ParentID *string `json:"parent_id"`+ Title string `json:"title"`+ CreatedByType string `json:"created_by_type"`+ CreatedByID string `json:"created_by_id"`+ CreatedAt string `json:"created_at"`+ UpdatedAt string `json:"updated_at"`+}++type DocVersionResponse struct {+ DocID string `json:"doc_id"`+ Number int32 `json:"number"`+ Title string `json:"title"`+ AuthorType string `json:"author_type"`+ AuthorID string `json:"author_id"`+ Message string `json:"message"`+ Action string `json:"action"`+ ActionRef *int32 `json:"action_ref"`+ TaskID *string `json:"task_id"`+ IssueID *string `json:"issue_id"`+ CreatedAt string `json:"created_at"`+ UpdatedAt string `json:"updated_at"`+ Content *string `json:"content,omitempty"`+}++func docToSummary(d db.Doc) DocSummaryResponse {+ return DocSummaryResponse{+ ID: uuidToString(d.ID),+ WorkspaceID: uuidToString(d.WorkspaceID),+ FolderID: uuidToPtr(d.FolderID),+ Title: d.Title,+ Revision: d.Revision,+ VersionCount: d.VersionCount,+ CreatedByType: d.CreatedByType,+ CreatedByID: uuidToString(d.CreatedByID),+ UpdatedByType: d.UpdatedByType,+ UpdatedByID: uuidToString(d.UpdatedByID),+ CreatedAt: timestampToString(d.CreatedAt),+ UpdatedAt: timestampToString(d.UpdatedAt),+ }+}++func docListRowToSummary(d db.ListDocsRow) DocSummaryResponse {+ return DocSummaryResponse{+ ID: uuidToString(d.ID),+ WorkspaceID: uuidToString(d.WorkspaceID),+ FolderID: uuidToPtr(d.FolderID),+ Title: d.Title,+ Revision: d.Revision,+ VersionCount: d.VersionCount,+ CreatedByType: d.CreatedByType,+ CreatedByID: uuidToString(d.CreatedByID),+ UpdatedByType: d.UpdatedByType,+ UpdatedByID: uuidToString(d.UpdatedByID),+ CreatedAt: timestampToString(d.CreatedAt),+ UpdatedAt: timestampToString(d.UpdatedAt),+ }+}++func docFolderToResponse(f db.DocFolder) DocFolderResponse {+ return DocFolderResponse{+ ID: uuidToString(f.ID),+ WorkspaceID: uuidToString(f.WorkspaceID),+ ParentID: uuidToPtr(f.ParentID),+ Title: f.Title,+ CreatedByType: f.CreatedByType,+ CreatedByID: uuidToString(f.CreatedByID),+ CreatedAt: timestampToString(f.CreatedAt),+ UpdatedAt: timestampToString(f.UpdatedAt),+ }+}++func docVersionToResponse(v db.DocVersion, withContent bool) DocVersionResponse {+ resp := DocVersionResponse{+ DocID: uuidToString(v.DocID),+ Number: v.Number,+ Title: v.Title,+ AuthorType: v.AuthorType,+ AuthorID: uuidToString(v.AuthorID),+ Message: v.Message,+ Action: v.Action,+ ActionRef: int4ToPtr(v.ActionRef),+ TaskID: uuidToPtr(v.TaskID),+ IssueID: uuidToPtr(v.IssueID),+ CreatedAt: timestampToString(v.CreatedAt),+ UpdatedAt: timestampToString(v.UpdatedAt),+ }+ if withContent {+ content := v.Content+ resp.Content = &content+ }+ return resp+}++func docVersionRowToResponse(v db.ListDocVersionsRow) DocVersionResponse {+ return DocVersionResponse{+ DocID: uuidToString(v.DocID),+ Number: v.Number,+ Title: v.Title,+ AuthorType: v.AuthorType,+ AuthorID: uuidToString(v.AuthorID),+ Message: v.Message,+ Action: v.Action,+ ActionRef: int4ToPtr(v.ActionRef),+ TaskID: uuidToPtr(v.TaskID),+ IssueID: uuidToPtr(v.IssueID),+ CreatedAt: timestampToString(v.CreatedAt),+ UpdatedAt: timestampToString(v.UpdatedAt),+ }+}++// docTaskContext attributes an agent write to the task (and its issue) that+// made it, so history can link back to the run.+func (h *Handler) docTaskContext(r *http.Request, actorType string) (pgtype.UUID, pgtype.UUID) {+ if actorType != "agent" {+ return pgtype.UUID{}, pgtype.UUID{}+ }+ taskUUID, err := util.ParseUUID(r.Header.Get("X-Task-ID"))+ if err != nil {+ return pgtype.UUID{}, pgtype.UUID{}+ }+ task, err := h.Queries.GetAgentTask(r.Context(), taskUUID)+ if err != nil {+ return taskUUID, pgtype.UUID{}+ }+ return taskUUID, task.IssueID+}++func validateDocTitle(w http.ResponseWriter, title string) bool {+ if utf8.RuneCountInString(title) > docTitleMaxLen {+ writeError(w, http.StatusBadRequest, "title must be at most 300 characters")+ return false+ }+ return true+}++func validateDocContent(w http.ResponseWriter, content string) bool {+ if len(content) > docContentMaxSize {+ writeError(w, http.StatusRequestEntityTooLarge, "content must be at most 2 MB")+ return false+ }+ if !utf8.ValidString(content) {+ writeError(w, http.StatusBadRequest, "content must be valid UTF-8")+ return false+ }+ return true+}++func validateDocMessage(w http.ResponseWriter, message string) bool {+ if utf8.RuneCountInString(message) > docMessageMaxLen {+ writeError(w, http.StatusBadRequest, "message must be at most 500 characters")+ return false+ }+ return true+}++func (h *Handler) docWorkspace(w http.ResponseWriter, r *http.Request) (string, pgtype.UUID, string, bool) {+ userID, ok := requireUserID(w, r)+ if !ok {+ return "", pgtype.UUID{}, "", false+ }+ workspaceID := h.resolveWorkspaceID(r)+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")+ if !ok {+ return "", pgtype.UUID{}, "", false+ }+ return userID, wsUUID, workspaceID, true+}++func (h *Handler) loadDoc(w http.ResponseWriter, r *http.Request, wsUUID pgtype.UUID) (db.Doc, bool) {+ docUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "doc id")+ if !ok {+ return db.Doc{}, false+ }+ doc, err := h.Queries.GetDoc(r.Context(), db.GetDocParams{ID: docUUID, WorkspaceID: wsUUID})+ if err != nil {+ if isNotFound(err) {+ writeError(w, http.StatusNotFound, "doc not found")+ } else {+ writeError(w, http.StatusInternalServerError, "failed to load doc")+ }+ return db.Doc{}, false+ }+ return doc, true+}++// requireDocFolder checks that a target folder exists in the workspace. A nil+// or empty id means the workspace root.+func requireDocFolder(ctx context.Context, w http.ResponseWriter, q *db.Queries, wsUUID pgtype.UUID, id *string, field string) (pgtype.UUID, bool) {+ if id == nil || *id == "" {+ return pgtype.UUID{}, true+ }+ folderUUID, ok := parseUUIDOrBadRequest(w, *id, field)+ if !ok {+ return pgtype.UUID{}, false+ }+ if _, err := q.GetDocFolder(ctx, db.GetDocFolderParams{ID: folderUUID, WorkspaceID: wsUUID}); err != nil {+ if isNotFound(err) {+ writeError(w, http.StatusBadRequest, "folder not found")+ } else {+ writeError(w, http.StatusInternalServerError, "failed to load folder")+ }+ return pgtype.UUID{}, false+ }+ return folderUUID, true+}++// ListDocTree returns every folder and doc (metadata only) in the workspace.+// Knowledge bases are small enough that the client builds the tree itself.+func (h *Handler) ListDocTree(w http.ResponseWriter, r *http.Request) {+ _, wsUUID, _, ok := h.docWorkspace(w, r)+ if !ok {+ return+ }+ folders, err := h.Queries.ListDocFolders(r.Context(), wsUUID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list folders")+ return+ }+ docs, err := h.Queries.ListDocs(r.Context(), wsUUID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list docs")+ return+ }+ folderResp := make([]DocFolderResponse, len(folders))+ for i, f := range folders {+ folderResp[i] = docFolderToResponse(f)+ }+ docResp := make([]DocSummaryResponse, len(docs))+ for i, d := range docs {+ docResp[i] = docListRowToSummary(d)+ }+ writeJSON(w, http.StatusOK, map[string]any{"folders": folderResp, "docs": docResp})+}++func (h *Handler) GetDoc(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+ }+ writeJSON(w, http.StatusOK, DocResponse{DocSummaryResponse: docToSummary(doc), Content: doc.Content})+}++type CreateDocRequest struct {+ Title string `json:"title"`+ Content string `json:"content"`+ FolderID *string `json:"folder_id"`+ Message string `json:"message"`+}++func (h *Handler) CreateDoc(w http.ResponseWriter, r *http.Request) {+ userID, wsUUID, workspaceID, ok := h.docWorkspace(w, r)+ if !ok {+ return+ }+ var req CreateDocRequest+ r.Body = http.MaxBytesReader(w, r.Body, docBodyMaxBytes)+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ req.Title = strings.TrimSpace(req.Title)+ if !validateDocTitle(w, req.Title) || !validateDocContent(w, req.Content) || !validateDocMessage(w, req.Message) {+ return+ }++ actorType, actorID := h.resolveActor(r, userID, workspaceID)+ taskID, issueID := h.docTaskContext(r, actorType)++ ctx := r.Context()+ tx, err := h.TxStarter.Begin(ctx)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to create doc")+ return+ }+ defer tx.Rollback(ctx)+ qtx := h.Queries.WithTx(tx)+ if err := qtx.LockDocTree(ctx, wsUUID); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to create doc")+ return+ }+ folderUUID, ok := requireDocFolder(ctx, w, qtx, wsUUID, req.FolderID, "folder_id")+ if !ok {+ return+ }+ doc, err := qtx.CreateDoc(ctx, db.CreateDocParams{+ WorkspaceID: wsUUID,+ FolderID: folderUUID,+ Title: req.Title,+ Content: req.Content,+ AuthorType: actorType,+ AuthorID: parseUUID(actorID),+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to create doc")+ return+ }+ if _, err := qtx.InsertDocVersion(ctx, db.InsertDocVersionParams{+ DocID: doc.ID,+ WorkspaceID: wsUUID,+ Number: 1,+ Title: doc.Title,+ Content: doc.Content,+ AuthorType: actorType,+ AuthorID: parseUUID(actorID),+ Message: req.Message,+ Action: "create",+ TaskID: taskID,+ IssueID: issueID,+ }); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to create doc")+ return+ }+ if err := tx.Commit(ctx); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to create doc")+ return+ }++ h.publish(protocol.EventDocCreated, workspaceID, actorType, actorID, map[string]any{"doc": docToSummary(doc)})+ writeJSON(w, http.StatusCreated, DocResponse{DocSummaryResponse: docToSummary(doc), Content: doc.Content})+}++type UpdateDocRequest struct {+ Title *string `json:"title"`+ Content *string `json:"content"`+ BaseRevision int64 `json:"base_revision"`+ Message string `json:"message"`+ Action string `json:"action"`+ ActionRef *int32 `json:"action_ref"`+}++// UpdateDoc appends a snapshot after checking the writer's base revision.+func (h *Handler) UpdateDoc(w http.ResponseWriter, r *http.Request) {+ userID, wsUUID, workspaceID, ok := h.docWorkspace(w, r)+ if !ok {+ return+ }+ docUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "doc id")+ if !ok {+ return+ }+ var req UpdateDocRequest+ r.Body = http.MaxBytesReader(w, r.Body, docBodyMaxBytes)+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if req.BaseRevision <= 0 {+ writeError(w, http.StatusBadRequest, "base_revision is required")+ return+ }+ if req.Action == "" {+ req.Action = "edit"+ }+ if !contains(validDocActions, req.Action) {+ writeError(w, http.StatusBadRequest, "action must be edit or restore")+ return+ }+ if req.Action != "edit" && (req.ActionRef == nil || *req.ActionRef <= 0) {+ writeError(w, http.StatusBadRequest, "action_ref is required for restore")+ return+ }+ if req.Title != nil {+ trimmed := strings.TrimSpace(*req.Title)+ req.Title = &trimmed+ if !validateDocTitle(w, trimmed) {+ return+ }+ }+ if req.Content != nil && !validateDocContent(w, *req.Content) {+ return+ }+ if !validateDocMessage(w, req.Message) {+ return+ }++ actorType, actorID := h.resolveActor(r, userID, workspaceID)+ taskID, issueID := h.docTaskContext(r, actorType)++ ctx := r.Context()+ tx, err := h.TxStarter.Begin(ctx)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to update doc")+ return+ }+ defer tx.Rollback(ctx)+ qtx := h.Queries.WithTx(tx)++ doc, err := qtx.GetDocForUpdate(ctx, db.GetDocForUpdateParams{ID: docUUID, WorkspaceID: wsUUID})+ if err != nil {+ if isNotFound(err) {+ writeError(w, http.StatusNotFound, "doc not found")+ } else {+ writeError(w, http.StatusInternalServerError, "failed to update doc")+ }+ return+ }+ if doc.Revision != req.BaseRevision {+ writeRevisionConflict(w, "doc", doc.ID, req.BaseRevision, doc.Revision)+ return+ }++ title, content := doc.Title, doc.Content+ if req.Action == "restore" {+ source, err := qtx.GetDocVersion(ctx, db.GetDocVersionParams{DocID: doc.ID, Number: *req.ActionRef})+ if err != nil {+ if isNotFound(err) {+ writeError(w, http.StatusBadRequest, "version not found")+ } else {+ writeError(w, http.StatusInternalServerError, "failed to update doc")+ }+ return+ }+ title, content = source.Title, source.Content+ } else {+ if req.Title != nil {+ title = *req.Title+ }+ if req.Content != nil {+ content = *req.Content+ }+ }+ if req.Action == "edit" && title == doc.Title && content == doc.Content {+ writeJSON(w, http.StatusOK, DocResponse{DocSummaryResponse: docToSummary(doc), Content: doc.Content})+ return+ }+ // Autosave writes every pause; keep one snapshot per editing stretch+ // instead of one per pause.+ merged := false+ if req.Action == "edit" && req.Message == "" {+ rows, err := qtx.MergeDocEditIntoVersion(ctx, db.MergeDocEditIntoVersionParams{+ Title: title, Content: content, DocID: doc.ID, Number: doc.VersionCount,+ AuthorType: actorType, AuthorID: parseUUID(actorID), TaskID: taskID,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to save version")+ return+ }+ merged = rows == 1+ }+ number := doc.VersionCount+ if !merged {+ number+++ var actionRef pgtype.Int4+ if req.Action == "restore" {+ actionRef = pgtype.Int4{Int32: *req.ActionRef, Valid: true}+ }+ if _, err := qtx.InsertDocVersion(ctx, db.InsertDocVersionParams{+ DocID: doc.ID, WorkspaceID: wsUUID, Number: number, Title: title, Content: content,+ AuthorType: actorType, AuthorID: parseUUID(actorID), Message: req.Message,+ Action: req.Action, ActionRef: actionRef, TaskID: taskID, IssueID: issueID,+ }); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to save version")+ return+ }+ }+ updated, err := qtx.UpdateDocContent(ctx, db.UpdateDocContentParams{+ Title: title,+ Content: content,+ VersionCount: number,+ UpdatedByType: actorType,+ UpdatedByID: parseUUID(actorID),+ ID: doc.ID,+ WorkspaceID: wsUUID,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to update doc")+ return+ }+ if err := tx.Commit(ctx); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to update doc")+ return+ }++ h.publish(protocol.EventDocUpdated, workspaceID, actorType, actorID, map[string]any{+ "doc": docToSummary(updated),+ "version": number,+ })+ writeJSON(w, http.StatusOK, DocResponse{DocSummaryResponse: docToSummary(updated), Content: updated.Content})+}++type MoveDocRequest struct {+ FolderID *string `json:"folder_id"`+}++func (h *Handler) MoveDoc(w http.ResponseWriter, r *http.Request) {+ userID, wsUUID, workspaceID, ok := h.docWorkspace(w, r)+ if !ok {+ return+ }+ docUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "doc id")+ if !ok {+ return+ }+ var req MoveDocRequest+ r.Body = http.MaxBytesReader(w, r.Body, 4096)+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ actorType, actorID := h.resolveActor(r, userID, workspaceID)++ ctx := r.Context()+ tx, err := h.TxStarter.Begin(ctx)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to move doc")+ return+ }+ defer tx.Rollback(ctx)+ qtx := h.Queries.WithTx(tx)+ if err := qtx.LockDocTree(ctx, wsUUID); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to move doc")+ return+ }+ folderUUID, ok := requireDocFolder(ctx, w, qtx, wsUUID, req.FolderID, "folder_id")+ if !ok {+ return+ }+ doc, err := qtx.MoveDoc(ctx, db.MoveDocParams{FolderID: folderUUID, ID: docUUID, WorkspaceID: wsUUID})+ if err != nil {+ if isNotFound(err) {+ writeError(w, http.StatusNotFound, "doc not found")+ } else {+ writeError(w, http.StatusInternalServerError, "failed to move doc")+ }+ return+ }+ if err := tx.Commit(ctx); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to move doc")+ return+ }+ h.publish(protocol.EventDocUpdated, workspaceID, actorType, actorID, map[string]any{"doc": docToSummary(doc)})+ writeJSON(w, http.StatusOK, docToSummary(doc))+}++func (h *Handler) DeleteDoc(w http.ResponseWriter, r *http.Request) {+ userID, wsUUID, workspaceID, ok := h.docWorkspace(w, r)+ if !ok {+ return+ }+ actorType, actorID := h.resolveActor(r, userID, workspaceID)+ if isMachineCredentialActor(r) || actorType != "member" || r.Header.Get("X-Agent-ID") != "" {+ writeError(w, http.StatusForbidden, "only humans can delete docs")+ return+ }+ id, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "doc id")+ if !ok {+ return+ }+ ctx := r.Context()+ tx, err := h.TxStarter.Begin(ctx)+ if err != nil {+ writeError(w, 500, "failed to delete doc")+ return+ }+ defer tx.Rollback(ctx)+ q := h.Queries.WithTx(tx)+ if _, err = q.GetDocForUpdate(ctx, db.GetDocForUpdateParams{ID: id, WorkspaceID: wsUUID}); err != nil {+ if isNotFound(err) {+ writeError(w, 404, "doc not found")+ } else {+ writeError(w, 500, "failed to delete doc")+ }+ return+ }+ if err = q.DeleteDoc(ctx, db.DeleteDocParams{ID: id, WorkspaceID: wsUUID}); err != nil {+ writeError(w, 500, "failed to delete doc")+ return+ }+ if err = tx.Commit(ctx); err != nil {+ writeError(w, 500, "failed to delete doc")+ return+ }+ h.publish(protocol.EventDocDeleted, workspaceID, actorType, actorID, map[string]any{"doc_id": uuidToString(id)})+ w.WriteHeader(http.StatusNoContent)+}++func (h *Handler) ListDocVersions(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.ListDocVersions(r.Context(), db.ListDocVersionsParams{DocID: doc.ID, Limit: docVersionsMax})+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list versions")+ return+ }+ versions := make([]DocVersionResponse, len(rows))+ for i, v := range rows {+ versions[i] = docVersionRowToResponse(v)+ }+ writeJSON(w, http.StatusOK, map[string]any{"versions": versions})+}++func (h *Handler) GetDocVersion(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+ }+ number, err := strconv.ParseInt(chi.URLParam(r, "number"), 10, 32)+ if err != nil || number <= 0 {+ writeError(w, http.StatusBadRequest, "invalid version number")+ return+ }+ v, err := h.Queries.GetDocVersion(r.Context(), db.GetDocVersionParams{DocID: doc.ID, Number: int32(number)})+ if err != nil {+ if isNotFound(err) {+ writeError(w, http.StatusNotFound, "version not found")+ } else {+ writeError(w, http.StatusInternalServerError, "failed to load version")+ }+ return+ }+ writeJSON(w, http.StatusOK, docVersionToResponse(v, true))+}++// --- Folders ---++type CreateDocFolderRequest struct {+ Title string `json:"title"`+ ParentID *string `json:"parent_id"`+}++func validateDocFolderTitle(w http.ResponseWriter, title string) bool {+ if l := utf8.RuneCountInString(title); l < 1 || l > 200 {+ writeError(w, http.StatusBadRequest, "folder name must be between 1 and 200 characters")+ return false+ }+ return true+}++func (h *Handler) CreateDocFolder(w http.ResponseWriter, r *http.Request) {+ userID, wsUUID, workspaceID, ok := h.docWorkspace(w, r)+ if !ok {+ return+ }+ var req CreateDocFolderRequest+ r.Body = http.MaxBytesReader(w, r.Body, 8192)+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ req.Title = strings.TrimSpace(req.Title)+ if !validateDocFolderTitle(w, req.Title) {+ return+ }+ actorType, actorID := h.resolveActor(r, userID, workspaceID)++ ctx := r.Context()+ tx, err := h.TxStarter.Begin(ctx)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to create folder")+ return+ }+ defer tx.Rollback(ctx)+ qtx := h.Queries.WithTx(tx)+ if err := qtx.LockDocTree(ctx, wsUUID); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to create folder")+ return+ }+ parentUUID, ok := requireDocFolder(ctx, w, qtx, wsUUID, req.ParentID, "parent_id")+ if !ok {+ return+ }+ folder, err := qtx.CreateDocFolder(ctx, db.CreateDocFolderParams{+ WorkspaceID: wsUUID,+ ParentID: parentUUID,+ Title: req.Title,+ CreatedByType: actorType,+ CreatedByID: parseUUID(actorID),+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to create folder")+ return+ }+ if err := tx.Commit(ctx); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to create folder")+ return+ }+ resp := docFolderToResponse(folder)+ h.publish(protocol.EventDocFolderCreated, workspaceID, actorType, actorID, map[string]any{"folder": resp})+ writeJSON(w, http.StatusCreated, resp)+}++type UpdateDocFolderRequest struct {+ Title string `json:"title"`+}++func (h *Handler) UpdateDocFolder(w http.ResponseWriter, r *http.Request) {+ userID, wsUUID, workspaceID, ok := h.docWorkspace(w, r)+ if !ok {+ return+ }+ folderUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "folder id")+ if !ok {+ return+ }+ var req UpdateDocFolderRequest+ r.Body = http.MaxBytesReader(w, r.Body, 8192)+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ req.Title = strings.TrimSpace(req.Title)+ if !validateDocFolderTitle(w, req.Title) {+ return+ }+ folder, err := h.Queries.RenameDocFolder(r.Context(), db.RenameDocFolderParams{Title: req.Title, ID: folderUUID, WorkspaceID: wsUUID})+ if err != nil {+ if isNotFound(err) {+ writeError(w, http.StatusNotFound, "folder not found")+ } else {+ writeError(w, http.StatusInternalServerError, "failed to rename folder")+ }+ return+ }+ actorType, actorID := h.resolveActor(r, userID, workspaceID)+ resp := docFolderToResponse(folder)+ h.publish(protocol.EventDocFolderUpdated, workspaceID, actorType, actorID, map[string]any{"folder": resp})+ writeJSON(w, http.StatusOK, resp)+}++type MoveDocFolderRequest struct {+ ParentID *string `json:"parent_id"`+}++// docFolderCreatesCycle reports whether putting folder under newParent would+// make it its own ancestor.+func docFolderCreatesCycle(folders []db.DocFolder, folder, newParent pgtype.UUID) bool {+ if !newParent.Valid {+ return false+ }+ parentOf := make(map[pgtype.UUID]pgtype.UUID, len(folders))+ for _, f := range folders {+ parentOf[f.ID] = f.ParentID+ }+ cur := newParent+ for steps := 0; cur.Valid && steps <= len(folders); steps++ {+ if cur == folder {+ return true+ }+ cur = parentOf[cur]+ }+ return false+}++func (h *Handler) MoveDocFolder(w http.ResponseWriter, r *http.Request) {+ userID, wsUUID, workspaceID, ok := h.docWorkspace(w, r)+ if !ok {+ return+ }+ folderUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "folder id")+ if !ok {+ return+ }+ var req MoveDocFolderRequest+ r.Body = http.MaxBytesReader(w, r.Body, 4096)+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ actorType, actorID := h.resolveActor(r, userID, workspaceID)++ ctx := r.Context()+ tx, err := h.TxStarter.Begin(ctx)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to move folder")+ return+ }+ defer tx.Rollback(ctx)+ qtx := h.Queries.WithTx(tx)+ if err := qtx.LockDocTree(ctx, wsUUID); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to move folder")+ return+ }+ parentUUID, ok := requireDocFolder(ctx, w, qtx, wsUUID, req.ParentID, "parent_id")+ if !ok {+ return+ }+ folders, err := qtx.ListDocFolders(ctx, wsUUID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to move folder")+ return+ }+ if docFolderCreatesCycle(folders, folderUUID, parentUUID) {+ writeErrorCode(w, http.StatusBadRequest, "folder_cycle", "a folder cannot be moved into itself or one of its subfolders")+ return+ }+ folder, err := qtx.MoveDocFolder(ctx, db.MoveDocFolderParams{ParentID: parentUUID, ID: folderUUID, WorkspaceID: wsUUID})+ if err != nil {+ if isNotFound(err) {+ writeError(w, http.StatusNotFound, "folder not found")+ } else {+ writeError(w, http.StatusInternalServerError, "failed to move folder")+ }+ return+ }+ if err := tx.Commit(ctx); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to move folder")+ return+ }+ resp := docFolderToResponse(folder)+ h.publish(protocol.EventDocFolderUpdated, workspaceID, actorType, actorID, map[string]any{"folder": resp})+ writeJSON(w, http.StatusOK, resp)+}++// DeleteDocFolder removes an empty folder. Non-empty folders are refused so a+// misclick can never take docs and their history with it.+func (h *Handler) DeleteDocFolder(w http.ResponseWriter, r *http.Request) {+ userID, wsUUID, workspaceID, ok := h.docWorkspace(w, r)+ if !ok {+ return+ }+ actorType, _ := h.resolveActor(r, userID, workspaceID)+ if isMachineCredentialActor(r) || actorType != "member" || r.Header.Get("X-Agent-ID") != "" {+ writeError(w, http.StatusForbidden, "only humans can delete folders")+ return+ }+ folderUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "folder id")+ if !ok {+ return+ }+ ctx := r.Context()+ tx, err := h.TxStarter.Begin(ctx)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to delete folder")+ return+ }+ defer tx.Rollback(ctx)+ qtx := h.Queries.WithTx(tx)+ if err := qtx.LockDocTree(ctx, wsUUID); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to delete folder")+ return+ }+ if _, err := qtx.GetDocFolder(ctx, db.GetDocFolderParams{ID: folderUUID, WorkspaceID: wsUUID}); err != nil {+ if isNotFound(err) {+ writeError(w, http.StatusNotFound, "folder not found")+ } else {+ writeError(w, http.StatusInternalServerError, "failed to delete folder")+ }+ return+ }+ children, err := qtx.CountDocFolderChildren(ctx, db.CountDocFolderChildrenParams{WorkspaceID: wsUUID, FolderID: folderUUID})+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to delete folder")+ return+ }+ if children > 0 {+ writeErrorCode(w, http.StatusConflict, "folder_not_empty", "move or delete the folder's contents first")+ return+ }+ if err := qtx.DeleteDocFolder(ctx, db.DeleteDocFolderParams{ID: folderUUID, WorkspaceID: wsUUID}); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to delete folder")+ return+ }+ if err := tx.Commit(ctx); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to delete folder")+ return+ }+ _, actorID := h.resolveActor(r, userID, workspaceID)+ h.publish(protocol.EventDocFolderDeleted, workspaceID, actorType, actorID, map[string]any{"folder_id": uuidToString(folderUUID)})+ w.WriteHeader(http.StatusNoContent)+}diff --git a/server/internal/handler/doc_test.go b/server/internal/handler/doc_test.gonew file mode 100644index 0000000000..ebaab768d0--- /dev/null+++ b/server/internal/handler/doc_test.go@@ -0,0 +1,148 @@+package handler++import (+ "context"+ "net/http"+ "testing"++ "github.com/multica-ai/multica/server/internal/testutil"+)++func createDocForTest(t *testing.T) DocResponse {+ t.Helper()+ var doc DocResponse+ testutil.Call(t, testHandler.CreateDoc, newRequest("POST", "/api/docs", map[string]any{"title": "Runbook", "content": "# First\n\nOriginal"})).Want(http.StatusCreated).JSON(&doc)+ t.Cleanup(func() {+ testPool.Exec(context.Background(), "DELETE FROM doc_version WHERE doc_id = $1", doc.ID)+ testPool.Exec(context.Background(), "DELETE FROM doc WHERE id = $1", doc.ID)+ })+ return doc+}++func TestDocSnapshotsConflictRestoreAndIsolation(t *testing.T) {+ doc := createDocForTest(t)+ var updated DocResponse+ patch := func(body map[string]any) *http.Request {+ return withURLParam(newRequest("PATCH", "/api/docs/"+doc.ID, body), "id", doc.ID)+ }+ testutil.Call(t, testHandler.UpdateDoc, patch(map[string]any{"base_revision": 1, "title": "Changed", "content": "Second"})).Want(http.StatusOK).JSON(&updated)+ if updated.Revision != 2 || updated.VersionCount != 2 {+ t.Fatalf("each save must append: %+v", updated)+ }+ var conflict map[string]any+ testutil.Call(t, testHandler.UpdateDoc, patch(map[string]any{"base_revision": 1, "content": "Stale"})).Want(http.StatusConflict).JSON(&conflict)+ if conflict["code"] != "revision_conflict" {+ t.Fatalf("unexpected conflict: %v", conflict)+ }+ testutil.Call(t, testHandler.UpdateDoc, patch(map[string]any{"base_revision": 2, "action": "restore", "action_ref": 1, "content": "ignored", "title": "ignored"})).Want(http.StatusOK).JSON(&updated)+ if updated.Revision != 3 || updated.VersionCount != 3 || updated.Title != doc.Title || updated.Content != doc.Content {+ t.Fatalf("restore must copy title/body into a new snapshot: %+v", updated)+ }+ var history struct {+ Versions []DocVersionResponse `json:"versions"`+ }+ testutil.Call(t, testHandler.ListDocVersions, withURLParam(newRequest("GET", "/api/docs/versions", nil), "id", doc.ID)).Want(http.StatusOK).JSON(&history)+ if len(history.Versions) != 3 {+ t.Fatalf("history overwritten: %v", history.Versions)+ }+ req := withURLParam(newRequest("GET", "/api/docs/versions/1", nil), "id", doc.ID)+ req = withURLParams(req, "id", doc.ID, "number", "1")+ var version DocVersionResponse+ testutil.Call(t, testHandler.GetDocVersion, req).Want(http.StatusOK).JSON(&version)+ if version.Content == nil || *version.Content != doc.Content || version.Title != doc.Title {+ t.Fatalf("original snapshot changed: %+v", version)+ }+ for _, handler := range []http.HandlerFunc{testHandler.GetDoc, testHandler.ListDocVersions, testHandler.UpdateDoc, testHandler.DeleteDoc} {+ req := patch(map[string]any{"base_revision": 3, "content": "Cross tenant"})+ req.Header.Set("X-Workspace-ID", "00000000-0000-4000-8000-000000000099")+ testutil.Call(t, handler, req).Want(http.StatusNotFound)+ }+ testutil.Call(t, testHandler.UpdateDoc, patch(map[string]any{"content": "No revision"})).Want(http.StatusBadRequest)+ testutil.Call(t, testHandler.UpdateDoc, patch(map[string]any{"base_revision": 3, "action": "revert", "action_ref": 1})).Want(http.StatusBadRequest)+}++func TestDocDeleteHumanOnlyAndHistoryCleanup(t *testing.T) {+ doc := createDocForTest(t)+ for _, source := range []string{"task_token", "cloud_pat"} {+ req := withURLParam(newRequest("DELETE", "/api/docs", nil), "id", doc.ID)+ req.Header.Set("X-Actor-Source", source)+ testutil.Call(t, testHandler.DeleteDoc, req).Want(http.StatusForbidden)+ }+ req := withURLParam(newRequest("DELETE", "/api/docs", nil), "id", doc.ID)+ req.Header.Set("X-Agent-ID", "00000000-0000-4000-8000-000000000001")+ testutil.Call(t, testHandler.DeleteDoc, req).Want(http.StatusForbidden)+ testutil.Call(t, testHandler.DeleteDoc, withURLParam(newRequest("DELETE", "/api/docs", nil), "id", doc.ID)).Want(http.StatusNoContent)+ var count int+ dbfx.QueryRow(t, "SELECT count(*) FROM doc_version WHERE doc_id = $1", doc.ID).Scan(&count)+ if count != 0 {+ t.Fatalf("delete left %d snapshots", count)+ }+}++func TestDocFolderCycleAndNonemptyDelete(t *testing.T) {+ create := func(parent *string) DocFolderResponse {+ var f DocFolderResponse+ testutil.Call(t, testHandler.CreateDocFolder, newRequest("POST", "/api/doc-folders", map[string]any{"title": "Guides", "parent_id": parent})).Want(http.StatusCreated).JSON(&f)+ t.Cleanup(func() { testPool.Exec(context.Background(), "DELETE FROM doc_folder WHERE id = $1", f.ID) })+ return f+ }+ root := create(nil)+ child := create(&root.ID)+ testutil.Call(t, testHandler.MoveDocFolder, withURLParam(newRequest("POST", "/move", map[string]any{"parent_id": child.ID}), "id", root.ID)).Want(http.StatusBadRequest)+ testutil.Call(t, testHandler.DeleteDocFolder, withURLParam(newRequest("DELETE", "/folder", nil), "id", root.ID)).Want(http.StatusConflict)+ req := withURLParam(newRequest("DELETE", "/folder", nil), "id", child.ID)+ req.Header.Set("X-Actor-Source", "task_token")+ testutil.Call(t, testHandler.DeleteDocFolder, req).Want(http.StatusForbidden)+ testutil.Call(t, testHandler.MoveDocFolder, withURLParam(newRequest("POST", "/move", map[string]any{"parent_id": nil}), "id", child.ID)).Want(http.StatusOK)+ testutil.Call(t, testHandler.DeleteDocFolder, withURLParam(newRequest("DELETE", "/folder", nil), "id", root.ID)).Want(http.StatusNoContent)+}++func TestDocEditsMergeIntoOneVersionPerEditingStretch(t *testing.T) {+ doc := createDocForTest(t)+ var updated DocResponse+ revision := int64(1)+ save := func(body map[string]any) DocResponse {+ t.Helper()+ body["base_revision"] = revision+ req := withURLParam(newRequest("PATCH", "/api/docs/"+doc.ID, body), "id", doc.ID)+ testutil.Call(t, testHandler.UpdateDoc, req).Want(http.StatusOK).JSON(&updated)+ revision = updated.Revision+ return updated+ }+ // The create snapshot stands alone; the first edit opens a new one.+ if got := save(map[string]any{"content": "a"}); got.VersionCount != 2 {+ t.Fatalf("first edit must open a version: %+v", got)+ }+ // Further autosaves in the same stretch fold into it.+ save(map[string]any{"content": "ab"})+ if got := save(map[string]any{"title": "Renamed", "content": "abc"}); got.VersionCount != 2 || got.Revision != 4 {+ t.Fatalf("autosaves must merge but still bump the revision: %+v", got)+ }+ var version DocVersionResponse+ req := withURLParams(newRequest("GET", "/api/docs/versions/2", nil), "id", doc.ID, "number", "2")+ testutil.Call(t, testHandler.GetDocVersion, req).Want(http.StatusOK).JSON(&version)+ if version.Content == nil || *version.Content != "abc" || version.Title != "Renamed" {+ t.Fatalf("merged snapshot must hold the latest save: %+v", version)+ }+ // A labeled save is its own version.+ if got := save(map[string]any{"content": "abcd", "message": "Checkpoint"}); got.VersionCount != 3 {+ t.Fatalf("labeled save must append: %+v", got)+ }+ // So is the next stretch, once the open snapshot is older than the window.+ if got := save(map[string]any{"content": "abcde"}); got.VersionCount != 4 {+ t.Fatalf("edit after a labeled save must append: %+v", got)+ }+ testPool.Exec(context.Background(), "UPDATE doc_version SET created_at = now() - interval '20 minutes' WHERE doc_id = $1 AND number = 4", doc.ID)+ if got := save(map[string]any{"content": "abcde!"}); got.VersionCount != 4 {+ t.Fatalf("edit inside the 30-minute window must merge: %+v", got)+ }+ testPool.Exec(context.Background(), "UPDATE doc_version SET created_at = now() - interval '31 minutes' WHERE doc_id = $1 AND number = 4", doc.ID)+ if got := save(map[string]any{"content": "abcdef"}); got.VersionCount != 5 {+ t.Fatalf("edit after the window must append: %+v", got)+ }+ // A restore never absorbs later edits.+ save(map[string]any{"action": "restore", "action_ref": 1})+ if got := save(map[string]any{"content": "after restore"}); got.VersionCount != 7 {+ t.Fatalf("edit after a restore must append: %+v", got)+ }+}diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.goindex 40cf8fdd8b..71c7d4c25f 100644--- a/server/internal/handler/workspace.go+++ b/server/internal/handler/workspace.go@@ -1396,6 +1396,10 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {return qtx.DeleteIssueWorkflowsForWorkspace(ctx, requester.WorkspaceID)},},+ {+ name: "delete docs",+ run: func() error { return qtx.DeleteWorkspaceDocs(ctx, requester.WorkspaceID) },+ },{name: "delete autopilot children",run: func() error { return qtx.DeleteWorkspaceAutopilotChildren(ctx, requester.WorkspaceID) },diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex 81c737b50d..4c70162137 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -65,6 +65,9 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"dingtalk_group_presence": workspaceDelete,"dingtalk_bot_identity": workspaceDelete,"dingtalk_group_route": workspaceDelete,+ "doc": workspaceDelete,+ "doc_folder": workspaceDelete,+ "doc_version": workspaceDelete,"entitlement_feature_attempt": workspaceDelete,"entitlement_limit_overage": workspaceDelete,"feedback": workspaceDeleteDetach,diff --git a/server/migrations/685_docs.down.sql b/server/migrations/685_docs.down.sqlnew file mode 100644index 0000000000..e55993da9f--- /dev/null+++ b/server/migrations/685_docs.down.sql@@ -0,0 +1,3 @@+DROP TABLE IF EXISTS doc_version;+DROP TABLE IF EXISTS doc;+DROP TABLE IF EXISTS doc_folder;diff --git a/server/migrations/685_docs.up.sql b/server/migrations/685_docs.up.sqlnew file mode 100644index 0000000000..032dc60586--- /dev/null+++ b/server/migrations/685_docs.up.sql@@ -0,0 +1,44 @@+-- Workspace Markdown documents and immutable snapshots. Keys attach after concurrent builds.+CREATE TABLE IF NOT EXISTS doc_folder (+ id UUID NOT NULL DEFAULT gen_random_uuid(),+ workspace_id UUID NOT NULL,+ parent_id UUID,+ title TEXT NOT NULL CHECK (char_length(title) BETWEEN 1 AND 200),+ created_by_type TEXT NOT NULL CHECK (created_by_type IN ('member', 'agent')),+ created_by_id UUID NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE TABLE IF NOT EXISTS doc (+ id UUID NOT NULL DEFAULT gen_random_uuid(),+ workspace_id UUID NOT NULL,+ folder_id UUID,+ title TEXT NOT NULL DEFAULT '' CHECK (char_length(title) <= 300),+ content TEXT NOT NULL DEFAULT '',+ revision BIGINT NOT NULL DEFAULT 1,+ version_count INTEGER NOT NULL DEFAULT 1,+ created_by_type TEXT NOT NULL CHECK (created_by_type IN ('member', 'agent')),+ created_by_id UUID NOT NULL,+ updated_by_type TEXT NOT NULL CHECK (updated_by_type IN ('member', 'agent')),+ updated_by_id UUID NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE TABLE IF NOT EXISTS doc_version (+ doc_id UUID NOT NULL,+ workspace_id UUID NOT NULL,+ number INTEGER NOT NULL,+ title TEXT NOT NULL DEFAULT '',+ content TEXT NOT NULL DEFAULT '',+ author_type TEXT NOT NULL CHECK (author_type IN ('member', 'agent')),+ author_id UUID NOT NULL,+ message TEXT NOT NULL DEFAULT '' CHECK (char_length(message) <= 500),+ action TEXT NOT NULL DEFAULT 'edit' CHECK (action IN ('create', 'edit', 'restore')),+ action_ref INTEGER,+ task_id UUID,+ issue_id UUID,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);diff --git a/server/migrations/686_doc_folder_pkey_index.down.sql b/server/migrations/686_doc_folder_pkey_index.down.sqlnew file mode 100644index 0000000000..cb6f220355--- /dev/null+++ b/server/migrations/686_doc_folder_pkey_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS doc_folder_pkey_idx;diff --git a/server/migrations/686_doc_folder_pkey_index.up.sql b/server/migrations/686_doc_folder_pkey_index.up.sqlnew file mode 100644index 0000000000..fff605d289--- /dev/null+++ b/server/migrations/686_doc_folder_pkey_index.up.sql@@ -0,0 +1 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS doc_folder_pkey_idx ON doc_folder (id);diff --git a/server/migrations/687_doc_folder_pkey.down.sql b/server/migrations/687_doc_folder_pkey.down.sqlnew file mode 100644index 0000000000..3161b82830--- /dev/null+++ b/server/migrations/687_doc_folder_pkey.down.sql@@ -0,0 +1 @@+ALTER TABLE doc_folder DROP CONSTRAINT IF EXISTS doc_folder_pkey;diff --git a/server/migrations/687_doc_folder_pkey.up.sql b/server/migrations/687_doc_folder_pkey.up.sqlnew file mode 100644index 0000000000..e912d084ad--- /dev/null+++ b/server/migrations/687_doc_folder_pkey.up.sql@@ -0,0 +1 @@+ALTER TABLE doc_folder ADD CONSTRAINT doc_folder_pkey PRIMARY KEY USING INDEX doc_folder_pkey_idx;diff --git a/server/migrations/688_doc_pkey_index.down.sql b/server/migrations/688_doc_pkey_index.down.sqlnew file mode 100644index 0000000000..4aa43f341f--- /dev/null+++ b/server/migrations/688_doc_pkey_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS doc_pkey_idx;diff --git a/server/migrations/688_doc_pkey_index.up.sql b/server/migrations/688_doc_pkey_index.up.sqlnew file mode 100644index 0000000000..69c86914d7--- /dev/null+++ b/server/migrations/688_doc_pkey_index.up.sql@@ -0,0 +1 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS doc_pkey_idx ON doc (id);diff --git a/server/migrations/689_doc_pkey.down.sql b/server/migrations/689_doc_pkey.down.sqlnew file mode 100644index 0000000000..800531e31a--- /dev/null+++ b/server/migrations/689_doc_pkey.down.sql@@ -0,0 +1 @@+ALTER TABLE doc DROP CONSTRAINT IF EXISTS doc_pkey;diff --git a/server/migrations/689_doc_pkey.up.sql b/server/migrations/689_doc_pkey.up.sqlnew file mode 100644index 0000000000..3ab60d56fa--- /dev/null+++ b/server/migrations/689_doc_pkey.up.sql@@ -0,0 +1 @@+ALTER TABLE doc ADD CONSTRAINT doc_pkey PRIMARY KEY USING INDEX doc_pkey_idx;diff --git a/server/migrations/690_doc_version_pkey_index.down.sql b/server/migrations/690_doc_version_pkey_index.down.sqlnew file mode 100644index 0000000000..89c5dd0cce--- /dev/null+++ b/server/migrations/690_doc_version_pkey_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS doc_version_pkey_idx;diff --git a/server/migrations/690_doc_version_pkey_index.up.sql b/server/migrations/690_doc_version_pkey_index.up.sqlnew file mode 100644index 0000000000..edddb055c0--- /dev/null+++ b/server/migrations/690_doc_version_pkey_index.up.sql@@ -0,0 +1 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS doc_version_pkey_idx ON doc_version (doc_id, number);diff --git a/server/migrations/691_doc_version_pkey.down.sql b/server/migrations/691_doc_version_pkey.down.sqlnew file mode 100644index 0000000000..7b016d7c46--- /dev/null+++ b/server/migrations/691_doc_version_pkey.down.sql@@ -0,0 +1 @@+ALTER TABLE doc_version DROP CONSTRAINT IF EXISTS doc_version_pkey;diff --git a/server/migrations/691_doc_version_pkey.up.sql b/server/migrations/691_doc_version_pkey.up.sqlnew file mode 100644index 0000000000..268152da1d--- /dev/null+++ b/server/migrations/691_doc_version_pkey.up.sql@@ -0,0 +1 @@+ALTER TABLE doc_version ADD CONSTRAINT doc_version_pkey PRIMARY KEY USING INDEX doc_version_pkey_idx;diff --git a/server/migrations/692_doc_folder_workspace_idx.down.sql b/server/migrations/692_doc_folder_workspace_idx.down.sqlnew file mode 100644index 0000000000..4460aaadf2--- /dev/null+++ b/server/migrations/692_doc_folder_workspace_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS doc_folder_workspace_idx;diff --git a/server/migrations/692_doc_folder_workspace_idx.up.sql b/server/migrations/692_doc_folder_workspace_idx.up.sqlnew file mode 100644index 0000000000..fdd3f3f589--- /dev/null+++ b/server/migrations/692_doc_folder_workspace_idx.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY IF NOT EXISTS doc_folder_workspace_idx ON doc_folder (workspace_id);diff --git a/server/migrations/693_doc_workspace_idx.down.sql b/server/migrations/693_doc_workspace_idx.down.sqlnew file mode 100644index 0000000000..ebfdc32f7d--- /dev/null+++ b/server/migrations/693_doc_workspace_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS doc_workspace_idx;diff --git a/server/migrations/693_doc_workspace_idx.up.sql b/server/migrations/693_doc_workspace_idx.up.sqlnew file mode 100644index 0000000000..614cc795c1--- /dev/null+++ b/server/migrations/693_doc_workspace_idx.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY IF NOT EXISTS doc_workspace_idx ON doc (workspace_id);diff --git a/server/migrations/694_doc_version_workspace_idx.down.sql b/server/migrations/694_doc_version_workspace_idx.down.sqlnew file mode 100644index 0000000000..c8542a5754--- /dev/null+++ b/server/migrations/694_doc_version_workspace_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS doc_version_workspace_idx;diff --git a/server/migrations/694_doc_version_workspace_idx.up.sql b/server/migrations/694_doc_version_workspace_idx.up.sqlnew file mode 100644index 0000000000..d6fe94b02b--- /dev/null+++ b/server/migrations/694_doc_version_workspace_idx.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY IF NOT EXISTS doc_version_workspace_idx ON doc_version (workspace_id);diff --git a/server/pkg/db/generated/doc.sql.go b/server/pkg/db/generated/doc.sql.gonew file mode 100644index 0000000000..b080113c63--- /dev/null+++ b/server/pkg/db/generated/doc.sql.go@@ -0,0 +1,691 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: doc.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const countDocFolderChildren = `-- name: CountDocFolderChildren :one+SELECT (+ (SELECT count(*) FROM doc_folder f WHERE f.workspace_id = $1 AND f.parent_id = $2::uuid)+ + (SELECT count(*) FROM doc d WHERE d.workspace_id = $1 AND d.folder_id = $2::uuid)+)::int AS total+`++type CountDocFolderChildrenParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ FolderID pgtype.UUID `json:"folder_id"`+}++func (q *Queries) CountDocFolderChildren(ctx context.Context, arg CountDocFolderChildrenParams) (int32, error) {+ row := q.db.QueryRow(ctx, countDocFolderChildren, arg.WorkspaceID, arg.FolderID)+ var total int32+ err := row.Scan(&total)+ return total, err+}++const createDoc = `-- name: CreateDoc :one+INSERT INTO doc (+ workspace_id, folder_id, title, content,+ created_by_type, created_by_id, updated_by_type, updated_by_id+) VALUES (+ $1, $2, $3, $4,+ $5, $6, $5, $6+)+RETURNING id, workspace_id, folder_id, title, content, revision, version_count, created_by_type, created_by_id, updated_by_type, updated_by_id, created_at, updated_at+`++type CreateDocParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ FolderID pgtype.UUID `json:"folder_id"`+ Title string `json:"title"`+ Content string `json:"content"`+ AuthorType string `json:"author_type"`+ AuthorID pgtype.UUID `json:"author_id"`+}++func (q *Queries) CreateDoc(ctx context.Context, arg CreateDocParams) (Doc, error) {+ row := q.db.QueryRow(ctx, createDoc,+ arg.WorkspaceID,+ arg.FolderID,+ arg.Title,+ arg.Content,+ arg.AuthorType,+ arg.AuthorID,+ )+ var i Doc+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.FolderID,+ &i.Title,+ &i.Content,+ &i.Revision,+ &i.VersionCount,+ &i.CreatedByType,+ &i.CreatedByID,+ &i.UpdatedByType,+ &i.UpdatedByID,+ &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)+RETURNING id, workspace_id, parent_id, title, created_by_type, created_by_id, created_at, updated_at+`++type CreateDocFolderParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ParentID pgtype.UUID `json:"parent_id"`+ Title string `json:"title"`+ CreatedByType string `json:"created_by_type"`+ CreatedByID pgtype.UUID `json:"created_by_id"`+}++func (q *Queries) CreateDocFolder(ctx context.Context, arg CreateDocFolderParams) (DocFolder, error) {+ row := q.db.QueryRow(ctx, createDocFolder,+ arg.WorkspaceID,+ arg.ParentID,+ arg.Title,+ arg.CreatedByType,+ arg.CreatedByID,+ )+ var i DocFolder+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.ParentID,+ &i.Title,+ &i.CreatedByType,+ &i.CreatedByID,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const deleteDoc = `-- name: DeleteDoc :exec+WITH v AS (DELETE FROM doc_version WHERE doc_version.doc_id = $1 AND doc_version.workspace_id = $2)+DELETE FROM doc WHERE doc.id = $1 AND doc.workspace_id = $2+`++type DeleteDocParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) DeleteDoc(ctx context.Context, arg DeleteDocParams) error {+ _, err := q.db.Exec(ctx, deleteDoc, arg.ID, arg.WorkspaceID)+ return err+}++const deleteDocFolder = `-- name: DeleteDocFolder :exec+DELETE FROM doc_folder WHERE id = $1 AND workspace_id = $2+`++type DeleteDocFolderParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) DeleteDocFolder(ctx context.Context, arg DeleteDocFolderParams) error {+ _, err := q.db.Exec(ctx, deleteDocFolder, arg.ID, arg.WorkspaceID)+ return err+}++const deleteWorkspaceDocs = `-- name: DeleteWorkspaceDocs :exec+WITH v AS (DELETE FROM doc_version WHERE doc_version.workspace_id = $1),+f AS (DELETE FROM doc_folder WHERE doc_folder.workspace_id = $1)+DELETE FROM doc WHERE doc.workspace_id = $1+`++func (q *Queries) DeleteWorkspaceDocs(ctx context.Context, workspaceID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deleteWorkspaceDocs, workspaceID)+ return err+}++const getDoc = `-- name: GetDoc :one+SELECT id, workspace_id, folder_id, title, content, revision, version_count, created_by_type, created_by_id, updated_by_type, updated_by_id, created_at, updated_at FROM doc+WHERE id = $1 AND workspace_id = $2+`++type GetDocParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) GetDoc(ctx context.Context, arg GetDocParams) (Doc, error) {+ row := q.db.QueryRow(ctx, getDoc, arg.ID, arg.WorkspaceID)+ var i Doc+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.FolderID,+ &i.Title,+ &i.Content,+ &i.Revision,+ &i.VersionCount,+ &i.CreatedByType,+ &i.CreatedByID,+ &i.UpdatedByType,+ &i.UpdatedByID,+ &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+`++type GetDocFolderParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) GetDocFolder(ctx context.Context, arg GetDocFolderParams) (DocFolder, error) {+ row := q.db.QueryRow(ctx, getDocFolder, arg.ID, arg.WorkspaceID)+ var i DocFolder+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.ParentID,+ &i.Title,+ &i.CreatedByType,+ &i.CreatedByID,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const getDocForUpdate = `-- name: GetDocForUpdate :one+SELECT id, workspace_id, folder_id, title, content, revision, version_count, created_by_type, created_by_id, updated_by_type, updated_by_id, created_at, updated_at FROM doc+WHERE id = $1 AND workspace_id = $2+FOR UPDATE+`++type GetDocForUpdateParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) GetDocForUpdate(ctx context.Context, arg GetDocForUpdateParams) (Doc, error) {+ row := q.db.QueryRow(ctx, getDocForUpdate, arg.ID, arg.WorkspaceID)+ var i Doc+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.FolderID,+ &i.Title,+ &i.Content,+ &i.Revision,+ &i.VersionCount,+ &i.CreatedByType,+ &i.CreatedByID,+ &i.UpdatedByType,+ &i.UpdatedByID,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const getDocVersion = `-- name: GetDocVersion :one+SELECT doc_id, workspace_id, number, title, content, author_type, author_id, message, action, action_ref, task_id, issue_id, created_at, updated_at FROM doc_version+WHERE doc_id = $1 AND number = $2+`++type GetDocVersionParams struct {+ DocID pgtype.UUID `json:"doc_id"`+ Number int32 `json:"number"`+}++func (q *Queries) GetDocVersion(ctx context.Context, arg GetDocVersionParams) (DocVersion, error) {+ row := q.db.QueryRow(ctx, getDocVersion, arg.DocID, arg.Number)+ var i DocVersion+ err := row.Scan(+ &i.DocID,+ &i.WorkspaceID,+ &i.Number,+ &i.Title,+ &i.Content,+ &i.AuthorType,+ &i.AuthorID,+ &i.Message,+ &i.Action,+ &i.ActionRef,+ &i.TaskID,+ &i.IssueID,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const insertDocVersion = `-- name: InsertDocVersion :one+INSERT INTO doc_version (+ doc_id, workspace_id, number, title, content, author_type, author_id,+ message, action, action_ref, task_id, issue_id+) VALUES (+ $1, $2, $3, $4, $5, $6, $7,+ $8, $9, $10, $11, $12+)+RETURNING doc_id, workspace_id, number, title, content, author_type, author_id, message, action, action_ref, task_id, issue_id, created_at, updated_at+`++type InsertDocVersionParams struct {+ DocID pgtype.UUID `json:"doc_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Number int32 `json:"number"`+ Title string `json:"title"`+ Content string `json:"content"`+ AuthorType string `json:"author_type"`+ AuthorID pgtype.UUID `json:"author_id"`+ Message string `json:"message"`+ Action string `json:"action"`+ ActionRef pgtype.Int4 `json:"action_ref"`+ TaskID pgtype.UUID `json:"task_id"`+ IssueID pgtype.UUID `json:"issue_id"`+}++func (q *Queries) InsertDocVersion(ctx context.Context, arg InsertDocVersionParams) (DocVersion, error) {+ row := q.db.QueryRow(ctx, insertDocVersion,+ arg.DocID,+ arg.WorkspaceID,+ arg.Number,+ arg.Title,+ arg.Content,+ arg.AuthorType,+ arg.AuthorID,+ arg.Message,+ arg.Action,+ arg.ActionRef,+ arg.TaskID,+ arg.IssueID,+ )+ var i DocVersion+ err := row.Scan(+ &i.DocID,+ &i.WorkspaceID,+ &i.Number,+ &i.Title,+ &i.Content,+ &i.AuthorType,+ &i.AuthorID,+ &i.Message,+ &i.Action,+ &i.ActionRef,+ &i.TaskID,+ &i.IssueID,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++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+ORDER BY lower(title), created_at+`++func (q *Queries) ListDocFolders(ctx context.Context, workspaceID pgtype.UUID) ([]DocFolder, error) {+ rows, err := q.db.Query(ctx, listDocFolders, workspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []DocFolder{}+ for rows.Next() {+ var i DocFolder+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.ParentID,+ &i.Title,+ &i.CreatedByType,+ &i.CreatedByID,+ &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 listDocVersions = `-- name: ListDocVersions :many+SELECT+ doc_id, workspace_id, number, title, author_type, author_id, message, action,+ action_ref, task_id, issue_id, created_at, updated_at+FROM doc_version+WHERE doc_id = $1+ORDER BY number DESC+LIMIT $2+`++type ListDocVersionsParams struct {+ DocID pgtype.UUID `json:"doc_id"`+ Limit int32 `json:"limit"`+}++type ListDocVersionsRow struct {+ DocID pgtype.UUID `json:"doc_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Number int32 `json:"number"`+ Title string `json:"title"`+ AuthorType string `json:"author_type"`+ AuthorID pgtype.UUID `json:"author_id"`+ Message string `json:"message"`+ Action string `json:"action"`+ ActionRef pgtype.Int4 `json:"action_ref"`+ TaskID pgtype.UUID `json:"task_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}++func (q *Queries) ListDocVersions(ctx context.Context, arg ListDocVersionsParams) ([]ListDocVersionsRow, error) {+ rows, err := q.db.Query(ctx, listDocVersions, arg.DocID, arg.Limit)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListDocVersionsRow{}+ for rows.Next() {+ var i ListDocVersionsRow+ if err := rows.Scan(+ &i.DocID,+ &i.WorkspaceID,+ &i.Number,+ &i.Title,+ &i.AuthorType,+ &i.AuthorID,+ &i.Message,+ &i.Action,+ &i.ActionRef,+ &i.TaskID,+ &i.IssueID,+ &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 listDocs = `-- name: ListDocs :many+SELECT id, workspace_id, folder_id, title, revision, version_count,+created_by_type, created_by_id, updated_by_type, updated_by_id, created_at, updated_at+FROM doc WHERE workspace_id = $1 ORDER BY lower(title), created_at+`++type ListDocsRow struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ FolderID pgtype.UUID `json:"folder_id"`+ Title string `json:"title"`+ Revision int64 `json:"revision"`+ VersionCount int32 `json:"version_count"`+ CreatedByType string `json:"created_by_type"`+ CreatedByID pgtype.UUID `json:"created_by_id"`+ UpdatedByType string `json:"updated_by_type"`+ UpdatedByID pgtype.UUID `json:"updated_by_id"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}++func (q *Queries) ListDocs(ctx context.Context, workspaceID pgtype.UUID) ([]ListDocsRow, error) {+ rows, err := q.db.Query(ctx, listDocs, workspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListDocsRow{}+ for rows.Next() {+ var i ListDocsRow+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.FolderID,+ &i.Title,+ &i.Revision,+ &i.VersionCount,+ &i.CreatedByType,+ &i.CreatedByID,+ &i.UpdatedByType,+ &i.UpdatedByID,+ &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 lockDocTree = `-- name: LockDocTree :exec++SELECT pg_advisory_xact_lock(hashtextextended($1::uuid::text || ':doc_tree', 0))+`++// Workspace documents and folders.+// Serializes folder/doc moves within one workspace so the cycle check and the+// move it guards see the same tree.+func (q *Queries) LockDocTree(ctx context.Context, workspaceID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, lockDocTree, workspaceID)+ return err+}++const mergeDocEditIntoVersion = `-- name: MergeDocEditIntoVersion :execrows+UPDATE doc_version SET+ title = $1,+ content = $2,+ updated_at = now()+WHERE doc_id = $3+ AND number = $4+ AND action = 'edit'+ AND message = ''+ AND author_type = $5+ AND author_id = $6+ AND task_id IS NOT DISTINCT FROM $7+ AND created_at > now() - interval '30 minutes'+`++type MergeDocEditIntoVersionParams struct {+ Title string `json:"title"`+ Content string `json:"content"`+ DocID pgtype.UUID `json:"doc_id"`+ Number int32 `json:"number"`+ AuthorType string `json:"author_type"`+ AuthorID pgtype.UUID `json:"author_id"`+ TaskID pgtype.UUID `json:"task_id"`+}++// Folds an edit into the latest snapshot while the same author keeps editing:+// an unlabeled edit from the same author and task within 30 minutes of the+// snapshot's start. Creates, restores and labeled edits always stand alone.+func (q *Queries) MergeDocEditIntoVersion(ctx context.Context, arg MergeDocEditIntoVersionParams) (int64, error) {+ result, err := q.db.Exec(ctx, mergeDocEditIntoVersion,+ arg.Title,+ arg.Content,+ arg.DocID,+ arg.Number,+ arg.AuthorType,+ arg.AuthorID,+ arg.TaskID,+ )+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const moveDoc = `-- name: MoveDoc :one+UPDATE doc SET folder_id = $1+WHERE id = $2 AND workspace_id = $3+RETURNING id, workspace_id, folder_id, title, content, revision, version_count, created_by_type, created_by_id, updated_by_type, updated_by_id, created_at, updated_at+`++type MoveDocParams struct {+ FolderID pgtype.UUID `json:"folder_id"`+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// A move is not an edit: revision and updated_at stay put so an open editor+// does not see a conflict and the doc does not jump in "recently edited".+func (q *Queries) MoveDoc(ctx context.Context, arg MoveDocParams) (Doc, error) {+ row := q.db.QueryRow(ctx, moveDoc, arg.FolderID, arg.ID, arg.WorkspaceID)+ var i Doc+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.FolderID,+ &i.Title,+ &i.Content,+ &i.Revision,+ &i.VersionCount,+ &i.CreatedByType,+ &i.CreatedByID,+ &i.UpdatedByType,+ &i.UpdatedByID,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const moveDocFolder = `-- name: MoveDocFolder :one+UPDATE doc_folder SET parent_id = $1, updated_at = now()+WHERE id = $2 AND workspace_id = $3+RETURNING id, workspace_id, parent_id, title, created_by_type, created_by_id, created_at, updated_at+`++type MoveDocFolderParams struct {+ ParentID pgtype.UUID `json:"parent_id"`+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) MoveDocFolder(ctx context.Context, arg MoveDocFolderParams) (DocFolder, error) {+ row := q.db.QueryRow(ctx, moveDocFolder, arg.ParentID, arg.ID, arg.WorkspaceID)+ var i DocFolder+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.ParentID,+ &i.Title,+ &i.CreatedByType,+ &i.CreatedByID,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const renameDocFolder = `-- name: RenameDocFolder :one+UPDATE doc_folder SET title = $1, updated_at = now()+WHERE id = $2 AND workspace_id = $3+RETURNING id, workspace_id, parent_id, title, created_by_type, created_by_id, created_at, updated_at+`++type RenameDocFolderParams struct {+ Title string `json:"title"`+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) RenameDocFolder(ctx context.Context, arg RenameDocFolderParams) (DocFolder, error) {+ row := q.db.QueryRow(ctx, renameDocFolder, arg.Title, arg.ID, arg.WorkspaceID)+ var i DocFolder+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.ParentID,+ &i.Title,+ &i.CreatedByType,+ &i.CreatedByID,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const updateDocContent = `-- name: UpdateDocContent :one+UPDATE doc SET+ title = $1,+ content = $2,+ revision = revision + 1,+ version_count = $3,+ updated_by_type = $4,+ updated_by_id = $5,+ updated_at = now()+WHERE id = $6 AND workspace_id = $7+RETURNING id, workspace_id, folder_id, title, content, revision, version_count, created_by_type, created_by_id, updated_by_type, updated_by_id, created_at, updated_at+`++type UpdateDocContentParams struct {+ Title string `json:"title"`+ Content string `json:"content"`+ VersionCount int32 `json:"version_count"`+ UpdatedByType string `json:"updated_by_type"`+ UpdatedByID pgtype.UUID `json:"updated_by_id"`+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) UpdateDocContent(ctx context.Context, arg UpdateDocContentParams) (Doc, error) {+ row := q.db.QueryRow(ctx, updateDocContent,+ arg.Title,+ arg.Content,+ arg.VersionCount,+ arg.UpdatedByType,+ arg.UpdatedByID,+ arg.ID,+ arg.WorkspaceID,+ )+ var i Doc+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.FolderID,+ &i.Title,+ &i.Content,+ &i.Revision,+ &i.VersionCount,+ &i.CreatedByType,+ &i.CreatedByID,+ &i.UpdatedByType,+ &i.UpdatedByID,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex c7b9f1c112..40ac357a14 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -843,6 +843,50 @@ type DingtalkGroupRoute struct {UpdatedAt pgtype.Timestamptz `json:"updated_at"`}+type Doc struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ FolderID pgtype.UUID `json:"folder_id"`+ Title string `json:"title"`+ Content string `json:"content"`+ Revision int64 `json:"revision"`+ VersionCount int32 `json:"version_count"`+ CreatedByType string `json:"created_by_type"`+ CreatedByID pgtype.UUID `json:"created_by_id"`+ UpdatedByType string `json:"updated_by_type"`+ UpdatedByID pgtype.UUID `json:"updated_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"`+ ParentID pgtype.UUID `json:"parent_id"`+ Title string `json:"title"`+ CreatedByType string `json:"created_by_type"`+ CreatedByID pgtype.UUID `json:"created_by_id"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}++type DocVersion struct {+ DocID pgtype.UUID `json:"doc_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Number int32 `json:"number"`+ Title string `json:"title"`+ Content string `json:"content"`+ AuthorType string `json:"author_type"`+ AuthorID pgtype.UUID `json:"author_id"`+ Message string `json:"message"`+ Action string `json:"action"`+ ActionRef pgtype.Int4 `json:"action_ref"`+ TaskID pgtype.UUID `json:"task_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}+type EntitlementFeatureAttempt struct {WorkspaceID pgtype.UUID `json:"workspace_id"`Feature string `json:"feature"`diff --git a/server/pkg/db/queries/doc.sql b/server/pkg/db/queries/doc.sqlnew file mode 100644index 0000000000..d7544a8eec--- /dev/null+++ b/server/pkg/db/queries/doc.sql@@ -0,0 +1,131 @@+-- Workspace documents and folders.++-- name: LockDocTree :exec+-- Serializes folder/doc moves within one workspace so the cycle check and the+-- move it guards see the same tree.+SELECT pg_advisory_xact_lock(hashtextextended(sqlc.arg('workspace_id')::uuid::text || ':doc_tree', 0));++-- name: ListDocFolders :many+SELECT * FROM doc_folder+WHERE workspace_id = $1+ORDER BY lower(title), created_at;++-- name: GetDocFolder :one+SELECT * FROM doc_folder+WHERE id = $1 AND workspace_id = $2;++-- name: CreateDocFolder :one+INSERT INTO doc_folder (workspace_id, parent_id, title, created_by_type, created_by_id)+VALUES (@workspace_id, sqlc.narg('parent_id'), @title, @created_by_type, @created_by_id)+RETURNING *;++-- name: RenameDocFolder :one+UPDATE doc_folder SET title = @title, updated_at = now()+WHERE id = @id AND workspace_id = @workspace_id+RETURNING *;++-- name: MoveDocFolder :one+UPDATE doc_folder SET parent_id = sqlc.narg('parent_id'), updated_at = now()+WHERE id = @id AND workspace_id = @workspace_id+RETURNING *;++-- name: CountDocFolderChildren :one+SELECT (+ (SELECT count(*) FROM doc_folder f WHERE f.workspace_id = @workspace_id AND f.parent_id = @folder_id::uuid)+ + (SELECT count(*) FROM doc d WHERE d.workspace_id = @workspace_id AND d.folder_id = @folder_id::uuid)+)::int AS total;++-- name: DeleteDocFolder :exec+DELETE FROM doc_folder WHERE id = $1 AND workspace_id = $2;++-- name: ListDocs :many+SELECT id, workspace_id, folder_id, title, revision, version_count,+created_by_type, created_by_id, updated_by_type, updated_by_id, created_at, updated_at+FROM doc WHERE workspace_id = $1 ORDER BY lower(title), created_at;++-- name: GetDoc :one+SELECT * FROM doc+WHERE id = $1 AND workspace_id = $2;++-- name: GetDocForUpdate :one+SELECT * FROM doc+WHERE id = $1 AND workspace_id = $2+FOR UPDATE;++-- name: CreateDoc :one+INSERT INTO doc (+ workspace_id, folder_id, title, content,+ created_by_type, created_by_id, updated_by_type, updated_by_id+) VALUES (+ @workspace_id, sqlc.narg('folder_id'), @title, @content,+ @author_type, @author_id, @author_type, @author_id+)+RETURNING *;++-- name: UpdateDocContent :one+UPDATE doc SET+ title = @title,+ content = @content,+ revision = revision + 1,+ version_count = @version_count,+ updated_by_type = @updated_by_type,+ updated_by_id = @updated_by_id,+ updated_at = now()+WHERE id = @id AND workspace_id = @workspace_id+RETURNING *;++-- name: MoveDoc :one+-- A move is not an edit: revision and updated_at stay put so an open editor+-- does not see a conflict and the doc does not jump in "recently edited".+UPDATE doc SET folder_id = sqlc.narg('folder_id')+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)+DELETE FROM doc WHERE doc.id = @id AND doc.workspace_id = @workspace_id;++-- name: GetDocVersion :one+SELECT * FROM doc_version+WHERE doc_id = $1 AND number = $2;++-- name: ListDocVersions :many+SELECT+ doc_id, workspace_id, number, title, author_type, author_id, message, action,+ action_ref, task_id, issue_id, created_at, updated_at+FROM doc_version+WHERE doc_id = $1+ORDER BY number DESC+LIMIT $2;++-- name: MergeDocEditIntoVersion :execrows+-- Folds an edit into the latest snapshot while the same author keeps editing:+-- an unlabeled edit from the same author and task within 30 minutes of the+-- snapshot's start. Creates, restores and labeled edits always stand alone.+UPDATE doc_version SET+ title = @title,+ content = @content,+ updated_at = now()+WHERE doc_id = @doc_id+ AND number = @number+ AND action = 'edit'+ AND message = ''+ AND author_type = @author_type+ AND author_id = @author_id+ AND task_id IS NOT DISTINCT FROM sqlc.narg('task_id')+ AND created_at > now() - interval '30 minutes';++-- name: InsertDocVersion :one+INSERT INTO doc_version (+ doc_id, workspace_id, number, title, content, author_type, author_id,+ message, action, action_ref, task_id, issue_id+) VALUES (+ @doc_id, @workspace_id, @number, @title, @content, @author_type, @author_id,+ @message, @action, sqlc.narg('action_ref'), sqlc.narg('task_id'), sqlc.narg('issue_id')+)+RETURNING *;++-- name: DeleteWorkspaceDocs :exec+WITH v AS (DELETE FROM doc_version WHERE doc_version.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;diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.goindex 413a27b505..8d7b9516f7 100644--- a/server/pkg/protocol/events.go+++ b/server/pkg/protocol/events.go@@ -152,6 +152,13 @@ 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"+// Pin eventsEventPinCreated = "pin:created"EventPinDeleted = "pin:deleted"