From 51907b1a84cfa98f88f6f8c761f2152c934ca9d0 Mon Sep 17 00:00:00 2001 From: Harvey Date: Tue, 17 Nov 2026 12:19:16 +0330 Subject: [PATCH 1/7] feat(editor): add the WriteGate and decoration-host extensions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit WriteGate filters every local transaction that changes the document while canWrite() is false, appended ones included, so read-only never makes a Yjs update that would later have to be dropped (details spec §1 rules 1-2). Changes from Yjs and meta-only transactions pass. The decoration host generalises the action-preview stub (rule 6): each declared layer is one plugin holding a DecorationSet, set by the meta-only setDecorationLayer command and mapped or cleared on document changes, so comments and Find add no eager plugin of their own. --- extensions/decoration-host/decoration-host.ts | 81 +++++++++++++++++ extensions/write-gate/write-gate.ts | 36 ++++++++ tests/unit/extensions/decoration-host.test.ts | 86 +++++++++++++++++++ 3 files changed, 203 insertions(+) create mode 100644 extensions/decoration-host/decoration-host.ts create mode 100644 extensions/write-gate/write-gate.ts create mode 100644 tests/unit/extensions/decoration-host.test.ts diff --git a/extensions/decoration-host/decoration-host.ts b/extensions/decoration-host/decoration-host.ts new file mode 100644 index 00000000..cd2eea07 --- /dev/null +++ b/extensions/decoration-host/decoration-host.ts @@ -0,0 +1,81 @@ +import { Extension } from "@tiptap/core"; +import { Plugin } from "@tiptap/pm/state"; +import { DecorationSet } from "@tiptap/pm/view"; + +export interface DecorationLayer { + /** The layer's name, e.g. "comments" or "find". */ + name: string; + /** + * Map the set through document changes (`DecorationSet.map`) instead of + * clearing it. Comments map; hits that are recomputed anyway clear. + */ + map?: boolean; +} + +export interface DecorationHostOptions { + layers: DecorationLayer[]; +} + +/** The meta every layer reads: `{ name, set }`. */ +const LAYER_META = "decorationLayer"; + +declare module "@tiptap/core" { + interface Commands { + decorationHost: { + /** + * Shows `set` (built against the current document) as layer `name`; + * `DecorationSet.empty` clears it. Meta-only: never the document, Yjs + * or undo. + */ + setDecorationLayer: (name: string, set: DecorationSet) => ReturnType; + }; + } +} + +/** + * Decoration host (details spec §1 rule 6), the `action-preview` pattern + * made general: each declared layer is one eager plugin whose only state + * is a `DecorationSet`, set by the meta-only `setDecorationLayer` command. + * All logic (finding hits, anchoring comments) lives in the layer's lazy + * chunk, which never calls `registerPlugin` (that re-creates every plugin + * view): a layer is declared here, in the extensions array, once. A local + * or remote document change maps a `map: true` layer and clears the rest. + */ +export const DecorationHost = Extension.create({ + name: "decorationHost", + + addOptions: () => ({ layers: [] }), + + addCommands: () => ({ + setDecorationLayer: + (name, set) => + ({ tr }) => { + // No steps, so no history entry and nothing for Yjs. + tr.setMeta(LAYER_META, { name, set }); + return true; + }, + }), + + addProseMirrorPlugins() { + return this.options.layers.map( + ({ name, map }) => + new Plugin({ + state: { + init: () => DecorationSet.empty, + apply(tr, set) { + const next = tr.getMeta(LAYER_META); + if (next?.name === name) return next.set; + // Mapping or clearing an empty set returns it unchanged. + if (!tr.docChanged) return set; + return map ? set.map(tr.mapping, tr.doc) : DecorationSet.empty; + }, + }, + props: { + decorations(state) { + return this.getState(state); + }, + }, + }), + ); + }, +}); diff --git a/extensions/write-gate/write-gate.ts b/extensions/write-gate/write-gate.ts new file mode 100644 index 00000000..d9e13ceb --- /dev/null +++ b/extensions/write-gate/write-gate.ts @@ -0,0 +1,36 @@ +import { Extension } from "@tiptap/core"; +import { isChangeOrigin } from "@tiptap/extension-collaboration"; +import { Plugin } from "@tiptap/pm/state"; + +export interface WriteGateOptions { + /** + * Whether this window may change the document. Required. Read on every + * transaction, so pass a function over a ref: it must not wait for + * `setEditable`, which runs in an effect after the editor is created. + */ + canWrite: () => boolean; +} + +/** + * Read-only enforced before a change exists (details spec §1 rules 1–2): a + * Yjs update is never dropped once made (later updates from the same + * client would strand), so a read-only document must not make one. Filters + * every local transaction that changes the document while `canWrite()` is + * false, appended ones included, so the plugins that write when a document + * opens (heading ids, the title, the trailing node, the outline) are gated + * too. Changes arriving from Yjs and meta-only transactions (folds, + * previews, decorations) always pass. `setEditable` still blocks typing. + */ +export const WriteGate = Extension.create({ + name: "writeGate", + + addProseMirrorPlugins() { + const { canWrite } = this.options; + return [ + new Plugin({ + filterTransaction: (tr) => + !tr.docChanged || isChangeOrigin(tr) || canWrite(), + }), + ]; + }, +}); diff --git a/tests/unit/extensions/decoration-host.test.ts b/tests/unit/extensions/decoration-host.test.ts new file mode 100644 index 00000000..ab300a5a --- /dev/null +++ b/tests/unit/extensions/decoration-host.test.ts @@ -0,0 +1,86 @@ +import { afterEach, describe, expect, it } from "bun:test"; + +import { Editor } from "@tiptap/core"; +import { Decoration, DecorationSet } from "@tiptap/pm/view"; +import { StarterKit } from "@tiptap/starter-kit"; + +import { DecorationHost } from "@/extensions/decoration-host/decoration-host"; + +let editor: Editor | undefined; +afterEach(() => { + editor?.destroy(); + editor = undefined; +}); + +function create(layers: { name: string; map?: boolean }[]): Editor { + editor = new Editor({ + element: document.createElement("div"), + extensions: [ + StarterKit.configure({ undoRedo: false }), + DecorationHost.configure({ layers }), + ], + content: "

Hello world

", + }); + return editor; +} + +/** Highlights "world" (positions 7–12) in the current document. */ +const worldSet = (e: Editor) => + DecorationSet.create(e.state.doc, [ + Decoration.inline(7, 12, { class: "hit" }), + ]); + +/** The text under each drawn decoration. */ +const hits = (e: Editor) => + [...e.view.dom.querySelectorAll(".hit")].map((node) => node.textContent); + +describe("DecorationHost", () => { + it("adds one plugin per declared layer, none without", () => { + const count = (layers: { name: string }[]) => { + const e = new Editor({ + element: document.createElement("div"), + extensions: [DecorationHost.configure({ layers }), StarterKit], + }); + const plugins = e.state.plugins.length; + e.destroy(); + return plugins; + }; + expect(count([{ name: "a" }, { name: "b" }]) - count([])).toBe(2); + // The command is there for lazy layers; with none declared it is inert. + expect( + create([]).commands.setDecorationLayer("find", DecorationSet.empty), + ).toBe(true); + }); + + it("shows and clears a layer without touching the document or undo", () => { + const e = create([{ name: "find" }]); + const doc = e.state.doc; + e.commands.setDecorationLayer("find", worldSet(e)); + expect(hits(e)).toEqual(["world"]); + expect(e.state.doc).toBe(doc); + e.commands.setDecorationLayer("find", DecorationSet.empty); + expect(hits(e)).toEqual([]); + }); + + it("leaves other layers alone", () => { + const e = create([{ name: "find" }, { name: "comments", map: true }]); + e.commands.setDecorationLayer("comments", worldSet(e)); + e.commands.setDecorationLayer("find", worldSet(e)); + e.commands.setDecorationLayer("find", DecorationSet.empty); + expect(hits(e)).toEqual(["world"]); + }); + + it("clears a plain layer on a document change", () => { + const e = create([{ name: "find" }]); + e.commands.setDecorationLayer("find", worldSet(e)); + e.commands.insertContentAt(1, "Oh "); + expect(hits(e)).toEqual([]); + }); + + it("maps a map: true layer through a document change", () => { + const e = create([{ name: "comments", map: true }]); + e.commands.setDecorationLayer("comments", worldSet(e)); + e.commands.insertContentAt(1, "Oh "); + expect(hits(e)).toEqual(["world"]); + }); +}); From 9639a64e7ccbff7f4a090f7891ed89cb30918007 Mon Sep 17 00:00:00 2001 From: Harvey Date: Tue, 17 Nov 2026 12:19:17 +0330 Subject: [PATCH 2/7] feat(editor): accept no provider and keep one stable Awareness DocumentEditor now takes the session's Awareness and a provider that may be null (desktop P2.2). The caret is configured with that Awareness, and the extensions memo depends on it rather than on the provider, so attaching a provider later never calls setOptions. The connection chip renders only with a provider: its connection state creates the shared socket. UniqueID finds the caret's provider option and waits for its "synced" event, so on and off forward to the provider of the moment through a ref; the web behaves as before. WriteGate and an empty decoration host join the extensions. The new readOnly prop drives the gate and setEditable; the web never sets it. --- .../document-editor/document-editor-config.ts | 30 ++- .../document-editor/document-editor.tsx | 45 ++++- hooks/use-yjs-document.ts | 2 + tests/helpers/editor-schema.ts | 6 +- .../document-editor-markdown.test.ts | 8 +- .../document-editor-no-provider.test.tsx | 179 +++++++++++++++++ .../editor-actions/shortcut-bindings.test.ts | 6 +- tests/unit/extensions/write-gate.test.ts | 183 ++++++++++++++++++ 8 files changed, 440 insertions(+), 19 deletions(-) create mode 100644 tests/unit/components/document-editor-no-provider.test.tsx create mode 100644 tests/unit/extensions/write-gate.test.ts diff --git a/components/document-editor/document-editor-config.ts b/components/document-editor/document-editor-config.ts index 484c94eb..de09cc58 100644 --- a/components/document-editor/document-editor-config.ts +++ b/components/document-editor/document-editor-config.ts @@ -31,6 +31,7 @@ import type { EditorState, Transaction } from "@tiptap/pm/state"; import { StarterKit } from "@tiptap/starter-kit"; import DOMPurify from "dompurify"; import { Marked, type marked } from "marked"; +import type { Awareness } from "y-protocols/awareness"; import type * as Y from "yjs"; import { HorizontalRule } from "@/components/tiptap-node/horizontal-rule-node/horizontal-rule-node-extension"; @@ -45,6 +46,7 @@ import { renderCaret, renderCaretSelection, } from "@/extensions/collaboration-caret/safe-caret-render"; +import { DecorationHost } from "@/extensions/decoration-host/decoration-host"; import { EditorActionShortcuts } from "@/extensions/editor-action-shortcuts"; import { HeadingDrag } from "@/extensions/heading-drag"; import { @@ -65,6 +67,7 @@ import { FastTableOfContents } from "@/extensions/table-of-contents"; import { FontSize, TextColor } from "@/extensions/text-style-marks"; import { TitleDocument } from "@/extensions/title-document"; import { TokenHighlight } from "@/extensions/token-highlight"; +import { WriteGate } from "@/extensions/write-gate/write-gate"; import { SUBSCRIPT_SHORTCUT } from "@/lib/app-shortcuts"; import { lowlight } from "@/lib/lowlight"; @@ -143,7 +146,15 @@ function createMarkedInstance(): typeof marked { interface BuildDocumentEditorExtensionsOptions { documentId: string; ydoc: Y.Doc; - provider: HocuspocusProvider; + /** + * The session's one Awareness. It outlives any provider, so attaching or + * detaching one never rebuilds the extensions (no `setOptions`). + */ + awareness: Awareness; + /** The provider of the moment, if any; read, never a dependency. */ + getProvider: () => HocuspocusProvider | null; + /** WriteGate's check: false blocks every local document change. */ + canWrite: () => boolean; onFoldChange: (foldedIds: Set) => void; onFilterChange: (state: HeadingFilterCallbackState) => void; onTocUpdate: (anchors: TableOfContentData) => void; @@ -176,7 +187,9 @@ function createHeadingFilterFoldAdapter() { export function buildDocumentEditorExtensions({ documentId, ydoc, - provider, + awareness, + getProvider, + canWrite, onFoldChange, onFilterChange, onTocUpdate, @@ -234,11 +247,22 @@ export function buildDocumentEditorExtensions({ CaretBlockVisible, RepeatFormatting, SlashTrigger, + // The caret reads only `provider.awareness` (3.x runtime), so it gets + // the session's Awareness and works with no provider at all. UniqueID + // finds this option too and waits for its "synced" event: forwarded to + // the provider of the moment, as before (none on desktop Local). CollaborationCaret.configure({ - provider, + provider: { + awareness, + on: (event: string, fn: () => void) => getProvider()?.on(event, fn), + off: (event: string, fn: () => void) => getProvider()?.off(event, fn), + }, render: renderCaret, selectionRender: renderCaretSelection, }), + WriteGate.configure({ canWrite }), + // Comment highlights and Find hits declare their layers here (rule 6). + DecorationHost, HorizontalRule, TextAlign.configure({ types: ["heading", "paragraph"] }), TaskList, diff --git a/components/document-editor/document-editor.tsx b/components/document-editor/document-editor.tsx index 4dfdd2d9..9491472b 100644 --- a/components/document-editor/document-editor.tsx +++ b/components/document-editor/document-editor.tsx @@ -14,6 +14,8 @@ import { useState, useSyncExternalStore, } from "react"; +import type { HocuspocusProvider } from "@hocuspocus/provider"; +import type { Awareness } from "y-protocols/awareness"; import type * as Y from "yjs"; import { focusRovingItem, Toolbar } from "@/components/ui/toolbar"; @@ -91,11 +93,20 @@ interface DocumentEditorProps { playgroundRegenerateTrigger?: number; /** The Playground tab's Regenerate, also run from the palette. */ onPlaygroundRegenerate?: () => void; + /** + * View only: no local ProseMirror change reaches the document, plugin + * writes on open included (WriteGate, details spec §1). The schema + * guard's Yjs repair is not gated yet. The web sandbox never sets it. + */ + readOnly?: boolean; } type DocumentEditorContentProps = DocumentEditorProps & { ydoc: Y.Doc; - provider: import("@hocuspocus/provider").HocuspocusProvider; + /** The session's one Awareness: carets and names, with or without a provider. */ + awareness: Awareness; + /** Null for a document with no server (desktop Local): nothing dials out. */ + provider: HocuspocusProvider | null; documentId: string; /** Why the server refuses edits (size, deleted, outdated…), if it does. */ rejectedReason: string | null; @@ -145,12 +156,14 @@ const EDITOR_PROPS = { function DocumentEditorContent({ ydoc, + awareness, provider, documentId, onTitleChange, initialContent, playgroundRegenerateTrigger, onPlaygroundRegenerate, + readOnly, rejectedReason, serverSynced, }: DocumentEditorContentProps) { @@ -191,22 +204,32 @@ function DocumentEditorContent({ // A repair deferred while refused (offline budget) runs now. if (rejectedReason === null) schemaGuard.onWritable(); }, [rejectedReason, schemaGuard]); + // Read by the extensions, never their deps: WriteGate on every + // transaction (from the first one on), UniqueID when it waits for a sync. + const liveRef = useRef({ provider, readOnly }); + useEffect(() => { + liveRef.current = { provider, readOnly }; + }, [provider, readOnly]); // `useEditor` compares its options on every render and, when any differ, // calls `editor.setOptions`: a full view update that also re-syncs the - // whole document to Yjs. Keep every option stable between renders. + // whole document to Yjs. Keep every option stable between renders: the + // deps hold the Awareness, never the provider, so attaching one later + // keeps this array. const extensions = useMemo( () => buildDocumentEditorExtensions({ documentId, ydoc, - provider, + awareness, + getProvider: () => liveRef.current.provider, + canWrite: () => !liveRef.current.readOnly, onFoldChange: setFoldedIds, onFilterChange: setFilterState, onTocUpdate: tocStore.set, onInvalidContent: schemaGuard.onInvalidContent, }), - [documentId, ydoc, provider, tocStore, schemaGuard], + [documentId, ydoc, awareness, tocStore, schemaGuard], ); const editor = useEditor({ @@ -235,8 +258,8 @@ function DocumentEditorContent({ // Stop accepting input the server would drop or the schema can't hold. useEffect(() => { - if (editor) editor.setEditable(reason === null); - }, [editor, reason]); + if (editor) editor.setEditable(reason === null && !readOnly); + }, [editor, reason, readOnly]); const headingFilter = useHeadingFilter({ editor, @@ -431,7 +454,8 @@ function DocumentEditorContent({ rejectedReason={rejectedReason} /> )} - + {/* Its connection state opens the shared socket: only with a provider. */} + {provider && } ); @@ -443,12 +467,13 @@ export function DocumentEditor({ initialContent, playgroundRegenerateTrigger, onPlaygroundRegenerate, + readOnly, }: DocumentEditorProps = {}) { const docId = documentId ?? "default"; - const { ydoc, provider, synced, serverSynced, rejectedReason } = + const { ydoc, awareness, provider, synced, serverSynced, rejectedReason } = useYjsDocument(docId); - if (!synced || !ydoc || !provider) { + if (!synced || !ydoc || !awareness) { return ( <> {/* Refused with no device copy: explain instead of loading forever. */} @@ -463,12 +488,14 @@ export function DocumentEditor({ return ( diff --git a/hooks/use-yjs-document.ts b/hooks/use-yjs-document.ts index 4195a526..f788b4c2 100644 --- a/hooks/use-yjs-document.ts +++ b/hooks/use-yjs-document.ts @@ -51,6 +51,8 @@ export function useYjsDocument(documentId: string) { return { ydoc, + /** The session's one Awareness (DocSession shape); the provider's here. */ + awareness: providerRef?.awareness ?? null, provider: providerRef, synced, serverSynced, diff --git a/tests/helpers/editor-schema.ts b/tests/helpers/editor-schema.ts index dcdbe60f..a2d17e31 100644 --- a/tests/helpers/editor-schema.ts +++ b/tests/helpers/editor-schema.ts @@ -1,6 +1,6 @@ -import type { HocuspocusProvider } from "@hocuspocus/provider"; import { getSchema } from "@tiptap/core"; import type { Schema } from "@tiptap/pm/model"; +import type { Awareness } from "y-protocols/awareness"; import * as Y from "yjs"; import { buildDocumentEditorExtensions } from "@/components/document-editor/document-editor-config"; @@ -11,7 +11,9 @@ export function getEditorSchema(): Schema { buildDocumentEditorExtensions({ documentId: "schema-test", ydoc: new Y.Doc(), - provider: {} as HocuspocusProvider, + awareness: {} as Awareness, + getProvider: () => null, + canWrite: () => true, onFoldChange() {}, onFilterChange() {}, onTocUpdate() {}, diff --git a/tests/unit/components/document-editor-markdown.test.ts b/tests/unit/components/document-editor-markdown.test.ts index d9b2c1d1..2b3ca9d0 100644 --- a/tests/unit/components/document-editor-markdown.test.ts +++ b/tests/unit/components/document-editor-markdown.test.ts @@ -1,18 +1,20 @@ import { describe, expect, it } from "bun:test"; -import type { HocuspocusProvider } from "@hocuspocus/provider"; import { Editor } from "@tiptap/core"; import { marked } from "marked"; +import type { Awareness } from "y-protocols/awareness"; import * as Y from "yjs"; import { buildDocumentEditorExtensions } from "@/components/document-editor/document-editor-config"; -/** The app's extensions, minus the two that need a live provider. */ +/** The app's extensions, minus the two collaboration ones (Yjs binding, carets). */ function buildEditor(): Editor { const extensions = buildDocumentEditorExtensions({ documentId: "markdown-test", ydoc: new Y.Doc(), - provider: {} as HocuspocusProvider, + awareness: {} as Awareness, + getProvider: () => null, + canWrite: () => true, onFoldChange() {}, onFilterChange() {}, onTocUpdate() {}, diff --git a/tests/unit/components/document-editor-no-provider.test.tsx b/tests/unit/components/document-editor-no-provider.test.tsx new file mode 100644 index 00000000..10a0488b --- /dev/null +++ b/tests/unit/components/document-editor-no-provider.test.tsx @@ -0,0 +1,179 @@ +import { + afterAll, + afterEach, + beforeAll, + describe, + expect, + it, + mock, + spyOn, +} from "bun:test"; + +import type { HocuspocusProvider } from "@hocuspocus/provider"; +import { Editor } from "@tiptap/core"; +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { Awareness } from "y-protocols/awareness"; +import * as Y from "yjs"; + +import * as yjsDocumentModule from "@/hooks/use-yjs-document"; +import * as hocuspocusModule from "@/lib/hocuspocus"; + +( + globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } +).IS_REACT_ACT_ENVIRONMENT = true; + +type YjsDocument = ReturnType; + +/** What the mocked session hands the editor; tests change it, then render. */ +let session: YjsDocument; + +/** Calls that would create (or reuse) the shared WebSocket. */ +let socketRequests = 0; +const socketStub = { + status: "connected", + connect() {}, + on() {}, + off() {}, +}; + +// mock.module is process-wide: the real modules go back in afterAll. +const realUseYjsDocument = yjsDocumentModule.useYjsDocument; +const realGetSocket = hocuspocusModule.getSharedHocuspocusSocket; +mock.module("@/hooks/use-yjs-document", () => ({ + ...yjsDocumentModule, + useYjsDocument: () => session, +})); +mock.module("@/lib/hocuspocus", () => ({ + ...hocuspocusModule, + getSharedHocuspocusSocket: () => { + socketRequests++; + return socketStub; + }, +})); +afterAll(() => { + mock.module("@/hooks/use-yjs-document", () => ({ + ...yjsDocumentModule, + useYjsDocument: realUseYjsDocument, + })); + mock.module("@/lib/hocuspocus", () => ({ + ...hocuspocusModule, + getSharedHocuspocusSocket: realGetSocket, + })); +}); + +const { DocumentEditor } = await import( + "@/components/document-editor/document-editor" +); + +/** Counts WebSocket constructions, whatever creates them. */ +let socketsOpened = 0; +const RealWebSocket = globalThis.WebSocket; +beforeAll(() => { + globalThis.WebSocket = class extends EventTarget { + constructor() { + super(); + socketsOpened++; + } + } as unknown as typeof WebSocket; +}); +afterAll(() => { + globalThis.WebSocket = RealWebSocket; +}); + +/** `useEditor` calls it when an option changes: a full view update. */ +const setOptions = spyOn(Editor.prototype, "setOptions"); +afterAll(() => setOptions.mockRestore()); + +let root: Root | undefined; +let container: HTMLElement | undefined; +let awareness: Awareness | undefined; +afterEach(async () => { + await act(async () => root?.unmount()); + container?.remove(); + awareness?.destroy(); + root = undefined; + container = undefined; + awareness = undefined; + socketRequests = 0; + socketsOpened = 0; + setOptions.mockClear(); +}); + +function localSession() { + const ydoc = new Y.Doc(); + awareness = new Awareness(ydoc); + return { + ydoc, + awareness, + provider: null, + synced: true, + serverSynced: true, + rejectedReason: null, + }; +} + +/** A provider double sharing the session's Awareness, as Live attaches. */ +const providerFor = (shared: Awareness) => + ({ + awareness: shared, + isSynced: true, + on() {}, + off() {}, + }) as unknown as HocuspocusProvider; + +async function render() { + await act(async () => { + root?.render(); + }); + // Tiptap creates the editor in an effect and emits `create` on a timer. + await act(() => new Promise((resolve) => setTimeout(resolve, 30))); +} + +async function mount() { + container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); + await render(); +} + +describe("DocumentEditor without a provider", () => { + it("mounts an editable editor and opens no socket", async () => { + session = localSession(); + await mount(); + expect(container?.querySelector(".document-editor")).not.toBeNull(); + expect(window.__tiptap_editor?.isEditable).toBe(true); + // The connection chip (and its socket) belongs to a provider only. + expect(container?.querySelector("[data-collab-status]")).toBeNull(); + expect(socketRequests).toBe(0); + expect(socketsOpened).toBe(0); + }); + + it("keeps its extensions when a provider attaches", async () => { + const local = localSession(); + session = local; + await mount(); + const editor = window.__tiptap_editor; + const optionCalls = setOptions.mock.calls.length; + + session = { ...local, provider: providerFor(local.awareness) }; + await render(); + expect(window.__tiptap_editor).toBe(editor); + expect(setOptions.mock.calls.length).toBe(optionCalls); + // With a provider, the chip and its connection come back. + expect(socketRequests).toBeGreaterThan(0); + }); + + it("would rebuild them for a new Awareness (control)", async () => { + const local = localSession(); + session = local; + await mount(); + const optionCalls = setOptions.mock.calls.length; + + const other = new Awareness(local.ydoc); + session = { ...local, awareness: other }; + await render(); + other.destroy(); + expect(setOptions.mock.calls.length).toBeGreaterThan(optionCalls); + }); +}); diff --git a/tests/unit/editor-actions/shortcut-bindings.test.ts b/tests/unit/editor-actions/shortcut-bindings.test.ts index a390af10..9bc3faeb 100644 --- a/tests/unit/editor-actions/shortcut-bindings.test.ts +++ b/tests/unit/editor-actions/shortcut-bindings.test.ts @@ -8,7 +8,7 @@ */ import { afterEach, describe, expect, it } from "bun:test"; -import type { HocuspocusProvider } from "@hocuspocus/provider"; +import type { Awareness } from "y-protocols/awareness"; import * as Y from "yjs"; import type { buildDocumentEditorExtensions as BuildExtensions } from "@/components/document-editor/document-editor-config"; @@ -43,7 +43,9 @@ async function loadEditor(): Promise<{ const extensions = buildDocumentEditorExtensions({ documentId: "keys", ydoc: new Y.Doc(), - provider: {} as HocuspocusProvider, + awareness: {} as Awareness, + getProvider: () => null, + canWrite: () => true, onFoldChange() {}, onFilterChange() {}, onTocUpdate() {}, diff --git a/tests/unit/extensions/write-gate.test.ts b/tests/unit/extensions/write-gate.test.ts new file mode 100644 index 00000000..3c5a5f14 --- /dev/null +++ b/tests/unit/extensions/write-gate.test.ts @@ -0,0 +1,183 @@ +import { afterEach, describe, expect, it } from "bun:test"; + +import type { HocuspocusProvider } from "@hocuspocus/provider"; +import { Editor, getSchema, type JSONContent } from "@tiptap/core"; +import { prosemirrorJSONToYDoc } from "@tiptap/y-tiptap"; +import { Awareness } from "y-protocols/awareness"; +import * as Y from "yjs"; + +import { buildDocumentEditorExtensions } from "@/components/document-editor/document-editor-config"; +import { headingFoldPluginKey } from "@/extensions/heading-fold"; + +const text = (value: string): JSONContent => ({ type: "text", text: value }); + +const heading = (level: number, value: string, id?: string): JSONContent => ({ + type: "heading", + attrs: id ? { level, id, "data-toc-id": id } : { level }, + content: [text(value)], +}); + +/** Unnamed headings: the outline names them when the editor is created. */ +const UNNAMED: JSONContent = { + type: "doc", + content: [heading(1, "Title"), heading(2, "Section")], +}; + +const NAMED: JSONContent = { + type: "doc", + content: [ + heading(1, "Title", "t"), + heading(2, "Section", "s"), + { type: "paragraph", content: [text("Body")] }, + ], +}; + +/** A provider stand-in: UniqueID only subscribes to "synced". */ +function fakeProvider() { + const listeners = new Map void>(); + const provider = { + on: (event: string, fn: () => void) => listeners.set(event, fn), + off: (event: string) => listeners.delete(event), + } as unknown as HocuspocusProvider; + return { provider, listeners, sync: () => listeners.get("synced")?.() }; +} + +interface OpenOptions { + canWrite?: () => boolean; + getProvider?: () => HocuspocusProvider | null; +} + +const extensionsFor = ( + ydoc: Y.Doc, + awareness: Awareness, + { canWrite = () => true, getProvider = () => null }: OpenOptions = {}, +) => + buildDocumentEditorExtensions({ + documentId: "write-gate", + ydoc, + awareness, + getProvider, + canWrite, + onFoldChange() {}, + onFilterChange() {}, + onTocUpdate() {}, + }); + +/** A Y.Doc holding `content` in the editor's fragment. */ +function seededDoc(content: JSONContent): Y.Doc { + const schema = getSchema(extensionsFor(new Y.Doc(), {} as Awareness)); + return prosemirrorJSONToYDoc(schema, content, "default"); +} + +let editor: Editor | undefined; +let awareness: Awareness | undefined; +afterEach(() => { + editor?.destroy(); + awareness?.destroy(); + editor = undefined; + awareness = undefined; +}); + +/** + * Opens the app's editor on `ydoc` and waits for `create` (Tiptap emits it + * on a timer); returns the Yjs updates it makes. + */ +async function open(ydoc: Y.Doc, options?: OpenOptions): Promise { + const updates: Uint8Array[] = []; + ydoc.on("update", (update: Uint8Array) => updates.push(update)); + awareness = new Awareness(ydoc); + editor = new Editor({ + element: document.createElement("div"), + extensions: extensionsFor(ydoc, awareness, options), + }); + await new Promise((resolve) => setTimeout(resolve, 20)); + return updates; +} + +const headingIds = () => { + const ids: unknown[] = []; + editor?.state.doc.forEach((node) => { + if (node.type.name === "heading") ids.push(node.attrs["data-toc-id"]); + }); + return ids; +}; + +const title = () => editor?.state.doc.firstChild?.textContent; + +describe("WriteGate", () => { + it("lets the opening writes through when writable", async () => { + await open(seededDoc(UNNAMED)); + // Control for the next test: the outline names both headings. + expect(headingIds().every((id) => typeof id === "string")).toBe(true); + }); + + it("blocks the opening writes when read-only", async () => { + const { provider, sync } = fakeProvider(); + const updates = await open(seededDoc(UNNAMED), { + canWrite: () => false, + getProvider: () => provider, + }); + // UniqueID's first-sync pass is gated too. + sync(); + expect(headingIds()).toEqual([null, null]); + expect(updates).toHaveLength(0); + // The content still renders from Yjs. + expect(editor?.state.doc.textContent).toBe("TitleSection"); + }); + + it("blocks local edits but not a collaborator's", async () => { + const ydoc = seededDoc(NAMED); + let writable = true; + const updates = await open(ydoc, { canWrite: () => writable }); + editor?.commands.insertContentAt(1, "My "); + expect(updates.length).toBeGreaterThan(0); + + writable = false; + const before = updates.length; + editor?.commands.insertContentAt(1, "Local "); + expect(updates.length).toBe(before); + expect(title()).toBe("My Title"); + + // A collaborator's change arrives through Yjs and is shown. + const remote = new Y.Doc(); + Y.applyUpdate(remote, Y.encodeStateAsUpdate(ydoc)); + const first = remote.getXmlFragment("default").get(0) as Y.XmlElement; + (first.get(0) as Y.XmlText).insert(0, "Remote "); + Y.applyUpdate( + ydoc, + Y.encodeStateAsUpdate(remote, Y.encodeStateVector(ydoc)), + ); + expect(title()).toBe("Remote My Title"); + }); + + it("lets meta-only transactions through", async () => { + await open(seededDoc(NAMED), { canWrite: () => false }); + // A fold is meta-only: it works on a read-only document. + editor?.commands.toggleFold("s"); + const folded = editor && headingFoldPluginKey.getState(editor.state); + expect([...(folded?.foldedIds ?? [])]).toEqual(["s"]); + }); +}); + +describe("no provider", () => { + it("opens and edits with the session's Awareness alone", async () => { + const ydoc = seededDoc(NAMED); + await open(ydoc); + editor?.commands.insertContentAt(1, "Local "); + expect(ydoc.getXmlFragment("default").toString()).toContain("Local Title"); + // The caret publishes this user on the session's Awareness. + editor?.commands.updateUser({ name: "Ada", color: "#000000" }); + expect(awareness?.getLocalState()?.user?.name).toBe("Ada"); + }); + + it("forwards UniqueID's wait for a sync to the provider of the moment", async () => { + let current: HocuspocusProvider | null = null; + const { provider, listeners } = fakeProvider(); + current = provider; + await open(seededDoc(UNNAMED), { getProvider: () => current }); + // As before this change: UniqueID waits on the real provider's sync. + expect(listeners.has("synced")).toBe(true); + listeners.get("synced")?.(); + expect(listeners.has("synced")).toBe(false); + }); +}); From cf3274275dc2a6906088f9021f2fe0d247e81806 Mon Sep 17 00:00:00 2001 From: Harvey Date: Tue, 17 Nov 2026 12:19:18 +0330 Subject: [PATCH 3/7] build(editor): fence the chunk budget at main plus the D23 ledger The budget was 23.5 KB of growth (contract A12); main is at +15,691 B. D23 lowers it to main plus the 1,580 B ledger, +17,271 B, so unrelated work cannot spend the ledger's bytes. The report prints exact bytes. --- scripts/check-editor-chunk-size.ts | 39 +++++++++++++++++++----------- 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/scripts/check-editor-chunk-size.ts b/scripts/check-editor-chunk-size.ts index b8de46ff..c310f675 100644 --- a/scripts/check-editor-chunk-size.ts +++ b/scripts/check-editor-chunk-size.ts @@ -1,8 +1,8 @@ /** - * Editor bundle gate (spec §7, contract §5.1): the lazy editor chunk group - * may grow by at most `EDITOR_CHUNK_BUDGET_BYTES` gzipped over the baseline - * measured on `58a9d22` (the `integrate/smart-toolbar-ab` tip, before any - * smart-toolbar v1 track merged). + * Editor bundle gate (spec §7, contract §5.1; desktop D23): the lazy editor + * chunk group may grow by at most `EDITOR_CHUNK_BUDGET_BYTES` gzipped over + * the baseline measured on `58a9d22` (the `integrate/smart-toolbar-ab` tip, + * before any smart-toolbar v1 track merged). * * The editor is a `next/dynamic` import (`components/editor-app`). Turbopack * emits a loader that fetches the editor's chunk group with @@ -21,14 +21,25 @@ import { join } from "node:path"; /** Gzipped bytes of the editor chunk group at `58a9d22`. */ export const EDITOR_CHUNK_BASELINE_BYTES = 377_888; /** - * Allowed growth for the whole smart toolbar v1. Spec §7 said +6 KB gz; - * owner decision O1 (contract §10 A9) lazy-loads what is not needed at - * first paint and sets the budget to the measured remainder (18.43 KB on - * the r2 integration), rounded up to the next 0.5 KB. A11 raises it to - * 20 KB for the r2 fix waves (owner, 2026-11-13), and A12 to 23.5 KB for - * PR E (owner, 2026-11-13). Raising it again needs a new contract amendment. + * Growth on `main` (f9cfc3a) when P2.2 set the fence: the smart toolbar v1 + * and everything merged before the desktop work. Its old 23.5 KB budget + * (contract A12) is replaced by the fence below. */ -export const EDITOR_CHUNK_BUDGET_BYTES = 23.5 * 1024; +export const EDITOR_CHUNK_MAIN_GROWTH_BYTES = 15_691; +/** + * The D23 editor-chunk ledger (desktop details spec §1 rule 5): every line + * the desktop, library and v1 feature work may add to this chunk, each + * measured in its PR. While D41's conditional 80 B undo line is + * unconfirmed the total is 1,580 B; if spike M18 confirms it, this becomes + * 1,660 B with no further approval. + */ +export const EDITOR_CHUNK_LEDGER_BYTES = 1_580; +/** + * The fence (D23): `main` plus the ledger, so unrelated work can't spend + * the ledger's bytes. Raising it needs an amendment to that rule. + */ +export const EDITOR_CHUNK_BUDGET_BYTES = + EDITOR_CHUNK_MAIN_GROWTH_BYTES + EDITOR_CHUNK_LEDGER_BYTES; /** Only `document-editor.tsx` renders this string. */ const EDITOR_MARKER = "Main content area, start typing to enter text."; @@ -75,13 +86,13 @@ function main() { const nextDir = dirFlag === -1 ? ".next" : process.argv[dirFlag + 1]; const { files, gzipBytes } = measureEditorChunk(nextDir); const growth = gzipBytes - EDITOR_CHUNK_BASELINE_BYTES; - const kb = (bytes: number) => `${(bytes / 1024).toFixed(1)} KB`; + const bytes = (n: number) => `${n.toLocaleString("en-US")} B`; console.log( - `Editor chunk group (${files.length} files): ${kb(gzipBytes)} gz`, + `Editor chunk group (${files.length} files): ${bytes(gzipBytes)} gz`, ); for (const file of files) console.log(` ${file}`); console.log( - `Baseline ${kb(EDITOR_CHUNK_BASELINE_BYTES)}, growth ${growth >= 0 ? "+" : ""}${kb(growth)}, budget +${kb(EDITOR_CHUNK_BUDGET_BYTES)}`, + `Baseline ${bytes(EDITOR_CHUNK_BASELINE_BYTES)}, growth ${growth >= 0 ? "+" : ""}${bytes(growth)}, budget +${bytes(EDITOR_CHUNK_BUDGET_BYTES)} (${bytes(EDITOR_CHUNK_BUDGET_BYTES - growth)} left)`, ); if (growth > EDITOR_CHUNK_BUDGET_BYTES) { console.error( From ec3eaf0f5a46d45bc73e65c0e8618dde5f430d2e Mon Sep 17 00:00:00 2001 From: Harvey Date: Tue, 17 Nov 2026 12:19:18 +0330 Subject: [PATCH 4/7] docs: record P2.2's measured ledger line and the caret decision --- CHANGELOG.md | 32 +++++++++++++++++++ .../specs/2026-11-15-desktop-architecture.md | 2 +- ...15-desktop-documents-and-editor-details.md | 4 +-- 3 files changed, 35 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b6c90779..2f153ca1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,38 @@ since the previous tag. ## [Unreleased] +### Editor without a provider; WriteGate; the editor-chunk fence (P2.2) + +Desktop Phase 2, P2.2. The web editor behaves as before: it still gets its +provider, and nothing passes the new read-only prop. The editor chunk goes +from +15,691 B to +15,988 B (+297 B of P2.2's 300 B line in the D23 ledger), +and the budget drops from 23.5 KB to +17,271 B (`main` plus the 1,580 B +ledger), leaving 1,283 B for the ledger's other lines. No schema or protocol +change; no Deploy note. + +#### Added + +- **Editor:** `DocumentEditor` takes the session's Awareness and accepts no + provider. With none, the connection chip isn't rendered and no socket + opens. Carets use the Awareness directly, and the extension list depends + on it rather than on the provider, so attaching a provider later never + rebuilds the extensions (no `setOptions`). +- **Editor:** `WriteGate` (`extensions/write-gate/`), a `filterTransaction` + plugin over a ref. With the new `readOnly` prop, no local ProseMirror + change reaches the document, including the writes plugins make when a + document opens. Changes from collaborators still apply. The schema + guard's repair writes Yjs directly and is not gated yet; it must be when + something first sets `readOnly`. +- **Editor:** the decoration host (`extensions/decoration-host/`): declared + layers each get a plugin holding a `DecorationSet`, set by the meta-only + `setDecorationLayer` command, either mapped or cleared on document + changes. No layer is declared yet; comments and Find will declare theirs. + +#### Changed + +- **Build:** `scripts/check-editor-chunk-size.ts` budget is `main` at + P2.2 plus the D23 ledger (+17,271 B), and it prints exact bytes. + ### Deploy: run install scripts on Bun, not the host's Node 14 The first automated deploy failed at `bun install`: husky's `prepare` script diff --git a/docs/superpowers/specs/2026-11-15-desktop-architecture.md b/docs/superpowers/specs/2026-11-15-desktop-architecture.md index 2c2b69e5..663fd514 100644 --- a/docs/superpowers/specs/2026-11-15-desktop-architecture.md +++ b/docs/superpowers/specs/2026-11-15-desktop-architecture.md @@ -196,7 +196,7 @@ All live in `lib/platform/ports.ts`, as types only. **Shared editor changes** stay within their lines in the editor-chunk ledger (owner D23, ≈1,540 B gz in all, ≈1,580–1,660 B with D41's conditional phone line; P2.2's line, no provider plus `WriteGate` and the decoration-host stub, is 300 B; details spec §1 rule 5), checked by the chunk script on both targets, with `EDITOR_CHUNK_BUDGET_BYTES` lowered to `main` plus the ledger: -1. **`provider` becomes `HocuspocusProvider | null`.** `CollaborationCaret` is configured with the session's stable `awareness` (**decided in P2.2**, against the extension's runtime). The `useMemo` deps hold `awareness`, never the provider, so a provider attached later never rebuilds the extensions array. +1. **`provider` becomes `HocuspocusProvider | null`.** `CollaborationCaret` is configured with the session's stable `awareness` (**decided in P2.2**, against the extension's runtime: the caret reads only `provider.awareness`, so it gets `{ awareness, on, off }`; UniqueID also finds that option and waits for its `"synced"` event, so `on` and `off` forward to the provider of the moment through a ref, and with no provider nothing is waited for). The `useMemo` deps hold `awareness`, never the provider, so a provider attached later never rebuilds the extensions array. 2. **`CollabStatusGroup` renders only when `provider` is non-null.** Today it calls `useConnectionState`, which **creates the shared socket**, so a Local document would dial the server. The desktop chip is rendered by the desktop shell, outside the editor chunk. 3. **Seeding stays as it is.** `authoritative` feeds the existing `serverSynced` prop, and `local-session` sets it once hydrate finishes, because the library *is* the authority. The seed effect (`use-document-editor-effects.ts:78`) runs unchanged, and `data-server-synced` doubles as the readiness hook for the `local` and `electron` projects. (Live) A joined document becomes authoritative only after its first server sync. diff --git a/docs/superpowers/specs/2026-11-15-desktop-documents-and-editor-details.md b/docs/superpowers/specs/2026-11-15-desktop-documents-and-editor-details.md index f96b89cb..3c559f70 100644 --- a/docs/superpowers/specs/2026-11-15-desktop-documents-and-editor-details.md +++ b/docs/superpowers/specs/2026-11-15-desktop-documents-and-editor-details.md @@ -56,7 +56,7 @@ These came out of the staff feasibility review. Each one was checked against the | Line | PR (owner) | Cap (gz) | |---|---|---| - | No provider, `WriteGate` and the decoration host | P2.2 | 300 B | + | No provider, `WriteGate` and the decoration host | P2.2 | 300 B (measured 297 B) | | Comments hook | P4.9 | 150 B | | Smart-quotes gate | P2.9c-1 | 150 B | | i18n core (`t()`, registry labels, `lang`/`dir`; also pays L3's `matchShortcut` / `visualStep` bytes, languages §3.7.1) | L1a | 400 B | @@ -68,7 +68,7 @@ These came out of the staff feasibility review. Each one was checked against the | Undo-gesture handler, **only if spike M18 shows native undo mutates the DOM** (D41, v8) | M19 | 80 B, conditional | | **Total** | | **1,580 B, or 1,660 B with the undo handler** | - - **Headroom:** 4,385 B real (the 24,064 B budget less `main` at 19,679 B, latest CHANGELOG entry). The ledger takes about a third of it, with or without the conditional line. + - **Headroom:** 4,385 B real when D23 was decided (the 24,064 B budget less `main` at 19,679 B). By P2.2, `main` had shrunk to +15,691 B, so P2.2 set the fence at +17,271 B (15,691 + 1,580) in `scripts/check-editor-chunk-size.ts`; after P2.2 1,283 B remain for the other lines. - **Phones (D41):** M27's hardware-keyboard listener (shortcut glyphs) stays **out** of the editor chunk. - **Fencing:** P2.2 lowers `EDITOR_CHUNK_BUDGET_BYTES` to the size on `main` plus the ledger total, so unrelated work can't spend these bytes. Raising it needs an amendment to this rule. While D41's conditional 80 B undo line is unconfirmed, the fence is `main` + 1,580 B. If spike M18 confirms the line, the fence rises to `main` + 1,660 B with no further approval (pre-approved by D41). - **A PR that would go over its line** stops for a budget review. A line's unused bytes don't move to another line without an amendment. From 14b05ef41fc938b97f2e01a382d8135ad1847373 Mon Sep 17 00:00:00 2001 From: Harvey Date: Tue, 17 Nov 2026 12:34:46 +0330 Subject: [PATCH 5/7] build(editor): re-measure the fence on main at 1ed981e #118 landed first: main is at +15,674 B, so the fence is +17,254 B (main plus the 1,580 B ledger). P2.2 measures 294 B on the merged tree. --- CHANGELOG.md | 8 ++++---- .../2026-11-15-desktop-documents-and-editor-details.md | 4 ++-- scripts/check-editor-chunk-size.ts | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c21175f7..29467203 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,9 +13,9 @@ since the previous tag. Desktop Phase 2, P2.2. The web editor behaves as before: it still gets its provider, and nothing passes the new read-only prop. The editor chunk goes -from +15,691 B to +15,988 B (+297 B of P2.2's 300 B line in the D23 ledger), -and the budget drops from 23.5 KB to +17,271 B (`main` plus the 1,580 B -ledger), leaving 1,283 B for the ledger's other lines. No schema or protocol +from +15,674 B to +15,968 B (+294 B of P2.2's 300 B line in the D23 ledger), +and the budget drops from 23.5 KB to +17,254 B (`main` plus the 1,580 B +ledger), leaving 1,286 B for the ledger's other lines. No schema or protocol change; no Deploy note. #### Added @@ -39,7 +39,7 @@ change; no Deploy note. #### Changed - **Build:** `scripts/check-editor-chunk-size.ts` budget is `main` at - P2.2 plus the D23 ledger (+17,271 B), and it prints exact bytes. + P2.2 plus the D23 ledger (+17,254 B), and it prints exact bytes. ### Dark links on highlighted text diff --git a/docs/superpowers/specs/2026-11-15-desktop-documents-and-editor-details.md b/docs/superpowers/specs/2026-11-15-desktop-documents-and-editor-details.md index 3c559f70..b67bfb6d 100644 --- a/docs/superpowers/specs/2026-11-15-desktop-documents-and-editor-details.md +++ b/docs/superpowers/specs/2026-11-15-desktop-documents-and-editor-details.md @@ -56,7 +56,7 @@ These came out of the staff feasibility review. Each one was checked against the | Line | PR (owner) | Cap (gz) | |---|---|---| - | No provider, `WriteGate` and the decoration host | P2.2 | 300 B (measured 297 B) | + | No provider, `WriteGate` and the decoration host | P2.2 | 300 B (measured 294 B) | | Comments hook | P4.9 | 150 B | | Smart-quotes gate | P2.9c-1 | 150 B | | i18n core (`t()`, registry labels, `lang`/`dir`; also pays L3's `matchShortcut` / `visualStep` bytes, languages §3.7.1) | L1a | 400 B | @@ -68,7 +68,7 @@ These came out of the staff feasibility review. Each one was checked against the | Undo-gesture handler, **only if spike M18 shows native undo mutates the DOM** (D41, v8) | M19 | 80 B, conditional | | **Total** | | **1,580 B, or 1,660 B with the undo handler** | - - **Headroom:** 4,385 B real when D23 was decided (the 24,064 B budget less `main` at 19,679 B). By P2.2, `main` had shrunk to +15,691 B, so P2.2 set the fence at +17,271 B (15,691 + 1,580) in `scripts/check-editor-chunk-size.ts`; after P2.2 1,283 B remain for the other lines. + - **Headroom:** 4,385 B real when D23 was decided (the 24,064 B budget less `main` at 19,679 B). By P2.2, `main` had shrunk to +15,674 B (1ed981e), so P2.2 set the fence at +17,254 B (15,674 + 1,580) in `scripts/check-editor-chunk-size.ts`; after P2.2 1,286 B remain for the other lines. - **Phones (D41):** M27's hardware-keyboard listener (shortcut glyphs) stays **out** of the editor chunk. - **Fencing:** P2.2 lowers `EDITOR_CHUNK_BUDGET_BYTES` to the size on `main` plus the ledger total, so unrelated work can't spend these bytes. Raising it needs an amendment to this rule. While D41's conditional 80 B undo line is unconfirmed, the fence is `main` + 1,580 B. If spike M18 confirms the line, the fence rises to `main` + 1,660 B with no further approval (pre-approved by D41). - **A PR that would go over its line** stops for a budget review. A line's unused bytes don't move to another line without an amendment. diff --git a/scripts/check-editor-chunk-size.ts b/scripts/check-editor-chunk-size.ts index c310f675..58c68f3a 100644 --- a/scripts/check-editor-chunk-size.ts +++ b/scripts/check-editor-chunk-size.ts @@ -21,11 +21,11 @@ import { join } from "node:path"; /** Gzipped bytes of the editor chunk group at `58a9d22`. */ export const EDITOR_CHUNK_BASELINE_BYTES = 377_888; /** - * Growth on `main` (f9cfc3a) when P2.2 set the fence: the smart toolbar v1 + * Growth on `main` (1ed981e) when P2.2 set the fence: the smart toolbar v1 * and everything merged before the desktop work. Its old 23.5 KB budget * (contract A12) is replaced by the fence below. */ -export const EDITOR_CHUNK_MAIN_GROWTH_BYTES = 15_691; +export const EDITOR_CHUNK_MAIN_GROWTH_BYTES = 15_674; /** * The D23 editor-chunk ledger (desktop details spec §1 rule 5): every line * the desktop, library and v1 feature work may add to this chunk, each From abebef8aa8a405face1d78cfc53a20d3de87d7fd Mon Sep 17 00:00:00 2001 From: Harvey Date: Tue, 17 Nov 2026 13:23:10 +0330 Subject: [PATCH 6/7] test(e2e): find the provider through the caret's forwarding on expectSavedToServer (#116) read isSynced from the caret's provider option, which P2.2 made the editor's Awareness holder, so it never saw the server ack and the perf and collab runs timed out. filter.spec's copy saw undefined and stopped waiting at all. The caret option's on returns the provider's on, which returns the provider, so the helper asks it; filter.spec now uses the same helper. A unit test pins it. --- tests/e2e/filter.spec.ts | 21 +++++---------------- tests/e2e/helpers/editor-page.ts | 17 +++++++++++++++-- tests/unit/extensions/write-gate.test.ts | 22 +++++++++++++++++++++- 3 files changed, 41 insertions(+), 19 deletions(-) diff --git a/tests/e2e/filter.spec.ts b/tests/e2e/filter.spec.ts index 0a9334ed..df3742a8 100644 --- a/tests/e2e/filter.spec.ts +++ b/tests/e2e/filter.spec.ts @@ -1,20 +1,7 @@ -import { expect, type Page, test } from "@playwright/test"; +import { expect, test } from "@playwright/test"; import { EditorPage } from "./helpers/editor-page"; -/** The headings must be on the server before a shared link opens. */ -async function waitForServerCopy(page: Page): Promise { - await page.waitForFunction(() => { - const caret = window.__tiptap_editor?.extensionManager.extensions.find( - (extension) => extension.name === "collaborationCaret", - ); - const provider = caret?.options.provider as - | { hasUnsyncedChanges: boolean } - | undefined; - return provider !== undefined && !provider.hasUnsyncedChanges; - }); -} - test.describe("heading filter", () => { let editorPage: EditorPage; @@ -48,7 +35,8 @@ test.describe("heading filter", () => { test("a ?filter= link applies the filter once the doc syncs", async ({ page, }) => { - await waitForServerCopy(page); + // The headings must be on the server before a shared link opens. + await editorPage.expectSavedToServer(); await page.goto("/?filter=alpha&mode=or"); await editorPage.waitForSync(); @@ -80,7 +68,8 @@ test.describe("heading filter", () => { test("a ?filter= link over the cap applies only its first 8 words", async ({ page, }) => { - await waitForServerCopy(page); + // The headings must be on the server before a shared link opens. + await editorPage.expectSavedToServer(); // Beta and Gamma come 9th and 10th, so they must be dropped unmatched. const kept = ["alpha", "w2", "w3", "w4", "w5", "w6", "w7", "w8"]; await page.goto(`/?filter=${[...kept, "beta", "gamma"].join("|")}&mode=or`); diff --git a/tests/e2e/helpers/editor-page.ts b/tests/e2e/helpers/editor-page.ts index 147b2a9f..25715da7 100644 --- a/tests/e2e/helpers/editor-page.ts +++ b/tests/e2e/helpers/editor-page.ts @@ -310,12 +310,25 @@ export class EditorPage { () => { const notice = document.querySelector(".document-size-notice"); if (notice) return { refusal: notice.textContent ?? "" }; + // The caret's `provider` option is the editor's Awareness holder, + // not the provider: its `on` forwards to the provider of the moment + // and returns what that returns, and `HocuspocusProvider.on` + // returns the provider itself (`this`). Null with no provider. const caret = window.__tiptap_editor?.extensionManager.extensions.find( (extension) => extension.name === "collaborationCaret", ); - const provider = caret?.options.provider as - | { isSynced: boolean; hasUnsyncedChanges: boolean } + const forward = caret?.options.provider as + | { on: (event: string, fn: () => void) => unknown } | undefined; + const probe = () => {}; + const provider = forward?.on("tinydocy:probe", probe) as + | { + isSynced: boolean; + hasUnsyncedChanges: boolean; + off: (event: string, fn: () => void) => void; + } + | undefined; + provider?.off("tinydocy:probe", probe); if (!provider?.isSynced || provider.hasUnsyncedChanges) return false; return { refusal: null }; }, diff --git a/tests/unit/extensions/write-gate.test.ts b/tests/unit/extensions/write-gate.test.ts index 3c5a5f14..811a94a7 100644 --- a/tests/unit/extensions/write-gate.test.ts +++ b/tests/unit/extensions/write-gate.test.ts @@ -35,8 +35,12 @@ const NAMED: JSONContent = { /** A provider stand-in: UniqueID only subscribes to "synced". */ function fakeProvider() { const listeners = new Map void>(); + // Like HocuspocusProvider's EventEmitter, `on` returns the provider. const provider = { - on: (event: string, fn: () => void) => listeners.set(event, fn), + on(event: string, fn: () => void) { + listeners.set(event, fn); + return provider; + }, off: (event: string) => listeners.delete(event), } as unknown as HocuspocusProvider; return { provider, listeners, sync: () => listeners.get("synced")?.() }; @@ -180,4 +184,20 @@ describe("no provider", () => { listeners.get("synced")?.(); expect(listeners.has("synced")).toBe(false); }); + + it("hands back the provider from the caret's on (e2e helpers find it so)", async () => { + const { provider } = fakeProvider(); + let current: HocuspocusProvider | null = null; + await open(seededDoc(NAMED), { getProvider: () => current }); + const caret = editor?.extensionManager.extensions.find( + (extension) => extension.name === "collaborationCaret", + ); + const forward = caret?.options.provider as { + on: (event: string, fn: () => void) => unknown; + }; + const probe = () => {}; + expect(forward.on("probe", probe)).toBeUndefined(); + current = provider; + expect(forward.on("probe", probe)).toBe(provider); + }); }); From 1c15715d91bfb5dca35ae274684786f72a668031 Mon Sep 17 00:00:00 2001 From: Harvey Date: Tue, 17 Nov 2026 13:28:32 +0330 Subject: [PATCH 7/7] build(editor): re-measure the fence on main at 08b7663 #126 landed first: main is at +15,284 B, so the fence is +16,864 B (main plus the 1,580 B ledger). P2.2 still measures 294 B on the merged tree (+15,578 B). --- CHANGELOG.md | 6 +++--- .../2026-11-15-desktop-documents-and-editor-details.md | 2 +- scripts/check-editor-chunk-size.ts | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d73f2f7c..7b270ff0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,8 +13,8 @@ since the previous tag. Desktop Phase 2, P2.2. The web editor behaves as before: it still gets its provider, and nothing passes the new read-only prop. The editor chunk goes -from +15,674 B to +15,968 B (+294 B of P2.2's 300 B line in the D23 ledger), -and the budget drops from 23.5 KB to +17,254 B (`main` plus the 1,580 B +from +15,284 B to +15,578 B (+294 B of P2.2's 300 B line in the D23 ledger), +and the budget drops from 23.5 KB to +16,864 B (`main` plus the 1,580 B ledger), leaving 1,286 B for the ledger's other lines. No schema or protocol change; no Deploy note. @@ -39,7 +39,7 @@ change; no Deploy note. #### Changed - **Build:** `scripts/check-editor-chunk-size.ts` budget is `main` at - P2.2 plus the D23 ledger (+17,254 B), and it prints exact bytes. + P2.2 plus the D23 ledger (+16,864 B), and it prints exact bytes. ### Desktop P2.1b: `local-session`, the batcher and `MemoryDocStore` diff --git a/docs/superpowers/specs/2026-11-15-desktop-documents-and-editor-details.md b/docs/superpowers/specs/2026-11-15-desktop-documents-and-editor-details.md index b67bfb6d..d160ac5f 100644 --- a/docs/superpowers/specs/2026-11-15-desktop-documents-and-editor-details.md +++ b/docs/superpowers/specs/2026-11-15-desktop-documents-and-editor-details.md @@ -68,7 +68,7 @@ These came out of the staff feasibility review. Each one was checked against the | Undo-gesture handler, **only if spike M18 shows native undo mutates the DOM** (D41, v8) | M19 | 80 B, conditional | | **Total** | | **1,580 B, or 1,660 B with the undo handler** | - - **Headroom:** 4,385 B real when D23 was decided (the 24,064 B budget less `main` at 19,679 B). By P2.2, `main` had shrunk to +15,674 B (1ed981e), so P2.2 set the fence at +17,254 B (15,674 + 1,580) in `scripts/check-editor-chunk-size.ts`; after P2.2 1,286 B remain for the other lines. + - **Headroom:** 4,385 B real when D23 was decided (the 24,064 B budget less `main` at 19,679 B). By P2.2, `main` had shrunk to +15,284 B (08b7663), so P2.2 set the fence at +16,864 B (15,284 + 1,580) in `scripts/check-editor-chunk-size.ts`; after P2.2 1,286 B remain for the other lines. - **Phones (D41):** M27's hardware-keyboard listener (shortcut glyphs) stays **out** of the editor chunk. - **Fencing:** P2.2 lowers `EDITOR_CHUNK_BUDGET_BYTES` to the size on `main` plus the ledger total, so unrelated work can't spend these bytes. Raising it needs an amendment to this rule. While D41's conditional 80 B undo line is unconfirmed, the fence is `main` + 1,580 B. If spike M18 confirms the line, the fence rises to `main` + 1,660 B with no further approval (pre-approved by D41). - **A PR that would go over its line** stops for a budget review. A line's unused bytes don't move to another line without an amendment. diff --git a/scripts/check-editor-chunk-size.ts b/scripts/check-editor-chunk-size.ts index 58c68f3a..604c9dff 100644 --- a/scripts/check-editor-chunk-size.ts +++ b/scripts/check-editor-chunk-size.ts @@ -21,11 +21,11 @@ import { join } from "node:path"; /** Gzipped bytes of the editor chunk group at `58a9d22`. */ export const EDITOR_CHUNK_BASELINE_BYTES = 377_888; /** - * Growth on `main` (1ed981e) when P2.2 set the fence: the smart toolbar v1 + * Growth on `main` (08b7663) when P2.2 set the fence: the smart toolbar v1 * and everything merged before the desktop work. Its old 23.5 KB budget * (contract A12) is replaced by the fence below. */ -export const EDITOR_CHUNK_MAIN_GROWTH_BYTES = 15_674; +export const EDITOR_CHUNK_MAIN_GROWTH_BYTES = 15_284; /** * The D23 editor-chunk ledger (desktop details spec §1 rule 5): every line * the desktop, library and v1 feature work may add to this chunk, each