Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(docx): collaborative DOCX editor with real-time sync (#7435)

Jacob Beckerman302ac39d4314
diff --git a/apps/docs/AI/mcp/tools/comment-on-document.mdx b/apps/docs/AI/mcp/tools/comment-on-document.mdx
index 3d84fa85c5..34af36ff16 100644
--- a/apps/docs/AI/mcp/tools/comment-on-document.mdx
+++ b/apps/docs/AI/mcp/tools/comment-on-document.mdx
@@ -6,7 +6,7 @@ description: >-
# CommentOnDocument
-Comment on a document on behalf of the user. Pass threadId to reply in an existing inline or Discussion thread; pass quote to start a new inline comment on a passage of a Macro markdown document; omit both to start a new Discussion comment on the document as a whole. Replies and Discussion comments support any document type. Only use this when explicitly asked to reply to or comment on a document. Thread ids come from the comments ReadContent returns. For an inline comment, quote the passage exactly as the document reads, as plain text without markdown syntax, within a single paragraph, heading, list item or table cell. If the passage appears more than once the tool refuses and lists each occurrence so you can choose one with occurrence, counting from 1; if the text is not found, read the document again rather than guessing. Do not combine threadId with quote. occurrence only applies with quote.
+Comment on a document on behalf of the user. Pass threadId to reply in an existing inline or Discussion thread; pass quote to start a new inline comment on a passage of a Macro markdown or Word (DOCX) document; omit both to start a new Discussion comment on the document as a whole. Replies and Discussion comments support any document type. Only use this when explicitly asked to reply to or comment on a document. Thread ids come from the comments ReadContent returns. For an inline comment, quote the passage exactly as the document reads, as plain text without markdown syntax, within a single paragraph, heading, list item or table cell. If the passage appears more than once the tool refuses and lists each occurrence so you can choose one with occurrence, counting from 1; if the text is not found, read the document again rather than guessing. Do not combine threadId with quote. occurrence only applies with quote.
## Parameters
@@ -15,5 +15,5 @@ Comment on a document on behalf of the user. Pass threadId to reply in an existi
| `documentId` | string | Yes | The id of the document to comment on. |
| `content` | string | Yes | Comment content in macro markdown format. This uses the same syntax as markdown documents. |
| `threadId` | string | No | The id of the inline or Discussion thread to reply in, from ReadContent. Cannot be combined with quote. Omit both threadId and quote to post a new Discussion comment on the document as a whole. |
-| `quote` | string | No | The passage to comment on, quoted exactly as the document reads: plain text without markdown syntax such as ** or link brackets. Keep it to the words the comment is about; a longer quote is more likely to be unique. Starts a new inline comment on a markdown document only. Cannot be combined with threadId. |
+| `quote` | string | No | The passage to comment on, quoted exactly as the document reads: plain text without markdown syntax such as ** or link brackets. Keep it to the words the comment is about; a longer quote is more likely to be unique. Starts a new inline comment on a markdown or Word (DOCX) document. Cannot be combined with threadId. |
| `occurrence` | integer | No | Which appearance of the quoted passage to comment on, counting from 1 in document order. Only applies with quote; only needed when the passage appears more than once. |
diff --git a/apps/web/package.json b/apps/web/package.json
index 613a2725ac..fff854e780 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -135,6 +135,7 @@
"detect-browser": "^5.3.0",
"diff": "^9.0.0",
"dinero.js": "2.0.0-alpha.8",
+ "docxodus": "12.6.5",
"effect": "^4.0.0-rc.111",
"email-validator": "^2.0.4",
"emojibase-data": "^17.0.0",
diff --git a/apps/web/scripts/docxodus-runtime.ts b/apps/web/scripts/docxodus-runtime.ts
new file mode 100644
index 0000000000..84827f98bb
--- /dev/null
+++ b/apps/web/scripts/docxodus-runtime.ts
@@ -0,0 +1,65 @@
+import { createReadStream, readdirSync, readFileSync, statSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import type { Plugin } from 'vite';
+
+/**
+ * Serve and emit the Docxodus .NET WebAssembly runtime.
+ *
+ * `dotnet.js` loads its sibling assemblies by name from its own directory, so
+ * the runtime has to keep its `_framework` layout and file names; bundling the
+ * files individually would hash them apart. The runtime is published under a
+ * versioned path (`docxodus/<version>/_framework/…`) so a deploy never mixes
+ * JavaScript wrappers from one release with assemblies from another.
+ * Precompressed `.br` twins are skipped: hosts negotiate compression.
+ */
+export function docxodusRuntime(): Plugin {
+ // The package exports only its ESM entry (dist/index.js); its root is two up.
+ const packageRoot = dirname(dirname(fileURLToPath(import.meta.resolve('docxodus'))));
+ const { version } = JSON.parse(
+ readFileSync(join(packageRoot, 'package.json'), 'utf8')
+ ) as { version: string };
+ const framework = join(packageRoot, 'dist/wasm/_framework');
+ const prefix = `docxodus/${version}/_framework/`;
+ const files = () =>
+ readdirSync(framework).filter(
+ (name) => !name.endsWith('.br') && statSync(join(framework, name)).isFile()
+ );
+ const contentType = (name: string) =>
+ name.endsWith('.wasm')
+ ? 'application/wasm'
+ : name.endsWith('.js')
+ ? 'text/javascript'
+ : name.endsWith('.json')
+ ? 'application/json'
+ : 'application/octet-stream';
+
+ return {
+ name: 'docxodus-runtime',
+ config: () => ({
+ define: {
+ 'import.meta.env.DOCXODUS_VERSION': JSON.stringify(version),
+ },
+ }),
+ configureServer(server) {
+ server.middlewares.use((req, res, next) => {
+ const path = req.url?.split('?')[0] ?? '';
+ const at = path.indexOf(prefix);
+ if (at < 0) return next();
+ const name = path.slice(at + prefix.length);
+ if (!files().includes(name)) return next();
+ res.setHeader('Content-Type', contentType(name));
+ res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
+ createReadStream(join(framework, name)).pipe(res);
+ });
+ },
+ generateBundle() {
+ for (const name of files())
+ this.emitFile({
+ type: 'asset',
+ fileName: `${prefix}${name}`,
+ source: readFileSync(join(framework, name)),
+ });
+ },
+ };
+}
diff --git a/apps/web/src/features/block-write/DocxBlock.tsx b/apps/web/src/features/block-write/DocxBlock.tsx
new file mode 100644
index 0000000000..81786e7e6e
--- /dev/null
+++ b/apps/web/src/features/block-write/DocxBlock.tsx
@@ -0,0 +1,264 @@
+import {
+ ResponsiveBlockToolbar,
+ ResponsivePermissionsBadge,
+} from '@components/app/ResponsiveBlockToolbar';
+import {
+ SplitHeaderLeft,
+ SplitHeaderRight,
+} from '@components/app/split-layout/components/SplitHeader';
+import { BlockItemSplitLabel } from '@components/app/split-layout/components/SplitLabel';
+import { useBlockId } from '@core/block';
+import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';
+import { BlockLiveIndicators } from '@core/component/LiveIndicators';
+import { toast } from '@core/component/Toast/Toast';
+import {
+ getShareDrawerRecipientInput,
+ ShareTrigger,
+} from '@core/component/TopBar/ShareButton';
+import { useShareModal } from '@core/component/TopBar/shareModal';
+import { useUserId } from '@core/context/user';
+import { blockDataSignal } from '@core/internal/BlockLoader';
+import { EntityDiscussion } from '@core/messages/EntityDiscussion';
+import { blockMetadataSignal } from '@core/signal/load';
+import {
+ useCanComment,
+ useCanEdit,
+ useGetPermissions,
+ useIsDocumentOwner,
+} from '@core/signal/permissions';
+import { getDisplayName, tryMacroId } from '@core/user';
+import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
+import { downloadFile } from '@filesystem/download';
+import IconShared from '@icon/share.svg';
+import { useMessageRootsQuery } from '@queries/messages/document-messages';
+import { Badge } from '@ui';
+import {
+ createMemo,
+ createSignal,
+ Match,
+ onMount,
+ Show,
+ Switch,
+} from 'solid-js';
+import type { DocxBlockData } from './definition';
+import {
+ buildDocxSeed,
+ connectDocxSync,
+ docxSyncExists,
+ fetchOriginalDocx,
+ initializeDocxSync,
+} from './queries/docx-document';
+import { createDocxSession } from './queries/docx-session';
+import { type DocxodusRuntime, loadDocxodus } from './queries/docxodus-runtime';
+import { DocxCommentMargin, DocxDetachedComments } from './views/DocxComments';
+import { DocxEditorView } from './views/DocxEditorView';
+
+const DOCX_MIME =
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
+
+function displayName(userId: string | undefined) {
+ return getDisplayName(tryMacroId(userId ?? ''), {
+ emailFallback: 'local-part',
+ });
+}
+
+/** Production composition of the collaborative DOCX editor. */
+export default function DocxBlock(props: { share?: string }) {
+ const documentId = useBlockId();
+ const name = useBlockDocumentName('Document');
+ const canEdit = useCanEdit();
+ const canComment = useCanComment();
+ const isOwner = useIsDocumentOwner();
+ const userId = useUserId();
+ const permissions = useGetPermissions();
+ const openShare = useShareModal(() => ({
+ id: documentId,
+ blockAlias: 'write',
+ itemType: 'document',
+ name: name() ?? '',
+ userPermissions: permissions(),
+ owner: blockMetadataSignal()?.owner,
+ }));
+ onMount(() => {
+ if (props.share === 'true') openShare();
+ });
+ const data = () => {
+ const value = blockDataSignal.get() as
+ | (DocxBlockData & { __block?: string })
+ | undefined;
+ return value?.__block === 'write' && 'documentMetadata' in value
+ ? value
+ : undefined;
+ };
+ const fileName = () => {
+ const base = name() || 'Document';
+ return /\.docx$/i.test(base) ? base : `${base}.docx`;
+ };
+ const parent = () => ({ type: 'document' as const, id: documentId });
+ const roots = useMessageRootsQuery(parent);
+ // Gated: reading a pending query's data would suspend and blank the editor.
+ const rootThreads = () => (roots.isSuccess ? (roots.data ?? []) : []);
+ // A plain signal, not a resource: reading a pending resource would suspend
+ // the block and blank it while the engine streams in.
+ const [runtime, setRuntime] = createSignal<DocxodusRuntime>();
+ const [runtimeError, setRuntimeError] = createSignal(false);
+ loadDocxodus().then(setRuntime, (error: unknown) => {
+ console.error('DOCX engine failed to load', error);
+ setRuntimeError(true);
+ });
+ const reportError = (error: unknown) => {
+ console.error('DOCX editor error', error);
+ toast.failure(
+ error instanceof Error ? error.message : 'Something went wrong'
+ );
+ };
+
+ return (
+ <DocumentBlockContainer>
+ <div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden">
+ <SplitHeaderLeft>
+ <BlockItemSplitLabel
+ trailingBadges={
+ <Badge variant="outline" size="xs">
+ Beta
+ </Badge>
+ }
+ />
+ </SplitHeaderLeft>
+ <SplitHeaderRight>
+ <BlockLiveIndicators />
+ </SplitHeaderRight>
+ <ResponsivePermissionsBadge />
+ <ResponsiveBlockToolbar
+ id={documentId}
+ itemType="document"
+ name={name()}
+ ops={[{ op: 'rename' }, { op: 'moveToProject' }, { op: 'delete' }]}
+ tools={[
+ {
+ group: 'sharing',
+ label: 'Share',
+ icon: IconShared,
+ action: openShare,
+ buttonComponent: () => <ShareTrigger onClick={openShare} />,
+ focusTarget: getShareDrawerRecipientInput,
+ },
+ ]}
+ />
+ <Show when={data()} keyed>
+ {(loaded) => {
+ const session = createDocxSession({
+ documentId,
+ userId: userId(),
+ canEdit,
+ canComment,
+ exists: () => docxSyncExists(documentId),
+ fetchOriginal: () => fetchOriginalDocx(documentId),
+ buildSeed: buildDocxSeed,
+ initialize: (snapshot) =>
+ initializeDocxSync(documentId, snapshot),
+ connect: () =>
+ connectDocxSync(documentId, loaded.token, loaded.authorization),
+ });
+ const state = session.state;
+ // Remount the editor only when the collaborative document is replaced.
+ const target = createMemo(
+ () => {
+ const current = state();
+ if (current.t === 'ready')
+ return { doc: current.doc, original: undefined };
+ if (current.t === 'original')
+ return { doc: null, original: current.bytes };
+ return undefined;
+ },
+ undefined,
+ {
+ equals: (a, b) =>
+ a?.doc === b?.doc && a?.original === b?.original,
+ }
+ );
+ return (
+ <Switch>
+ <Match when={state().t === 'error' || runtimeError()}>
+ <div class="p-6 text-sm text-failure">
+ {(() => {
+ const current = state();
+ return current.t === 'error'
+ ? current.message
+ : 'The document editor could not be loaded.';
+ })()}
+ </div>
+ </Match>
+ <Match when={!runtime() || !target()}>
+ <div class="p-6 text-sm text-ink-muted">
+ Opening document…
+ </div>
+ </Match>
+ <Match when={runtime()}>
+ {(engine) => (
+ <Show when={target()} keyed>
+ {({ doc, original }) => (
+ <DocxEditorView
+ runtime={engine()}
+ doc={doc}
+ original={original}
+ canEdit={!!doc && canEdit()}
+ canComment={() => !!doc && canComment()}
+ author={displayName(userId()) || 'Macro user'}
+ fileName={fileName()}
+ peers={session.peers}
+ displayName={displayName}
+ onSelection={session.setSelection}
+ subscribeRemote={session.onRemoteChange}
+ commentRoots={doc ? rootThreads : undefined}
+ margin={(context) => (
+ <DocxCommentMargin
+ documentId={documentId}
+ comments={context.comments}
+ editorRoot={context.editorRoot}
+ margin={context.margin}
+ revision={context.revision}
+ canComment={() => !!doc && canComment()}
+ isOwner={isOwner}
+ userId={userId}
+ />
+ )}
+ footer={(comments) => (
+ <>
+ <DocxDetachedComments
+ documentId={documentId}
+ threads={comments.detached()}
+ canComment={canComment}
+ isOwner={isOwner}
+ />
+ <EntityDiscussion
+ parent={parent()}
+ canWrite={canComment()}
+ canModerate={isOwner()}
+ link={{ type: 'write', id: documentId }}
+ label="Discussion"
+ />
+ </>
+ )}
+ onDownload={(bytes) =>
+ downloadFile(
+ new Blob([bytes.slice().buffer], {
+ type: DOCX_MIME,
+ }),
+ fileName()
+ )
+ }
+ onError={reportError}
+ />
+ )}
+ </Show>
+ )}
+ </Match>
+ </Switch>
+ );
+ }}
+ </Show>
+ </div>
+ </DocumentBlockContainer>
+ );
+}
diff --git a/apps/web/src/features/block-write/browser-test/README.md b/apps/web/src/features/block-write/browser-test/README.md
new file mode 100644
index 0000000000..cb0998c96d
--- /dev/null
+++ b/apps/web/src/features/block-write/browser-test/README.md
@@ -0,0 +1,28 @@
+# DOCX editor browser tests
+
+These tests run the production `DocxEditorView` in real Chromium against the
+real sync service. They do not use the app shell. The compiled Rust sync
+Worker runs in Miniflare (`sync-server.ts`), so they need no dev login,
+backend or Docker.
+
+- `fixture.tsx` mounts one editor per tab with `createDocxSession`. Its
+ comment threads are stored in a Loro map in place of the message service,
+ and it exposes `window.docxFixture` for assertions.
+- `collaboration.browser.e2e.ts` opens several people on one document and
+ tests:
+ - live and concurrent edits, formatting and lists;
+ - read-only viewers and header edits;
+ - an offline merge;
+ - comments, including table cells;
+ - the downloaded `.docx`.
+
+```sh
+(\cd services/sync-service && just worker-build) # once, builds build/worker/shim.mjs
+\cd apps/web
+bunx playwright test -c src/features/block-write/browser-test/playwright.config.ts
+```
+
+Set `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` when Playwright's bundled Chromium
+is not installed. The fixture serves on port 3018 and must be reached as
+`localhost`, because the sync Worker only accepts `http://localhost:3000-3999`
+origins.
diff --git a/apps/web/src/features/block-write/browser-test/collaboration.browser.e2e.ts b/apps/web/src/features/block-write/browser-test/collaboration.browser.e2e.ts
new file mode 100644
index 0000000000..5918a03909
--- /dev/null
+++ b/apps/web/src/features/block-write/browser-test/collaboration.browser.e2e.ts
@@ -0,0 +1,361 @@
+import { readFile } from 'node:fs/promises';
+import { expect, type Page, test } from '@playwright/test';
+import { strFromU8, unzipSync } from 'fflate';
+import type { Miniflare } from 'miniflare';
+import { fixtureUrl, startSyncServer } from './sync-server';
+
+let server: Miniflare;
+let serverUrl: string;
+// The sync Worker allows localhost origins (ports 3000-3999).
+const BASE = 'http://localhost:3018';
+const ALICE = 'macro|[email protected]';
+const BOB = 'macro|[email protected]';
+const SHOTS = process.env.DOCX_E2E_SHOTS;
+
+test.beforeAll(async () => {
+ ({ server, url: serverUrl } = await startSyncServer());
+});
+test.afterAll(async () => {
+ await server?.dispose();
+});
+
+async function open(page: Page, documentId: string, user: string, extra = {}) {
+ // Text painted by the comment highlights, for assertions.
+ await page.addInitScript(() => {
+ globalThis.highlightedText = () =>
+ Array.from(CSS.highlights.values())
+ .flatMap((highlight) => Array.from(highlight))
+ .map((range) => range.toString())
+ .join('\n');
+ });
+ await page.goto(fixtureUrl(BASE, serverUrl, documentId, user, extra));
+ await expect
+ .poll(() => page.evaluate(() => window.docxFixture?.ready() ?? false), {
+ timeout: 60_000,
+ })
+ .toBe(true);
+ await expect
+ .poll(() => page.evaluate(() => window.docxFixture?.status()))
+ .toBe('connected');
+}
+
+const paragraphs = (page: Page) =>
+ page.evaluate(() => window.docxFixture?.paragraphs() ?? []);
+
+/** The editable paragraph whose text starts with `prefix`. */
+const paragraph = (page: Page, prefix: string) =>
+ page
+ .locator('.docx-body-flow [data-anchor][contenteditable="true"]')
+ .filter({ hasText: prefix })
+ .first();
+
+/** Select a whole paragraph's text, as a user dragging across it would. */
+async function selectParagraph(page: Page, prefix: string) {
+ await paragraph(page, prefix).click();
+ await page.evaluate((text) => {
+ const block = Array.from(
+ document.querySelectorAll<HTMLElement>(
+ '.docx-body-flow [data-anchor][contenteditable="true"]'
+ )
+ ).find((element) => element.textContent?.includes(text));
+ if (!block) throw new Error(`no paragraph ${text}`);
+ const range = document.createRange();
+ range.selectNodeContents(block);
+ const selection = window.getSelection()!;
+ selection.removeAllRanges();
+ selection.addRange(range);
+ }, prefix);
+}
+
+/** Computed weight of the first text run in the paragraph containing `text`. */
+const fontWeightAt = (page: Page, text: string) =>
+ page.evaluate((needle) => {
+ const block = Array.from(
+ document.querySelectorAll<HTMLElement>('.docx-body-flow [data-anchor]')
+ ).find((element) => element.textContent?.includes(needle));
+ const walker =
+ block && document.createTreeWalker(block, NodeFilter.SHOW_TEXT);
+ const node = walker?.nextNode();
+ return node?.parentElement
+ ? getComputedStyle(node.parentElement).fontWeight
+ : '';
+ }, text);
+
+declare global {
+ function highlightedText(): string;
+}
+
+async function caretAtEnd(page: Page, prefix: string) {
+ const target = paragraph(page, prefix);
+ await target.click();
+ await page.keyboard.press('End');
+}
+
+test('two people edit the same DOCX live through the sync service', async ({
+ browser,
+}) => {
+ const documentId = crypto.randomUUID();
+ const contexts = await Promise.all([
+ browser.newContext(),
+ browser.newContext(),
+ ]);
+ const [alice, bob] = await Promise.all(
+ contexts.map((context) => context.newPage())
+ );
+ for (const page of [alice, bob])
+ page.on('console', (message) => {
+ if (message.type() === 'error')
+ console.log(`[${page === alice ? 'alice' : 'bob'}]`, message.text());
+ });
+ try {
+ // Alice opens an unseen document: her client seeds it from the upload.
+ await open(alice, documentId, ALICE);
+ await open(bob, documentId, BOB);
+ expect(await paragraphs(bob)).toEqual(await paragraphs(alice));
+ if (SHOTS) await alice.screenshot({ path: `${SHOTS}/01-opened.png` });
+
+ // Typing is committed while Alice pauses and reaches Bob without a blur.
+ await caretAtEnd(alice, 'This Agreement shall remain');
+ await alice.keyboard.type(' Renewal requires mutual written consent.');
+ await expect
+ .poll(async () => (await paragraphs(bob)).join('\n'))
+ .toContain('Renewal requires mutual written consent.');
+
+ // Concurrent edits to different paragraphs both survive.
+ await caretAtEnd(alice, '"Representatives" means');
+ await alice.keyboard.type(' [alice]');
+ await caretAtEnd(bob, 'This Agreement shall be governed');
+ await bob.keyboard.type(' [bob]');
+ await alice.locator('body').press('Escape');
+ for (const page of [alice, bob]) {
+ await expect
+ .poll(async () => (await paragraphs(page)).join('\n'))
+ .toContain('[alice]');
+ await expect
+ .poll(async () => (await paragraphs(page)).join('\n'))
+ .toContain('[bob]');
+ }
+
+ // Enter splits a paragraph for everyone.
+ const before = (await paragraphs(alice)).length;
+ await caretAtEnd(bob, 'IN WITNESS WHEREOF');
+ await bob.keyboard.press('Enter');
+ await bob.keyboard.type('Signed by the parties below.');
+ await expect
+ .poll(async () => (await paragraphs(alice)).length)
+ .toBe(before + 1);
+ await expect
+ .poll(async () => (await paragraphs(alice)).join('\n'))
+ .toContain('Signed by the parties below.');
+
+ // Each sees the other's caret.
+ await expect(alice.locator('[data-docx-peer]')).toHaveCount(1);
+ await expect(alice.locator('[data-docx-peer]')).toContainText('Bob');
+ if (SHOTS)
+ await alice.screenshot({ path: `${SHOTS}/02-collaborating.png` });
+
+ // Toolbar formatting propagates.
+ await selectParagraph(alice, 'This Agreement shall be governed');
+ await alice.getByRole('button', { name: 'Bold' }).click();
+ await expect
+ .poll(() => fontWeightAt(bob, 'This Agreement shall be governed'))
+ .toBe('700');
+
+ // A list toggle changes the numbering part: Bob's editor remounts on it.
+ await paragraph(alice, '"Confidential Information" means').click();
+ await alice.getByRole('button', { name: 'Bulleted list' }).click();
+ await expect
+ .poll(() =>
+ bob.evaluate(
+ () =>
+ Array.from(
+ document.querySelectorAll('.docx-body-flow [data-list-marker]')
+ ).length
+ )
+ )
+ .toBeGreaterThan(3);
+
+ // Comments: select any line, comment, and the thread appears beside it
+ // for both collaborators, with the text highlighted.
+ await selectParagraph(alice, 'Each party shall use');
+ await alice.getByRole('button', { name: 'Comment on selection' }).click();
+ await alice
+ .getByRole('textbox', { name: 'Comment text' })
+ .fill('Limit this to the evaluation period?');
+ await alice.getByRole('button', { name: 'Comment', exact: true }).click();
+ await expect
+ .poll(() =>
+ bob.evaluate(
+ () => Object.keys(window.docxFixture?.marks() ?? {}).length
+ )
+ )
+ .toBe(1);
+ for (const page of [alice, bob]) {
+ await expect(page.locator('[data-docx-thread]')).toContainText(
+ 'Limit this to the evaluation period?'
+ );
+ await expect
+ .poll(() => page.evaluate(() => highlightedText()))
+ .toContain('Each party shall use the Confidential Information');
+ }
+ // The floating button comments on a selection inside a table cell too.
+ await selectParagraph(bob, 'Retainer');
+ await bob
+ .locator(
+ '[data-docx-comment-button] button, button[data-docx-comment-button]'
+ )
+ .first()
+ .click();
+ await bob
+ .getByRole('textbox', { name: 'Comment text' })
+ .fill('Confirm the retainer amount.');
+ await bob.getByRole('button', { name: 'Comment', exact: true }).click();
+ await expect(alice.locator('[data-docx-thread]')).toHaveCount(2);
+ // Edits to commented text keep the thread on it.
+ await caretAtEnd(alice, 'Each party shall use');
+ await alice.keyboard.type(' during the term');
+ await expect
+ .poll(() => bob.evaluate(() => highlightedText()), { timeout: 30_000 })
+ .toContain(
+ 'evaluating a potential business relationship between the parties.'
+ );
+ if (SHOTS) await bob.screenshot({ path: `${SHOTS}/03-comments.png` });
+
+ // Download produces a clean .docx carrying everyone's edits.
+ const [download] = await Promise.all([
+ bob.waitForEvent('download'),
+ bob.getByRole('button', { name: 'Download .docx' }).click(),
+ ]);
+ if (SHOTS) await download.saveAs(`${SHOTS}/edited.docx`);
+ const files = unzipSync(
+ new Uint8Array(await readFile((await download.path())!))
+ );
+ const documentXml = strFromU8(files['word/document.xml']);
+ expect(documentXml).toContain('Renewal requires mutual written consent.');
+ expect(documentXml).toContain('Signed by the parties below.');
+ expect(documentXml).not.toContain('Unid=');
+ // Comments are Macro threads: the Word file itself carries no comments.
+ expect(files['word/comments.xml']).toBeUndefined();
+
+ // Bob reloads and gets the merged document back from the server.
+ const merged = await paragraphs(alice);
+ await bob.reload();
+ await expect
+ .poll(() => bob.evaluate(() => window.docxFixture?.ready() ?? false), {
+ timeout: 60_000,
+ })
+ .toBe(true);
+ await expect.poll(() => paragraphs(bob)).toEqual(merged);
+ if (SHOTS) await alice.screenshot({ path: `${SHOTS}/04-final.png` });
+ } finally {
+ await Promise.all(contexts.map((context) => context.close()));
+ }
+});
+
+test('viewers follow along read-only, and header edits reach them', async ({
+ browser,
+}) => {
+ const documentId = crypto.randomUUID();
+ const contexts = await Promise.all([
+ browser.newContext(),
+ browser.newContext(),
+ ]);
+ const [alice, viewer] = await Promise.all(
+ contexts.map((context) => context.newPage())
+ );
+ try {
+ await open(alice, documentId, ALICE, { fixture: 'complex-msa.docx' });
+ await open(viewer, documentId, BOB, {
+ readonly: '1',
+ fixture: 'complex-msa.docx',
+ });
+ await expect(
+ viewer.locator('.docx-body-flow [contenteditable="true"]')
+ ).toHaveCount(0);
+ await expect(viewer.getByRole('button', { name: 'Bold' })).toHaveCount(0);
+
+ // A body edit in a document with a table, image and content control.
+ await caretAtEnd(alice, 'Either party may terminate');
+ await alice.keyboard.type(' Termination notices must be in writing.');
+ await expect
+ .poll(async () => (await paragraphs(viewer)).join('\n'))
+ .toContain('Termination notices must be in writing.');
+
+ // Header text lives in its own package part.
+ const header = alice
+ .locator('[data-hf-band="header"] [contenteditable="true"]')
+ .first();
+ await header.click();
+ await alice.keyboard.press('End');
+ await alice.keyboard.type(' (DRAFT)');
+ await alice.locator('.docx-body-flow [data-anchor]').first().click();
+ // Viewers read the print layout: every page repeats the header.
+ await expect(viewer.locator('.docx-editor-host')).toContainText(
+ 'CONFIDENTIAL - Acme / Globex (DRAFT)'
+ );
+ } finally {
+ await Promise.all(contexts.map((context) => context.close()));
+ }
+});
+
+test('edits made offline merge when the connection returns', async ({
+ browser,
+}) => {
+ const documentId = crypto.randomUUID();
+ const contexts = await Promise.all([
+ browser.newContext(),
+ browser.newContext(),
+ ]);
+ const [alice, bob] = await Promise.all(
+ contexts.map((context) => context.newPage())
+ );
+ // Route Bob's sync socket through the test so the network can be cut.
+ let offline = false;
+ const sockets: Array<{ close: () => Promise<void> }> = [];
+ await bob.routeWebSocket(/\/connect\?/, (socket) => {
+ if (offline) {
+ void socket.close();
+ return;
+ }
+ socket.connectToServer();
+ sockets.push(socket);
+ });
+ try {
+ await open(alice, documentId, ALICE);
+ await open(bob, documentId, BOB);
+ offline = true;
+ await Promise.all(sockets.splice(0).map((socket) => socket.close()));
+ await expect
+ .poll(() => bob.evaluate(() => window.docxFixture?.status()))
+ .not.toBe('connected');
+
+ await caretAtEnd(bob, 'This Agreement shall remain');
+ await bob.keyboard.type(' [written offline]');
+ await caretAtEnd(alice, '"Representatives" means');
+ await alice.keyboard.type(' [written online]');
+ await expect
+ .poll(async () => (await paragraphs(alice)).join('\n'))
+ .toContain('[written online]');
+ // Bob keeps working locally while disconnected.
+ await expect
+ .poll(async () => (await paragraphs(bob)).join('\n'))
+ .toContain('[written offline]');
+
+ offline = false;
+ for (const page of [alice, bob]) {
+ await expect
+ .poll(async () => (await paragraphs(page)).join('\n'), {
+ timeout: 60_000,
+ })
+ .toContain('[written offline]');
+ await expect
+ .poll(async () => (await paragraphs(page)).join('\n'), {
+ timeout: 60_000,
+ })
+ .toContain('[written online]');
+ }
+ expect(await paragraphs(bob)).toEqual(await paragraphs(alice));
+ } finally {
+ await Promise.all(contexts.map((context) => context.close()));
+ }
+});
diff --git a/apps/web/src/features/block-write/browser-test/fixture.tsx b/apps/web/src/features/block-write/browser-test/fixture.tsx
new file mode 100644
index 0000000000..f3b3df538d
--- /dev/null
+++ b/apps/web/src/features/block-write/browser-test/fixture.tsx
@@ -0,0 +1,387 @@
+import '@fontsource-variable/inter';
+import '../../../index.css';
+import { noopChatter } from '@macro-inc/collaboration/collab/chatter';
+import type { SnapshotStore } from '@macro-inc/collaboration/collab/snapshot-store';
+import { InMemoryWALStore } from '@macro-inc/collaboration/collab/wal';
+import { InitializeFromSnapshotRequest } from '@macro-inc/collaboration/sync-service/generated/schema';
+import { createSyncSocket } from '@macro-inc/collaboration/sync-service/socket';
+import {
+ mapToSyncStatus,
+ SyncServiceSource,
+} from '@macro-inc/collaboration/sync-service/source';
+import { createWebsocketStateSignal } from '@macro-inc/collaboration/websocket/solid/state-signal';
+import type { MessageListItem } from '@service-storage/messages';
+import type { LoroDoc } from 'loro-crdt';
+import { createSignal, onCleanup, Show } from 'solid-js';
+import { render } from 'solid-js/web';
+import { readCommentMarks } from '../core/comment-marks';
+import { readDocxState } from '../core/docx-loro';
+import { buildSeedSnapshot } from '../core/docx-seed';
+import ComplexMsa from '../core/fixtures/complex-msa.docx?url';
+import MutualNda from '../core/fixtures/mutual-nda.docx?url';
+import { contentText } from '../core/text-offsets';
+import type { LocatedThread } from '../primitives/create-docx-comments';
+import type { createDocxEditor } from '../primitives/create-docx-editor';
+import { createDocxSession } from '../queries/docx-session';
+import {
+ type DocxodusRuntime,
+ loadDocxodus,
+} from '../queries/docxodus-runtime';
+import { DocxEditorView } from '../views/DocxEditorView';
+import { DocxMarginLayout } from '../views/DocxMarginLayout';
+
+type Handle = ReturnType<typeof createDocxEditor>;
+
+declare global {
+ interface Window {
+ docxFixture?: {
+ status: () => string;
+ ready: () => boolean;
+ paragraphs: () => string[];
+ sharedOrder: () => string[];
+ marks: () => Record<string, unknown>;
+ handle: () => Handle | undefined;
+ };
+ }
+}
+
+const FIXTURES: Record<string, string> = {
+ 'mutual-nda.docx': MutualNda,
+ 'complex-msa.docx': ComplexMsa,
+};
+
+class MemorySnapshots implements SnapshotStore<Uint8Array> {
+ private value: Uint8Array | null = null;
+ async save(snapshot: Uint8Array) {
+ this.value = snapshot;
+ }
+ async load() {
+ return this.value;
+ }
+ async delete() {
+ this.value = null;
+ }
+}
+
+const params = new URLSearchParams(location.search);
+const documentId = params.get('document') ?? 'local';
+const worker = params.get('worker') ?? '';
+const socketUrl = params.get('socket') ?? '';
+const token = params.get('token') ?? '';
+const user = params.get('user') ?? 'macro|[email protected]';
+const readonly = params.has('readonly');
+const fixture =
+ FIXTURES[params.get('fixture') ?? 'mutual-nda.docx'] ?? MutualNda;
+
+const shortName = (id: string | undefined) =>
+ (id ?? '')
+ .replace(/^macro\|/, '')
+ .split('@')[0]
+ .replace(/^./, (c) => c.toUpperCase());
+
+/**
+ * Fixture-only stand-in for the message store: threads live in a side map
+ * of the synced document so every collaborator sees them. Production threads
+ * come from the shared messages API.
+ */
+const FIXTURE_THREADS = 'fixtureThreads';
+
+function watchFixtureThreads(
+ doc: LoroDoc,
+ set: (roots: MessageListItem[]) => void
+) {
+ const map = doc.getMap(FIXTURE_THREADS);
+ const read = () =>
+ set(
+ map
+ .keys()
+ .map((key) => JSON.parse(String(map.get(key))) as MessageListItem)
+ .sort((a, b) => a.created_at.localeCompare(b.created_at))
+ );
+ read();
+ onCleanup(map.subscribe(read));
+}
+
+function postFixtureThread(doc: LoroDoc, markId: string, content: string) {
+ const now = new Date().toISOString();
+ doc.getMap(FIXTURE_THREADS).set(
+ markId,
+ JSON.stringify({
+ id: markId,
+ content,
+ sender_id: user,
+ created_at: now,
+ updated_at: now,
+ attachments: [],
+ mentions: [],
+ reactions: [],
+ parent: { type: 'document', id: documentId },
+ state: {
+ anchor: { type: 'markdown', mark_id: markId },
+ resolved: false,
+ root_id: markId,
+ created_at: now,
+ updated_at: now,
+ user_id: user,
+ },
+ thread: { preview: [], reply_count: 0 },
+ })
+ );
+ doc.commit();
+}
+
+function resolveFixtureThread(doc: LoroDoc, id: string, resolved: boolean) {
+ const map = doc.getMap(FIXTURE_THREADS);
+ const root = JSON.parse(String(map.get(id))) as MessageListItem;
+ map.set(id, JSON.stringify({ ...root, state: { ...root.state, resolved } }));
+ doc.commit();
+}
+
+function FixtureThreadCard(props: {
+ thread: LocatedThread;
+ active: boolean;
+ onPost: (text: string) => Promise<unknown>;
+ onCancel: () => void;
+ onResolve: (resolved: boolean) => void;
+}) {
+ const [text, setText] = createSignal('');
+ return (
+ <div
+ data-fixture-thread={props.thread.root ? props.thread.id : 'draft'}
+ class="rounded-xl border border-edge bg-surface p-3 text-sm shadow-md"
+ classList={{ '-translate-x-2': props.active }}
+ >
+ <Show
+ when={props.thread.root}
+ fallback={
+ <form
+ class="flex flex-col gap-2"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void props.onPost(text());
+ }}
+ >
+ <textarea
+ aria-label="Comment text"
+ placeholder="Leave a comment..."
+ class="min-h-16 rounded-lg border border-edge-muted bg-input p-2 text-sm text-ink"
+ onInput={(event) => setText(event.currentTarget.value)}
+ />
+ <div class="flex justify-end gap-2">
+ <button
+ type="button"
+ class="rounded-md px-2 py-1 text-xs text-ink-muted"
+ onClick={() => props.onCancel()}
+ >
+ Cancel
+ </button>
+ <button
+ type="submit"
+ class="rounded-md bg-accent px-3 py-1 text-xs text-accent-contrast"
+ >
+ Comment
+ </button>
+ </div>
+ </form>
+ }
+ >
+ {(root) => (
+ <div class="flex flex-col gap-1">
+ <div class="flex items-center gap-2">
+ <span class="flex size-5 items-center justify-center rounded-full bg-accent text-[10px] font-semibold text-accent-contrast">
+ {shortName(root().sender_id).slice(0, 1)}
+ </span>
+ <span class="text-xs font-medium text-ink">
+ {shortName(root().sender_id)}
+ </span>
+ <Show when={root().state.resolved}>
+ <span class="text-xs text-success">Resolved</span>
+ </Show>
+ </div>
+ <p class="text-sm text-ink">{root().content}</p>
+ <Show when={props.active}>
+ <div class="flex justify-end">
+ <button
+ type="button"
+ class="rounded-md px-2 py-1 text-xs text-ink-muted"
+ onClick={(event) => {
+ event.stopPropagation();
+ props.onResolve(!root().state.resolved);
+ }}
+ >
+ {root().state.resolved ? 'Reopen' : 'Resolve'}
+ </button>
+ </div>
+ </Show>
+ </div>
+ )}
+ </Show>
+ </div>
+ );
+}
+
+function Fixture() {
+ const [runtime, setRuntime] = createSignal<DocxodusRuntime>();
+ const [handle, setHandle] = createSignal<Handle>();
+ const [roots, setRoots] = createSignal<MessageListItem[]>([]);
+ void loadDocxodus().then(setRuntime);
+
+ const session = createDocxSession({
+ documentId,
+ userId: user,
+ canEdit: () => !readonly,
+ canComment: () => true,
+ exists: async () =>
+ (
+ await fetch(`${worker}document/${documentId}/exists`, {
+ method: 'HEAD',
+ })
+ ).ok,
+ fetchOriginal: async () =>
+ new Uint8Array(await (await fetch(fixture)).arrayBuffer()),
+ buildSeed: async (original) =>
+ buildSeedSnapshot(
+ (await loadDocxodus()).exports.DocxSessionBridge,
+ original
+ ),
+ initialize: async (snapshot) => {
+ const response = await fetch(
+ `${worker}document/${documentId}/initialize`,
+ {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${token}` },
+ body: new Uint8Array(
+ InitializeFromSnapshotRequest.encode({ snapshot })
+ ),
+ }
+ );
+ if (!response.ok)
+ throw new Error(`initialize failed: ${response.status}`);
+ },
+ connect: () => {
+ const socket = createSyncSocket(socketUrl);
+ const state = createWebsocketStateSignal(socket);
+ const source = new SyncServiceSource(socket, documentId, {
+ status: () => mapToSyncStatus(state()),
+ });
+ return { source, doInitialSync: source.doInitialSync };
+ },
+ persistence: {
+ snapshots: new MemorySnapshots(),
+ wal: new InMemoryWALStore<Uint8Array>(),
+ // Collaborators reach each other only through the sync service, even
+ // when two of them share an origin (the side-by-side demo stage).
+ makeChatter: () => noopChatter(),
+ },
+ });
+
+ window.docxFixture = {
+ status: session.status,
+ ready: () => !!handle(),
+ paragraphs: () =>
+ Array.from(
+ document.querySelectorAll<HTMLElement>('.docx-body-flow [data-anchor]')
+ )
+ .filter((element) => !element.querySelector('[data-anchor]'))
+ .map(contentText),
+ sharedOrder: () => {
+ const state = session.state();
+ return state.t === 'ready' ? readDocxState(state.doc).order : [];
+ },
+ marks: () => {
+ const state = session.state();
+ return state.t === 'ready'
+ ? Object.fromEntries(readCommentMarks(state.doc))
+ : {};
+ },
+ handle,
+ };
+ onCleanup(() => Reflect.deleteProperty(window, 'docxFixture'));
+
+ return (
+ <main class="h-screen w-screen overflow-hidden bg-page font-sans text-ink">
+ <Show
+ when={(() => {
+ const state = session.state();
+ const engine = runtime();
+ return engine && state.t === 'ready'
+ ? { engine, doc: state.doc }
+ : undefined;
+ })()}
+ keyed
+ fallback={
+ <div class="p-6 text-sm text-ink-muted" data-fixture-state>
+ {session.state().t}
+ </div>
+ }
+ >
+ {(ready) => {
+ watchFixtureThreads(ready.doc, setRoots);
+ return (
+ <DocxEditorView
+ runtime={ready.engine}
+ doc={ready.doc}
+ canEdit={!readonly}
+ canComment={() => true}
+ author={shortName(user)}
+ fileName="fixture.docx"
+ peers={session.peers}
+ displayName={shortName}
+ onSelection={session.setSelection}
+ subscribeRemote={session.onRemoteChange}
+ commentRoots={roots}
+ onReady={setHandle}
+ onDownload={(bytes) => {
+ const url = URL.createObjectURL(
+ new Blob([bytes.slice().buffer], {
+ type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ })
+ );
+ const anchor = document.createElement('a');
+ anchor.href = url;
+ anchor.download = 'fixture.docx';
+ anchor.click();
+ setTimeout(() => URL.revokeObjectURL(url), 1_000);
+ }}
+ onError={(error) => console.error('[docx-fixture]', error)}
+ margin={(context) => (
+ <DocxMarginLayout
+ comments={context.comments}
+ editorRoot={context.editorRoot}
+ margin={context.margin}
+ revision={context.revision}
+ canComment={() => true}
+ renderCard={(thread, isActive) => (
+ <FixtureThreadCard
+ thread={thread}
+ active={isActive()}
+ onPost={(text) =>
+ context.comments.commitDraft(async (draft) =>
+ postFixtureThread(ready.doc, draft.markId, text)
+ )
+ }
+ onCancel={() => context.comments.cancelDraft()}
+ onResolve={(resolved) =>
+ thread.root &&
+ resolveFixtureThread(
+ ready.doc,
+ thread.root.id,
+ resolved
+ )
+ }
+ />
+ )}
+ />
+ )}
+ />
+ );
+ }}
+ </Show>
+ </main>
+ );
+}
+
+const root = document.getElementById('root');
+if (!root) throw new Error('DOCX fixture root is missing.');
+const dispose = render(() => <Fixture />, root);
+import.meta.hot?.dispose(dispose);
diff --git a/apps/web/src/features/block-write/browser-test/index.html b/apps/web/src/features/block-write/browser-test/index.html
new file mode 100644
index 0000000000..584232d5a0
--- /dev/null
+++ b/apps/web/src/features/block-write/browser-test/index.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en" data-modality="keyboard">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>DOCX editor browser fixture</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/fixture.tsx"></script>
+ </body>
+</html>
diff --git a/apps/web/src/features/block-write/browser-test/playwright.config.ts b/apps/web/src/features/block-write/browser-test/playwright.config.ts
new file mode 100644
index 0000000000..765113ca08
--- /dev/null
+++ b/apps/web/src/features/block-write/browser-test/playwright.config.ts
@@ -0,0 +1,41 @@
+import { fileURLToPath } from 'node:url';
+import { defineConfig, devices } from '@playwright/test';
+
+const directory = fileURLToPath(new URL('.', import.meta.url));
+const webDirectory = fileURLToPath(new URL('../../../../', import.meta.url));
+
+export default defineConfig({
+ testDir: directory,
+ testMatch: '*.browser.e2e.ts',
+ outputDir: `${directory}/test-results`,
+ timeout: 120_000,
+ expect: { timeout: 20_000 },
+ fullyParallel: false,
+ workers: 1,
+ reporter: 'line',
+ use: {
+ baseURL: 'http://localhost:3018',
+ trace: 'retain-on-failure',
+ screenshot: 'only-on-failure',
+ },
+ webServer: {
+ command:
+ 'bunx vite --config src/features/block-write/browser-test/vite.config.ts',
+ cwd: webDirectory,
+ url: 'http://localhost:3018',
+ reuseExistingServer: true,
+ timeout: 120_000,
+ },
+ projects: [
+ {
+ name: 'chromium',
+ use: {
+ ...devices['Desktop Chrome'],
+ viewport: { width: 1440, height: 900 },
+ launchOptions: {
+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
+ },
+ },
+ },
+ ],
+});
diff --git a/apps/web/src/features/block-write/browser-test/sync-server.ts b/apps/web/src/features/block-write/browser-test/sync-server.ts
new file mode 100644
index 0000000000..a3e1bb5772
--- /dev/null
+++ b/apps/web/src/features/block-write/browser-test/sync-server.ts
@@ -0,0 +1,99 @@
+import { createHmac } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { Miniflare } from 'miniflare';
+
+const root = fileURLToPath(new URL('../../../../../../', import.meta.url));
+
+/** A document-scoped JWT signed with the local test secret. */
+export function syncToken(documentId: string, user: string, access = 'edit') {
+ const header = Buffer.from(
+ JSON.stringify({ alg: 'HS256', typ: 'JWT' })
+ ).toString('base64url');
+ const payload = Buffer.from(
+ JSON.stringify({
+ document_id: documentId,
+ user_id: user,
+ access_level: access,
+ exp: Math.floor(Date.now() / 1000) + 3600,
+ })
+ ).toString('base64url');
+ const signature = createHmac('sha256', 'local')
+ .update(`${header}.${payload}`)
+ .digest('base64url');
+ return `${header}.${payload}.${signature}`;
+}
+
+/**
+ * Boot the compiled Rust sync Worker in an isolated Miniflare instance. Build
+ * `services/sync-service/build/worker/shim.mjs` first (`just worker-build`).
+ */
+export async function startSyncServer() {
+ const syncPath = `${root}/services/sync-service`;
+ const server = new Miniflare({
+ host: '127.0.0.1',
+ port: 0,
+ scriptPath: `${syncPath}/build/worker/shim.mjs`,
+ modules: true,
+ modulesRoot: syncPath,
+ modulesRules: [
+ { type: 'ESModule', include: ['**/build/index.js'] },
+ { type: 'CompiledWasm', include: ['**/*.wasm'], fallthrough: true },
+ ],
+ compatibilityDate: '2025-03-05',
+ durableObjects: {
+ DOCUMENT_SYNC_SESSION: {
+ className: 'DocumentSyncSession',
+ useSQLite: true,
+ },
+ },
+ d1Databases: { USER_PEER_MAPPING: 'docx-test' },
+ r2Buckets: { DOCUMENT_SNAPSHOT_BUCKET: 'docx-test' },
+ kvNamespaces: {
+ DOCUMENT_VERSIONING_KV: 'versions',
+ SNAPSHOT_STORE_KV: 'snapshots',
+ },
+ bindings: {
+ DOCUMENT_PERMISSIONS_SECRET: 'local',
+ INTERNAL_API_SECRET_KEY: 'INTERNAL_API_SECRET',
+ INTERNAL_API_SECRET: 'local',
+ SPS_API_SECRET_KEY: 'local',
+ SPS_URL: 'http://discard.test',
+ local: true,
+ },
+ outboundService: async () => new Response(null, { status: 204 }),
+ });
+ const url = (await server.ready).toString();
+ const db = await server.getD1Database('USER_PEER_MAPPING');
+ for (const file of ['0001_add_users.sql', '0002_add_blame.sql']) {
+ const sql = readFileSync(
+ `${syncPath}/database/user-peer-mapping/migrations/${file}`,
+ 'utf8'
+ );
+ for (const statement of sql
+ .split(';')
+ .map((part) => part.trim())
+ .filter(Boolean))
+ await db.prepare(statement).run();
+ }
+ return { server, url };
+}
+
+/** Fixture URL for one collaborator on `documentId`. */
+export function fixtureUrl(
+ base: string,
+ serverUrl: string,
+ documentId: string,
+ user: string,
+ extra: Record<string, string> = {}
+) {
+ const token = syncToken(documentId, user);
+ return `${base}/?${new URLSearchParams({
+ document: documentId,
+ worker: serverUrl,
+ socket: `${serverUrl.replace('http:', 'ws:')}document/${documentId}/connect?token=${token}`,
+ token,
+ user,
+ ...extra,
+ })}`;
+}
diff --git a/apps/web/src/features/block-write/browser-test/vite.config.ts b/apps/web/src/features/block-write/browser-test/vite.config.ts
new file mode 100644
index 0000000000..53bccedf9e
--- /dev/null
+++ b/apps/web/src/features/block-write/browser-test/vite.config.ts
@@ -0,0 +1,36 @@
+import { fileURLToPath } from 'node:url';
+import tailwind from '@tailwindcss/vite';
+import { defineConfig } from 'vite';
+import solidPlugin from 'vite-plugin-solid';
+import solidSvg from 'vite-plugin-solid-svg';
+import wasm from 'vite-plugin-wasm';
+import tsconfigPaths from 'vite-tsconfig-paths';
+import { docxodusRuntime } from '../../../../scripts/docxodus-runtime';
+
+const directory = fileURLToPath(new URL('.', import.meta.url));
+const webDirectory = fileURLToPath(new URL('../../../../', import.meta.url));
+const workspaceDirectory = fileURLToPath(
+ new URL('../../../../../../', import.meta.url)
+);
+
+export default defineConfig({
+ root: directory,
+ cacheDir: `${directory}/.vite`,
+ plugins: [
+ solidPlugin(),
+ solidSvg({ defaultAsComponent: true }),
+ tsconfigPaths({ projects: [`${webDirectory}/tsconfig.json`] }),
+ tailwind(),
+ wasm(),
+ docxodusRuntime(),
+ ],
+ resolve: { dedupe: ['solid-js', 'loro-crdt'] },
+ optimizeDeps: { include: ['fflate', 'docxodus'], exclude: ['loro-crdt'] },
+ server: {
+ host: '127.0.0.1',
+ port: 3018,
+ strictPort: true,
+ fs: { allow: [workspaceDirectory] },
+ },
+ build: { target: 'esnext', outDir: `${directory}/.dist`, emptyOutDir: true },
+});
diff --git a/apps/web/src/features/block-write/components/DocxToolbar.tsx b/apps/web/src/features/block-write/components/DocxToolbar.tsx
new file mode 100644
index 0000000000..071da63676
--- /dev/null
+++ b/apps/web/src/features/block-write/components/DocxToolbar.tsx
@@ -0,0 +1,225 @@
+import ArrowClockwise from '@phosphor/arrow-clockwise.svg';
+import ArrowCounterClockwise from '@phosphor/arrow-counter-clockwise.svg';
+import ChatCircleText from '@phosphor/chat-circle-text.svg';
+import DownloadSimple from '@phosphor/download-simple.svg';
+import ListBullets from '@phosphor/list-bullets.svg';
+import ListNumbers from '@phosphor/list-numbers.svg';
+import PencilSimpleLine from '@phosphor/pencil-simple-line.svg';
+import Table from '@phosphor/table.svg';
+import TextAlignCenter from '@phosphor/text-align-center.svg';
+import TextAlignJustify from '@phosphor/text-align-justify.svg';
+import TextAlignLeft from '@phosphor/text-align-left.svg';
+import TextAlignRight from '@phosphor/text-align-right.svg';
+import TextB from '@phosphor/text-b.svg';
+import TextItalic from '@phosphor/text-italic.svg';
+import TextStrikethrough from '@phosphor/text-strikethrough.svg';
+import TextUnderline from '@phosphor/text-underline.svg';
+import { Toolbar } from '@ui/components/Toolbar';
+import { For, type JSX, Show } from 'solid-js';
+
+export type DocxInlineFormat = 'bold' | 'italic' | 'underline' | 'strike';
+export type DocxAlignment = 'left' | 'center' | 'right' | 'justify';
+export type DocxParagraphStyle = { id: string; name: string };
+
+export type DocxToolbarProps = {
+ canEdit: boolean;
+ canComment: boolean;
+ format: Partial<Record<DocxInlineFormat, boolean>>;
+ paragraphStyle: string | null;
+ paragraphStyles: DocxParagraphStyle[];
+ trackChanges: boolean;
+ onFormat: (format: DocxInlineFormat) => void;
+ onParagraphStyle: (styleId: string) => void;
+ onList: (kind: 'bullet' | 'decimal') => void;
+ onAlign: (alignment: DocxAlignment) => void;
+ onUndo: () => void;
+ onRedo: () => void;
+ onInsertTable: () => void;
+ onToggleTrackChanges: () => void;
+ onComment: () => void;
+ onDownload: () => void;
+};
+
+const INLINE: Array<{
+ format: DocxInlineFormat;
+ label: string;
+ icon: () => JSX.Element;
+ shortcut?: string;
+}> = [
+ { format: 'bold', label: 'Bold', icon: () => <TextB />, shortcut: 'Mod+B' },
+ {
+ format: 'italic',
+ label: 'Italic',
+ icon: () => <TextItalic />,
+ shortcut: 'Mod+I',
+ },
+ {
+ format: 'underline',
+ label: 'Underline',
+ icon: () => <TextUnderline />,
+ shortcut: 'Mod+U',
+ },
+ {
+ format: 'strike',
+ label: 'Strikethrough',
+ icon: () => <TextStrikethrough />,
+ },
+];
+
+const ALIGNMENTS: Array<{
+ alignment: DocxAlignment;
+ label: string;
+ icon: () => JSX.Element;
+}> = [
+ { alignment: 'left', label: 'Align left', icon: () => <TextAlignLeft /> },
+ {
+ alignment: 'center',
+ label: 'Align center',
+ icon: () => <TextAlignCenter />,
+ },
+ { alignment: 'right', label: 'Align right', icon: () => <TextAlignRight /> },
+ { alignment: 'justify', label: 'Justify', icon: () => <TextAlignJustify /> },
+];
+
+/**
+ * Keep the editor's selection: controls act on the caret the user left in
+ * the document, so pressing one must not move focus out of it.
+ */
+const keepEditorFocus = (event: PointerEvent | MouseEvent) => {
+ if (!(event.target as HTMLElement).closest('select')) event.preventDefault();
+};
+
+/** Formatting and document actions for the DOCX editor. */
+export function DocxToolbar(props: DocxToolbarProps) {
+ return (
+ <div
+ class="flex w-full shrink-0 justify-center overflow-x-auto px-3 py-2"
+ onPointerDown={keepEditorFocus}
+ onMouseDown={keepEditorFocus}
+ >
+ <Toolbar
+ size="icon-sm"
+ aria-label="Document formatting"
+ class="max-w-full"
+ >
+ <Show when={props.canEdit}>
+ <Toolbar.Group>
+ <Toolbar.Button
+ label="Undo"
+ shortcut="Mod+Z"
+ onClick={() => props.onUndo()}
+ >
+ <ArrowCounterClockwise />
+ </Toolbar.Button>
+ <Toolbar.Button
+ label="Redo"
+ shortcut="Mod+Shift+Z"
+ onClick={() => props.onRedo()}
+ >
+ <ArrowClockwise />
+ </Toolbar.Button>
+ </Toolbar.Group>
+ <Toolbar.Divider />
+ <select
+ aria-label="Paragraph style"
+ class="h-6 max-w-36 rounded-md border border-edge-muted bg-input px-1.5 text-xs text-ink"
+ value={props.paragraphStyle ?? ''}
+ onChange={(event) =>
+ props.onParagraphStyle(event.currentTarget.value)
+ }
+ >
+ <Show
+ when={
+ !props.paragraphStyles.some(
+ (style) => style.id === props.paragraphStyle
+ )
+ }
+ >
+ <option value="">
+ {props.paragraphStyle ? 'Custom style' : 'Style'}
+ </option>
+ </Show>
+ <For each={props.paragraphStyles}>
+ {(style) => <option value={style.id}>{style.name}</option>}
+ </For>
+ </select>
+ <Toolbar.Divider />
+ <Toolbar.Group>
+ <For each={INLINE}>
+ {(item) => (
+ <Toolbar.Button
+ label={item.label}
+ shortcut={item.shortcut}
+ aria-pressed={!!props.format[item.format]}
+ onClick={() => props.onFormat(item.format)}
+ >
+ {item.icon()}
+ </Toolbar.Button>
+ )}
+ </For>
+ </Toolbar.Group>
+ <Toolbar.Divider />
+ <Toolbar.Group>
+ <Toolbar.Button
+ label="Bulleted list"
+ onClick={() => props.onList('bullet')}
+ >
+ <ListBullets />
+ </Toolbar.Button>
+ <Toolbar.Button
+ label="Numbered list"
+ onClick={() => props.onList('decimal')}
+ >
+ <ListNumbers />
+ </Toolbar.Button>
+ </Toolbar.Group>
+ <Toolbar.Divider />
+ <Toolbar.Group>
+ <For each={ALIGNMENTS}>
+ {(item) => (
+ <Toolbar.Button
+ label={item.label}
+ onClick={() => props.onAlign(item.alignment)}
+ >
+ {item.icon()}
+ </Toolbar.Button>
+ )}
+ </For>
+ </Toolbar.Group>
+ <Toolbar.Divider />
+ <Toolbar.Button
+ label="Insert table"
+ onClick={() => props.onInsertTable()}
+ >
+ <Table />
+ </Toolbar.Button>
+ <Toolbar.Button
+ label={
+ props.trackChanges ? 'Stop tracking changes' : 'Track changes'
+ }
+ aria-pressed={props.trackChanges}
+ onClick={() => props.onToggleTrackChanges()}
+ >
+ <PencilSimpleLine />
+ </Toolbar.Button>
+ <Toolbar.Divider />
+ </Show>
+ <Show when={props.canComment}>
+ <Toolbar.Button
+ label="Comment on selection"
+ shortcut="Mod+Alt+M"
+ onClick={() => props.onComment()}
+ >
+ <ChatCircleText />
+ </Toolbar.Button>
+ </Show>
+ <Toolbar.Button
+ label="Download .docx"
+ onClick={() => props.onDownload()}
+ >
+ <DownloadSimple />
+ </Toolbar.Button>
+ </Toolbar>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/block-write/core/comment-layout.test.ts b/apps/web/src/features/block-write/core/comment-layout.test.ts
new file mode 100644
index 0000000000..55609dc1c0
--- /dev/null
+++ b/apps/web/src/features/block-write/core/comment-layout.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from 'vitest';
+import { layoutMarginCards } from './comment-layout';
+
+const heights = new Map([
+ ['a', 50],
+ ['b', 50],
+ ['c', 50],
+]);
+
+describe('layoutMarginCards', () => {
+ it('keeps cards at their anchors when they do not overlap', () => {
+ const placed = layoutMarginCards(
+ [
+ { id: 'a', top: 0 },
+ { id: 'b', top: 100 },
+ ],
+ heights,
+ null
+ );
+ expect([...placed]).toEqual([
+ ['a', 0],
+ ['b', 100],
+ ]);
+ });
+
+ it('pushes overlapping cards down in anchor order', () => {
+ const placed = layoutMarginCards(
+ [
+ { id: 'b', top: 10 },
+ { id: 'a', top: 0 },
+ { id: 'c', top: 20 },
+ ],
+ heights,
+ null,
+ 10
+ );
+ expect(placed.get('a')).toBe(0);
+ expect(placed.get('b')).toBe(60);
+ expect(placed.get('c')).toBe(120);
+ });
+
+ it('pins the active card and moves its neighbours around it', () => {
+ const placed = layoutMarginCards(
+ [
+ { id: 'a', top: 0 },
+ { id: 'b', top: 10 },
+ { id: 'c', top: 20 },
+ ],
+ heights,
+ 'b',
+ 10
+ );
+ expect(placed.get('b')).toBe(10);
+ expect(placed.get('a')).toBe(-50);
+ expect(placed.get('c')).toBe(70);
+ });
+});
diff --git a/apps/web/src/features/block-write/core/comment-layout.ts b/apps/web/src/features/block-write/core/comment-layout.ts
new file mode 100644
index 0000000000..4f4a19f886
--- /dev/null
+++ b/apps/web/src/features/block-write/core/comment-layout.ts
@@ -0,0 +1,44 @@
+export type MarginItem = { id: string; top: number };
+
+/**
+ * Stack margin cards beside their anchors without overlap. The active card
+ * sits exactly at its anchor; cards above it are pushed up and cards below
+ * are pushed down, the way a word processor's markup area behaves.
+ */
+export function layoutMarginCards(
+ items: readonly MarginItem[],
+ heights: ReadonlyMap<string, number>,
+ activeId: string | null,
+ gap = 8
+): Map<string, number> {
+ const sorted = [...items].sort(
+ (a, b) => a.top - b.top || (a.id < b.id ? -1 : 1)
+ );
+ const height = (id: string) => heights.get(id) ?? 80;
+ const placed = new Map<string, number>();
+ const pivot = sorted.findIndex((item) => item.id === activeId);
+ if (pivot < 0) {
+ let bottom = -Infinity;
+ for (const item of sorted) {
+ const top = Math.max(item.top, bottom + gap);
+ placed.set(item.id, top);
+ bottom = top + height(item.id);
+ }
+ return placed;
+ }
+ const anchor = sorted[pivot];
+ placed.set(anchor.id, anchor.top);
+ let bottom = anchor.top + height(anchor.id);
+ for (const item of sorted.slice(pivot + 1)) {
+ const top = Math.max(item.top, bottom + gap);
+ placed.set(item.id, top);
+ bottom = top + height(item.id);
+ }
+ let ceiling = anchor.top;
+ for (const item of sorted.slice(0, pivot).reverse()) {
+ const top = Math.min(item.top, ceiling - gap - height(item.id));
+ placed.set(item.id, top);
+ ceiling = top;
+ }
+ return placed;
+}
diff --git a/apps/web/src/features/block-write/core/comment-marks.test.ts b/apps/web/src/features/block-write/core/comment-marks.test.ts
new file mode 100644
index 0000000000..49f406d9e2
--- /dev/null
+++ b/apps/web/src/features/block-write/core/comment-marks.test.ts
@@ -0,0 +1,87 @@
+import { LoroDoc } from 'loro-crdt';
+import { describe, expect, it } from 'vitest';
+import {
+ type CommentMark,
+ deleteCommentMark,
+ MAX_MARK_TEXT,
+ readCommentMarks,
+ resolveMark,
+ writeCommentMark,
+} from './comment-marks';
+
+const mark: CommentMark = { block: 'b', start: 4, length: 5, text: 'brown' };
+
+describe('resolveMark', () => {
+ it('keeps a mark whose text is still in place', () => {
+ expect(
+ resolveMark(mark, [
+ { id: 'a', text: 'intro' },
+ { id: 'b', text: 'The brown fox' },
+ ])
+ ).toEqual({ ...mark, relocated: false });
+ });
+
+ it('follows its text when the paragraph is edited', () => {
+ expect(
+ resolveMark(mark, [{ id: 'b', text: 'Then the quick brown fox' }])
+ ).toMatchObject({ block: 'b', start: 15, relocated: true });
+ });
+
+ it('prefers the occurrence nearest the old position', () => {
+ expect(
+ resolveMark({ ...mark, start: 20 }, [
+ { id: 'b', text: 'brown and then more brown' },
+ ])
+ ).toMatchObject({ start: 20 });
+ });
+
+ it('moves to the closest paragraph when a split carries the text away', () => {
+ expect(
+ resolveMark(mark, [
+ { id: 'z', text: 'far brown' },
+ { id: 'x', text: 'gap' },
+ { id: 'b', text: 'The ' },
+ { id: 'c', text: 'brown fox' },
+ ])
+ ).toMatchObject({ block: 'c', start: 0, relocated: true });
+ });
+
+ it('reports a mark whose text was deleted', () => {
+ expect(resolveMark(mark, [{ id: 'b', text: 'The fox' }])).toBeNull();
+ });
+});
+
+describe('comment mark storage', () => {
+ it('round-trips marks through the collaborative document', () => {
+ const doc = new LoroDoc();
+ writeCommentMark(doc, 'm1', mark);
+ const other = new LoroDoc();
+ other.import(doc.export({ mode: 'snapshot' }));
+ expect(readCommentMarks(other).get('m1')).toEqual(mark);
+ deleteCommentMark(doc, 'm1');
+ expect(readCommentMarks(doc).size).toBe(0);
+ });
+
+ it('stores long selections so they resolve in place, not as a move', () => {
+ const doc = new LoroDoc();
+ const text = 'x'.repeat(MAX_MARK_TEXT + 200);
+ writeCommentMark(doc, 'm1', {
+ block: 'b',
+ start: 0,
+ length: text.length,
+ text,
+ });
+ const stored = readCommentMarks(doc).get('m1');
+ expect(stored).toMatchObject({ length: MAX_MARK_TEXT });
+ expect(resolveMark(stored!, [{ id: 'b', text }])).toMatchObject({
+ relocated: false,
+ });
+ });
+
+ it('ignores malformed marks', () => {
+ const doc = new LoroDoc();
+ doc.getMap('docxMarks').set('bad', '{"block":1}');
+ doc.getMap('docxMarks').set('worse', 'not json');
+ expect(readCommentMarks(doc).size).toBe(0);
+ });
+});
diff --git a/apps/web/src/features/block-write/core/comment-marks.ts b/apps/web/src/features/block-write/core/comment-marks.ts
new file mode 100644
index 0000000000..6425f9b7d4
--- /dev/null
+++ b/apps/web/src/features/block-write/core/comment-marks.ts
@@ -0,0 +1,124 @@
+import type { LoroDoc } from 'loro-crdt';
+import { DOCX_LORO_CONTAINERS } from './docx-loro';
+
+/**
+ * Where a comment thread is anchored in a DOCX: a span of one paragraph's
+ * text. Marks live in the collaborative document, beside the blocks, and are
+ * joined to message threads by mark id the same way markdown comment marks
+ * are. The document file itself is never modified by commenting.
+ */
+export type CommentMark = {
+ /** Persisted engine id of the paragraph. */
+ block: string;
+ start: number;
+ length: number;
+ /** The text the mark covered when it was placed or last relocated. */
+ text: string;
+};
+
+export type ResolvedMark = CommentMark & { relocated: boolean };
+
+function parseMark(value: unknown): CommentMark | null {
+ if (typeof value !== 'string') return null;
+ try {
+ const parsed = JSON.parse(value) as Partial<CommentMark>;
+ if (
+ typeof parsed.block === 'string' &&
+ typeof parsed.start === 'number' &&
+ typeof parsed.length === 'number' &&
+ typeof parsed.text === 'string' &&
+ parsed.length > 0
+ )
+ return {
+ block: parsed.block,
+ start: parsed.start,
+ length: parsed.length,
+ text: parsed.text,
+ };
+ } catch {
+ // A malformed mark is ignored rather than breaking every other comment.
+ }
+ return null;
+}
+
+export function readCommentMarks(doc: LoroDoc): Map<string, CommentMark> {
+ const map = doc.getMap(DOCX_LORO_CONTAINERS.marks);
+ const marks = new Map<string, CommentMark>();
+ for (const id of map.keys()) {
+ const mark = parseMark(map.get(id));
+ if (mark) marks.set(id, mark);
+ }
+ return marks;
+}
+
+/** Longest quoted text a mark keeps; longer selections anchor on their start. */
+export const MAX_MARK_TEXT = 1000;
+
+export function writeCommentMark(doc: LoroDoc, id: string, mark: CommentMark) {
+ doc.getMap(DOCX_LORO_CONTAINERS.marks).set(
+ id,
+ JSON.stringify({
+ ...mark,
+ length: Math.min(mark.length, MAX_MARK_TEXT),
+ text: mark.text.slice(0, MAX_MARK_TEXT),
+ })
+ );
+ doc.commit({ origin: 'docx-comment' });
+}
+
+export function deleteCommentMark(doc: LoroDoc, id: string) {
+ doc.getMap(DOCX_LORO_CONTAINERS.marks).delete(id);
+ doc.commit({ origin: 'docx-comment' });
+}
+
+function nearestOccurrence(haystack: string, needle: string, near: number) {
+ let best = -1;
+ let index = haystack.indexOf(needle);
+ while (index >= 0) {
+ if (best < 0 || Math.abs(index - near) < Math.abs(best - near))
+ best = index;
+ index = haystack.indexOf(needle, index + 1);
+ }
+ return best;
+}
+
+/**
+ * Find a mark's text in the current document. The mark keeps its place while
+ * its paragraph's text there is unchanged; otherwise the nearest occurrence in
+ * the same paragraph wins, then the occurrence in the closest other paragraph
+ * (a split moves text to a new paragraph). Null means the text is gone.
+ *
+ * `blocks` lists paragraph ids and texts in document order.
+ */
+export function resolveMark(
+ mark: CommentMark,
+ blocks: ReadonlyArray<{ id: string; text: string }>
+): ResolvedMark | null {
+ const home = blocks.findIndex((block) => block.id === mark.block);
+ if (home >= 0) {
+ const text = blocks[home].text;
+ if (text.slice(mark.start, mark.start + mark.length) === mark.text)
+ return { ...mark, relocated: false };
+ const start = nearestOccurrence(text, mark.text, mark.start);
+ if (start >= 0)
+ return { ...mark, start, length: mark.text.length, relocated: true };
+ }
+ type Match = { index: number; start: number; distance: number };
+ let best: Match | null = null;
+ blocks.forEach((block, index) => {
+ if (index === home) return;
+ const start = block.text.indexOf(mark.text);
+ if (start < 0) return;
+ const distance = home >= 0 ? Math.abs(index - home) : index;
+ if (!best || distance < best.distance) best = { index, start, distance };
+ });
+ if (!best) return null;
+ const found: Match = best;
+ return {
+ block: blocks[found.index].id,
+ start: found.start,
+ length: mark.text.length,
+ text: mark.text,
+ relocated: true,
+ };
+}
diff --git a/apps/web/src/features/block-write/core/docx-engine.ts b/apps/web/src/features/block-write/core/docx-engine.ts
new file mode 100644
index 0000000000..a58646db7e
--- /dev/null
+++ b/apps/web/src/features/block-write/core/docx-engine.ts
@@ -0,0 +1,93 @@
+import { type DocxPackageState, splitPackage } from './docx-package';
+
+/** The Docxodus session bridge calls the collaboration layer uses. */
+export type DocxSyncBridge = {
+ SaveWithAnchorIds?: (handle: number) => Uint8Array;
+ ListAnchors?: (handle: number) => string;
+ RawReplaceXml?: (handle: number, anchor: string, xml: string) => string;
+ RawInsertXml?: (
+ handle: number,
+ anchor: string,
+ position: string,
+ xml: string
+ ) => string;
+ DeleteBlock: (handle: number, anchor: string) => string;
+ MoveBlock?: (
+ handle: number,
+ source: string,
+ target: string,
+ position: string
+ ) => string;
+};
+
+export type BlockPosition = 'before' | 'after';
+
+/** Engine operations over one live document session. */
+export type DocxEngine = {
+ /** The session's current document, split the way collaboration stores it. */
+ snapshot(): DocxPackageState;
+ /** Body block id → the engine anchor that addresses it. */
+ bodyAnchors(): Map<string, string>;
+ replaceBlock(anchor: string, xml: string): boolean;
+ insertBlock(anchor: string, position: BlockPosition, xml: string): boolean;
+ deleteBlock(anchor: string): boolean;
+ moveBlock(source: string, target: string, position: BlockPosition): boolean;
+};
+
+export class DocxEngineUnsupportedError extends Error {}
+
+function succeeded(result: string | undefined): boolean {
+ if (!result) return false;
+ try {
+ const parsed: unknown = JSON.parse(result);
+ return (
+ typeof parsed === 'object' &&
+ parsed !== null &&
+ 'success' in parsed &&
+ parsed.success === true
+ );
+ } catch {
+ return false;
+ }
+}
+
+function require<T>(value: T | undefined, name: string): T {
+ if (value === undefined)
+ throw new DocxEngineUnsupportedError(
+ `This Docxodus build lacks ${name}, which collaboration requires.`
+ );
+ return value;
+}
+
+type AnchorIndex = Record<string, { unid?: string; scope?: string }>;
+
+export function bridgeEngine(
+ bridge: DocxSyncBridge,
+ handle: () => number
+): DocxEngine {
+ const save = require(bridge.SaveWithAnchorIds, 'SaveWithAnchorIds');
+ const listAnchors = require(bridge.ListAnchors, 'ListAnchors');
+ const replace = require(bridge.RawReplaceXml, 'RawReplaceXml');
+ const insert = require(bridge.RawInsertXml, 'RawInsertXml');
+ return {
+ snapshot: () => splitPackage(save(handle())),
+ bodyAnchors() {
+ const parsed = JSON.parse(listAnchors(handle())) as {
+ anchorIndex?: AnchorIndex;
+ };
+ const anchors = new Map<string, string>();
+ for (const [anchor, info] of Object.entries(parsed.anchorIndex ?? {})) {
+ if (info.scope === 'body' && info.unid) anchors.set(info.unid, anchor);
+ }
+ return anchors;
+ },
+ replaceBlock: (anchor, xml) => succeeded(replace(handle(), anchor, xml)),
+ insertBlock: (anchor, position, xml) =>
+ succeeded(insert(handle(), anchor, position, xml)),
+ deleteBlock: (anchor) => succeeded(bridge.DeleteBlock(handle(), anchor)),
+ moveBlock: (source, target, position) =>
+ bridge.MoveBlock
+ ? succeeded(bridge.MoveBlock(handle(), source, target, position))
+ : false,
+ };
+}
diff --git a/apps/web/src/features/block-write/core/docx-loro-schema.ts b/apps/web/src/features/block-write/core/docx-loro-schema.ts
new file mode 100644
index 0000000000..6283158baa
--- /dev/null
+++ b/apps/web/src/features/block-write/core/docx-loro-schema.ts
@@ -0,0 +1,16 @@
+import { schema } from '@loro-mirror/core';
+import { DOCX_LORO_CONTAINERS } from './docx-loro';
+
+const strings = () =>
+ schema.LoroMap({} as Record<string, ReturnType<typeof schema.String>>);
+
+/** Mirror schema for the collaborative DOCX roots (see `DOCX_LORO_CONTAINERS`). */
+export const DOCX_LORO_SCHEMA = schema({
+ [DOCX_LORO_CONTAINERS.meta]: schema.LoroMap(
+ {} as Record<string, ReturnType<typeof schema.Number>>
+ ),
+ [DOCX_LORO_CONTAINERS.blocks]: strings(),
+ [DOCX_LORO_CONTAINERS.order]: strings(),
+ [DOCX_LORO_CONTAINERS.parts]: strings(),
+ [DOCX_LORO_CONTAINERS.marks]: strings(),
+});
diff --git a/apps/web/src/features/block-write/core/docx-loro.ts b/apps/web/src/features/block-write/core/docx-loro.ts
new file mode 100644
index 0000000000..7d06eb163f
--- /dev/null
+++ b/apps/web/src/features/block-write/core/docx-loro.ts
@@ -0,0 +1,237 @@
+import type { LoroDoc, LoroMap } from 'loro-crdt';
+import type { DocxPackageState } from './docx-package';
+import { compareKeyed, keysBetween } from './fractional-index';
+
+/**
+ * Root containers of a collaborative DOCX. Every root is a flat map so two
+ * peers editing different blocks, parts, or comment marks never conflict;
+ * concurrent writes to the same key resolve last-writer-wins.
+ */
+export const DOCX_LORO_CONTAINERS = {
+ meta: 'docxMeta',
+ blocks: 'docxBlocks',
+ order: 'docxOrder',
+ parts: 'docxParts',
+ marks: 'docxMarks',
+} as const;
+
+export const DOCX_FORMAT_VERSION = 1;
+
+function container(doc: LoroDoc, name: string): LoroMap {
+ return doc.getMap(name);
+}
+
+function stringEntries(map: LoroMap): Array<[string, string]> {
+ const out: Array<[string, string]> = [];
+ for (const key of map.keys()) {
+ const value = map.get(key);
+ if (typeof value === 'string') out.push([key, value]);
+ }
+ return out;
+}
+
+export function docxFormatVersion(doc: LoroDoc): number | undefined {
+ const value = container(doc, DOCX_LORO_CONTAINERS.meta).get('formatVersion');
+ return typeof value === 'number' ? value : undefined;
+}
+
+/** True once a peer has seeded the document body. */
+export function isDocxSeeded(doc: LoroDoc): boolean {
+ return docxFormatVersion(doc) !== undefined;
+}
+
+export type OrderKeys = ReadonlyMap<string, string>;
+
+/** The current block order keys, for computing a minimal reorder. */
+export function readOrderKeys(doc: LoroDoc): Map<string, string> {
+ return new Map(stringEntries(container(doc, DOCX_LORO_CONTAINERS.order)));
+}
+
+/**
+ * The document the collaborative state describes. A block is visible only
+ * when it has both content and a position; a half-written block (possible
+ * mid-merge after a concurrent delete) is skipped rather than guessed at.
+ */
+export function readDocxState(doc: LoroDoc): DocxPackageState {
+ const blocks = new Map(
+ stringEntries(container(doc, DOCX_LORO_CONTAINERS.blocks))
+ );
+ const keyed = stringEntries(container(doc, DOCX_LORO_CONTAINERS.order))
+ .filter(([id]) => blocks.has(id))
+ .map(([id, key]) => ({ id, key }))
+ .sort(compareKeyed);
+ return {
+ order: keyed.map((entry) => entry.id),
+ blocks,
+ parts: new Map(stringEntries(container(doc, DOCX_LORO_CONTAINERS.parts))),
+ };
+}
+
+/** Write a freshly split package as the initial collaborative state. */
+export function seedDocxState(doc: LoroDoc, state: DocxPackageState) {
+ const blocks = container(doc, DOCX_LORO_CONTAINERS.blocks);
+ const order = container(doc, DOCX_LORO_CONTAINERS.order);
+ const parts = container(doc, DOCX_LORO_CONTAINERS.parts);
+ const keys = keysBetween(null, null, state.order.length);
+ state.order.forEach((id, index) => {
+ blocks.set(id, state.blocks.get(id) ?? '');
+ order.set(id, keys[index]);
+ });
+ for (const [name, value] of state.parts) parts.set(name, value);
+ container(doc, DOCX_LORO_CONTAINERS.meta).set(
+ 'formatVersion',
+ DOCX_FORMAT_VERSION
+ );
+ doc.commit({ origin: 'docx-seed' });
+}
+
+export type DocxChanges = {
+ /** Blocks whose content was created or changed. */
+ upserts: ReadonlyMap<string, string>;
+ /** Blocks removed from the document. */
+ removed: readonly string[];
+ /** The complete new block order, when it changed. */
+ order?: readonly string[];
+ /** Parts created or changed (string) or removed (null). */
+ parts: ReadonlyMap<string, string | null>;
+};
+
+export function hasChanges(changes: DocxChanges): boolean {
+ return (
+ changes.upserts.size > 0 ||
+ changes.removed.length > 0 ||
+ changes.order !== undefined ||
+ changes.parts.size > 0
+ );
+}
+
+/** Indices of a longest strictly increasing subsequence of `values`. */
+function longestIncreasing(values: readonly string[]): Set<number> {
+ const tails: number[] = [];
+ const previous = new Array<number>(values.length).fill(-1);
+ values.forEach((value, index) => {
+ let low = 0;
+ let high = tails.length;
+ while (low < high) {
+ const mid = (low + high) >> 1;
+ if (values[tails[mid]] < value) low = mid + 1;
+ else high = mid;
+ }
+ if (low > 0) previous[index] = tails[low - 1];
+ tails[low] = index;
+ });
+ const keep = new Set<number>();
+ let cursor = tails.length ? tails[tails.length - 1] : -1;
+ while (cursor >= 0) {
+ keep.add(cursor);
+ cursor = previous[cursor];
+ }
+ return keep;
+}
+
+/**
+ * Position keys for `order` that reuse as many existing keys as possible:
+ * blocks already in relative order keep their keys; moved and new blocks get
+ * fresh keys between their kept neighbours. Returns only keys that change.
+ */
+export function reorderKeys(
+ existing: OrderKeys,
+ order: readonly string[]
+): Map<string, string> {
+ const current = order.map((id) => existing.get(id));
+ const candidates: number[] = [];
+ current.forEach((key, index) => {
+ if (key !== undefined) candidates.push(index);
+ });
+ // Ties between concurrently minted keys break by id, matching readDocxState.
+ const sortable = candidates.map(
+ (index) => `${current[index]}\u0000${order[index]}`
+ );
+ const keptCandidates = longestIncreasing(sortable);
+ const kept = new Set<number>();
+ let previousKey: string | undefined;
+ candidates.forEach((index, i) => {
+ if (!keptCandidates.has(i)) return;
+ // Concurrent peers can mint the same key; re-key the later block so new
+ // keys always have a strictly ordered pair of neighbours.
+ if (current[index] === previousKey) return;
+ previousKey = current[index];
+ kept.add(index);
+ });
+
+ const changed = new Map<string, string>();
+ let index = 0;
+ while (index < order.length) {
+ if (kept.has(index)) {
+ index++;
+ continue;
+ }
+ const runStart = index;
+ while (index < order.length && !kept.has(index)) index++;
+ const low = runStart > 0 ? (current[runStart - 1] ?? null) : null;
+ const high = index < order.length ? (current[index] ?? null) : null;
+ const keys = keysBetween(low, high, index - runStart);
+ for (let i = runStart; i < index; i++) {
+ const key = keys[i - runStart];
+ current[i] = key;
+ changed.set(order[i], key);
+ }
+ }
+ return changed;
+}
+
+/** Apply local document changes to the collaborative state in one commit. */
+export function writeDocxChanges(doc: LoroDoc, changes: DocxChanges) {
+ if (!hasChanges(changes)) return;
+ const blocks = container(doc, DOCX_LORO_CONTAINERS.blocks);
+ const order = container(doc, DOCX_LORO_CONTAINERS.order);
+ const parts = container(doc, DOCX_LORO_CONTAINERS.parts);
+ for (const [id, xml] of changes.upserts) blocks.set(id, xml);
+ for (const id of changes.removed) {
+ blocks.delete(id);
+ order.delete(id);
+ }
+ if (changes.order) {
+ const existing = readOrderKeys(doc);
+ // A block another peer deleted concurrently stays deleted unless this
+ // peer also changed its content.
+ const ordered = changes.order.filter(
+ (id) => existing.has(id) || changes.upserts.has(id)
+ );
+ for (const [id, key] of reorderKeys(existing, ordered)) order.set(id, key);
+ }
+ for (const [name, value] of changes.parts) {
+ if (value === null) parts.delete(name);
+ else parts.set(name, value);
+ }
+ doc.commit({ origin: 'docx-edit' });
+}
+
+/** Changes that turn `before` into `after`. */
+export function diffDocxStates(
+ before: DocxPackageState,
+ after: DocxPackageState
+): DocxChanges {
+ const upserts = new Map<string, string>();
+ for (const id of after.order) {
+ const xml = after.blocks.get(id);
+ if (xml !== undefined && before.blocks.get(id) !== xml)
+ upserts.set(id, xml);
+ }
+ const present = new Set(after.order);
+ const removed = before.order.filter((id) => !present.has(id));
+ const orderChanged =
+ before.order.length !== after.order.length ||
+ before.order.some((id, index) => after.order[index] !== id);
+ const parts = new Map<string, string | null>();
+ for (const [name, value] of after.parts)
+ if (before.parts.get(name) !== value) parts.set(name, value);
+ for (const name of before.parts.keys())
+ if (!after.parts.has(name)) parts.set(name, null);
+ return {
+ upserts,
+ removed,
+ order: orderChanged ? after.order : undefined,
+ parts,
+ };
+}
diff --git a/apps/web/src/features/block-write/core/docx-package.test.ts b/apps/web/src/features/block-write/core/docx-package.test.ts
new file mode 100644
index 0000000000..5dc08cf4c1
--- /dev/null
+++ b/apps/web/src/features/block-write/core/docx-package.test.ts
@@ -0,0 +1,156 @@
+// @vitest-environment node
+import { strFromU8, unzipSync } from 'fflate';
+import { beforeAll, describe, expect, it } from 'vitest';
+import {
+ bridge,
+ fixture,
+ loadEngine,
+ SYNC_SESSION_SETTINGS,
+ xmlText,
+} from '../tests/docx-test-peer';
+import {
+ assembleDocumentXml,
+ assemblePackage,
+ BLOCKS_PLACEHOLDER,
+ DOCUMENT_PART,
+ decodePart,
+ encodePart,
+ splitDocumentXml,
+ splitPackage,
+} from './docx-package';
+
+beforeAll(loadEngine, 60_000);
+
+const W = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
+const PT = 'http://powertools.codeplex.com/2011';
+
+function documentXml(body: string) {
+ return `<?xml version="1.0" encoding="utf-8"?><w:document xmlns:w="${W}" xmlns:r="urn:r"><w:body xmlns:p18="${PT}">${body}</w:body></w:document>`;
+}
+
+describe('splitDocumentXml', () => {
+ it('extracts top-level blocks with their ids and keeps the final section in the shell', () => {
+ const split = splitDocumentXml(
+ documentXml(
+ '<w:p p18:Unid="a1"><w:r><w:t>One &gt; two</w:t></w:r></w:p>' +
+ '<!-- note --><w:tbl p18:Unid="b2"><w:tr><w:tc><w:p p18:Unid="c3"/></w:tc></w:tr></w:tbl>' +
+ '<w:p p18:Unid="d4" w:rsidR="x>y"/>' +
+ '<w:sectPr p18:Unid="e5"><w:pgSz w:w="12240"/></w:sectPr>'
+ )
+ );
+ expect(split.order).toEqual(['a1', 'b2', 'd4']);
+ expect(split.shell).toContain(`${BLOCKS_PLACEHOLDER}<w:sectPr`);
+ expect(split.shell).not.toContain('a1');
+ // Blocks declare the prefixes their ancestors declared.
+ const first = split.blocks.get('a1')!;
+ expect(first).toContain(`xmlns:p18="${PT}"`);
+ expect(first).toContain(`xmlns:w="${W}"`);
+ expect(first).not.toContain('xmlns:r=');
+ expect(split.blocks.get('d4')).toContain('w:rsidR="x>y"');
+ });
+
+ it('round-trips through assembly', () => {
+ const xml = documentXml(
+ '<w:p p18:Unid="a1"><w:r><w:t>Hello</w:t></w:r></w:p><w:p p18:Unid="b2"/>'
+ );
+ const split = splitDocumentXml(xml);
+ const assembled = assembleDocumentXml({
+ order: split.order,
+ blocks: split.blocks,
+ parts: new Map([[DOCUMENT_PART, split.shell]]),
+ });
+ expect(splitDocumentXml(assembled).order).toEqual(['a1', 'b2']);
+ expect(xmlText(assembled)).toBe('Hello');
+ });
+
+ it('gives elements without ids a deterministic content address', () => {
+ const xml = documentXml('<w:p/><w:p/><w:p><w:r><w:t>x</w:t></w:r></w:p>');
+ const first = splitDocumentXml(xml);
+ expect(new Set(first.order).size).toBe(3);
+ expect(splitDocumentXml(xml).order).toEqual(first.order);
+ });
+
+ it('handles an empty body', () => {
+ const split = splitDocumentXml(documentXml(''));
+ expect(split.order).toEqual([]);
+ expect(split.shell).toContain(BLOCKS_PLACEHOLDER);
+ });
+
+ it('rejects documents that are not WordprocessingML', () => {
+ expect(() => splitDocumentXml('<root><body/></root>')).toThrow();
+ });
+});
+
+describe('package parts', () => {
+ it('encodes binary parts as base64 and text parts verbatim', () => {
+ const binary = new Uint8Array([0, 255, 128, 10]);
+ const encoded = encodePart('word/media/image1.png', binary);
+ expect(encoded.startsWith('b64:')).toBe(true);
+ expect(decodePart(encoded)).toEqual(binary);
+ expect(
+ encodePart('word/styles.xml', new TextEncoder().encode('<a/>'))
+ ).toBe('<a/>');
+ });
+});
+
+describe.each(['mutual-nda.docx', 'complex-msa.docx'])(
+ 'engine snapshots of %s',
+ (name) => {
+ it('split into blocks that reopen to the same document', () => {
+ const engine = bridge();
+ const handle = engine.OpenSession(fixture(name), SYNC_SESSION_SETTINGS);
+ try {
+ const state = splitPackage(engine.SaveWithAnchorIds(handle));
+ expect(state.order.length).toBeGreaterThan(5);
+ expect(state.parts.has('word/styles.xml')).toBe(true);
+ const reopened = engine.OpenSession(
+ assemblePackage(state),
+ SYNC_SESSION_SETTINGS
+ );
+ try {
+ const again = splitPackage(engine.SaveWithAnchorIds(reopened));
+ expect(again.order).toEqual(state.order);
+ for (const id of state.order)
+ expect(xmlText(again.blocks.get(id)!)).toBe(
+ xmlText(state.blocks.get(id)!)
+ );
+ // User-facing saves strip the engine's anchor ids.
+ const clean = unzipSync(engine.Save(reopened));
+ expect(strFromU8(clean[DOCUMENT_PART])).not.toContain('Unid=');
+ } finally {
+ engine.CloseSession(reopened);
+ }
+ } finally {
+ engine.CloseSession(handle);
+ }
+ });
+
+ it('produce blocks every raw engine operation accepts', () => {
+ const engine = bridge();
+ const handle = engine.OpenSession(fixture(name), SYNC_SESSION_SETTINGS);
+ try {
+ const state = splitPackage(engine.SaveWithAnchorIds(handle));
+ const anchors = JSON.parse(engine.ListAnchors!(handle))
+ .anchorIndex as Record<string, { unid: string; scope: string }>;
+ const byId = new Map(
+ Object.entries(anchors)
+ .filter(([, info]) => info.scope === 'body')
+ .map(([anchor, info]) => [info.unid, anchor])
+ );
+ const paragraph = state.order.find((id) =>
+ byId.get(id)?.startsWith('p:')
+ )!;
+ const result = JSON.parse(
+ engine.RawReplaceXml(
+ handle,
+ byId.get(paragraph)!,
+ state.blocks.get(paragraph)!
+ )
+ );
+ expect(result.success).toBe(true);
+ } finally {
+ engine.CloseSession(handle);
+ }
+ });
+ }
+);
diff --git a/apps/web/src/features/block-write/core/docx-package.ts b/apps/web/src/features/block-write/core/docx-package.ts
new file mode 100644
index 0000000000..f3f8965279
--- /dev/null
+++ b/apps/web/src/features/block-write/core/docx-package.ts
@@ -0,0 +1,390 @@
+import { strFromU8, strToU8, unzipSync, type Zippable, zipSync } from 'fflate';
+
+/**
+ * A DOCX package as the collaboration layer stores it: the body's top-level
+ * elements as addressable blocks, and every other part verbatim.
+ *
+ * Blocks are keyed by the engine's persisted anchor id (`PtOpenXml:Unid`), so
+ * the same paragraph has the same id on every client and survives a reopen.
+ */
+export type DocxPackageState = {
+ /** Top-level body elements in document order. */
+ order: string[];
+ /** Block id → standalone element XML. */
+ blocks: ReadonlyMap<string, string>;
+ /** Part name → content. XML parts are text; binary parts are base64 with a `b64:` prefix. `word/document.xml` is the body shell. */
+ parts: ReadonlyMap<string, string>;
+};
+
+export const DOCUMENT_PART = 'word/document.xml';
+const CONTENT_TYPES_PART = '[Content_Types].xml';
+/** Where the shell's body content goes when the package is assembled. */
+export const BLOCKS_PLACEHOLDER = '<!--macro-docx-blocks-->';
+const WORDML_NS =
+ 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
+const POWERTOOLS_NS = 'http://powertools.codeplex.com/2011';
+const MARKUP_COMPATIBILITY_NS =
+ 'http://schemas.openxmlformats.org/markup-compatibility/2006';
+const BINARY_PREFIX = 'b64:';
+
+export class DocxPackageError extends Error {}
+
+function isTextPart(name: string): boolean {
+ return name === CONTENT_TYPES_PART || /\.(xml|rels)$/i.test(name);
+}
+
+function bytesToBase64(bytes: Uint8Array): string {
+ let binary = '';
+ const chunk = 0x8000;
+ for (let i = 0; i < bytes.length; i += chunk)
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
+ return btoa(binary);
+}
+
+function base64ToBytes(value: string): Uint8Array {
+ const binary = atob(value);
+ const bytes = new Uint8Array(binary.length);
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
+ return bytes;
+}
+
+export function encodePart(name: string, bytes: Uint8Array): string {
+ return isTextPart(name)
+ ? strFromU8(bytes)
+ : BINARY_PREFIX + bytesToBase64(bytes);
+}
+
+export function decodePart(value: string): Uint8Array {
+ return value.startsWith(BINARY_PREFIX)
+ ? base64ToBytes(value.slice(BINARY_PREFIX.length))
+ : strToU8(value);
+}
+
+type StartTag = {
+ /** Qualified element name. */
+ name: string;
+ /** Offset of `<`. */
+ start: number;
+ /** Offset just past `>`. */
+ end: number;
+ selfClosing: boolean;
+};
+
+/** Offset just past the tag that opens at `start`, honouring quoted attribute values. */
+function tagEnd(xml: string, start: number): number {
+ let quote: string | null = null;
+ for (let i = start + 1; i < xml.length; i++) {
+ const char = xml[i];
+ if (quote) {
+ if (char === quote) quote = null;
+ } else if (char === '"' || char === "'") {
+ quote = char;
+ } else if (char === '>') {
+ return i + 1;
+ }
+ }
+ throw new DocxPackageError('unterminated XML tag');
+}
+
+function skipSpecial(xml: string, start: number): number | null {
+ if (xml.startsWith('<!--', start)) {
+ const end = xml.indexOf('-->', start + 4);
+ if (end < 0) throw new DocxPackageError('unterminated XML comment');
+ return end + 3;
+ }
+ if (xml.startsWith('<![CDATA[', start)) {
+ const end = xml.indexOf(']]>', start + 9);
+ if (end < 0) throw new DocxPackageError('unterminated CDATA section');
+ return end + 3;
+ }
+ if (xml.startsWith('<?', start)) {
+ const end = xml.indexOf('?>', start + 2);
+ if (end < 0)
+ throw new DocxPackageError('unterminated processing instruction');
+ return end + 2;
+ }
+ return null;
+}
+
+function readStartTag(xml: string, start: number): StartTag {
+ const end = tagEnd(xml, start);
+ const match = /^<([^\s/>]+)/.exec(
+ xml.slice(start, Math.min(end, start + 256))
+ );
+ if (!match) throw new DocxPackageError('malformed XML start tag');
+ return {
+ name: match[1],
+ start,
+ end,
+ selfClosing: xml[end - 2] === '/',
+ };
+}
+
+/** Offset just past the element whose start tag is `tag`. */
+function elementEnd(xml: string, tag: StartTag): number {
+ if (tag.selfClosing) return tag.end;
+ let depth = 1;
+ let i = tag.end;
+ while (i < xml.length) {
+ const lt = xml.indexOf('<', i);
+ if (lt < 0) break;
+ const special = skipSpecial(xml, lt);
+ if (special !== null) {
+ i = special;
+ continue;
+ }
+ const end = tagEnd(xml, lt);
+ if (xml[lt + 1] === '/') {
+ depth--;
+ if (depth === 0) return end;
+ } else if (xml[end - 2] !== '/') {
+ depth++;
+ }
+ i = end;
+ }
+ throw new DocxPackageError(`unterminated <${tag.name}> element`);
+}
+
+/** Namespace declarations made by one start tag (prefix → uri; '' is the default namespace). */
+function declarations(startTag: string): Map<string, string> {
+ const found = new Map<string, string>();
+ for (const match of startTag.matchAll(
+ /\sxmlns(?::([\w.-]+))?\s*=\s*"([^"]*)"/g
+ ))
+ found.set(match[1] ?? '', match[2]);
+ return found;
+}
+
+function attribute(startTag: string, qualifiedName: string): string | null {
+ const escaped = qualifiedName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ const match = new RegExp(`\\s${escaped}\\s*=\\s*"([^"]*)"`).exec(startTag);
+ return match ? match[1] : null;
+}
+
+function prefixFor(scope: Map<string, string>, uri: string): string | null {
+ for (const [prefix, value] of scope)
+ if (value === uri && prefix) return prefix;
+ return null;
+}
+
+/** Prefixes an element's markup uses, including those named by mc:Ignorable-style attributes. */
+function usedPrefixes(xml: string, mcPrefix: string | null): Set<string> {
+ const used = new Set<string>();
+ for (const match of xml.matchAll(/<\/?([A-Za-z_][\w.-]*):/g))
+ used.add(match[1]);
+ for (const match of xml.matchAll(
+ /\s([A-Za-z_][\w.-]*):[A-Za-z_][\w.-]*\s*=/g
+ ))
+ used.add(match[1]);
+ if (mcPrefix) {
+ const listed = new RegExp(
+ `\\s${mcPrefix}:(?:Ignorable|ProcessContent|MustUnderstand|PreserveElements|PreserveAttributes)\\s*=\\s*"([^"]*)"`,
+ 'g'
+ );
+ for (const match of xml.matchAll(listed))
+ for (const token of match[1].split(/\s+/)) {
+ const prefix = token.split(':')[0];
+ if (prefix) used.add(prefix);
+ }
+ }
+ used.delete('xmlns');
+ used.delete('xml');
+ return used;
+}
+
+/**
+ * Make an element extracted from its document self-describing: declare every
+ * namespace prefix it uses that an ancestor declared. Raw engine operations
+ * parse a block on its own, outside the document it came from.
+ */
+function standalone(
+ xml: string,
+ tag: StartTag,
+ scope: Map<string, string>,
+ mcPrefix: string | null
+): string {
+ const startTag = xml.slice(0, tag.end - tag.start);
+ const own = declarations(startTag);
+ const missing: string[] = [];
+ for (const prefix of usedPrefixes(xml, mcPrefix)) {
+ if (own.has(prefix)) continue;
+ const uri = scope.get(prefix);
+ if (uri !== undefined) missing.push(` xmlns:${prefix}="${uri}"`);
+ }
+ if (missing.length === 0) return xml;
+ const insertAt = tag.name.length + 1;
+ return xml.slice(0, insertAt) + missing.sort().join('') + xml.slice(insertAt);
+}
+
+export type SplitDocument = {
+ shell: string;
+ order: string[];
+ blocks: Map<string, string>;
+};
+
+/**
+ * Split `word/document.xml` into its top-level body elements and a shell that
+ * keeps everything else (root, namespaces, final section properties).
+ */
+export function splitDocumentXml(xml: string): SplitDocument {
+ let i = 0;
+ let root: StartTag | null = null;
+ while (i < xml.length) {
+ const lt = xml.indexOf('<', i);
+ if (lt < 0) break;
+ const special = skipSpecial(xml, lt);
+ if (special !== null) {
+ i = special;
+ continue;
+ }
+ root = readStartTag(xml, lt);
+ break;
+ }
+ if (!root) throw new DocxPackageError('document part has no root element');
+ const scope = declarations(xml.slice(root.start, root.end));
+ const w = prefixFor(scope, WORDML_NS);
+ if (!w) throw new DocxPackageError('document part is not WordprocessingML');
+
+ const bodyName = `${w}:body`;
+ let body: StartTag | null = null;
+ i = root.end;
+ while (i < xml.length) {
+ const lt = xml.indexOf('<', i);
+ if (lt < 0) break;
+ const special = skipSpecial(xml, lt);
+ if (special !== null) {
+ i = special;
+ continue;
+ }
+ if (xml[lt + 1] === '/') break;
+ const tag = readStartTag(xml, lt);
+ if (tag.name === bodyName) {
+ body = tag;
+ break;
+ }
+ i = elementEnd(xml, tag);
+ }
+ if (!body) throw new DocxPackageError('document part has no body');
+ if (body.selfClosing) {
+ return {
+ shell:
+ xml.slice(0, body.end - 2) +
+ `>${BLOCKS_PLACEHOLDER}</${bodyName}>` +
+ xml.slice(body.end),
+ order: [],
+ blocks: new Map(),
+ };
+ }
+ for (const [prefix, uri] of declarations(xml.slice(body.start, body.end)))
+ scope.set(prefix, uri);
+ const unidPrefix = prefixFor(scope, POWERTOOLS_NS);
+ const mcPrefix = prefixFor(scope, MARKUP_COMPATIBILITY_NS);
+
+ type Child = { tag: StartTag; end: number };
+ const children: Child[] = [];
+ let bodyClose = -1;
+ i = body.end;
+ while (i < xml.length) {
+ const lt = xml.indexOf('<', i);
+ if (lt < 0) break;
+ const special = skipSpecial(xml, lt);
+ if (special !== null) {
+ i = special;
+ continue;
+ }
+ if (xml[lt + 1] === '/') {
+ bodyClose = lt;
+ break;
+ }
+ const tag = readStartTag(xml, lt);
+ const end = elementEnd(xml, tag);
+ children.push({ tag, end });
+ i = end;
+ }
+ if (bodyClose < 0) throw new DocxPackageError('unterminated document body');
+
+ // The body's final sectPr describes the last section; it belongs to the shell.
+ const last = children.at(-1);
+ const finalSection =
+ last && last.tag.name === `${w}:sectPr` ? children.pop() : undefined;
+
+ const order: string[] = [];
+ const blocks = new Map<string, string>();
+ const seen = new Map<string, number>();
+ for (const child of children) {
+ const element = xml.slice(child.tag.start, child.end);
+ const startTag = xml.slice(child.tag.start, child.tag.end);
+ let id = unidPrefix ? attribute(startTag, `${unidPrefix}:Unid`) : null;
+ if (!id) {
+ // Every element the engine saves carries an id; fall back to a content
+ // address so a foreign package still splits deterministically.
+ const base = `x${fnv1a(element)}`;
+ const count = seen.get(base) ?? 0;
+ seen.set(base, count + 1);
+ id = count ? `${base}-${count}` : base;
+ }
+ if (blocks.has(id))
+ throw new DocxPackageError(`duplicate block id ${id} in document body`);
+ order.push(id);
+ blocks.set(id, standalone(element, child.tag, scope, mcPrefix));
+ }
+
+ const tail = finalSection
+ ? xml.slice(finalSection.tag.start, finalSection.end)
+ : '';
+ const shell =
+ xml.slice(0, body.end) + BLOCKS_PLACEHOLDER + tail + xml.slice(bodyClose);
+ return { shell, order, blocks };
+}
+
+function fnv1a(value: string): string {
+ let hash = 0x811c9dc5;
+ for (let i = 0; i < value.length; i++) {
+ hash ^= value.charCodeAt(i);
+ hash = Math.imul(hash, 0x01000193);
+ }
+ return (hash >>> 0).toString(16).padStart(8, '0');
+}
+
+/** Read an engine snapshot (saved with anchor ids) into collaboration state. */
+export function splitPackage(bytes: Uint8Array): DocxPackageState {
+ const files = unzipSync(bytes);
+ const document = files[DOCUMENT_PART];
+ if (!document) throw new DocxPackageError('package has no word/document.xml');
+ const split = splitDocumentXml(strFromU8(document));
+ const parts = new Map<string, string>();
+ for (const [name, content] of Object.entries(files)) {
+ if (name.endsWith('/')) continue;
+ parts.set(
+ name,
+ name === DOCUMENT_PART ? split.shell : encodePart(name, content)
+ );
+ }
+ return { order: split.order, blocks: split.blocks, parts };
+}
+
+/** The document part for `state`: its shell with the ordered blocks in the body. */
+export function assembleDocumentXml(state: DocxPackageState): string {
+ const shell = state.parts.get(DOCUMENT_PART);
+ if (shell === undefined || !shell.includes(BLOCKS_PLACEHOLDER))
+ throw new DocxPackageError('collaboration state has no document shell');
+ const body = state.order.map((id) => state.blocks.get(id) ?? '').join('');
+ return shell.replace(BLOCKS_PLACEHOLDER, () => body);
+}
+
+/** Build an openable package from collaboration state. */
+export function assemblePackage(state: DocxPackageState): Uint8Array {
+ const files: Zippable = {};
+ const contentTypes = state.parts.get(CONTENT_TYPES_PART);
+ if (contentTypes !== undefined)
+ files[CONTENT_TYPES_PART] = strToU8(contentTypes);
+ for (const [name, value] of state.parts) {
+ if (name === CONTENT_TYPES_PART) continue;
+ files[name] =
+ name === DOCUMENT_PART
+ ? strToU8(assembleDocumentXml(state))
+ : decodePart(value);
+ }
+ // Stored, not deflated: the package is opened in-process immediately.
+ return zipSync(files, { level: 0 });
+}
diff --git a/apps/web/src/features/block-write/core/docx-seed.ts b/apps/web/src/features/block-write/core/docx-seed.ts
new file mode 100644
index 0000000000..e35307c620
--- /dev/null
+++ b/apps/web/src/features/block-write/core/docx-seed.ts
@@ -0,0 +1,38 @@
+import { LoroDoc } from 'loro-crdt';
+import { bridgeEngine, type DocxSyncBridge } from './docx-engine';
+import { seedDocxState } from './docx-loro';
+
+/** Settings every session in a collaborative editor is opened with. */
+export const DOCX_SYNC_SESSION_SETTINGS = {
+ // The editor re-renders from HTML; markdown patches are wasted work.
+ emitMarkdownPatch: false,
+ // Raw operations only ever carry XML the engine itself serialized.
+ validateRawOps: false,
+};
+
+type SeedBridge = DocxSyncBridge & {
+ OpenSession: (bytes: Uint8Array, settingsJson: string) => number;
+ CloseSession: (handle: number) => void;
+};
+
+/**
+ * The first collaborative snapshot of an uploaded DOCX: open it once, split
+ * the engine's save into blocks and parts, and write them to a new Loro
+ * document. Every peer that opens the same upload derives the same block ids.
+ */
+export function buildSeedSnapshot(
+ bridge: SeedBridge,
+ bytes: Uint8Array
+): Uint8Array {
+ const handle = bridge.OpenSession(
+ bytes,
+ JSON.stringify(DOCX_SYNC_SESSION_SETTINGS)
+ );
+ try {
+ const doc = new LoroDoc();
+ seedDocxState(doc, bridgeEngine(bridge, () => handle).snapshot());
+ return doc.export({ mode: 'snapshot' });
+ } finally {
+ bridge.CloseSession(handle);
+ }
+}
diff --git a/apps/web/src/features/block-write/core/docx-sync.test.ts b/apps/web/src/features/block-write/core/docx-sync.test.ts
new file mode 100644
index 0000000000..db13987558
--- /dev/null
+++ b/apps/web/src/features/block-write/core/docx-sync.test.ts
@@ -0,0 +1,286 @@
+// @vitest-environment node
+import { afterEach, beforeAll, describe, expect, it } from 'vitest';
+import { bridge, fixture, loadEngine, TestPeer } from '../tests/docx-test-peer';
+import { readDocxState } from './docx-loro';
+
+beforeAll(loadEngine, 60_000);
+
+const peers: TestPeer[] = [];
+afterEach(() => {
+ for (const peer of peers.splice(0)) peer.close();
+});
+
+/** A seeding peer plus `count - 1` peers joined from its snapshot. */
+function room(count: number, name = 'mutual-nda.docx'): TestPeer[] {
+ const bytes = fixture(name);
+ const first = new TestPeer(bytes);
+ const seed = first.doc.export({ mode: 'snapshot' });
+ const all = [first];
+ for (let i = 1; i < count; i++) all.push(new TestPeer(bytes, seed));
+ peers.push(...all);
+ return all;
+}
+
+function exchange(all: TestPeer[]) {
+ for (let round = 0; round < 2; round++)
+ for (const peer of all)
+ peer.deliver(...all.filter((other) => other !== peer));
+}
+
+function expectConverged(all: TestPeer[]) {
+ const [first, ...rest] = all;
+ const shared = readDocxState(first.doc);
+ for (const peer of rest) {
+ expect(peer.text()).toEqual(first.text());
+ expect(readDocxState(peer.doc).order).toEqual(shared.order);
+ }
+ // The engine sessions agree with the shared document they converged on.
+ for (const peer of all)
+ expect(peer.sync.sharedState.order).toEqual(shared.order);
+}
+
+function anchor(peer: TestPeer, index: number) {
+ return peer.bodyIds()[index];
+}
+
+function edit(peer: TestPeer, index: number, text: string) {
+ const result = JSON.parse(
+ bridge().ReplaceTextAtSpan(peer.handle, anchor(peer, index), 0, 0, text)
+ );
+ expect(result.success).toBe(true);
+ peer.sync.publishLocal();
+}
+
+describe('DocxSyncController', () => {
+ it('opens joining peers on the seeded document', () => {
+ const [alice, bob] = room(2);
+ expect(bob.bodyIds()).toEqual(alice.bodyIds());
+ expect(bob.text()).toEqual(alice.text());
+ });
+
+ it('propagates a text edit by patching only that block', () => {
+ const [alice, bob] = room(2);
+ edit(alice, 1, 'AMENDED: ');
+ alice.deliver(bob);
+ expect(bob.text()[1].startsWith('AMENDED: ')).toBe(true);
+ expect(bob.rebuilds).toBe(0);
+ expectConverged([alice, bob]);
+ });
+
+ it('merges concurrent edits to different paragraphs', () => {
+ const [alice, bob, carol] = room(3);
+ edit(alice, 1, '[alice] ');
+ edit(bob, 3, '[bob] ');
+ edit(carol, 4, '[carol] ');
+ exchange([alice, bob, carol]);
+ expectConverged([alice, bob, carol]);
+ const text = alice.text();
+ expect(text[1].startsWith('[alice] ')).toBe(true);
+ expect(text[3].startsWith('[bob] ')).toBe(true);
+ expect(text[4].startsWith('[carol] ')).toBe(true);
+ });
+
+ it('converges when two peers edit the same paragraph at once', () => {
+ const [alice, bob] = room(2);
+ edit(alice, 1, '[alice] ');
+ edit(bob, 1, '[bob] ');
+ exchange([alice, bob]);
+ expectConverged([alice, bob]);
+ expect(
+ ['[alice] ', '[bob] '].some((p) => alice.text()[1].startsWith(p))
+ ).toBe(true);
+ });
+
+ it('propagates paragraph splits, merges, deletes and moves', () => {
+ const [alice, bob] = room(2);
+ const engine = bridge();
+ expect(
+ JSON.parse(engine.SplitParagraph(alice.handle, anchor(alice, 1), 20))
+ .success
+ ).toBe(true);
+ alice.sync.publishLocal();
+ alice.deliver(bob);
+ expectConverged([alice, bob]);
+ expect(bob.bodyIds()).toEqual(alice.bodyIds());
+
+ expect(
+ JSON.parse(
+ engine.MergeParagraphs(alice.handle, anchor(alice, 1), anchor(alice, 2))
+ ).success
+ ).toBe(true);
+ alice.sync.publishLocal();
+ alice.deliver(bob);
+ expectConverged([alice, bob]);
+
+ expect(
+ JSON.parse(engine.DeleteBlock(bob.handle, anchor(bob, 3))).success
+ ).toBe(true);
+ bob.sync.publishLocal();
+ bob.deliver(alice);
+ expectConverged([alice, bob]);
+
+ expect(
+ JSON.parse(
+ engine.MoveBlock(
+ alice.handle,
+ anchor(alice, 5),
+ anchor(alice, 1),
+ 'before'
+ )
+ ).success
+ ).toBe(true);
+ alice.sync.publishLocal();
+ alice.deliver(bob);
+ expectConverged([alice, bob]);
+ expect(alice.rebuilds + bob.rebuilds).toBe(0);
+ });
+
+ it('keeps concurrent inserts from both peers', () => {
+ const [alice, bob] = room(2);
+ const engine = bridge();
+ engine.SplitParagraph(alice.handle, anchor(alice, 1), 10);
+ alice.sync.publishLocal();
+ engine.SplitParagraph(bob.handle, anchor(bob, 1), 30);
+ bob.sync.publishLocal();
+ const before = alice.bodyIds().length;
+ exchange([alice, bob]);
+ expectConverged([alice, bob]);
+ expect(alice.bodyIds().length).toBe(before + 1);
+ });
+
+ it('replicates undo as an ordinary change', () => {
+ const [alice, bob] = room(2);
+ const original = alice.text()[1];
+ edit(alice, 1, 'Typo ');
+ alice.deliver(bob);
+ expect(bridge().Undo(alice.handle)).toBe(true);
+ alice.sync.publishLocal();
+ alice.deliver(bob);
+ expect(bob.text()[1]).toBe(original);
+ expectConverged([alice, bob]);
+ });
+
+ it('rebuilds peers when an edit changes a package part', () => {
+ const [alice, bob] = room(2);
+ const result = JSON.parse(
+ bridge().ApplyListFormat(alice.handle, anchor(alice, 1), 'bullet')
+ );
+ expect(result.success).toBe(true);
+ alice.sync.publishLocal();
+ alice.deliver(bob);
+ expectConverged([alice, bob]);
+ expect(bob.rebuilds).toBe(1);
+ });
+
+ it('opens a late joiner on the merged document', () => {
+ const [alice, bob] = room(2);
+ edit(alice, 1, '[alice] ');
+ edit(bob, 4, '[bob] ');
+ exchange([alice, bob]);
+ const late = new TestPeer(
+ fixture('mutual-nda.docx'),
+ alice.doc.export({ mode: 'snapshot' })
+ );
+ peers.push(late);
+ expectConverged([alice, bob, late]);
+ });
+
+ it('defers a remote change to a block the user is still typing in', () => {
+ const [alice, bob] = room(2);
+ const busy = anchor(bob, 1).split(':')[2];
+ const host = (
+ bob.sync as unknown as { host: { isBusy?: (id: string) => boolean } }
+ ).host;
+ host.isBusy = (id) => id === busy;
+ edit(alice, 1, '[alice] ');
+ alice.deliver(bob);
+ expect(bob.text()[1].startsWith('[alice] ')).toBe(false);
+ // Once the typing commits, this peer's version wins and both converge.
+ host.isBusy = () => false;
+ edit(bob, 1, '[bob] ');
+ bob.deliver(alice);
+ expectConverged([alice, bob]);
+ expect(alice.text()[1].startsWith('[bob] ')).toBe(true);
+ });
+
+ it('handles documents with tables, content controls and headers', () => {
+ const [alice, bob] = room(2, 'complex-msa.docx');
+ const ids = alice.bodyIds();
+ const table = ids.findIndex((id) => id.startsWith('tbl:'));
+ expect(table).toBeGreaterThan(0);
+ edit(alice, 2, 'Edited: ');
+ expect(
+ JSON.parse(
+ bridge().InsertTableRow(alice.handle, cellAnchor(alice), 'below')
+ ).success
+ ).toBe(true);
+ alice.sync.publishLocal();
+ alice.deliver(bob);
+ expectConverged([alice, bob]);
+ });
+});
+
+describe('randomized collaboration', () => {
+ it.each([11, 29, 47])(
+ 'converges after random concurrent edits (seed %i)',
+ (seed) => {
+ let state = seed;
+ const random = () => {
+ state = (state * 16807) % 2147483647;
+ return state / 2147483647;
+ };
+ const pick = <T>(items: readonly T[]) =>
+ items[Math.floor(random() * items.length)];
+ const all = room(3);
+ const engine = bridge();
+ for (let step = 0; step < 40; step++) {
+ const peer = pick(all);
+ const paragraphs = peer
+ .bodyIds()
+ .filter((id) => id.startsWith('p:') || id.startsWith('h:'));
+ const target = pick(paragraphs);
+ const length = peer.blockText(target).length;
+ const operation = Math.floor(random() * 5);
+ if (operation === 0 || operation === 1) {
+ engine.ReplaceTextAtSpan(
+ peer.handle,
+ target,
+ Math.floor(random() * (length + 1)),
+ 0,
+ `<${step}>`
+ );
+ } else if (operation === 2 && length > 2) {
+ engine.SplitParagraph(
+ peer.handle,
+ target,
+ 1 + Math.floor(random() * (length - 1))
+ );
+ } else if (operation === 3 && paragraphs.length > 6) {
+ engine.DeleteBlock(peer.handle, target);
+ } else if (operation === 4) {
+ const other = pick(paragraphs);
+ if (other !== target)
+ engine.MoveBlock(
+ peer.handle,
+ target,
+ other,
+ pick(['before', 'after'])
+ );
+ }
+ peer.sync.publishLocal();
+ if (random() < 0.4) peer.deliver(...all.filter((p) => p !== peer));
+ }
+ exchange(all);
+ expectConverged(all);
+ },
+ 60_000
+ );
+});
+
+function cellAnchor(peer: TestPeer): string {
+ const anchors = JSON.parse(bridge().ListAnchors!(peer.handle))
+ .anchorIndex as Record<string, unknown>;
+ const cell = Object.keys(anchors).find((id) => id.startsWith('tc:'));
+ if (!cell) throw new Error('fixture has no table cell');
+ return cell;
+}
diff --git a/apps/web/src/features/block-write/core/docx-sync.ts b/apps/web/src/features/block-write/core/docx-sync.ts
new file mode 100644
index 0000000000..899429aad9
--- /dev/null
+++ b/apps/web/src/features/block-write/core/docx-sync.ts
@@ -0,0 +1,221 @@
+import type { LoroDoc } from 'loro-crdt';
+import type { DocxEngine } from './docx-engine';
+import {
+ type DocxChanges,
+ diffDocxStates,
+ hasChanges,
+ readDocxState,
+ writeDocxChanges,
+} from './docx-loro';
+import { assemblePackage, type DocxPackageState } from './docx-package';
+
+/** What the sync controller needs from the editor that owns the session. */
+export type DocxSyncHost = {
+ /** The engine for the session currently on screen. */
+ engine(): DocxEngine;
+ /** Repaint after the session was changed outside the editor's own commands. */
+ refresh(): void;
+ /** Replace the session with a package and remount the editor. */
+ rebuild(bytes: Uint8Array): void;
+ /** True while a block holds typing the editor has not committed yet. */
+ isBusy?(blockId: string): boolean;
+};
+
+export type RemoteOutcome = 'unchanged' | 'patched' | 'rebuilt';
+
+/** More block operations than this remount instead of patching one by one. */
+const MAX_PATCH_OPERATIONS = 64;
+
+function applyChanges(
+ state: DocxPackageState,
+ changes: DocxChanges,
+ order: readonly string[]
+): DocxPackageState {
+ const blocks = new Map(state.blocks);
+ for (const [id, xml] of changes.upserts) blocks.set(id, xml);
+ for (const id of changes.removed) blocks.delete(id);
+ const parts = new Map(state.parts);
+ for (const [name, value] of changes.parts) {
+ if (value === null) parts.delete(name);
+ else parts.set(name, value);
+ }
+ return { order: [...order], blocks, parts };
+}
+
+/** Indices of `sequence` that form a longest common subsequence with `target`. */
+function stableIds(
+ sequence: readonly string[],
+ target: readonly string[]
+): Set<string> {
+ const position = new Map(target.map((id, index) => [id, index]));
+ const ranks = sequence.map((id) => position.get(id) ?? -1);
+ const tails: number[] = [];
+ const previous = new Array<number>(ranks.length).fill(-1);
+ ranks.forEach((rank, index) => {
+ if (rank < 0) return;
+ let low = 0;
+ let high = tails.length;
+ while (low < high) {
+ const mid = (low + high) >> 1;
+ if (ranks[tails[mid]] < rank) low = mid + 1;
+ else high = mid;
+ }
+ if (low > 0) previous[index] = tails[low - 1];
+ tails[low] = index;
+ });
+ const stable = new Set<string>();
+ let cursor = tails.length ? tails[tails.length - 1] : -1;
+ while (cursor >= 0) {
+ stable.add(sequence[cursor]);
+ cursor = previous[cursor];
+ }
+ return stable;
+}
+
+/**
+ * Keeps one live Docxodus session and one collaborative Loro document in step.
+ *
+ * Two baselines make the exchange echo-free: `session` is what the engine held
+ * when the two last agreed, and `shared` is what the Loro document held. Local
+ * publishing diffs the engine against `session`; remote application diffs Loro
+ * against `shared`. Re-serialization differences between the two never show up
+ * as edits on either side.
+ */
+export class DocxSyncController {
+ private session: DocxPackageState;
+ private shared: DocxPackageState;
+
+ constructor(
+ private readonly doc: LoroDoc,
+ private readonly host: DocxSyncHost
+ ) {
+ this.session = host.engine().snapshot();
+ this.shared = readDocxState(doc);
+ }
+
+ /** The collaborative document as last applied to the session. */
+ get sharedState(): DocxPackageState {
+ return this.shared;
+ }
+
+ /** Publish edits made in the session since the last exchange. */
+ publishLocal(): boolean {
+ const current = this.host.engine().snapshot();
+ const changes = diffDocxStates(this.session, current);
+ this.session = current;
+ if (!hasChanges(changes)) return false;
+ writeDocxChanges(this.doc, changes);
+ this.shared = applyChanges(this.shared, changes, current.order);
+ return true;
+ }
+
+ /** Bring the session up to date with the collaborative document. */
+ applyRemote(): RemoteOutcome {
+ // Never let a remote patch overwrite committed-but-unpublished edits.
+ this.publishLocal();
+ const next = readDocxState(this.doc);
+ const changes = diffDocxStates(this.shared, next);
+ if (!hasChanges(changes)) {
+ this.shared = next;
+ return 'unchanged';
+ }
+ const deferred = new Map<string, string>();
+ if (changes.parts.size === 0 && this.patch(next, changes, deferred)) {
+ this.host.refresh();
+ this.session = this.host.engine().snapshot();
+ const blocks = new Map(next.blocks);
+ for (const [id, xml] of deferred) blocks.set(id, xml);
+ this.shared = { ...next, blocks };
+ return 'patched';
+ }
+ this.rebuild(next);
+ return 'rebuilt';
+ }
+
+ /** Replace the session wholesale with the collaborative document. */
+ rebuild(next: DocxPackageState = readDocxState(this.doc)) {
+ this.host.rebuild(assemblePackage(next));
+ this.session = this.host.engine().snapshot();
+ this.shared = next;
+ }
+
+ /**
+ * Translate block changes into raw engine operations. Returns false when the
+ * session cannot be patched in place, leaving the caller to rebuild.
+ * `deferred` collects blocks skipped because the user is typing in them,
+ * mapped to the shared content they last agreed on.
+ */
+ private patch(
+ next: DocxPackageState,
+ changes: DocxChanges,
+ deferred: Map<string, string>
+ ): boolean {
+ const engine = this.host.engine();
+ const target = next.order;
+ const removed = new Set(changes.removed);
+ const sessionOrder = this.session.order.filter((id) => !removed.has(id));
+ const inSession = new Set(sessionOrder);
+ // Blocks the session has that the shared document neither has nor removed
+ // mean the two diverged in a way a patch cannot reason about.
+ const wanted = new Set(target);
+ if (sessionOrder.some((id) => !wanted.has(id))) return false;
+
+ const stable = stableIds(sessionOrder, target);
+ const operations =
+ changes.removed.length +
+ target.filter((id) => !stable.has(id)).length +
+ changes.upserts.size;
+ if (operations > MAX_PATCH_OPERATIONS) return false;
+
+ let anchors = engine.bodyAnchors();
+ const anchorOf = (id: string): string | undefined => {
+ const known = anchors.get(id);
+ if (known) return known;
+ anchors = engine.bodyAnchors();
+ return anchors.get(id);
+ };
+
+ for (const id of changes.removed) {
+ if (!this.session.blocks.has(id)) continue;
+ const anchor = anchorOf(id);
+ if (!anchor || !engine.deleteBlock(anchor)) return false;
+ }
+
+ const inserted = new Set<string>();
+ const firstStable = target.find((id) => stable.has(id));
+ let previous: string | null = null;
+ for (const id of target) {
+ if (!stable.has(id)) {
+ const neighbour =
+ previous ?? firstStable ?? sessionOrder.find((other) => other !== id);
+ const position = previous ? 'after' : 'before';
+ const neighbourAnchor = neighbour ? anchorOf(neighbour) : undefined;
+ if (!neighbourAnchor) return false;
+ if (inSession.has(id)) {
+ const anchor = anchorOf(id);
+ if (!anchor || !engine.moveBlock(anchor, neighbourAnchor, position))
+ return false;
+ } else {
+ const xml = next.blocks.get(id);
+ if (xml === undefined) return false;
+ if (!engine.insertBlock(neighbourAnchor, position, xml)) return false;
+ inserted.add(id);
+ inSession.add(id);
+ }
+ }
+ previous = id;
+ }
+
+ for (const [id, xml] of changes.upserts) {
+ if (inserted.has(id)) continue;
+ if (this.host.isBusy?.(id)) {
+ const agreed = this.shared.blocks.get(id);
+ if (agreed !== undefined) deferred.set(id, agreed);
+ continue;
+ }
+ const anchor = anchorOf(id);
+ if (!anchor || !engine.replaceBlock(anchor, xml)) return false;
+ }
+ return true;
+ }
+}
diff --git a/apps/web/src/features/block-write/core/editor-bridge.ts b/apps/web/src/features/block-write/core/editor-bridge.ts
new file mode 100644
index 0000000000..742b01304d
--- /dev/null
+++ b/apps/web/src/features/block-write/core/editor-bridge.ts
@@ -0,0 +1,199 @@
+import type { DocxEditorExports } from 'docxodus';
+
+/**
+ * Bridge calls that read the session without changing it. Everything else is
+ * treated as a mutation, so a Docxodus release that adds an editing command is
+ * published conservatively instead of silently dropped.
+ */
+const READ_ONLY_CALLS = new Set([
+ 'CloseSession',
+ 'CreateBlankDocx',
+ 'GetDiff',
+ 'GetEditSummary',
+ 'GetFormatting',
+ 'GetImageCapabilities',
+ 'GetListMembership',
+ 'GetSectionInfo',
+ 'GetVersion',
+ 'Grep',
+ 'GrepCrossBlock',
+ 'ListAnchors',
+ 'ListBlocks',
+ 'ListBookmarks',
+ 'ListComments',
+ 'ListContentControls',
+ 'ListHyperlinks',
+ 'ListImages',
+ 'ListInlineSpans',
+ 'ListNotes',
+ 'ListRenderedBlocks',
+ 'ListRevisions',
+ 'ListStyles',
+ 'OpenSession',
+ 'Project',
+ 'RawGetXml',
+ 'RemainingPlaceholders',
+ 'Save',
+ 'SaveWithAnchorIds',
+ 'ValidMoveTargets',
+]);
+
+const isRead = (name: string) =>
+ READ_ONLY_CALLS.has(name) ||
+ name.startsWith('Render') ||
+ name.startsWith('Find');
+
+/** Whole-document renders whose stylesheet must be scoped to the editor. */
+const DOCUMENT_RENDERS = [
+ 'RenderHtml',
+ 'RenderHtmlForReview',
+ 'RenderEditorHtml',
+] as const;
+
+export type EditorBridgeOptions = {
+ /** Selector of the editor's mount; document CSS is confined to it. */
+ rootSelector: string;
+ /** Settings merged into every session the editor opens. */
+ sessionSettings: Record<string, unknown>;
+ /** Called after every bridge call that may have changed the session. */
+ onMutation: (call: string) => void;
+};
+
+type AnyFunction = (...args: never[]) => unknown;
+
+/**
+ * The editor's view of the engine: every session is opened with the sync
+ * settings, document styles are scoped so the converter's `body`/`span` rules
+ * cannot restyle the app, and mutations are reported for publishing.
+ */
+export function editorBridge(
+ exports: DocxEditorExports,
+ options: EditorBridgeOptions
+): DocxEditorExports {
+ const source = exports.DocxSessionBridge as unknown as Record<
+ string,
+ unknown
+ >;
+ const bridge: Record<string, unknown> = {};
+ for (const [name, value] of Object.entries(source)) {
+ if (typeof value !== 'function') {
+ bridge[name] = value;
+ continue;
+ }
+ const call = value as AnyFunction;
+ if (name === 'OpenSession') {
+ bridge[name] = (bytes: Uint8Array, settingsJson: string) => {
+ const requested = settingsJson
+ ? (JSON.parse(settingsJson) as object)
+ : {};
+ return (call as (b: Uint8Array, s: string) => number)(
+ bytes,
+ JSON.stringify({ ...requested, ...options.sessionSettings })
+ );
+ };
+ } else if ((DOCUMENT_RENDERS as readonly string[]).includes(name)) {
+ bridge[name] = (...args: never[]) =>
+ scopeDocumentStyles(call(...args) as string, options.rootSelector);
+ } else if (isRead(name)) {
+ bridge[name] = call;
+ } else {
+ bridge[name] = (...args: never[]) => {
+ const result = call(...args);
+ options.onMutation(name);
+ return result;
+ };
+ }
+ }
+ const convert = exports.DocumentConverter.ConvertDocxToHtmlComplete;
+ return {
+ DocxSessionBridge: bridge as DocxEditorExports['DocxSessionBridge'],
+ DocumentConverter: {
+ ConvertDocxToHtmlComplete: (...args: unknown[]) =>
+ scopeDocumentStyles(convert(...args), options.rootSelector),
+ },
+ };
+}
+
+const SCOPED_ATTRIBUTE = 'data-macro-docx-scoped';
+
+function splitSelectors(selectorText: string): string[] {
+ const selectors: string[] = [];
+ let depth = 0;
+ let start = 0;
+ for (let i = 0; i < selectorText.length; i++) {
+ const char = selectorText[i];
+ if (char === '(' || char === '[') depth++;
+ else if (char === ')' || char === ']') depth--;
+ else if (char === ',' && depth === 0) {
+ selectors.push(selectorText.slice(start, i).trim());
+ start = i + 1;
+ }
+ }
+ selectors.push(selectorText.slice(start).trim());
+ return selectors.filter(Boolean);
+}
+
+/** Re-root one selector: the document's `html`/`body`/`:root` become the mount. */
+export function scopeSelector(selector: string, root: string): string {
+ let rest = selector.trim();
+ let consumed = false;
+ let separated = false;
+ for (;;) {
+ const match = /^(?:html|body|:root)(?=$|[\s>+~.#[:])/.exec(rest);
+ if (!match) break;
+ consumed = true;
+ rest = rest.slice(match[0].length);
+ const space = /^\s+/.exec(rest);
+ separated = !!space;
+ if (!space) break;
+ rest = rest.slice(space[0].length);
+ }
+ if (!consumed) return `${root} ${rest}`;
+ if (!rest) return root;
+ if (separated || /^[>+~]/.test(rest)) return `${root} ${rest}`;
+ return `${root}${rest}`;
+}
+
+function scopeRules(container: CSSStyleSheet | CSSGroupingRule, root: string) {
+ for (let i = container.cssRules.length - 1; i >= 0; i--) {
+ const rule = container.cssRules[i];
+ // @page and @import cannot be confined to an element; drop them.
+ if (rule instanceof CSSPageRule || rule instanceof CSSImportRule) {
+ container.deleteRule(i);
+ } else if (rule instanceof CSSStyleRule) {
+ rule.selectorText = splitSelectors(rule.selectorText)
+ .map((selector) => scopeSelector(selector, root))
+ .join(', ');
+ } else if ('cssRules' in rule) {
+ scopeRules(rule as CSSGroupingRule, root);
+ }
+ }
+}
+
+function scopeStyle(style: HTMLStyleElement, root: string) {
+ if (style.hasAttribute(SCOPED_ATTRIBUTE)) return;
+ // Parse with the browser's CSSOM in an inert sheet, then write it back.
+ const parser = document.createElement('style');
+ parser.media = 'not all';
+ parser.textContent = style.textContent ?? '';
+ document.head.appendChild(parser);
+ try {
+ const sheet = parser.sheet;
+ if (!sheet) return;
+ scopeRules(sheet, root);
+ style.textContent = Array.from(sheet.cssRules, (rule) => rule.cssText).join(
+ '\n'
+ );
+ style.setAttribute(SCOPED_ATTRIBUTE, '');
+ } finally {
+ parser.remove();
+ }
+}
+
+function scopeDocumentStyles(html: string, root: string): string {
+ if (!html || html.charCodeAt(0) === 0x7b /* error object */) return html;
+ const parsed = new DOMParser().parseFromString(html, 'text/html');
+ for (const style of Array.from(parsed.querySelectorAll('style')))
+ scopeStyle(style, root);
+ return `<!doctype html>\n${parsed.documentElement.outerHTML}`;
+}
diff --git a/apps/web/src/features/block-write/core/fixtures/complex-msa.docx b/apps/web/src/features/block-write/core/fixtures/complex-msa.docx
new file mode 100644
index 0000000000..70e1c17282
Binary files /dev/null and b/apps/web/src/features/block-write/core/fixtures/complex-msa.docx differ
diff --git a/apps/web/src/features/block-write/core/fixtures/mutual-nda.docx b/apps/web/src/features/block-write/core/fixtures/mutual-nda.docx
new file mode 100644
index 0000000000..e87d7e8539
Binary files /dev/null and b/apps/web/src/features/block-write/core/fixtures/mutual-nda.docx differ
diff --git a/apps/web/src/features/block-write/core/fractional-index.test.ts b/apps/web/src/features/block-write/core/fractional-index.test.ts
new file mode 100644
index 0000000000..12346280fc
--- /dev/null
+++ b/apps/web/src/features/block-write/core/fractional-index.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it } from 'vitest';
+import { compareKeyed, keyBetween, keysBetween } from './fractional-index';
+
+describe('fractional keys', () => {
+ it('orders keys between open and closed bounds', () => {
+ const first = keyBetween(null, null);
+ const before = keyBetween(null, first);
+ const after = keyBetween(first, null);
+ expect(before < first && first < after).toBe(true);
+ expect(keyBetween(before, first) > before).toBe(true);
+ expect(keyBetween(before, first) < first).toBe(true);
+ });
+
+ it('keeps inserting into the same gap without breaking order', () => {
+ let low: string | null = null;
+ const high = keyBetween(null, null);
+ for (let i = 0; i < 200; i++) {
+ const next = keyBetween(low, high);
+ if (low !== null) expect(next > low).toBe(true);
+ expect(next < high).toBe(true);
+ expect(next.endsWith('0')).toBe(false);
+ low = next;
+ }
+ });
+
+ it('survives random insertion sequences', () => {
+ const keys: string[] = [];
+ let seed = 7;
+ const random = () => {
+ seed = (seed * 16807) % 2147483647;
+ return seed / 2147483647;
+ };
+ for (let i = 0; i < 500; i++) {
+ const at = Math.floor(random() * (keys.length + 1));
+ const key = keyBetween(keys[at - 1] ?? null, keys[at] ?? null);
+ keys.splice(at, 0, key);
+ }
+ const sorted = [...keys].sort();
+ expect(keys).toEqual(sorted);
+ expect(new Set(keys).size).toBe(keys.length);
+ });
+
+ it('spreads many keys with short lengths', () => {
+ const keys = keysBetween(null, null, 2000);
+ expect(keys).toEqual([...keys].sort());
+ expect(new Set(keys).size).toBe(2000);
+ expect(Math.max(...keys.map((key) => key.length))).toBeLessThanOrEqual(4);
+ });
+
+ it('rejects reversed or malformed bounds', () => {
+ expect(() => keyBetween('b', 'a')).toThrow();
+ expect(() => keyBetween('a0', null)).toThrow();
+ expect(() => keyBetween('a!', null)).toThrow();
+ });
+
+ it('breaks equal-key ties by id', () => {
+ const entries = [
+ { key: 'V', id: 'b' },
+ { key: 'V', id: 'a' },
+ { key: 'A', id: 'z' },
+ ].sort(compareKeyed);
+ expect(entries.map((entry) => entry.id)).toEqual(['z', 'a', 'b']);
+ });
+});
diff --git a/apps/web/src/features/block-write/core/fractional-index.ts b/apps/web/src/features/block-write/core/fractional-index.ts
new file mode 100644
index 0000000000..2e76083b26
--- /dev/null
+++ b/apps/web/src/features/block-write/core/fractional-index.ts
@@ -0,0 +1,79 @@
+/**
+ * Fractional position keys for ordering blocks inside a CRDT map.
+ *
+ * Keys are base-62 fractions in (0, 1) compared as plain strings. A key never
+ * ends in the smallest digit, so there is always room before and after it.
+ * Concurrent writers can mint the same key; readers break ties by block id.
+ */
+
+const DIGITS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
+const BASE = DIGITS.length;
+
+function digitValue(char: string): number {
+ const value = DIGITS.indexOf(char);
+ if (value < 0) throw new Error(`invalid fractional key digit "${char}"`);
+ return value;
+}
+
+function midpoint(low: string, high: string | null): string {
+ if (high !== null) {
+ let shared = 0;
+ while (shared < high.length && (low[shared] ?? DIGITS[0]) === high[shared])
+ shared++;
+ if (shared > 0)
+ return (
+ high.slice(0, shared) + midpoint(low.slice(shared), high.slice(shared))
+ );
+ }
+ const lowDigit = low ? digitValue(low[0]) : 0;
+ const highDigit = high !== null ? digitValue(high[0]) : BASE;
+ if (highDigit - lowDigit > 1)
+ return DIGITS[Math.floor((lowDigit + highDigit) / 2)];
+ // Adjacent digits: the high key's first digit alone sorts between them when
+ // the high key continues, otherwise extend the low key.
+ if (high !== null && high.length > 1) return high[0];
+ return DIGITS[lowDigit] + midpoint(low.slice(1), null);
+}
+
+function assertKey(key: string | null, name: string) {
+ if (key === null) return;
+ if (key === '' || key.endsWith(DIGITS[0]))
+ throw new Error(`invalid fractional ${name} key "${key}"`);
+ for (const char of key) digitValue(char);
+}
+
+/** A key strictly between `low` and `high`; null means the open end. */
+export function keyBetween(low: string | null, high: string | null): string {
+ assertKey(low, 'low');
+ assertKey(high, 'high');
+ if (low !== null && high !== null && low >= high)
+ throw new Error(`fractional keys out of order: ${low} >= ${high}`);
+ return midpoint(low ?? '', high);
+}
+
+/** `count` ascending keys between `low` and `high`, growing logarithmically. */
+export function keysBetween(
+ low: string | null,
+ high: string | null,
+ count: number
+): string[] {
+ if (count <= 0) return [];
+ const middle = keyBetween(low, high);
+ if (count === 1) return [middle];
+ const before = Math.floor((count - 1) / 2);
+ return [
+ ...keysBetween(low, middle, before),
+ middle,
+ ...keysBetween(middle, high, count - 1 - before),
+ ];
+}
+
+/** Stable order for (key, id) pairs: key first, id breaks concurrent ties. */
+export function compareKeyed(
+ a: { key: string; id: string },
+ b: { key: string; id: string }
+): number {
+ if (a.key !== b.key) return a.key < b.key ? -1 : 1;
+ if (a.id === b.id) return 0;
+ return a.id < b.id ? -1 : 1;
+}
diff --git a/apps/web/src/features/block-write/core/text-offsets.test.ts b/apps/web/src/features/block-write/core/text-offsets.test.ts
new file mode 100644
index 0000000000..5cd5fc82ca
--- /dev/null
+++ b/apps/web/src/features/block-write/core/text-offsets.test.ts
@@ -0,0 +1,69 @@
+import { beforeEach, describe, expect, it } from 'vitest';
+import {
+ blockOf,
+ blockSpanOfRange,
+ contentOffset,
+ contentRange,
+ contentText,
+} from './text-offsets';
+
+let root: HTMLElement;
+
+beforeEach(() => {
+ document.body.innerHTML = `
+ <div id="root">
+ <p data-anchor="p1"><span data-list-marker="">1.</span><span>‎Hello </span><b>bold</b><span> world</span></p>
+ <p data-anchor="p2">Page <span data-field="" data-field-cached="7">12</span> end</p>
+ </div>`;
+ root = document.getElementById('root')!;
+});
+
+const block = (id: string) =>
+ root.querySelector<HTMLElement>(`[data-anchor="${id}"]`)!;
+
+describe('content offsets', () => {
+ it('excludes list markers and bidi marks from the text', () => {
+ expect(contentText(block('p1'))).toBe('Hello bold world');
+ });
+
+ it('counts a field as its cached result', () => {
+ expect(contentText(block('p2'))).toBe('Page 7 end');
+ });
+
+ it('maps DOM positions to content offsets', () => {
+ const bold = block('p1').querySelector('b')!.firstChild!;
+ expect(contentOffset(block('p1'), bold, 2)).toBe(8);
+ });
+
+ it('builds ranges that cover exactly the requested text', () => {
+ const range = contentRange(block('p1'), 6, 7)!;
+ expect(range.toString()).toBe('bold wo');
+ expect(contentRange(block('p1'), 0, 5)!.toString()).toBe('Hello');
+ expect(contentRange(block('p1'), 40, 2)).toBeNull();
+ });
+
+ it('round-trips a selection into a block span', () => {
+ const range = contentRange(block('p1'), 6, 4)!;
+ expect(blockSpanOfRange(range, root)).toMatchObject({
+ block: block('p1'),
+ start: 6,
+ length: 4,
+ });
+ });
+
+ it('clamps a selection that continues into the next block', () => {
+ const range = document.createRange();
+ const start = contentRange(block('p1'), 11, 1)!;
+ range.setStart(start.startContainer, start.startOffset);
+ range.setEnd(block('p2').firstChild!, 2);
+ expect(blockSpanOfRange(range, root)).toMatchObject({
+ start: 11,
+ length: 5,
+ });
+ });
+
+ it('finds the block that owns a node', () => {
+ expect(blockOf(block('p2').firstChild, root)).toBe(block('p2'));
+ expect(blockOf(root, root)).toBeNull();
+ });
+});
diff --git a/apps/web/src/features/block-write/core/text-offsets.ts b/apps/web/src/features/block-write/core/text-offsets.ts
new file mode 100644
index 0000000000..02f4c746b0
--- /dev/null
+++ b/apps/web/src/features/block-write/core/text-offsets.ts
@@ -0,0 +1,205 @@
+/**
+ * Content offsets inside a rendered DOCX block, in the same space the
+ * Docxodus editor uses for its own selection spans: generated chrome (list
+ * numbers, note references) and injected bidi marks do not count, and a field
+ * counts as its cached result.
+ */
+
+const GENERATED_CHROME =
+ '[data-list-marker], a.footnote-ref, a.endnote-ref, a[class$="-backref"], a.comment-marker';
+const BIDI_MARKS = /[‎‏؜‪-‮⁦-⁩]/;
+const BIDI_MARKS_GLOBAL = new RegExp(BIDI_MARKS.source, 'g');
+
+function stripBidi(text: string): string {
+ return text.replace(BIDI_MARKS_GLOBAL, '');
+}
+
+function isElement(node: Node): node is Element {
+ return node.nodeType === Node.ELEMENT_NODE;
+}
+
+function isChrome(node: Node, block: Element): boolean {
+ let element: Element | null = isElement(node) ? node : node.parentElement;
+ while (element && element !== block) {
+ if (element.matches(GENERATED_CHROME)) return true;
+ element = element.parentElement;
+ }
+ return false;
+}
+
+function isField(node: Node): node is HTMLElement {
+ return isElement(node) && node.hasAttribute('data-field');
+}
+
+function fieldText(field: HTMLElement): string {
+ return stripBidi(field.dataset.fieldCached ?? field.textContent ?? '');
+}
+
+/** The block (rendered paragraph) a node belongs to, inside `root`. */
+export function blockOf(node: Node | null, root: Element): HTMLElement | null {
+ let element: Element | null =
+ node && isElement(node) ? node : (node?.parentElement ?? null);
+ while (element && element !== root) {
+ if (element.hasAttribute('data-anchor') && element instanceof HTMLElement)
+ return element;
+ element = element.parentElement;
+ }
+ return null;
+}
+
+/** The block's text in content-offset space. */
+export function contentText(block: Element): string {
+ let out = '';
+ const walk = (node: Node) => {
+ if (isField(node)) out += fieldText(node);
+ else if (node.nodeType === Node.TEXT_NODE) {
+ if (!isChrome(node, block)) out += stripBidi(node.textContent ?? '');
+ } else node.childNodes.forEach(walk);
+ };
+ walk(block);
+ return out;
+}
+
+/** Content offset of a DOM position (container + offset) inside `block`. */
+export function contentOffset(
+ block: Element,
+ container: Node,
+ offset: number
+): number {
+ let count = 0;
+ let done = false;
+ const walk = (node: Node) => {
+ if (done) return;
+ if (isField(node)) {
+ const inside = node === container || node.contains(container);
+ if (!inside || offset > 0 || node !== container)
+ count += fieldText(node).length;
+ if (inside) done = true;
+ return;
+ }
+ if (node.nodeType === Node.TEXT_NODE) {
+ const chrome = isChrome(node, block);
+ if (node === container) {
+ if (!chrome)
+ count += stripBidi((node.textContent ?? '').slice(0, offset)).length;
+ done = true;
+ return;
+ }
+ if (!chrome) count += stripBidi(node.textContent ?? '').length;
+ return;
+ }
+ if (node === container) {
+ const children = Array.from(node.childNodes);
+ for (let i = 0; i < offset && i < children.length; i++) walk(children[i]);
+ done = true;
+ return;
+ }
+ node.childNodes.forEach(walk);
+ };
+ walk(block);
+ return count;
+}
+
+type Point = { node: Node; offset: number };
+
+/** The DOM position at content offset `target`, or null past the end. */
+function pointAt(
+ block: Element,
+ target: number,
+ preferEnd: boolean
+): Point | null {
+ let count = 0;
+ let found: Point | null = null;
+ const walk = (node: Node): boolean => {
+ if (isField(node)) {
+ const length = fieldText(node).length;
+ if (
+ target <= count + length &&
+ (preferEnd ? target > count : target < count + length)
+ ) {
+ const parent = node.parentNode;
+ if (!parent) return false;
+ const index = Array.prototype.indexOf.call(parent.childNodes, node);
+ found = { node: parent, offset: preferEnd ? index + 1 : index };
+ return true;
+ }
+ count += length;
+ return false;
+ }
+ if (node.nodeType === Node.TEXT_NODE) {
+ if (isChrome(node, block)) return false;
+ const raw = node.textContent ?? '';
+ const length = stripBidi(raw).length;
+ const hit = preferEnd
+ ? target > count && target <= count + length
+ : target >= count && target < count + length;
+ if (hit) {
+ let content = count;
+ for (let i = 0; i <= raw.length; i++) {
+ if (
+ content === target &&
+ (i === raw.length || !BIDI_MARKS.test(raw[i]))
+ ) {
+ found = { node, offset: i };
+ return true;
+ }
+ if (i < raw.length && !BIDI_MARKS.test(raw[i])) content++;
+ }
+ }
+ count += length;
+ return false;
+ }
+ for (const child of Array.from(node.childNodes))
+ if (walk(child)) return true;
+ return false;
+ };
+ walk(block);
+ return found;
+}
+
+/** A DOM range covering content offsets [start, start + length) of `block`. */
+export function contentRange(
+ block: Element,
+ start: number,
+ length: number
+): Range | null {
+ if (length <= 0) return null;
+ const from = pointAt(block, start, false);
+ const to = pointAt(block, start + length, true);
+ if (!from || !to) return null;
+ const range = document.createRange();
+ range.setStart(from.node, from.offset);
+ range.setEnd(to.node, to.offset);
+ return range.collapsed ? null : range;
+}
+
+/** A collapsed range at content offset `offset` of `block` (clamped to its end). */
+export function caretRange(block: Element, offset: number): Range | null {
+ const length = contentText(block).length;
+ const target = Math.max(0, Math.min(offset, length));
+ const point =
+ target > 0 ? pointAt(block, target, true) : pointAt(block, 0, false);
+ const range = document.createRange();
+ if (point) range.setStart(point.node, point.offset);
+ else range.selectNodeContents(block);
+ range.collapse(true);
+ return range;
+}
+
+/**
+ * The part of `range` that falls inside one block: the block where the range
+ * starts, clamped to that block's end when the range continues past it.
+ */
+export function blockSpanOfRange(
+ range: Range,
+ root: Element
+): { block: HTMLElement; start: number; length: number } | null {
+ const block = blockOf(range.startContainer, root);
+ if (!block) return null;
+ const start = contentOffset(block, range.startContainer, range.startOffset);
+ const end = block.contains(range.endContainer)
+ ? contentOffset(block, range.endContainer, range.endOffset)
+ : contentText(block).length;
+ if (end <= start) return null;
+ return { block, start, length: end - start };
+}
diff --git a/apps/web/src/features/block-write/definition.ts b/apps/web/src/features/block-write/definition.ts
new file mode 100644
index 0000000000..2b85e94a20
--- /dev/null
+++ b/apps/web/src/features/block-write/definition.ts
@@ -0,0 +1,32 @@
+import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';
+import { fetchSyncDocumentOpenContext } from '@queries/storage/documentLoad/sync-document-context';
+import { err, ok } from 'neverthrow';
+import { lazy } from 'solid-js';
+
+/**
+ * The collaborative DOCX editor. It owns the `write` block name, which is the
+ * DOCX block; when `enable-docx-editor` is off, `write` resolves to the PDF
+ * rendering instead (see `fileTypeToBlockName`).
+ */
+export const definition = defineBlock({
+ name: 'write',
+ description: 'Edit Word documents together',
+ accepted: {
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ },
+ component: lazy(() => import('./DocxBlock')),
+ liveTrackingEnabled: true,
+ syncServiceEnabled: true,
+ editPermissionEnabled: true,
+ async load(source, intent) {
+ if (source.type !== 'sync-service') return LoadErrors.INVALID;
+ if (intent === 'preload') return ok({ type: 'preload', origin: source });
+ // The same open context as the other sync-service blocks: a token plus a
+ // session-bound authorization that re-checks access on reconnect.
+ const context = await fetchSyncDocumentOpenContext(source.id);
+ if (context.isErr()) return err(context.error);
+ return ok(context.value);
+ },
+});
+
+export type DocxBlockData = ExtractLoadType<(typeof definition)['load']>;
diff --git a/apps/web/src/features/block-write/primitives/create-comment-highlights.ts b/apps/web/src/features/block-write/primitives/create-comment-highlights.ts
new file mode 100644
index 0000000000..c48004a062
--- /dev/null
+++ b/apps/web/src/features/block-write/primitives/create-comment-highlights.ts
@@ -0,0 +1,47 @@
+import { type Accessor, createEffect, onCleanup } from 'solid-js';
+import type { DocxComments } from './create-docx-comments';
+
+let instances = 0;
+
+/**
+ * Paint comment highlights with the CSS Custom Highlight API, which styles
+ * ranges without touching the editor's DOM, so commenting never interferes
+ * with editing. Returns the stylesheet text for the per-instance names.
+ */
+export function createCommentHighlights(
+ comments: DocxComments,
+ enabled: Accessor<boolean>
+): string {
+ const id = ++instances;
+ const base = `docx-comment-${id}`;
+ const active = `docx-comment-active-${id}`;
+ const supported = () => typeof CSS !== 'undefined' && 'highlights' in CSS;
+ createEffect(() => {
+ if (!supported()) return;
+ const threads = enabled() ? comments.located() : [];
+ const selected = comments.active();
+ CSS.highlights.set(
+ base,
+ new Highlight(
+ ...threads
+ .filter((thread) => !thread.resolved && thread.id !== selected)
+ .map((thread) => thread.range)
+ )
+ );
+ CSS.highlights.set(
+ active,
+ new Highlight(
+ ...threads
+ .filter((thread) => thread.id === selected)
+ .map((thread) => thread.range)
+ )
+ );
+ });
+ onCleanup(() => {
+ if (!supported()) return;
+ CSS.highlights.delete(base);
+ CSS.highlights.delete(active);
+ });
+ return `::highlight(${base}) { background-color: oklch(from var(--color-yellow) l c h / 0.28); text-decoration: underline 2px oklch(from var(--color-yellow) l c h / 0.7); }
+::highlight(${active}) { background-color: oklch(from var(--color-yellow) l c h / 0.55); text-decoration: underline 2px oklch(from var(--color-yellow) l c h / 0.9); }`;
+}
diff --git a/apps/web/src/features/block-write/primitives/create-docx-comments.ts b/apps/web/src/features/block-write/primitives/create-docx-comments.ts
new file mode 100644
index 0000000000..a933faa65c
--- /dev/null
+++ b/apps/web/src/features/block-write/primitives/create-docx-comments.ts
@@ -0,0 +1,258 @@
+import type { MessageListItem } from '@service-storage/messages';
+import type { LoroDoc } from 'loro-crdt';
+import {
+ type Accessor,
+ createEffect,
+ createMemo,
+ createSignal,
+ onCleanup,
+ untrack,
+} from 'solid-js';
+import { v7 as uuidv7 } from 'uuid';
+import {
+ type CommentMark,
+ deleteCommentMark,
+ MAX_MARK_TEXT,
+ readCommentMarks,
+ resolveMark,
+ writeCommentMark,
+} from '../core/comment-marks';
+import { DOCX_LORO_CONTAINERS } from '../core/docx-loro';
+import {
+ blockSpanOfRange,
+ contentRange,
+ contentText,
+} from '../core/text-offsets';
+
+export type DocxCommentDraft = { markId: string; mark: CommentMark };
+
+export type LocatedThread = {
+ /** Thread root id, or the draft's mark id. */
+ id: string;
+ markId: string;
+ root: MessageListItem | null;
+ resolved: boolean;
+ block: HTMLElement;
+ range: Range;
+};
+
+type Paragraph = { id: string; text: string; element: HTMLElement };
+
+/** A placeholder mark for a thread known only by its quoted text. */
+function quotedMark(root: MessageListItem): CommentMark | null {
+ const anchor = root.state.anchor;
+ const text =
+ anchor && anchor.type === 'markdown' ? anchor.marked_text?.trim() : null;
+ return text ? { block: '', start: 0, length: text.length, text } : null;
+}
+
+/** The mark id a thread is anchored to, when it is a text anchor. */
+export function threadMarkId(root: MessageListItem): string | null {
+ const anchor = root.state.anchor;
+ return anchor && anchor.type === 'markdown' ? anchor.mark_id : null;
+}
+
+/**
+ * Comment anchoring for a rendered DOCX: marks live in the collaborative
+ * document, threads come from the shared message store, and both are joined
+ * to the paragraphs currently on screen.
+ */
+export function createDocxComments(options: {
+ doc: LoroDoc | null;
+ roots: Accessor<MessageListItem[]>;
+ /** The element the editor renders the document body into. */
+ root: Accessor<HTMLElement | undefined>;
+ /** Bumps whenever the rendered document may have changed. */
+ revision: Accessor<number>;
+ canEdit: Accessor<boolean>;
+}) {
+ const [marks, setMarks] = createSignal<Map<string, CommentMark>>(
+ options.doc ? readCommentMarks(options.doc) : new Map()
+ );
+ const [draft, setDraft] = createSignal<DocxCommentDraft>();
+ const [active, setActive] = createSignal<string | null>(null);
+
+ if (options.doc) {
+ const doc = options.doc;
+ const unsubscribe = doc
+ .getMap(DOCX_LORO_CONTAINERS.marks)
+ .subscribe(() => setMarks(readCommentMarks(doc)));
+ onCleanup(unsubscribe);
+ }
+
+ const paragraphs = createMemo<Paragraph[]>(() => {
+ options.revision();
+ const root = options.root();
+ if (!root) return [];
+ const body = root.querySelector<HTMLElement>('.docx-body-flow') ?? root;
+ return Array.from(body.querySelectorAll<HTMLElement>('[data-anchor]'))
+ .filter((element) => !element.querySelector('[data-anchor]'))
+ .map((element) => ({
+ id: element.getAttribute('data-anchor')!,
+ text: contentText(element),
+ element,
+ }));
+ });
+
+ const live = (root: MessageListItem) => !root.state.deleted_at;
+
+ const placement = createMemo(() => {
+ const blocks = paragraphs();
+ const all = marks();
+ const out: LocatedThread[] = [];
+ const relocations: Array<[string, CommentMark]> = [];
+ const place = (
+ id: string,
+ markId: string,
+ mark: CommentMark,
+ root: MessageListItem | null
+ ) => {
+ const found = resolveMark(mark, blocks);
+ if (!found) return false;
+ const block = blocks.find((paragraph) => paragraph.id === found.block);
+ const range =
+ block && contentRange(block.element, found.start, found.length);
+ if (!block || !range) return false;
+ if (found.relocated && root)
+ relocations.push([
+ markId,
+ {
+ block: found.block,
+ start: found.start,
+ length: found.length,
+ text: found.text,
+ },
+ ]);
+ out.push({
+ id,
+ markId,
+ root,
+ resolved: !!root?.state.resolved,
+ block: block.element,
+ range,
+ });
+ return true;
+ };
+ for (const root of options.roots()) {
+ if (!live(root)) continue;
+ const markId = threadMarkId(root);
+ if (!markId) continue;
+ // A thread posted with only its quoted text (an agent's comment, or one
+ // whose mark was never written) is placed by finding that text; an
+ // editor then pins it with a real mark.
+ const mark = all.get(markId) ?? quotedMark(root);
+ if (mark) place(root.id, markId, mark, root);
+ }
+ const pending = draft();
+ if (pending) place(pending.markId, pending.markId, pending.mark, null);
+ return { threads: out, relocations };
+ });
+ const located = () => placement().threads;
+
+ // Keep stored offsets close to the text so later edits relocate cheaply.
+ // Writing a relocated mark re-resolves it in place, so this settles; marks
+ // already stored at the new place (another editor got there first) are
+ // left alone so peers do not commit the same move twice.
+ createEffect(() => {
+ const { relocations } = placement();
+ const doc = options.doc;
+ if (!relocations.length || !doc || !untrack(options.canEdit)) return;
+ const stored = untrack(marks);
+ for (const [markId, mark] of relocations) {
+ const current = stored.get(markId);
+ if (
+ current &&
+ current.block === mark.block &&
+ current.start === mark.start &&
+ current.length === mark.length &&
+ current.text === mark.text
+ )
+ continue;
+ writeCommentMark(doc, markId, mark);
+ }
+ });
+
+ /** Threads that cannot be shown beside the text: legacy anchors or removed text. */
+ const detached = createMemo(() => {
+ const shown = new Set(located().map((thread) => thread.id));
+ return options
+ .roots()
+ .filter((root) => live(root) && root.state.anchor && !shown.has(root.id));
+ });
+
+ /** Start a comment on the current selection. False when nothing usable is selected. */
+ function beginDraft(): boolean {
+ const root = options.root();
+ const selection = window.getSelection();
+ if (
+ !root ||
+ !selection ||
+ selection.rangeCount === 0 ||
+ selection.isCollapsed
+ )
+ return false;
+ const span = blockSpanOfRange(selection.getRangeAt(0), root);
+ if (!span) return false;
+ const id = span.block.getAttribute('data-anchor');
+ const length = Math.min(span.length, MAX_MARK_TEXT);
+ const text = contentText(span.block).slice(span.start, span.start + length);
+ if (!id || !text.trim()) return false;
+ const markId = uuidv7();
+ setDraft({ markId, mark: { block: id, start: span.start, length, text } });
+ setActive(markId);
+ return true;
+ }
+
+ function cancelDraft() {
+ const pending = draft();
+ setDraft(undefined);
+ if (pending && active() === pending.markId) setActive(null);
+ }
+
+ /**
+ * Persist the draft's mark, then post its thread. The mark is written
+ * first so the new thread is placed the moment it appears; it is removed
+ * again if posting fails.
+ */
+ async function commitDraft<T>(post: (draft: DocxCommentDraft) => Promise<T>) {
+ const pending = draft();
+ if (!pending || !options.doc) throw new Error('No comment to post');
+ writeCommentMark(options.doc, pending.markId, pending.mark);
+ try {
+ const result = await post(pending);
+ setDraft(undefined);
+ return result;
+ } catch (error) {
+ deleteCommentMark(options.doc, pending.markId);
+ throw error;
+ }
+ }
+
+ /** The thread whose highlight contains a caret position. */
+ function threadAt(node: Node, offset: number): string | null {
+ for (const thread of located()) {
+ if (thread.resolved && active() !== thread.id) continue;
+ if (
+ thread.range.comparePoint(node, offset) === 0 &&
+ thread.block.contains(node)
+ )
+ return thread.id;
+ }
+ return null;
+ }
+
+ return {
+ marks,
+ located,
+ detached,
+ draft,
+ active,
+ setActive,
+ beginDraft,
+ cancelDraft,
+ commitDraft,
+ threadAt,
+ };
+}
+
+export type DocxComments = ReturnType<typeof createDocxComments>;
diff --git a/apps/web/src/features/block-write/primitives/create-docx-editor.ts b/apps/web/src/features/block-write/primitives/create-docx-editor.ts
new file mode 100644
index 0000000000..fcd3a9320c
--- /dev/null
+++ b/apps/web/src/features/block-write/primitives/create-docx-editor.ts
@@ -0,0 +1,266 @@
+import type { DocxEditor } from 'docxodus';
+import type { LoroDoc } from 'loro-crdt';
+import { type Accessor, createSignal, onCleanup } from 'solid-js';
+import { bridgeEngine, type DocxEngine } from '../core/docx-engine';
+import { readDocxState } from '../core/docx-loro';
+import { assemblePackage } from '../core/docx-package';
+import { DOCX_SYNC_SESSION_SETTINGS } from '../core/docx-seed';
+import { DocxSyncController } from '../core/docx-sync';
+import { editorBridge } from '../core/editor-bridge';
+import { caretRange, contentOffset, contentText } from '../core/text-offsets';
+import type { DocxodusRuntime } from '../queries/docxodus-runtime';
+
+/** Commit typing this long after the last keystroke so peers see it live. */
+const IDLE_COMMIT_MS = 1_200;
+/** Coalesce bursts of engine mutations into one publish. */
+const PUBLISH_DELAY_MS = 80;
+
+export type DocxEditorOptions = {
+ runtime: DocxodusRuntime;
+ /** The collaborative document; null opens `original` read-only, unsynced. */
+ doc: LoroDoc | null;
+ original?: Uint8Array;
+ editable: boolean;
+ author: string;
+ /** The scrolling element around the document, kept in place on remounts. */
+ scroller?: () => HTMLElement | undefined;
+ /** Called after remote changes land (`subscribe` receives the trigger). */
+ subscribeRemote?: (listener: () => void) => () => void;
+ onError?: (error: unknown) => void;
+};
+
+export type DocxEditorHandle = {
+ editor: Accessor<DocxEditor | undefined>;
+ /** Bumps whenever the rendered document changes (local or remote). */
+ revision: Accessor<number>;
+ /** Mount the editor into `element`. */
+ mount: (element: HTMLElement) => Promise<void>;
+ /** Publish committed local edits now (e.g. before leaving). */
+ flush: () => void;
+ /** The editor's live document bytes, without engine bookkeeping. */
+ save: () => Uint8Array | undefined;
+};
+
+let mountCounter = 0;
+
+/**
+ * Own one Docxodus editor and keep it in step with the collaborative
+ * document: local engine mutations are published, remote changes are patched
+ * into the live session, and typing is committed while the user pauses.
+ */
+export function createDocxEditor(options: DocxEditorOptions): DocxEditorHandle {
+ const [editor, setEditor] = createSignal<DocxEditor>();
+ const [revision, setRevision] = createSignal(0);
+ const bump = () => setRevision((value) => value + 1);
+ let container: HTMLElement | undefined;
+ let controller: DocxSyncController | undefined;
+ let publishTimer: ReturnType<typeof setTimeout> | undefined;
+ let idleTimer: ReturnType<typeof setTimeout> | undefined;
+ let disposed = false;
+ let applying = false;
+ let unsubscribeRemote: (() => void) | undefined;
+ const rootId = `docx-editor-${++mountCounter}`;
+ const rootSelector = `[data-docx-editor="${rootId}"]`;
+
+ const publish = () => {
+ clearTimeout(publishTimer);
+ publishTimer = undefined;
+ if (!controller || applying || disposed) return;
+ try {
+ if (controller.publishLocal()) bump();
+ } catch (error) {
+ options.onError?.(error);
+ }
+ };
+ const schedulePublish = () => {
+ if (applying || !options.doc) return;
+ clearTimeout(publishTimer);
+ publishTimer = setTimeout(publish, PUBLISH_DELAY_MS);
+ };
+
+ const exports = editorBridge(options.runtime.exports, {
+ rootSelector,
+ sessionSettings: DOCX_SYNC_SESSION_SETTINGS,
+ onMutation: () => {
+ schedulePublish();
+ bump();
+ },
+ });
+
+ const engine: DocxEngine = bridgeEngine(
+ options.runtime.exports.DocxSessionBridge,
+ () => {
+ const current = editor();
+ if (!current) throw new Error('DOCX editor is not mounted');
+ return current.sessionHandle;
+ }
+ );
+
+ const editorOptions = () => ({
+ editable: options.editable,
+ comments: false,
+ // Docxodus renders header/footer stories as editing bands only; readers
+ // get the print layout, where every page carries its header and footer.
+ headerFooter: options.editable,
+ paginated: !options.editable,
+ blockDrag: options.editable,
+ revisionAuthor: options.author,
+ commentAuthor: options.author,
+ });
+
+ /** A fresh child for each editor instance; the scoped root stays stable. */
+ const freshHost = () => {
+ const host = document.createElement('div');
+ host.className = 'docx-editor-host';
+ container!.replaceChildren(host);
+ return host;
+ };
+
+ const activeBlock = (): HTMLElement | null => {
+ const active = document.activeElement;
+ if (!(active instanceof HTMLElement) || !container?.contains(active))
+ return null;
+ return active.closest<HTMLElement>('[data-anchor][contenteditable="true"]');
+ };
+ const isDirty = (block: HTMLElement) =>
+ block.dataset.committedText !== undefined &&
+ contentText(block) !== block.dataset.committedText;
+
+ /** True while a block (or a paragraph inside it) holds uncommitted typing. */
+ const isBusy = (blockId: string) => {
+ const block = activeBlock();
+ if (!block || !isDirty(block)) return false;
+ if (block.getAttribute('data-anchor') === blockId) return true;
+ const owner = container?.querySelector(
+ `[data-anchor="${CSS.escape(blockId)}"]`
+ );
+ return !!owner?.contains(block);
+ };
+
+ /**
+ * Commit the block the user is typing in without moving their caret: the
+ * editor commits on blur, so blur and restore focus at the same offset.
+ */
+ const commitTyping = () => {
+ idleTimer = undefined;
+ const block = activeBlock();
+ if (!block || !isDirty(block)) return;
+ const selection = window.getSelection();
+ if (!selection?.isCollapsed || !selection.anchorNode) return;
+ if (!block.contains(selection.anchorNode)) return;
+ const offset = contentOffset(
+ block,
+ selection.anchorNode,
+ selection.anchorOffset
+ );
+ const id = block.getAttribute('data-anchor');
+ const scrollParent = options.scroller?.();
+ const scrollTop = scrollParent?.scrollTop;
+ block.blur();
+ const fresh =
+ (id &&
+ container?.querySelector<HTMLElement>(
+ `[data-anchor="${CSS.escape(id)}"][contenteditable="true"]`
+ )) ||
+ null;
+ if (!fresh) return;
+ fresh.focus({ preventScroll: true });
+ const caret = caretRange(fresh, offset);
+ if (caret) {
+ selection.removeAllRanges();
+ selection.addRange(caret);
+ }
+ if (scrollParent && scrollTop !== undefined)
+ scrollParent.scrollTop = scrollTop;
+ };
+
+ const onInput = (event: Event) => {
+ if ((event as InputEvent).isComposing) return;
+ clearTimeout(idleTimer);
+ idleTimer = setTimeout(commitTyping, IDLE_COMMIT_MS);
+ };
+
+ const rebuild = (bytes: Uint8Array) => {
+ const previous = editor();
+ const scrollParent = options.scroller?.();
+ const scrollTop = scrollParent?.scrollTop ?? 0;
+ previous?.close();
+ const next = options.runtime.module.DocxEditor.open(
+ freshHost(),
+ bytes,
+ exports,
+ editorOptions()
+ );
+ setEditor(next);
+ if (scrollParent) scrollParent.scrollTop = scrollTop;
+ };
+
+ const applyRemote = () => {
+ if (!controller || disposed) return;
+ applying = true;
+ try {
+ controller.applyRemote();
+ } catch (error) {
+ options.onError?.(error);
+ } finally {
+ applying = false;
+ }
+ bump();
+ };
+
+ async function mount(element: HTMLElement) {
+ container = element;
+ container.setAttribute('data-docx-editor', rootId);
+ container.addEventListener('input', onInput);
+ const bytes = options.doc
+ ? assemblePackage(readDocxState(options.doc))
+ : options.original;
+ if (!bytes) throw new Error('No document to open');
+ const opened = await options.runtime.module.DocxEditor.openAsync(
+ freshHost(),
+ bytes,
+ exports,
+ editorOptions()
+ );
+ if (disposed) {
+ opened.close();
+ return;
+ }
+ setEditor(opened);
+ if (options.doc) {
+ controller = new DocxSyncController(options.doc, {
+ engine: () => engine,
+ refresh: () => editor()?.refresh(),
+ rebuild,
+ isBusy,
+ });
+ unsubscribeRemote = options.subscribeRemote?.(applyRemote);
+ // Changes that arrived while the editor was mounting.
+ applyRemote();
+ }
+ bump();
+ }
+
+ const onHide = () => {
+ if (document.visibilityState === 'hidden') publish();
+ };
+ document.addEventListener('visibilitychange', onHide);
+
+ onCleanup(() => {
+ publish();
+ disposed = true;
+ unsubscribeRemote?.();
+ clearTimeout(idleTimer);
+ document.removeEventListener('visibilitychange', onHide);
+ container?.removeEventListener('input', onInput);
+ editor()?.close();
+ });
+
+ return {
+ editor,
+ revision,
+ mount,
+ flush: publish,
+ save: () => editor()?.save(),
+ };
+}
diff --git a/apps/web/src/features/block-write/queries/docx-document.ts b/apps/web/src/features/block-write/queries/docx-document.ts
new file mode 100644
index 0000000000..a5c0a145ca
--- /dev/null
+++ b/apps/web/src/features/block-write/queries/docx-document.ts
@@ -0,0 +1,53 @@
+import { queryClient } from '@queries/client';
+import { downloadExportedDocument } from '@service-storage/util/downloadExportedDocument';
+import { syncServiceClient } from '@service-sync/client';
+import { createSyncServiceSource } from '@service-sync/source';
+import type { DocumentSyncAuthorization } from '@service-sync/source/authorization';
+import { buildSeedSnapshot } from '../core/docx-seed';
+import type { DocxConnection } from './docx-session';
+import { loadDocxodus } from './docxodus-runtime';
+
+const docxKeys = {
+ original: (documentId: string) => ['docx', 'original', documentId] as const,
+};
+
+/**
+ * The DOCX as uploaded, rebuilt by document storage from its stored parts.
+ * Cached so views opening the same file share one download.
+ */
+export function fetchOriginalDocx(documentId: string): Promise<Uint8Array> {
+ return queryClient.fetchQuery({
+ queryKey: docxKeys.original(documentId),
+ queryFn: () => downloadExportedDocument({ documentId }),
+ });
+}
+
+export async function docxSyncExists(documentId: string): Promise<boolean> {
+ const result = await syncServiceClient.exists({ documentId });
+ if (result.isErr()) throw new Error('Unable to reach the sync service.');
+ return result.value.exists;
+}
+
+export async function initializeDocxSync(
+ documentId: string,
+ snapshot: Uint8Array
+): Promise<void> {
+ const result = await syncServiceClient.initializeFromSnapshot({
+ documentId,
+ snapshot,
+ });
+ if (result.isErr()) throw new Error('Unable to initialize collaboration.');
+}
+
+export async function buildDocxSeed(original: Uint8Array): Promise<Uint8Array> {
+ const runtime = await loadDocxodus();
+ return buildSeedSnapshot(runtime.exports.DocxSessionBridge, original);
+}
+
+export function connectDocxSync(
+ documentId: string,
+ token: string | undefined,
+ authorization?: DocumentSyncAuthorization
+): DocxConnection {
+ return createSyncServiceSource(documentId, token, authorization);
+}
diff --git a/apps/web/src/features/block-write/queries/docx-session.ts b/apps/web/src/features/block-write/queries/docx-session.ts
new file mode 100644
index 0000000000..d4c6a68b05
--- /dev/null
+++ b/apps/web/src/features/block-write/queries/docx-session.ts
@@ -0,0 +1,341 @@
+import { createAwareness } from '@macro-inc/collaboration/collab/awareness';
+import type { Chatter } from '@macro-inc/collaboration/collab/chatter';
+import { createSyncEngine } from '@macro-inc/collaboration/collab/engine';
+import { LoroManager } from '@macro-inc/collaboration/collab/manager';
+import {
+ IDBSnapshotStore,
+ LORO_SNAPSHOT_DB_NAME,
+ loadCachedState,
+ type SnapshotStore,
+} from '@macro-inc/collaboration/collab/snapshot-store';
+import {
+ type InitialSync,
+ type LiveSyncSource,
+ SyncError,
+ type SyncSourceEvent,
+ SyncSourceStatus,
+} from '@macro-inc/collaboration/collab/source';
+import {
+ BrowserWALStore,
+ LORO_WAL_DB_NAME,
+ type WALStore,
+ WALSyncer,
+} from '@macro-inc/collaboration/collab/wal';
+import type { LoroDoc } from 'loro-crdt';
+import { errAsync, type ResultAsync } from 'neverthrow';
+import { type Accessor, createSignal, onCleanup } from 'solid-js';
+import { match } from 'ts-pattern';
+import {
+ DOCX_FORMAT_VERSION,
+ docxFormatVersion,
+ isDocxSeeded,
+} from '../core/docx-loro';
+import { DOCX_LORO_SCHEMA } from '../core/docx-loro-schema';
+
+/** Where a collaborator's caret is: a paragraph and an offset in its text. */
+export type DocxSelection = { block: string; offset: number };
+
+export type DocxPeer = {
+ userId: string | undefined;
+ color: string;
+ peerId: string;
+ selection: DocxSelection;
+};
+
+export type DocxSessionState =
+ | { t: 'loading' }
+ | { t: 'ready'; doc: LoroDoc }
+ /** The uploaded file, read-only, before anyone with edit access opened it. */
+ | { t: 'original'; bytes: Uint8Array }
+ | { t: 'error'; message: string };
+
+export type DocxConnection = {
+ source: LiveSyncSource;
+ doInitialSync: () => ResultAsync<InitialSync, SyncError>;
+};
+
+export type DocxSessionOptions = {
+ documentId: string;
+ userId?: string;
+ canEdit: Accessor<boolean>;
+ canComment: Accessor<boolean>;
+ /** Whether the sync service already holds this document. */
+ exists: () => Promise<boolean>;
+ /** The uploaded DOCX, used to seed and as a read-only fallback. */
+ fetchOriginal: () => Promise<Uint8Array>;
+ /** The first collaborative snapshot for the original. */
+ buildSeed: (original: Uint8Array) => Promise<Uint8Array>;
+ /** Store the first snapshot. Rejects when it could not be stored. */
+ initialize: (snapshot: Uint8Array) => Promise<void>;
+ /** Open the live transport. Called once, after the document exists. */
+ connect: () => DocxConnection;
+ persistence?: {
+ snapshots: SnapshotStore<Uint8Array>;
+ wal: WALStore<Uint8Array>;
+ makeChatter?: (documentId: string) => Chatter;
+ };
+};
+
+export type DocxSession = {
+ state: Accessor<DocxSessionState>;
+ status: Accessor<'connected' | 'offline' | 'connecting'>;
+ peers: Accessor<DocxPeer[]>;
+ setSelection: (selection: DocxSelection | undefined) => void;
+ /** Called after remote changes were merged into the document. */
+ onRemoteChange: (listener: () => void) => () => void;
+};
+
+function isSelection(value: unknown): value is DocxSelection {
+ return (
+ typeof value === 'object' &&
+ value !== null &&
+ 'block' in value &&
+ typeof value.block === 'string' &&
+ 'offset' in value &&
+ typeof value.offset === 'number'
+ );
+}
+
+/**
+ * The collaborative DOCX on the shared sync stack: a Loro document with a
+ * local snapshot, write-ahead log, live transport and presence, seeded from
+ * the uploaded file the first time someone with edit access opens it.
+ */
+export function createDocxSession(options: DocxSessionOptions): DocxSession {
+ const manager = new LoroManager(DOCX_LORO_SCHEMA, {
+ documentId: options.documentId,
+ });
+ const snapshots =
+ options.persistence?.snapshots ??
+ new IDBSnapshotStore<Uint8Array>(LORO_SNAPSHOT_DB_NAME, options.documentId);
+ const walStore =
+ options.persistence?.wal ??
+ new BrowserWALStore<Uint8Array>(LORO_WAL_DB_NAME, options.documentId);
+ const [state, setState] = createSignal<DocxSessionState>({ t: 'loading' });
+ const [connection, setConnection] = createSignal<DocxConnection>();
+ const listeners = new Set<() => void>();
+ let disposed = false;
+ let started = false;
+
+ const wal = new WALSyncer(
+ walStore,
+ (updates) =>
+ connection()?.source.pushUpdate(updates) ?? Promise.resolve(false),
+ options.documentId
+ );
+
+ const awareness = createAwareness<DocxSelection, DocxSelection>(
+ manager.peerIdStr,
+ options.userId,
+ {
+ encode: (selection) => selection,
+ decode: (selection) =>
+ isSelection(selection) ? selection : { block: '', offset: 0 },
+ }
+ );
+ let selection: DocxSelection | undefined;
+ // Awareness expires; keep an idle caret visible while connected.
+ const heartbeat = setInterval(() => {
+ if (
+ selection &&
+ connection()?.source.status() === SyncSourceStatus.Connected
+ )
+ awareness.updateLocalAwareness(selection);
+ }, 3_000);
+
+ const notify = () => {
+ for (const listener of listeners) listener();
+ };
+
+ // The engine starts before the transport exists when a cached copy opens
+ // offline-first, so it talks to a source that forwards to the connection
+ // once there is one.
+ const liveListeners = new Set<(event: SyncSourceEvent) => void>();
+ let peerId: bigint | undefined;
+ const notConnected = () => errAsync(SyncError.connectionFailed());
+ const live: LiveSyncSource = {
+ documentId: options.documentId,
+ status: () => connection()?.source.status() ?? SyncSourceStatus.Connecting,
+ listen: (listener) => {
+ liveListeners.add(listener);
+ return () => liveListeners.delete(listener);
+ },
+ pushUpdate: (updates) =>
+ connection()?.source.pushUpdate(updates) ?? Promise.resolve(false),
+ pushAwareness: (value) => connection()?.source.pushAwareness(value),
+ registerPeerId: (value) => {
+ peerId = value;
+ connection()?.source.registerPeerId(value);
+ },
+ requestUpdatesSince: (version) =>
+ connection()?.source.requestUpdatesSince(version) ?? notConnected(),
+ requestSnapshot: () =>
+ connection()?.source.requestSnapshot() ?? notConnected(),
+ reconnect: () => connection()?.source.reconnect(),
+ cleanup: () => connection()?.source.cleanup(),
+ };
+
+ const engine = createSyncEngine({
+ loroManager: manager,
+ awareness,
+ syncs: { live, wal },
+ bindings: { onRemoteState: notify },
+ readonly: () => !options.canComment(),
+ snapshotStore: snapshots,
+ makeChatter: options.persistence?.makeChatter,
+ });
+
+ // The engine swaps its LoroDoc when it recovers from an invalid update.
+ const unsubscribeManager = manager.onStateChange(() => {
+ const current = state();
+ if (current.t === 'ready' && current.doc !== manager.doc)
+ setState({ t: 'ready', doc: manager.doc });
+ });
+
+ async function start() {
+ if (disposed) return;
+ const version = docxFormatVersion(manager.doc);
+ if (version !== undefined && version > DOCX_FORMAT_VERSION) {
+ setState({
+ t: 'error',
+ message: 'This document uses a newer format. Update Macro to open it.',
+ });
+ return;
+ }
+ if (!isDocxSeeded(manager.doc)) {
+ setState({
+ t: 'error',
+ message: 'This document has no editable content.',
+ });
+ return;
+ }
+ if (!started) {
+ // Persist the base before accepting edits so a crash can always replay
+ // WAL entries against a valid snapshot.
+ await snapshots.save(manager.doc.export({ mode: 'snapshot' }));
+ if (disposed) return;
+ engine.start();
+ started = true;
+ }
+ setState({ t: 'ready', doc: manager.doc });
+ if (options.canComment()) void wal.flush();
+ }
+
+ async function accept(initial: InitialSync) {
+ if (initial.awareness.length)
+ awareness.importRemoteAwareness(initial.awareness);
+ const result = manager.initialized
+ ? manager.importUpdate(initial.snapshot)
+ : await manager.initializeFromSnapshot(initial.snapshot);
+ if (disposed) return;
+ if (result.isErr()) {
+ setState({ t: 'error', message: 'This document could not be opened.' });
+ return;
+ }
+ if (started) notify();
+ else await start();
+ }
+
+ async function seed(): Promise<boolean> {
+ const original = await options.fetchOriginal();
+ if (disposed) return false;
+ if (!options.canEdit()) {
+ setState({ t: 'original', bytes: original });
+ return false;
+ }
+ const snapshot = await options.buildSeed(original);
+ try {
+ await options.initialize(snapshot);
+ } catch (cause) {
+ // Another editor may have initialized it first.
+ if (!(await options.exists())) throw cause;
+ }
+ return true;
+ }
+
+ async function hydrate() {
+ await wal.ready();
+ const cached = await loadCachedState(manager, snapshots, walStore).catch(
+ () => false
+ );
+ if (disposed) return;
+ if (cached && isDocxSeeded(manager.doc)) await start();
+ else if (!(await options.exists()) && !(await seed())) return;
+ if (disposed) return;
+ const opened = options.connect();
+ setConnection(opened);
+ opened.source.listen((event) => {
+ for (const listener of liveListeners) listener(event);
+ if (event.type === 'reconnect')
+ accept(event)
+ .then(() => wal.flush())
+ .catch((cause: unknown) => {
+ console.error('DOCX session failed to resync', cause);
+ if (!disposed)
+ setState({
+ t: 'error',
+ message: 'Unable to open this document.',
+ });
+ });
+ });
+ if (peerId !== undefined) opened.source.registerPeerId(peerId);
+ const initial = await opened.doInitialSync();
+ if (disposed) return;
+ if (initial.isErr()) {
+ if (!started)
+ setState({
+ t: 'error',
+ message: 'Unable to connect to this document.',
+ });
+ return;
+ }
+ await accept(initial.value);
+ }
+
+ hydrate().catch((cause: unknown) => {
+ console.error('DOCX session failed to open', cause);
+ if (!disposed)
+ setState({ t: 'error', message: 'Unable to open this document.' });
+ });
+
+ onCleanup(() => {
+ disposed = true;
+ clearInterval(heartbeat);
+ unsubscribeManager();
+ engine.stop();
+ wal.destroy();
+ connection()?.source.cleanup();
+ listeners.clear();
+ manager.dispose();
+ });
+
+ return {
+ state,
+ status: () =>
+ match(connection()?.source.status())
+ .with(SyncSourceStatus.Connected, () => 'connected' as const)
+ .with(SyncSourceStatus.Disconnected, () => 'offline' as const)
+ .otherwise(() => 'connecting' as const),
+ peers: () =>
+ awareness.remote().flatMap((peer) =>
+ peer.selection?.block
+ ? [
+ {
+ userId: peer.user.userId,
+ color: peer.user.color,
+ peerId: peer.user.peerId,
+ selection: peer.selection,
+ },
+ ]
+ : []
+ ),
+ setSelection: (next) => {
+ selection = next;
+ awareness.updateLocalAwareness(next);
+ },
+ onRemoteChange: (listener) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ };
+}
diff --git a/apps/web/src/features/block-write/queries/docxodus-runtime.ts b/apps/web/src/features/block-write/queries/docxodus-runtime.ts
new file mode 100644
index 0000000000..f6561fa3b6
--- /dev/null
+++ b/apps/web/src/features/block-write/queries/docxodus-runtime.ts
@@ -0,0 +1,37 @@
+import type { DocxEditorExports } from 'docxodus';
+
+type DocxodusModule = typeof import('docxodus');
+
+export type DocxodusRuntime = {
+ module: DocxodusModule;
+ /** Raw engine exports, shared by every editor on the page. */
+ exports: ReturnType<DocxodusModule['getWasmExports']>;
+};
+
+let loading: Promise<DocxodusRuntime> | undefined;
+
+/** Where the build serves the runtime (see `scripts/docxodus-runtime.ts`). */
+export function docxodusRuntimeBase(): string {
+ const version = import.meta.env.DOCXODUS_VERSION;
+ if (!version) throw new Error('This build does not serve the DOCX engine.');
+ return `${import.meta.env.BASE_URL.replace(/\/?$/, '/')}docxodus/${version}/`;
+}
+
+/**
+ * Load the Docxodus editor and its WebAssembly engine once per page.
+ * Assemblies stream in and compile off the main thread; nothing is fetched
+ * until a DOCX is opened.
+ */
+export function loadDocxodus(): Promise<DocxodusRuntime> {
+ loading ??= (async () => {
+ const module = await import('docxodus');
+ await module.initialize(docxodusRuntimeBase());
+ return { module, exports: module.getWasmExports() };
+ })().catch((error: unknown) => {
+ loading = undefined;
+ throw error;
+ });
+ return loading;
+}
+
+export type { DocxEditorExports };
diff --git a/apps/web/src/features/block-write/tests/docx-test-peer.ts b/apps/web/src/features/block-write/tests/docx-test-peer.ts
new file mode 100644
index 0000000000..a2f65c69ce
--- /dev/null
+++ b/apps/web/src/features/block-write/tests/docx-test-peer.ts
@@ -0,0 +1,107 @@
+import { readFileSync } from 'node:fs';
+import { getWasmExports, initialize } from 'docxodus/core';
+import { LoroDoc } from 'loro-crdt';
+import { bridgeEngine, type DocxEngine } from '../core/docx-engine';
+import { readDocxState, seedDocxState } from '../core/docx-loro';
+import { assemblePackage } from '../core/docx-package';
+import { DocxSyncController } from '../core/docx-sync';
+
+/** Session settings the collaborative editor opens every session with. */
+export const SYNC_SESSION_SETTINGS = JSON.stringify({
+ emitMarkdownPatch: false,
+ validateRawOps: false,
+});
+
+export function fixture(name: string): Uint8Array {
+ return new Uint8Array(
+ readFileSync(new URL(`../core/fixtures/${name}`, import.meta.url))
+ );
+}
+
+let ready: Promise<void> | undefined;
+/** Boot the Node build of the Docxodus engine once per test file. */
+export function loadEngine() {
+ ready ??= initialize();
+ return ready;
+}
+
+type Bridge = ReturnType<typeof getWasmExports>['DocxSessionBridge'];
+
+export function bridge(): Bridge {
+ return getWasmExports().DocxSessionBridge;
+}
+
+/**
+ * One collaborator: a live engine session and a Loro replica. Updates are
+ * queued rather than delivered so tests choose when peers see each other.
+ */
+export class TestPeer {
+ readonly doc = new LoroDoc();
+ handle: number;
+ readonly engine: DocxEngine;
+ readonly sync: DocxSyncController;
+ rebuilds = 0;
+ private readonly outbox: Uint8Array[] = [];
+
+ constructor(bytes: Uint8Array, seed?: Uint8Array) {
+ if (seed) this.doc.import(seed);
+ this.doc.subscribeLocalUpdates((update) => this.outbox.push(update));
+ const opening = seed ? assemblePackage(readDocxState(this.doc)) : bytes;
+ this.handle = bridge().OpenSession(opening, SYNC_SESSION_SETTINGS);
+ this.engine = bridgeEngine(bridge(), () => this.handle);
+ if (!seed) seedDocxState(this.doc, this.engine.snapshot());
+ this.sync = new DocxSyncController(this.doc, {
+ engine: () => this.engine,
+ refresh: () => {},
+ rebuild: (next) => {
+ this.rebuilds++;
+ bridge().CloseSession(this.handle);
+ this.handle = bridge().OpenSession(next, SYNC_SESSION_SETTINGS);
+ },
+ });
+ }
+
+ /** Hand every queued update to `others` and apply them there. */
+ deliver(...others: TestPeer[]) {
+ const updates = this.outbox.splice(0);
+ for (const other of others) {
+ for (const update of updates) other.doc.import(update);
+ other.sync.applyRemote();
+ }
+ }
+
+ bodyIds(): string[] {
+ return (
+ JSON.parse(bridge().ListBlocks!(this.handle)) as {
+ body: Array<{ id: string }>;
+ }
+ ).body.map((unit) => unit.id);
+ }
+
+ /** The run text of every body block, in order. */
+ text(): string[] {
+ return this.bodyIds().map((id) => this.blockText(id));
+ }
+
+ blockText(anchor: string): string {
+ return xmlText(bridge().RawGetXml(this.handle, anchor));
+ }
+
+ close() {
+ bridge().CloseSession(this.handle);
+ }
+}
+
+/** Concatenated `w:t` text of an element. */
+export function xmlText(xml: string): string {
+ return [...xml.matchAll(/<w:t(?:\s[^>]*)?>([^<]*)<\/w:t>/g)]
+ .map((match) =>
+ match[1]
+ .replaceAll('&lt;', '<')
+ .replaceAll('&gt;', '>')
+ .replaceAll('&quot;', '"')
+ .replaceAll('&apos;', "'")
+ .replaceAll('&amp;', '&')
+ )
+ .join('');
+}
diff --git a/apps/web/src/features/block-write/views/DocxCollaborators.tsx b/apps/web/src/features/block-write/views/DocxCollaborators.tsx
new file mode 100644
index 0000000000..4cdff67a3f
--- /dev/null
+++ b/apps/web/src/features/block-write/views/DocxCollaborators.tsx
@@ -0,0 +1,80 @@
+import { type Accessor, createMemo, For, Show } from 'solid-js';
+import { caretRange } from '../core/text-offsets';
+import type { DocxPeer } from '../queries/docx-session';
+
+type Caret = {
+ peer: DocxPeer;
+ name: string;
+ top: number;
+ left: number;
+ height: number;
+};
+
+/** Where each collaborator's caret is, drawn over the document. */
+export function DocxCollaboratorCarets(props: {
+ peers: DocxPeer[];
+ editorRoot: HTMLElement | undefined;
+ /** Positioning parent of the overlay. */
+ overlay: HTMLElement | undefined;
+ revision: Accessor<number>;
+ displayName: (userId: string | undefined) => string;
+}) {
+ const carets = createMemo<Caret[]>(() => {
+ props.revision();
+ const root = props.editorRoot;
+ const overlay = props.overlay;
+ if (!root || !overlay) return [];
+ const origin = overlay.getBoundingClientRect();
+ return props.peers.flatMap((peer) => {
+ const block = root.querySelector<HTMLElement>(
+ `[data-anchor="${CSS.escape(peer.selection.block)}"]`
+ );
+ if (!block) return [];
+ const range = caretRange(block, peer.selection.offset);
+ const rect =
+ range?.getClientRects()[0] ??
+ range?.getBoundingClientRect() ??
+ block.getBoundingClientRect();
+ const fallback = block.getBoundingClientRect();
+ const height = rect.height || Math.min(fallback.height, 20);
+ return [
+ {
+ peer,
+ name: props.displayName(peer.userId),
+ top: (rect.height ? rect.top : fallback.top) - origin.top,
+ left: (rect.height ? rect.left : fallback.left) - origin.left,
+ height,
+ },
+ ];
+ });
+ });
+
+ return (
+ <For each={carets()}>
+ {(caret) => (
+ <div
+ class="pointer-events-none absolute z-10"
+ data-docx-peer={caret.peer.peerId}
+ style={{
+ top: `${caret.top}px`,
+ left: `${caret.left}px`,
+ height: `${caret.height}px`,
+ }}
+ >
+ <div
+ class="h-full w-0.5"
+ style={{ 'background-color': caret.peer.color }}
+ />
+ <Show when={caret.name}>
+ <div
+ class="absolute bottom-full left-0 whitespace-nowrap rounded-sm px-1 py-px text-[10px] font-medium leading-tight"
+ style={{ 'background-color': caret.peer.color, color: '#fff' }}
+ >
+ {caret.name}
+ </div>
+ </Show>
+ </div>
+ )}
+ </For>
+ );
+}
diff --git a/apps/web/src/features/block-write/views/DocxComments.tsx b/apps/web/src/features/block-write/views/DocxComments.tsx
new file mode 100644
index 0000000000..03e92e0397
--- /dev/null
+++ b/apps/web/src/features/block-write/views/DocxComments.tsx
@@ -0,0 +1,189 @@
+import {
+ commentView,
+ DRAFT_THREAD_ID,
+ type Root,
+ type ThreadId,
+} from '@core/comments/commentType';
+import {
+ CommentsContext,
+ type CommentsContextType,
+ ThreadCard,
+} from '@core/comments/Thread';
+import {
+ newMessageId,
+ useSendMessageMutation,
+} from '@queries/messages/mutations';
+import type { MessageListItem } from '@service-storage/messages';
+import { type Accessor, For, Show } from 'solid-js';
+import type {
+ DocxComments,
+ LocatedThread,
+} from '../primitives/create-docx-comments';
+import { DocxMarginLayout } from './DocxMarginLayout';
+
+function toRoot(item: MessageListItem, anchorId: string): Root {
+ return {
+ ...commentView(item),
+ rootId: item.id,
+ threadId: item.id,
+ anchorId,
+ isNew: false,
+ children: item.thread.preview.map((reply) => reply.id),
+ replyCount: item.thread.reply_count,
+ resolved: item.state.resolved,
+ };
+}
+
+function draftRoot(markId: string, userId: string): Root {
+ return {
+ id: DRAFT_THREAD_ID,
+ rootId: DRAFT_THREAD_ID,
+ threadId: DRAFT_THREAD_ID,
+ anchorId: markId,
+ owner: userId,
+ author: userId,
+ text: '',
+ createdAt: undefined,
+ isNew: true,
+ children: [],
+ };
+}
+
+/**
+ * Comment threads beside a DOCX, on the shared message store. Threads are
+ * anchored by marks in the collaborative document; the margin lays out one
+ * card per visible thread next to its text.
+ */
+export function DocxCommentMargin(props: {
+ documentId: string;
+ comments: DocxComments;
+ /** The editor element; selection and clicks are read from it. */
+ editorRoot: HTMLElement | undefined;
+ /** Positioning parent: the margin scrolls with the document. */
+ margin: HTMLElement | undefined;
+ revision: Accessor<number>;
+ canComment: Accessor<boolean>;
+ isOwner: Accessor<boolean>;
+ userId: Accessor<string | undefined>;
+}) {
+ const userId = props.userId;
+ const send = useSendMessageMutation();
+ const parent = () => ({ type: 'document' as const, id: props.documentId });
+
+ const setActiveThread = (threadId: ThreadId | null) => {
+ if (threadId === null || threadId === DRAFT_THREAD_ID) {
+ if (threadId === null && props.comments.draft())
+ props.comments.cancelDraft();
+ else if (threadId === null) props.comments.setActive(null);
+ return;
+ }
+ props.comments.setActive(String(threadId));
+ };
+
+ const context: CommentsContextType = {
+ setActiveThread,
+ setThreadHeight: () => {},
+ canComment: props.canComment,
+ isDocumentOwner: props.isOwner,
+ documentId: props.documentId,
+ documentType: 'write',
+ highlightedCommentId: () => null,
+ messageOperations: {
+ createComment: async ({ threadId: _threadId, ...message }) => {
+ const senderId = userId();
+ if (!senderId) return null;
+ const optimisticId = newMessageId();
+ try {
+ const created = await props.comments.commitDraft((draft) =>
+ send.mutateAsync({
+ parent: parent(),
+ senderId,
+ optimisticId,
+ message: {
+ ...message,
+ anchor: {
+ type: 'markdown',
+ mark_id: draft.markId,
+ marked_text: draft.mark.text,
+ },
+ },
+ })
+ );
+ props.comments.setActive(optimisticId);
+ return created;
+ } catch (error) {
+ console.error('Failed to post DOCX comment', error);
+ return null;
+ }
+ },
+ },
+ };
+
+ const rootFor = (thread: LocatedThread): Root =>
+ thread.root
+ ? toRoot(thread.root, thread.markId)
+ : draftRoot(thread.markId, userId() ?? '');
+
+ return (
+ <CommentsContext.Provider value={context}>
+ <DocxMarginLayout
+ comments={props.comments}
+ editorRoot={props.editorRoot}
+ margin={props.margin}
+ revision={props.revision}
+ canComment={props.canComment}
+ renderCard={(thread, isActive) => (
+ <ThreadCard comment={rootFor(thread)} isActive={isActive()} />
+ )}
+ />
+ </CommentsContext.Provider>
+ );
+}
+
+/** Threads whose text is gone, or that were left on an earlier rendering of the file. */
+export function DocxDetachedComments(props: {
+ documentId: string;
+ threads: MessageListItem[];
+ canComment: Accessor<boolean>;
+ isOwner: Accessor<boolean>;
+}) {
+ const context: CommentsContextType = {
+ setActiveThread: () => {},
+ setThreadHeight: () => {},
+ canComment: props.canComment,
+ isDocumentOwner: props.isOwner,
+ documentId: props.documentId,
+ documentType: 'write',
+ highlightedCommentId: () => null,
+ messageOperations: { createComment: () => Promise.resolve(null) },
+ };
+ return (
+ <Show when={props.threads.length}>
+ <CommentsContext.Provider value={context}>
+ <section
+ class="flex flex-col gap-2"
+ aria-label="Comments on changed text"
+ >
+ <h3 class="text-xs font-medium text-ink-muted">
+ Comments on text that has changed
+ </h3>
+ <For each={props.threads}>
+ {(thread) => (
+ <div class="w-full">
+ <ThreadCard
+ comment={toRoot(
+ thread,
+ thread.state.anchor && 'mark_id' in thread.state.anchor
+ ? thread.state.anchor.mark_id
+ : thread.id
+ )}
+ isActive
+ />
+ </div>
+ )}
+ </For>
+ </section>
+ </CommentsContext.Provider>
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/block-write/views/DocxEditorView.tsx b/apps/web/src/features/block-write/views/DocxEditorView.tsx
new file mode 100644
index 0000000000..f4a7bd2d17
--- /dev/null
+++ b/apps/web/src/features/block-write/views/DocxEditorView.tsx
@@ -0,0 +1,323 @@
+import type { MessageListItem } from '@service-storage/messages';
+import type { LoroDoc } from 'loro-crdt';
+import {
+ type Accessor,
+ createEffect,
+ createMemo,
+ createSignal,
+ type JSX,
+ onCleanup,
+ onMount,
+ Show,
+} from 'solid-js';
+import {
+ type DocxAlignment,
+ type DocxInlineFormat,
+ type DocxParagraphStyle,
+ DocxToolbar,
+} from '../components/DocxToolbar';
+import { blockOf, contentOffset } from '../core/text-offsets';
+import { createCommentHighlights } from '../primitives/create-comment-highlights';
+import {
+ createDocxComments,
+ type DocxComments,
+} from '../primitives/create-docx-comments';
+import { createDocxEditor } from '../primitives/create-docx-editor';
+import type { DocxPeer, DocxSelection } from '../queries/docx-session';
+import type { DocxodusRuntime } from '../queries/docxodus-runtime';
+import { DocxCollaboratorCarets } from './DocxCollaborators';
+
+/** Paragraph styles offered in the toolbar, when the document defines them. */
+const PREFERRED_STYLES = [
+ 'Normal',
+ 'Title',
+ 'Subtitle',
+ 'Heading 1',
+ 'Heading 2',
+ 'Heading 3',
+ 'Quote',
+];
+
+export type DocxMarginContext = {
+ comments: DocxComments;
+ editorRoot: HTMLElement | undefined;
+ margin: HTMLElement | undefined;
+ revision: Accessor<number>;
+};
+
+export type DocxEditorViewProps = {
+ runtime: DocxodusRuntime;
+ /** Collaborative document, or null for a read-only original. */
+ doc: LoroDoc | null;
+ original?: Uint8Array;
+ canEdit: boolean;
+ canComment: Accessor<boolean>;
+ author: string;
+ fileName: string;
+ peers: Accessor<DocxPeer[]>;
+ displayName: (userId: string | undefined) => string;
+ onSelection?: (selection: DocxSelection | undefined) => void;
+ subscribeRemote?: (listener: () => void) => () => void;
+ /** Comment roots for this document; omit to disable commenting. */
+ commentRoots?: Accessor<MessageListItem[]>;
+ /** Margin content (comment threads) laid out beside the page. */
+ margin?: (context: DocxMarginContext) => JSX.Element;
+ /** Content below the page (discussion, detached comments). */
+ footer?: (comments: DocxComments) => JSX.Element;
+ onDownload: (bytes: Uint8Array) => void;
+ onError?: (error: unknown) => void;
+ /** Test hook: the mounted editor handle. */
+ onReady?: (handle: ReturnType<typeof createDocxEditor>) => void;
+};
+
+/** The collaborative DOCX editor: toolbar, page, collaborators and comments. */
+export function DocxEditorView(props: DocxEditorViewProps) {
+ let scroller!: HTMLDivElement;
+ let page!: HTMLDivElement;
+ const [editorRoot, setEditorRoot] = createSignal<HTMLDivElement>();
+ const [margin, setMargin] = createSignal<HTMLDivElement>();
+ const [loading, setLoading] = createSignal(true);
+ const [format, setFormat] = createSignal<
+ Partial<Record<DocxInlineFormat, boolean>>
+ >({});
+ const [paragraphStyle, setParagraphStyle] = createSignal<string | null>(null);
+ const [trackChanges, setTrackChanges] = createSignal(false);
+
+ const handle = createDocxEditor({
+ runtime: props.runtime,
+ doc: props.doc,
+ original: props.original,
+ editable: props.canEdit,
+ author: props.author,
+ scroller: () => scroller,
+ subscribeRemote: props.subscribeRemote,
+ onError: props.onError,
+ });
+ const editor = handle.editor;
+
+ const comments = createDocxComments({
+ doc: props.doc,
+ roots: () => props.commentRoots?.() ?? [],
+ root: editorRoot,
+ revision: handle.revision,
+ canEdit: () => props.canEdit,
+ });
+
+ const highlightStyles = createCommentHighlights(
+ comments,
+ () => !!props.commentRoots
+ );
+
+ onMount(() => {
+ const root = editorRoot();
+ if (!root) return;
+ handle
+ .mount(root)
+ .then(() => {
+ setLoading(false);
+ props.onReady?.(handle);
+ })
+ .catch((error: unknown) => {
+ setLoading(false);
+ props.onError?.(error);
+ });
+ });
+
+ const paragraphStyles = createMemo<DocxParagraphStyle[]>(() => {
+ handle.revision();
+ const current = editor();
+ if (!current) return [];
+ const byName = new Map(
+ current
+ .styles()
+ .filter((style) => style.type === 'paragraph')
+ .map((style) => [style.name.toLowerCase(), style])
+ );
+ return PREFERRED_STYLES.flatMap((name) => {
+ const style = byName.get(name.toLowerCase());
+ return style ? [{ id: style.id, name }] : [];
+ });
+ });
+
+ const refreshFormat = () => {
+ const current = editor();
+ if (!current) return;
+ try {
+ setFormat(current.queryFormatState());
+ setParagraphStyle(current.styleAtCaret());
+ } catch {
+ // The caret is outside an editable block.
+ }
+ };
+
+ // Publish this user's caret and keep the toolbar state current.
+ createEffect(() => {
+ const root = editorRoot();
+ if (!root) return;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const onSelectionChange = () => {
+ clearTimeout(timer);
+ timer = setTimeout(() => {
+ refreshFormat();
+ const selection = window.getSelection();
+ const node = selection?.focusNode;
+ const block = node ? blockOf(node, root) : null;
+ const id = block?.getAttribute('data-anchor');
+ props.onSelection?.(
+ block && id && node
+ ? {
+ block: id,
+ offset: contentOffset(block, node, selection!.focusOffset),
+ }
+ : undefined
+ );
+ }, 80);
+ };
+ document.addEventListener('selectionchange', onSelectionChange);
+ onCleanup(() => {
+ clearTimeout(timer);
+ document.removeEventListener('selectionchange', onSelectionChange);
+ });
+ });
+
+ const beginComment = () => {
+ if (!comments.beginDraft())
+ props.onError?.(new Error('Select text to comment on.'));
+ };
+
+ createEffect(() => {
+ const root = editorRoot();
+ if (!root || !props.commentRoots) return;
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (
+ (event.metaKey || event.ctrlKey) &&
+ event.altKey &&
+ event.code === 'KeyM'
+ ) {
+ event.preventDefault();
+ beginComment();
+ }
+ };
+ root.addEventListener('keydown', onKeyDown);
+ onCleanup(() => root.removeEventListener('keydown', onKeyDown));
+ });
+
+ const run = (
+ command: (instance: NonNullable<ReturnType<typeof editor>>) => void
+ ) => {
+ const current = editor();
+ if (!current) return;
+ try {
+ command(current);
+ } catch (error) {
+ props.onError?.(error);
+ }
+ refreshFormat();
+ };
+
+ return (
+ <div class="flex size-full min-h-0 min-w-0 flex-col">
+ {/* A DOCX is authored for paper: its runs carry their own colours, so
+ the sheet stays white whatever the app theme is. */}
+ <style>{`.docx-paper { background: #fff; color: #000; }
+.docx-paper .docx-hf-band { padding: 10px 1in; }
+.docx-paper .docx-hf-band[data-hf-band='header'] { border-bottom: 1px dashed #e5e7eb; }
+.docx-paper .docx-hf-band[data-hf-band='footer'] { border-top: 1px dashed #e5e7eb; }
+.docx-paper .docx-hf-placeholder { font: 12px/1.5 var(--font-sans, sans-serif); color: #9ca3af; }
+.docx-paper .docx-hf-tag { margin-bottom: 2px; font: 500 10px/1.4 var(--font-sans, sans-serif); letter-spacing: 0.06em; text-transform: uppercase; color: #9ca3af; }
+${highlightStyles}`}</style>
+ <DocxToolbar
+ canEdit={props.canEdit}
+ canComment={!!props.commentRoots && props.canComment()}
+ format={format()}
+ paragraphStyle={paragraphStyle()}
+ paragraphStyles={paragraphStyles()}
+ trackChanges={trackChanges()}
+ onFormat={(key) => run((instance) => instance.format(key))}
+ onParagraphStyle={(id) =>
+ run((instance) => instance.setParagraphStyle(id))
+ }
+ onList={(kind) => run((instance) => instance.toggleList(kind))}
+ onAlign={(alignment: DocxAlignment) =>
+ run((instance) => instance.setAlignment(alignment))
+ }
+ onUndo={() => run((instance) => instance.undo())}
+ onRedo={() => run((instance) => instance.redo())}
+ onInsertTable={() => run((instance) => instance.insertTable(3, 3))}
+ onToggleTrackChanges={() =>
+ run((instance) => {
+ const next = !trackChanges();
+ instance.setTrackedChanges(
+ next
+ ? props.runtime.module.TrackedChangeMode.RenderInline
+ : props.runtime.module.TrackedChangeMode.Accept
+ );
+ setTrackChanges(next);
+ })
+ }
+ onComment={beginComment}
+ onDownload={() => {
+ handle.flush();
+ const bytes = handle.save();
+ if (bytes) props.onDownload(bytes);
+ }}
+ />
+ <div
+ ref={scroller}
+ class="relative min-h-0 flex-1 overflow-auto bg-panel"
+ data-docx-scroller
+ >
+ {/* The page column shrinks so Docxodus zooms the sheet to fit a
+ narrow split instead of scrolling it sideways. */}
+ <div class="relative mx-auto flex max-w-[1160px] justify-center gap-2 px-4 pt-6 pb-24">
+ <div
+ ref={page}
+ class="relative min-w-0 max-w-[816px] flex-1"
+ data-docx-page
+ >
+ <div ref={setEditorRoot} class="docx-paper rounded-sm shadow-md" />
+ <DocxCollaboratorCarets
+ peers={props.peers()}
+ editorRoot={editorRoot()}
+ overlay={page}
+ revision={handle.revision}
+ displayName={props.displayName}
+ />
+ <Show when={loading()}>
+ <div class="absolute inset-0 flex items-start justify-center pt-24 text-sm text-ink-muted">
+ Opening document…
+ </div>
+ </Show>
+ </div>
+ <Show when={props.margin}>
+ {(renderMargin) => (
+ <div
+ ref={setMargin}
+ class="relative w-[296px] shrink-0"
+ data-docx-margin
+ >
+ {renderMargin()({
+ comments,
+ get editorRoot() {
+ return editorRoot();
+ },
+ get margin() {
+ return margin();
+ },
+ revision: handle.revision,
+ })}
+ </div>
+ )}
+ </Show>
+ </div>
+ <Show when={props.footer}>
+ {(renderFooter) => (
+ <div class="mx-auto flex max-w-3xl flex-col gap-6 px-4 pb-16">
+ {renderFooter()(comments)}
+ </div>
+ )}
+ </Show>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/block-write/views/DocxMarginLayout.tsx b/apps/web/src/features/block-write/views/DocxMarginLayout.tsx
new file mode 100644
index 0000000000..be0d475c04
--- /dev/null
+++ b/apps/web/src/features/block-write/views/DocxMarginLayout.tsx
@@ -0,0 +1,175 @@
+import ChatCircleText from '@phosphor/chat-circle-text.svg';
+import { Button } from '@ui';
+import {
+ type Accessor,
+ createEffect,
+ createMemo,
+ createSignal,
+ For,
+ type JSX,
+ onCleanup,
+ Show,
+} from 'solid-js';
+import { createStore } from 'solid-js/store';
+import { layoutMarginCards } from '../core/comment-layout';
+import { blockOf } from '../core/text-offsets';
+import type {
+ DocxComments,
+ LocatedThread,
+} from '../primitives/create-docx-comments';
+
+const CARD_WIDTH = 280;
+
+/**
+ * The comment margin beside a DOCX: one card per placed thread, stacked next
+ * to its text, a floating comment button beside any selection, and clicks on
+ * highlighted text open their thread. The card itself is supplied.
+ */
+export function DocxMarginLayout(props: {
+ comments: DocxComments;
+ /** The editor element; selection and clicks are read from it. */
+ editorRoot: HTMLElement | undefined;
+ /** Positioning parent: the margin scrolls with the document. */
+ margin: HTMLElement | undefined;
+ revision: Accessor<number>;
+ canComment: Accessor<boolean>;
+ renderCard: (
+ thread: LocatedThread,
+ isActive: Accessor<boolean>
+ ) => JSX.Element;
+}) {
+ const [heights, setHeights] = createStore<Record<string, number>>({});
+ const [layoutTick, setLayoutTick] = createSignal(0);
+ const relayout = () => setLayoutTick((tick) => tick + 1);
+
+ createEffect(() => {
+ const margin = props.margin;
+ const root = props.editorRoot;
+ if (!margin || !root) return;
+ const observer = new ResizeObserver(relayout);
+ observer.observe(margin);
+ observer.observe(root);
+ onCleanup(() => observer.disconnect());
+ });
+
+ const anchorTop = (thread: LocatedThread, marginTop: number) => {
+ const rects = thread.range.getClientRects();
+ const first = rects.length
+ ? rects[0]
+ : thread.range.getBoundingClientRect();
+ return first.top - marginTop;
+ };
+
+ const positions = createMemo(() => {
+ layoutTick();
+ props.revision();
+ const margin = props.margin;
+ if (!margin) return new Map<string, number>();
+ const marginTop = margin.getBoundingClientRect().top;
+ const items = props.comments
+ .located()
+ .map((thread) => ({ id: thread.id, top: anchorTop(thread, marginTop) }));
+ return layoutMarginCards(
+ items,
+ new Map(Object.entries(heights)),
+ props.comments.active()
+ );
+ });
+
+ // Clicking highlighted text opens its thread.
+ createEffect(() => {
+ const root = props.editorRoot;
+ if (!root) return;
+ const onClick = () => {
+ const selection = window.getSelection();
+ if (!selection?.isCollapsed || !selection.anchorNode) return;
+ if (!blockOf(selection.anchorNode, root)) return;
+ const hit = props.comments.threadAt(
+ selection.anchorNode,
+ selection.anchorOffset
+ );
+ if (hit) props.comments.setActive(hit);
+ else if (!props.comments.draft()) props.comments.setActive(null);
+ };
+ root.addEventListener('click', onClick);
+ onCleanup(() => root.removeEventListener('click', onClick));
+ });
+
+ // A floating "comment" affordance beside any selected text.
+ const [selectionTop, setSelectionTop] = createSignal<number | null>(null);
+ createEffect(() => {
+ const root = props.editorRoot;
+ const margin = props.margin;
+ if (!root || !margin) return;
+ const update = () => {
+ const selection = window.getSelection();
+ if (
+ !props.canComment() ||
+ !selection ||
+ selection.isCollapsed ||
+ selection.rangeCount === 0 ||
+ !blockOf(selection.getRangeAt(0).startContainer, root)
+ ) {
+ setSelectionTop(null);
+ return;
+ }
+ const rect = selection.getRangeAt(0).getClientRects()[0];
+ setSelectionTop(
+ rect ? rect.top - margin.getBoundingClientRect().top : null
+ );
+ };
+ document.addEventListener('selectionchange', update);
+ onCleanup(() => document.removeEventListener('selectionchange', update));
+ });
+
+ return (
+ <>
+ <Show when={selectionTop() !== null && !props.comments.draft()}>
+ <div
+ class="absolute left-2 z-10"
+ style={{ top: `${selectionTop()}px` }}
+ >
+ <Button
+ size="icon-md"
+ variant="cta"
+ label="Comment"
+ data-docx-comment-button
+ onMouseDown={(event: MouseEvent) => event.preventDefault()}
+ onClick={() => props.comments.beginDraft()}
+ >
+ <ChatCircleText />
+ </Button>
+ </div>
+ </Show>
+ <For each={props.comments.located()}>
+ {(thread) => {
+ let card!: HTMLDivElement;
+ createEffect(() => {
+ const observer = new ResizeObserver(() =>
+ setHeights(thread.id, card.offsetHeight)
+ );
+ observer.observe(card);
+ onCleanup(() => observer.disconnect());
+ });
+ const top = () => positions().get(thread.id) ?? 0;
+ const isActive = () => props.comments.active() === thread.id;
+ return (
+ <div
+ ref={card}
+ data-docx-thread={thread.id}
+ class="absolute left-2 transition-[top] duration-150"
+ classList={{
+ 'z-20': isActive(),
+ 'opacity-70': thread.resolved && !isActive(),
+ }}
+ style={{ top: `${top()}px`, width: `${CARD_WIDTH}px` }}
+ onClick={() => props.comments.setActive(thread.id)}
+ >
+ {props.renderCard(thread, isActive)}
+ </div>
+ );
+ }}
+ </For>
+ </>
+ );
+}
diff --git a/apps/web/src/lib/core/block.ts b/apps/web/src/lib/core/block.ts
index 9bd7a55157..df2304a100 100644
--- a/apps/web/src/lib/core/block.ts
+++ b/apps/web/src/lib/core/block.ts
@@ -51,13 +51,6 @@ import type { ObjectLike, ResultError } from './util/result';
export { BlockAliasRegistry, BlockRegistry } from '../constants/block-registry';
-/** Block names that resolve through another concrete block implementation. */
-export const VirtualBlockRegistry = ['write'] as const;
-const virtualBlockNames = new Set<string>(VirtualBlockRegistry);
-export const ConcreteBlockRegistry = BlockRegistry.filter(
- (name) => !virtualBlockNames.has(name)
-);
-
type BlockNameKeys = keyof typeof BlockRegistry & number;
/**
diff --git a/apps/web/src/lib/core/comments/Thread.tsx b/apps/web/src/lib/core/comments/Thread.tsx
index b0c7cdf570..17ae1f2596 100644
--- a/apps/web/src/lib/core/comments/Thread.tsx
+++ b/apps/web/src/lib/core/comments/Thread.tsx
@@ -52,7 +52,7 @@ export type CommentsContextType = {
/** Comment writes through the shared message API. */
messageOperations: MessageCommentOperations;
documentId: string;
- documentType: 'md' | 'task' | 'snippet' | 'skill' | 'pdf';
+ documentType: 'md' | 'task' | 'snippet' | 'skill' | 'pdf' | 'write';
highlightedCommentId: Accessor<CommentId | null>;
/** Releases the comment-link highlight when the highlighted comment is clicked. */
clearHighlightedComment?: () => void;
diff --git a/apps/web/src/lib/core/constant/allBlocks.test.ts b/apps/web/src/lib/core/constant/allBlocks.test.ts
index 783042a109..65979d6b53 100644
--- a/apps/web/src/lib/core/constant/allBlocks.test.ts
+++ b/apps/web/src/lib/core/constant/allBlocks.test.ts
@@ -1,4 +1,4 @@
-import { ConcreteBlockRegistry } from '@core/block';
+import { BlockRegistry } from '@core/block';
import { describe, expect, it } from 'vitest';
const definitionFiles = import.meta.glob(
@@ -11,7 +11,7 @@ const definitionFiles = import.meta.glob(
);
describe('block definition discovery', () => {
- it('has one definition file for every concrete block', () => {
+ it('has one definition file for every block', () => {
const discoveredNames = Object.keys(definitionFiles).map((path) =>
path
.split('/')
@@ -19,6 +19,6 @@ describe('block definition discovery', () => {
?.replace(/^block-/, '')
);
- expect(discoveredNames.sort()).toEqual([...ConcreteBlockRegistry].sort());
+ expect(discoveredNames.sort()).toEqual([...BlockRegistry].sort());
});
});
diff --git a/apps/web/src/lib/core/constant/allBlocks.ts b/apps/web/src/lib/core/constant/allBlocks.ts
index a75019d45e..115e08673a 100644
--- a/apps/web/src/lib/core/constant/allBlocks.ts
+++ b/apps/web/src/lib/core/constant/allBlocks.ts
@@ -3,7 +3,6 @@ import {
type BlockAlias,
type BlockName,
BlockRegistry,
- ConcreteBlockRegistry,
type FileTypeString,
type MimeType,
} from '@core/block';
@@ -11,7 +10,11 @@ import type { SubType } from '@entity';
import type { ItemType } from '@service-storage/client';
import type { BasicDocumentSubTypeProperty } from '@service-storage/generated/schemas';
import type { BasicDocumentFileType } from '@service-storage/generated/schemas/basicDocumentFileType';
-import { ENABLE_DOCX_TO_PDF } from './featureFlags';
+import {
+ ENABLE_DOCX_TO_PDF,
+ enableDocxEditor,
+ isFeatureEnabled,
+} from './featureFlags';
import { DefaultFilename } from './filename';
const discoveredBlockDefinitions = Object.values<AnyBlockDefinition>(
@@ -33,9 +36,9 @@ if (duplicateDefinitionNames.length > 0) {
);
}
-// `write` is a legacy virtual block name that resolves to `pdf` when the
-// DOCX-to-PDF feature is enabled; every other concrete block needs a module.
-const missingBlockDefinitions = ConcreteBlockRegistry.filter(
+// Every block needs a module. `write` (DOCX) is the collaborative DOCX editor
+// when it is enabled; otherwise `verifyBlockName` resolves it to `pdf`.
+const missingBlockDefinitions = BlockRegistry.filter(
(name) => !definitionNames.includes(name)
);
if (missingBlockDefinitions.length > 0) {
@@ -189,10 +192,9 @@ export function fileTypeToBlockName(
if (blockOrFiletype === 'crm_company') return 'company';
if (blockOrFiletype === 'crm_contact') return 'contact';
- if (ENABLE_DOCX_TO_PDF) {
- if (blockOrFiletype === 'docx' || blockOrFiletype === 'write') {
- return icon ? 'write' : 'pdf';
- }
+ if (blockOrFiletype === 'docx' || blockOrFiletype === 'write') {
+ if (isFeatureEnabled(enableDocxEditor)) return 'write';
+ if (ENABLE_DOCX_TO_PDF) return icon ? 'write' : 'pdf';
}
if (isBlockAlias(blockOrFiletype)) {
@@ -329,8 +331,9 @@ export function verifyBlockName(
name: string | undefined
): BlockName | BlockAlias {
if (!name) return 'unknown';
- if (ENABLE_DOCX_TO_PDF && name === 'write') {
- return 'pdf';
+ if (name === 'write') {
+ if (isFeatureEnabled(enableDocxEditor)) return 'write';
+ if (ENABLE_DOCX_TO_PDF) return 'pdf';
}
if (isBlockAlias(name)) return name;
if (name && name in blocks) return name as BlockName;
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index d689db30e2..9d91a54f79 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -224,6 +224,16 @@ export const ENABLE_DOCX_TO_PDF = defineFlag({
default: true,
}).enabled;
+/**
+ * Open DOCX files in the collaborative DOCX editor instead of the converted
+ * PDF. On in development; deployed environments defer to PostHog.
+ */
+export const enableDocxEditor = defineFlag({
+ key: 'enable-docx-editor',
+ env: 'ENABLE_DOCX_EDITOR',
+ default: DEV_MODE_ENV || undefined,
+});
+
export const ENABLE_MARKDOWN_LIVE_COLLABORATION = defineFlag({
env: 'ENABLE_MARKDOWN_LIVE_COLLABORATION',
default: true,
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index e9305f4808..62ee7a3f92 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -2110,7 +2110,7 @@ export interface SpreadsheetChange {
range?: string | null;
}
/**
- * Comment on a document on behalf of the user. Pass threadId to reply in an existing inline or Discussion thread; pass quote to start a new inline comment on a passage of a Macro markdown document; omit both to start a new Discussion comment on the document as a whole. Replies and Discussion comments support any document type. Only use this when explicitly asked to reply to or comment on a document. Thread ids come from the comments ReadContent returns. For an inline comment, quote the passage exactly as the document reads, as plain text without markdown syntax, within a single paragraph, heading, list item or table cell. If the passage appears more than once the tool refuses and lists each occurrence so you can choose one with occurrence, counting from 1; if the text is not found, read the document again rather than guessing. Do not combine threadId with quote. occurrence only applies with quote.
+ * Comment on a document on behalf of the user. Pass threadId to reply in an existing inline or Discussion thread; pass quote to start a new inline comment on a passage of a Macro markdown or Word (DOCX) document; omit both to start a new Discussion comment on the document as a whole. Replies and Discussion comments support any document type. Only use this when explicitly asked to reply to or comment on a document. Thread ids come from the comments ReadContent returns. For an inline comment, quote the passage exactly as the document reads, as plain text without markdown syntax, within a single paragraph, heading, list item or table cell. If the passage appears more than once the tool refuses and lists each occurrence so you can choose one with occurrence, counting from 1; if the text is not found, read the document again rather than guessing. Do not combine threadId with quote. occurrence only applies with quote.
*/
export interface CommentOnDocument {
/**
@@ -2126,7 +2126,7 @@ export interface CommentOnDocument {
*/
threadId?: string | null;
/**
- * The passage to comment on, quoted exactly as the document reads: plain text without markdown syntax such as ** or link brackets. Keep it to the words the comment is about; a longer quote is more likely to be unique. Starts a new inline comment on a markdown document only. Cannot be combined with threadId.
+ * The passage to comment on, quoted exactly as the document reads: plain text without markdown syntax such as ** or link brackets. Keep it to the words the comment is about; a longer quote is more likely to be unique. Starts a new inline comment on a markdown or Word (DOCX) document. Cannot be combined with threadId.
*/
quote?: string | null;
/**
diff --git a/apps/web/src/lib/service-clients/service-storage/util/downloadExportedDocument.ts b/apps/web/src/lib/service-clients/service-storage/util/downloadExportedDocument.ts
new file mode 100644
index 0000000000..4fab22e116
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/util/downloadExportedDocument.ts
@@ -0,0 +1,24 @@
+import { storageServiceClient } from '../client';
+import { fetchPresigned } from './fetchPresigned';
+
+/**
+ * Download a document as document storage exports it, e.g. a Word document
+ * rebuilt from its stored parts.
+ */
+export async function downloadExportedDocument({
+ documentId,
+}: {
+ documentId: string;
+}): Promise<Uint8Array> {
+ const exported = await storageServiceClient.exportDocument({ documentId });
+ if (exported.isErr()) throw new Error('Unable to export the document.');
+ const bytes = await fetchPresigned(
+ exported.value.presigned_url,
+ 'arraybuffer'
+ );
+ if (bytes.isErr())
+ throw new Error(
+ `Unable to download the exported document: ${bytes.error[0]?.message}`
+ );
+ return new Uint8Array(bytes.value);
+}
diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.ts
index 7d089cb8da..e7addf046e 100644
--- a/apps/web/src/vite-env.d.ts
+++ b/apps/web/src/vite-env.d.ts
@@ -4,6 +4,8 @@ interface ImportMetaEnv {
readonly __APP_BUILD_TIME__?: number;
readonly __LOCAL_JWT__: string;
readonly __GIT_BRANCH__: string;
+ /** Docxodus release whose WebAssembly runtime the build serves. */
+ readonly DOCXODUS_VERSION?: string;
readonly VITE_SEGMENT_WRITE_KEY: string;
readonly VITE_POSTHOG_API_KEY: string;
diff --git a/apps/web/vite.base.ts b/apps/web/vite.base.ts
index a4e550f571..ccfb1dcc46 100644
--- a/apps/web/vite.base.ts
+++ b/apps/web/vite.base.ts
@@ -11,6 +11,7 @@ import tsconfigpaths from 'vite-tsconfig-paths';
// @ts-ignore
import { version } from './package.json';
import { devHttps } from './scripts/dev-https';
+import { docxodusRuntime } from './scripts/docxodus-runtime';
import { hostedDevProxy } from './scripts/hosted-dev-proxy';
import { keepImportMetaDev } from './scripts/keep-import-meta-dev';
import { localDevServer } from './scripts/local-dev-server';
@@ -99,6 +100,7 @@ export const createAppViteConfig = (): UserConfigFn => {
root: './',
}),
gitBranchHmrPlugin(),
+ docxodusRuntime(),
],
define: defineEnv(ENV_MODE, command),
clearScreen: false,
diff --git a/bun.lock b/bun.lock
index ab3f948a2e..71b93567d6 100644
--- a/bun.lock
+++ b/bun.lock
@@ -135,6 +135,7 @@
"detect-browser": "^5.3.0",
"diff": "^9.0.0",
"dinero.js": "2.0.0-alpha.8",
+ "docxodus": "12.6.5",
"effect": "^4.0.0-rc.111",
"email-validator": "^2.0.4",
"emojibase-data": "^17.0.0",
@@ -582,6 +583,10 @@
"@asyncapi/specs": ["@asyncapi/[email protected]", "", { "dependencies": { "@types/json-schema": "^7.0.11" } }, "sha512-A3WBLqAKGoJ2+6FWFtpjBlCQ1oFCcs4GxF7zsIGvNqp/klGUHjlA3aAcZ9XMMpLGE8zPeYDz2x9FmO6DSuKraQ=="],
+ "@atlaskit/pragmatic-drag-and-drop": ["@atlaskit/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.0.0", "bind-event-listener": "^3.0.0", "raf-schd": "^4.0.3" } }, "sha512-ou1j+lBqutK7p2S80lMresJeKu9qAL1zr1K+N0OyCTzbMpD6pXRHray8VkRoHgJICI7Wp1fk5ScJh6EctyAuPw=="],
+
+ "@atlaskit/pragmatic-drag-and-drop-auto-scroll": ["@atlaskit/[email protected]", "", { "dependencies": { "@atlaskit/pragmatic-drag-and-drop": "^4.0.0", "@babel/runtime": "^7.0.0" } }, "sha512-2fhWAG48EjPoKhoHLG6RcT3/VaCzYEbRb6BtA/Vcfx4FrL0P1KrEgBJ6OAwB0X8MOV6UH22YgjFFHjv8fQD9rA=="],
+
"@aws-crypto/sha256-js": ["@aws-crypto/[email protected]", "", { "dependencies": { "@aws-crypto/util": "^5.2.0", "@aws-sdk/types": "^3.222.0", "tslib": "^2.6.2" } }, "sha512-FFQQyu7edu4ufvIZ+OadFpHHOt+eSTBaYaki44c+akjg7qZg9oOQeLlk77F6tSYqjDAFClrHJk9tMf0HdVyOvA=="],
"@aws-crypto/util": ["@aws-crypto/[email protected]", "", { "dependencies": { "@aws-sdk/types": "^3.222.0", "@smithy/util-utf8": "^2.0.0", "tslib": "^2.6.2" } }, "sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ=="],
@@ -1972,6 +1977,8 @@
"binary-search-bounds": ["[email protected]", "", {}, "sha512-H0ea4Fd3lS1+sTEB2TgcLoK21lLhwEJzlQv3IN47pJS976Gx4zoWe0ak3q+uYh60ppQxg9F16Ri4tS1sfD4+jA=="],
+ "bind-event-listener": ["[email protected]", "", {}, "sha512-PJvH288AWQhKs2v9zyfYdPzlPqf5bXbGMmhmUIY9x4dAUGIWgomO771oBQNwJnMQSnUIXhKu6sgzpBRXTlvb8Q=="],
+
"bitf": ["[email protected]", "", {}, "sha512-l3PytekTpJOq4W8QmXQQtDRI29Fp3ds2F9SfK+RTc9rvfDk0RFtFRjTuVSpYOyh0qITJP6walQq9TkxjY7gAFw=="],
"bl": ["[email protected]", "", { "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", "readable-stream": "^3.4.0" } }, "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w=="],
@@ -2262,6 +2269,8 @@
"dir-glob": ["[email protected]", "", { "dependencies": { "path-type": "^4.0.0" } }, "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA=="],
+ "docxodus": ["[email protected]", "", { "dependencies": { "@atlaskit/pragmatic-drag-and-drop": "^2.0.2", "@atlaskit/pragmatic-drag-and-drop-auto-scroll": "^3.0.0" }, "peerDependencies": { "react": ">=16.8.0" }, "optionalPeers": ["react"] }, "sha512-TnZr0/InZAEIesK2tNZ8BmNHOGafYfoHooHzXboj+bO6EmBngvP5C9jGaIYkGLmztIXd4epdSDIPvSJp1xPF6A=="],
+
"dogapi": ["[email protected]", "", { "dependencies": { "extend": "^3.0.2", "json-bigint": "^1.0.0", "lodash": "^4.17.21", "minimist": "^1.2.5", "rc": "^1.2.8" }, "bin": { "dogapi": "bin/dogapi" } }, "sha512-065fsvu5dB0o4+ENtLjZILvXMClDNH/yA9H6L8nsdcNiz9l0Hzpn7aQaCOPYXxqyzq4CRPOdwkFXUjDOXfRGbg=="],
"dom-accessibility-api": ["[email protected]", "", {}, "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg=="],
@@ -3212,6 +3221,8 @@
"raf": ["[email protected]", "", { "dependencies": { "performance-now": "^2.1.0" } }, "sha512-Sq4CW4QhwOHE8ucn6J34MqtZCeWFP2aQSmrlroYgqAV1PjStIhJXxYuTgUIfkEk7zTLjmIjLmU5q+fbD1NnOJA=="],
+ "raf-schd": ["[email protected]", "", {}, "sha512-tQkJl2GRWh83ui2DiPTJz9wEiMN20syf+5oKfB03yYP7ioZcJwsIK8FjrtLwH1m7C7e+Tt2yYBlrOpdT+dyeIQ=="],
+
"random-js": ["[email protected]", "", {}, "sha512-CRUyWmnzmZBA7RZSVGq0xMqmgCyPPxbiKNLFA5ud7KenojVX2s7Gv+V7eB52beKTPGxWRnVZ7D/tCIgYJJ8vNQ=="],
"randombytes": ["[email protected]", "", { "dependencies": { "safe-buffer": "^5.1.0" } }, "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ=="],
@@ -3786,6 +3797,8 @@
"@asamuzakjp/css-color/lru-cache": ["[email protected]", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="],
+ "@atlaskit/pragmatic-drag-and-drop-auto-scroll/@atlaskit/pragmatic-drag-and-drop": ["@atlaskit/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.0.0", "bind-event-listener": "^3.0.0", "raf-schd": "^4.0.3" } }, "sha512-pyDo2B5NiaExoKGmgeXKGNUL4aR4UzzSZm8QWWjYTEyBLVqSqKyKUwtVxMw2YEkakagOGFONUdHM32LAH2nPug=="],
+
"@babel/core/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
"@babel/helper-compilation-targets/lru-cache": ["[email protected]", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],
diff --git a/crates/documents/src/inbound/toolset/comment_on_document.rs b/crates/documents/src/inbound/toolset/comment_on_document.rs
index 61dbabe3b7..d0bd85bc3a 100644
--- a/crates/documents/src/inbound/toolset/comment_on_document.rs
+++ b/crates/documents/src/inbound/toolset/comment_on_document.rs
@@ -3,11 +3,13 @@
use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use ai_toolset::{ToolAnnotated, ToolAnnotations};
use async_trait::async_trait;
+use entity_access::domain::models::EntityAccessReceipt;
use entity_access::domain::ports::EntityAccessService;
use macro_sync_service_jwt::DocumentPermissionToken;
use messages::domain::models::{
MessageAttribution, NewThreadAnchor, PostMessage, PostMessageNotificationPolicy,
};
+use messages::domain::service::MessageWrite;
use model::document::FileType;
use models_permissions::share_permission::access_level::AccessLevel;
use schemars::JsonSchema;
@@ -26,7 +28,7 @@ use crate::domain::ports::{
#[serde(rename_all = "camelCase")]
#[schemars(
title = "CommentOnDocument",
- description = "Comment on a document on behalf of the user. Pass threadId to reply in an existing inline or Discussion thread; pass quote to start a new inline comment on a passage of a Macro markdown document; omit both to start a new Discussion comment on the document as a whole. Replies and Discussion comments support any document type. Only use this when explicitly asked to reply to or comment on a document. Thread ids come from the comments ReadContent returns. For an inline comment, quote the passage exactly as the document reads, as plain text without markdown syntax, within a single paragraph, heading, list item or table cell. If the passage appears more than once the tool refuses and lists each occurrence so you can choose one with occurrence, counting from 1; if the text is not found, read the document again rather than guessing. Do not combine threadId with quote. occurrence only applies with quote."
+ description = "Comment on a document on behalf of the user. Pass threadId to reply in an existing inline or Discussion thread; pass quote to start a new inline comment on a passage of a Macro markdown or Word (DOCX) document; omit both to start a new Discussion comment on the document as a whole. Replies and Discussion comments support any document type. Only use this when explicitly asked to reply to or comment on a document. Thread ids come from the comments ReadContent returns. For an inline comment, quote the passage exactly as the document reads, as plain text without markdown syntax, within a single paragraph, heading, list item or table cell. If the passage appears more than once the tool refuses and lists each occurrence so you can choose one with occurrence, counting from 1; if the text is not found, read the document again rather than guessing. Do not combine threadId with quote. occurrence only applies with quote."
)]
pub struct CommentOnDocument {
#[schemars(description = "The id of the document to comment on.")]
@@ -43,7 +45,7 @@ pub struct CommentOnDocument {
pub thread_id: Option<Uuid>,
#[schemars(
- description = "The passage to comment on, quoted exactly as the document reads: plain text without markdown syntax such as ** or link brackets. Keep it to the words the comment is about; a longer quote is more likely to be unique. Starts a new inline comment on a markdown document only. Cannot be combined with threadId."
+ description = "The passage to comment on, quoted exactly as the document reads: plain text without markdown syntax such as ** or link brackets. Keep it to the words the comment is about; a longer quote is more likely to be unique. Starts a new inline comment on a markdown or Word (DOCX) document. Cannot be combined with threadId."
)]
pub quote: Option<String>,
@@ -148,14 +150,18 @@ where
description: "unable to look up this document".to_string(),
internal_error: e.into(),
})?;
- if document.try_file_type() != Some(FileType::Md) {
- return Err(ToolCallError {
- description: "inline comments anchor to text in Macro markdown documents only; omit quote to comment on this document as a whole".to_string(),
- internal_error: anyhow::anyhow!(
- "document file type {:?} is not markdown",
- document.file_type
- ),
- });
+ match document.try_file_type() {
+ Some(FileType::Md) => {}
+ Some(FileType::Docx) => return self.comment_on_docx_text(&ctx, access, quote).await,
+ _ => {
+ return Err(ToolCallError {
+ description: "inline comments anchor to text in Macro markdown and Word documents only; omit quote to comment on this document as a whole".to_string(),
+ internal_error: anyhow::anyhow!(
+ "document file type {:?} does not support inline comments",
+ document.file_type
+ ),
+ });
+ }
}
// Placing the mark is a content change, but the one a commenter makes
@@ -247,6 +253,65 @@ where
}
}
+impl CommentOnDocument {
+ /// A Word document keeps its comment marks beside its collaborative
+ /// blocks, where the editor places a thread by the text it quotes and pins
+ /// it with a mark. The thread is posted with that quote and a fresh mark id;
+ /// a quote the editor cannot find shows with the comments on changed text.
+ async fn comment_on_docx_text<DSvc, ESvc, EDSvc>(
+ &self,
+ ctx: &ServiceContext<DocumentToolContext<DSvc, ESvc, EDSvc>>,
+ access: EntityAccessReceipt<MessageWrite>,
+ quote: &str,
+ ) -> ToolResult<CommentOnDocumentResponse>
+ where
+ DSvc: DocumentService + DocumentCreationService,
+ ESvc: EntityAccessService,
+ EDSvc: EditingWorkerService,
+ {
+ if self.occurrence.is_some_and(|occurrence| occurrence > 1) {
+ return Err(ToolCallError {
+ description: "comments on a Word document attach to the first appearance of the quoted text; quote a longer passage that appears only once".to_string(),
+ internal_error: anyhow::anyhow!("occurrence {:?} on a docx", self.occurrence),
+ });
+ }
+ let marked_text = quote.trim();
+ if marked_text.is_empty() {
+ return Err(ToolCallError {
+ description: "quote the passage to comment on".to_string(),
+ internal_error: anyhow::anyhow!("empty quote"),
+ });
+ }
+ let message = ctx
+ .messages
+ .post(
+ access,
+ PostMessage {
+ id: None,
+ attribution: MessageAttribution::ActingUser,
+ notification_policy: PostMessageNotificationPolicy::Default,
+ content: self.content.clone(),
+ thread_id: None,
+ anchor: Some(NewThreadAnchor::Markdown {
+ mark_id: Uuid::now_v7(),
+ marked_text: Some(marked_text.to_owned()),
+ }),
+ mentions: vec![],
+ attachments: vec![],
+ nonce: None,
+ },
+ )
+ .await
+ .map_err(comment_error("unable to post the comment"))?;
+ Ok(CommentOnDocumentResponse {
+ document_id: self.document_id,
+ thread_id: message.id,
+ comment_id: message.id,
+ marked_text: Some(marked_text.to_owned()),
+ })
+ }
+}
+
/// Best-effort removal of a mark whose thread was never posted: left in place
/// it would highlight text nobody commented on.
async fn remove_mark<EDSvc: EditingWorkerService>(
diff --git a/crates/documents/src/inbound/toolset/comment_test.rs b/crates/documents/src/inbound/toolset/comment_test.rs
index 589607a9c3..1be9d03acc 100644
--- a/crates/documents/src/inbound/toolset/comment_test.rs
+++ b/crates/documents/src/inbound/toolset/comment_test.rs
@@ -586,13 +586,73 @@ async fn comment_on_text_rejects_documents_that_are_not_markdown() {
.unwrap_err();
assert!(
- error.description.contains("markdown documents only"),
+ error
+ .description
+ .contains("markdown and Word documents only"),
"{}",
error.description
);
assert!(editing.added_comment_marks.lock().unwrap().is_empty());
}
+#[tokio::test]
+async fn comment_on_docx_text_posts_a_thread_the_editor_places_by_its_quote() {
+ let messages = FakeMessages::default();
+ let editing = FakeEditingWorker::default();
+ let response = comment_on_text(" thirty (30) days ", Some(1))
+ .call(
+ context_with(
+ AccessLevel::Comment,
+ messages.clone(),
+ "docx",
+ editing.clone(),
+ ),
+ request(),
+ )
+ .await
+ .unwrap();
+
+ // DOCX marks live in the collaborative document, not in Lexical: no
+ // editing-worker round trip.
+ assert!(editing.added_comment_marks.lock().unwrap().is_empty());
+ let posts = messages.posts.lock().unwrap();
+ let [(access, post)] = posts.as_slice() else {
+ panic!("expected one post, got {}", posts.len());
+ };
+ assert_bot_on_document(access);
+ assert_eq!(post.thread_id, None);
+ let Some(NewThreadAnchor::Markdown { marked_text, .. }) = &post.anchor else {
+ panic!("expected a text anchor, got {:?}", post.anchor);
+ };
+ assert_eq!(marked_text.as_deref(), Some("thirty (30) days"));
+ assert_eq!(response.marked_text.as_deref(), Some("thirty (30) days"));
+ assert_eq!(response.thread_id, Uuid::from_u128(99));
+}
+
+#[tokio::test]
+async fn comment_on_docx_text_asks_for_a_unique_quote_instead_of_an_occurrence() {
+ let messages = FakeMessages::default();
+ let error = comment_on_text("the Agreement", Some(2))
+ .call(
+ context_with(
+ AccessLevel::Comment,
+ messages.clone(),
+ "docx",
+ FakeEditingWorker::default(),
+ ),
+ request(),
+ )
+ .await
+ .unwrap_err();
+
+ assert!(
+ error.description.contains("first appearance"),
+ "{}",
+ error.description
+ );
+ assert!(messages.posts.lock().unwrap().is_empty());
+}
+
#[tokio::test]
async fn comment_on_text_removes_the_mark_when_placing_it_fails() {
let messages = FakeMessages::default();
diff --git a/docs/AGENT_GUIDE/README.md b/docs/AGENT_GUIDE/README.md
index 6675317768..6c20fcafa5 100644
--- a/docs/AGENT_GUIDE/README.md
+++ b/docs/AGENT_GUIDE/README.md
@@ -8,7 +8,7 @@ verified live against a local stack (`just run_local`).
| --- | --- |
| [login.md](login.md) | Passwordless login end to end, Mailpit, known crash + recovery |
| [navigation.md](navigation.md) | Routes, sidebar, command menu, keyboard model, splits |
-| [documents.md](documents.md) | Creating docs, typing in the editor, AI edit, comments, side panel |
+| [documents.md](documents.md) | Creating docs, typing in the editor, AI edit, comments, Word (DOCX) editor, side panel |
| [databases.md](databases.md) | Properties, records, kanban boards, saved views, AI questions, live answers |
| [ai-chat.md](ai-chat.md) | Standalone and doc-scoped AI chat |
| [../CLAUDE_CLOUD_DEMO.md](../CLAUDE_CLOUD_DEMO.md) | Claude in Harness settings, encrypted saved connection, Open in Claude, and cloud-side transcript polling |
diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.md
index bd50ebeb0a..6c507f2b75 100644
--- a/docs/AGENT_GUIDE/documents.md
+++ b/docs/AGENT_GUIDE/documents.md
@@ -712,6 +712,39 @@ highlight; deleting a placeable's discussion removes the placeable. An anchor bo
to a legacy annotation thread that was never imported stays hidden rather than
shown as a bare highlight.
+## Word (DOCX) editor
+
+When `enable-docx-editor` is on, uploaded `.docx` files open at
+`/app/write/<id>` in an editor instead of the PDF preview. The flag is a
+PostHog flag that is on by default in dev mode; set `VITE_ENABLE_DOCX_EDITOR`
+to override it locally. The header label has a **Beta** badge. The page is the
+Docxodus WASM engine. Edits sync through the sync service, so every open copy
+updates live and shows each collaborator's caret with their name.
+
+- Editors get a toolbar labelled `Document formatting` with the following
+ controls: `Undo`, `Redo`, a `Paragraph style` select, bold, italic,
+ underline and strikethrough, `Bulleted list`, `Numbered list`, the alignment
+ buttons, `Insert table` and `Track changes`.
+- Typing is committed after about a second of idle time, or on blur. Wait
+ roughly 1.5 s before checking another tab for the text.
+- Editors see editable `Header` and `Footer` bands. Viewers and commenters get
+ a read-only paginated rendering instead.
+- To comment on any text, including table cells: select it, then click the
+ floating `Comment` button beside the selection. You can also use the toolbar
+ `Comment on selection` button or Mod+Alt+M. The draft opens a thread card in
+ the right margin. Posting creates a normal document discussion (`markdown`
+ anchor with `mark_id`), so it also appears in channels and notifications.
+- Highlighted text is drawn with the CSS Custom Highlight API rather than DOM
+ marks: query `CSS.highlights`, not `<mark>` elements.
+- Threads whose text was deleted are listed under `Comments on text that has
+ changed`, above the `Discussion` composer.
+- AI `CommentOnDocument` works on DOCX by quote. The editor pins each quote to
+ the first matching text the next time someone opens the file.
+- `Download .docx` exports the current collaborative state with every edit.
+ Comments stay in Macro threads and are not written into the file.
+- The stored upload is not rewritten yet. Search, the PDF export and AI
+ `ReadContent` still see the original file.
+
## Document history
On desktop, open the title's file menu (**…**) and choose **History**. This
diff --git a/nix-support/node_modules-hashes.json b/nix-support/node_modules-hashes.json
index 2248668a1c..5f6337d4fa 100644
--- a/nix-support/node_modules-hashes.json
+++ b/nix-support/node_modules-hashes.json
@@ -1,6 +1,6 @@
{
"nodeModules": {
- "aarch64-darwin": "sha256-gL0PRN6Mex+H14FR+axzcj85ivDJ5+5my9MakhmMMGI=",
- "x86_64-linux": "sha256-q1A4pPjhAFzc2885Zjh3V4oe81a5pWU3J3c0EOPROZQ="
+ "aarch64-darwin": "sha256-uXdx2uoDP1VH6NVNLZ1LLB2AwgNAjJRGPi8J89cKa/s=",
+ "x86_64-linux": "sha256-ifhk7ye/msxcYFHHAYTiQPVrANLs8k4wltq5EMxjERE="
}
}
diff --git a/rules/ast-grep/ts-feature-components-presentational.yml b/rules/ast-grep/ts-feature-components-presentational.yml
index d1e1bc8bbc..6282689f06 100644
--- a/rules/ast-grep/ts-feature-components-presentational.yml
+++ b/rules/ast-grep/ts-feature-components-presentational.yml
@@ -31,6 +31,7 @@ files:
- apps/web/src/features/email-thread/components/**
- apps/web/src/features/email-compose/components/**
- apps/web/src/features/agent-changes/components/**
+ - apps/web/src/features/block-write/components/**
rule:
any:
- kind: string
diff --git a/rules/ast-grep/ts-feature-core-pure.yml b/rules/ast-grep/ts-feature-core-pure.yml
index 0801fef712..a9f053e4c2 100644
--- a/rules/ast-grep/ts-feature-core-pure.yml
+++ b/rules/ast-grep/ts-feature-core-pure.yml
@@ -32,6 +32,7 @@ files:
- apps/web/src/features/email-thread/core/**
- apps/web/src/features/email-compose/core/**
- apps/web/src/features/agent-changes/core/**
+ - apps/web/src/features/block-write/core/**
rule:
kind: string
regex: ^['"](solid-js|@urql|urql|@app/lib/urql|@queries/|@service-storage/|@core/|@property/|@components/|@ui|@entity/|(\.\./)+(queries|primitives|components|views|ui|component|context)(/|['"]))
diff --git a/rules/ast-grep/ts-feature-data-no-ui.yml b/rules/ast-grep/ts-feature-data-no-ui.yml
index 30372e2618..c5a1b5698c 100644
--- a/rules/ast-grep/ts-feature-data-no-ui.yml
+++ b/rules/ast-grep/ts-feature-data-no-ui.yml
@@ -48,6 +48,8 @@ files:
- apps/web/src/features/email-compose/primitives/**
- apps/web/src/features/agent-changes/queries/**
- apps/web/src/features/agent-changes/primitives/**
+ - apps/web/src/features/block-write/queries/**
+ - apps/web/src/features/block-write/primitives/**
rule:
kind: string
regex: ^['"](solid-js/web|@ui|@components/|(\.\./)+(components|views|ui|component)(/|['"]))
diff --git a/rules/ast-grep/ts-feature-layers-use-context.yml b/rules/ast-grep/ts-feature-layers-use-context.yml
index 7fc66f7fe9..6591bf18c8 100644
--- a/rules/ast-grep/ts-feature-layers-use-context.yml
+++ b/rules/ast-grep/ts-feature-layers-use-context.yml
@@ -88,6 +88,11 @@ files:
- apps/web/src/features/agent-changes/queries/**
- apps/web/src/features/agent-changes/primitives/**
- apps/web/src/features/agent-changes/views/**
+ - apps/web/src/features/block-write/queries/**
+ - apps/web/src/features/block-write/primitives/**
+ - apps/web/src/features/block-write/components/**
+ - apps/web/src/features/block-write/views/**
+ - apps/web/src/features/block-write/context/**
rule:
kind: string
regex: ^['"](@service-storage/graphql-soup|@core/context/user|@core/user|@property/hooks|@property/editor/hooks|@core/component/LexicalMarkdown/component/core/BlockLink|@app/lib/analytics/posthog)
diff --git a/rules/ast-grep/tsx-feature-components-presentational.yml b/rules/ast-grep/tsx-feature-components-presentational.yml
index aab71e8c25..c1de968ebe 100644
--- a/rules/ast-grep/tsx-feature-components-presentational.yml
+++ b/rules/ast-grep/tsx-feature-components-presentational.yml
@@ -31,6 +31,7 @@ files:
- apps/web/src/features/email-thread/components/**
- apps/web/src/features/email-compose/components/**
- apps/web/src/features/agent-changes/components/**
+ - apps/web/src/features/block-write/components/**
rule:
any:
- kind: string
diff --git a/rules/ast-grep/tsx-feature-core-pure.yml b/rules/ast-grep/tsx-feature-core-pure.yml
index 94a306bae2..88de22ae64 100644
--- a/rules/ast-grep/tsx-feature-core-pure.yml
+++ b/rules/ast-grep/tsx-feature-core-pure.yml
@@ -32,6 +32,7 @@ files:
- apps/web/src/features/email-thread/core/**
- apps/web/src/features/email-compose/core/**
- apps/web/src/features/agent-changes/core/**
+ - apps/web/src/features/block-write/core/**
rule:
kind: string
regex: ^['"](solid-js|@urql|urql|@app/lib/urql|@queries/|@service-storage/|@core/|@property/|@components/|@ui|@entity/|(\.\./)+(queries|primitives|components|views|ui|component|context)(/|['"]))
diff --git a/rules/ast-grep/tsx-feature-data-no-ui.yml b/rules/ast-grep/tsx-feature-data-no-ui.yml
index 3f84daad8a..24b14e4725 100644
--- a/rules/ast-grep/tsx-feature-data-no-ui.yml
+++ b/rules/ast-grep/tsx-feature-data-no-ui.yml
@@ -48,6 +48,8 @@ files:
- apps/web/src/features/email-compose/primitives/**
- apps/web/src/features/agent-changes/queries/**
- apps/web/src/features/agent-changes/primitives/**
+ - apps/web/src/features/block-write/queries/**
+ - apps/web/src/features/block-write/primitives/**
rule:
kind: string
regex: ^['"](solid-js/web|@ui|@components/|(\.\./)+(components|views|ui|component)(/|['"]))
diff --git a/rules/ast-grep/tsx-feature-layers-use-context.yml b/rules/ast-grep/tsx-feature-layers-use-context.yml
index c7b2f1eb39..2fb2c41c6b 100644
--- a/rules/ast-grep/tsx-feature-layers-use-context.yml
+++ b/rules/ast-grep/tsx-feature-layers-use-context.yml
@@ -88,6 +88,11 @@ files:
- apps/web/src/features/agent-changes/queries/**
- apps/web/src/features/agent-changes/primitives/**
- apps/web/src/features/agent-changes/views/**
+ - apps/web/src/features/block-write/queries/**
+ - apps/web/src/features/block-write/primitives/**
+ - apps/web/src/features/block-write/components/**
+ - apps/web/src/features/block-write/views/**
+ - apps/web/src/features/block-write/context/**
rule:
kind: string
regex: ^['"](@service-storage/graphql-soup|@core/context/user|@core/user|@property/hooks|@property/editor/hooks|@core/component/LexicalMarkdown/component/core/BlockLink|@app/lib/analytics/posthog)