fix: wait for network adapter to be ready before creating document

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 <noreply@anthropic.com>
This commit is contained in:
Jeff Emmett 2025-11-16 22:07:24 -07:00
parent 06aa537e32
commit f1acd09a4e
1 changed files with 9 additions and 3 deletions

View File

@ -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(() => {