From e70cba82b4f707f17981128efde485a54413b770 Mon Sep 17 00:00:00 2001 From: Jeff Emmett Date: Sun, 16 Nov 2025 22:07:24 -0700 Subject: [PATCH] fix: wait for network adapter to be ready before creating document MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Added await for adapter.whenReady() to ensure WebSocket connection is established before creating the Automerge document. This should enable the Automerge Repo to properly send binary sync messages when document changes occur. Changes: - Extract adapter from repo initialization to access it - Wait for adapter.whenReady() before creating document - Update useEffect dependencies to include adapter and workerUrl 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/automerge/useAutomergeSyncRepo.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/automerge/useAutomergeSyncRepo.ts b/src/automerge/useAutomergeSyncRepo.ts index 567ead4..767ea45 100644 --- a/src/automerge/useAutomergeSyncRepo.ts +++ b/src/automerge/useAutomergeSyncRepo.ts @@ -100,7 +100,7 @@ export function useAutomergeSync(config: AutomergeSyncConfig): TLStoreWithStatus return }, []) - const [repo] = useState(() => { + const [repo, adapter] = useState(() => { const adapter = new CloudflareNetworkAdapter(workerUrl, roomId, applyJsonSyncData) const repo = new Repo({ network: [adapter], @@ -113,7 +113,7 @@ export function useAutomergeSync(config: AutomergeSyncConfig): TLStoreWithStatus console.log('🔄 CloudflareAdapter received message from network:', msg.type) }) - return repo + return [repo, adapter] as const }) // Initialize Automerge document handle @@ -124,6 +124,12 @@ export function useAutomergeSync(config: AutomergeSyncConfig): TLStoreWithStatus try { console.log("🔌 Initializing Automerge Repo with NetworkAdapter for room:", roomId) + // CRITICAL: Wait for the network adapter to be ready before creating document + // This ensures the WebSocket connection is established for sync + console.log("⏳ Waiting for network adapter to be ready...") + await adapter.whenReady() + console.log("✅ Network adapter is ready, WebSocket connected") + if (mounted) { // CRITICAL: Create a new Automerge document (repo.create() generates a proper document ID) // Each client gets its own document, but Automerge sync protocol keeps them in sync @@ -255,7 +261,7 @@ export function useAutomergeSync(config: AutomergeSyncConfig): TLStoreWithStatus return () => { mounted = false } - }, [repo, roomId]) + }, [repo, roomId, adapter, workerUrl]) // Track mouse state to prevent persistence during active mouse interactions useEffect(() => {