Skip to content
Merged
32 changes: 32 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,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.

#### 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 (+16,864 B), and it prints exact bytes.

### Desktop P2.1b: `local-session`, the batcher and `MemoryDocStore`

The second half of desktop plan P2.1: the platform-neutral storage path that
Expand Down
30 changes: 27 additions & 3 deletions components/document-editor/document-editor-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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 {
Expand All @@ -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";

Expand Down Expand Up @@ -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<string>) => void;
onFilterChange: (state: HeadingFilterCallbackState) => void;
onTocUpdate: (anchors: TableOfContentData) => void;
Expand Down Expand Up @@ -176,7 +187,9 @@ function createHeadingFilterFoldAdapter() {
export function buildDocumentEditorExtensions({
documentId,
ydoc,
provider,
awareness,
getProvider,
canWrite,
onFoldChange,
onFilterChange,
onTocUpdate,
Expand Down Expand Up @@ -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,
Expand Down
45 changes: 36 additions & 9 deletions components/document-editor/document-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -145,12 +156,14 @@ const EDITOR_PROPS = {

function DocumentEditorContent({
ydoc,
awareness,
provider,
documentId,
onTitleChange,
initialContent,
playgroundRegenerateTrigger,
onPlaygroundRegenerate,
readOnly,
rejectedReason,
serverSynced,
}: DocumentEditorContentProps) {
Expand Down Expand Up @@ -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({
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -431,7 +454,8 @@ function DocumentEditorContent({
rejectedReason={rejectedReason}
/>
)}
<CollabStatusGroup />
{/* Its connection state opens the shared socket: only with a provider. */}
{provider && <CollabStatusGroup />}
</EditorContext.Provider>
</main>
);
Expand All @@ -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. */}
Expand All @@ -463,12 +488,14 @@ export function DocumentEditor({
return (
<DocumentEditorContent
ydoc={ydoc}
awareness={awareness}
provider={provider}
documentId={docId}
onTitleChange={onTitleChange}
initialContent={initialContent}
playgroundRegenerateTrigger={playgroundRegenerateTrigger}
onPlaygroundRegenerate={onPlaygroundRegenerate}
readOnly={readOnly}
rejectedReason={rejectedReason}
serverSynced={serverSynced}
/>
Expand Down
2 changes: 1 addition & 1 deletion docs/superpowers/specs/2026-11-15-desktop-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ Each port has its own types-only file in `lib/platform/` (P2.1): `doc-session.ts

**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.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 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 |
Expand All @@ -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,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.
Expand Down
81 changes: 81 additions & 0 deletions extensions/decoration-host/decoration-host.ts
Original file line number Diff line number Diff line change
@@ -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<ReturnType> {
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<DecorationHostOptions>({
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<DecorationSet>({
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);
},
},
}),
);
},
});
36 changes: 36 additions & 0 deletions extensions/write-gate/write-gate.ts
Original file line number Diff line number Diff line change
@@ -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<WriteGateOptions>({
name: "writeGate",

addProseMirrorPlugins() {
const { canWrite } = this.options;
return [
new Plugin({
filterTransaction: (tr) =>
!tr.docChanged || isChangeOrigin(tr) || canWrite(),
}),
];
},
});
Loading
Loading