Repository navigation
[EXPERIMENTAL — DO NOT MERGE] perf: make Vue nodes usable on large graphs - #15016
benjcooley wants to merge 10 commits into
Conversation
`getAllNodes()` rebuilds the full node layout map on every access, which is wasteful for callers that only need a count, and unusable as a cache key for callers that need to know whether geometry changed. - `nodeCount` reports the tracked node count without materialising layouts. - `layoutVersion` exposes the existing mutation counter for use as a cache key. Deliberately a plain number rather than a ref: consumers poll it to decide whether a derived structure is stale, and must not re-run reactively on every mutation. Split out so the consumers that follow can be reverted independently.
The minimap re-derived the whole graph every animation frame. On a 3000-node workflow this dominated frame time; profiling a continuous pan showed ~62% of samples in minimap work, more than the node DOM itself. Four causes, all per-frame: - `LayoutStoreDataSource.getNodes()` ran `_nodes.find()` inside a loop over every node, i.e. O(n^2) - ~9M comparisons per frame at 3000 nodes and ~64M at 8000. Use the graph's own id index instead. - `checkForChangesInternal()` called `JSON.stringify(graph.links)` to detect rewires, serialising every link each frame. Replace with an allocation-free rolling digest over node geometry and link endpoints. - A single render pass builds the data source several times (bounds, node rects, link endpoints). Memoise per instance; sources are already constructed per pass. - Change detection ran on `useRafFn`. Structural edits already trigger a redraw via graph event hooks, so the loop only needs to catch drags and resizes, which emit no event. Poll at 100ms instead - the minimap is an approximate overview and need not track a drag frame by frame. Digests can in principle collide and drop a single refresh; the next change re-syncs, which is acceptable for an overview pane.
Adds a position query for "which nodes intersect this rect", backed by a QuadTree that is rebuilt only when layoutVersion changes. Panning over a static graph then costs a tree query rather than a scan of every node. Deliberately does not reuse the shared SpatialIndexManager. That index is built on QUADTREE_CONFIG.DEFAULT_BOUNDS, a fixed +/-10000 box, and QuadTree.insert silently drops anything not fully contained (its return value is discarded, and update() cannot recover an item that was never inserted). Real workflows outgrow that box - a graph built by stamping the default workflow across empty space spans tens of thousands of units on each axis - so most nodes would be missing from query results. This index sizes its root to the graph's own extent instead. Nodes with no layout yet cannot be indexed, so they are reported by every query; callers must mount them in order for them to measure themselves. Unused until the next commit wires it up, so the two can be reverted independently.
GraphCanvas rendered every node in the graph, so a large workflow paid full DOM cost for nodes nobody could see. Filter the v-for down to nodes intersecting an expanded viewport rect. Measured on a graph built by stamping the default workflow across empty space, panning at a working zoom: 8000 nodes: 1790ms -> 133ms median frame, 606k -> 5.3k DOM elements 3000 nodes: 272ms -> 49ms median frame Design notes: - The mounted set is derived from a throttled sample of the camera, not a reactive dependency on it. TransformPane deliberately writes its transform via direct DOM mutation to avoid re-diffing every node each frame; binding the node list to the camera would reintroduce exactly that cost. - Nodes mount as soon as they enter and unmount after a delay, so nodes oscillating on the viewport edge do not thrash. Because that delay only elapses once panning stops, a long continuous pan would otherwise accumulate everything swept over; an eager prune bounds the set once it outgrows what is visible. - Selected nodes are never culled, so unmounting cannot interrupt a drag or resize in progress. - Culls by unmounting, never by `display: none`. The shared ResizeObserver has no zero-size guard, so a hidden node would write 0x0 bounds back through layoutStore into `liteNode.size` and corrupt the saved workflow. Note this does not help when the whole graph is on screen. `min_scale` is 0.1, but loadGraphData's fit-view bypasses that clamp, so a freshly loaded large workflow starts fully visible with nothing to cull.
The culling margin was a fraction of the viewport, which is screen-space, so dividing it by the zoom made it cover more and more of the graph as the user zoomed out. At minimum zoom it more than doubled the queried area and mounted far more nodes than a pan could ever reach before the next recompute - 2012 of 3003 nodes on a large graph. Cap it at roughly five node widths, which is ample lead time at any zoom. Working zoom is unaffected: the cap only binds once the ratio exceeds it, which happens below roughly 0.35 zoom. Panning a 3000-node graph at minimum zoom: 141.2ms -> 78.7ms median frame, 2012 -> 910 nodes mounted This does not help when the whole graph is already on screen; no margin change can cull nodes that are genuinely in view.
Litegraph already stops drawing node detail once text would be too small to read, falling back to plain filled rectangles and skipping text, badges and shadows. Vue nodes rendered full DOM trees at every zoom, so a graph opened zoomed out paid for thousands of complete component trees to draw what amounts to coloured boxes. Mirror litegraph's own threshold (min_font_size_for_lod, adjusted for DPR) so both renderers simplify at exactly the same zoom and the existing setting keeps working in either mode. Below it, each node renders as a single positioned div instead of a component tree. 3000-node graph at its opening zoom: 227,787 -> 2,786 DOM elements. Also releases the slot-sync wait while simplified. Link rendering waits for nodes to report slot positions measured from the DOM; simplified nodes have no slot elements, so on a graph large enough to open below the threshold that measurement never arrived and links stayed hidden for as long as the view stayed zoomed out. Links now fall back to positions derived from node bounds, which is what the zoomed-out view wants anyway.
The previous commit rendered a positioned div per node while zoomed out past legibility. That still cost an element per node - 3,003 of them on a large graph - and profiling showed the browser spending most of a frame on layout, paint and compositing for elements that amount to filled rectangles. Draw them on the canvas instead, which is what the renderer already does for its own low-quality pass, and mount nothing. Vue nodes are only worth their cost once their contents are legible. Slot metrics are still computed for every node so hit-testing and link endpoints stay correct; only the early return that skips painting moves. 3000-node graph at its opening zoom: 227,787 -> 417 DOM elements, the latter being application chrome rather than nodes.
This reverts commit 93f7e4d. Drawing the simplified nodes through litegraph's own node pass means the Vue renderer cannot render a zoomed-out graph without litegraph present, which is the opposite of the direction this renderer is heading. Links already have the right shape - a Vue-owned canvas element with the drawing itself living renderer-side in CanvasPathRenderer - so the simplified node pass should follow that pattern instead.
The previous approach mounted a div per node while zoomed out past legibility, which still cost an element per node - 3,003 of them on a large graph - and profiling showed most of a frame going to layout, paint and compositing for what amounts to filled rectangles. Draw them onto a canvas instead. The drawing lives in nodeBoxRenderer, which takes a 2D context and a set of bounds and has no graph or canvas renderer dependencies, mirroring how CanvasPathRenderer already owns link drawing. A zoomed-out graph therefore does not depend on the legacy canvas renderer being present, which an earlier attempt at this did. Node bounds come from the culling index, which already keeps them cached against layoutVersion, so redrawing each frame rebuilds nothing. 3000-node graph at its opening zoom: 227,787 -> 418 DOM elements, the remainder being application chrome rather than nodes.
Captures what was changed, what each change bought, how it was measured, and what is deliberately left - including the constraints that shaped the implementation, which are not obvious from the code alone.
|
🎉 Thank you for your contribution, we really appreciate it! 🎉 Like many open source projects, we require contributors to sign our Contributor License Agreement (CLA). A CLA makes the ownership of contributions explicit, so contributors and the project share a clear understanding of how the code can be used. By signing, you:
CLAs are standard practice across major open source projects including those under the Apache Software Foundation and the Linux Foundation. Ours is based on the Apache Software Foundation's CLA. Most importantly, it would enable us to relicense the project under a more permissive license in the future, giving the project and its community greater flexibility. ✍ To sign, please post a new comment on this PR with exactly the following text: ✍ I have read and agree to the Contributor License Agreement You can retrigger this bot by commenting recheck in this Pull Request. Posted by the CLA Assistant Lite bot. |
🎭 Playwright: ❌ 1790 passed, 3 failed · 5 flaky❌ Failed Tests📊 Browser Reports
🎨 Storybook: ✅ Built — View Storybook📦 Bundle: 8.7 MB gzip 🔴 +4.83 kBDetailsSummary
Category Glance App Entry Points — 3.67 kB (baseline 3.67 kB) • ⚪ 0 BMain entry bundles and manifests
Status: 1 added / 1 removed Graph Workspace — 1.37 MB (baseline 1.36 MB) • 🔴 +12.3 kBGraph editor runtime, canvas, workflow orchestration
Status: 2 added / 2 removed / 1 unchanged Views & Navigation — 124 kB (baseline 124 kB) • ⚪ 0 BTop-level views, pages, and routed surfaces
Status: 13 added / 13 removed / 4 unchanged Panels & Settings — 565 kB (baseline 565 kB) • ⚪ 0 BConfiguration panels, inspectors, and settings screens
Status: 10 added / 10 removed / 16 unchanged User & Accounts — 27 kB (baseline 27 kB) • ⚪ 0 BAuthentication, profile, and account management bundles
Status: 6 added / 6 removed / 4 unchanged Editors & Dialogs — 125 kB (baseline 125 kB) • ⚪ 0 BModals, dialogs, drawers, and in-app editors
Status: 7 added / 7 removed / 1 unchanged UI Components — 67.1 kB (baseline 67.1 kB) • ⚪ 0 BReusable component library chunks
Status: 6 added / 6 removed / 8 unchanged Data & Services — 3.5 MB (baseline 3.5 MB) • 🔴 +1.02 kBStores, services, APIs, and repositories
Status: 14 added / 14 removed / 3 unchanged Utilities & Hooks — 549 kB (baseline 549 kB) • ⚪ 0 BHelpers, composables, and utility bundles
Status: 18 added / 18 removed / 20 unchanged Vendor & Third-Party — 16.3 MB (baseline 16.3 MB) • ⚪ 0 BExternal libraries and shared vendor chunks Status: 17 unchanged Other — 14 MB (baseline 14 MB) • ⚪ 0 BBundles that do not match a named category
Status: 68 added / 68 removed / 218 unchanged ⚡ Performance
|
📝 WalkthroughWalkthroughThe PR improves large-graph rendering by adding viewport culling, a version-aware QuadTree index, canvas-based low-detail node rendering, and minimap change-detection optimizations. It also adds tests and documents benchmark results, methodology, caveats, and follow-up work. ChangesLarge-graph performance
Estimated code review effort: 4 (Complex) | ~60 minutes Suggested labels: Sequence Diagram(s)sequenceDiagram
participant GraphCanvas
participant useViewportCulling
participant nodeCullingIndex
participant NodeBoxOverlay
participant drawNodeBoxes
GraphCanvas->>useViewportCulling: calculate mounted node IDs
useViewportCulling->>nodeCullingIndex: query expanded viewport
nodeCullingIndex-->>GraphCanvas: return visible node IDs
GraphCanvas->>NodeBoxOverlay: provide visible node boxes at low quality
NodeBoxOverlay->>drawNodeBoxes: render transformed rectangles
Important Pre-merge checks failedPlease resolve all errors before merging. Addressing warnings is optional. ❌ Failed checks (1 inconclusive)
✅ Passed checks (5 passed)
✨ Finishing Touches 💡 1🛠️ Fix failing CI checks 💡
📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 14
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/components/graph/GraphCanvas.vue`:
- Around line 317-322: Update getNodeBoxes to return a lazy Iterable<NodeBox>
using a generator instead of allocating a mapped array for every frame. Import
the NodeBox type, yield each cullingIndex entry with its bounds and color, and
remove the non-null assertion now that entries() provides narrowed bounds; keep
drawNodeBoxes unchanged.
- Around line 337-338: Update the graph indexing setup around getEntries to
hoist and reuse a single getAllNodes() computed outside the callback, then read
its cached value when building entries. Avoid calling layoutStore.getAllNodes()
inside each rebuild so the full layout map is materialized only when
layoutVersion invalidates it.
In `@src/composables/graph/useViewportCulling.test.ts`:
- Around line 61-64: Update src/composables/graph/useViewportCulling.test.ts at
lines 61-64 and 48-58: track each effectScope created by setup, then add a
shared afterEach that stops those scopes and calls vi.useRealTimers(). Ensure
cleanup runs after every test so watchers and fake timers do not leak.
In `@src/composables/graph/useViewportCulling.ts`:
- Line 188: Update the resize listener in the viewport culling setup to use the
existing refreshThrottled handler instead of refreshMountedNodes, preserving the
RECOMPUTE_THROTTLE_MS limit used by the camera path.
In `@src/renderer/core/canvas/nodeBoxRenderer.ts`:
- Around line 68-75: Update intersects to reuse the existing boundsIntersect
helper from layoutMath.ts instead of duplicating the overlap logic. Preserve the
current edge-inclusive behavior, including treating touching edges as
intersecting, and remove the local comparison implementation.
In `@src/renderer/core/spatial/nodeCullingIndex.ts`:
- Around line 116-119: Update nodeCullingIndex.ts lines 116-119 by introducing
or reusing a narrowed entry type with non-null Bounds, and type
positionedEntries and entries() accordingly; remove the bounds! assertion at
line 92. In GraphCanvas.vue lines 317-322, remove entry.bounds! in getNodeBoxes
and rely on the narrowed entries() type.
- Around line 47-48: Define and use a narrowed positioned-entry type for entries
whose bounds are guaranteed non-null, and type positionedEntries accordingly.
Update the relevant accessor and getNodeBoxes in GraphCanvas.vue to return/use
this narrowed type so the bounds non-null assertion in the positioning loop and
getNodeBoxes can be removed without suppression assertions.
In `@src/renderer/extensions/minimap/composables/useMinimap.test.ts`:
- Around line 89-110: The useIntervalFn mock in the minimap tests must model
fake-timer scheduling instead of invoking callbacks immediately on resume.
Update the mock to honor the 100 ms interval and cancel pending callbacks when
pause() or destroy() occurs, then assert no update at 99 ms, exactly one at 100
ms, and none after pause() or destroy().
In `@src/renderer/extensions/minimap/composables/useMinimapGraph.ts`:
- Around line 43-68: The connection digest in computeLinkDigest currently mixes
only origin_id and target_id; also mix origin_slot and target_slot for every
link so slot-only rewires are detected. Add a regression case in
src/renderer/extensions/minimap/composables/useMinimapGraph.test.ts lines
308-334 that changes only one slot and verifies the connection change is
reported.
In `@src/renderer/extensions/vueNodes/components/NodeBoxOverlay.vue`:
- Around line 67-71: Add aria-hidden="true" to the decorative canvas element
identified by data-testid="node-box-overlay" in NodeBoxOverlay.vue, leaving its
existing rendering and pointer-events attributes unchanged.
- Around line 51-57: Move the --node-box-color resolution out of the useRafFn
frame callback and cache it once during component setup or onMounted, then pass
the cached value as defaultColor to drawNodeBoxes. Add onMounted if needed,
preserve the `#353535` fallback, and only recompute through an appropriate
palette/theme watcher if runtime theme changes must be supported.
In `@src/renderer/extensions/vueNodes/composables/useLowQualityRendering.test.ts`:
- Around line 16-37: Add tests for the useLowQualityRendering watcher, driving
camera.z across getLowQualityThreshold in both low- and high-quality directions.
Assert that each transition updates layoutStore.pendingSlotSync appropriately
and invokes the canvas setDirty side effect, covering the high-quality
transition that is currently untested.
In `@src/renderer/extensions/vueNodes/composables/useLowQualityRendering.ts`:
- Around line 23-28: Update getLowQualityThreshold to use the same zero-value
guard as LGraphCanvas.updateLowQualityThreshold, or otherwise apply consistent
negative-value validation in both paths; preserve the shared threshold formula
and documented parity.
- Around line 45-52: Update the isLowQuality watcher to detect the true-to-false
transition using its previous value and set layoutStore.pendingSlotSync to true
before remounting; preserve the immediate high-quality run without triggering
synchronization, while retaining the existing low-quality reset and canvas
dirtiness behavior. Add a regression test covering the transition and
pending-slot synchronization.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: 28c58095-ddd0-4546-8a7a-a978349717b0
📒 Files selected for processing (21)
docs/architecture/vue-nodes-large-graph-performance.mdsrc/components/graph/GraphCanvas.vuesrc/composables/graph/useViewportCulling.test.tssrc/composables/graph/useViewportCulling.tssrc/renderer/core/canvas/nodeBoxRenderer.test.tssrc/renderer/core/canvas/nodeBoxRenderer.tssrc/renderer/core/layout/store/layoutStore.tssrc/renderer/core/spatial/nodeCullingIndex.test.tssrc/renderer/core/spatial/nodeCullingIndex.tssrc/renderer/extensions/minimap/composables/useMinimap.test.tssrc/renderer/extensions/minimap/composables/useMinimap.tssrc/renderer/extensions/minimap/composables/useMinimapGraph.test.tssrc/renderer/extensions/minimap/composables/useMinimapGraph.tssrc/renderer/extensions/minimap/data/AbstractMinimapDataSource.tssrc/renderer/extensions/minimap/data/LayoutStoreDataSource.tssrc/renderer/extensions/minimap/data/LiteGraphDataSource.tssrc/renderer/extensions/minimap/data/MinimapDataSource.test.tssrc/renderer/extensions/minimap/data/MinimapDataSourceFactory.tssrc/renderer/extensions/vueNodes/components/NodeBoxOverlay.vuesrc/renderer/extensions/vueNodes/composables/useLowQualityRendering.test.tssrc/renderer/extensions/vueNodes/composables/useLowQualityRendering.ts
| function getNodeBoxes() { | ||
| const colors = nodeColors.value | ||
| return cullingIndex | ||
| .entries() | ||
| .map((entry) => ({ bounds: entry.bounds!, color: colors.get(entry.id) })) | ||
| } |
There was a problem hiding this comment.
🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy lift
getNodeBoxes allocates an array of every node on every frame.
NodeBoxOverlay calls getBoxes() once per animation frame through useRafFn. getNodeBoxes calls cullingIndex.entries(), which returns every positioned node in the graph, then .map()s it into a new array of new objects. On a 3000-node graph this allocates 3000 objects and one 3000-element array per frame. drawNodeBoxes then discards the off-screen ones through its own intersects check.
This is the hot path of the low-quality mode, so the allocation cost lands exactly where the PR aims to reduce cost. Return a lazy iterable instead. drawNodeBoxes accepts Iterable<NodeBox> and iterates once, so a generator needs no renderer change.
🐛 Proposed fix
-function getNodeBoxes() {
- const colors = nodeColors.value
- return cullingIndex
- .entries()
- .map((entry) => ({ bounds: entry.bounds!, color: colors.get(entry.id) }))
-}
+function* getNodeBoxes(): Generator<NodeBox> {
+ const colors = nodeColors.value
+ for (const entry of cullingIndex.entries()) {
+ yield { bounds: entry.bounds, color: colors.get(entry.id) }
+ }
+}Add import type { NodeBox } from '@/renderer/core/canvas/nodeBoxRenderer'. The entry.bounds access drops its ! once entries() returns the narrowed type proposed in src/renderer/core/spatial/nodeCullingIndex.ts.
A further reduction is to query the index by the current viewport rather than iterating every entry, which would also remove the redundant intersects pass in drawNodeBoxes.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/components/graph/GraphCanvas.vue` around lines 317 - 322, Update
getNodeBoxes to return a lazy Iterable<NodeBox> using a generator instead of
allocating a mapped array for every frame. Import the NodeBox type, yield each
cullingIndex entry with its bounds and color, and remove the non-null assertion
now that entries() provides narrowed bounds; keep drawNodeBoxes unchanged.
| getEntries: () => { | ||
| const layouts = layoutStore.getAllNodes().value |
There was a problem hiding this comment.
🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win
getAllNodes() builds a throwaway computed and a full layout Map on every rebuild.
layoutStore.getAllNodes() returns a newly constructed ComputedRef on each call (src/renderer/core/layout/store/layoutStore.ts Lines 383-396). Reading .value immediately runs the full O(n) loop that calls yNodeToLayout for every node, and the computed is then discarded, so its cache is never reused.
getEntries runs on every index rebuild. A node drag bumps layoutVersion on each move operation, so each throttle window pays this full materialisation on top of the QuadTree construction. On a 3000-node graph that is a per-rebuild O(n) pass whose only purpose is a lookup by id.
Hoist the computed once, or read each layout individually so only the nodes in rawNodes are materialised.
🐛 Proposed fix
+const allNodeLayouts = layoutStore.getAllNodes()
+
const cullingIndex = createNodeCullingIndex({
getVersion: () => layoutStore.layoutVersion,
getEntries: () => {
- const layouts = layoutStore.getAllNodes().value
+ const layouts = allNodeLayouts.value
return rawNodes.value.map((node) => {Hoisting keeps one computed whose cache is invalidated by version, so repeated rebuilds within the same version cost a cache read instead of a full rescan.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| getEntries: () => { | |
| const layouts = layoutStore.getAllNodes().value | |
| const allNodeLayouts = layoutStore.getAllNodes() | |
| const cullingIndex = createNodeCullingIndex({ | |
| getVersion: () => layoutStore.layoutVersion, | |
| getEntries: () => { | |
| const layouts = allNodeLayouts.value |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/components/graph/GraphCanvas.vue` around lines 337 - 338, Update the
graph indexing setup around getEntries to hoist and reuse a single getAllNodes()
computed outside the callback, then read its cached value when building entries.
Avoid calling layoutStore.getAllNodes() inside each rebuild so the full layout
map is materialized only when layoutVersion invalidates it.
| beforeEach(() => { | ||
| vi.useFakeTimers() | ||
| Object.assign(camera, { x: 0, y: 0, z: 1 }) | ||
| }) |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
The test file has no afterEach hook, so two kinds of state persist across tests. beforeEach installs fake timers and the setup helper creates effect scopes, but nothing tears either down. A single afterEach resolves both.
src/composables/graph/useViewportCulling.test.ts#L61-L64: add anafterEachthat callsvi.useRealTimers()so fake timers do not persist beyond each test.src/composables/graph/useViewportCulling.test.ts#L48-L58: collect theeffectScopeinstances created bysetupand stop them in the sameafterEach, so watchers bound to the shared module-scopecamerado not keep running for the rest of the file.
As per path instructions: docs/testing/vitest-patterns.md states "reset mocks in beforeEach, and restore fake timers in afterEach", and .agents/checks/test-quality.md requires covering "timer, and cleanup cases".
📍 Affects 1 file
src/composables/graph/useViewportCulling.test.ts#L61-L64(this comment)src/composables/graph/useViewportCulling.test.ts#L48-L58
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/composables/graph/useViewportCulling.test.ts` around lines 61 - 64,
Update src/composables/graph/useViewportCulling.test.ts at lines 61-64 and
48-58: track each effectScope created by setup, then add a shared afterEach that
stops those scopes and calls vi.useRealTimers(). Ensure cleanup runs after every
test so watchers and fake timers do not leak.
Source: Path instructions
| () => void refreshThrottled() | ||
| ) | ||
|
|
||
| useEventListener(window, 'resize', refreshMountedNodes) |
There was a problem hiding this comment.
🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win
Throttle the resize handler.
The resize event fires in bursts while the user drags the window edge. refreshMountedNodes runs a full spatial query and a pinned-node scan on each call. Reuse refreshThrottled so resize matches the camera path and stays bounded by RECOMPUTE_THROTTLE_MS.
♻️ Proposed change
- useEventListener(window, 'resize', refreshMountedNodes)
+ useEventListener(window, 'resize', () => void refreshThrottled())📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| useEventListener(window, 'resize', refreshMountedNodes) | |
| useEventListener(window, 'resize', () => void refreshThrottled()) |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/composables/graph/useViewportCulling.ts` at line 188, Update the resize
listener in the viewport culling setup to use the existing refreshThrottled
handler instead of refreshMountedNodes, preserving the RECOMPUTE_THROTTLE_MS
limit used by the camera path.
| function intersects(a: Bounds, b: Bounds): boolean { | ||
| return !( | ||
| a.x + a.width < b.x || | ||
| b.x + b.width < a.x || | ||
| a.y + a.height < b.y || | ||
| b.y + b.height < a.y | ||
| ) | ||
| } |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Compare the existing helper's implementation with the local copy.
rg -n -A 12 'export function boundsIntersect' src/renderer/core/layout/utils/layoutMath.ts
# Find any other duplicate AABB predicates already in the tree.
ast-grep run --pattern 'function $NAME($A: Bounds, $B: Bounds): boolean { $$$ }' --lang typescript srcRepository: Comfy-Org/ComfyUI_frontend
Length of output: 2041
Reuse boundsIntersect from src/renderer/core/layout/utils/layoutMath.ts. It has identical edge semantics, including treating touching edges as intersecting. Removing the duplicate prevents future divergence.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/renderer/core/canvas/nodeBoxRenderer.ts` around lines 68 - 75, Update
intersects to reuse the existing boundsIntersect helper from layoutMath.ts
instead of duplicating the overlap logic. Preserve the current edge-inclusive
behavior, including treating touching edges as intersecting, and remove the
local comparison implementation.
| drawNodeBoxes(ctx, getBoxes(), camera, viewportBounds(width, height), { | ||
| // Matches the node surface colour so a zoomed-out graph reads the same as | ||
| // a zoomed-in one. | ||
| defaultColor: | ||
| getComputedStyle(el).getPropertyValue('--node-box-color').trim() || | ||
| '#353535' | ||
| }) |
There was a problem hiding this comment.
🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win
getComputedStyle runs on every animation frame.
useRafFn executes this block at up to 60 Hz. getComputedStyle(el).getPropertyValue('--node-box-color') forces a style resolution on each call. The value comes from the static [--node-box-color:var(--color-zinc-700)] class at Line 70 and does not change at runtime, so the per-frame read is pure overhead in the path this PR optimises.
Resolve the colour once outside the frame loop.
🐛 Proposed fix
+const FALLBACK_NODE_BOX_COLOR = '`#353535`'
+let defaultColor = FALLBACK_NODE_BOX_COLOR
+
+onMounted(() => {
+ const el = canvasRef.value
+ if (!el) return
+ defaultColor =
+ getComputedStyle(el).getPropertyValue('--node-box-color').trim() ||
+ FALLBACK_NODE_BOX_COLOR
+})
+
useRafFn(() => {
@@
drawNodeBoxes(ctx, getBoxes(), camera, viewportBounds(width, height), {
// Matches the node surface colour so a zoomed-out graph reads the same as
// a zoomed-in one.
- defaultColor:
- getComputedStyle(el).getPropertyValue('--node-box-color').trim() ||
- '`#353535`'
+ defaultColor
})
})Add onMounted to the vue import. If the colour must follow a runtime theme change, recompute it in a watcher on the palette rather than per frame.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| drawNodeBoxes(ctx, getBoxes(), camera, viewportBounds(width, height), { | |
| // Matches the node surface colour so a zoomed-out graph reads the same as | |
| // a zoomed-in one. | |
| defaultColor: | |
| getComputedStyle(el).getPropertyValue('--node-box-color').trim() || | |
| '#353535' | |
| }) | |
| const FALLBACK_NODE_BOX_COLOR = '`#353535`' | |
| let defaultColor = FALLBACK_NODE_BOX_COLOR | |
| onMounted(() => { | |
| const el = canvasRef.value | |
| if (!el) return | |
| defaultColor = | |
| getComputedStyle(el).getPropertyValue('--node-box-color').trim() || | |
| FALLBACK_NODE_BOX_COLOR | |
| }) | |
| useRafFn(() => { | |
| drawNodeBoxes(ctx, getBoxes(), camera, viewportBounds(width, height), { | |
| // Matches the node surface colour so a zoomed-out graph reads the same as | |
| // a zoomed-in one. | |
| defaultColor | |
| }) | |
| }) |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/renderer/extensions/vueNodes/components/NodeBoxOverlay.vue` around lines
51 - 57, Move the --node-box-color resolution out of the useRafFn frame callback
and cache it once during component setup or onMounted, then pass the cached
value as defaultColor to drawNodeBoxes. Add onMounted if needed, preserve the
`#353535` fallback, and only recompute through an appropriate palette/theme
watcher if runtime theme changes must be supported.
| <canvas | ||
| ref="canvasRef" | ||
| data-testid="node-box-overlay" | ||
| class="pointer-events-none absolute inset-0 size-full [--node-box-color:var(--color-zinc-700)]" | ||
| /> |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
Mark the decorative canvas as hidden from assistive technology.
The canvas duplicates node rectangles for visual purposes only and is pointer-events-none. It carries no accessible name. Add aria-hidden="true" so assistive technology skips it.
♻️ Proposed change
<canvas
ref="canvasRef"
+ aria-hidden="true"
data-testid="node-box-overlay"
class="pointer-events-none absolute inset-0 size-full [--node-box-color:var(--color-zinc-700)]"
/>📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| <canvas | |
| ref="canvasRef" | |
| data-testid="node-box-overlay" | |
| class="pointer-events-none absolute inset-0 size-full [--node-box-color:var(--color-zinc-700)]" | |
| /> | |
| <canvas | |
| ref="canvasRef" | |
| aria-hidden="true" | |
| data-testid="node-box-overlay" | |
| class="pointer-events-none absolute inset-0 size-full [--node-box-color:var(--color-zinc-700)]" | |
| /> |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/renderer/extensions/vueNodes/components/NodeBoxOverlay.vue` around lines
67 - 71, Add aria-hidden="true" to the decorative canvas element identified by
data-testid="node-box-overlay" in NodeBoxOverlay.vue, leaving its existing
rendering and pointer-events attributes unchanged.
| describe('getLowQualityThreshold', () => { | ||
| it('matches the zoom at which text hits the minimum readable size', () => { | ||
| setDpr(1) | ||
|
|
||
| // NODE_TEXT_SIZE is 14, so 14px text renders at 7px once zoomed to 0.5. | ||
| expect(getLowQualityThreshold(7)).toBeCloseTo(0.5, 5) | ||
| }) | ||
|
|
||
| it('lets higher-DPI displays stay detailed longer', () => { | ||
| setDpr(1) | ||
| const at1x = getLowQualityThreshold(8) | ||
| setDpr(4) | ||
| const at4x = getLowQualityThreshold(8) | ||
|
|
||
| // sqrt(4) = 2, so the threshold halves rather than quartering. | ||
| expect(at4x).toBeCloseTo(at1x / 2, 5) | ||
| }) | ||
|
|
||
| it('reports no threshold when LOD is disabled', () => { | ||
| expect(getLowQualityThreshold(0)).toBe(0) | ||
| }) | ||
| }) |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
Add coverage for the useLowQualityRendering watcher.
The tests cover only getLowQualityThreshold. The composable's watcher performs the side effects that matter: it clears pendingSlotSync and calls setDirty. Neither branch is tested, which is why the missing high-quality transition flagged in src/renderer/extensions/vueNodes/composables/useLowQualityRendering.ts Lines 45-52 went unnoticed.
Add tests that drive camera.z across the threshold and assert the resulting layoutStore and canvas state in both directions.
As per coding guidelines: "Write tests for code changes, especially bug fixes, to prevent regressions."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/renderer/extensions/vueNodes/composables/useLowQualityRendering.test.ts`
around lines 16 - 37, Add tests for the useLowQualityRendering watcher, driving
camera.z across getLowQualityThreshold in both low- and high-quality directions.
Assert that each transition updates layoutStore.pendingSlotSync appropriately
and invokes the canvas setDirty side effect, covering the high-quality
transition that is currently untested.
Source: Coding guidelines
| export function getLowQualityThreshold(minFontSize: number): number { | ||
| if (minFontSize <= 0) return 0 | ||
|
|
||
| const dprAdjustment = Math.sqrt(window.devicePixelRatio || 1) | ||
| return minFontSize / (LiteGraph.NODE_TEXT_SIZE * dprAdjustment) | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Locate litegraph's own low-quality threshold computation.
rg -n -C 10 'updateLowQualityThreshold|low_quality|min_font_size_for_lod' src/lib/litegraph/src
# Confirm the NODE_TEXT_SIZE constant used by both paths.
rg -n -C 2 'NODE_TEXT_SIZE\s*[:=]' src/lib/litegraph/srcRepository: Comfy-Org/ComfyUI_frontend
Length of output: 35520
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- helper ---'
cat -n src/renderer/extensions/vueNodes/composables/useLowQualityRendering.ts | sed -n '1,80p'
printf '%s\n' '--- threshold usages and setting validation ---'
rg -n -C 4 'getLowQualityThreshold|min_font_size_for_lod' srcRepository: Comfy-Org/ComfyUI_frontend
Length of output: 12513
Align the LOD guard with LGraphCanvas.updateLowQualityThreshold.
The threshold formula matches, but the helper uses minFontSize <= 0 while LGraphCanvas checks === 0. Use the same guard or validate negative values consistently to preserve the documented parity.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/renderer/extensions/vueNodes/composables/useLowQualityRendering.ts`
around lines 23 - 28, Update getLowQualityThreshold to use the same zero-value
guard as LGraphCanvas.updateLowQualityThreshold, or otherwise apply consistent
negative-value validation in both paths; preserve the shared threshold formula
and documented parity.
| watch( | ||
| isLowQuality, | ||
| (lowQuality) => { | ||
| if (lowQuality) layoutStore.setPendingSlotSync(false) | ||
| canvas.value?.setDirty(true, true) | ||
| }, | ||
| { immediate: true } | ||
| ) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check whether slot tracking measures on mount without an explicit request.
ast-grep outline src/renderer/extensions/vueNodes/composables/useSlotElementTracking.ts --items all
# Find every writer of pendingSlotSync to confirm the expected lifecycle.
rg -n -C 6 'setPendingSlotSync|pendingSlotSync' srcRepository: Comfy-Org/ComfyUI_frontend
Length of output: 19004
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- useLowQualityRendering.ts ---'
cat -n src/renderer/extensions/vueNodes/composables/useLowQualityRendering.ts
printf '%s\n' '--- useSlotElementTracking.ts (mount, request, flush, composable) ---'
sed -n '1,145p' src/renderer/extensions/vueNodes/composables/useSlotElementTracking.ts
sed -n '250,340p' src/renderer/extensions/vueNodes/composables/useSlotElementTracking.ts
printf '%s\n' '--- GraphCanvas transition watcher ---'
sed -n '350,395p' src/components/graph/GraphCanvas.vue
printf '%s\n' '--- low-quality usage and Vue node rendering ---'
rg -n -C 5 'useLowQualityRendering|isLowQuality|v-if=.*low|lowQuality' src/renderer/extensions/vueNodes src/components/graph | head -n 240Repository: Comfy-Org/ComfyUI_frontend
Length of output: 22062
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- slot tracking cleanup ---'
sed -n '330,405p' src/renderer/extensions/vueNodes/composables/useSlotElementTracking.ts
printf '%s\n' '--- LGraphNode slot tracking usage ---'
rg -n -C 8 'useSlotElementTracking' src/renderer/extensions/vueNodes
printf '%s\n' '--- GraphCanvas setup order and template conditions ---'
sed -n '60,105p' src/components/graph/GraphCanvas.vue
sed -n '285,335p' src/components/graph/GraphCanvas.vue
printf '%s\n' '--- transition-related tests ---'
rg -n -C 8 'low quality|LowQuality|pendingSlotSync|requestSlotLayoutSyncForAllNodes' src/renderer/extensions/vueNodes src/components/graph --glob '*test*'Repository: Comfy-Org/ComfyUI_frontend
Length of output: 36986
🏁 Script executed:
#!/bin/bash
set -e
python3 - <<'PY'
from pathlib import Path
import re
low_quality = Path(
'src/renderer/extensions/vueNodes/composables/useLowQualityRendering.ts'
).read_text()
graph_canvas = Path('src/components/graph/GraphCanvas.vue').read_text()
tracking = Path(
'src/renderer/extensions/vueNodes/composables/useSlotElementTracking.ts'
).read_text()
assert 'v-for="nodeData in isLowQuality ? [] : allNodes"' in graph_canvas
assert 'layoutStore.deleteSlotLayout(slotKey)' in tracking
assert 'onMounted(() =>' in tracking
assert 'scheduleSlotLayoutSync(nodeId)' in tracking
assert 'if (lowQuality) layoutStore.setPendingSlotSync(false)' in low_quality
assert 'setPendingSlotSync(true)' not in low_quality
watch_body = re.search(
r'watch\(\s*isLowQuality,\s*\((.*?)\)\s*=>\s*\{(.*?)\n\s*\},',
low_quality,
re.S,
)
assert watch_body, 'low-quality watcher not found'
parameters, body = watch_body.groups()
print('low-quality node list is empty:', True)
print('slot unmount deletes cached layouts:', True)
print('slot mount schedules a layout sync:', True)
print('watcher clears pending sync on low-quality:', 'setPendingSlotSync(false)' in body)
print('watcher restores pending sync on high-quality:', 'setPendingSlotSync(true)' in body)
print('watcher receives previous value:', ',' in parameters)
PYRepository: Comfy-Org/ComfyUI_frontend
Length of output: 425
Re-enable slot synchronization when leaving low-quality mode.
When isLowQuality changes from true to false, set pendingSlotSync to true before Vue remounts the nodes. Low-quality mode removes slot layouts, and remounted slots need a fresh measurement before links render. Guard this branch with the previous watcher value so the immediate high-quality run does not trigger an unnecessary sync. Add a regression test.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/renderer/extensions/vueNodes/composables/useLowQualityRendering.ts`
around lines 45 - 52, Update the isLowQuality watcher to detect the
true-to-false transition using its previous value and set
layoutStore.pendingSlotSync to true before remounting; preserve the immediate
high-quality run without triggering synchronization, while retaining the
existing low-quality reset and canvas dirtiness behavior. Add a regression test
covering the transition and pending-slot synchronization.
Codecov Report❌ Patch coverage is @@ Coverage Diff @@
## main #15016 +/- ##
==========================================
- Coverage 78.69% 78.60% -0.09%
==========================================
Files 1864 1874 +10
Lines 115461 116938 +1477
Branches 33553 35143 +1590
==========================================
+ Hits 90864 91922 +1058
- Misses 24055 24462 +407
- Partials 542 554 +12
Flags with carried forward coverage won't be shown. Click here to find out more.
... and 70 files with indirect coverage changes 🚀 New features to boost your workflow:
|
) ## Summary The minimap re-derived its entire picture every animation frame — an O(n²) node scan, `JSON.stringify` over all links, and several full rebuilds of the layout map from Yjs — costing CPU continuously even while idle. ## Changes - **What**: Change detection moved from per-frame RAF to a 100ms interval; the O(n²) `_nodes.find` per layout entry replaced with the graph's own id index; per-node strings and link `JSON.stringify` replaced with allocation-free rolling digests; data sources memoize `getNodes()` per render pass; new `layoutStore.nodeCount` / `layoutVersion` / `nodeGeometryVersion` accessors avoid rebuilding the full layout map for count and staleness checks. - Detection is keyed on `nodeGeometryVersion` (bumped only when a node is added/removed or its position/size/bounds is written) rather than the operation counter, so `setNodeZIndex` — one per widget pointerdown — and reroute drags no longer force a rebuild and redraw. Backed by `observeDeep`, so it also covers remote changes arriving via `applyUpdate`. - Polling is gated on document visibility (a tab hidden at mount never starts the loop) and on having a canvas to draw into; two of the three `useMinimap()` call sites have none. - Removed a dead `watch(layoutStoreVersion)` and the `getVersion()` it was the last caller of — it returned a `ComputedRef` over a plain field and could never fire. ## Measurements Per-tick cost of change detection, benchmarked by @christian-byrne during review: | nodes | before | after | | ----: | -----: | ----: | | 245 | 0.343 ms | 0.0105 ms | | 2500 | 22.4 ms | 0.101 ms | Attribution at 2500 nodes: the `getNodeById` fix is 12.8x and the only asymptotic term, the digest 17x, RAF→interval 6x. `performance.spec.ts` `minimap idle` (245 nodes, TBT) runs on every push of this branch via `ci-perf-report.yaml`, with the comparison posted by `pr-report.yaml` — that's the CI-visible number for this change. ## Review Focus - Digest collisions are possible in principle (would drop one refresh, self-correcting on the next change) — accepted as the minimap is an approximate overview. Non-finite values coerce per term, so one NaN cannot mask other movement. - The link digest hashes endpoints and slots, not just count, so a same-count rewire still triggers a redraw. - Known follow-up (FE-1557): threading a single data source through `updateMinimap` (three builds per pass → two), and wrapping the composable's watchers in an `effectScope` so `destroy()` tears them down. Split from Comfy-Org#15016 (part 1 of 3). --------- Co-authored-by: github-actions <github-actions@github.com>
Summary
Vue node rendering was unusable on large workflows — every node stayed mounted as a DOM component tree at all times, at every zoom — so a 3000-node graph panned at ~310ms/frame where the canvas renderer managed 27ms. Vue nodes now match or beat the pre-work canvas-renderer baseline in five of six measured configurations.
Changes
Median frame time while panning. "litegraph" is the canvas renderer before this work, i.e. the bar to clear:
DOM elements on the 3000-node graph: 227,787 → 5,355 at working zoom, → 418 (application chrome only) when zoomed out.
Full write-up, method and follow-ups:
docs/architecture/vue-nodes-large-graph-performance.md.Suggested split
727 lines of non-test, non-doc source is well past the 300-line guideline. The commits are already separable and should become three PRs:
d67006644e) — independent, renderer-agnostic, and made the canvas renderer ~2x faster on its own.987c5b7532,d53cc46874,43271d6e60,8e11dd9520) — a stack; revert top-down.fcb96da734,c68cf7a8cd,982c3ab751) — includes a revert of an approach that made the DOM renderer depend on litegraph to draw a zoomed-out graph; worth reading that revert message.Review Focus
nodeCullingIndexdeliberately does not reuseSpatialIndexManager. That index is built on a fixed ±10000 box andQuadTree.insertsilently drops anything outside it — the return value is discarded andupdate()cannot recover an item never inserted. Real workflows outgrow it, so most nodes would be missing from query results. This index sizes its root to the graph's extent.display: none. The sharedResizeObserverhas no zero-size guard, so a hidden node writes 0x0 bounds throughlayoutStoreintoliteNode.sizeand corrupts the saved workflow.TransformPanewrites its transform by direct DOM mutation specifically to avoid re-diffing every node each frame; camera state is sampled through a throttle instead.useMinimapGraphnow readsgraph._nodes/graph.linksdirectly for its digest, where it previously went throughMinimapDataSourceFactory. That is more coupling, traded for dropping a per-frameJSON.stringifyof every link.min_font_size_for_lodoff the canvas renderer, so both renderers switch at the same zoom. The node box drawing itself has no litegraph dependency.Not done
renderLinkrebuilds its render context per link, per frame (~15% of frame time at fit zoom). Shared link path, so it helps both renderers; the fix is hoisting the context out of the loop, not caching, sinceLGraphCanvas.link_type_colorsis mutated in place by extensions.drawConnections. Predates this work, and is the remaining obstacle to the DOM renderer standing alone.Testing
Unit tests added for the culling composable, the culling index, the LOD threshold, and the box renderer. Verified manually against generated workflows of 1000/3000/8000 nodes: normal zoom unchanged, LOD transition round-trips with widgets/slots/links/error state intact, no page errors.
Note: this checkout has a pre-existing broken install (two
@vue/runtime-corecopies) that fails ~1694 tests.mainfails identically, so it is environmental — the branch adds 23 passing tests and breaks none.