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.

fix(comments): stage inline anchors before publishing messages (#9479)

gbirman70831cf4d554
diff --git a/.github/workflows/deploy_on_push.yml b/.github/workflows/deploy_on_push.yml
index f19d4f5b5e..596ef07785 100644
--- a/.github/workflows/deploy_on_push.yml
+++ b/.github/workflows/deploy_on_push.yml
@@ -58,6 +58,7 @@ jobs:
deploy-web-app:
needs:
- deploy-cloud-storage
+ - deploy-sync-service
- build-web-app
name: Deploy Web App
uses: ./.github/workflows/deploy_web_app.yml
diff --git a/.github/workflows/deploy_sync_service.yml b/.github/workflows/deploy_sync_service.yml
index c4c3ba9d65..c4b5d1f7f2 100644
--- a/.github/workflows/deploy_sync_service.yml
+++ b/.github/workflows/deploy_sync_service.yml
@@ -54,6 +54,12 @@ jobs:
- name: Install dependencies
run: npm ci
working-directory: services/sync-service
+ - name: Check required secrets
+ run: node scripts/check-deploy-secrets.mjs ${{ inputs.environment || 'dev' }}
+ env:
+ CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
+ CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
+ working-directory: services/sync-service
- name: Apply D1 migrations
run: npx wrangler d1 migrations apply USER_PEER_MAPPING --env ${{ inputs.environment || 'dev' }} --remote
env:
@@ -67,5 +73,7 @@ jobs:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
working-directory: services/sync-service
+ - name: Wait for active Durable Objects to update
+ run: sleep 300
concurrency:
group: deploy-sync-service-${{ inputs.environment || 'dev' }}
diff --git a/.github/workflows/release-production.yml b/.github/workflows/release-production.yml
index 6a61605ac7..4344fe5b12 100644
--- a/.github/workflows/release-production.yml
+++ b/.github/workflows/release-production.yml
@@ -117,7 +117,8 @@ jobs:
deploy:
name: Deploy Web App
runs-on: namespace-profile-linux-mid;overrides.cache-tag=web-ci
- needs: [build, deploy-cloud-storage]
+ # New clients require the worker's sync protocol support before publication.
+ needs: [build, deploy-cloud-storage, deploy-sync-service]
env:
CI: "true"
steps:
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 89ec868d70..5ea905780f 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -1058,6 +1058,28 @@ and bot personas share one renderer; keep surface sizing in the caller.
- Advertise Mail v5 capsules only for the current browser engine or a verified supported installed native build; OTA bundle version alone cannot establish native capability.
- Bound native Mail capability discovery to 1.5 seconds and cache the legacy profile on failure or timeout so stalled IPC cannot block GraphQL transport; record the selected profile and bounded outcome in HTTP and WebSocket setup spans without error text.
+### Inline comment drafts
+
+Use `MessageLoadError` for compact discussion/thread failures; missing resources
+show an unavailable state without a retry action or composer.
+
+Keep collaborative drafts as cursor-based overlays outside the shared editor tree.
+Flush pending text, catch up missing server history before publication, then
+publish the mark from an isolated peer with `PeerCommentUpdate`,
+and post the message only after acknowledgement. Refused operations never enter
+the editor's WAL. Preserve input on failure. Cancelled publications retry mark
+cleanup from the user/document-scoped IndexedDB queue; preserve marks when a
+message request's outcome is uncertain. Keep failed cleanup entries queued without
+blocking later entries. Overlapping comments must retain each
+saved range through cancel, save, and collaboration updates.
+Comment controls preserve editor focus on both pointerdown and mousedown.
+The backend-free browser regression is
+`bunx playwright test --config src/features/block-md/comments/browser-test/playwright.config.ts`.
+It exercises selection, press, cancel, retry, and repeated posting in editor and
+commenter modes. The collaboration fixture includes concurrent remote edits and
+rejected updates; provider tests cover message metadata arriving on either side
+of posting, multi-paragraph anchors, saved ranges, and cancellation during posting.
+
## Performance
### Tracing
diff --git a/apps/web/src/features/block-md/comments/LocalCommentDraft.tsx b/apps/web/src/features/block-md/comments/LocalCommentDraft.tsx
new file mode 100644
index 0000000000..b5f3c442bc
--- /dev/null
+++ b/apps/web/src/features/block-md/comments/LocalCommentDraft.tsx
@@ -0,0 +1,339 @@
+import {
+ $convertLexicalSelectionToCursors,
+ $cursorToLexicalPoint,
+} from '@core/component/LexicalMarkdown/collaboration/cursor';
+import { flushCollaboration } from '@core/component/LexicalMarkdown/collaboration/flush';
+import type { LexicalSelectionAwareness } from '@core/component/LexicalMarkdown/collaboration/LexicalAwareness';
+import { LocationHighlight } from '@core/component/LexicalMarkdown/component/core/Highlights';
+import type { EphemeralLocation } from '@core/component/LexicalMarkdown/plugins/location/locationPlugin';
+import { fireAndForget } from '@core/util/fireAndForget';
+import type { LoroManager } from '@macro-inc/collaboration/collab/manager';
+import type { LiveSyncSource } from '@macro-inc/collaboration/collab/source';
+import { BrowserWALStore } from '@macro-inc/collaboration/collab/wal';
+import {
+ $getCommentMarkText,
+ type NodeIdMappings,
+} from '@macro-inc/lexical-core';
+import { Telemetry } from '@macro-inc/observability';
+import {
+ $createRangeSelection,
+ $isElementNode,
+ $isTextNode,
+ type LexicalEditor,
+ type RangeSelection,
+} from 'lexical';
+import {
+ createEffect,
+ createMemo,
+ createSignal,
+ onCleanup,
+ Show,
+} from 'solid-js';
+import { createCommentMarkCleanup } from './commentMarkCleanup';
+import {
+ publishCommentMark,
+ removePublishedCommentMark,
+} from './publishCommentMark';
+
+export type DraftPublication = {
+ text: () => string | undefined;
+ publish: () => Promise<boolean>;
+ post: <T>(send: () => Promise<T | null>) => Promise<T | null>;
+};
+
+type LocalDraft = {
+ id: string;
+ cursors: LexicalSelectionAwareness;
+ pending?: Promise<boolean>;
+ source?: LiveSyncSource;
+ cleanup?: Promise<void>;
+ cleanupQueue?: ReturnType<typeof createCommentMarkCleanup>;
+ posting: boolean;
+ postUncertain: boolean;
+ committed: boolean;
+};
+
+/** A draft is a pair of CRDT cursors, never split text nodes in the shared tree. */
+export function createLocalCommentDraft(options: {
+ editor: LexicalEditor;
+ manager: LoroManager;
+ mapping: NodeIdMappings;
+ source: () => LiveSyncSource | undefined;
+ interactable: () => boolean;
+ userId: () => string | undefined;
+ hasPostedComment: (markId: string) => Promise<boolean>;
+ add: (id: string, anchor: HTMLElement, publication: DraftPublication) => void;
+ remove: (id: string) => void;
+}) {
+ const { editor, manager, mapping } = options;
+ const [draft, setDraft] = createSignal<LocalDraft>();
+ const [location, setLocation] = createSignal<EphemeralLocation>();
+ const [mount, setMount] = createSignal<HTMLElement>();
+ const anchorElement = document.createElement('span');
+ anchorElement.dataset.commentDraftAnchor = '';
+ anchorElement.style.cssText = 'position:absolute;pointer-events:none';
+ let disposed = false;
+ let publishingCount = 0;
+ const lockEditor = async (operation: () => Promise<boolean>) => {
+ publishingCount += 1;
+ editor.setEditable(false);
+ try {
+ return await operation();
+ } finally {
+ publishingCount -= 1;
+ if (!disposed && publishingCount === 0)
+ editor.setEditable(options.interactable());
+ }
+ };
+ const cleanupQueue = createMemo(() => {
+ const userId = options.userId();
+ if (!userId) return;
+ return createCommentMarkCleanup(
+ new BrowserWALStore<string>(
+ 'macro-comment-mark-cleanup',
+ JSON.stringify([userId, manager.documentId])
+ ),
+ async (markId) => {
+ const active = () => !disposed && options.userId() === userId;
+ const source = options.source();
+ if (!active() || !source) return false;
+ // A persisted message always owns its mark, even after a lost response.
+ if (await options.hasPostedComment(markId)) return true;
+ return lockEditor(async () => {
+ if (!active() || !(await flushCollaboration(editor))) return false;
+ if (!active()) return false;
+ return removePublishedCommentMark({
+ manager,
+ source,
+ markId,
+ active,
+ });
+ });
+ }
+ );
+ });
+ createEffect(() => {
+ const queue = cleanupQueue();
+ const source = options.source();
+ if (!queue || !source) return;
+ const replay = () => fireAndForget(queue.flush(), 'comment-draft-cleanup');
+ let initialized = false;
+ onCleanup(
+ editor.registerUpdateListener(() => {
+ if (initialized || !manager.initialized) return;
+ initialized = true;
+ replay();
+ })
+ );
+ onCleanup(
+ source.listen((event) => {
+ if (event.type === 'connect' || event.type === 'reconnect') replay();
+ })
+ );
+ window.addEventListener('online', replay);
+ onCleanup(() => window.removeEventListener('online', replay));
+ replay();
+ });
+ const cleanupPublished = (record: LocalDraft) => {
+ if (
+ !record.source ||
+ record.committed ||
+ record.posting ||
+ record.postUncertain
+ )
+ return Promise.resolve();
+ record.cleanup ??= record.cleanupQueue?.enqueue(record.id);
+ return record.cleanup ?? Promise.resolve();
+ };
+
+ const $selection = () => {
+ const current = draft();
+ if (!current) return null;
+ const anchor = $cursorToLexicalPoint(
+ current.cursors.anchor,
+ manager,
+ editor,
+ mapping
+ );
+ const focus = $cursorToLexicalPoint(
+ current.cursors.focus,
+ manager,
+ editor,
+ mapping
+ );
+ if (!anchor || !focus) return null;
+ for (const point of [anchor, focus]) {
+ const node = point.getNode();
+ const size = $isTextNode(node)
+ ? node.getTextContentSize()
+ : $isElementNode(node)
+ ? node.getChildrenSize()
+ : 0;
+ if (point.offset > size) return null;
+ }
+ const selection = $createRangeSelection();
+ selection.anchor.set(anchor.key, anchor.offset, anchor.type);
+ selection.focus.set(focus.key, focus.offset, focus.type);
+ return selection;
+ };
+ const refresh = () =>
+ editor.getEditorState().read(() => {
+ const selection = $selection();
+ if (!selection || selection.isCollapsed()) {
+ setLocation();
+ return;
+ }
+ setLocation({
+ type: 'ephemeral',
+ anchor: { key: selection.anchor.key, offset: selection.anchor.offset },
+ focus: { key: selection.focus.key, offset: selection.focus.offset },
+ });
+ });
+ const text = () =>
+ editor.read(() => {
+ const current = draft();
+ if (!current) return undefined;
+ return $getCommentMarkText(current.id) || $selection()?.getTextContent();
+ });
+ const clear = (committed: boolean) => {
+ const current = draft();
+ if (current && committed) current.committed = true;
+ setDraft();
+ setLocation();
+ anchorElement.remove();
+ if (current) {
+ options.remove(current.id);
+ if (!current.pending && !committed)
+ fireAndForget(cleanupPublished(current), 'comment-draft-cleanup');
+ }
+ };
+ const discard = () => clear(false);
+ onCleanup(
+ editor.registerRootListener((root) => {
+ setMount(root?.parentElement ?? undefined);
+ })
+ );
+ onCleanup(editor.registerUpdateListener(refresh));
+ onCleanup(
+ editor.registerEditableListener((editable) => {
+ if (editable && publishingCount > 0) editor.setEditable(false);
+ })
+ );
+ onCleanup(() => {
+ disposed = true;
+ discard();
+ });
+ return {
+ current: () => draft()?.id,
+ create: (id: string, selection: RangeSelection) => {
+ const userId = options.userId();
+ if (!userId || !manager.initialized || !mount()) return false;
+ const cursors = $convertLexicalSelectionToCursors(
+ manager,
+ mapping,
+ selection
+ );
+ if (!cursors) return false;
+ const record: LocalDraft = {
+ id,
+ cursors,
+ posting: false,
+ postUncertain: false,
+ committed: false,
+ cleanupQueue: cleanupQueue(),
+ };
+ setDraft(record);
+ const active = () =>
+ !disposed && draft() === record && options.userId() === userId;
+ mount()!.append(anchorElement);
+ options.add(id, anchorElement, {
+ text,
+ publish: () => {
+ if (!active()) return Promise.resolve(false);
+ if (record.pending) return record.pending;
+ const source = options.source();
+ const selectedText = text();
+ if (!source || !selectedText || draft()?.id !== id)
+ return Promise.resolve(false);
+ record.source = source;
+ const publish = async () => {
+ try {
+ const accepted = await lockEditor(async () => {
+ if (!(await flushCollaboration(editor)) || !active())
+ return false;
+ return publishCommentMark({
+ manager,
+ source,
+ markId: id,
+ cursors,
+ text: selectedText,
+ active,
+ });
+ });
+ if (!active()) {
+ await cleanupPublished(record);
+ return false;
+ }
+ return accepted;
+ } finally {
+ record.pending = undefined;
+ }
+ };
+ record.pending = publish();
+ return record.pending;
+ },
+ post: async (send) => {
+ if (!active()) return null;
+ record.posting = true;
+ let settled = false;
+ try {
+ const result = await send();
+ settled = true;
+ if (result) record.committed = true;
+ return result;
+ } finally {
+ record.posting = false;
+ if (!settled) record.postUncertain = true;
+ if (record.postUncertain)
+ Telemetry.warn('comment.message.outcome_unknown', {
+ 'document.id': manager.documentId,
+ 'comment.mark_id': record.id,
+ });
+ if (disposed || draft() !== record) await cleanupPublished(record);
+ }
+ },
+ });
+ // The create command has not committed its selection yet.
+ setLocation({
+ type: 'ephemeral',
+ anchor: { key: selection.anchor.key, offset: selection.anchor.offset },
+ focus: { key: selection.focus.key, offset: selection.focus.offset },
+ });
+ return true;
+ },
+ discard,
+ commit: () => clear(true),
+ Highlight: () => (
+ <Show when={mount()}>
+ {(element) => (
+ <LocationHighlight
+ editor={editor}
+ location={location()}
+ mountRef={element()}
+ class="bg-comment-bg"
+ captureBoundingDomRect={(rect) => {
+ if (!location()) return;
+ const parent = element().getBoundingClientRect();
+ Object.assign(anchorElement.style, {
+ left: `${rect.left - parent.left}px`,
+ top: `${rect.top - parent.top}px`,
+ width: `${rect.width}px`,
+ height: `${rect.height}px`,
+ });
+ }}
+ />
+ )}
+ </Show>
+ ),
+ };
+}
diff --git a/apps/web/src/features/block-md/comments/MessageCommentsProvider.test.tsx b/apps/web/src/features/block-md/comments/MessageCommentsProvider.test.tsx
index e33f6e25c2..6f84f08938 100644
--- a/apps/web/src/features/block-md/comments/MessageCommentsProvider.test.tsx
+++ b/apps/web/src/features/block-md/comments/MessageCommentsProvider.test.tsx
@@ -1,16 +1,34 @@
+import 'fake-indexeddb/auto';
+import {
+ DRAFT_THREAD_ID,
+ type MessageCommentOperations,
+} from '@core/comments/commentType';
+import { FLUSH_COLLABORATION_COMMAND } from '@core/component/LexicalMarkdown/collaboration/flush';
import {
LexicalWrapperContext,
type LexicalWrapperWithMapping,
} from '@core/component/LexicalMarkdown/context/LexicalWrapperContext';
import type { PluginManager } from '@core/component/LexicalMarkdown/plugins';
-import type { LoroManager } from '@macro-inc/collaboration/collab/manager';
-import { $createCommentNode, CommentNode } from '@macro-inc/lexical-core';
+import { CREATE_DRAFT_COMMENT_COMMAND } from '@core/component/LexicalMarkdown/plugins/comments/commentPlugin';
+import { LoroManager } from '@macro-inc/collaboration/collab/manager';
+import { createNoopLiveSyncSource } from '@macro-inc/collaboration/collab/source';
+import {
+ $createCommentNode,
+ $updateAllNodeIds,
+ CommentNode,
+ peerIdPlugin,
+} from '@macro-inc/lexical-core';
+import { MARKDOWN_LORO_SCHEMA } from '@macro-inc/lexical-core/markdown-loro-schema';
+import { markdownToLoroSnapshot } from '@macro-inc/lexical-core/markdown-loro-snapshot';
import type { MessageListItem } from '@service-storage/messages';
import { cleanup, render } from '@solidjs/testing-library';
import {
$createParagraphNode,
+ $createRangeSelection,
$createTextNode,
$getRoot,
+ $setSelection,
+ COMMAND_PRIORITY_NORMAL,
createEditor,
type LexicalEditor,
} from 'lexical';
@@ -18,6 +36,7 @@ import { batch, createSignal, onCleanup, onMount } from 'solid-js';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createMarkdownDocumentState } from '../context/markdown-document-state';
import { MessageCommentsProvider } from './MessageCommentsProvider';
+import { useCreateMessageComment } from './messageCommentOperations';
const mocks = vi.hoisted(() => ({
state: undefined as
@@ -26,11 +45,37 @@ const mocks = vi.hoisted(() => ({
threads: (): MessageListItem[] => [],
rootId: (): string | null => 'root',
navigationCount: (): number => 0,
+ post: vi.fn(),
+ publish: vi.fn().mockResolvedValue(true),
+ removePublished: vi.fn().mockResolvedValue(true),
+}));
+
+vi.mock('./publishCommentMark', () => ({
+ publishCommentMark: (...args: unknown[]) => mocks.publish(...args),
+ removePublishedCommentMark: (...args: unknown[]) =>
+ mocks.removePublished(...args),
+}));
+vi.mock('@core/component/LexicalMarkdown/component/core/Highlights', () => ({
+ LocationHighlight: () => null,
}));
+vi.mock('@app/lib/analytics/analytics-context', () => ({
+ useAnalytics: () => ({ track: vi.fn() }),
+}));
+vi.mock('@queries/messages/posted-comment', () => ({
+ hasPostedComment: async () => false,
+}));
+vi.mock('./messageCommentsResource', () => ({
+ useCreateMarkedMessageResource: () => mocks.post,
+ useCreateMessageReplyResource: () => mocks.post,
+}));
vi.mock('../context/markdown-document-context', () => ({
useMarkdownDocument: () => ({
documentId: () => 'document',
+ documentSource: () => ({
+ type: 'sync',
+ source: createNoopLiveSyncSource('document'),
+ }),
state: mocks.state,
permissions: { canEdit: () => false, canComment: () => true },
}),
@@ -63,9 +108,6 @@ vi.mock('@queries/messages/mutations', () => ({
vi.mock('@queries/messages/sync', () => ({
onThreadStateUpdated: () => () => {},
}));
-vi.mock('./commentOperations', () => ({
- useDeleteNewComments: () => () => {},
-}));
const thread: MessageListItem = {
id: 'root',
@@ -92,9 +134,15 @@ afterEach(() => {
cleanup();
vi.restoreAllMocks();
vi.unstubAllGlobals();
+ mocks.publish.mockReset().mockResolvedValue(true);
+ mocks.removePublished.mockReset().mockResolvedValue(true);
+ mocks.post.mockReset();
});
-function setup() {
+function setup(lateEditor = false) {
+ const manager: LoroManager = new LoroManager(MARKDOWN_LORO_SCHEMA, {
+ documentId: 'document',
+ });
const state = createMarkdownDocumentState();
mocks.state = state;
const [threads, setThreads] = createSignal<MessageListItem[]>([]);
@@ -128,22 +176,57 @@ function setup() {
onCleanup(plugin(editor)),
} as unknown as PluginManager,
};
+ if (!lateEditor) state.editor.setMd('editor', editor);
+ let post!: MessageCommentOperations['createComment'];
+ function Posting() {
+ post = useCreateMessageComment();
+ return null;
+ }
render(() => (
<LexicalWrapperContext.Provider value={wrapper}>
<div
ref={(el) => {
+ onCleanup(
+ peerIdPlugin({ peerId: () => '1', nodes: [CommentNode] })(editor)
+ );
+ onCleanup(
+ editor.registerCommand(
+ FLUSH_COLLABORATION_COMMAND,
+ (done) => {
+ done(true);
+ return true;
+ },
+ COMMAND_PRIORITY_NORMAL
+ )
+ );
onMount(() => editor.setRootElement(el));
onCleanup(() => editor.setRootElement(null));
}}
/>
+ <Posting />
<MessageCommentsProvider
activeComment={activeComment}
- loroManager={{ peerIdStr: '1' } as unknown as LoroManager}
+ loroManager={manager}
/>
</LexicalWrapperContext.Provider>
));
+ if (lateEditor) state.editor.setMd('editor', editor);
return {
+ editor,
state,
+ post: (input: Parameters<typeof post>[0]) => post(input),
+ synchronize: async () => {
+ editor.update(() => $updateAllNodeIds(wrapper.mapping), {
+ discrete: true,
+ });
+ if (!manager.initialized) {
+ const snapshot = await markdownToLoroSnapshot('Initial text');
+ if (!snapshot) throw new Error('Missing snapshot');
+ await manager.initializeFromSnapshot(snapshot);
+ }
+ await manager.syncToLoro({ ...editor.getEditorState().toJSON() });
+ },
+ setThreads,
scroll,
loadComments: () =>
batch(() => {
@@ -175,6 +258,287 @@ function setup() {
}
describe('inline comment link navigation', () => {
+ it('keeps the draft and posts no message when its anchor is not acknowledged', async () => {
+ const f = setup();
+ f.editor.update(
+ () => {
+ const text = $createTextNode('Selected passage');
+ $getRoot().append($createParagraphNode().append(text));
+ text.select(0, 8);
+ },
+ { discrete: true }
+ );
+ await f.synchronize();
+ f.editor.update(
+ () => {
+ f.editor.dispatchCommand(CREATE_DRAFT_COMMENT_COMMAND, undefined);
+ },
+ { discrete: true }
+ );
+ const anchorId = f.state.comments.threads[DRAFT_THREAD_ID]!.anchorId;
+ mocks.publish.mockResolvedValueOnce(false);
+ expect(
+ await f.post({ threadId: DRAFT_THREAD_ID, content: 'Keep this comment' })
+ ).toBeNull();
+ expect(mocks.post).not.toHaveBeenCalled();
+ expect(f.state.comments.threads[DRAFT_THREAD_ID]?.anchorId).toBe(anchorId);
+ });
+
+ it('does not post or clear a newer draft when an abandoned publication finishes', async () => {
+ const f = setup();
+ f.editor.update(
+ () => {
+ const text = $createTextNode('First and second');
+ $getRoot().append($createParagraphNode().append(text));
+ text.select(0, 5);
+ },
+ { discrete: true }
+ );
+ await f.synchronize();
+ f.editor.update(
+ () => {
+ f.editor.dispatchCommand(CREATE_DRAFT_COMMENT_COMMAND, undefined);
+ },
+ { discrete: true }
+ );
+ const firstId = f.state.comments.threads[DRAFT_THREAD_ID]!.anchorId;
+ let finish!: (accepted: boolean) => void;
+ let started!: () => void;
+ const publicationStarted = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ const publication = new Promise<boolean>((resolve) => {
+ finish = resolve;
+ });
+ mocks.publish.mockImplementationOnce(() => {
+ started();
+ return publication;
+ });
+ const firstPost = f.post({
+ threadId: DRAFT_THREAD_ID,
+ content: 'First comment',
+ });
+ await publicationStarted;
+ f.state.setCommentState('activeCommentThread', null);
+ f.editor.update(
+ () => {
+ $getRoot().getAllTextNodes()[0].select(10, 16);
+ f.editor.dispatchCommand(CREATE_DRAFT_COMMENT_COMMAND, undefined);
+ },
+ { discrete: true }
+ );
+ const secondId = f.state.comments.threads[DRAFT_THREAD_ID]!.anchorId;
+ expect(secondId).not.toBe(firstId);
+ finish(true);
+ expect(await firstPost).toBeNull();
+ expect(mocks.post).not.toHaveBeenCalled();
+ expect(mocks.removePublished).toHaveBeenCalledWith(
+ expect.objectContaining({ markId: firstId })
+ );
+ expect(f.state.comments.threads[DRAFT_THREAD_ID]?.anchorId).toBe(secondId);
+ });
+
+ it.each([false, true])(
+ 'handles cancellation after message failure, outcome uncertain: %s',
+ async (uncertain) => {
+ const f = setup();
+ f.editor.update(
+ () => {
+ const text = $createTextNode('Selected passage');
+ $getRoot().append($createParagraphNode().append(text));
+ text.select(0, 8);
+ },
+ { discrete: true }
+ );
+ await f.synchronize();
+ f.editor.update(
+ () => {
+ f.editor.dispatchCommand(CREATE_DRAFT_COMMENT_COMMAND, undefined);
+ },
+ { discrete: true }
+ );
+ const anchorId = f.state.comments.threads[DRAFT_THREAD_ID]!.anchorId;
+ if (uncertain)
+ mocks.post.mockRejectedValueOnce(new Error('response lost'));
+ else mocks.post.mockResolvedValueOnce(null);
+ const post = f.post({
+ threadId: DRAFT_THREAD_ID,
+ content: 'Unsent message',
+ });
+ if (uncertain) {
+ await expect(post).rejects.toThrow('response lost');
+ f.state.setCommentState('activeCommentThread', null);
+ expect(mocks.removePublished).not.toHaveBeenCalled();
+ return;
+ }
+ expect(await post).toBeNull();
+ let finishRemoval!: () => void;
+ const removed = new Promise<void>((resolve) => {
+ finishRemoval = resolve;
+ });
+ mocks.removePublished.mockImplementationOnce(async () => {
+ finishRemoval();
+ return true;
+ });
+ f.state.setCommentState('activeCommentThread', null);
+ await removed;
+ expect(mocks.removePublished).toHaveBeenCalledWith(
+ expect.objectContaining({ markId: anchorId })
+ );
+ }
+ );
+
+ it.each([false, true])(
+ 'opens another comment after posting, metadata first: %s',
+ async (metadataFirst) => {
+ const f = setup(true);
+ f.finishLoading();
+ f.editor.update(
+ () => {
+ $getRoot().append(
+ $createParagraphNode().append(
+ $createTextNode('A shared directory with useful notes.')
+ )
+ );
+ },
+ { discrete: true }
+ );
+ for (let attempt = 0; attempt < 3; attempt++) {
+ await f.synchronize();
+ f.editor.update(
+ () => {
+ const text = $getRoot()
+ .getAllTextNodes()
+ .find((node) => node.getTextContent().includes('shared'))!;
+ const start = text.getTextContent().indexOf('shared');
+ text.select(start, start + 6);
+ expect(
+ f.editor.dispatchCommand(CREATE_DRAFT_COMMENT_COMMAND, undefined)
+ ).toBe(true);
+ },
+ { discrete: true }
+ );
+ expect(f.state.comments.activeCommentThread).toBe(DRAFT_THREAD_ID);
+ const anchorId = f.state.comments.threads[DRAFT_THREAD_ID]!.anchorId;
+ const posted = {
+ ...thread,
+ id: `root-${attempt}`,
+ state: {
+ ...thread.state,
+ root_id: `root-${attempt}`,
+ anchor: { type: 'markdown' as const, mark_id: anchorId },
+ },
+ };
+ mocks.post.mockImplementationOnce(async () => {
+ if (metadataFirst) f.setThreads((previous) => [...previous, posted]);
+ return posted;
+ });
+ await f.post({ threadId: DRAFT_THREAD_ID, content: 'A comment' });
+ if (!metadataFirst) f.setThreads((previous) => [...previous, posted]);
+ await Promise.resolve();
+ expect(f.editor.getRootElement()?.textContent).toBe(
+ 'A shared directory with useful notes.'
+ );
+ expect(
+ f.editor.getRootElement()?.querySelectorAll('mark.draft')
+ ).toHaveLength(0);
+ f.state.setCommentState('activeCommentThread', null);
+ }
+ }
+ );
+ it('opens a new draft inside an existing comment and preserves that comment on cancellation', async () => {
+ const f = setup();
+ f.loadMarks();
+ f.loadComments();
+ f.finishLoading();
+ await f.synchronize();
+ f.editor.update(
+ () => {
+ const text = $getRoot().getAllTextNodes()[0];
+ text.select(2, 7);
+ expect(
+ f.editor.dispatchCommand(CREATE_DRAFT_COMMENT_COMMAND, undefined)
+ ).toBe(true);
+ },
+ { discrete: true }
+ );
+ expect(f.state.comments.activeCommentThread).toBe(DRAFT_THREAD_ID);
+ expect(f.state.comments.threads[DRAFT_THREAD_ID]?.isNew).toBe(true);
+ f.state.setCommentState('activeCommentThread', null);
+ await Promise.resolve();
+ expect(f.state.comments.threads.root?.anchorId).toBe('mark');
+ expect(f.editor.getRootElement()?.textContent).toBe('Commented text');
+ });
+ it('keeps a draft spanning paragraphs outside the document tree', async () => {
+ const f = setup();
+ f.editor.update(
+ () => {
+ const first = $createTextNode('First paragraph');
+ const last = $createTextNode('Last paragraph');
+ $getRoot().append(
+ $createParagraphNode().append(first),
+ $createParagraphNode().append(last)
+ );
+ const selection = $createRangeSelection();
+ selection.anchor.set(first.getKey(), 0, 'text');
+ selection.focus.set(last.getKey(), 4, 'text');
+ $setSelection(selection);
+ },
+ { discrete: true }
+ );
+ await f.synchronize();
+ f.editor.update(
+ () => {
+ f.editor.dispatchCommand(CREATE_DRAFT_COMMENT_COMMAND, undefined);
+ },
+ { discrete: true }
+ );
+ const draft = f.state.comments.threads[DRAFT_THREAD_ID];
+ expect(draft?.isNew).toBe(true);
+ expect(
+ Object.values(f.state.comments.marks[draft!.anchorId]!.markNodes).filter(
+ Boolean
+ )
+ ).toHaveLength(1);
+ expect(f.state.comments.marks[draft!.anchorId]!.publication?.text()).toBe(
+ 'First paragraph\nLast'
+ );
+ expect(f.editor.getRootElement()?.querySelectorAll('mark')).toHaveLength(0);
+ });
+
+ it.each([false, true])(
+ 'opens and cancels a draft (editor published after mounting: %s)',
+ async (lateEditor) => {
+ const f = setup(lateEditor);
+ f.editor.update(
+ () => {
+ const text = $createTextNode('Text to comment on');
+ $getRoot().append($createParagraphNode().append(text));
+ text.select(0, 4);
+ },
+ { discrete: true }
+ );
+ await f.synchronize();
+ f.editor.update(
+ () => {
+ expect(
+ f.editor.dispatchCommand(CREATE_DRAFT_COMMENT_COMMAND, undefined)
+ ).toBe(true);
+ },
+ { discrete: true }
+ );
+ expect(f.state.comments.activeCommentThread).toBe(DRAFT_THREAD_ID);
+ expect(f.state.comments.threads[DRAFT_THREAD_ID]?.isNew).toBe(true);
+ expect(f.editor.getRootElement()?.querySelectorAll('mark')).toHaveLength(
+ 0
+ );
+ f.state.setCommentState('activeCommentThread', null);
+ await Promise.resolve();
+ expect(f.editor.getRootElement()?.querySelectorAll('mark')).toHaveLength(
+ 0
+ );
+ }
+ );
it('waits for editor initialization even when comments and marks arrive first', () => {
const f = setup();
f.loadComments();
diff --git a/apps/web/src/features/block-md/comments/MessageCommentsProvider.tsx b/apps/web/src/features/block-md/comments/MessageCommentsProvider.tsx
index f97932ce83..4c3d95c198 100644
--- a/apps/web/src/features/block-md/comments/MessageCommentsProvider.tsx
+++ b/apps/web/src/features/block-md/comments/MessageCommentsProvider.tsx
@@ -23,11 +23,13 @@ import { useUserId } from '@core/context/user';
import { onElementConnect } from '@core/util/onElementConnect';
import type { LoroManager } from '@macro-inc/collaboration/collab/manager';
import type { CommentNode } from '@macro-inc/lexical-core';
+import { Telemetry } from '@macro-inc/observability';
import {
useMessageLink,
useMessageRootsQuery,
} from '@queries/messages/document-messages';
import { usePatchThreadMutation } from '@queries/messages/mutations';
+import { hasPostedComment } from '@queries/messages/posted-comment';
import { onThreadStateUpdated } from '@queries/messages/sync';
import type { MessageThread } from '@service-storage/messages';
import {
@@ -50,6 +52,7 @@ import { createStore, reconcile } from 'solid-js/store';
import { useMarkdownDocument } from '../context/markdown-document-context';
import { useDeleteNewComments } from './commentOperations';
import type { Mark, ThreadStore } from './commentType';
+import { createLocalCommentDraft } from './LocalCommentDraft';
function getHighlightThread(
highlight: Mark
@@ -95,6 +98,7 @@ export const MessageCommentsProvider: VoidComponent<{
documentId: getDocumentId,
permissions,
state,
+ documentSource,
} = useMarkdownDocument();
const { comments: commentState, setCommentState } = state;
const documentId = getDocumentId();
@@ -264,7 +268,7 @@ export const MessageCommentsProvider: VoidComponent<{
setMountedMarks(markId, markNodeKey, markElement);
const existing = marks[markId];
- if (existing && (!isDraft || existing.existsOnServer)) {
+ if (existing) {
if (existing.existsOnServer) markElement.classList.remove('draft');
setMarks(markId, 'markNodes', markNodeKey, markElement);
return;
@@ -274,6 +278,13 @@ export const MessageCommentsProvider: VoidComponent<{
return;
}
+ if (isDraft) {
+ Telemetry.info('comment.draft.mounted', {
+ 'document.id': documentId,
+ 'comment.mark_id': markId,
+ });
+ }
+
setMarks(markId, {
id: markId,
existsOnServer: hasServerThread,
@@ -584,6 +595,35 @@ export const MessageCommentsProvider: VoidComponent<{
)
);
+ const localDraft = createLocalCommentDraft({
+ userId,
+ hasPostedComment: (markId) => hasPostedComment(documentId, markId),
+ editor,
+ manager: props.loroManager,
+ mapping: wrapper.mapping,
+ interactable: wrapper.isInteractable,
+ source: () => {
+ const source = documentSource();
+ return source.type === 'sync' ? source.source : undefined;
+ },
+ add: (id, element, publication) => {
+ setMarks(id, {
+ id,
+ existsOnServer: false,
+ isDraft: true,
+ owner: userId(),
+ markNodes: { draft: element },
+ publication,
+ });
+ },
+ remove: (id) => {
+ // A posted mark has its own mounted ranges by now.
+ if (marks[id]?.existsOnServer)
+ setMarks(id, 'markNodes', 'draft', undefined);
+ else setMarks(id, undefined);
+ },
+ });
+
plugins.use(
commentPlugin({
ops: {
@@ -593,8 +633,10 @@ export const MessageCommentsProvider: VoidComponent<{
init: initComments,
},
peerId: currentPeerId,
+ documentId,
+ draft: localDraft,
})
);
- return null;
+ return <localDraft.Highlight />;
};
diff --git a/apps/web/src/features/block-md/comments/browser-test/collab.browser.e2e.ts b/apps/web/src/features/block-md/comments/browser-test/collab.browser.e2e.ts
new file mode 100644
index 0000000000..00b4be95f9
--- /dev/null
+++ b/apps/web/src/features/block-md/comments/browser-test/collab.browser.e2e.ts
@@ -0,0 +1,90 @@
+import { expect, test } from '@playwright/test';
+
+for (const readonly of [false, true]) {
+ for (const mode of ['acked', 'rejected', 'catchup']) {
+ const reject = mode === 'rejected';
+ const catchup = mode === 'catchup';
+ test(`repeated comments preserve collaborative text (${readonly ? 'commenter' : 'editor'}, ${mode})`, async ({
+ page,
+ }) => {
+ await page.route('**/*', (route) =>
+ new URL(route.request().url()).hostname === 'localhost'
+ ? route.continue()
+ : route.abort()
+ );
+ await page.routeWebSocket('**/*', (socket) => socket.close());
+ await page.goto(
+ `/src/features/block-md/comments/browser-test/collab.html?${readonly ? 'readonly&' : ''}${reject ? 'reject' : ''}${catchup ? 'missed-update' : ''}`
+ );
+ await page.waitForFunction(() => window.commentCollab?.ready());
+ const editor = page.getByRole('textbox', { name: 'Document' });
+ const original = await editor.locator('p').first().innerText();
+ for (let attempt = 0; attempt < 3; attempt++) {
+ const version = await page.evaluate(() =>
+ window.commentCollab!.version()
+ );
+ const selectionRect = await editor.evaluate((element) => {
+ const walker = document.createTreeWalker(
+ element,
+ NodeFilter.SHOW_TEXT
+ );
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+ const start = node.textContent?.indexOf('shared') ?? -1;
+ if (start < 0) continue;
+ const range = document.createRange();
+ range.setStart(node, start);
+ range.setEnd(node, start + 6);
+ const rect = range.getBoundingClientRect();
+ return {
+ left: rect.left,
+ right: rect.right,
+ y: rect.top + rect.height / 2,
+ };
+ }
+ throw new Error('Missing selected word');
+ });
+ await page.mouse.move(selectionRect.left, selectionRect.y);
+ await page.mouse.down();
+ await page.mouse.move(selectionRect.right, selectionRect.y, {
+ steps: 6,
+ });
+ await page.mouse.up();
+ await expect
+ .poll(() => page.evaluate(() => window.getSelection()?.toString()))
+ .toBe('shared');
+ await page
+ .getByRole('button', { name: 'Comment', exact: true })
+ .click();
+ await expect(page.getByTestId('draft')).not.toBeEmpty();
+ expect(await page.evaluate(() => window.commentCollab!.version())).toBe(
+ version
+ );
+ await page.evaluate(() => window.commentCollab!.remoteEdit());
+ const visibleEdits = catchup ? attempt * 2 : attempt + 1;
+ await expect(page.getByTestId('draft')).not.toBeEmpty();
+ await expect
+ .poll(() => editor.locator('p').first().innerText())
+ .toBe(original.replace('notes', 'notes' + '!'.repeat(visibleEdits)));
+ await page
+ .getByRole('button', { name: 'Post comment', exact: true })
+ .click();
+ await expect(page.getByTestId('result')).toHaveText(
+ reject ? 'rejected' : 'accepted'
+ );
+ if (reject) {
+ await expect(page.getByTestId('draft')).not.toBeEmpty();
+ await page.getByRole('button', { name: 'Cancel draft' }).click();
+ }
+ await expect(page.getByTestId('draft')).toBeEmpty();
+ await expect
+ .poll(() => editor.locator('p').first().innerText())
+ .toBe(
+ original.replace(
+ 'notes',
+ 'notes' + '!'.repeat((attempt + 1) * (catchup ? 2 : 1))
+ )
+ );
+ }
+ });
+ }
+}
diff --git a/apps/web/src/features/block-md/comments/browser-test/collab.html b/apps/web/src/features/block-md/comments/browser-test/collab.html
new file mode 100644
index 0000000000..de3873ca94
--- /dev/null
+++ b/apps/web/src/features/block-md/comments/browser-test/collab.html
@@ -0,0 +1,3 @@
+<!doctype html>
+<html><head><meta name="viewport" content="width=device-width, initial-scale=1"></head>
+<body><div id="root"></div><script type="module" src="./collab.tsx"></script></body></html>
diff --git a/apps/web/src/features/block-md/comments/browser-test/collab.tsx b/apps/web/src/features/block-md/comments/browser-test/collab.tsx
new file mode 100644
index 0000000000..294eac5b67
--- /dev/null
+++ b/apps/web/src/features/block-md/comments/browser-test/collab.tsx
@@ -0,0 +1,308 @@
+import '@app/index.css';
+import { AnalyticsContextProvider } from '@app/lib/analytics/analytics-context';
+import { PosthogProvider } from '@app/lib/analytics/posthog';
+import { CollabProvider } from '@core/component/LexicalMarkdown/collaboration/CollabProvider';
+import type { MarkdownEditorErrors } from '@core/component/LexicalMarkdown/constants';
+import {
+ createLexicalWrapper,
+ LexicalWrapperContext,
+} from '@core/component/LexicalMarkdown/context/LexicalWrapperContext';
+import { registerMarkdownEditing } from '@core/component/LexicalMarkdown/editing/registerMarkdownEditing';
+import {
+ COMMIT_COMMENT_MARK_COMMAND,
+ CREATE_DRAFT_COMMENT_COMMAND,
+ commentPlugin,
+ DELETE_COMMENT_COMMAND,
+ DISCARD_DRAFT_COMMENT_COMMAND,
+} from '@core/component/LexicalMarkdown/plugins/comments/commentPlugin';
+import { editorFocusSignal } from '@core/component/LexicalMarkdown/utils';
+import { UserContextProvider } from '@core/context/user';
+import { fireAndForget } from '@core/util/fireAndForget';
+import { onElementConnect } from '@core/util/onElementConnect';
+import { createLoroManager } from '@macro-inc/collaboration/collab/manager';
+import {
+ type LiveSyncSource,
+ type SyncSourceEvent,
+ SyncSourceStatus,
+} from '@macro-inc/collaboration/collab/source';
+import { createPeerIdValidator } from '@macro-inc/lexical-core';
+import { MARKDOWN_LORO_SCHEMA } from '@macro-inc/lexical-core/markdown-loro-schema';
+import { markdownToLoroSnapshot } from '@macro-inc/lexical-core/markdown-loro-snapshot';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { DragDropProvider } from '@thisbeyond/solid-dnd';
+import { $getRoot, type LexicalEditor } from 'lexical';
+import { okAsync } from 'neverthrow';
+import { createEffect, createSignal, onCleanup, Show } from 'solid-js';
+import { render } from 'solid-js/web';
+import { CommentButton } from '../../component/CommentButton';
+import {
+ createLocalCommentDraft,
+ type DraftPublication,
+} from '../LocalCommentDraft';
+
+declare global {
+ interface Window {
+ commentCollab?: {
+ ready: () => boolean;
+ state: () => unknown;
+ text: () => string;
+ remoteEdit: () => Promise<void>;
+ version: () => string;
+ };
+ }
+}
+
+const MARKDOWN =
+ 'The shared directory contains useful notes for every reader.\n\nA second paragraph offers another place for comments.';
+
+function Fixture() {
+ const documentId = crypto.randomUUID();
+ const loroManager = createLoroManager(MARKDOWN_LORO_SCHEMA, { documentId });
+ const server = createLoroManager(MARKDOWN_LORO_SCHEMA, { documentId });
+ const listeners = new Set<(event: SyncSourceEvent) => void>();
+ const source: LiveSyncSource = {
+ documentId,
+ status: () => SyncSourceStatus.Connected,
+ listen: (listener) => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+ pushUpdate: async (updates) => {
+ if (new URLSearchParams(location.search).has('reject')) return false;
+ for (const update of updates) {
+ if (server.importUpdate(update).isErr()) return false;
+ }
+ return true;
+ },
+ pushAwareness: () => {},
+ registerPeerId: () => {},
+ requestUpdatesSince: (from) =>
+ okAsync(server.doc.export({ mode: 'update', from })),
+ requestSnapshot: () =>
+ okAsync(
+ server.doc.export({
+ mode: 'shallow-snapshot',
+ frontiers: server.doc.oplogFrontiers(),
+ })
+ ),
+ reconnect: () => {},
+ cleanup: () => {},
+ };
+ const [syncSource, setSyncSource] = createSignal<LiveSyncSource>();
+ const [ready, setReady] = createSignal(false);
+ let editor: LexicalEditor | undefined;
+
+ const connect = async () => {
+ const snapshot = await markdownToLoroSnapshot(MARKDOWN);
+ if (!snapshot) throw new Error('no snapshot');
+ await server.ingest({ kind: 'dss', snapshot });
+ await loroManager.ingest({ kind: 'dss', snapshot });
+ setSyncSource(source);
+ };
+ fireAndForget(connect(), 'comment-collab-fixture');
+
+ window.commentCollab = {
+ ready,
+ version: () => JSON.stringify(loroManager.doc.oplogVersion().toJSON()),
+ remoteEdit: async () => {
+ const version = server.doc.oplogVersion();
+ const state = structuredClone(server.state!.state);
+ const paragraph = state.root.children[0];
+ const text = paragraph.children.find((node: { text?: string }) =>
+ node.text?.includes('notes')
+ );
+ if (!text) throw new Error('Missing remote text');
+ const missed = new URLSearchParams(location.search).has('missed-update');
+ text.text = text.text.replace('notes', missed ? 'notes!!' : 'notes!');
+ const result = await server.syncToLoro(state);
+ if (result.isErr()) throw new Error('Remote edit failed');
+ if (missed) return;
+ const update = server.doc.export({ mode: 'update', from: version });
+ for (const listener of listeners) listener({ type: 'update', update });
+ },
+ state: () => loroManager.doc.toJSON(),
+ text: () => editor?.read(() => $getRoot().getTextContent()) ?? '',
+ };
+
+ return (
+ <main class="p-4 text-ink bg-page">
+ <Show when={syncSource()}>
+ <Editor
+ documentId={documentId}
+ loroManager={loroManager}
+ syncSource={syncSource}
+ onEditor={(e) => {
+ editor = e;
+ }}
+ onReady={() => setReady(true)}
+ />
+ </Show>
+ </main>
+ );
+}
+
+/** The editor `CollabMarkdownEditor` builds, minus menus and overlays. */
+function Editor(props: {
+ documentId: string;
+ loroManager: ReturnType<
+ typeof createLoroManager<typeof MARKDOWN_LORO_SCHEMA>
+ >;
+ syncSource: () => LiveSyncSource | undefined;
+ onEditor: (editor: LexicalEditor) => void;
+ onReady: () => void;
+}) {
+ const [editorReady, setEditorReady] = createSignal(false);
+ const [editorError, setEditorError] =
+ createSignal<MarkdownEditorErrors | null>(null);
+ const readonly = new URLSearchParams(location.search).has('readonly');
+ const isContentEditable = () => !readonly && editorReady() && !editorError();
+ const lexicalWrapper = createLexicalWrapper({
+ type: 'markdown-sync',
+ namespace: 'comment-collab',
+ isInteractable: isContentEditable,
+ withIds: true,
+ });
+ const { editor, plugins, cleanup } = lexicalWrapper;
+ onCleanup(cleanup);
+ props.onEditor(editor);
+ const [editorFocus, setEditorFocus] = createSignal(false);
+ editorFocusSignal(editor, setEditorFocus);
+ const peerId = () => props.loroManager.peerIdStr;
+ const [draft, setDraft] = createSignal<string>();
+ const [publication, setPublication] = createSignal<DraftPublication>();
+ const [result, setResult] = createSignal('');
+ const localDraft = createLocalCommentDraft({
+ userId: () => 'fixture-user',
+ hasPostedComment: async () => false,
+ interactable: isContentEditable,
+ editor,
+ manager: props.loroManager,
+ mapping: lexicalWrapper.mapping,
+ source: props.syncSource,
+ add: (id, _anchor, publication) => {
+ setDraft(id);
+ setPublication(publication);
+ },
+ remove: () => {
+ setDraft();
+ setPublication();
+ },
+ });
+ onCleanup(
+ commentPlugin({
+ peerId,
+ draft: localDraft,
+ ops: {
+ add: (id, _node, _element, _saved, isDraft, local) => {
+ if (isDraft && local) setDraft(id);
+ },
+ remove: (id, _key, last) => {
+ if (last && draft() === id) setDraft(undefined);
+ },
+ init: () => {},
+ setActiveIds: () => {},
+ },
+ })(editor)
+ );
+ plugins
+ .richText()
+ .list()
+ .markdownShortcuts()
+ .delete()
+ .history(400, props.loroManager);
+ registerMarkdownEditing({
+ lexicalWrapper,
+ isContentEditable,
+ peerIdValidator: createPeerIdValidator(peerId, true),
+ source: { id: props.documentId, trackMentions: false },
+ onVersionError: setEditorError,
+ peerId,
+ });
+ createEffect(() => editor.setEditable(isContentEditable()));
+ createEffect(() => {
+ if (editorReady()) props.onReady();
+ });
+ let container!: HTMLDivElement;
+ return (
+ <LexicalWrapperContext.Provider value={lexicalWrapper}>
+ <div class="relative border border-edge-muted p-2" ref={container}>
+ <div
+ ref={(el) => onElementConnect(el, () => editor.setRootElement(el))}
+ contentEditable={isContentEditable()}
+ role="textbox"
+ aria-label="Document"
+ aria-multiline="true"
+ class="w-full outline-none"
+ />
+ <CommentButton
+ onClick={() =>
+ editor.dispatchCommand(CREATE_DRAFT_COMMENT_COMMAND, undefined)
+ }
+ />
+ <button
+ onClick={async () => {
+ setResult('');
+ const id = draft();
+ const accepted = await publication()?.publish();
+ setResult(accepted ? 'accepted' : 'rejected');
+ if (id && accepted)
+ editor.dispatchCommand(COMMIT_COMMENT_MARK_COMMAND, {
+ markId: id,
+ });
+ }}
+ >
+ Post comment
+ </button>
+ <button
+ onClick={() => {
+ const id = draft();
+ if (id) editor.dispatchCommand(DELETE_COMMENT_COMMAND, [id, false]);
+ editor.dispatchCommand(DISCARD_DRAFT_COMMENT_COMMAND, undefined);
+ setDraft(undefined);
+ }}
+ >
+ Cancel draft
+ </button>
+ <output data-testid="draft">{draft()}</output>
+ <output data-testid="result">{result()}</output>
+ <localDraft.Highlight />
+ <CollabProvider
+ editor={editor}
+ pluginManager={plugins}
+ editorContainerRef={container}
+ highlightLayerRef={container}
+ mappings={lexicalWrapper.mapping!}
+ editorFocus={editorFocus}
+ setEditorReady={setEditorReady}
+ setEditorError={setEditorError}
+ loroManager={props.loroManager}
+ syncSource={props.syncSource}
+ sourceReady={() => true}
+ canEdit={() => !readonly}
+ canComment={() => true}
+ editorError={editorError}
+ />
+ </div>
+ </LexicalWrapperContext.Provider>
+ );
+}
+
+const client = new QueryClient();
+render(
+ () => (
+ <AnalyticsContextProvider>
+ <PosthogProvider>
+ <QueryClientProvider client={client}>
+ <UserContextProvider>
+ <DragDropProvider>
+ <Fixture />
+ </DragDropProvider>
+ </UserContextProvider>
+ </QueryClientProvider>
+ </PosthogProvider>
+ </AnalyticsContextProvider>
+ ),
+ document.getElementById('root')!
+);
diff --git a/apps/web/src/features/block-md/comments/browser-test/drafts.browser.e2e.ts b/apps/web/src/features/block-md/comments/browser-test/drafts.browser.e2e.ts
new file mode 100644
index 0000000000..ea2e8cb630
--- /dev/null
+++ b/apps/web/src/features/block-md/comments/browser-test/drafts.browser.e2e.ts
@@ -0,0 +1,74 @@
+import { expect, test } from '@playwright/test';
+
+for (const readonly of [false, true]) {
+ for (const paragraph of [0, 1]) {
+ test(`open, cancel and retry on ${paragraph === 0 ? 'commented' : 'plain'} text (${readonly ? 'commenter' : 'editor'})`, async ({
+ page,
+ }, testInfo) => {
+ await page.route('**/*', async (route) => {
+ if (new URL(route.request().url()).hostname === 'localhost')
+ await route.continue();
+ else await route.abort();
+ });
+ await page.routeWebSocket('**/*', (socket) => socket.close());
+ await page.goto(
+ `/src/features/block-md/comments/browser-test/drafts.html${readonly ? '?readonly' : ''}`
+ );
+ const editor = page.getByRole('textbox', { name: 'Document' });
+ await expect(editor).toContainText('Already commented text');
+ for (let attempt = 0; attempt < 2; attempt++) {
+ await editor.evaluate((element, paragraph) => {
+ element.focus();
+ const text = element
+ .querySelectorAll('p')
+ [paragraph].querySelector('[data-lexical-text]')?.firstChild;
+ if (!text) throw new Error('Missing selected text');
+ const range = document.createRange();
+ range.setStart(text, 2);
+ range.setEnd(text, Math.min(7, text.textContent?.length ?? 0));
+ const selection = window.getSelection();
+ selection?.removeAllRanges();
+ selection?.addRange(range);
+ }, paragraph);
+ const button = page.getByRole('button', {
+ name: 'Comment',
+ exact: true,
+ });
+ await expect(button).toBeEnabled();
+ const rect = await button.boundingBox();
+ if (!rect) throw new Error('Comment button missing');
+ if (testInfo.project.use.hasTouch) {
+ await button.tap();
+ } else {
+ await page.mouse.move(
+ rect.x + rect.width / 2,
+ rect.y + rect.height / 2
+ );
+ await page.mouse.down();
+ if (!readonly) await expect(editor).toBeFocused();
+ await page.mouse.up();
+ }
+ await expect(page.getByTestId('result')).toHaveText('true');
+ await expect(page.getByTestId('draft')).not.toBeEmpty();
+ await expect(editor.locator('mark.draft')).toHaveCount(1);
+ await expect(editor.locator('p').nth(0)).toHaveText(
+ 'Already commented text'
+ );
+ await expect(editor.locator('p').nth(1)).toHaveText(
+ 'Plain text for another comment'
+ );
+ const draftId = await page.getByTestId('draft').textContent();
+ await expect(page.getByTestId('saved')).not.toContainText(draftId!);
+ await expect(page.getByTestId('saved')).toContainText('saved-comment');
+ if (attempt === 0)
+ await page.screenshot({
+ path: testInfo.outputPath('comment-draft.png'),
+ });
+ await page.getByRole('button', { name: 'Cancel draft' }).click();
+ await expect(editor.locator('mark.draft')).toHaveCount(0);
+ await expect(editor.locator('mark')).toHaveCount(1);
+ await expect(editor).toContainText('Already commented text');
+ }
+ });
+ }
+}
diff --git a/apps/web/src/features/block-md/comments/browser-test/drafts.html b/apps/web/src/features/block-md/comments/browser-test/drafts.html
new file mode 100644
index 0000000000..89e9a1b105
--- /dev/null
+++ b/apps/web/src/features/block-md/comments/browser-test/drafts.html
@@ -0,0 +1,3 @@
+<!doctype html>
+<html><head><meta name="viewport" content="width=device-width, initial-scale=1"></head>
+<body><div id="root"></div><script type="module" src="./drafts.tsx"></script></body></html>
diff --git a/apps/web/src/features/block-md/comments/browser-test/drafts.tsx b/apps/web/src/features/block-md/comments/browser-test/drafts.tsx
new file mode 100644
index 0000000000..4c7dbb5b65
--- /dev/null
+++ b/apps/web/src/features/block-md/comments/browser-test/drafts.tsx
@@ -0,0 +1,133 @@
+import '@app/index.css';
+import {
+ COMMIT_COMMENT_MARK_COMMAND,
+ CREATE_DRAFT_COMMENT_COMMAND,
+ commentPlugin,
+ DELETE_COMMENT_COMMAND,
+ DISCARD_DRAFT_COMMENT_COMMAND,
+} from '@core/component/LexicalMarkdown/plugins/comments/commentPlugin';
+import {
+ $createCommentNode,
+ CommentNode,
+ peerIdPlugin,
+ stripDraftCommentMarks,
+} from '@macro-inc/lexical-core';
+import {
+ $createParagraphNode,
+ $createTextNode,
+ $getRoot,
+ createEditor,
+} from 'lexical';
+import { createSignal, onCleanup, onMount } from 'solid-js';
+import { render } from 'solid-js/web';
+import { CommentButton } from '../../component/CommentButton';
+
+function Fixture() {
+ const readonly = new URLSearchParams(location.search).has('readonly');
+ const [focused, setFocused] = createSignal(false);
+ const [draftId, setDraftId] = createSignal<string>();
+ const [result, setResult] = createSignal('');
+ const [saved, setSaved] = createSignal('');
+ const editor = createEditor({
+ namespace: 'comment-drafts',
+ nodes: [CommentNode],
+ onError: (error) => {
+ throw error;
+ },
+ });
+ let root!: HTMLDivElement;
+ onMount(() => {
+ editor.setRootElement(root);
+ editor.setEditable(!readonly);
+ const cleanupPeer = peerIdPlugin({
+ peerId: () => '1',
+ nodes: [CommentNode],
+ })(editor);
+ const cleanupComments = commentPlugin({
+ peerId: () => '1',
+ documentId: 'comment-fixture',
+ ops: {
+ add: (id, _node, _element, _saved, draft, local) => {
+ if (draft && local) setDraftId(id);
+ },
+ remove: (id, _key, last) => {
+ if (last && id === draftId()) setDraftId(undefined);
+ },
+ init: () => {},
+ setActiveIds: () => {},
+ },
+ })(editor);
+ const cleanupUpdates = editor.registerUpdateListener(({ editorState }) => {
+ setSaved(JSON.stringify(stripDraftCommentMarks(editorState.toJSON())));
+ });
+ editor.update(
+ () => {
+ $getRoot().append(
+ $createParagraphNode().append(
+ $createCommentNode({ ids: ['saved-comment'] }).append(
+ $createTextNode('Already commented text')
+ )
+ ),
+ $createParagraphNode().append(
+ $createTextNode('Plain text for another comment')
+ )
+ );
+ },
+ { discrete: true }
+ );
+ onCleanup(() => {
+ cleanupUpdates();
+ cleanupComments();
+ cleanupPeer();
+ editor.setRootElement(null);
+ });
+ });
+ const cancel = () => {
+ const id = draftId();
+ if (id) editor.dispatchCommand(DELETE_COMMENT_COMMAND, [id, false]);
+ editor.dispatchCommand(DISCARD_DRAFT_COMMENT_COMMAND, undefined);
+ setDraftId(undefined);
+ };
+ return (
+ <main class="bg-page text-ink p-6 space-y-4">
+ <h1>Inline comment regression</h1>
+ <div
+ ref={root}
+ contentEditable={!readonly}
+ role="textbox"
+ aria-label="Document"
+ class="border border-edge p-4 min-h-32"
+ onFocusIn={() => setFocused(true)}
+ onFocusOut={() => setFocused(false)}
+ />
+ <CommentButton
+ disabled={!readonly && !focused()}
+ onClick={() =>
+ setResult(
+ String(
+ editor.dispatchCommand(CREATE_DRAFT_COMMENT_COMMAND, undefined)
+ )
+ )
+ }
+ />
+ <button onClick={cancel}>Cancel draft</button>
+ <button
+ onClick={() => {
+ const id = draftId();
+ if (id)
+ editor.dispatchCommand(COMMIT_COMMENT_MARK_COMMAND, { markId: id });
+ setDraftId(undefined);
+ }}
+ >
+ Commit mark
+ </button>
+ <output data-testid="result">{result()}</output>
+ <output data-testid="draft">{draftId() ?? ''}</output>
+ <pre data-testid="saved" class="whitespace-pre-wrap break-all">
+ {saved()}
+ </pre>
+ </main>
+ );
+}
+
+render(() => <Fixture />, document.getElementById('root')!);
diff --git a/apps/web/src/features/block-md/comments/browser-test/playwright.config.ts b/apps/web/src/features/block-md/comments/browser-test/playwright.config.ts
new file mode 100644
index 0000000000..f70ec9f389
--- /dev/null
+++ b/apps/web/src/features/block-md/comments/browser-test/playwright.config.ts
@@ -0,0 +1,44 @@
+import { fileURLToPath } from 'node:url';
+import { defineConfig, devices } from '@playwright/test';
+
+const PORT = process.env.COMMENT_TEST_PORT ?? '3529';
+export default defineConfig({
+ testDir: fileURLToPath(new URL('.', import.meta.url)),
+ testMatch: '*.browser.e2e.ts',
+ workers: 1,
+ timeout: 60_000,
+ use: { baseURL: `http://localhost:${PORT}`, trace: 'retain-on-failure' },
+ projects: [
+ {
+ name: 'chromium',
+ use: {
+ browserName: 'chromium',
+ viewport: { width: 1280, height: 900 },
+ launchOptions: {
+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
+ },
+ },
+ },
+ {
+ name: 'webkit',
+ use: { browserName: 'webkit', viewport: { width: 1280, height: 900 } },
+ },
+ {
+ name: 'phone',
+ use: {
+ ...devices['iPhone 13'],
+ defaultBrowserType: 'chromium',
+ launchOptions: {
+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
+ },
+ },
+ },
+ ],
+ webServer: {
+ command: `MACRO_DEV_HTTPS=false bunx vite --port ${PORT} --strictPort`,
+ cwd: fileURLToPath(new URL('../../../../../', import.meta.url)),
+ url: `http://localhost:${PORT}/app/`,
+ reuseExistingServer: false,
+ timeout: 60_000,
+ },
+});
diff --git a/apps/web/src/features/block-md/comments/commentMarkCleanup.test.ts b/apps/web/src/features/block-md/comments/commentMarkCleanup.test.ts
new file mode 100644
index 0000000000..8a72448be3
--- /dev/null
+++ b/apps/web/src/features/block-md/comments/commentMarkCleanup.test.ts
@@ -0,0 +1,114 @@
+import { InMemoryWALStore } from '@macro-inc/collaboration/collab/wal';
+import { expect, it, vi } from 'vitest';
+import { createCommentMarkCleanup } from './commentMarkCleanup';
+
+it('keeps failed removals for a new drain without retrying successful entries', async () => {
+ const store = new InMemoryWALStore<string>();
+ await store.append('failed');
+ await store.append('accepted');
+ const remove = vi.fn(async (id: string) => id === 'accepted');
+ await createCommentMarkCleanup(store, remove).flush();
+ expect((await store.getAll()).map((entry) => entry.update)).toEqual([
+ 'failed',
+ ]);
+
+ const retry = vi.fn(async () => true);
+ await createCommentMarkCleanup(store, retry).flush();
+ expect(retry).toHaveBeenCalledExactlyOnceWith('failed');
+ expect(await store.getAll()).toEqual([]);
+});
+
+it('retains intents when lookup or transport throws', async () => {
+ const store = new InMemoryWALStore<string>();
+ const error = new Error('offline');
+ const remove = vi.fn().mockRejectedValue(error);
+ await expect(
+ createCommentMarkCleanup(store, remove).enqueue('cancelled')
+ ).rejects.toMatchObject({ errors: [error] });
+ expect((await store.getAll()).map((entry) => entry.update)).toEqual([
+ 'cancelled',
+ ]);
+});
+
+it('continues after a rejected lookup without losing its cleanup intent', async () => {
+ const store = new InMemoryWALStore<string>();
+ await store.append('failed');
+ await store.append('accepted');
+ const error = new Error('lookup unavailable');
+ const remove = vi.fn(async (id: string) => {
+ if (id === 'failed') throw error;
+ return true;
+ });
+ await expect(
+ createCommentMarkCleanup(store, remove).flush()
+ ).rejects.toMatchObject({
+ errors: [error],
+ });
+ expect(remove.mock.calls).toEqual([['failed'], ['accepted']]);
+ expect((await store.getAll()).map((entry) => entry.update)).toEqual([
+ 'failed',
+ ]);
+
+ const retry = vi.fn(async () => true);
+ await createCommentMarkCleanup(store, retry).flush();
+ expect(retry).toHaveBeenCalledExactlyOnceWith('failed');
+ expect(await store.getAll()).toEqual([]);
+});
+
+it('drains an intent appended while another removal is pending', async () => {
+ const store = new InMemoryWALStore<string>();
+ let finish!: (accepted: boolean) => void;
+ let start!: () => void;
+ const first = new Promise<boolean>((resolve) => {
+ finish = resolve;
+ });
+ const started = new Promise<void>((resolve) => {
+ start = resolve;
+ });
+ const remove = vi.fn(async (id: string) => {
+ if (id !== 'first') return true;
+ start();
+ return first;
+ });
+ const queue = createCommentMarkCleanup(store, remove);
+ const a = queue.enqueue('first');
+ await started;
+ const b = queue.enqueue('second');
+ finish(true);
+ await Promise.all([a, b]);
+ expect(remove.mock.calls).toEqual([['first'], ['second']]);
+ expect(await store.getAll()).toEqual([]);
+});
+
+it.each([false, true])(
+ 'retries a reconnect that arrives during a failed attempt, throws: %s',
+ async (throws) => {
+ const store = new InMemoryWALStore<string>();
+ await store.append('cancelled');
+ let finish!: (accepted: boolean) => void;
+ let start!: () => void;
+ const result = new Promise<boolean>((resolve) => {
+ finish = resolve;
+ });
+ const started = new Promise<void>((resolve) => {
+ start = resolve;
+ });
+ const remove = vi
+ .fn()
+ .mockResolvedValue(true)
+ .mockImplementationOnce(async () => {
+ start();
+ await result;
+ if (throws) throw new Error('offline');
+ return false;
+ });
+ const queue = createCommentMarkCleanup(store, remove);
+ const attempt = queue.flush();
+ await started;
+ const reconnect = queue.flush();
+ finish(false);
+ await Promise.all([attempt, reconnect]);
+ expect(remove).toHaveBeenCalledTimes(2);
+ expect(await store.getAll()).toEqual([]);
+ }
+);
diff --git a/apps/web/src/features/block-md/comments/commentMarkCleanup.ts b/apps/web/src/features/block-md/comments/commentMarkCleanup.ts
new file mode 100644
index 0000000000..441b3a67be
--- /dev/null
+++ b/apps/web/src/features/block-md/comments/commentMarkCleanup.ts
@@ -0,0 +1,58 @@
+import type { WALStore } from '@macro-inc/collaboration/collab/wal';
+
+/** Only cancelled publications with no pending or uncertain message write enter here. */
+export function createCommentMarkCleanup(
+ store: WALStore<string>,
+ remove: (markId: string) => Promise<boolean>
+) {
+ let pending: Promise<void> | undefined;
+ let rerun = false;
+
+ async function drain() {
+ const errors: unknown[] = [];
+ for (const entry of await store.getAll()) {
+ try {
+ if (!entry.delivered && (await remove(entry.update)))
+ await store.markDelivered([entry.id]);
+ } catch (error) {
+ errors.push(error);
+ }
+ }
+ await store.pruneDelivered();
+ if (errors.length)
+ throw new AggregateError(errors, 'Comment mark cleanup failed');
+ }
+
+ async function flush() {
+ if (pending) {
+ rerun = true;
+ return pending;
+ }
+ const drainRequested = async () => {
+ do {
+ rerun = false;
+ try {
+ await drain();
+ } catch (error) {
+ if (!rerun) throw error;
+ }
+ } while (rerun);
+ };
+ pending = drainRequested();
+ try {
+ await pending;
+ } finally {
+ pending = undefined;
+ }
+ }
+
+ return {
+ flush,
+ async enqueue(markId: string) {
+ // Persist before trying the network. Unlike document edits, abandoned
+ // anchor removals do not expire while this document remains unopened.
+ await store.append(markId);
+ await flush();
+ },
+ };
+}
diff --git a/apps/web/src/features/block-md/comments/commentOperations.ts b/apps/web/src/features/block-md/comments/commentOperations.ts
index 900a078967..22a807079d 100644
--- a/apps/web/src/features/block-md/comments/commentOperations.ts
+++ b/apps/web/src/features/block-md/comments/commentOperations.ts
@@ -8,18 +8,17 @@ import { useMarkdownDocument } from '../context/markdown-document-context';
export function useDeleteNewComments() {
const { state } = useMarkdownDocument();
const { comments: commentState, setCommentState } = state;
- const editor = state.editor.md.editor;
return createCallback((discardPending = true) => {
- // console.trace('delete new comments');
+ const editor = state.editor.md.editor;
for (const [markId, mark] of Object.entries(commentState.marks)) {
if (!mark || !mark.existsOnServer) {
setCommentState('marks', markId, undefined);
editor?.dispatchCommand(DELETE_COMMENT_COMMAND, [markId, false]);
}
- if (discardPending) {
- editor?.dispatchCommand(DISCARD_DRAFT_COMMENT_COMMAND, undefined);
- }
+ }
+ if (discardPending) {
+ editor?.dispatchCommand(DISCARD_DRAFT_COMMENT_COMMAND, undefined);
}
});
}
diff --git a/apps/web/src/features/block-md/comments/commentType.ts b/apps/web/src/features/block-md/comments/commentType.ts
index 069e0cf73b..6bf9f75a56 100644
--- a/apps/web/src/features/block-md/comments/commentType.ts
+++ b/apps/web/src/features/block-md/comments/commentType.ts
@@ -6,6 +6,7 @@ import type {
} from '@core/comments/commentType';
import type { Message } from '@service-storage/messages';
import type { NodeKey } from 'lexical';
+import type { DraftPublication } from './LocalCommentDraft';
export type MarkId = string; // uuid
@@ -28,6 +29,7 @@ export type Mark = {
isDraft: boolean;
peerId?: string;
thread?: ThreadPayload;
+ publication?: DraftPublication;
};
export type MarkStore = Partial<Record<MarkId, Mark>>;
diff --git a/apps/web/src/features/block-md/comments/draftCommentMarkSync.test.ts b/apps/web/src/features/block-md/comments/draftCommentMarkSync.test.ts
index 57edf3f4e8..d6196c5f31 100644
--- a/apps/web/src/features/block-md/comments/draftCommentMarkSync.test.ts
+++ b/apps/web/src/features/block-md/comments/draftCommentMarkSync.test.ts
@@ -1,7 +1,9 @@
import { $reconcileLexicalState } from '@core/component/LexicalMarkdown/collaboration/reconcile';
import {
+ COMMIT_COMMENT_MARK_COMMAND,
CREATE_DRAFT_COMMENT_COMMAND,
commentPlugin,
+ DELETE_COMMENT_COMMAND,
} from '@core/component/LexicalMarkdown/plugins/comments/commentPlugin';
import {
getSaveState,
@@ -10,6 +12,7 @@ import {
} from '@core/component/LexicalMarkdown/utils';
import {
$createCommentNode,
+ $getCommentMarkText,
$isCommentNode,
$updateAllNodeIds,
CommentNode,
@@ -206,6 +209,63 @@ describe('draft comment marks stay out of the shared document', () => {
]);
});
+ it.each(['cancel', 'commit', 'remote'] as const)(
+ 'preserves a saved range when an overlapping draft is %s',
+ (action) => {
+ const { editor, mappings } = setup();
+ editor.update(
+ () => {
+ const text = $createTextNode('Already commented text');
+ $getRoot().append(
+ $createParagraphNode().append(
+ $createCommentNode({ ids: ['saved'] }).append(text)
+ )
+ );
+ text.select(2, 7);
+ editor.dispatchCommand(CREATE_DRAFT_COMMENT_COMMAND, undefined);
+ $updateAllNodeIds(mappings);
+ },
+ { discrete: true }
+ );
+ const key = draftKeys(editor)[0];
+ const id = editor.read(
+ () => $getNodeByKey<CommentNode>(key)!.getIDs()[0]
+ );
+ const shared = loroSyncState(editor.getEditorState());
+ expect(JSON.stringify(shared)).not.toContain(id);
+ expect(JSON.stringify(shared)).toContain('saved');
+ expect(editor.read(() => $getCommentMarkText('saved'))).toBe(
+ 'Already commented text'
+ );
+
+ if (action === 'remote') {
+ applyRemote(editor, mappings, shared);
+ expect(draftKeys(editor)).toEqual([key]);
+ expect(draftText(editor, key)).toBe('ready');
+ } else {
+ editor.update(
+ () => {
+ if (action === 'cancel')
+ editor.dispatchCommand(DELETE_COMMENT_COMMAND, [id, false]);
+ else
+ editor.dispatchCommand(COMMIT_COMMENT_MARK_COMMAND, {
+ markId: id,
+ });
+ },
+ { discrete: true }
+ );
+ expect(draftKeys(editor)).toEqual([]);
+ expect(editor.read(() => $getCommentMarkText(id))).toBe(
+ action === 'commit' ? 'ready' : ''
+ );
+ }
+ expect(editor.read(() => $getCommentMarkText('saved'))).toBe(
+ 'Already commented text'
+ );
+ expect(paragraphText(editor)).toEqual(['Already commented text']);
+ }
+ );
+
it('returns the same state object when there is no draft to strip', () => {
const { editor } = setup();
editor.update(
diff --git a/apps/web/src/features/block-md/comments/messageCommentOperations.ts b/apps/web/src/features/block-md/comments/messageCommentOperations.ts
index a954d2a078..083b8aa579 100644
--- a/apps/web/src/features/block-md/comments/messageCommentOperations.ts
+++ b/apps/web/src/features/block-md/comments/messageCommentOperations.ts
@@ -44,28 +44,40 @@ export function useCreateMessageComment(): MessageCommentOperations['createComme
console.error('Unable to comment');
return null;
}
+ const anchorId = draft.anchorId;
// Read the mark now rather than when the draft was made: what the comment
// is about is whatever it still covers as the comment is posted.
+ const publication = marks[anchorId]?.publication;
const markedText =
- editor?.read(() => $getCommentMarkText(draft.anchorId)) || undefined;
+ publication?.text() ||
+ editor?.read(() => $getCommentMarkText(anchorId)) ||
+ undefined;
- const response = await createMarkedMessage(
- message.content,
- draft.anchorId,
- markedText,
- message.mentions,
- message.attachments
- );
+ if (publication && !(await publication.publish())) return null;
+ if (publication && marks[anchorId]?.publication !== publication)
+ return null;
+
+ const send = () =>
+ createMarkedMessage(
+ message.content,
+ anchorId,
+ markedText,
+ message.mentions,
+ message.attachments
+ );
+ const response = publication ? await publication.post(send) : await send();
if (!response) return null;
+ if (publication && marks[anchorId]?.publication !== publication)
+ return response;
- if (marks[draft.anchorId]) {
- setMarks(draft.anchorId, 'existsOnServer', true);
- setMarks(draft.anchorId, 'isDraft', false);
+ if (marks[anchorId]) {
+ setMarks(anchorId, 'existsOnServer', true);
+ setMarks(anchorId, 'isDraft', false);
}
setActiveThread(response.id);
editor?.dispatchCommand(COMMIT_COMMENT_MARK_COMMAND, {
- markId: draft.anchorId,
+ markId: anchorId,
});
deleteNewComments();
return response;
diff --git a/apps/web/src/features/block-md/comments/publishCommentMark.ts b/apps/web/src/features/block-md/comments/publishCommentMark.ts
new file mode 100644
index 0000000000..005e18cb4c
--- /dev/null
+++ b/apps/web/src/features/block-md/comments/publishCommentMark.ts
@@ -0,0 +1,199 @@
+import { $cursorToLexicalPoint } from '@core/component/LexicalMarkdown/collaboration/cursor';
+import type { LexicalSelectionAwareness } from '@core/component/LexicalMarkdown/collaboration/LexicalAwareness';
+import { $unwrapMarkNode, $wrapSelectionInMarkNode } from '@lexical/mark';
+import { LoroManager } from '@macro-inc/collaboration/collab/manager';
+import type { LiveSyncSource } from '@macro-inc/collaboration/collab/source';
+import {
+ $createCommentNode,
+ $getCommentMarkText,
+ $updateAllNodeIds,
+ CommentNode,
+ type NodeIdMappings,
+ NodeReplacements,
+ nodeIdPlugin,
+ SupportedNodeTypes,
+} from '@macro-inc/lexical-core';
+import { MARKDOWN_LORO_SCHEMA } from '@macro-inc/lexical-core/markdown-loro-schema';
+import { Telemetry } from '@macro-inc/observability';
+import { $createRangeSelection, $nodesOfType, createEditor } from 'lexical';
+
+type CommentMarkChange = {
+ manager?: LoroManager;
+ active?: () => boolean;
+ source: LiveSyncSource;
+ markId: string;
+} & (
+ | { action: 'add'; cursors: LexicalSelectionAwareness; text: string }
+ | { action: 'remove' }
+);
+
+/** Publish from a separate peer: a refused mark must never enter the editor's WAL. */
+export async function publishCommentMark(options: {
+ manager: LoroManager;
+ active?: () => boolean;
+ source: LiveSyncSource;
+ markId: string;
+ cursors: LexicalSelectionAwareness;
+ text: string;
+}): Promise<boolean> {
+ return changeCommentMark({ ...options, action: 'add' });
+}
+
+export function removePublishedCommentMark(options: {
+ manager?: LoroManager;
+ active?: () => boolean;
+ source: LiveSyncSource;
+ markId: string;
+}) {
+ return changeCommentMark({ ...options, action: 'remove' });
+}
+
+async function changeCommentMark(options: CommentMarkChange): Promise<boolean> {
+ const { manager, source, markId } = options;
+ const active = options.active ?? (() => true);
+ const liveVersion =
+ manager && active() ? manager.doc.oplogVersion() : undefined;
+ const span = Telemetry.span('comment.mark.publish');
+ span.setAttr('comment.action', options.action);
+ span.setAttr('document.id', source.documentId);
+ span.setAttr('comment.mark_id', markId);
+ const staged: LoroManager = new LoroManager(MARKDOWN_LORO_SCHEMA, {
+ documentId: source.documentId,
+ ownsTelemetry: false,
+ });
+ const editor = createEditor({
+ namespace: 'comment-publication',
+ nodes: [...SupportedNodeTypes, ...NodeReplacements],
+ onError: (error) => {
+ throw error;
+ },
+ });
+ const mapping: NodeIdMappings = {
+ idToNodeKeyMap: new Map(),
+ nodeKeyToIdMap: new Map(),
+ };
+ const cleanup = nodeIdPlugin({
+ nodes: SupportedNodeTypes,
+ idLength: 8,
+ mappings: mapping,
+ })(editor);
+ const refuse = (reason: string) => {
+ span.setAttr('comment.outcome', reason);
+ Telemetry.warn('comment.mark.publication_failed', {
+ 'document.id': source.documentId,
+ 'comment.mark_id': markId,
+ 'comment.reason': reason,
+ });
+ return false;
+ };
+ try {
+ const snapshot = await source.requestSnapshot();
+ if (snapshot.isErr()) return refuse('snapshot_failed');
+ const loaded = await staged.initializeFromSnapshot(snapshot.value);
+ if (loaded.isErr() || !staged.state) return refuse('snapshot_invalid');
+ if (manager && liveVersion) {
+ const compared = staged.doc.oplogVersion().compare(liveVersion);
+ if (compared === undefined || compared < 0)
+ return refuse('local_changes_pending');
+ if (compared > 0) {
+ // A shallow snapshot cannot supply an existing peer's missing history.
+ // Catch up before publishing, including retries of an accepted mark.
+ span.setAttr('comment.catchup_required', true);
+ const updates = await source.requestUpdatesSince(
+ manager.doc.oplogVersion()
+ );
+ if (!active()) return refuse('cancelled');
+ if (updates.isErr()) return refuse('catchup_failed');
+ if (manager.importUpdate(updates.value).isErr())
+ return refuse('catchup_merge_failed');
+ const merged = manager.doc
+ .oplogVersion()
+ .compare(staged.doc.oplogVersion());
+ if (merged === undefined || merged < 0)
+ return refuse('catchup_incomplete');
+ }
+ // Draft cursors can refer to text containers replaced by a remote edit.
+ // Keep the live peer's history so they resolve after snapshot compaction.
+ const restored = await staged.reset(
+ manager.doc.export({ mode: 'snapshot' })
+ );
+ if (restored.isErr() || !staged.state)
+ return refuse('history_snapshot_invalid');
+ }
+ if (!active()) return refuse('cancelled');
+ editor.setEditorState(
+ editor.parseEditorState(JSON.stringify(staged.state.state))
+ );
+ let placed = false;
+ editor.update(
+ () => {
+ $updateAllNodeIds(mapping);
+ if (options.action === 'remove') {
+ for (const node of $nodesOfType(CommentNode)) {
+ if (!node.isAttached() || !node.getIDs().includes(markId)) continue;
+ if (node.getIDs().length > 1) node.deleteID(markId);
+ else $unwrapMarkNode(node);
+ }
+ placed = true;
+ return;
+ }
+ // An earlier request may have landed even though its acknowledgement was lost.
+ if ($getCommentMarkText(markId)) {
+ placed = true;
+ return;
+ }
+ const anchor = $cursorToLexicalPoint(
+ options.cursors.anchor,
+ staged,
+ editor,
+ mapping
+ );
+ const focus = $cursorToLexicalPoint(
+ options.cursors.focus,
+ staged,
+ editor,
+ mapping
+ );
+ if (!anchor || !focus) return;
+ const selection = $createRangeSelection();
+ selection.anchor.set(anchor.key, anchor.offset, anchor.type);
+ selection.focus.set(focus.key, focus.offset, focus.type);
+ if (
+ selection.getTextContent() !== options.text ||
+ selection.isCollapsed()
+ )
+ return;
+ $wrapSelectionInMarkNode(
+ selection,
+ selection.isBackward(),
+ markId,
+ (ids) => $createCommentNode({ ids, isDraft: false })
+ );
+ placed = true;
+ },
+ { discrete: true }
+ );
+ if (!placed) {
+ return refuse('selection_changed');
+ }
+ const version = staged.doc.oplogVersion();
+ const synced = await staged.syncToLoro({
+ ...editor.getEditorState().toJSON(),
+ });
+ if (synced.isErr()) return refuse('staging_failed');
+ const update = staged.doc.export({ mode: 'update', from: version });
+ if (!active()) return refuse('cancelled');
+ const acked = await source.pushUpdate([update], { commentOnly: true });
+ span.setAttr('comment.outcome', acked ? 'accepted' : 'not_acked');
+ if (!acked) return refuse('not_acked');
+ if (manager && active()) {
+ if (manager.importUpdate(update).isErr())
+ return refuse('update_merge_failed');
+ }
+ return true;
+ } finally {
+ cleanup();
+ staged.dispose();
+ span.end();
+ }
+}
diff --git a/apps/web/src/features/block-md/component/CommentButton.tsx b/apps/web/src/features/block-md/component/CommentButton.tsx
new file mode 100644
index 0000000000..e10119af90
--- /dev/null
+++ b/apps/web/src/features/block-md/component/CommentButton.tsx
@@ -0,0 +1,27 @@
+import ChatTeardrop from '@icon/system/regular/chat-teardrop.svg';
+import { Button } from '@ui';
+
+/** Keep the selected editor range alive until the comment command runs. */
+export function CommentButton(props: {
+ disabled?: boolean;
+ onClick: () => void;
+}) {
+ return (
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Comment"
+ tooltip="Comment"
+ disabled={props.disabled}
+ onPointerDown={(event) => event.preventDefault()}
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ props.onClick();
+ }}
+ >
+ <ChatTeardrop class="size-3.5 touch:size-6 shrink-0 pointer-events-none" />
+ </Button>
+ );
+}
diff --git a/apps/web/src/features/block-md/component/FormatTools.tsx b/apps/web/src/features/block-md/component/FormatTools.tsx
index 716c301624..ecb4e55d37 100644
--- a/apps/web/src/features/block-md/component/FormatTools.tsx
+++ b/apps/web/src/features/block-md/component/FormatTools.tsx
@@ -14,7 +14,6 @@ import { ENABLE_MARKDOWN_COMMENTS } from '@core/constant/featureFlags';
import type { ValidHotkey } from '@core/hotkey/types';
import CaretDown from '@icon/system/regular/caret-down.svg';
import CaretRight from '@icon/system/regular/caret-right.svg';
-import ChatTeardrop from '@icon/system/regular/chat-teardrop.svg';
import Check from '@icon/system/regular/check-square.svg';
import TextCode from '@icon/system/regular/code.svg';
import CodeBlock from '@icon/system/regular/code-block.svg';
@@ -83,6 +82,7 @@ import {
} from 'solid-js';
import { Dynamic } from 'solid-js/web';
import { useMarkdownDocument } from '../context/markdown-document-context';
+import { CommentButton } from './CommentButton';
import { MediaSelector } from './MediaSelector';
import { TableInsert } from './TableInsert';
@@ -1054,19 +1054,10 @@ export function FormatTools(props: {
</Button>
<MediaSelector buttonIsDisabled={buttonIsDisabled} />
<Show when={ENABLE_MARKDOWN_COMMENTS}>
- <Button
- variant="ghost"
- size="icon-sm"
- tooltip="Comment"
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- handleInsertComment();
- }}
+ <CommentButton
+ onClick={handleInsertComment}
disabled={commentButtonIsDisabled()}
- >
- <ChatTeardrop class="size-3.5 touch:size-6 shrink-0 pointer-events-none" />
- </Button>
+ />
</Show>
<VerticalBar />
<Dropdown
@@ -1148,19 +1139,10 @@ export function FormatTools(props: {
<div class="w-4"></div>
</Show>
<Show when={ENABLE_MARKDOWN_COMMENTS && canComment() && !canEdit()}>
- <Button
- variant="ghost"
- size="icon-sm"
- tooltip="Comment"
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- handleInsertComment();
- }}
+ <CommentButton
+ onClick={handleInsertComment}
disabled={commentButtonIsDisabled()}
- >
- <ChatTeardrop class="size-3.5 touch:size-6 shrink-0 pointer-events-none" />
- </Button>
+ />
</Show>
</>
);
diff --git a/apps/web/src/features/block-md/component/MarkdownPopup.tsx b/apps/web/src/features/block-md/component/MarkdownPopup.tsx
index 47288a96f1..fd489b78ff 100644
--- a/apps/web/src/features/block-md/component/MarkdownPopup.tsx
+++ b/apps/web/src/features/block-md/component/MarkdownPopup.tsx
@@ -60,7 +60,6 @@ import { getScrollParentElement } from '@core/util/scrollParent';
import CheckIcon from '@icon/system/bold/check-bold.svg?component-solid';
import SparkleIcon from '@icon/system/bold/sparkle-bold.svg?component-solid';
import LoadingIcon from '@icon/system/bold/spinner-gap-bold.svg?component-solid';
-import ChatTeardrop from '@icon/system/regular/chat-teardrop.svg';
import CheckSquareIcon from '@icon/system/regular/check-square.svg?component-solid';
import GridIcon from '@icon/system/regular/grid-four.svg';
import LinkIcon from '@icon/system/regular/link.svg?component-solid';
@@ -105,6 +104,7 @@ import {
$insertAtSavedPoint,
type SavedPoint,
} from '../util/insertAtSavedPoint';
+import { CommentButton } from './CommentButton';
import { FormatTools } from './FormatTools';
import { TouchSelectionToolbar } from './TouchSelectionToolbar';
@@ -727,14 +727,7 @@ export function MarkdownPopup(props: {
<Toolbar.Divider />
</Show>
<Show when={ENABLE_MARKDOWN_COMMENTS && canComment()}>
- <Toolbar.Button
- aria-label="Comment"
- size="icon-sm"
- onClick={handleInsertComment}
- tooltip="Comment"
- >
- <ChatTeardrop class="size-4" />
- </Toolbar.Button>
+ <CommentButton onClick={handleInsertComment} />
</Show>
<Toolbar.Button
aria-label="Copy link to snippet"
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/collaboration/CollabProvider.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/collaboration/CollabProvider.tsx
index 6e2a1c5b1c..a664bb0719 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/collaboration/CollabProvider.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/collaboration/CollabProvider.tsx
@@ -17,6 +17,7 @@ import {
loroSyncState,
} from '@core/component/LexicalMarkdown/utils';
import { useUserId } from '@core/context/user';
+import { fireAndForget } from '@core/util/fireAndForget';
import {
$isCodeHighlightNode,
$isCodeNode,
@@ -69,6 +70,7 @@ import {
onCleanup,
type Setter,
} from 'solid-js';
+import { FLUSH_COLLABORATION_COMMAND } from './flush';
type MutatedNodes = UpdateListenerPayload['mutatedNodes'];
@@ -155,6 +157,32 @@ export function CollabProvider(props: CollabProviderProps) {
),
});
+ onCleanup(
+ props.editor.registerCommand(
+ FLUSH_COLLABORATION_COMMAND,
+ (complete) => {
+ const state = loroSyncState(props.editor.getEditorState());
+ const flush = async () => {
+ try {
+ if (!syncEngine.isRunning()) {
+ complete(false);
+ return;
+ }
+ await syncEngine.syncStateToLoro({ ...state });
+ await walSyncer.flush();
+ complete((await walSyncer.summary()).dirty === 0);
+ } catch (error) {
+ Telemetry.error(error, { surface: 'comment-flush' });
+ complete(false);
+ }
+ };
+ fireAndForget(flush(), 'comment-flush');
+ return true;
+ },
+ COMMAND_PRIORITY_NORMAL
+ )
+ );
+
const { refreshRemoteCursors, RemoteCursorsOverlay } = useRemoteCursors({
loroManager: loroManager,
mapping: props.mappings,
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/collaboration/flush.ts b/apps/web/src/lib/core/component/LexicalMarkdown/collaboration/flush.ts
new file mode 100644
index 0000000000..cda4ebf166
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/collaboration/flush.ts
@@ -0,0 +1,13 @@
+import { createCommand, type LexicalEditor } from 'lexical';
+
+/** Resolve after the editor's current state has been synchronized and acknowledged. */
+export const FLUSH_COLLABORATION_COMMAND = createCommand<
+ (acked: boolean) => void
+>('FLUSH_COLLABORATION_COMMAND');
+
+export function flushCollaboration(editor: LexicalEditor): Promise<boolean> {
+ return new Promise((resolve) => {
+ if (!editor.dispatchCommand(FLUSH_COLLABORATION_COMMAND, resolve))
+ resolve(false);
+ });
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/comments/commentPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/comments/commentPlugin.ts
index 942adbf7aa..7f37ef384b 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/comments/commentPlugin.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/comments/commentPlugin.ts
@@ -4,7 +4,7 @@ import {
$unwrapMarkNode,
$wrapSelectionInMarkNode,
} from '@lexical/mark';
-import { mergeRegister, registerNestedElementResolver } from '@lexical/utils';
+import { mergeRegister } from '@lexical/utils';
import {
$addSharedPeer,
$createCommentNode,
@@ -13,7 +13,9 @@ import {
$removePeerId,
CommentNode,
} from '@macro-inc/lexical-core';
+import { Telemetry } from '@macro-inc/observability';
import {
+ $copyNode,
$getNodeByKey,
$getSelection,
$isRangeSelection,
@@ -26,6 +28,7 @@ import {
type LexicalEditor,
type LexicalNode,
type NodeKey,
+ type RangeSelection,
} from 'lexical';
import { v7 } from 'uuid';
@@ -109,6 +112,14 @@ export const markNodeKeysToIDs: Map<NodeKey, Array<string>> = new Map();
type CommentPluginProps = {
ops: CommentOperations;
peerId: () => string | undefined;
+ documentId?: string;
+ /** Collaborative drafts keep their selection outside the document tree. */
+ draft?: {
+ current: () => string | undefined;
+ create: (id: string, selection: RangeSelection) => boolean;
+ discard: () => void;
+ commit: () => void;
+ };
};
function registerPlugin(editor: LexicalEditor, props: CommentPluginProps) {
@@ -163,6 +174,11 @@ function registerPlugin(editor: LexicalEditor, props: CommentPluginProps) {
};
const $selectMarksAtCaret = () => {
+ const localDraft = props.draft?.current();
+ if (localDraft) {
+ markSelected([localDraft]);
+ return;
+ }
const selection = $getSelection();
if (selection === null) return;
let hasActiveIds = false;
@@ -186,39 +202,32 @@ function registerPlugin(editor: LexicalEditor, props: CommentPluginProps) {
};
return mergeRegister(
- registerNestedElementResolver<CommentNode>(
- editor,
- CommentNode,
- (from: CommentNode) => {
- const newNode = $createCommentNode({
- ids: from.getIDs(),
- threadId: from.getThreadId(),
- isDraft: from.getIsDraft(),
- });
- for (const id of newNode.getIDs()) {
- markNodeMap.get(id)?.delete(from.getKey());
- markNodeMap.get(id)?.add(newNode.getKey());
- }
- return newNode;
- },
- (from: CommentNode, to: CommentNode) => {
- to.setIsDraft(from.getIsDraft());
-
- // Merge the IDs
- const ids = from.getIDs();
- ids.forEach((id) => {
- to.addID(id);
- markNodeMap.get(id)?.delete(from.getKey());
- markNodeMap.get(id)?.add(to.getKey());
- });
-
- // Add shared peers.
- const fromPeerId = $getPeerId(from);
- if (fromPeerId) {
- $addSharedPeer(to, fromPeerId);
- }
+ // Drafts remain separate wrappers until posted. Merging a draft with a
+ // saved range gives both IDs one isDraft bit: either the composer vanishes
+ // or saving strips part of the existing comment from the shared document.
+ editor.registerNodeTransform(CommentNode, (node) => {
+ const parent = node.getParent();
+ if (
+ node.getIsDraft() ||
+ !$isCommentNode(parent) ||
+ parent.getIsDraft() ||
+ node.getChildren().some($isCommentNode)
+ )
+ return;
+
+ for (const id of parent.getIDs()) node.addID(id);
+ const parentPeerId = $getPeerId(parent);
+ if (parentPeerId) $addSharedPeer(node, parentPeerId);
+
+ const nextSiblings = node.getNextSiblings();
+ parent.insertAfter(node);
+ if (nextSiblings.length > 0) {
+ const remaining = $copyNode(parent);
+ node.insertAfter(remaining);
+ remaining.append(...nextSiblings);
}
- ),
+ if (parent.getChildrenSize() === 0) parent.remove();
+ }),
editor.registerUpdateListener(({ editorState }) => {
if (editorState.isEmpty()) return;
@@ -243,28 +252,65 @@ function registerPlugin(editor: LexicalEditor, props: CommentPluginProps) {
editor.registerCommand(
CREATE_DRAFT_COMMENT_COMMAND,
() => {
- const selection = $getSelection();
- if (
- $isRangeSelection(selection) &&
- selection.getTextContent().trim() !== ''
- ) {
+ const span = Telemetry.span('comment.draft.create');
+ if (props.documentId) span.setAttr('document.id', props.documentId);
+ try {
+ const selection = $getSelection();
+ if (
+ !$isRangeSelection(selection) ||
+ selection.getTextContent().trim() === ''
+ ) {
+ span.setAttr('comment.outcome', 'no_selection');
+ Telemetry.warn('comment.draft.rejected', {
+ 'document.id': props.documentId,
+ 'comment.reason': 'no_selection',
+ });
+ return false;
+ }
+ // Retrying Comment while a composer is open must not create a second
+ // draft with the same UI thread ID.
+ const localDraft = props.draft?.current();
+ if (localDraft) {
+ markSelected([localDraft]);
+ span.setAttr('comment.outcome', 'existing_draft');
+ return true;
+ }
+ if (draftMarkId && markNodeMap.has(draftMarkId)) {
+ markSelected([draftMarkId]);
+ span.setAttr('comment.outcome', 'existing_draft');
+ return true;
+ }
const markId = generateMarkId();
+ if (props.draft) {
+ const created = props.draft.create(markId, selection);
+ if (created) markSelected([markId]);
+ span.setAttr(
+ 'comment.outcome',
+ created ? 'created' : 'unsynced_selection'
+ );
+ return created;
+ }
draftMarkId = markId;
$wrapSelectionInMarkNode(
selection,
selection.isBackward(),
markId,
(ids) => {
- const comment = new CommentNode(ids, undefined, -1, true);
- for (const id of ids) {
- setMarkNodeMapEntry(id, comment.getKey());
- }
+ const comment = $createCommentNode({
+ ids,
+ threadId: -1,
+ isDraft: true,
+ });
+ for (const id of ids) setMarkNodeMapEntry(id, comment.getKey());
return comment;
}
);
+ span.setAttr('comment.mark_id', markId);
+ span.setAttr('comment.outcome', 'created');
return true;
+ } finally {
+ span.end();
}
- return false;
},
COMMAND_PRIORITY_EDITOR
),
@@ -272,6 +318,7 @@ function registerPlugin(editor: LexicalEditor, props: CommentPluginProps) {
editor.registerCommand(
DISCARD_DRAFT_COMMENT_COMMAND,
() => {
+ props.draft?.discard();
if (draftMarkId) {
draftMarkId = null;
}
@@ -283,6 +330,10 @@ function registerPlugin(editor: LexicalEditor, props: CommentPluginProps) {
editor.registerCommand(
DELETE_COMMENT_COMMAND,
([markId, forceDelete]) => {
+ if (props.draft?.current() === markId) {
+ props.draft.discard();
+ return true;
+ }
const markNodeKeys = markNodeMap.get(markId);
if (!markNodeKeys) return false;
@@ -323,6 +374,10 @@ function registerPlugin(editor: LexicalEditor, props: CommentPluginProps) {
editor.registerCommand(
COMMIT_COMMENT_MARK_COMMAND,
({ markId }) => {
+ if (props.draft?.current() === markId) {
+ props.draft.commit();
+ return true;
+ }
const markNodeKeys = markNodeMap.get(markId);
if (!markNodeKeys) return false;
for (const key of markNodeKeys) {
@@ -386,7 +441,9 @@ function registerPlugin(editor: LexicalEditor, props: CommentPluginProps) {
const isDraft = node.getIsDraft();
const hasServerThread = !isDraft;
const nodePeerId = $getPeerId(node);
- const isLocal = Boolean(nodePeerId && nodePeerId === peerId());
+ const isLocal =
+ id === draftMarkId ||
+ Boolean(nodePeerId && nodePeerId === peerId());
ops.add(
id,
node,
diff --git a/apps/web/src/lib/core/messages/EntityConversation.test.tsx b/apps/web/src/lib/core/messages/EntityConversation.test.tsx
index ef9e9b69ea..94a5e0b5b1 100644
--- a/apps/web/src/lib/core/messages/EntityConversation.test.tsx
+++ b/apps/web/src/lib/core/messages/EntityConversation.test.tsx
@@ -487,9 +487,32 @@ it('hides cached comments when a linked message denies access and retries the li
));
expect(view.queryAllByRole('article')).toHaveLength(0);
expect(view.queryByRole('textbox')).toBeNull();
- fireEvent.click(
- view.getByRole('button', { name: 'Could not load comments. Retry' })
- );
+ fireEvent.click(view.getByRole('button', { name: 'Retry' }));
expect(refetch).toHaveBeenCalled();
expect(mocks.refetchLink).toHaveBeenCalled();
});
+
+it.each([false, true])(
+ 'keeps a missing-parent error visible (hide empty: %s)',
+ (hideWhenEmpty) => {
+ mocks.timeline.mockReturnValue({
+ isPending: false,
+ isError: true,
+ error: new ThrownResultError([
+ { code: 'NOT_FOUND', message: 'message or parent not found' },
+ ]),
+ });
+ const view = render(() => (
+ <EntityConversation
+ parent={{ type: 'document', id: 'deleted' }}
+ canWrite
+ hideWhenEmpty={hideWhenEmpty}
+ />
+ ));
+ expect(view.getByRole('alert').textContent).toBe(
+ 'Comments are unavailable for this item.'
+ );
+ expect(view.queryByRole('button', { name: 'Retry' })).toBeNull();
+ expect(view.queryByRole('textbox')).toBeNull();
+ }
+);
diff --git a/apps/web/src/lib/core/messages/EntityConversation.tsx b/apps/web/src/lib/core/messages/EntityConversation.tsx
index c44746c3c6..e4248a5923 100644
--- a/apps/web/src/lib/core/messages/EntityConversation.tsx
+++ b/apps/web/src/lib/core/messages/EntityConversation.tsx
@@ -16,6 +16,7 @@ import { useMessageTimelineQuery } from '@queries/messages/timeline';
import { timelineMessages } from '@queries/messages/timeline-entries';
import type { MessageParent } from '@service-storage/messages';
import { createMemo, createSignal, For, Show } from 'solid-js';
+import { MessageLoadError } from './MessageLoadError';
import { MessageThread } from './MessageThread';
import type { MessageData } from './types';
@@ -90,6 +91,8 @@ export function EntityConversation(props: {
thrownResultErrorHasCode(query.error, code) ||
(code !== 'NOT_FOUND' && thrownResultErrorHasCode(target.error(), code))
);
+ const missingParent = () =>
+ thrownResultErrorHasCode(query.error, 'NOT_FOUND');
// Until the link resolves, the shared latest page would flash before the window jumps.
const messages = () =>
target.resolved() && !query.isPending && !unavailable()
@@ -107,7 +110,14 @@ export function EntityConversation(props: {
() => new Map(messages().map((message) => [message.id, message]))
);
return (
- <Show when={!props.hideWhenEmpty || messages().length > 0}>
+ <Show
+ when={
+ !props.hideWhenEmpty ||
+ messages().length > 0 ||
+ query.isError ||
+ unavailable()
+ }
+ >
<section class="mt-3 pb-12" data-entity-conversation>
<button
type="button"
@@ -127,15 +137,25 @@ export function EntityConversation(props: {
<p class="text-xs text-ink-muted">Loading comments...</p>
</Show>
<Show when={query.isError || unavailable()}>
- <button
- onClick={() => {
- fireAndForget(query.refetch(), 'entity-conversation');
- if (props.targetId)
- fireAndForget(target.refetch(), 'entity-conversation');
- }}
+ <MessageLoadError
+ retrying={query.isFetching}
+ onRetry={
+ missingParent()
+ ? undefined
+ : () => {
+ fireAndForget(query.refetch(), 'entity-conversation');
+ if (props.targetId)
+ fireAndForget(
+ target.refetch(),
+ 'entity-conversation'
+ );
+ }
+ }
>
- Could not load comments. Retry
- </button>
+ {missingParent()
+ ? 'Comments are unavailable for this item.'
+ : 'Could not load comments.'}
+ </MessageLoadError>
</Show>
<Show when={!unavailable() && query.hasNextPage}>
<button
diff --git a/apps/web/src/lib/core/messages/MessageLoadError.tsx b/apps/web/src/lib/core/messages/MessageLoadError.tsx
new file mode 100644
index 0000000000..cacc4b65ce
--- /dev/null
+++ b/apps/web/src/lib/core/messages/MessageLoadError.tsx
@@ -0,0 +1,27 @@
+import { Button } from '@ui';
+import { type JSX, Show } from 'solid-js';
+
+export function MessageLoadError(props: {
+ children: JSX.Element;
+ onRetry?: () => void;
+ retrying?: boolean;
+}) {
+ return (
+ <div
+ role="alert"
+ class="my-2 flex flex-wrap items-center gap-x-3 gap-y-2 text-xs text-ink-muted"
+ >
+ <p>{props.children}</p>
+ <Show when={props.onRetry}>
+ <Button
+ size="sm"
+ variant="secondary"
+ disabled={props.retrying}
+ onClick={props.onRetry}
+ >
+ Retry
+ </Button>
+ </Show>
+ </div>
+ );
+}
diff --git a/apps/web/src/lib/core/messages/MessageThread.tsx b/apps/web/src/lib/core/messages/MessageThread.tsx
index aaff504c4b..cb79b31622 100644
--- a/apps/web/src/lib/core/messages/MessageThread.tsx
+++ b/apps/web/src/lib/core/messages/MessageThread.tsx
@@ -9,6 +9,7 @@ import { buildMessageLink } from '@channel/Thread/utils/message-actions';
import { useUserId } from '@core/context/user';
import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';
import { fireAndForget } from '@core/util/fireAndForget';
+import { thrownResultErrorHasCode } from '@core/util/result';
import {
useDeleteMessageMutation,
usePatchMessageMutation,
@@ -24,6 +25,7 @@ import type {
MessageThread as ThreadData,
} from '@service-storage/messages';
import { createEffect, createSignal, Show } from 'solid-js';
+import { MessageLoadError } from './MessageLoadError';
import type { MessageActionHandler, MessageData } from './types';
export function threadListItem(thread: ThreadData): MessageListItem {
@@ -223,16 +225,24 @@ export function MessageThreadById(
() => props.parent,
() => props.rootId
);
+ const missing = () => thrownResultErrorHasCode(query.error, 'NOT_FOUND');
return (
<Show
when={query.isSuccess && !query.data.state.deleted_at}
fallback={
<Show when={query.isError}>
- <button
- onClick={() => fireAndForget(query.refetch(), 'message-thread')}
+ <MessageLoadError
+ retrying={query.isFetching}
+ onRetry={
+ missing()
+ ? undefined
+ : () => fireAndForget(query.refetch(), 'message-thread')
+ }
>
- Could not load thread. Retry
- </button>
+ {missing()
+ ? 'This thread is unavailable.'
+ : 'Could not load thread.'}
+ </MessageLoadError>
</Show>
}
>
diff --git a/apps/web/src/lib/queries/messages/keys.ts b/apps/web/src/lib/queries/messages/keys.ts
index 67555ac6d1..00754c4a89 100644
--- a/apps/web/src/lib/queries/messages/keys.ts
+++ b/apps/web/src/lib/queries/messages/keys.ts
@@ -11,6 +11,9 @@ export const messageKeys = createQueryKeys('messages', {
threadReplies: (parent: MessageParent, rootId: string) => ({
queryKey: [parent, rootId],
}),
+ postedComment: (documentId: string, markId: string) => ({
+ queryKey: [documentId, markId],
+ }),
resolveMessage: (parent: MessageParent, messageId: string) => ({
queryKey: [parent, messageId],
}),
diff --git a/apps/web/src/lib/queries/messages/posted-comment.test.ts b/apps/web/src/lib/queries/messages/posted-comment.test.ts
new file mode 100644
index 0000000000..3e64ec2454
--- /dev/null
+++ b/apps/web/src/lib/queries/messages/posted-comment.test.ts
@@ -0,0 +1,44 @@
+import { afterEach, expect, it, vi } from 'vitest';
+import { hasPostedComment } from './posted-comment';
+
+const list = vi.hoisted(() => vi.fn());
+vi.mock('@service-storage/messages', () => ({
+ entityMessagesClient: { list },
+}));
+vi.mock('../client', async () => {
+ const { QueryClient } = await import('@tanstack/solid-query');
+ return { queryClient: new QueryClient() };
+});
+afterEach(() => list.mockReset());
+
+it('preserves an anchor owned by a root on a later page', async () => {
+ const cursor = { created_at: '2026-01-01T00:00:00Z', id: 'earlier' };
+ list.mockResolvedValueOnce({ items: [], next_cursor: cursor });
+ list.mockResolvedValueOnce({
+ items: [{ state: { anchor: { type: 'markdown', mark_id: 'saved' } } }],
+ next_cursor: null,
+ });
+ expect(await hasPostedComment('document', 'saved')).toBe(true);
+ expect(list).toHaveBeenNthCalledWith(
+ 2,
+ { type: 'document', id: 'document' },
+ { anchored: true, limit: 100, cursor }
+ );
+});
+
+it('does not infer an orphan when a page fails', async () => {
+ list.mockRejectedValueOnce(new Error('unavailable'));
+ await expect(hasPostedComment('document', 'saved')).rejects.toThrow(
+ 'unavailable'
+ );
+});
+
+it('checks the server again after an earlier lookup found no posted comment', async () => {
+ list.mockResolvedValueOnce({ items: [], next_cursor: null });
+ expect(await hasPostedComment('document', 'new-mark')).toBe(false);
+ list.mockResolvedValueOnce({
+ items: [{ state: { anchor: { type: 'markdown', mark_id: 'new-mark' } } }],
+ next_cursor: null,
+ });
+ expect(await hasPostedComment('document', 'new-mark')).toBe(true);
+});
diff --git a/apps/web/src/lib/queries/messages/posted-comment.ts b/apps/web/src/lib/queries/messages/posted-comment.ts
new file mode 100644
index 0000000000..9b4d0e5d30
--- /dev/null
+++ b/apps/web/src/lib/queries/messages/posted-comment.ts
@@ -0,0 +1,40 @@
+import {
+ entityMessagesClient,
+ type MessageCursor,
+} from '@service-storage/messages';
+import { queryClient } from '../client';
+import { messageKeys } from './keys';
+
+/** Check the complete persisted root list, never the optimistic comment cache. */
+async function fetchPostedComment(documentId: string, markId: string) {
+ let cursor: MessageCursor | null | undefined;
+ do {
+ const page = await entityMessagesClient.list(
+ { type: 'document', id: documentId },
+ { anchored: true, limit: 100, cursor: cursor ?? undefined }
+ );
+ if (
+ page.items.some(
+ (root) =>
+ root.state.anchor?.type === 'markdown' &&
+ root.state.anchor.mark_id === markId
+ )
+ )
+ return true;
+ cursor = page.next_cursor;
+ } while (cursor);
+ return false;
+}
+
+export function postedCommentQueryOptions(documentId: string, markId: string) {
+ return {
+ queryKey: messageKeys.postedComment(documentId, markId).queryKey,
+ queryFn: () => fetchPostedComment(documentId, markId),
+ staleTime: 0,
+ retry: false,
+ };
+}
+
+export function hasPostedComment(documentId: string, markId: string) {
+ return queryClient.fetchQuery(postedCommentQueryOptions(documentId, markId));
+}
diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.md
index bfa37652b7..87cf3c7464 100644
--- a/docs/agent-guide/documents.md
+++ b/docs/agent-guide/documents.md
@@ -2741,6 +2741,33 @@ the floating **Leave a comment...** input remains available. If the discussion
becomes empty again, the section disappears. Desktop keeps the empty section
and inline input.
+Select plain text or text already covered by a comment, then press **Comment**.
+The press keeps the editor selection until the draft opens. Cancel with Escape
+or the composer's close control, then select the same text and try again: the
+new draft highlight should clear on cancellation and the existing comment
+should keep its full range. Repeat with a selection spanning paragraphs and
+with a collaborator editing another part of the document. Draft marks stay
+local until the comment is posted. Posting first saves the highlight, then the
+message. Refuse an anchor update and verify that no message is posted, the input
+survives, and cancelling lets another comment open without changing document text.
+Document typing briefly pauses during anchor publication so pending text is
+flushed before the highlight is saved. Repeat posting and starting another comment
+with both edit and comment-only access; creating a document tests the owner path.
+Also withhold a collaborator's update before posting: catch up its missing history
+before publishing the highlight, preserving both the remote text and the comment.
+Confirm the posted comment appears in a separate browser, since reopening the
+same client can restore an unsynced mark from its local snapshot. When messages
+and notifications exist but another browser has no inline highlights, check WAL
+acknowledgements and sync-service's comment-validation errors.
+Cancellation retries unconfirmed highlight cleanup after reconnect or reopening.
+An uncertain message response preserves its highlight rather than risking a saved
+comment becoming invisible.
+
+Discussion and thread loading errors use compact muted text and a separate
+**Retry** button. Retry is disabled while fetching. A missing parent or thread
+shows an unavailable message without Retry; a deleted task cannot load comments
+until it is restored. Verify that an unavailable discussion hides its composer.
+
Comments anchored to selected text open in a floating margin card on desktop and
a `Comments` drawer on touch devices. Hovering a desktop card reveals its actions
without changing the card size or header text wrapping. New comments, replies,
diff --git a/packages/collaboration/src/collab/manager-integration.test.ts b/packages/collaboration/src/collab/manager-integration.test.ts
index 12c25b7592..83e69249a2 100644
--- a/packages/collaboration/src/collab/manager-integration.test.ts
+++ b/packages/collaboration/src/collab/manager-integration.test.ts
@@ -1,10 +1,12 @@
import { Mirror, schema } from '@loro-mirror/core';
+import { Telemetry } from '@macro-inc/observability';
import { LoroDoc, type VersionVector } from 'loro-crdt';
import { createRoot } from 'solid-js';
import { describe, expect, it, vi } from 'vitest';
import { noopChatter } from './chatter';
import { createSyncEngine } from './engine';
import { createLoroManager, type LoroManager } from './manager';
+import { logTelemetry } from './telemetry';
import { TestServer } from './test-utils/test-server';
import { InMemoryWALStore, WALSyncer } from './wal';
@@ -19,6 +21,24 @@ const TEST_SCHEMA = schema({
),
});
+it('keeps the live telemetry session when a staging peer is disposed', () => {
+ const info = vi.spyOn(Telemetry, 'info').mockImplementation(() => {});
+ const live = createLoroManager(TEST_SCHEMA, {
+ documentId: 'telemetry-owner',
+ });
+ logTelemetry('telemetry-owner', 'info', 'before');
+ const attributes = info.mock.calls[0][1];
+ const staged = createLoroManager(TEST_SCHEMA, {
+ documentId: 'telemetry-owner',
+ ownsTelemetry: false,
+ });
+ staged.dispose();
+ logTelemetry('telemetry-owner', 'info', 'after');
+ expect(info.mock.calls[1][1]).toEqual(attributes);
+ live.dispose();
+ info.mockRestore();
+});
+
function paragraphTexts(manager: LoroManager<typeof TEST_SCHEMA>): string[] {
return manager.state?.state.paragraphs.map((p) => p.text) ?? [];
}
diff --git a/packages/collaboration/src/collab/manager.ts b/packages/collaboration/src/collab/manager.ts
index f7f900ffa7..3162074231 100644
--- a/packages/collaboration/src/collab/manager.ts
+++ b/packages/collaboration/src/collab/manager.ts
@@ -55,6 +55,8 @@ export type SnapshotIngest =
export type LoroManagerOptions = {
documentId: string;
+ /** Temporary peers share the live document's telemetry without owning it. */
+ ownsTelemetry?: boolean;
/** Caller-owned initial document flow, never ended by the manager. */
parentSpan?: Span;
/**
@@ -148,7 +150,9 @@ export class LoroManager<S extends GenericRootSchema = GenericRootSchema>
this.options = options;
// Stamp this doc's telemetry with the peer identity as soon as it
// exists, so every span and log record carries who we are.
- setTelemetryAttr(options.documentId, 'loro.peer_id', this._doc.peerIdStr);
+ if (options.ownsTelemetry !== false) {
+ setTelemetryAttr(options.documentId, 'loro.peer_id', this._doc.peerIdStr);
+ }
}
/** The inner LoroDoc. Only touch this if you know what you're doing. */
@@ -627,7 +631,9 @@ export class LoroManager<S extends GenericRootSchema = GenericRootSchema>
this.initListeners.clear();
this._mirror?.dispose();
this._doc.free();
- disposeTelemetryFor(this.options.documentId);
+ if (this.options.ownsTelemetry !== false) {
+ disposeTelemetryFor(this.options.documentId);
+ }
}
}
diff --git a/packages/collaboration/src/collab/source.ts b/packages/collaboration/src/collab/source.ts
index d115f14cde..1ae8afcbba 100644
--- a/packages/collaboration/src/collab/source.ts
+++ b/packages/collaboration/src/collab/source.ts
@@ -71,7 +71,10 @@ export type LiveSyncSource = {
readonly documentId: string;
readonly listen: Listen<SyncSourceEvent>;
/** Sends a batch of updates to the server. Resolves true if acked, false if timed out. */
- pushUpdate: (updates: RawUpdate[]) => Promise<boolean>;
+ pushUpdate: (
+ updates: RawUpdate[],
+ options?: { commentOnly: boolean }
+ ) => Promise<boolean>;
pushAwareness: (awareness: RawUpdate) => void;
registerPeerId: (peerId: bigint) => void;
status: Accessor<SyncSourceStatus>;
diff --git a/packages/collaboration/src/sync-service/generated/schema.bop b/packages/collaboration/src/sync-service/generated/schema.bop
index 15d60537f6..2090d574dd 100644
--- a/packages/collaboration/src/sync-service/generated/schema.bop
+++ b/packages/collaboration/src/sync-service/generated/schema.bop
@@ -17,6 +17,12 @@ union FromPeer {
5 -> struct PeerRegisterId {
uint64 peerid;
}
+ // Comment publication is validated even for editors. Older servers reject
+ // this variant rather than accepting an unchecked structural text change.
+ 6 -> struct PeerCommentUpdate {
+ byte[][] updates;
+ string id;
+ }
}
union FromRemote {
diff --git a/packages/collaboration/src/sync-service/generated/schema.ts b/packages/collaboration/src/sync-service/generated/schema.ts
index 98a8c68f60..92979b590c 100644
--- a/packages/collaboration/src/sync-service/generated/schema.ts
+++ b/packages/collaboration/src/sync-service/generated/schema.ts
@@ -17,7 +17,7 @@
import { BebopView, BebopRuntimeError, BebopRecord, BebopJson, BebopTypeGuard, Guid, GuidMap } from "bebop";
export const BEBOP_SCHEMA = new Uint8Array ([
-3, 25, 0, 0, 0, 80, 101, 101, 114, 85, 112, 100, 97, 116,
+3, 26, 0, 0, 0, 80, 101, 101, 114, 85, 112, 100, 97, 116,
101, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 117, 112, 100, 97, 116,
101, 115, 0, 242, 255, 255, 255, 1, 254, 255, 255, 255, 0,
105, 100, 0, 245, 255, 255, 255, 0, 80, 101, 101, 114, 65,
@@ -31,74 +31,78 @@ export const BEBOP_SCHEMA = new Uint8Array ([
115, 104, 111, 116, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 80, 101,
101, 114, 82, 101, 103, 105, 115, 116, 101, 114, 73, 100,
0, 1, 0, 0, 8, 0, 0, 0, 1, 1, 112, 101, 101, 114, 105,
-100, 0, 249, 255, 255, 255, 0, 70, 114, 111, 109, 80, 101,
-101, 114, 0, 3, 0, 5, 0, 0, 0, 5, 1, 0, 0, 0, 0, 2, 1, 0,
-0, 0, 3, 2, 0, 0, 0, 4, 3, 0, 0, 0, 5, 4, 0, 0, 0, 82,
-101, 109, 111, 116, 101, 73, 110, 105, 116, 105, 97, 108,
-83, 121, 110, 99, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 115, 110,
-97, 112, 115, 104, 111, 116, 0, 242, 255, 255, 255, 0,
-254, 255, 255, 255, 0, 97, 119, 97, 114, 101, 110, 101,
-115, 115, 0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0,
-82, 101, 109, 111, 116, 101, 85, 112, 100, 97, 116, 101,
-0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 117, 112, 100, 97, 116, 101,
-0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0, 82, 101,
-109, 111, 116, 101, 65, 119, 97, 114, 101, 110, 101, 115,
-115, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 97, 119, 97, 114, 101,
-110, 101, 115, 115, 0, 242, 255, 255, 255, 0, 254, 255,
-255, 255, 0, 82, 101, 109, 111, 116, 101, 83, 110, 97,
-112, 115, 104, 111, 116, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1,
+100, 0, 249, 255, 255, 255, 0, 80, 101, 101, 114, 67, 111,
+109, 109, 101, 110, 116, 85, 112, 100, 97, 116, 101, 0, 1,
+0, 0, 8, 0, 0, 0, 0, 2, 117, 112, 100, 97, 116, 101, 115,
+0, 242, 255, 255, 255, 1, 254, 255, 255, 255, 0, 105, 100,
+0, 245, 255, 255, 255, 0, 70, 114, 111, 109, 80, 101, 101,
+114, 0, 3, 0, 5, 0, 0, 0, 6, 1, 0, 0, 0, 0, 2, 1, 0, 0, 0,
+3, 2, 0, 0, 0, 4, 3, 0, 0, 0, 5, 4, 0, 0, 0, 6, 5, 0, 0,
+0, 82, 101, 109, 111, 116, 101, 73, 110, 105, 116, 105,
+97, 108, 83, 121, 110, 99, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2,
115, 110, 97, 112, 115, 104, 111, 116, 0, 242, 255, 255,
-255, 0, 254, 255, 255, 255, 0, 82, 101, 109, 111, 116,
-101, 85, 112, 100, 97, 116, 101, 65, 99, 107, 0, 1, 0, 0,
-4, 0, 0, 0, 0, 1, 105, 100, 0, 245, 255, 255, 255, 0, 82,
-101, 109, 111, 116, 101, 85, 112, 100, 97, 116, 101, 83,
-105, 110, 99, 101, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 117, 112,
-100, 97, 116, 101, 0, 242, 255, 255, 255, 0, 254, 255,
-255, 255, 0, 118, 118, 0, 242, 255, 255, 255, 0, 254, 255,
-255, 255, 0, 70, 114, 111, 109, 82, 101, 109, 111, 116,
-101, 0, 3, 0, 9, 0, 0, 0, 6, 1, 6, 0, 0, 0, 2, 7, 0, 0, 0,
-3, 8, 0, 0, 0, 4, 9, 0, 0, 0, 5, 10, 0, 0, 0, 6, 11, 0, 0,
-0, 79, 112, 101, 114, 97, 116, 105, 111, 110, 0, 1, 0, 0,
-12, 0, 0, 0, 0, 2, 117, 112, 100, 97, 116, 101, 0, 242,
-255, 255, 255, 0, 254, 255, 255, 255, 0, 116, 105, 109,
-101, 115, 116, 97, 109, 112, 0, 243, 255, 255, 255, 0, 79,
-112, 101, 114, 97, 116, 105, 111, 110, 76, 111, 103, 0, 1,
-0, 0, 4, 0, 0, 0, 0, 1, 111, 112, 101, 114, 97, 116, 105,
-111, 110, 115, 0, 242, 255, 255, 255, 0, 13, 0, 0, 0, 0,
-73, 110, 105, 116, 105, 97, 108, 105, 122, 101, 70, 114,
-111, 109, 83, 110, 97, 112, 115, 104, 111, 116, 82, 101,
-113, 117, 101, 115, 116, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1,
-115, 110, 97, 112, 115, 104, 111, 116, 0, 242, 255, 255,
-255, 0, 254, 255, 255, 255, 0, 82, 111, 117, 116, 101,
-114, 83, 117, 98, 115, 99, 114, 105, 98, 101, 0, 1, 0, 0,
-8, 0, 0, 0, 0, 2, 100, 111, 99, 73, 100, 0, 245, 255, 255,
-255, 0, 116, 111, 107, 101, 110, 0, 245, 255, 255, 255, 0,
-82, 111, 117, 116, 101, 114, 85, 110, 115, 117, 98, 115,
-99, 114, 105, 98, 101, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 100,
-111, 99, 73, 100, 0, 245, 255, 255, 255, 0, 82, 111, 117,
-116, 101, 114, 70, 114, 97, 109, 101, 0, 1, 0, 0, 8, 0, 0,
+255, 0, 254, 255, 255, 255, 0, 97, 119, 97, 114, 101, 110,
+101, 115, 115, 0, 242, 255, 255, 255, 0, 254, 255, 255,
+255, 0, 82, 101, 109, 111, 116, 101, 85, 112, 100, 97,
+116, 101, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 117, 112, 100, 97,
+116, 101, 0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0,
+82, 101, 109, 111, 116, 101, 65, 119, 97, 114, 101, 110,
+101, 115, 115, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 97, 119, 97,
+114, 101, 110, 101, 115, 115, 0, 242, 255, 255, 255, 0,
+254, 255, 255, 255, 0, 82, 101, 109, 111, 116, 101, 83,
+110, 97, 112, 115, 104, 111, 116, 0, 1, 0, 0, 4, 0, 0, 0,
+0, 1, 115, 110, 97, 112, 115, 104, 111, 116, 0, 242, 255,
+255, 255, 0, 254, 255, 255, 255, 0, 82, 101, 109, 111,
+116, 101, 85, 112, 100, 97, 116, 101, 65, 99, 107, 0, 1,
+0, 0, 4, 0, 0, 0, 0, 1, 105, 100, 0, 245, 255, 255, 255,
+0, 82, 101, 109, 111, 116, 101, 85, 112, 100, 97, 116,
+101, 83, 105, 110, 99, 101, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2,
+117, 112, 100, 97, 116, 101, 0, 242, 255, 255, 255, 0,
+254, 255, 255, 255, 0, 118, 118, 0, 242, 255, 255, 255, 0,
+254, 255, 255, 255, 0, 70, 114, 111, 109, 82, 101, 109,
+111, 116, 101, 0, 3, 0, 9, 0, 0, 0, 6, 1, 7, 0, 0, 0, 2,
+8, 0, 0, 0, 3, 9, 0, 0, 0, 4, 10, 0, 0, 0, 5, 11, 0, 0, 0,
+6, 12, 0, 0, 0, 79, 112, 101, 114, 97, 116, 105, 111, 110,
+0, 1, 0, 0, 12, 0, 0, 0, 0, 2, 117, 112, 100, 97, 116,
+101, 0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0, 116,
+105, 109, 101, 115, 116, 97, 109, 112, 0, 243, 255, 255,
+255, 0, 79, 112, 101, 114, 97, 116, 105, 111, 110, 76,
+111, 103, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 111, 112, 101,
+114, 97, 116, 105, 111, 110, 115, 0, 242, 255, 255, 255,
+0, 14, 0, 0, 0, 0, 73, 110, 105, 116, 105, 97, 108, 105,
+122, 101, 70, 114, 111, 109, 83, 110, 97, 112, 115, 104,
+111, 116, 82, 101, 113, 117, 101, 115, 116, 0, 1, 0, 0, 4,
+0, 0, 0, 0, 1, 115, 110, 97, 112, 115, 104, 111, 116, 0,
+242, 255, 255, 255, 0, 254, 255, 255, 255, 0, 82, 111,
+117, 116, 101, 114, 83, 117, 98, 115, 99, 114, 105, 98,
+101, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 100, 111, 99, 73, 100,
+0, 245, 255, 255, 255, 0, 116, 111, 107, 101, 110, 0, 245,
+255, 255, 255, 0, 82, 111, 117, 116, 101, 114, 85, 110,
+115, 117, 98, 115, 99, 114, 105, 98, 101, 0, 1, 0, 0, 4,
+0, 0, 0, 0, 1, 100, 111, 99, 73, 100, 0, 245, 255, 255,
+255, 0, 82, 111, 117, 116, 101, 114, 70, 114, 97, 109,
+101, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 100, 111, 99, 73, 100,
+0, 245, 255, 255, 255, 0, 112, 97, 121, 108, 111, 97, 100,
+0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0, 84, 111,
+82, 111, 117, 116, 101, 114, 0, 3, 0, 9, 0, 0, 0, 3, 1,
+17, 0, 0, 0, 2, 18, 0, 0, 0, 3, 19, 0, 0, 0, 82, 111, 117,
+116, 101, 114, 83, 117, 98, 115, 99, 114, 105, 98, 101,
+100, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 100, 111, 99, 73, 100,
+0, 245, 255, 255, 255, 0, 82, 111, 117, 116, 101, 114, 83,
+117, 98, 115, 99, 114, 105, 98, 101, 70, 97, 105, 108,
+101, 100, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 100, 111, 99, 73,
+100, 0, 245, 255, 255, 255, 0, 114, 101, 97, 115, 111,
+110, 0, 245, 255, 255, 255, 0, 82, 111, 117, 116, 101,
+114, 68, 111, 99, 70, 114, 97, 109, 101, 0, 1, 0, 0, 8, 0,
+0, 0, 0, 2, 100, 111, 99, 73, 100, 0, 245, 255, 255, 255,
+0, 112, 97, 121, 108, 111, 97, 100, 0, 242, 255, 255, 255,
+0, 254, 255, 255, 255, 0, 82, 111, 117, 116, 101, 114, 68,
+111, 99, 67, 108, 111, 115, 101, 100, 0, 1, 0, 0, 8, 0, 0,
0, 0, 2, 100, 111, 99, 73, 100, 0, 245, 255, 255, 255, 0,
-112, 97, 121, 108, 111, 97, 100, 0, 242, 255, 255, 255, 0,
-254, 255, 255, 255, 0, 84, 111, 82, 111, 117, 116, 101,
-114, 0, 3, 0, 9, 0, 0, 0, 3, 1, 16, 0, 0, 0, 2, 17, 0, 0,
-0, 3, 18, 0, 0, 0, 82, 111, 117, 116, 101, 114, 83, 117,
-98, 115, 99, 114, 105, 98, 101, 100, 0, 1, 0, 0, 4, 0, 0,
-0, 0, 1, 100, 111, 99, 73, 100, 0, 245, 255, 255, 255, 0,
-82, 111, 117, 116, 101, 114, 83, 117, 98, 115, 99, 114,
-105, 98, 101, 70, 97, 105, 108, 101, 100, 0, 1, 0, 0, 8,
-0, 0, 0, 0, 2, 100, 111, 99, 73, 100, 0, 245, 255, 255,
-255, 0, 114, 101, 97, 115, 111, 110, 0, 245, 255, 255,
-255, 0, 82, 111, 117, 116, 101, 114, 68, 111, 99, 70, 114,
-97, 109, 101, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 100, 111, 99,
-73, 100, 0, 245, 255, 255, 255, 0, 112, 97, 121, 108, 111,
-97, 100, 0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0,
-82, 111, 117, 116, 101, 114, 68, 111, 99, 67, 108, 111,
-115, 101, 100, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 100, 111, 99,
-73, 100, 0, 245, 255, 255, 255, 0, 114, 101, 97, 115, 111,
-110, 0, 245, 255, 255, 255, 0, 70, 114, 111, 109, 82, 111,
-117, 116, 101, 114, 0, 3, 0, 9, 0, 0, 0, 4, 1, 20, 0, 0,
-0, 2, 21, 0, 0, 0, 3, 22, 0, 0, 0, 4, 23, 0, 0, 0, 0, 0,
-0, 0
+114, 101, 97, 115, 111, 110, 0, 245, 255, 255, 255, 0, 70,
+114, 111, 109, 82, 111, 117, 116, 101, 114, 0, 3, 0, 9, 0,
+0, 0, 4, 1, 21, 0, 0, 0, 2, 22, 0, 0, 0, 3, 23, 0, 0, 0,
+4, 24, 0, 0, 0, 0, 0, 0, 0
]);
export interface IPeerUpdate extends BebopRecord {
@@ -592,12 +596,131 @@ export class PeerRegisterId implements IPeerRegisterId {
}
+export interface IPeerCommentUpdate extends BebopRecord {
+
+ readonly updates: Array<Uint8Array>;
+
+ readonly id: string;
+}
+
+export class PeerCommentUpdate implements IPeerCommentUpdate {
+ public readonly discriminator: number = 6 as 6;
+ public static readonly discriminator: number = 6 as 6;
+ public readonly updates: Array<Uint8Array>;
+ public readonly id: string;
+
+ constructor(record: IPeerCommentUpdate) {
+ this.updates = record.updates;
+ this.id = record.id;
+ }
+
+ /**
+ * Serializes the current instance into a JSON-Over-Bebop string
+ */
+ public stringify(): string {
+ return PeerCommentUpdate.encodeToJSON(this);
+ }
+
+ /**
+ * Serializes the specified object into a JSON-Over-Bebop string
+ */
+ public static encodeToJSON(record: IPeerCommentUpdate): string {
+ return JSON.stringify(record, BebopJson.replacer);
+ }
+
+ /**
+ * Validates that the runtime types of members in the current instance are correct.
+ */
+ public validateTypes(): void {
+ PeerCommentUpdate.validateCompatibility(this);
+ }
+
+ /**
+ * Validates that the specified dynamic object can become an instance of {@link PeerCommentUpdate}.
+ */
+ public static validateCompatibility(record: IPeerCommentUpdate): void {
+ BebopTypeGuard.ensureArray(record.updates, (element) => BebopTypeGuard.ensureArray(element, BebopTypeGuard.ensureUint8));
+ BebopTypeGuard.ensureString(record.id)
+ }
+
+ /**
+ * Unsafely creates an instance of {@link PeerCommentUpdate} from the specified dynamic object. No type checking is performed.
+ */
+ public static unsafeCast(record: any): IPeerCommentUpdate {
+ return new PeerCommentUpdate(record);
+ }
+
+ /**
+ * Creates a new {@link PeerCommentUpdate} instance from a JSON-Over-Bebop string. Type checking is performed.
+ */
+ public static fromJSON(json: string): IPeerCommentUpdate {
+ if (typeof json !== 'string' || json.trim().length === 0) {
+ throw new BebopRuntimeError(`PeerCommentUpdate.fromJSON: expected string`);
+ }
+ const parsed = JSON.parse(json, BebopJson.reviver);
+ PeerCommentUpdate.validateCompatibility(parsed);
+ return PeerCommentUpdate.unsafeCast(parsed);
+ }
+ public encode(): Uint8Array {
+ return PeerCommentUpdate.encode(this);
+ }
+
+ public static encode(record: IPeerCommentUpdate): Uint8Array {
+ const view = BebopView.getInstance();
+ view.startWriting();
+ PeerCommentUpdate.encodeInto(record, view);
+ return view.toArray();
+ }
+
+ public static encodeInto(record: IPeerCommentUpdate, view: BebopView): number {
+ const before = view.length;
+ {
+ const length0 = record.updates.length;
+ view.writeUint32(length0);
+ for (let i0 = 0; i0 < length0; i0++) {
+ view.writeBytes(record.updates[i0]);
+ }
+ }
+ view.writeString(record.id);
+ const after = view.length;
+ return after - before;
+ }
+
+ public static decode(buffer: Uint8Array): IPeerCommentUpdate {
+ const view = BebopView.getInstance();
+ view.startReading(buffer);
+ return PeerCommentUpdate.readFrom(view);
+ }
+
+ public static readFrom(view: BebopView): IPeerCommentUpdate {
+ let field0: Array<Uint8Array>;
+ {
+ let length0 = view.readUint32();
+ field0 = new Array<Uint8Array>(length0);
+ for (let i0 = 0; i0 < length0; i0++) {
+ let x0: Uint8Array;
+ x0 = view.readBytes();
+ field0[i0] = x0;
+ }
+ }
+ let field1: string;
+ field1 = view.readString();
+ let message: IPeerCommentUpdate = {
+ updates: field0,
+ id: field1,
+ };
+ return new PeerCommentUpdate(message);
+ }
+}
+
+
export type IFromPeerType
= { discriminator: 1, value: IPeerUpdate }
| { discriminator: 2, value: IPeerAwareness }
| { discriminator: 3, value: IPeerRequestSince }
| { discriminator: 4, value: IPeerRequestSnapshot }
- | { discriminator: 5, value: IPeerRegisterId };
+ | { discriminator: 5, value: IPeerRegisterId }
+ | { discriminator: 6, value: IPeerCommentUpdate };
export interface IFromPeer extends BebopRecord {
readonly data: IFromPeerType;
@@ -658,6 +781,14 @@ export class FromPeer implements IFromPeer {
return this.data.value instanceof PeerRegisterId;
}
+ public static fromPeerCommentUpdate(value: IPeerCommentUpdate) {
+ return new FromPeer({ discriminator: 6, value: new PeerCommentUpdate(value)});
+ }
+
+ public isPeerCommentUpdate(): this is { value: PeerCommentUpdate } & { data: Extract<IFromPeerType, { discriminator: 6 }> } {
+ return this.data.value instanceof PeerCommentUpdate;
+ }
+
/**
* Serializes the current instance into a JSON-Over-Bebop string
@@ -708,6 +839,10 @@ export class FromPeer implements IFromPeer {
PeerRegisterId.validateCompatibility(record.data.value);
break;
}
+ case 6: {
+ PeerCommentUpdate.validateCompatibility(record.data.value);
+ break;
+ }
default: {
throw new Error(`Unknown discriminator for FromPeer: ${discriminator}`);
}
@@ -735,6 +870,9 @@ export class FromPeer implements IFromPeer {
case 5: {
return new FromPeer({ discriminator: 5, value: PeerRegisterId.unsafeCast(record.value) });
}
+ case 6: {
+ return new FromPeer({ discriminator: 6, value: PeerCommentUpdate.unsafeCast(record.value) });
+ }
}
throw new BebopRuntimeError(`Failed to unsafely cast union from discriminator: ${discriminator}`);
}
@@ -782,6 +920,9 @@ export class FromPeer implements IFromPeer {
case 5:
PeerRegisterId.encodeInto(record.data.value, view);
break;
+ case 6:
+ PeerCommentUpdate.encodeInto(record.data.value, view);
+ break;
}
const end = view.length;
view.fillMessageLength(pos, end - start);
@@ -809,6 +950,8 @@ export class FromPeer implements IFromPeer {
return this.fromPeerRequestSnapshot(PeerRequestSnapshot.readFrom(view));
case 5:
return this.fromPeerRegisterId(PeerRegisterId.readFrom(view));
+ case 6:
+ return this.fromPeerCommentUpdate(PeerCommentUpdate.readFrom(view));
default:
view.index = end;
throw new BebopRuntimeError("Unrecognized discriminator while decoding FromPeer");
diff --git a/packages/collaboration/src/sync-service/source.test.ts b/packages/collaboration/src/sync-service/source.test.ts
index 704ecb7775..db9e482143 100644
--- a/packages/collaboration/src/sync-service/source.test.ts
+++ b/packages/collaboration/src/sync-service/source.test.ts
@@ -5,7 +5,7 @@ import {
WebsocketEvent,
type WebsocketEventListener,
} from '../websocket';
-import type { FromRemote, IFromPeer } from './generated/schema';
+import { FromPeer, type FromRemote, type IFromPeer } from './generated/schema';
import type { SyncSocket } from './socket';
import { SyncServiceSource, TIMEOUTS } from './source';
@@ -291,6 +291,20 @@ describe('SyncServiceSource', () => {
expect(await acked).toBe(true);
});
+ it('requests mandatory comment validation and still waits for its acknowledgement', async () => {
+ const ws = new FakeSocket();
+ const src = new SyncServiceSource(ws, 'doc1', { newId: () => 'comment-1' });
+ ws.deliver(remote.initialSync(snap, aw));
+ await src.doInitialSync();
+ const update = new Uint8Array([1]);
+ const acked = src.pushUpdate([update], { commentOnly: true });
+ expect(ws.sent).toEqual([
+ FromPeer.fromPeerCommentUpdate({ updates: [update], id: 'comment-1' }),
+ ]);
+ ws.deliver(remote.ack('comment-1'));
+ expect(await acked).toBe(true);
+ });
+
it('releases unacknowledged edits on disconnect before a fast resubscribe', async () => {
vi.useFakeTimers();
try {
diff --git a/packages/collaboration/src/sync-service/source.ts b/packages/collaboration/src/sync-service/source.ts
index c79ac3c4b3..c2f40a2cbd 100644
--- a/packages/collaboration/src/sync-service/source.ts
+++ b/packages/collaboration/src/sync-service/source.ts
@@ -171,7 +171,10 @@ export class SyncServiceSource implements LiveSyncSource {
public status: LiveSyncSource['status'] = () =>
mapToSyncStatus(this.ws.connectionState);
- public pushUpdate = async (updates: RawUpdate[]): Promise<boolean> => {
+ public pushUpdate: LiveSyncSource['pushUpdate'] = async (
+ updates,
+ options
+ ) => {
if (!this.initialSyncReceived) return false;
if (updates.length === 0) return true;
@@ -187,7 +190,11 @@ export class SyncServiceSource implements LiveSyncSource {
() => false
);
- this.ws.send(FromPeer.fromPeerUpdate({ updates, id }));
+ this.ws.send(
+ options?.commentOnly
+ ? FromPeer.fromPeerCommentUpdate({ updates, id })
+ : FromPeer.fromPeerUpdate({ updates, id })
+ );
return acked;
};
diff --git a/services/agent_harness_service/AGENTS.md b/services/agent_harness_service/AGENTS.md
index 90c06969bd..40a65d9cf3 100644
--- a/services/agent_harness_service/AGENTS.md
+++ b/services/agent_harness_service/AGENTS.md
@@ -30,6 +30,9 @@ Pulumi stacks; they do not host extra agent processes.
`ai-code-mode` get only `ExecuteCode`/`DescribeCodeTools`/`ReadCodeDocs` on
`tools/list` (`tool_service.rs`); hidden native tools stay callable. The flag
is cached per user (`tool_mode_cache.rs`).
+ Code execution's destination list in `src/code_mode.rs` also includes the
+ configured editing worker, whose comment-mark endpoint requires a scoped
+ document token; this does not grant permission to edit document content.
`src/public_mcp/analytics.rs` sends PostHog `$mcp_initialize` /
`$mcp_tool_call` events (PostHog MCP analytics schema) in the background,
with the user's team as the `team` group. At most 64 sends run at once
diff --git a/services/agent_harness_service/src/code_mode.rs b/services/agent_harness_service/src/code_mode.rs
index 5ead190153..48a795f1c5 100644
--- a/services/agent_harness_service/src/code_mode.rs
+++ b/services/agent_harness_service/src/code_mode.rs
@@ -119,6 +119,7 @@ pub fn sdk_hosts() -> anyhow::Result<BTreeMap<String, String>> {
DocumentStorageServiceCloudfrontDistributionUrl::new()?.to_string(),
),
("static-content", StaticFilePublicUrl::new()?.to_string()),
+ ("editing-worker", AiEditingWorkerUrl::new()?.to_string()),
("storage", storage.clone()),
("search", storage.clone()),
("properties", storage),
diff --git a/services/sync-service/AGENTS.md b/services/sync-service/AGENTS.md
index 8aeff35521..c587232c79 100644
--- a/services/sync-service/AGENTS.md
+++ b/services/sync-service/AGENTS.md
@@ -39,8 +39,9 @@ updates over WebSocket.
## Recipes
-- Change the wire protocol: `bebop/schema.bop` → `cd bebop && npx bebop-tools build`
- (TS bindings) → `worker-build` regenerates Rust bindings via `build.rs`.
+- Change the wire protocol with the repository-pinned Bebop generator; update
+ both service and collaboration package bindings (see README), then
+ `worker-build` regenerates Rust bindings via `build.rs`.
- Add a storage backend: `src/outbound/storage/backends/` (new file + `mod.rs`) → gate
it behind a new feature in `Cargo.toml` → wire into `src/outbound/storage.rs`.
- Add a non-document surface: `src/inbound/durable_object/surface_api.rs` →
@@ -87,7 +88,10 @@ to the requested surface. These are scoped sync JWTs, not app-session tokens.
A new write path does the same (`tests/peer_authors.test.ts`).
- `migration-test-hooks` is test-only fault injection — never enable it in a
deployed worker (see the feature's doc comment in `Cargo.toml`).
+- Provision `LEXICAL_SERVICE_AUTH_KEY` to match lexical-service before deploying; `just check-secrets <environment>` checks binding presence without reading values.
+- Deploy `PeerCommentUpdate` support before clients send it; validate these frames as comment-only for editors as well as commenters, and reject viewers.
- Never run `just deploy-dev` / `just deploy-prod` without explicit approval.
+- Wait at least five minutes after a manual worker deployment before publishing clients that require its new protocol; the CI worker job waits out Durable Objects' default 300-second code-update deferral.
## Related
diff --git a/services/sync-service/README.md b/services/sync-service/README.md
index 8a67d0377a..0baead7edf 100644
--- a/services/sync-service/README.md
+++ b/services/sync-service/README.md
@@ -48,22 +48,56 @@ mutation barrier across HTTP requests, WebSocket messages, alarms and closes.
Socket write policy allows viewers to read, document commenters to change only
comment marks, and editors to write full updates. Surface commenters cannot
-write. The HTTP API schema is generated with `just openapi`; WebSocket messages
+write. `PeerCommentUpdate` requires comment-only validation even on an editor's
+connection, so a staged annotation cannot alter document text. Deploy support
+for this message before deploying clients that send it; the dev push and
+production release workflows enforce this order while building the web app in
+parallel. The worker deployment job waits 300 seconds after deployment for
+[active Durable Objects to adopt the new code](https://developers.cloudflare.com/durable-objects/deployments/durable-objects-code-updates/).
+Manual deployments must preserve the same order and wait at least five minutes
+before publishing clients. Keep the workflow wait aligned with any future
+`code_update_strategy` change. Older workers refuse
+the unknown variant without acknowledging or applying it. The HTTP API schema
+is generated with `just openapi`; WebSocket messages
continue to use the Bebop schema. Regenerate the HTTP types from
`apps/web/src/lib/service-clients` with
`bun run orval --config orval.config.ts --project syncService`. The existing web
transport handles binary payloads and permission tokens; Orval generates shared
models only.
+## Comment validation configuration
+
+Document commenters authenticate to lexical-service with the worker secret
+`LEXICAL_SERVICE_AUTH_KEY`. Provision it in each deployed environment with the
+matching lexical-service `INTERNAL_AUTH_KEY` through `wrangler secret put`.
+Never store its value in Wrangler vars or source control. Missing or invalid
+credentials fail closed. Current clients stage anchors outside the live editor,
+wait for acknowledgement, and retain the draft instead of posting a message when
+validation fails. Older clients can create the message independently while the
+anchor remains unacknowledged in their WAL and local snapshot; another browser
+then cannot display that inline comment.
+
+CI and the `just deploy-*` recipes run `check-secrets` before migrations or
+worker deployment. This checks binding names only, not credential validity;
+validate comment-only writes after provisioning or rotating a key. Rejected
+validation spans include `document.id` and `op.id` for correlation with clients.
+
## Bebop
The bebop schema is defined in `./bebop/schema.bop`.
#### Generating typescript bindings locally
The typescript bindings are primarily used for testing and QA environemnt.
```bash
-cd bebop && npx bebop-tools build
+\cd bebop
+../../../node_modules/.bin/bebopc build
```
+Use the repository-pinned generator. Copy `schema.bop` to
+`packages/collaboration/src/sync-service/generated/schema.bop` and run
+`../../node_modules/.bin/bebopc build` from `packages/collaboration` to update
+the web bindings from the same schema. The package's `generate-sync-schema`
+command fetches the deployed schema and is unsuitable for an unreleased change.
+
#### Generating rust bindings locally
Rust bindings get automatically generated when building the worker.
The behavior for this is defined in `./build.rs`.
diff --git a/services/sync-service/bebop-schema/src/generated.rs b/services/sync-service/bebop-schema/src/generated.rs
index 7c33607d94..a6df89eff3 100644
--- a/services/sync-service/bebop-schema/src/generated.rs
+++ b/services/sync-service/bebop-schema/src/generated.rs
@@ -49,6 +49,12 @@ pub enum FromPeer<'raw> {
PeerRegisterId {
peerid: u64,
},
+
+ /// Discriminator 6
+ PeerCommentUpdate {
+ updates: ::std::vec::Vec<::bebop::SliceWrapper<'raw, u8>>,
+ id: &'raw str,
+ },
}
impl<'raw> ::bebop::SubRecord<'raw> for FromPeer<'raw> {
@@ -91,6 +97,14 @@ impl<'raw> ::bebop::SubRecord<'raw> for FromPeer<'raw> {
=> {
_peerid.serialized_size()
}
+ Self::PeerCommentUpdate {
+ updates: ref _updates,
+ id: ref _id,
+ }
+ => {
+ _updates.serialized_size() +
+ _id.serialized_size()
+ }
}
}
@@ -136,6 +150,15 @@ impl<'raw> ::bebop::SubRecord<'raw> for FromPeer<'raw> {
5u8._serialize_chained(dest)?;
_peerid._serialize_chained(dest)?;
}
+ Self::PeerCommentUpdate {
+ updates: ref _updates,
+ id: ref _id,
+ }
+ => {
+ 6u8._serialize_chained(dest)?;
+ _updates._serialize_chained(dest)?;
+ _id._serialize_chained(dest)?;
+ }
}
Ok(size)
});
@@ -182,6 +205,17 @@ impl<'raw> ::bebop::SubRecord<'raw> for FromPeer<'raw> {
peerid: v0,
}
}
+ 6 => {
+ let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+ let (read, v1) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+
+ FromPeer::PeerCommentUpdate {
+ updates: v0,
+ id: v1,
+ }
+ }
_ => {
i = len;
FromPeer::Unknown
@@ -909,6 +943,12 @@ pub mod owned {
PeerRegisterId {
peerid: u64,
},
+
+ /// Discriminator 6
+ PeerCommentUpdate {
+ updates: ::std::vec::Vec<::std::vec::Vec<u8>>,
+ id: String,
+ },
}
impl<'raw> ::core::convert::From<super::FromPeer<'raw>> for FromPeer {
@@ -957,6 +997,16 @@ pub mod owned {
peerid: _peerid,
}
}
+ super::FromPeer::PeerCommentUpdate {
+ updates: _updates,
+ id: _id,
+ }
+ => {
+ Self::PeerCommentUpdate {
+ updates: _updates.into_iter().map(|value| value.iter().map(|value| value).collect()).collect(),
+ id: _id.into(),
+ }
+ }
}
}
@@ -1001,6 +1051,14 @@ pub mod owned {
=> {
_peerid.serialized_size()
}
+ Self::PeerCommentUpdate {
+ updates: ref _updates,
+ id: ref _id,
+ }
+ => {
+ _updates.serialized_size() +
+ _id.serialized_size()
+ }
}
}
@@ -1046,6 +1104,15 @@ pub mod owned {
5u8._serialize_chained(dest)?;
_peerid._serialize_chained(dest)?;
}
+ Self::PeerCommentUpdate {
+ updates: ref _updates,
+ id: ref _id,
+ }
+ => {
+ 6u8._serialize_chained(dest)?;
+ _updates._serialize_chained(dest)?;
+ _id._serialize_chained(dest)?;
+ }
}
Ok(size)
});
@@ -1092,6 +1159,17 @@ pub mod owned {
peerid: v0,
}
}
+ 6 => {
+ let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+ let (read, v1) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
+
+ FromPeer::PeerCommentUpdate {
+ updates: v0,
+ id: v1,
+ }
+ }
_ => {
i = len;
FromPeer::Unknown
diff --git a/services/sync-service/bebop-schema/src/lib.rs b/services/sync-service/bebop-schema/src/lib.rs
index 3d93094578..42fcb14f7c 100644
--- a/services/sync-service/bebop-schema/src/lib.rs
+++ b/services/sync-service/bebop-schema/src/lib.rs
@@ -7,6 +7,7 @@ impl std::fmt::Display for FromPeer<'_> {
let m = match self {
FromPeer::Unknown => "Unknown",
FromPeer::PeerUpdate { .. } => "PeerUpdate",
+ FromPeer::PeerCommentUpdate { .. } => "PeerCommentUpdate",
FromPeer::PeerAwareness { .. } => "PeerAwareness",
FromPeer::PeerRequestSince { .. } => "PeerRequestSince",
FromPeer::PeerRequestSnapshot {} => "PeerRequestSnapshot",
diff --git a/services/sync-service/bebop/generated/schema.ts b/services/sync-service/bebop/generated/schema.ts
index fd309141cf..bc0d293d46 100644
--- a/services/sync-service/bebop/generated/schema.ts
+++ b/services/sync-service/bebop/generated/schema.ts
@@ -17,7 +17,7 @@
import { BebopView, BebopRuntimeError, BebopRecord, BebopJson, BebopTypeGuard, Guid, GuidMap } from "bebop";
export const BEBOP_SCHEMA = new Uint8Array ([
-3, 25, 0, 0, 0, 80, 101, 101, 114, 85, 112, 100, 97, 116,
+3, 26, 0, 0, 0, 80, 101, 101, 114, 85, 112, 100, 97, 116,
101, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 117, 112, 100, 97, 116,
101, 115, 0, 242, 255, 255, 255, 1, 254, 255, 255, 255, 0,
105, 100, 0, 245, 255, 255, 255, 0, 80, 101, 101, 114, 65,
@@ -31,74 +31,78 @@ export const BEBOP_SCHEMA = new Uint8Array ([
115, 104, 111, 116, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 80, 101,
101, 114, 82, 101, 103, 105, 115, 116, 101, 114, 73, 100,
0, 1, 0, 0, 8, 0, 0, 0, 1, 1, 112, 101, 101, 114, 105,
-100, 0, 249, 255, 255, 255, 0, 70, 114, 111, 109, 80, 101,
-101, 114, 0, 3, 0, 5, 0, 0, 0, 5, 1, 0, 0, 0, 0, 2, 1, 0,
-0, 0, 3, 2, 0, 0, 0, 4, 3, 0, 0, 0, 5, 4, 0, 0, 0, 82,
-101, 109, 111, 116, 101, 73, 110, 105, 116, 105, 97, 108,
-83, 121, 110, 99, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 115, 110,
-97, 112, 115, 104, 111, 116, 0, 242, 255, 255, 255, 0,
-254, 255, 255, 255, 0, 97, 119, 97, 114, 101, 110, 101,
-115, 115, 0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0,
-82, 101, 109, 111, 116, 101, 85, 112, 100, 97, 116, 101,
-0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 117, 112, 100, 97, 116, 101,
-0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0, 82, 101,
-109, 111, 116, 101, 65, 119, 97, 114, 101, 110, 101, 115,
-115, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 97, 119, 97, 114, 101,
-110, 101, 115, 115, 0, 242, 255, 255, 255, 0, 254, 255,
-255, 255, 0, 82, 101, 109, 111, 116, 101, 83, 110, 97,
-112, 115, 104, 111, 116, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1,
+100, 0, 249, 255, 255, 255, 0, 80, 101, 101, 114, 67, 111,
+109, 109, 101, 110, 116, 85, 112, 100, 97, 116, 101, 0, 1,
+0, 0, 8, 0, 0, 0, 0, 2, 117, 112, 100, 97, 116, 101, 115,
+0, 242, 255, 255, 255, 1, 254, 255, 255, 255, 0, 105, 100,
+0, 245, 255, 255, 255, 0, 70, 114, 111, 109, 80, 101, 101,
+114, 0, 3, 0, 5, 0, 0, 0, 6, 1, 0, 0, 0, 0, 2, 1, 0, 0, 0,
+3, 2, 0, 0, 0, 4, 3, 0, 0, 0, 5, 4, 0, 0, 0, 6, 5, 0, 0,
+0, 82, 101, 109, 111, 116, 101, 73, 110, 105, 116, 105,
+97, 108, 83, 121, 110, 99, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2,
115, 110, 97, 112, 115, 104, 111, 116, 0, 242, 255, 255,
-255, 0, 254, 255, 255, 255, 0, 82, 101, 109, 111, 116,
-101, 85, 112, 100, 97, 116, 101, 65, 99, 107, 0, 1, 0, 0,
-4, 0, 0, 0, 0, 1, 105, 100, 0, 245, 255, 255, 255, 0, 82,
-101, 109, 111, 116, 101, 85, 112, 100, 97, 116, 101, 83,
-105, 110, 99, 101, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 117, 112,
-100, 97, 116, 101, 0, 242, 255, 255, 255, 0, 254, 255,
-255, 255, 0, 118, 118, 0, 242, 255, 255, 255, 0, 254, 255,
-255, 255, 0, 70, 114, 111, 109, 82, 101, 109, 111, 116,
-101, 0, 3, 0, 9, 0, 0, 0, 6, 1, 6, 0, 0, 0, 2, 7, 0, 0, 0,
-3, 8, 0, 0, 0, 4, 9, 0, 0, 0, 5, 10, 0, 0, 0, 6, 11, 0, 0,
-0, 79, 112, 101, 114, 97, 116, 105, 111, 110, 0, 1, 0, 0,
-12, 0, 0, 0, 0, 2, 117, 112, 100, 97, 116, 101, 0, 242,
-255, 255, 255, 0, 254, 255, 255, 255, 0, 116, 105, 109,
-101, 115, 116, 97, 109, 112, 0, 243, 255, 255, 255, 0, 79,
-112, 101, 114, 97, 116, 105, 111, 110, 76, 111, 103, 0, 1,
-0, 0, 4, 0, 0, 0, 0, 1, 111, 112, 101, 114, 97, 116, 105,
-111, 110, 115, 0, 242, 255, 255, 255, 0, 13, 0, 0, 0, 0,
-73, 110, 105, 116, 105, 97, 108, 105, 122, 101, 70, 114,
-111, 109, 83, 110, 97, 112, 115, 104, 111, 116, 82, 101,
-113, 117, 101, 115, 116, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1,
-115, 110, 97, 112, 115, 104, 111, 116, 0, 242, 255, 255,
-255, 0, 254, 255, 255, 255, 0, 82, 111, 117, 116, 101,
-114, 83, 117, 98, 115, 99, 114, 105, 98, 101, 0, 1, 0, 0,
-8, 0, 0, 0, 0, 2, 100, 111, 99, 73, 100, 0, 245, 255, 255,
-255, 0, 116, 111, 107, 101, 110, 0, 245, 255, 255, 255, 0,
-82, 111, 117, 116, 101, 114, 85, 110, 115, 117, 98, 115,
-99, 114, 105, 98, 101, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 100,
-111, 99, 73, 100, 0, 245, 255, 255, 255, 0, 82, 111, 117,
-116, 101, 114, 70, 114, 97, 109, 101, 0, 1, 0, 0, 8, 0, 0,
+255, 0, 254, 255, 255, 255, 0, 97, 119, 97, 114, 101, 110,
+101, 115, 115, 0, 242, 255, 255, 255, 0, 254, 255, 255,
+255, 0, 82, 101, 109, 111, 116, 101, 85, 112, 100, 97,
+116, 101, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 117, 112, 100, 97,
+116, 101, 0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0,
+82, 101, 109, 111, 116, 101, 65, 119, 97, 114, 101, 110,
+101, 115, 115, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 97, 119, 97,
+114, 101, 110, 101, 115, 115, 0, 242, 255, 255, 255, 0,
+254, 255, 255, 255, 0, 82, 101, 109, 111, 116, 101, 83,
+110, 97, 112, 115, 104, 111, 116, 0, 1, 0, 0, 4, 0, 0, 0,
+0, 1, 115, 110, 97, 112, 115, 104, 111, 116, 0, 242, 255,
+255, 255, 0, 254, 255, 255, 255, 0, 82, 101, 109, 111,
+116, 101, 85, 112, 100, 97, 116, 101, 65, 99, 107, 0, 1,
+0, 0, 4, 0, 0, 0, 0, 1, 105, 100, 0, 245, 255, 255, 255,
+0, 82, 101, 109, 111, 116, 101, 85, 112, 100, 97, 116,
+101, 83, 105, 110, 99, 101, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2,
+117, 112, 100, 97, 116, 101, 0, 242, 255, 255, 255, 0,
+254, 255, 255, 255, 0, 118, 118, 0, 242, 255, 255, 255, 0,
+254, 255, 255, 255, 0, 70, 114, 111, 109, 82, 101, 109,
+111, 116, 101, 0, 3, 0, 9, 0, 0, 0, 6, 1, 7, 0, 0, 0, 2,
+8, 0, 0, 0, 3, 9, 0, 0, 0, 4, 10, 0, 0, 0, 5, 11, 0, 0, 0,
+6, 12, 0, 0, 0, 79, 112, 101, 114, 97, 116, 105, 111, 110,
+0, 1, 0, 0, 12, 0, 0, 0, 0, 2, 117, 112, 100, 97, 116,
+101, 0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0, 116,
+105, 109, 101, 115, 116, 97, 109, 112, 0, 243, 255, 255,
+255, 0, 79, 112, 101, 114, 97, 116, 105, 111, 110, 76,
+111, 103, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 111, 112, 101,
+114, 97, 116, 105, 111, 110, 115, 0, 242, 255, 255, 255,
+0, 14, 0, 0, 0, 0, 73, 110, 105, 116, 105, 97, 108, 105,
+122, 101, 70, 114, 111, 109, 83, 110, 97, 112, 115, 104,
+111, 116, 82, 101, 113, 117, 101, 115, 116, 0, 1, 0, 0, 4,
+0, 0, 0, 0, 1, 115, 110, 97, 112, 115, 104, 111, 116, 0,
+242, 255, 255, 255, 0, 254, 255, 255, 255, 0, 82, 111,
+117, 116, 101, 114, 83, 117, 98, 115, 99, 114, 105, 98,
+101, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 100, 111, 99, 73, 100,
+0, 245, 255, 255, 255, 0, 116, 111, 107, 101, 110, 0, 245,
+255, 255, 255, 0, 82, 111, 117, 116, 101, 114, 85, 110,
+115, 117, 98, 115, 99, 114, 105, 98, 101, 0, 1, 0, 0, 4,
+0, 0, 0, 0, 1, 100, 111, 99, 73, 100, 0, 245, 255, 255,
+255, 0, 82, 111, 117, 116, 101, 114, 70, 114, 97, 109,
+101, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 100, 111, 99, 73, 100,
+0, 245, 255, 255, 255, 0, 112, 97, 121, 108, 111, 97, 100,
+0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0, 84, 111,
+82, 111, 117, 116, 101, 114, 0, 3, 0, 9, 0, 0, 0, 3, 1,
+17, 0, 0, 0, 2, 18, 0, 0, 0, 3, 19, 0, 0, 0, 82, 111, 117,
+116, 101, 114, 83, 117, 98, 115, 99, 114, 105, 98, 101,
+100, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 100, 111, 99, 73, 100,
+0, 245, 255, 255, 255, 0, 82, 111, 117, 116, 101, 114, 83,
+117, 98, 115, 99, 114, 105, 98, 101, 70, 97, 105, 108,
+101, 100, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 100, 111, 99, 73,
+100, 0, 245, 255, 255, 255, 0, 114, 101, 97, 115, 111,
+110, 0, 245, 255, 255, 255, 0, 82, 111, 117, 116, 101,
+114, 68, 111, 99, 70, 114, 97, 109, 101, 0, 1, 0, 0, 8, 0,
+0, 0, 0, 2, 100, 111, 99, 73, 100, 0, 245, 255, 255, 255,
+0, 112, 97, 121, 108, 111, 97, 100, 0, 242, 255, 255, 255,
+0, 254, 255, 255, 255, 0, 82, 111, 117, 116, 101, 114, 68,
+111, 99, 67, 108, 111, 115, 101, 100, 0, 1, 0, 0, 8, 0, 0,
0, 0, 2, 100, 111, 99, 73, 100, 0, 245, 255, 255, 255, 0,
-112, 97, 121, 108, 111, 97, 100, 0, 242, 255, 255, 255, 0,
-254, 255, 255, 255, 0, 84, 111, 82, 111, 117, 116, 101,
-114, 0, 3, 0, 9, 0, 0, 0, 3, 1, 16, 0, 0, 0, 2, 17, 0, 0,
-0, 3, 18, 0, 0, 0, 82, 111, 117, 116, 101, 114, 83, 117,
-98, 115, 99, 114, 105, 98, 101, 100, 0, 1, 0, 0, 4, 0, 0,
-0, 0, 1, 100, 111, 99, 73, 100, 0, 245, 255, 255, 255, 0,
-82, 111, 117, 116, 101, 114, 83, 117, 98, 115, 99, 114,
-105, 98, 101, 70, 97, 105, 108, 101, 100, 0, 1, 0, 0, 8,
-0, 0, 0, 0, 2, 100, 111, 99, 73, 100, 0, 245, 255, 255,
-255, 0, 114, 101, 97, 115, 111, 110, 0, 245, 255, 255,
-255, 0, 82, 111, 117, 116, 101, 114, 68, 111, 99, 70, 114,
-97, 109, 101, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 100, 111, 99,
-73, 100, 0, 245, 255, 255, 255, 0, 112, 97, 121, 108, 111,
-97, 100, 0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0,
-82, 111, 117, 116, 101, 114, 68, 111, 99, 67, 108, 111,
-115, 101, 100, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 100, 111, 99,
-73, 100, 0, 245, 255, 255, 255, 0, 114, 101, 97, 115, 111,
-110, 0, 245, 255, 255, 255, 0, 70, 114, 111, 109, 82, 111,
-117, 116, 101, 114, 0, 3, 0, 9, 0, 0, 0, 4, 1, 20, 0, 0,
-0, 2, 21, 0, 0, 0, 3, 22, 0, 0, 0, 4, 23, 0, 0, 0, 0, 0,
-0, 0
+114, 101, 97, 115, 111, 110, 0, 245, 255, 255, 255, 0, 70,
+114, 111, 109, 82, 111, 117, 116, 101, 114, 0, 3, 0, 9, 0,
+0, 0, 4, 1, 21, 0, 0, 0, 2, 22, 0, 0, 0, 3, 23, 0, 0, 0,
+4, 24, 0, 0, 0, 0, 0, 0, 0
]);
export interface IPeerUpdate extends BebopRecord {
@@ -592,12 +596,131 @@ export class PeerRegisterId implements IPeerRegisterId {
}
+export interface IPeerCommentUpdate extends BebopRecord {
+
+ readonly updates: Array<Uint8Array>;
+
+ readonly id: string;
+}
+
+export class PeerCommentUpdate implements IPeerCommentUpdate {
+ public readonly discriminator: number = 6 as 6;
+ public static readonly discriminator: number = 6 as 6;
+ public readonly updates: Array<Uint8Array>;
+ public readonly id: string;
+
+ constructor(record: IPeerCommentUpdate) {
+ this.updates = record.updates;
+ this.id = record.id;
+ }
+
+ /**
+ * Serializes the current instance into a JSON-Over-Bebop string
+ */
+ public stringify(): string {
+ return PeerCommentUpdate.encodeToJSON(this);
+ }
+
+ /**
+ * Serializes the specified object into a JSON-Over-Bebop string
+ */
+ public static encodeToJSON(record: IPeerCommentUpdate): string {
+ return JSON.stringify(record, BebopJson.replacer);
+ }
+
+ /**
+ * Validates that the runtime types of members in the current instance are correct.
+ */
+ public validateTypes(): void {
+ PeerCommentUpdate.validateCompatibility(this);
+ }
+
+ /**
+ * Validates that the specified dynamic object can become an instance of {@link PeerCommentUpdate}.
+ */
+ public static validateCompatibility(record: IPeerCommentUpdate): void {
+ BebopTypeGuard.ensureArray(record.updates, (element) => BebopTypeGuard.ensureArray(element, BebopTypeGuard.ensureUint8));
+ BebopTypeGuard.ensureString(record.id)
+ }
+
+ /**
+ * Unsafely creates an instance of {@link PeerCommentUpdate} from the specified dynamic object. No type checking is performed.
+ */
+ public static unsafeCast(record: any): IPeerCommentUpdate {
+ return new PeerCommentUpdate(record);
+ }
+
+ /**
+ * Creates a new {@link PeerCommentUpdate} instance from a JSON-Over-Bebop string. Type checking is performed.
+ */
+ public static fromJSON(json: string): IPeerCommentUpdate {
+ if (typeof json !== 'string' || json.trim().length === 0) {
+ throw new BebopRuntimeError(`PeerCommentUpdate.fromJSON: expected string`);
+ }
+ const parsed = JSON.parse(json, BebopJson.reviver);
+ PeerCommentUpdate.validateCompatibility(parsed);
+ return PeerCommentUpdate.unsafeCast(parsed);
+ }
+ public encode(): Uint8Array {
+ return PeerCommentUpdate.encode(this);
+ }
+
+ public static encode(record: IPeerCommentUpdate): Uint8Array {
+ const view = BebopView.getInstance();
+ view.startWriting();
+ PeerCommentUpdate.encodeInto(record, view);
+ return view.toArray();
+ }
+
+ public static encodeInto(record: IPeerCommentUpdate, view: BebopView): number {
+ const before = view.length;
+ {
+ const length0 = record.updates.length;
+ view.writeUint32(length0);
+ for (let i0 = 0; i0 < length0; i0++) {
+ view.writeBytes(record.updates[i0]);
+ }
+ }
+ view.writeString(record.id);
+ const after = view.length;
+ return after - before;
+ }
+
+ public static decode(buffer: Uint8Array): IPeerCommentUpdate {
+ const view = BebopView.getInstance();
+ view.startReading(buffer);
+ return PeerCommentUpdate.readFrom(view);
+ }
+
+ public static readFrom(view: BebopView): IPeerCommentUpdate {
+ let field0: Array<Uint8Array>;
+ {
+ let length0 = view.readUint32();
+ field0 = new Array<Uint8Array>(length0);
+ for (let i0 = 0; i0 < length0; i0++) {
+ let x0: Uint8Array;
+ x0 = view.readBytes();
+ field0[i0] = x0;
+ }
+ }
+ let field1: string;
+ field1 = view.readString();
+ let message: IPeerCommentUpdate = {
+ updates: field0,
+ id: field1,
+ };
+ return new PeerCommentUpdate(message);
+ }
+}
+
+
export type IFromPeerType
= { discriminator: 1, value: IPeerUpdate }
| { discriminator: 2, value: IPeerAwareness }
| { discriminator: 3, value: IPeerRequestSince }
| { discriminator: 4, value: IPeerRequestSnapshot }
- | { discriminator: 5, value: IPeerRegisterId };
+ | { discriminator: 5, value: IPeerRegisterId }
+ | { discriminator: 6, value: IPeerCommentUpdate };
export interface IFromPeer extends BebopRecord {
readonly data: IFromPeerType;
@@ -658,6 +781,14 @@ export class FromPeer implements IFromPeer {
return this.data.value instanceof PeerRegisterId;
}
+ public static fromPeerCommentUpdate(value: IPeerCommentUpdate) {
+ return new FromPeer({ discriminator: 6, value: new PeerCommentUpdate(value)});
+ }
+
+ public isPeerCommentUpdate(): this is { value: PeerCommentUpdate } & { data: Extract<IFromPeerType, { discriminator: 6 }> } {
+ return this.data.value instanceof PeerCommentUpdate;
+ }
+
/**
* Serializes the current instance into a JSON-Over-Bebop string
@@ -708,6 +839,10 @@ export class FromPeer implements IFromPeer {
PeerRegisterId.validateCompatibility(record.data.value);
break;
}
+ case 6: {
+ PeerCommentUpdate.validateCompatibility(record.data.value);
+ break;
+ }
default: {
throw new Error(`Unknown discriminator for FromPeer: ${discriminator}`);
}
@@ -735,6 +870,9 @@ export class FromPeer implements IFromPeer {
case 5: {
return new FromPeer({ discriminator: 5, value: PeerRegisterId.unsafeCast(record.value) });
}
+ case 6: {
+ return new FromPeer({ discriminator: 6, value: PeerCommentUpdate.unsafeCast(record.value) });
+ }
}
throw new BebopRuntimeError(`Failed to unsafely cast union from discriminator: ${discriminator}`);
}
@@ -782,6 +920,9 @@ export class FromPeer implements IFromPeer {
case 5:
PeerRegisterId.encodeInto(record.data.value, view);
break;
+ case 6:
+ PeerCommentUpdate.encodeInto(record.data.value, view);
+ break;
}
const end = view.length;
view.fillMessageLength(pos, end - start);
@@ -809,6 +950,8 @@ export class FromPeer implements IFromPeer {
return this.fromPeerRequestSnapshot(PeerRequestSnapshot.readFrom(view));
case 5:
return this.fromPeerRegisterId(PeerRegisterId.readFrom(view));
+ case 6:
+ return this.fromPeerCommentUpdate(PeerCommentUpdate.readFrom(view));
default:
view.index = end;
throw new BebopRuntimeError("Unrecognized discriminator while decoding FromPeer");
diff --git a/services/sync-service/bebop/schema.bop b/services/sync-service/bebop/schema.bop
index 15d60537f6..2090d574dd 100644
--- a/services/sync-service/bebop/schema.bop
+++ b/services/sync-service/bebop/schema.bop
@@ -17,6 +17,12 @@ union FromPeer {
5 -> struct PeerRegisterId {
uint64 peerid;
}
+ // Comment publication is validated even for editors. Older servers reject
+ // this variant rather than accepting an unchecked structural text change.
+ 6 -> struct PeerCommentUpdate {
+ byte[][] updates;
+ string id;
+ }
}
union FromRemote {
diff --git a/services/sync-service/justfile b/services/sync-service/justfile
index 9488bf8a0c..4b675749a7 100644
--- a/services/sync-service/justfile
+++ b/services/sync-service/justfile
@@ -31,13 +31,13 @@ dev: migrate-d1-local
clean:
rm -rf node_modules .wrangler data
-deploy-dev:
+deploy-dev: (check-secrets "dev")
npx wrangler deploy --env dev
migrate-d1-playground:
CI=true npx wrangler d1 migrations apply USER_PEER_MAPPING --env playground --remote
-deploy-playground: migrate-d1-playground
+deploy-playground: (check-secrets "playground") migrate-d1-playground
npx wrangler deploy --env playground
deploy-playground-dry:
@@ -52,10 +52,14 @@ deploy-prod-dry:
migrate-d1-prod:
CI=true npx wrangler d1 migrations apply USER_PEER_MAPPING --env prod --remote
-# CI runs the same two steps (.github/workflows/deploy_sync_service.yml)
-deploy-prod: migrate-d1-prod
+# CI runs the same three steps (.github/workflows/deploy_sync_service.yml)
+deploy-prod: (check-secrets "prod") migrate-d1-prod
npx wrangler deploy --env prod
openapi:
cargo run --quiet --bin sync_service_openapi --features openapi > ../../apps/web/src/lib/service-clients/service-sync/openapi.json
\cd ../../apps/web && bunx --bun @biomejs/biome format --write src/lib/service-clients/service-sync/openapi.json
+
+# Read-only: verifies binding names without retrieving secret values.
+check-secrets environment:
+ node scripts/check-deploy-secrets.mjs {{environment}}
diff --git a/services/sync-service/scripts/check-deploy-secrets.mjs b/services/sync-service/scripts/check-deploy-secrets.mjs
new file mode 100644
index 0000000000..e6e2cb763b
--- /dev/null
+++ b/services/sync-service/scripts/check-deploy-secrets.mjs
@@ -0,0 +1,21 @@
+import { execFileSync } from "node:child_process";
+
+// Wrangler lists names and types only; secret values never enter this process.
+const environment = process.argv[2];
+if (!["dev", "prod", "playground"].includes(environment)) {
+ throw new Error("Expected environment: dev, prod, or playground");
+}
+const secrets = JSON.parse(
+ execFileSync("npx", ["wrangler", "secret", "list", "--env", environment], {
+ encoding: "utf8",
+ }),
+);
+if (
+ !Array.isArray(secrets) ||
+ !secrets.some((secret) => secret.name === "LEXICAL_SERVICE_AUTH_KEY")
+) {
+ throw new Error(
+ `Missing LEXICAL_SERVICE_AUTH_KEY in ${environment}. Provision the matching lexical-service INTERNAL_AUTH_KEY before deploying.`,
+ );
+}
+console.log(`Required comment validation secret is present in ${environment}.`);
diff --git a/services/sync-service/src/socket/protocol.rs b/services/sync-service/src/socket/protocol.rs
index e9509cd899..37efe0fee9 100644
--- a/services/sync-service/src/socket/protocol.rs
+++ b/services/sync-service/src/socket/protocol.rs
@@ -31,6 +31,7 @@ pub fn message_type(message: &FromPeer<'_>) -> &'static str {
match message {
FromPeer::PeerRegisterId { .. } => "register_id",
FromPeer::PeerUpdate { .. } => "update",
+ FromPeer::PeerCommentUpdate { .. } => "comment_update",
FromPeer::PeerAwareness { .. } => "awareness",
FromPeer::PeerRequestSince { .. } => "request_since",
FromPeer::PeerRequestSnapshot { .. } => "request_snapshot",
@@ -181,6 +182,7 @@ pub async fn process_message(
message = tracing::field::display(&message),
"process websocket message"
);
+ let comment_only = matches!(message, FromPeer::PeerCommentUpdate { .. });
match message {
// Handle peer id registration
// This registers a peer id to the owner of the current websocket
@@ -193,7 +195,7 @@ pub async fn process_message(
// Handle an incoming update from a peer
// Should extract binary update and broadcast it to all other connected peers
// Should also store the update in the operation log to be applied to the remote doc
- FromPeer::PeerUpdate { updates, id } => {
+ FromPeer::PeerUpdate { updates, id } | FromPeer::PeerCommentUpdate { updates, id } => {
telemetry.op_id = Some(id.to_string());
telemetry.update_bytes = Some(updates.iter().map(|u| u.len()).sum());
match Wsm::new(dss, sender.websocket()).write_access().await? {
@@ -202,11 +204,26 @@ pub async fn process_message(
return Ok(());
}
WriteAccess::CommentMarks => {
- if !changes_only_comment_marks(dss, document_state, &updates).await {
+ if !changes_only_comment_marks(dss, document_state, &updates, document_id, id)
+ .await
+ {
+ return Ok(());
+ }
+ }
+ WriteAccess::Full => {
+ if comment_only
+ && !changes_only_comment_marks(
+ dss,
+ document_state,
+ &updates,
+ document_id,
+ id,
+ )
+ .await
+ {
return Ok(());
}
}
- WriteAccess::Full => {}
}
let attribution = match Wsm::new(dss, sender.websocket()).edit_attribution().await {
@@ -347,10 +364,13 @@ pub async fn process_message(
/// A commenter's updates are accepted only when they change nothing but
/// comment marks. Anything that cannot be checked is refused.
+#[tracing::instrument(skip_all, fields(document.id = %document_id, op.id = %op_id))]
async fn changes_only_comment_marks(
dss: &SyncSession,
document_state: &DocumentState,
updates: &[SliceWrapper<'_, u8>],
+ document_id: &str,
+ op_id: &str,
) -> bool {
let updates: Vec<&[u8]> = updates.iter().map(|update| &update[..]).collect();
let change = match document_state.root_change(&updates) {
diff --git a/services/sync-service/tests/check-deploy-secrets.test.ts b/services/sync-service/tests/check-deploy-secrets.test.ts
new file mode 100644
index 0000000000..9db86bae19
--- /dev/null
+++ b/services/sync-service/tests/check-deploy-secrets.test.ts
@@ -0,0 +1,44 @@
+import { afterEach, beforeEach, expect, test, vi } from "vitest";
+
+const { listSecrets } = vi.hoisted(() => ({ listSecrets: vi.fn() }));
+vi.mock("node:child_process", () => ({ execFileSync: listSecrets }));
+const originalArguments = process.argv;
+beforeEach(() => {
+ vi.resetModules();
+ process.argv = ["node", "check-deploy-secrets.mjs", "prod"];
+ vi.spyOn(console, "log").mockImplementation(() => {});
+});
+afterEach(() => {
+ process.argv = originalArguments;
+ vi.restoreAllMocks();
+});
+
+test("blocks deployment when commenter validation has no credential", async () => {
+ listSecrets.mockReturnValue(
+ JSON.stringify([{ name: "SYNC_SERVICE_KEY_PROD" }]),
+ );
+ await expect(import("../scripts/check-deploy-secrets.mjs")).rejects.toThrow(
+ "Missing LEXICAL_SERVICE_AUTH_KEY",
+ );
+});
+
+test("accepts the required binding without reading secret values", async () => {
+ listSecrets.mockReturnValue(
+ JSON.stringify([{ name: "LEXICAL_SERVICE_AUTH_KEY", type: "secret_text" }]),
+ );
+ await import("../scripts/check-deploy-secrets.mjs");
+ expect(listSecrets).toHaveBeenLastCalledWith(
+ "npx",
+ ["wrangler", "secret", "list", "--env", "prod"],
+ { encoding: "utf8" },
+ );
+});
+
+test("fails closed if Cloudflare cannot list the bindings", async () => {
+ listSecrets.mockImplementation(() => {
+ throw new Error("List unavailable");
+ });
+ await expect(import("../scripts/check-deploy-secrets.mjs")).rejects.toThrow(
+ "List unavailable",
+ );
+});
diff --git a/services/sync-service/tests/comment_marks.test.ts b/services/sync-service/tests/comment_marks.test.ts
index 1980d70945..c60cd8fb69 100644
--- a/services/sync-service/tests/comment_marks.test.ts
+++ b/services/sync-service/tests/comment_marks.test.ts
@@ -60,12 +60,12 @@ afterAll(async () => {
);
});
-async function seed(verdict: Verdict) {
+async function seed(verdict: Verdict, instance = mf) {
const id = crypto.randomUUID();
verdicts.set(id, verdict);
const doc = new LoroDoc();
doc.getMap("root").set("title", id);
- const response = await mf.dispatchFetch(
+ const response = await instance.dispatchFetch(
`http://localhost/document/${id}/initialize`,
{
method: "POST",
@@ -79,7 +79,11 @@ async function seed(verdict: Verdict) {
return id;
}
-async function connect(id: string, access: "comment" | "edit") {
+async function connect(
+ id: string,
+ access: "view" | "comment" | "edit",
+ instance = mf,
+) {
const token = jwt.sign(
{
document_id: id,
@@ -89,7 +93,7 @@ async function connect(id: string, access: "comment" | "edit") {
},
"local",
);
- const response = await mf.dispatchFetch(
+ const response = await instance.dispatchFetch(
`http://localhost/document/${id}/connect?token=${token}`,
{
headers: { Upgrade: "websocket" },
@@ -114,16 +118,18 @@ type Client = Awaited<ReturnType<typeof connect>>;
async function send(
client: Client,
write: (doc: LoroDoc) => void,
+ commentOnly = false,
): Promise<boolean> {
const from = client.doc.oplogVersion();
write(client.doc);
client.doc.commit();
const id = crypto.randomUUID();
+ const update = { updates: [client.doc.export({ mode: "update", from })], id };
client.send(
- FromPeer.fromPeerUpdate({
- updates: [client.doc.export({ mode: "update", from })],
- id,
- }).encode(),
+ (commentOnly
+ ? FromPeer.fromPeerCommentUpdate(update)
+ : FromPeer.fromPeerUpdate(update)
+ ).encode(),
);
try {
for (;;) {
@@ -137,8 +143,8 @@ async function send(
}
}
-async function stored(id: string) {
- const response = await mf.dispatchFetch(
+async function stored(id: string, instance = mf) {
+ const response = await instance.dispatchFetch(
`http://localhost/document/${id}/raw`,
{
headers: { "x-internal-auth-key": "local" },
@@ -216,3 +222,69 @@ test("an editor update is stored without a check", async () => {
expect(checks).toEqual([]);
expect(await stored(id)).toEqual({ root: { title: id, body: "rewritten" } });
});
+
+test.each(["comment", "edit"] as const)(
+ "staged comment publication validates %s access",
+ async (access) => {
+ const id = await seed("not_comment_only");
+ const client = await connect(id, access);
+ expect(
+ await send(
+ client,
+ (doc) => doc.getMap("root").set("body", "moved text"),
+ true,
+ ),
+ ).toBe(false);
+ expect(await stored(id)).toEqual({ root: { title: id } });
+ const accepted = await seed("comment_only");
+ const fresh = await connect(accepted, access);
+ expect(
+ await send(fresh, (doc) => doc.getMap("root").set("mark", "saved"), true),
+ ).toBe(true);
+ expect(await stored(accepted)).toEqual({
+ root: { title: accepted, mark: "saved" },
+ });
+ },
+);
+
+test("staged publication grants no write access to viewers", async () => {
+ const id = await seed("comment_only");
+ const viewer = await connect(id, "view");
+ expect(
+ await send(viewer, (doc) => doc.getMap("root").set("mark", "saved"), true),
+ ).toBe(false);
+ expect(await stored(id)).toEqual({ root: { title: id } });
+});
+
+// A missing deployment binding must never let commenters edit body content.
+test("missing lexical credentials leave commenter anchors local and editors writable", async () => {
+ const address = server.address();
+ if (!address || typeof address === "string")
+ throw new Error("Missing stand-in address");
+ const missingKey = await setupMiniflare({
+ lexicalServiceUrl: `http://127.0.0.1:${address.port}`,
+ lexicalServiceAuthKey: null,
+ });
+ try {
+ const id = await seed("comment_only", missingKey);
+ const commenter = await connect(id, "comment", missingKey);
+ expect(
+ await send(commenter, (doc) =>
+ doc.getMap("root").set("mark", "local-mark"),
+ ),
+ ).toBe(false);
+ expect(commenter.doc.toJSON()).toEqual({
+ root: { title: id, mark: "local-mark" },
+ });
+ expect(await stored(id, missingKey)).toEqual({ root: { title: id } });
+ const fresh = await connect(id, "edit", missingKey);
+ expect(fresh.doc.toJSON()).toEqual({ root: { title: id } });
+ expect(
+ await send(fresh, (doc) =>
+ doc.getMap("root").set("body", "editor change"),
+ ),
+ ).toBe(true);
+ } finally {
+ await missingKey.dispose();
+ }
+});
diff --git a/services/sync-service/tests/utils.ts b/services/sync-service/tests/utils.ts
index 9c42968a3f..bff5244951 100644
--- a/services/sync-service/tests/utils.ts
+++ b/services/sync-service/tests/utils.ts
@@ -37,6 +37,7 @@ export async function setupMiniflare(
migrate?: boolean;
dssUrl?: string;
lexicalServiceUrl?: string;
+ lexicalServiceAuthKey?: string | null;
fetchMock?: MiniflareOptions['fetchMock'];
} = {},
) {
@@ -78,7 +79,7 @@ export async function setupMiniflare(
local:true,
...(options.dssUrl ? { DSS_URL: options.dssUrl, DSS_INTERNAL_AUTH_KEY: "local" } : {}),
...(options.lexicalServiceUrl
- ? { LEXICAL_SERVICE_URL: options.lexicalServiceUrl, LEXICAL_SERVICE_AUTH_KEY: "lexical-key" }
+ ? { LEXICAL_SERVICE_URL: options.lexicalServiceUrl, ...(options.lexicalServiceAuthKey === null ? {} : { LEXICAL_SERVICE_AUTH_KEY: options.lexicalServiceAuthKey ?? "lexical-key" }) }
: {}),
},
compatibilityDate: '2025-03-05'
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_on_push.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_on_push.rs
index 84d071d259..ded12d8c2f 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_on_push.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_on_push.rs
@@ -1,6 +1,6 @@
//! `Deploy on Push` — the single push-to-main dev deploy pipeline. Mirrors the
-//! production release flow: cloud storage first, then the sync service and web
-//! app, with every stage deploying unconditionally. The web app *builds* in
+//! production release flow: cloud storage first, then the sync service, then the
+//! web app, with every stage deploying unconditionally. The web app *builds* in
//! parallel with the backend; only its upload waits, so the frontend still
//! goes live last.
//!
@@ -33,6 +33,9 @@
use anyhow::Result;
use gh_workflow::{Concurrency, Event, Expression, Job, Push, Workflow};
+#[cfg(test)]
+mod test;
+
/// Prepended to the generated YAML, under the "do not edit" header. The
/// no-gating decision is the single most likely thing for someone to try to
/// "optimize" while reading the workflow file rather than this module, so the
@@ -174,13 +177,14 @@ fn build_web_app() -> Job {
.uses("./.github/workflows/build_web_app.yml")
}
-/// Same ordering rationale as [`deploy_sync_service`]; uploads the dist that
-/// [`build_web_app`] left in this run.
+/// Publish only after the worker supports the frontend's sync protocol. The
+/// build remains parallel, but a failed worker deploy must block new clients.
fn deploy_web_app() -> Job {
Job::default()
.name("Deploy Web App")
.needs(vec![
"deploy-cloud-storage".to_string(),
+ "deploy-sync-service".to_string(),
"build-web-app".to_string(),
])
.uses("./.github/workflows/deploy_web_app.yml")
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_on_push/test.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_on_push/test.rs
new file mode 100644
index 0000000000..da13575801
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_on_push/test.rs
@@ -0,0 +1,60 @@
+use super::*;
+
+#[test]
+fn web_publication_waits_for_sync_protocol_support() -> Result<()> {
+ let dev = crate::workflows::render_patched(deploy_on_push, patch)?;
+ let prod = std::fs::read_to_string(
+ xtask_paths::repo_root().join(".github/workflows/release-production.yml"),
+ )?;
+
+ for (environment, yaml, web_job, build_job) in [
+ ("dev", dev, "deploy-web-app", "build-web-app"),
+ ("prod", prod, "deploy", "build"),
+ ] {
+ let workflow: serde_yaml::Value = serde_yaml::from_str(&yaml)?;
+ let jobs = &workflow["jobs"];
+ let needs = jobs[web_job]["needs"].as_sequence().expect("dependencies");
+ assert!(
+ needs.contains(&serde_yaml::Value::from("deploy-sync-service")),
+ "{environment} must deploy sync-service before publishing the web app"
+ );
+ assert!(needs.contains(&serde_yaml::Value::from(build_job)));
+ assert!(
+ jobs[web_job]["if"].is_null(),
+ "failed sync deployment must prevent web publication"
+ );
+ assert!(
+ jobs[build_job]["needs"].is_null(),
+ "the web build should still run in parallel with deployment"
+ );
+ }
+ Ok(())
+}
+
+#[test]
+fn sync_deployment_waits_for_active_objects_before_unblocking_clients() -> Result<()> {
+ let yaml = crate::workflows::render_patched(
+ crate::workflows::deploy_sync_service::deploy_sync_service,
+ crate::workflows::deploy_sync_service::patch,
+ )?;
+ let workflow: serde_yaml::Value = serde_yaml::from_str(&yaml)?;
+ let steps = workflow["jobs"]["deploy"]["steps"]
+ .as_sequence()
+ .expect("deployment steps");
+ let deploy = steps
+ .iter()
+ .position(|step| {
+ step["run"]
+ .as_str()
+ .is_some_and(|command| command.starts_with("npx wrangler deploy --env "))
+ })
+ .expect("worker deployment");
+ let wait = steps
+ .iter()
+ .position(|step| step["run"].as_str() == Some("sleep 300"))
+ .expect("the worker job must wait out the default code-update deferral");
+ assert!(deploy < wait);
+ assert!(steps[wait]["if"].is_null());
+ assert!(steps[wait]["continue-on-error"].is_null());
+ Ok(())
+}
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_sync_service.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_sync_service.rs
index 2ace636ef7..6a99669fce 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_sync_service.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/deploy_sync_service.rs
@@ -3,7 +3,7 @@
//! Unlike [`crate::workflows::deploy_ai_editing_worker`] this worker is Rust, so
//! the job needs a toolchain and the wasm target. Call/dispatch-only: push
//! deploys to dev come through [`crate::workflows::deploy_on_push`] (which owns
-//! the path gating) and prod deploys through `release-production`. Generated
+//! deployment ordering) and prod deploys through `release-production`. Generated
//! into `deploy_sync_service.yml`.
use anyhow::Result;
@@ -77,8 +77,10 @@ fn deploy() -> Job {
.add_step(add_wasm_target())
.add_step(setup_node())
.add_step(install_deps())
+ .add_step(check_secrets())
.add_step(apply_d1_migrations())
.add_step(deploy_step())
+ .add_step(wait_for_active_objects())
}
/// [`steps::setup_rust_light`] installs the channel explicitly, which skips
@@ -101,6 +103,17 @@ fn install_deps() -> Step<Run> {
.working_directory(xtask_paths::repo_dir!("services/sync-service"))
}
+/// Fail before migrations or deployment if commenter validation cannot authenticate.
+fn check_secrets() -> Step<Run> {
+ Step::new("Check required secrets")
+ .run(format!(
+ "node scripts/check-deploy-secrets.mjs {ENVIRONMENT}"
+ ))
+ .working_directory(xtask_paths::repo_dir!("services/sync-service"))
+ .add_env(("CLOUDFLARE_API_TOKEN", vars::CLOUDFLARE_API_TOKEN))
+ .add_env(("CLOUDFLARE_ACCOUNT_ID", vars::CLOUDFLARE_ACCOUNT_ID))
+}
+
/// Migrate first: new code against an already-migrated D1 is safe, the reverse
/// is a live error.
fn apply_d1_migrations() -> Step<Run> {
@@ -121,3 +134,10 @@ fn deploy_step() -> Step<Run> {
.add_env(("CLOUDFLARE_API_TOKEN", vars::CLOUDFLARE_API_TOKEN))
.add_env(("CLOUDFLARE_ACCOUNT_ID", vars::CLOUDFLARE_ACCOUNT_ID))
}
+
+/// Active Durable Objects can defer code adoption for 300 seconds by default.
+/// Keep dependent clients behind that window without forcing sessions to reset
+/// early. Keep this delay aligned with any future `code_update_strategy` change.
+fn wait_for_active_objects() -> Step<Run> {
+ Step::new("Wait for active Durable Objects to update").run("sleep 300")
+}