Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(docs): open a doc straight into its live editor (MUL-9781) (#11130)
Jiayuan Zhang1034a926a683
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 980fe2f84f..0899c2be31 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -1096,9 +1096,14 @@ export class ApiClient {{ endpoint: "GET /api/docs/{id}/versions" },).versions;}- async createDocCollabTicket(id: string): Promise<DocCollabTicket> {+ /** `state` also asks for the Yjs state saved with the doc, to show it+ * before the live session syncs. */+ async createDocCollabTicket(id: string, options?: { state?: boolean }): Promise<DocCollabTicket> {return parseWithFallback<DocCollabTicket>(- await this.fetch<unknown>(`/api/docs/${id}/collab-ticket`, { method: "POST" }),+ await this.fetch<unknown>(`/api/docs/${id}/collab-ticket`, {+ method: "POST",+ ...(options?.state ? { body: JSON.stringify({ state: true }) } : {}),+ }),DocCollabTicketSchema,{ enabled: false },{ endpoint: "POST /api/docs/{id}/collab-ticket" },diff --git a/packages/core/docs/client.test.ts b/packages/core/docs/client.test.tsindex 95459c229f..a2156e01f4 100644--- a/packages/core/docs/client.test.ts+++ b/packages/core/docs/client.test.ts@@ -67,6 +67,31 @@ describe("knowledge base client", () => {).rejects.toThrow(/Malformed response/);});+ it("asks for the saved state with a collab ticket only when told to", async () => {+ const client = new ApiClient("https://api.example.test");+ const fetchMock = respond({ enabled: true, token: "t", document: "doc:d1", expires_at: "2026-11-21T00:00:00Z", state: "AAE=" });+ expect(await client.createDocCollabTicket("d1", { state: true })).toEqual({+ enabled: true,+ token: "t",+ document: "doc:d1",+ expiresAt: "2026-11-21T00:00:00Z",+ state: "AAE=",+ });+ expect(fetchMock.mock.calls[0]![1].body).toBe(JSON.stringify({ state: true }));++ const plain = respond({ enabled: true, token: "t", document: "doc:d1" });+ expect(await client.createDocCollabTicket("d1")).not.toHaveProperty("state");+ expect(plain.mock.calls[0]![1].body).toBeUndefined();+ });++ it("treats a malformed collab ticket as live editing off", async () => {+ const client = new ApiClient("https://api.example.test");+ respond({ enabled: "yes", state: 42 });+ expect(await client.createDocCollabTicket("d1", { state: true })).toEqual({ enabled: false });+ respond({ enabled: true, document: "doc:d1" });+ expect(await client.createDocCollabTicket("d1")).toEqual({ enabled: false });+ });+it("falls back to an empty tree and versions on malformed responses", async () => {const client = new ApiClient("https://api.example.test");respond({ folders: "nope" });diff --git a/packages/core/docs/schemas.ts b/packages/core/docs/schemas.tsindex 8b0225f542..09ef11e779 100644--- a/packages/core/docs/schemas.ts+++ b/packages/core/docs/schemas.ts@@ -168,9 +168,16 @@ export const DocCollabTicketSchema = ztoken: z.string().optional(),document: z.string().optional(),expires_at: z.string().optional(),+ state: z.string().optional(),}).transform((t) =>t.enabled && t.token && t.document- ? { enabled: true as const, token: t.token, document: t.document, expiresAt: t.expires_at ?? "" }+ ? {+ enabled: true as const,+ token: t.token,+ document: t.document,+ expiresAt: t.expires_at ?? "",+ ...(t.state ? { state: t.state } : {}),+ }: { enabled: false as const },);diff --git a/packages/core/types/doc.ts b/packages/core/types/doc.tsindex 7b083afbd1..0ee9f97d65 100644--- a/packages/core/types/doc.ts+++ b/packages/core/types/doc.ts@@ -87,7 +87,15 @@ export interface DocVersion {/** Lets an editor join a doc's live session; `enabled: false` when the* server runs without the collaboration service. */export type DocCollabTicket =- | { enabled: true; token: string; document: string; expiresAt: string }+ | {+ enabled: true;+ token: string;+ document: string;+ expiresAt: string;+ /** Base64 Yjs state saved with the doc's current revision, when asked+ * for and the live session would load it unchanged. */+ state?: string;+ }| { enabled: false };export interface CreateDocRequest {title: string;diff --git a/packages/views/docs/components/doc-live-session.test.ts b/packages/views/docs/components/doc-live-session.test.tsnew file mode 100644index 0000000000..68b6a295f4--- /dev/null+++ b/packages/views/docs/components/doc-live-session.test.ts@@ -0,0 +1,249 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import * as Y from "yjs";++const { apiMock, providers, sockets } = vi.hoisted(() => ({+ apiMock: { createDocCollabTicket: vi.fn() },+ providers: [] as Array<{+ config: {+ name: string;+ token: () => Promise<string>;+ onSynced: (e: { state: boolean }) => void;+ onClose: (e: { event: { reason: string } }) => void;+ };+ destroyed: boolean;+ awareness: { local: unknown };+ }>,+ sockets: [] as Array<{ destroyed: boolean }>,+}));++vi.mock("@multica/core/api", () => ({ api: apiMock }));+vi.mock("@hocuspocus/provider", () => {+ class HocuspocusProviderWebsocket {+ status = "disconnected";+ destroyed = false;+ constructor() {+ sockets.push(this);+ }+ destroy() {+ this.destroyed = true;+ }+ }+ class HocuspocusProvider {+ destroyed = false;+ awareness = {+ local: {} as unknown,+ on() {},+ off() {},+ getStates: () => new Map(),+ getLocalState() {+ return this.local;+ },+ setLocalState(state: unknown) {+ this.local = state;+ },+ };+ constructor(public config: (typeof providers)[number]["config"]) {+ providers.push(this);+ }+ attach() {}+ destroy() {+ this.destroyed = true;+ }+ }+ return {+ HocuspocusProvider,+ HocuspocusProviderWebsocket,+ WebSocketStatus: { Connected: "connected", Connecting: "connecting", Disconnected: "disconnected" },+ };+});++import {+ acquireDocSession,+ findDocSession,+ liveEditingOff,+ peekDocLive,+ prefetchDocLive,+ releaseDocSession,+} from "./doc-live-session";++let n = 0;+const ids = () => {+ n++;+ return { url: `ws://collab-${n}.test/collab`, docId: `doc-${n}` };+};++function savedState(text: string): string {+ const doc = new Y.Doc();+ doc.getText("t").insert(0, text);+ return btoa(String.fromCharCode(...Y.encodeStateAsUpdate(doc)));+}++const ticket = (docId: string, extra: Record<string, unknown> = {}) => ({+ enabled: true,+ token: `token-${docId}`,+ document: `doc:${docId}`,+ expiresAt: new Date(Date.now() + 5 * 60_000).toISOString(),+ ...extra,+});++beforeEach(() => {+ apiMock.createDocCollabTicket.mockReset();+ providers.length = 0;+ sockets.length = 0;+});++afterEach(() => {+ vi.useRealTimers();+});++describe("prefetchDocLive", () => {+ it("asks once for a doc while the answer is fresh, with its saved state", async () => {+ const { url, docId } = ids();+ apiMock.createDocCollabTicket.mockResolvedValue(ticket(docId));+ await Promise.all([prefetchDocLive(url, docId, "u1"), prefetchDocLive(url, docId, "u1")]);+ expect(apiMock.createDocCollabTicket).toHaveBeenCalledTimes(1);+ expect(apiMock.createDocCollabTicket).toHaveBeenCalledWith(docId, { state: true });+ expect(peekDocLive(url, docId, "u1")).toMatchObject({ enabled: true, document: `doc:${docId}` });+ });++ it("remembers a server without live editing and opens no socket to it", async () => {+ const { url, docId } = ids();+ apiMock.createDocCollabTicket.mockResolvedValue({ enabled: false });+ await prefetchDocLive(url, docId, "u1");+ expect(liveEditingOff.has(url)).toBe(true);+ expect(sockets).toHaveLength(0);+ });++ it("opens the socket early only for a server known to edit live", async () => {+ vi.useFakeTimers();+ const { url, docId } = ids();+ apiMock.createDocCollabTicket.mockResolvedValue(ticket(docId));+ const first = prefetchDocLive(url, docId, "u1");+ expect(sockets).toHaveLength(0);+ await first;+ expect(sockets).toHaveLength(1);+ vi.advanceTimersByTime(60_000);+ expect(sockets[0]!.destroyed).toBe(true);++ void prefetchDocLive(url, `${docId}-next`, "u1");+ expect(sockets).toHaveLength(2);+ });++ it("keeps answers per user: a ticket is personal", async () => {+ const { url, docId } = ids();+ apiMock.createDocCollabTicket.mockResolvedValue(ticket(docId));+ await prefetchDocLive(url, docId, "u1");+ expect(peekDocLive(url, docId, "u2")).toBeUndefined();+ await prefetchDocLive(url, docId, "u2");+ expect(apiMock.createDocCollabTicket).toHaveBeenCalledTimes(2);+ });++ it("forgets an answer nobody used once it is stale, and asks again", async () => {+ vi.useFakeTimers();+ const { url, docId } = ids();+ apiMock.createDocCollabTicket.mockResolvedValue(ticket(docId));+ await prefetchDocLive(url, docId, "u1");+ vi.advanceTimersByTime(30_000);+ expect(peekDocLive(url, docId, "u1")).toBeUndefined();+ await prefetchDocLive(url, docId, "u1");+ expect(apiMock.createDocCollabTicket).toHaveBeenCalledTimes(2);+ });++ it("forgets a failed request so the next one retries", async () => {+ const { url, docId } = ids();+ apiMock.createDocCollabTicket.mockRejectedValueOnce(new Error("offline"));+ await expect(prefetchDocLive(url, docId, "u1")).rejects.toThrow("offline");+ apiMock.createDocCollabTicket.mockResolvedValue(ticket(docId));+ await prefetchDocLive(url, docId, "u1");+ expect(apiMock.createDocCollabTicket).toHaveBeenCalledTimes(2);+ });+});++describe("doc sessions", () => {+ it("shows the saved state before syncing and joins with the prefetched ticket once", async () => {+ const { url, docId } = ids();+ apiMock.createDocCollabTicket.mockResolvedValueOnce(ticket(docId, { state: savedState("hello") }));+ await prefetchDocLive(url, docId, "u1");++ const session = acquireDocSession(url, docId, "u1", `doc:${docId}`);+ expect(session.getState()).toMatchObject({ ready: true, synced: false });+ expect(session.ydoc.getText("t").toString()).toBe("hello");+ expect(session.edited).toBe(false);++ const provider = providers.at(-1)!;+ expect(JSON.parse(await provider.config.token())).toEqual({ ticket: `token-${docId}` });+ expect(apiMock.createDocCollabTicket).toHaveBeenCalledTimes(1);++ // A rejoin asks for a fresh ticket.+ apiMock.createDocCollabTicket.mockResolvedValueOnce(ticket(docId, { token: "fresh" }));+ expect(JSON.parse(await provider.config.token()).ticket).toBe("fresh");++ provider.config.onSynced({ state: true });+ expect(session.getState()).toMatchObject({ ready: true, synced: true });+ releaseDocSession(session, { discard: true });+ });++ it("waits for the first sync when there is no saved state", async () => {+ const { url, docId } = ids();+ apiMock.createDocCollabTicket.mockResolvedValueOnce(ticket(docId));+ await prefetchDocLive(url, docId, "u1");+ const session = acquireDocSession(url, docId, "u1", `doc:${docId}`);+ expect(session.getState().ready).toBe(false);+ session.ydoc.getText("t").insert(0, "typed");+ expect(session.edited).toBe(true);+ releaseDocSession(session, { discard: true });+ });++ it("keeps a released session for the next visit, then ends it", () => {+ vi.useFakeTimers();+ const { url, docId } = ids();+ const session = acquireDocSession(url, docId, "u1", `doc:${docId}`);+ releaseDocSession(session);+ expect(acquireDocSession(url, docId, "u1", `doc:${docId}`)).toBe(session);+ expect(providers).toHaveLength(1);++ releaseDocSession(session);+ vi.advanceTimersByTime(60_000);+ expect(findDocSession(url, docId, "u1")).toBeUndefined();+ expect(providers[0]!.destroyed).toBe(true);+ // The socket closes once nothing uses it.+ vi.advanceTimersByTime(60_000);+ expect(sockets.at(-1)!.destroyed).toBe(true);+ });++ it("leaves the doc's presence while kept, and rejoins it on the next visit", () => {+ const { url, docId } = ids();+ const session = acquireDocSession(url, docId, "u1", `doc:${docId}`);+ const awareness = providers.at(-1)!.awareness;+ awareness.local = { user: { id: "u1" } };+ releaseDocSession(session);+ expect(awareness.local).toBeNull();+ acquireDocSession(url, docId, "u1", `doc:${docId}`);+ expect(awareness.local).toEqual({});+ releaseDocSession(session, { discard: true });+ });++ it("shares one socket between docs on the same server", () => {+ const { url, docId } = ids();+ const a = acquireDocSession(url, docId, "u1", `doc:${docId}`);+ const b = acquireDocSession(url, `${docId}-b`, "u1", `doc:${docId}-b`);+ expect(sockets).toHaveLength(1);+ releaseDocSession(a, { discard: true });+ releaseDocSession(b, { discard: true });+ });++ it("ends a reset session once its page lets go, and starts the next one fresh", () => {+ const { url, docId } = ids();+ const session = acquireDocSession(url, docId, "u1", `doc:${docId}`);+ providers.at(-1)!.config.onClose({ event: { reason: "document-reset" } });+ expect(session.getState().reset).toBe(true);+ expect(findDocSession(url, docId, "u1")).toBeUndefined();+ expect(providers.at(-1)!.destroyed).toBe(false);++ const next = acquireDocSession(url, docId, "u1", `doc:${docId}`);+ expect(next).not.toBe(session);+ releaseDocSession(session);+ expect(providers[0]!.destroyed).toBe(true);+ releaseDocSession(next, { discard: true });+ });+});diff --git a/packages/views/docs/components/doc-live-session.ts b/packages/views/docs/components/doc-live-session.tsnew file mode 100644index 0000000000..c07b92e7c8--- /dev/null+++ b/packages/views/docs/components/doc-live-session.ts@@ -0,0 +1,385 @@+"use client";+import * as Y from "yjs";+import {+ HocuspocusProvider,+ HocuspocusProviderWebsocket,+ WebSocketStatus,+} from "@hocuspocus/provider";+import { api } from "@multica/core/api";+import type { DocCollabTicket } from "@multica/core/types";++/**+ * Live sessions for docs, kept outside React so opening a doc does as little+ * as possible in front of the reader:+ *+ * - One WebSocket per collaboration server, shared by every open doc, so a+ * doc joins over a socket that is usually already open.+ * - The ticket and the doc's saved Yjs state come in one request, made as+ * soon as the doc is opened or hovered. The state fills the shared document+ * before the session syncs, so the editor shows the doc at once.+ * - A session outlives its page for a while, so going back to a doc finds it+ * connected and current.+ */++/** Servers that answered that live editing is off. That is server+ * configuration, so later docs open for solo editing without asking again. */+export const liveEditingOff = new Set<string>();+/** Servers that answered that live editing is on; their socket can open+ * before the next answer arrives. */+const liveEditingOn = new Set<string>();++const COLORS = ["#2563eb", "#db2777", "#059669", "#d97706", "#7c3aed", "#0891b2", "#dc2626", "#4f46e5"];++export function colorFor(id: string): string {+ let hash = 0;+ for (const char of id) hash = (hash * 31 + char.charCodeAt(0)) | 0;+ return COLORS[Math.abs(hash) % COLORS.length]!;+}++/** Someone else in the session: a person, or an agent writing through the API. */+export interface DocCollaborator {+ key: number;+ id: string;+ name: string;+ color: string;+ kind: "member" | "agent";+}++// ---- Ticket and saved state --------------------------------------------------++/** How long a fetched ticket and state are used to open the doc. The state+ * only has to be close: the session brings it up to date. */+const LIVE_INFO_MAX_AGE_MS = 30_000;+/** A ticket this close to expiring is not used for a new connection. */+const TICKET_MARGIN_MS = 30_000;++type LiveTicket = Extract<DocCollabTicket, { enabled: true }>;++interface LiveInfo {+ at: number;+ promise: Promise<DocCollabTicket>;+ value?: DocCollabTicket;+}++/** Tickets are personal, so answers are kept per user like sessions are. */+const liveInfos = new Map<string, LiveInfo>();+const infoKey = (collabUrl: string, docId: string, userId: string) => `${collabUrl}\n${docId}\n${userId}`;++/**+ * Asks for the doc's ticket and saved state, unless a recent answer is on+ * hand or on its way. Also opens the shared socket of a server known to edit+ * live, so it is up by the time the doc joins.+ */+export function prefetchDocLive(collabUrl: string, docId: string, userId: string): Promise<DocCollabTicket> {+ const key = infoKey(collabUrl, docId, userId);+ const cached = liveInfos.get(key);+ if (cached && Date.now() - cached.at < LIVE_INFO_MAX_AGE_MS) return cached.promise;+ const info: LiveInfo = { at: Date.now(), promise: Promise.resolve({ enabled: false }) };+ info.promise = api.createDocCollabTicket(docId, { state: true }).then(+ (ticket) => {+ info.value = ticket;+ if (ticket.enabled) {+ liveEditingOff.delete(collabUrl);+ if (!liveEditingOn.has(collabUrl)) warmSocket(collabUrl);+ liveEditingOn.add(collabUrl);+ } else {+ liveEditingOff.add(collabUrl);+ liveEditingOn.delete(collabUrl);+ }+ return ticket;+ },+ (error: unknown) => {+ if (liveInfos.get(key) === info) liveInfos.delete(key);+ throw error;+ },+ );+ liveInfos.set(key, info);+ // A hovered doc that is never opened must not hold its state for good.+ setTimeout(() => {+ if (liveInfos.get(key) === info) liveInfos.delete(key);+ }, LIVE_INFO_MAX_AGE_MS);+ if (liveEditingOn.has(collabUrl)) warmSocket(collabUrl);+ return info.promise;+}++/** The answer of a recent `prefetchDocLive`, if it has arrived. */+export function peekDocLive(collabUrl: string, docId: string, userId: string): DocCollabTicket | undefined {+ const info = liveInfos.get(infoKey(collabUrl, docId, userId));+ return info && Date.now() - info.at < LIVE_INFO_MAX_AGE_MS ? info.value : undefined;+}++/** Takes the answer for a session about to start: its state describes the+ * doc only until the session moves on, so it is used once. */+function takeDocLive(collabUrl: string, docId: string, userId: string): LiveTicket | undefined {+ const value = peekDocLive(collabUrl, docId, userId);+ liveInfos.delete(infoKey(collabUrl, docId, userId));+ return value?.enabled ? value : undefined;+}++function ticketUsable(ticket: LiveTicket | null): ticket is LiveTicket {+ if (!ticket) return false;+ const expires = Date.parse(ticket.expiresAt);+ return Number.isFinite(expires) && expires - Date.now() > TICKET_MARGIN_MS;+}++// ---- Shared sockets ------------------------------------------------------------++/** How long a socket nobody uses stays open. */+const SOCKET_IDLE_MS = 60_000;++interface SharedSocket {+ socket: HocuspocusProviderWebsocket;+ users: number;+ idle: ReturnType<typeof setTimeout> | null;+}++const sockets = new Map<string, SharedSocket>();++function acquireSocket(url: string): HocuspocusProviderWebsocket {+ let shared = sockets.get(url);+ if (!shared) {+ shared = { socket: new HocuspocusProviderWebsocket({ url }), users: 0, idle: null };+ sockets.set(url, shared);+ }+ if (shared.idle) clearTimeout(shared.idle);+ shared.idle = null;+ shared.users++;+ return shared.socket;+}++function releaseSocket(url: string) {+ const shared = sockets.get(url);+ if (!shared) return;+ shared.users = Math.max(0, shared.users - 1);+ if (shared.users > 0 || shared.idle) return;+ shared.idle = setTimeout(() => {+ if (sockets.get(url) !== shared || shared.users > 0) return;+ sockets.delete(url);+ shared.socket.destroy();+ }, SOCKET_IDLE_MS);+}++/** Opens the server's socket ahead of a doc joining it. */+export function warmSocket(url: string) {+ acquireSocket(url);+ releaseSocket(url);+}++// ---- Sessions ------------------------------------------------------------------++/** How long a session stays connected after its page closes. */+const SESSION_KEEP_MS = 60_000;+/** Sessions kept for pages that are closed; the oldest goes first. */+const MAX_KEPT_SESSIONS = 5;++export interface DocSessionState {+ /** The shared document holds the doc, from its saved state or the first+ * sync, so the editor can show it. */+ ready: boolean;+ /** The first sync with the server is done. */+ synced: boolean;+ connected: boolean;+ collaborators: DocCollaborator[];+ /** The server rebuilt the doc: this session is over and a new one starts+ * from the server's copy. */+ reset: boolean;+}++let nextSessionId = 1;++export class DocSession {+ readonly id = nextSessionId++;+ readonly ydoc = new Y.Doc();+ readonly provider: HocuspocusProvider;+ /** Changed by this tab since it was filled, not by the server. */+ edited = false;+ private state: DocSessionState;+ private readonly listeners = new Set<() => void>();+ private users = 0;+ private keep: ReturnType<typeof setTimeout> | null = null;+ private ticket: LiveTicket | null;+ private destroyed = false;++ constructor(+ readonly key: string,+ private readonly collabUrl: string,+ private readonly docId: string,+ readonly document: string,+ seed: LiveTicket | undefined,+ ) {+ this.ticket = seed ?? null;+ let seeded = false;+ if (seed?.state) {+ try {+ Y.applyUpdate(this.ydoc, base64ToBytes(seed.state));+ seeded = true;+ } catch {+ // An unreadable state is ignored; the first sync fills the document.+ }+ }+ const socket = acquireSocket(collabUrl);+ this.state = {+ ready: seeded,+ synced: false,+ connected: socket.status === WebSocketStatus.Connected,+ collaborators: [],+ reset: false,+ };+ this.provider = new HocuspocusProvider({+ websocketProvider: socket,+ name: document,+ document: this.ydoc,+ // Asked on every (re)join. The epoch names the copy this tab holds, so+ // the server can tell it to start over if the doc was rebuilt.+ token: async () => {+ const ticket = ticketUsable(this.ticket) ? this.ticket : await api.createDocCollabTicket(this.docId);+ this.ticket = null;+ if (!ticket.enabled) throw new Error("live editing is off");+ const epoch = this.ydoc.getMap("meta").get("epoch");+ return JSON.stringify({ ticket: ticket.token, epoch: typeof epoch === "string" ? epoch : undefined });+ },+ onSynced: ({ state }) => {+ if (state) this.update({ synced: true, ready: true });+ },+ onStatus: ({ status }) => this.update({ connected: status === WebSocketStatus.Connected }),+ onClose: ({ event }) => {+ if (event.reason === "document-reset") this.update({ reset: true });+ },+ });+ this.provider.attach();+ this.ydoc.on("update", (_update: Uint8Array, origin: unknown) => {+ if (origin !== this.provider) this.edited = true;+ });+ this.provider.awareness?.on("change", this.updateCollaborators);+ }++ getState = (): DocSessionState => this.state;++ subscribe = (listener: () => void): (() => void) => {+ this.listeners.add(listener);+ return () => this.listeners.delete(listener);+ };++ private update(patch: Partial<DocSessionState>) {+ const next = { ...this.state, ...patch };+ if ((Object.keys(patch) as (keyof DocSessionState)[]).every((k) => next[k] === this.state[k])) return;+ this.state = next;+ if (next.reset) dropSession(this);+ for (const listener of this.listeners) listener();+ }++ // Awareness changes on every caret move of every editor; only re-render+ // when who is here changes.+ private signature = "";+ private updateCollaborators = () => {+ const seen = new Set<string>();+ const next: DocCollaborator[] = [];+ for (const [key, state] of this.provider.awareness?.getStates() ?? []) {+ if (key === this.ydoc.clientID) continue;+ const u = (state as { user?: Partial<DocCollaborator> }).user;+ if (!u?.name || !u.id) continue;+ const dedupe = `${u.kind}:${u.id}`;+ if (seen.has(dedupe)) continue;+ seen.add(dedupe);+ next.push({ key, id: u.id, name: u.name, color: u.color ?? colorFor(u.id), kind: u.kind === "agent" ? "agent" : "member" });+ }+ const signature = next.map((c) => `${c.key}:${c.kind}:${c.id}:${c.name}:${c.color}`).join("|");+ if (signature === this.signature) return;+ this.signature = signature;+ this.update({ collaborators: next });+ };++ /** Out of the cache: no page joins it again, and it ends with its last user. */+ dropped = false;++ /** @internal */+ retain() {+ if (this.keep) clearTimeout(this.keep);+ this.keep = null;+ this.users++;+ // Fields such as the editor's user can only be set on a present state.+ const awareness = this.provider.awareness;+ if (awareness && awareness.getLocalState() === null) awareness.setLocalState({});+ }++ /** @internal Reports whether the session is now kept for later. */+ release(): boolean {+ this.users = Math.max(0, this.users - 1);+ if (this.users > 0) return false;+ if (this.dropped) {+ this.destroy();+ return false;+ }+ // Nobody is on the page any more, so others stop seeing this tab in it.+ this.provider.awareness?.setLocalState(null);+ this.keep = setTimeout(() => dropSession(this), SESSION_KEEP_MS);+ return true;+ }++ get idle() {+ return this.users === 0;+ }++ /** @internal */+ destroy() {+ if (this.destroyed) return;+ this.destroyed = true;+ if (this.keep) clearTimeout(this.keep);+ this.provider.awareness?.off("change", this.updateCollaborators);+ this.provider.destroy();+ this.ydoc.destroy();+ releaseSocket(this.collabUrl);+ this.listeners.clear();+ }+}++/** Live sessions by server, doc and user, oldest first. */+const sessions = new Map<string, DocSession>();++const sessionKey = (collabUrl: string, docId: string, userId: string) => `${collabUrl}\n${docId}\n${userId}`;++function dropSession(session: DocSession) {+ if (sessions.get(session.key) === session) sessions.delete(session.key);+ session.dropped = true;+ if (session.idle) session.destroy();+}++/**+ * The doc's live session, joined or started. A new session is filled from+ * the saved state a recent `prefetchDocLive` brought, if any. Pair with+ * `releaseDocSession`.+ */+export function acquireDocSession(collabUrl: string, docId: string, userId: string, document: string): DocSession {+ const key = sessionKey(collabUrl, docId, userId);+ let session = sessions.get(key);+ if (session) {+ sessions.delete(key);+ } else {+ session = new DocSession(key, collabUrl, docId, document, takeDocLive(collabUrl, docId, userId));+ }+ sessions.set(key, session);+ session.retain();+ return session;+}++/** Hands the session back. It stays connected for a while unless `discard`+ * ends it now, as when the page stops editing live. */+export function releaseDocSession(session: DocSession, opts: { discard?: boolean } = {}) {+ if (opts.discard && sessions.get(session.key) === session) sessions.delete(session.key);+ if (opts.discard) session.dropped = true;+ if (!session.release()) return;+ const kept = [...sessions.values()].filter((s) => s.idle);+ for (const old of kept.slice(0, Math.max(0, kept.length - MAX_KEPT_SESSIONS))) dropSession(old);+}++/** The doc's live session, if one is open or kept. */+export function findDocSession(collabUrl: string, docId: string, userId: string): DocSession | undefined {+ return sessions.get(sessionKey(collabUrl, docId, userId));+}++function base64ToBytes(base64: string): Uint8Array {+ const binary = atob(base64);+ const bytes = new Uint8Array(binary.length);+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);+ return bytes;+}diff --git a/packages/views/docs/components/doc-not-found.test.tsx b/packages/views/docs/components/doc-not-found.test.tsxindex f2cbd1fa26..e8d0d0c28c 100644--- a/packages/views/docs/components/doc-not-found.test.tsx+++ b/packages/views/docs/components/doc-not-found.test.tsx@@ -68,6 +68,13 @@ vi.mock("../../editor", () => ({useEditorUpload: () => ({ uploadWithToast: vi.fn() }),}));vi.mock("./use-doc-collab", () => ({ useDocCollab: () => ({ mode: "solo" }) }));+vi.mock("@multica/core/realtime", () => ({ useWS: () => ({ collabUrl: "ws://collab.test/collab" }) }));+vi.mock("./doc-live-session", () => ({+ liveEditingOff: new Set(["ws://collab.test/collab"]),+ peekDocLive: () => undefined,+ findDocSession: () => undefined,+ prefetchDocLive: () => Promise.resolve({ enabled: false }),+}));vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));vi.mock("../../layout/breadcrumb-header", () => ({BreadcrumbHeader: ({ actions }: { actions?: React.ReactNode }) => <header>{actions}</header>,diff --git a/packages/views/docs/components/doc-outline.test.tsx b/packages/views/docs/components/doc-outline.test.tsxindex 531d0c60a7..93ab04d866 100644--- a/packages/views/docs/components/doc-outline.test.tsx+++ b/packages/views/docs/components/doc-outline.test.tsx@@ -32,6 +32,15 @@ describe("readOutline", () => {});});+describe("readOutline: hidden editor", () => {+ it("skips an editor still mounting behind `hidden`", () => {+ const root = document.createElement("div");+ root.innerHTML =+ '<div class="ProseMirror"><h1>Shown</h1></div><div hidden><div class="ProseMirror"><h1>Mounting</h1></div></div>';+ expect(readOutline(root).map(({ text }) => text)).toEqual(["Shown"]);+ });+});+describe("DocOutline", () => {it("marks the current heading and reports clicks", () => {const headings = readOutline(diff --git a/packages/views/docs/components/doc-outline.tsx b/packages/views/docs/components/doc-outline.tsxindex 9335d6ba70..2d2757906d 100644--- a/packages/views/docs/components/doc-outline.tsx+++ b/packages/views/docs/components/doc-outline.tsx@@ -17,13 +17,15 @@ 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. */+/** Top-level H1–H3 of the rendered document, in order; empty headings skipped.+ * An editor still mounting behind `hidden` has no positions yet, so it is not read. */export function readOutline(root: ParentNode): OutlineHeading[] {return Array.from(root.querySelectorAll<HTMLElement>(".ProseMirror > h1, .ProseMirror > h2, .ProseMirror > h3",),)+ .filter((element) => !element.closest("[hidden]")).map((element) => ({level: Number(element.tagName.slice(1)),text: element.textContent?.trim() ?? "",@@ -46,11 +48,13 @@ function sameOutline(a: OutlineHeading[], b: OutlineHeading[]): boolean {/*** Headings of the editor under `rootRef`, kept current as the user types, and- * which one the scroll position of `scrollRef` is in.+ * which one the scroll position of `scrollRef` is in. A new `bodyKey` reads+ * them again at once, for a host that swaps what the root shows.*/export function useDocOutline(rootRef: RefObject<HTMLElement | null>,scrollRef: RefObject<HTMLElement | null>,+ bodyKey?: string | number,) {const [headings, setHeadings] = useState<OutlineHeading[]>([]);const [activeIndex, setActiveIndex] = useState(0);@@ -64,7 +68,7 @@ export function useDocOutline(const next = readOutline(root);setHeadings((prev) => (sameOutline(prev, next) ? prev : next));});- }, [rootRef]);+ }, [rootRef, bodyKey]);useEffect(() => {const scroller = scrollRef.current;@@ -80,7 +84,7 @@ export function useDocOutline(update();scroller.addEventListener("scroll", update, { passive: true });return () => scroller.removeEventListener("scroll", update);- }, [headings, scrollRef]);+ }, [headings, scrollRef, bodyKey]);const scrollTo = (heading: OutlineHeading) => {const scroller = scrollRef.current;diff --git a/packages/views/docs/components/doc-page.live-settle.test.tsx b/packages/views/docs/components/doc-page.live-settle.test.tsxnew file mode 100644index 0000000000..09ac0ad10a--- /dev/null+++ b/packages/views/docs/components/doc-page.live-settle.test.tsx@@ -0,0 +1,132 @@+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 { configStore } from "@multica/core/config";+import { docKeys, useDocDraftStore } from "@multica/core/docs";+import { DOCS_V1_FLAG } from "@multica/core/feature-flags";+import type { Doc } from "@multica/core/types";+import { DocPage } from "./doc-page";+import enDocs from "../../locales/en/docs.json";+import enEditor from "../../locales/en/editor.json";+import enIssues from "../../locales/en/issues.json";++// A doc opened from a hover has its live answer on hand, and its editor takes+// that answer as it starts. The page must not read that as "not known yet"+// on its next render and drop the editor for the skeleton.+const { apiMock, live } = vi.hoisted(() => ({+ apiMock: {+ getDoc: vi.fn(), updateDoc: vi.fn(), listDocTree: vi.fn(),+ listDocComments: vi.fn(), listMembers: vi.fn(), listAgents: vi.fn(),+ },+ live: { answer: undefined as unknown },+}));+vi.mock("@multica/core/api", () => ({ api: apiMock, ApiError: class extends Error {} }));+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}`,+ docHistory: (id: string) => `/review/docs/${id}/history`,+ }),+}));+vi.mock("@multica/core/workspace/hooks", () => ({+ useActorName: () => ({ getActorName: () => "Reviewer" }),+}));+vi.mock("../../navigation", () => ({+ useNavigation: () => ({ pathname: "/review/docs/runbook", push: vi.fn(), getShareableUrl: (path: string) => path, searchParams: new URLSearchParams() }),+ AppLink: ({ children, href, className }: { children: React.ReactNode; href: string; className?: string }) => (+ <a href={href} className={className}>{children}</a>+ ),+}));+vi.mock("../../editor", () => ({+ ContentEditor: ({ value, onUpdate }: { value: string; onUpdate: (value: string) => void }) => (+ <textarea aria-label="Body" value={value} onChange={(event) => onUpdate(event.target.value)} />+ ),+ ReadonlyContent: ({ content }: { content: string }) => <div>{content}</div>,+ useEditorUpload: () => ({ uploadWithToast: vi.fn() }),+}));+// The editor's session takes the prefetched answer; the page then edits solo+// (as after a connect timeout), which renders the plain body.+vi.mock("./use-doc-collab", () => ({+ useDocCollab: () => {+ live.answer = undefined;+ return { mode: "solo" };+ },+}));+vi.mock("@multica/core/realtime", () => ({ useWS: () => ({ collabUrl: "ws://collab.test/collab" }) }));+vi.mock("./doc-live-session", () => ({+ liveEditingOff: new Set(),+ peekDocLive: () => live.answer,+ findDocSession: () => undefined,+ prefetchDocLive: () => new Promise(() => {}),+}));+vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));+vi.mock("../../layout/breadcrumb-header", () => ({+ BreadcrumbHeader: ({ actions }: { actions?: React.ReactNode }) => <header>{actions}</header>,+}));++const doc: Doc = {+ id: "runbook",+ workspaceId: "review-ws",+ folderId: null,+ title: "Release runbook",+ content: "Steps",+ revision: 1,+ versionCount: 1,+ createdByType: "member",+ createdById: "reviewer",+ updatedByType: "member",+ updatedById: "reviewer",+ createdAt: "2026-11-18T00:00:00Z",+ updatedAt: "2026-11-18T00:00:00Z",+};+let qc: QueryClient;+beforeEach(() => {+ vi.clearAllMocks();+ configStore.getState().setFeatureFlags({ [DOCS_V1_FLAG]: true });+ useDocDraftStore.getState().clearDraft();+ qc = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });+ live.answer = { enabled: true, token: "t", document: "doc:runbook", expiresAt: "" };+ apiMock.getDoc.mockResolvedValue(doc);+ apiMock.listDocTree.mockResolvedValue({ folders: [], docs: [doc] });+ apiMock.listDocComments.mockResolvedValue([]);+ apiMock.listMembers.mockResolvedValue([]);+ apiMock.listAgents.mockResolvedValue([]);+});+afterEach(() => { cleanup(); qc.clear(); });++function mount() {+ return render(<QueryClientProvider client={qc}><I18nProvider locale="en" resources={{ en: { docs: enDocs, editor: enEditor, issues: enIssues } }}><DocPage docId="runbook" /></I18nProvider></QueryClientProvider>);+}++it("keeps the editor through a refetch after its session took the prefetched answer", async () => {+ mount();+ const body = await screen.findByLabelText("Body");+ // Someone else's edit: the realtime event refetches the doc.+ apiMock.getDoc.mockResolvedValue({ ...doc, revision: 2, updatedAt: "2026-11-18T01:00:00Z" });+ await act(async () => { await qc.invalidateQueries({ queryKey: docKeys.all("review-ws") }); });+ expect(screen.getByLabelText("Body")).toBe(body);+});++it("keeps the editor when a save updates the doc", async () => {+ apiMock.updateDoc.mockImplementation(async (_id: string, { content }: { content?: string }) => {+ const saved = { ...doc, content: content ?? doc.content, revision: 2 };+ apiMock.getDoc.mockResolvedValue(saved);+ return saved;+ });+ mount();+ const body = await screen.findByLabelText("Body");+ fireEvent.change(body, { target: { value: "Steps, edited" } });+ await waitFor(() => expect(apiMock.updateDoc).toHaveBeenCalled(), { timeout: 4000 });+ await waitFor(() => expect(qc.getQueryData<Doc>(docKeys.detail("review-ws", "runbook"))?.revision).toBe(2));+ expect(screen.getByLabelText("Body")).toBe(body);+});diff --git a/packages/views/docs/components/doc-page.tsx b/packages/views/docs/components/doc-page.tsxindex 0c55ca6e8c..c9c65faf1a 100644--- a/packages/views/docs/components/doc-page.tsx+++ b/packages/views/docs/components/doc-page.tsx@@ -35,7 +35,9 @@ import {holdLiveDoc,isDocNotFound,} from "@multica/core/docs";+import { useAuthStore } from "@multica/core/auth";import { useWorkspaceId } from "@multica/core/hooks";+import { useWS } from "@multica/core/realtime";import { useWorkspacePaths } from "@multica/core/paths";import { useActorName } from "@multica/core/workspace/hooks";import type { Doc } from "@multica/core/types";@@ -46,6 +48,7 @@ import { AppLink, useNavigation } from "../../navigation";import { useT, useTimeAgo } from "../../i18n";import { useDocDraft } from "./use-doc-draft";import { useDocCollab, type DocCollaborator } from "./use-doc-collab";+import { findDocSession, liveEditingOff, peekDocLive, prefetchDocLive } from "./doc-live-session";import { useLiveDocTitle } from "./use-live-doc-title";import { DocOutline, MIN_OUTLINE_HEADINGS, useDocOutline } from "./doc-outline";import { DocCommentsPanel, groupDocThreads } from "./doc-comments-panel";@@ -65,13 +68,52 @@ export function DocPage({ docId }: { docId: string }) {);}+/** How long the page waits for the doc's live session info before showing+ * the doc without it. The two requests leave together, so this is rarely+ * reached. */+const LIVE_INFO_WAIT_MS = 1000;++/**+ * Whether the page knows how the doc opens: solo, or live with the saved+ * state to show at once. Waiting for that briefly lets the doc appear in its+ * editor in one paint instead of as a static copy swapped out later. Once+ * settled it stays so for the doc: the editor consumes what settled it, and+ * falling back to the skeleton would unmount the editor.+ */+function useLiveInfoSettled(docId: string): boolean {+ const { collabUrl } = useWS();+ const userId = useAuthStore((s) => s.user?.id ?? "");+ const [settledDoc, setSettledDoc] = useState<string | null>(null);+ const settled =+ settledDoc === docId ||+ liveEditingOff.has(collabUrl) ||+ peekDocLive(collabUrl, docId, userId) !== undefined ||+ !!findDocSession(collabUrl, docId, userId)?.getState().ready;+ if (settled && settledDoc !== docId) setSettledDoc(docId);+ useEffect(() => {+ if (settled) return;+ let cancelled = false;+ const done = () => {+ if (!cancelled) setSettledDoc(docId);+ };+ prefetchDocLive(collabUrl, docId, userId).then(done, done);+ const wait = setTimeout(done, LIVE_INFO_WAIT_MS);+ return () => {+ cancelled = true;+ clearTimeout(wait);+ };+ }, [settled, collabUrl, docId, userId]);+ return settled;+}+function DocPageContent({ docId }: { docId: string }) {const wsId = useWorkspaceId();const { t } = useT("docs");const query = useQuery(docDetailOptions(wsId, docId));+ const liveSettled = useLiveInfoSettled(docId);// Also when it was open: a refetch answered 404 once someone deleted it.if (isDocNotFound(query.error)) return <DocNotFound docId={docId} />;- if (!query.data)+ if (!query.data || !liveSettled)return (<DocPageSkeleton docId={docId}>{query.isError ? (@@ -158,15 +200,22 @@ function DocEditor({ doc }: { doc: Doc }) {// itself; only the title goes through the API. Until the page knows which// mode it is in, nothing is saved: the body is shown read-only and a typed// title is held.- const collab = useDocCollab(doc.id);+ const collab = useDocCollab(doc.id, doc.content);const live = collab.mode === "live" ? collab : null;const solo = collab.mode === "solo";const { draft, status, dirty, change, retry, reload, setAside } = useDocDraft(doc, solo);const liveTitle = useLiveDocTitle(doc, !!live);+ // The live editor appears once its Tiptap instance exists; until then the+ // static copy stands in, so the body never goes blank.+ const [editorReadyFor, setEditorReadyFor] = useState<number | null>(null);+ const showLiveEditor = !!live?.ready && editorReadyFor === live.generation;useEffect(() => {if (solo) {const title = liveTitle.take();- if (title !== null) change({ title });+ const content = collab.carried ?? null;+ if (title !== null || content !== null) {+ change({ ...(title !== null ? { title } : {}), ...(content !== null ? { content } : {}) });+ }} else if (live) {setAside();}@@ -190,7 +239,9 @@ function DocEditor({ doc }: { doc: Doc }) {const uploadFile = useCallback((file: File) => uploadWithToast(file), [uploadWithToast]);const scrollRef = useRef<HTMLDivElement>(null);const bodyRef = useRef<HTMLDivElement>(null);- const outline = useDocOutline(bodyRef, scrollRef);+ // Changes when the body switches between the static copy and an editor.+ const bodyKey = solo ? "solo" : showLiveEditor ? live!.generation : "static";+ const outline = useDocOutline(bodyRef, scrollRef, bodyKey);const showOutline = outline.headings.length >= MIN_OUTLINE_HEADINGS;// Discussions. A link from the inbox names one with ?thread=.@@ -218,7 +269,7 @@ function DocEditor({ doc }: { doc: Doc }) {})),[threads, activeThread],);- const highlights = useDocCommentHighlights(bodyRef, anchored, activeThread);+ const highlights = useDocCommentHighlights(bodyRef, anchored, activeThread, bodyKey);const activateThread = (id: string) => {setActiveThread(id);setCommentsOpen(true);@@ -268,6 +319,7 @@ function DocEditor({ doc }: { doc: Doc }) {<LiveStatusconnected={live.connected}synced={live.synced}+ slow={live.slow}collaborators={live.collaborators}titleFailed={liveTitle.failed}onRetryTitle={liveTitle.retry}@@ -416,20 +468,26 @@ function DocEditor({ doc }: { doc: Doc }) {</Tooltip></div><div ref={bodyRef} onClick={onBodyClick}>- {collab.mode === "checking" || (live && !live.synced) ? (- <ReadonlyContent content={doc.content} className="min-h-80" />- ) : live ? (- <ContentEditor- key={live.generation}- collaboration={live.collaboration}- selectionAction={commentAction}- placeholder={t(($) => $.editor.placeholder)}- enableSlashCommands- slashCommandMode="blocks"- showBlockHandles- onUploadFile={uploadFile}- className="min-h-80"- />+ {!solo ? (+ <>+ {!showLiveEditor && <ReadonlyContent content={doc.content} className="min-h-80" />}+ {live?.ready && (+ <div hidden={!showLiveEditor}>+ <ContentEditor+ key={live.generation}+ collaboration={live.collaboration}+ onReady={() => setEditorReadyFor(live.generation)}+ selectionAction={commentAction}+ placeholder={t(($) => $.editor.placeholder)}+ enableSlashCommands+ slashCommandMode="blocks"+ showBlockHandles+ onUploadFile={uploadFile}+ className="min-h-80"+ />+ </div>+ )}+ </>) : (<ContentEditorselectionAction={commentAction}@@ -495,12 +553,14 @@ function DocEditor({ doc }: { doc: Doc }) {function LiveStatus({connected,synced,+ slow,collaborators,titleFailed,onRetryTitle,}: {connected: boolean;synced: boolean;+ slow: boolean;collaborators: DocCollaborator[];titleFailed: boolean;onRetryTitle: () => void;@@ -557,9 +617,11 @@ function LiveStatus({<span aria-hidden className="size-1.5 rounded-full bg-success" />{t(($) => $.editor.live)}</span>- ) : (- t(($) => (synced ? $.editor.reconnecting : $.editor.connecting))- )}+ ) : synced ? (+ t(($) => $.editor.reconnecting)+ ) : slow ? (+ t(($) => $.editor.connecting)+ ) : null}</span>);}diff --git a/packages/views/docs/components/doc-tree.delete.test.tsx b/packages/views/docs/components/doc-tree.delete.test.tsxindex fcc9258972..4164306c31 100644--- a/packages/views/docs/components/doc-tree.delete.test.tsx+++ b/packages/views/docs/components/doc-tree.delete.test.tsx@@ -26,6 +26,7 @@ vi.mock("../../navigation", () => ({useNavigation: () => ({ pathname: "/docs", push: vi.fn() }),AppLink: ({ children, href }: { children: React.ReactNode; href: string }) => <a href={href}>{children}</a>,}));+vi.mock("./use-prefetch-doc", () => ({ usePrefetchDoc: () => () => ({}), useWarmDocPage: () => undefined }));const tree = {folders: [],diff --git a/packages/views/docs/components/doc-tree.dnd.test.tsx b/packages/views/docs/components/doc-tree.dnd.test.tsxindex 7fa4f5cc6e..21f1102c5c 100644--- a/packages/views/docs/components/doc-tree.dnd.test.tsx+++ b/packages/views/docs/components/doc-tree.dnd.test.tsx@@ -34,6 +34,7 @@ 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("./use-prefetch-doc", () => ({ usePrefetchDoc: () => () => ({}), useWarmDocPage: () => undefined }));vi.mock("@multica/core/issue-statuses/hooks", () => ({useIssueStatuses: () => ({ iconOf: () => null, colorOf: () => null }),}));diff --git a/packages/views/docs/components/doc-tree.tsx b/packages/views/docs/components/doc-tree.tsxindex 013f6eb0ec..069b7da3e1 100644--- a/packages/views/docs/components/doc-tree.tsx+++ b/packages/views/docs/components/doc-tree.tsx@@ -54,6 +54,7 @@ import { AppLink, useNavigation } from "../../navigation";import { useT } from "../../i18n";import { MoveDialog, type MoveTarget } from "./move-dialog";import { useCanDeleteDoc } from "./use-can-delete-doc";+import { usePrefetchDoc, useWarmDocPage } from "./use-prefetch-doc";type Item =| { kind: "doc"; item: DocSummary }@@ -168,6 +169,8 @@ export function DocTree() {const wsId = useWorkspaceId();const { pathname, push } = useNavigation();const tree = useQuery(docTreeOptions(wsId));+ const prefetchDoc = usePrefetchDoc();+ useWarmDocPage(tree.data?.docs[0]?.id);const createDoc = useCreateDoc();const createFolder = useCreateDocFolder();const renameFolder = useRenameDocFolder();@@ -404,6 +407,7 @@ export function DocTree() {<FileText className="size-4 shrink-0 text-muted-foreground" /><AppLinkhref={p.docDetail(doc.id)}+ {...prefetchDoc(doc.id)}className="min-w-0 flex-1 truncate">{doc.title || t(($) => $.untitled)}diff --git a/packages/views/docs/components/docs-home-page.tsx b/packages/views/docs/components/docs-home-page.tsxindex 2a41b021ee..fd258afe36 100644--- a/packages/views/docs/components/docs-home-page.tsx+++ b/packages/views/docs/components/docs-home-page.tsx@@ -9,6 +9,7 @@ import { PageHeader } from "../../layout/page-header";import { AppLink } from "../../navigation";import { useT } from "../../i18n";import { DocsGate } from "./docs-gate";+import { usePrefetchDoc, useWarmDocPage } from "./use-prefetch-doc";export function DocsHomePage({folderId = null,}: {@@ -26,9 +27,11 @@ function DocsHomePageContent({ folderId }: { folderId: string | null }) {const wsId = useWorkspaceId();const p = useWorkspacePaths();const tree = useQuery(docTreeOptions(wsId));+ const prefetchDoc = usePrefetchDoc();const folders =tree.data?.folders.filter((f) => f.parentId === folderId) ?? [];const docs = tree.data?.docs.filter((d) => d.folderId === folderId) ?? [];+ useWarmDocPage(docs[0]?.id ?? tree.data?.docs[0]?.id);return (<div className="flex h-full min-h-0 flex-col"><PageHeader>@@ -67,6 +70,7 @@ function DocsHomePageContent({ folderId }: { folderId: string | null }) {<li key={d.id}><AppLinkhref={p.docDetail(d.id)}+ {...prefetchDoc(d.id)}className="flex items-center gap-3 rounded-md p-3 text-body hover:bg-surface-hover"><FileText className="size-4" />diff --git a/packages/views/docs/components/dom-throttle.ts b/packages/views/docs/components/dom-throttle.tsindex ee8b95c6ac..62a1ed71a0 100644--- a/packages/views/docs/components/dom-throttle.ts+++ b/packages/views/docs/components/dom-throttle.ts@@ -2,18 +2,30 @@* Runs `fn` once now and then at most once per `intervalMs` while `target`'s* subtree keeps changing. A live doc changes on every keystroke and caret* move of every collaborator, so per-frame work would run sixty times a- * second; the last change is always picked up within `intervalMs`.+ * second; the last change is always picked up within `intervalMs`. A change+ * after a quiet spell runs `fn` at once, before the next paint, so content+ * that just appeared (the editor mounting) is never shown without it.*/export function watchDom(target: Node, fn: () => void, intervalMs = 200): () => void {let timer: ReturnType<typeof setTimeout> | null = null;+ let lastRun = 0;+ const run = () => {+ lastRun = performance.now();+ fn();+ };const schedule = () => {if (timer) return;+ const wait = intervalMs - (performance.now() - lastRun);+ if (wait <= 0) {+ run();+ return;+ }timer = setTimeout(() => {timer = null;- fn();- }, intervalMs);+ run();+ }, wait);};- fn();+ run();const observer = new MutationObserver(schedule);observer.observe(target, { childList: true, subtree: true, characterData: true });return () => {diff --git a/packages/views/docs/components/use-doc-collab.ts b/packages/views/docs/components/use-doc-collab.tsindex d82fd447fd..eb4e102faf 100644--- a/packages/views/docs/components/use-doc-collab.ts+++ b/packages/views/docs/components/use-doc-collab.ts@@ -1,84 +1,99 @@"use client";-import { useEffect, useMemo, useState } from "react";-import * as Y from "yjs";-import { HocuspocusProvider } from "@hocuspocus/provider";-import { api } from "@multica/core/api";+import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";import { useAuthStore } from "@multica/core/auth";+import { configStore } from "@multica/core/config";import { useWS } from "@multica/core/realtime";import type { EditorCollaboration } from "../../editor/extensions";+import { createDocumentCodec } from "../../editor/schema/codec";+import {+ acquireDocSession,+ colorFor,+ findDocSession,+ liveEditingOff,+ peekDocLive,+ prefetchDocLive,+ releaseDocSession,+ type DocCollaborator,+ type DocSession,+ type DocSessionState,+} from "./doc-live-session";++export type { DocCollaborator };/** How long a first connection may take before the page edits without the* live session. Saves then go through the API, which merges them in. */const CONNECT_TIMEOUT_MS = 8000;--/** Servers that answered that live editing is off. That is server- * configuration, so later docs open for solo editing without asking again. */-const liveEditingOff = new Set<string>();--const COLORS = ["#2563eb", "#db2777", "#059669", "#d97706", "#7c3aed", "#0891b2", "#dc2626", "#4f46e5"];--function colorFor(id: string): string {- let hash = 0;- for (const char of id) hash = (hash * 31 + char.charCodeAt(0)) | 0;- return COLORS[Math.abs(hash) % COLORS.length]!;-}--/** Someone else in the session: a person, or an agent writing through the API. */-export interface DocCollaborator {- key: number;- id: string;- name: string;- color: string;- kind: "member" | "agent";-}+/** A first connection quicker than this is not announced. */+const CONNECTING_NOTICE_MS = 3000;export type DocCollabState =/** Asking the server whether live editing is on. */| { mode: "checking" }- /** Live editing is off or unreachable: edit through the API. */- | { mode: "solo" }+ /** Live editing is off or unreachable: edit through the API. `carried` is+ * what was typed into the live session before it gave up, to save. */+ | { mode: "solo"; carried?: string | null }| {mode: "live";- /** False until the first sync; the editor waits for it. */+ /** The shared document holds the doc; the editor can show it. */+ ready: boolean;+ /** The first sync is done. */synced: boolean;connected: boolean;+ /** Still connecting for the first time after a noticeable while. */+ slow: boolean;collaboration: EditorCollaboration;collaborators: DocCollaborator[];/** Changes the editor's key when the session starts over. */generation: number;};-interface Session {- ydoc: Y.Doc;- provider: HocuspocusProvider;- generation: number;+const IDLE_STATE: DocSessionState = { ready: false, synced: false, connected: false, collaborators: [], reset: false };+const noSubscribe = () => () => {};+const idleState = () => IDLE_STATE;++/** The doc as typed into the session, when that differs from `base`. */+function editedContent(session: DocSession, base: string): string | null {+ if (!session.edited) return null;+ try {+ const codec = createDocumentCodec({ cdnDomain: configStore.getState().cdnDomain });+ const typed = codec.ydocToMarkdown(session.ydoc);+ return typed === codec.serialize(codec.parse(base)) ? null : typed;+ } catch {+ return null;+ }}-export function useDocCollab(docId: string): DocCollabState {+export function useDocCollab(docId: string, content: string): DocCollabState {const { collabUrl } = useWS();const user = useAuthStore((s) => s.user);- const [mode, setMode] = useState<"checking" | "solo" | "live">(() =>- liveEditingOff.has(collabUrl) ? "solo" : "checking",- );- const [document, setDocument] = useState<string | null>(null);+ const userId = user?.id ?? "";+ // A kept session or an answer fetched ahead of the page settles the mode+ // without waiting.+ const [initial] = useState(() => {+ if (liveEditingOff.has(collabUrl)) return { mode: "solo" as const, document: null };+ const document =+ findDocSession(collabUrl, docId, userId)?.document ??+ (() => {+ const ticket = peekDocLive(collabUrl, docId, userId);+ return ticket?.enabled ? ticket.document : null;+ })();+ return document ? { mode: "live" as const, document } : { mode: "checking" as const, document: null };+ });+ const [mode, setMode] = useState<"checking" | "solo" | "live">(initial.mode);+ const [document, setDocument] = useState<string | null>(initial.document);+ const [carried, setCarried] = useState<string | null>(null);const [generation, setGeneration] = useState(0);- const [session, setSession] = useState<Session | null>(null);- const [synced, setSynced] = useState(false);- const [connected, setConnected] = useState(false);- const [collaborators, setCollaborators] = useState<DocCollaborator[]>([]);+ const [session, setSession] = useState<DocSession | null>(null);+ const [slow, setSlow] = useState(false);+ const discard = useRef(false);+ const contentRef = useRef(content);+ contentRef.current = content;useEffect(() => {- if (liveEditingOff.has(collabUrl)) {- setMode("solo");- return;- }+ if (mode !== "checking") return;let cancelled = false;- setMode("checking");- api- .createDocCollabTicket(docId)+ prefetchDocLive(collabUrl, docId, userId).then((ticket) => {- if (ticket.enabled) liveEditingOff.delete(collabUrl);- else liveEditingOff.add(collabUrl);if (cancelled) return;setDocument(ticket.enabled ? ticket.document : null);setMode(ticket.enabled ? "live" : "solo");@@ -89,70 +104,39 @@ export function useDocCollab(docId: string): DocCollabState {return () => {cancelled = true;};- }, [docId, collabUrl]);+ }, [mode, docId, collabUrl, userId]);useEffect(() => {- if (mode !== "live" || !document) return;- const ydoc = new Y.Doc();- let everSynced = false;- const provider = new HocuspocusProvider({- url: collabUrl,- name: document,- document: ydoc,- // Asked on every (re)connect. The epoch names the copy this tab holds,- // so the server can tell it to start over if the doc was rebuilt.- token: async () => {- const ticket = await api.createDocCollabTicket(docId);- if (!ticket.enabled) throw new Error("live editing is off");- const epoch = ydoc.getMap("meta").get("epoch");- return JSON.stringify({ ticket: ticket.token, epoch: typeof epoch === "string" ? epoch : undefined });- },- onSynced: ({ state }) => {- if (!state) return;- everSynced = true;- setSynced(true);- },- onStatus: ({ status }) => setConnected(status === "connected"),- onClose: ({ event }) => {- if (event.reason === "document-reset") setGeneration((g) => g + 1);- },- });- // Awareness changes on every caret move of every editor; only re-render- // when who is here changes.- let signature = "";- const updateCollaborators = () => {- const seen = new Set<string>();- const next: DocCollaborator[] = [];- for (const [key, state] of provider.awareness?.getStates() ?? []) {- if (key === ydoc.clientID) continue;- const u = (state as { user?: Partial<DocCollaborator> }).user;- if (!u?.name || !u.id) continue;- const dedupe = `${u.kind}:${u.id}`;- if (seen.has(dedupe)) continue;- seen.add(dedupe);- next.push({ key, id: u.id, name: u.name, color: u.color ?? colorFor(u.id), kind: u.kind === "agent" ? "agent" : "member" });- }- const nextSignature = next.map((c) => `${c.key}:${c.kind}:${c.id}:${c.name}:${c.color}`).join("|");- if (nextSignature === signature) return;- signature = nextSignature;- setCollaborators(next);+ if (mode !== "live" || !document || !userId) return;+ const next = acquireDocSession(collabUrl, docId, userId, document);+ discard.current = false;+ setSession(next);+ return () => {+ releaseDocSession(next, { discard: discard.current });+ setSession(null);};- provider.awareness?.on("change", updateCollaborators);- const timeout = setTimeout(() => {- if (!everSynced) setMode("solo");+ }, [mode, document, docId, collabUrl, userId, generation]);++ const state = useSyncExternalStore(session?.subscribe ?? noSubscribe, session?.getState ?? idleState);++ useEffect(() => {+ if (state.reset) setGeneration((g) => g + 1);+ }, [state.reset]);++ useEffect(() => {+ setSlow(false);+ if (!session || state.synced) return;+ const notice = setTimeout(() => setSlow(true), CONNECTING_NOTICE_MS);+ const giveUp = setTimeout(() => {+ setCarried(editedContent(session, contentRef.current));+ discard.current = true;+ setMode("solo");}, CONNECT_TIMEOUT_MS);- setSession({ ydoc, provider, generation });return () => {- clearTimeout(timeout);- provider.awareness?.off("change", updateCollaborators);- provider.destroy();- ydoc.destroy();- setSession(null);- setSynced(false);- setConnected(false);- setCollaborators([]);+ clearTimeout(notice);+ clearTimeout(giveUp);};- }, [mode, document, docId, collabUrl, generation]);+ }, [session, state.synced]);const collaboration = useMemo<EditorCollaboration | null>(() => {if (!session || !user) return null;@@ -163,9 +147,17 @@ export function useDocCollab(docId: string): DocCollabState {};}, [session, user]);- if (mode === "checking") return { mode };- if (mode === "solo" || !collaboration || !session) {- return mode === "solo" ? { mode } : { mode: "checking" };- }- return { mode: "live", synced, connected, collaboration, collaborators, generation: session.generation };+ if (mode === "solo") return { mode, carried };+ // A reset session is about to be replaced; nothing may keep editing it.+ if (mode === "checking" || !collaboration || !session || state.reset) return { mode: "checking" };+ return {+ mode: "live",+ ready: state.ready,+ synced: state.synced,+ connected: state.connected,+ slow,+ collaboration,+ collaborators: state.collaborators,+ generation: session.id,+ };}diff --git a/packages/views/docs/components/use-doc-comment-highlights.ts b/packages/views/docs/components/use-doc-comment-highlights.tsindex 1baffd9886..50be58e6cf 100644--- a/packages/views/docs/components/use-doc-comment-highlights.ts+++ b/packages/views/docs/components/use-doc-comment-highlights.ts@@ -20,12 +20,14 @@ function canHighlight() {* Paints each open discussion's quoted text in the doc and keeps the ranges* current while the doc is edited. Returns which discussions could not be* found (their text was edited away) and a lookup from a DOM point to the- * discussion it sits in, for clicking a highlight.+ * discussion it sits in, for clicking a highlight. A new `bodyKey` paints+ * again at once, for a host that swaps what the root shows.*/export function useDocCommentHighlights(rootRef: RefObject<HTMLElement | null>,threads: AnchoredThread[],activeId: string | null,+ bodyKey?: string | number,) {const rangesRef = useRef(new Map<string, Range>());const [missing, setMissing] = useState<ReadonlySet<string>>(new Set());@@ -66,7 +68,7 @@ export function useDocCommentHighlights(CSS.highlights.delete(ACTIVE_HIGHLIGHT);}};- }, [rootRef, threadsKey, activeId]);+ }, [rootRef, threadsKey, activeId, bodyKey]);/** The discussion whose quoted text contains this point, if any. */const threadAt = (node: Node, offset: number): string | null => {diff --git a/packages/views/docs/components/use-prefetch-doc.ts b/packages/views/docs/components/use-prefetch-doc.tsnew file mode 100644index 0000000000..1917c27428--- /dev/null+++ b/packages/views/docs/components/use-prefetch-doc.ts@@ -0,0 +1,83 @@+"use client";+import { useCallback, useEffect, useRef } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { docCommentsOptions, docDetailOptions } from "@multica/core/docs";+import { useAuthStore } from "@multica/core/auth";+import { useWorkspaceId } from "@multica/core/hooks";+import { useWorkspacePaths } from "@multica/core/paths";+import { useWS } from "@multica/core/realtime";+import { useNavigation } from "../../navigation";+import { findDocSession, liveEditingOff, prefetchDocLive } from "./doc-live-session";++/** A pointer passing over a list is not heading for every row in it. */+const HOVER_INTENT_MS = 80;++let docPageWarmed = false;++/**+ * Prefetches one doc's route once per session when the browser is idle. On+ * web the doc page's code is shared by every doc but only requested after a+ * doc's route payload arrives, which put a whole round trip in front of the+ * first doc opened; warming it here leaves each open with just its payload.+ * Desktop bundles its routes and has no route prefetch, so this is a no-op.+ */+export function useWarmDocPage(docId: string | undefined) {+ const { prefetch } = useNavigation();+ const p = useWorkspacePaths();+ const href = docId ? p.docDetail(docId) : null;+ useEffect(() => {+ if (!href || !prefetch || docPageWarmed) return;+ const warm = () => {+ docPageWarmed = true;+ prefetch(href);+ };+ if (typeof window.requestIdleCallback === "function") {+ const id = window.requestIdleCallback(warm, { timeout: 3000 });+ return () => window.cancelIdleCallback(id);+ }+ const timer = window.setTimeout(warm, 1500);+ return () => window.clearTimeout(timer);+ }, [href, prefetch]);+}++/**+ * Hover and focus handlers for a link to a doc: they fetch what the doc page+ * opens with (the doc, its discussions, its live session's ticket and saved+ * state), so the page usually paints in full on the click.+ */+export function usePrefetchDoc() {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();+ const { collabUrl } = useWS();+ const userId = useAuthStore((s) => s.user?.id ?? "");+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);+ useEffect(() => () => {+ if (timer.current) clearTimeout(timer.current);+ }, []);++ const prefetch = useCallback(+ (docId: string) => {+ void qc.prefetchQuery(docDetailOptions(wsId, docId));+ void qc.prefetchQuery(docCommentsOptions(wsId, docId));+ // An open or kept session already holds the doc and is kept current.+ if (liveEditingOff.has(collabUrl) || findDocSession(collabUrl, docId, userId)) return;+ prefetchDocLive(collabUrl, docId, userId).catch(() => undefined);+ },+ [qc, wsId, collabUrl, userId],+ );++ return useCallback(+ (docId: string) => ({+ onMouseEnter: () => {+ if (timer.current) clearTimeout(timer.current);+ timer.current = setTimeout(() => prefetch(docId), HOVER_INTENT_MS);+ },+ onMouseLeave: () => {+ if (timer.current) clearTimeout(timer.current);+ timer.current = null;+ },+ onFocus: () => prefetch(docId),+ }),+ [prefetch],+ );+}diff --git a/server/internal/handler/doc_collab.go b/server/internal/handler/doc_collab.goindex 5243042990..616e91e784 100644--- a/server/internal/handler/doc_collab.go+++ b/server/internal/handler/doc_collab.go@@ -161,13 +161,26 @@ func (h *Handler) flushDocCollab(ctx context.Context, docID pgtype.UUID) {}}+type DocCollabTicketRequest struct {+ // State asks for the Yjs state saved with the doc, so the editor can+ // show the doc before its live session has synced.+ State bool `json:"state"`+}+type DocCollabTicketResponse struct {Enabled bool `json:"enabled"`Token string `json:"token,omitempty"`Document string `json:"document,omitempty"`ExpiresAt string `json:"expires_at,omitempty"`+ // State is the base64 Yjs state saved with the doc's current revision.+ // Omitted when there is none the live session would load as it is.+ State string `json:"state,omitempty"`}+// docCollabStateMaxBytes caps the state sent to an editor; a larger doc+// waits for its live session instead.+const docCollabStateMaxBytes = 2 << 20+// CreateDocCollabTicket lets an editor join a doc's live session. Editors ask// again on every reconnect, so tickets are short-lived.func (h *Handler) CreateDocCollabTicket(w http.ResponseWriter, r *http.Request) {@@ -183,6 +196,11 @@ func (h *Handler) CreateDocCollabTicket(w http.ResponseWriter, r *http.Request)writeJSON(w, http.StatusOK, DocCollabTicketResponse{Enabled: false})return}+ // The body is optional: older clients send none.+ var req DocCollabTicketRequest+ if r.Body != nil {+ _ = json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<10)).Decode(&req)+ }actorType, actorID := h.resolveActor(r, userID, workspaceID)expires := time.Now().Add(docCollabTicketTTL)document := collab.DocumentName(uuidToString(doc.ID))@@ -192,9 +210,33 @@ func (h *Handler) CreateDocCollabTicket(w http.ResponseWriter, r *http.Request)Actor: h.collabActor(r.Context(), actorType, actorID),ExpiresAt: expires,})- writeJSON(w, http.StatusOK, DocCollabTicketResponse{+ resp := DocCollabTicketResponse{Enabled: true, Token: token, Document: document, ExpiresAt: expires.UTC().Format(time.RFC3339),- })+ }+ if req.State {+ resp.State = h.docCollabState(r.Context(), doc)+ }+ writeJSON(w, http.StatusOK, resp)+}++// docCollabState returns the saved Yjs state when the collaboration service+// would load it unchanged: saved with the current revision, and not so far+// past its Markdown that the service rebuilds it (COMPACT_STATE_* in+// apps/collab). Any other state would be replaced on load and reset the+// editor that showed it.+func (h *Handler) docCollabState(ctx context.Context, doc db.Doc) string {+ row, err := h.Queries.GetDocForCollab(ctx, doc.ID)+ if err != nil || row.WorkspaceID != doc.WorkspaceID || row.Ystate == nil || !row.YstateRevision.Valid {+ return ""+ }+ size := len(row.Ystate)+ if row.YstateRevision.Int64 != row.Revision || size > docCollabStateMaxBytes {+ return ""+ }+ if size > 1<<20 && size > 4*len(row.Content) {+ return ""+ }+ return base64.StdEncoding.EncodeToString(row.Ystate)}type DocWriteResponse struct {diff --git a/server/internal/handler/doc_collab_test.go b/server/internal/handler/doc_collab_test.goindex 82d11f43a6..6534fef8ff 100644--- a/server/internal/handler/doc_collab_test.go+++ b/server/internal/handler/doc_collab_test.go@@ -153,6 +153,44 @@ func TestUpdateDocGoesThroughCollabWithItsMergeBase(t *testing.T) {testutil.Call(t, testHandler.UpdateDoc, withURLParam(newRequest("PATCH", "/api/docs/"+doc.ID, map[string]any{"base_revision": 9, "content": "x"}), "id", doc.ID)).Want(http.StatusConflict)}+func TestCollabTicketCarriesTheStateSavedWithTheCurrentRevision(t *testing.T) {+ doc := createDocForTest(t)+ service := httptest.NewServer(http.NotFoundHandler())+ url := service.URL+ service.Close()+ useCollab(t, url)++ ticket := func(body any) DocCollabTicketResponse {+ t.Helper()+ var resp DocCollabTicketResponse+ testutil.Call(t, testHandler.CreateDocCollabTicket, withURLParam(newRequest("POST", "/api/docs/"+doc.ID+"/collab-ticket", body), "id", doc.ID)).Want(http.StatusOK).JSON(&resp)+ if !resp.Enabled || resp.Token == "" || resp.Document != "doc:"+doc.ID {+ t.Fatalf("ticket must be issued: %+v", resp)+ }+ return resp+ }+ if got := ticket(map[string]any{"state": true}); got.State != "" {+ t.Fatalf("a doc never opened live has no state: %+v", got)+ }++ state := base64.StdEncoding.EncodeToString([]byte{7, 8, 9})+ testutil.Call(t, testHandler.StoreCollabDoc, withURLParam(newRequest("POST", "/internal/collab/docs/"+doc.ID+"/store", map[string]any{+ "base_revision": 1, "content": doc.Content, "ystate": state, "contributors": []DocContributor{}, "state_only": true,+ }), "id", doc.ID)).Want(http.StatusOK)+ if got := ticket(map[string]any{"state": true}); got.State != state {+ t.Fatalf("state saved with the current revision must come back: %+v", got)+ }+ if got := ticket(nil); got.State != "" {+ t.Fatalf("state is sent only when asked for: %+v", got)+ }++ // Written without the live session: the saved state is behind the doc.+ testutil.Call(t, testHandler.UpdateDoc, withURLParam(newRequest("PATCH", "/api/docs/"+doc.ID, map[string]any{"base_revision": 1, "content": "Direct"}), "id", doc.ID)).Want(http.StatusOK)+ if got := ticket(map[string]any{"state": true}); got.State != "" {+ t.Fatalf("a state behind the doc must not be sent: %+v", got)+ }+}+func TestDocWritesFallBackWhenCollabIsDown(t *testing.T) {doc := createDocForTest(t)service := httptest.NewServer(http.NotFoundHandler())