From 09b62c69bdedc26bd274f478402b598371d00ad2 Mon Sep 17 00:00:00 2001 From: Jan-Henrik Bruhn Date: Fri, 10 Oct 2025 16:54:40 +0200 Subject: [PATCH] fix: clear graph editor when no document is active MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes an issue where nodes from a previous document would persist when creating a new document after closing all documents. The problem occurred because: 1. When all documents were closed (activeDocumentId becomes null), the graph store wasn't being cleared 2. When a new document was created, stale data from the old document could contaminate the new document through race conditions Changes: - Clear nodes and edges from graph store when activeDocumentId is null - Add safeguard to prevent saving stale graph data to newly created documents before they've been fully loaded - Maintain proper state tracking to prevent cross-document contamination 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/stores/workspace/useActiveDocument.ts | 32 +++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/stores/workspace/useActiveDocument.ts b/src/stores/workspace/useActiveDocument.ts index b41e5c3..307c31c 100644 --- a/src/stores/workspace/useActiveDocument.ts +++ b/src/stores/workspace/useActiveDocument.ts @@ -81,6 +81,31 @@ export function useActiveDocument() { setTimeout(() => { isLoadingRef.current = false; }, 100); + } else if (!activeDocumentId) { + // Clear graph store when no document is active + console.log('No active document, clearing graph editor'); + + // Set loading flag to prevent dirty marking during clear + isLoadingRef.current = true; + lastLoadedDocIdRef.current = null; + + setNodes([]); + setEdges([]); + // Note: We keep nodeTypes and edgeTypes so they're available for new documents + + // Clear the last synced state + lastSyncedStateRef.current = { + documentId: null, + nodes: [], + edges: [], + nodeTypes: [], + edgeTypes: [], + }; + + // Clear loading flag after a brief delay + setTimeout(() => { + isLoadingRef.current = false; + }, 100); } }, [activeDocumentId, activeDocument, documents, setNodes, setEdges, setNodeTypes, setEdgeTypes]); @@ -101,6 +126,13 @@ export function useActiveDocument() { return; } + // CRITICAL: Prevent saving stale data to new documents + // If the last loaded document doesn't match the active document, skip this check + if (lastLoadedDocIdRef.current !== activeDocumentId) { + console.log(`Skipping dirty check - document hasn't been loaded yet (last loaded: ${lastLoadedDocIdRef.current}, active: ${activeDocumentId})`); + return; + } + // Mark document as dirty when graph changes const hasChanges = JSON.stringify(graphNodes) !== JSON.stringify(lastSyncedStateRef.current.nodes) ||