diff --git a/browser_tests/fixtures/helpers/NodeOperationsHelper.ts b/browser_tests/fixtures/helpers/NodeOperationsHelper.ts index f4f23d395e7..704338cab7d 100644 --- a/browser_tests/fixtures/helpers/NodeOperationsHelper.ts +++ b/browser_tests/fixtures/helpers/NodeOperationsHelper.ts @@ -94,12 +94,6 @@ export class NodeOperationsHelper { return await this.page.evaluate(() => window.app!.graph.nodes.length) } - async getNodes(): Promise { - return await this.page.evaluate(() => { - return window.app!.graph.nodes - }) - } - async waitForGraphNodes(count: number): Promise { await this.page.waitForFunction((count) => { return window.app?.canvas.graph?.nodes?.length === count diff --git a/browser_tests/tests/nodeBadge.spec.ts b/browser_tests/tests/nodeBadge.spec.ts index 975225b389c..e2dc2fa99fd 100644 --- a/browser_tests/tests/nodeBadge.spec.ts +++ b/browser_tests/tests/nodeBadge.spec.ts @@ -48,25 +48,6 @@ test.describe('Node Badge', { tag: ['@screenshot', '@smoke', '@node'] }, () => { await expect(comfyPage.canvas).toHaveScreenshot('node-badge-multiple.png') }) - - test('Can add badge left-side', async ({ comfyPage }) => { - await comfyPage.page.evaluate(() => { - const LGraphBadge = window.LGraphBadge! - const app = window.app as ComfyApp - const graph = app.graph - const nodes = graph.nodes - - for (const node of nodes) { - node.badges = [new LGraphBadge({ text: 'Test Badge' })] - // @ts-expect-error - Enum value - node.badgePosition = 'top-left' - } - - graph.setDirtyCanvas(true, true) - }) - - await expect(comfyPage.canvas).toHaveScreenshot('node-badge-left.png') - }) }) test.describe( diff --git a/browser_tests/tests/nodeBadge.spec.ts-snapshots/node-badge-left-chromium-linux.png b/browser_tests/tests/nodeBadge.spec.ts-snapshots/node-badge-left-chromium-linux.png deleted file mode 100644 index 2bdffb1d2e0..00000000000 Binary files a/browser_tests/tests/nodeBadge.spec.ts-snapshots/node-badge-left-chromium-linux.png and /dev/null differ diff --git a/browser_tests/tests/workflowPersistence.spec.ts b/browser_tests/tests/workflowPersistence.spec.ts index ee2e3f42c46..b116dfe8818 100644 --- a/browser_tests/tests/workflowPersistence.spec.ts +++ b/browser_tests/tests/workflowPersistence.spec.ts @@ -252,10 +252,9 @@ test.describe('Workflow Persistence', () => { await expect.poll(() => comfyPage.nodeOps.getNodeCount()).toBe(1) await expect - .poll(async () => { - const nodes = await comfyPage.nodeOps.getNodes() - return nodes[0]?.type - }) + .poll(() => + comfyPage.page.evaluate(() => window.app!.graph.nodes[0]?.type) + ) .toBe('KSampler') }) diff --git a/docs/adr/0008-entity-component-system.md b/docs/adr/0008-entity-component-system.md index 11f2d345c05..8371bbff6e5 100644 --- a/docs/adr/0008-entity-component-system.md +++ b/docs/adr/0008-entity-component-system.md @@ -37,14 +37,20 @@ writes are tracked without an action chokepoint. The `layoutStore` link connectivity mirror and the `slot._floatingLinks` sets were deleted in the same work; the layout store now holds geometry only. -### Amendment (2026-07-14, PR 13458) +### Amendment (2026-07-15, PR 13458) -`nodeBadgeStore` joined the dedicated-store set: plain `BadgeData` rows -keyed by `NodeId` in root-graph-scoped buckets. Unlike the -proxy-adoption stores above, rows are written by a reactive badge -system (`src/systems/badgeSystem.ts`) — a pure `computeBadges` inside a -per-node effect scope — see -[Node Badge Store](../architecture/node-badge-store.md). +Node badge rows remain plain `BadgeData`, but they are derived presentation +data rather than authoritative entity state. Materializing them in a dedicated +store duplicated settings, node definitions, palette, pricing, widget, link, +and graph state. It also required registration, teardown, and cache lifecycle +logic. + +Instead, `src/systems/badgeSystem.ts` keeps one lazy computed projection per +node instance. Renderers query that projection through a temporary app-layer +registration seam, which keeps the litegraph layer independent from the badge +system's pricing dependencies. Badge rows remain transient: they are +not serialized, transmitted through CRDT, or included in undo history. See +[Node Badge Store](../architecture/node-badge-store.md) for the design history. ## Context @@ -247,6 +253,15 @@ Systems are pure functions that query the relevant store(s) for entities with sp - **LayoutSystem** — queries `Position` + `Dimensions` + structural components for auto-layout - **SelectionSystem** — queries `Position` for point entities and `Position` + `Dimensions` for box hit-testing +Until a `RenderSystem` owns render orchestration, node badges use a registered +query function so the legacy canvas can read the app-owned projection without +importing the badge system. Once the `RenderSystem` can query entity data and +compose renderer input, badge lookup should move there. That migration should +delete the registration seam and remove badge projection access from +`LGraphNode`; the render system will query `BadgeData` and pass plain draw data +to the canvas. This keeps badge derivation app-owned without materializing its +output as a second source of truth. + System design is deferred to a future ADR. For detailed before/after walkthroughs of how lifecycle operations (node removal, link creation, subgraph nesting, etc.) transform under ECS, see [ECS Lifecycle Scenarios](../architecture/ecs-lifecycle-scenarios.md). ### Migration Strategy diff --git a/docs/architecture/node-badge-store.md b/docs/architecture/node-badge-store.md index ccf6fcbf016..7abf84f8952 100644 --- a/docs/architecture/node-badge-store.md +++ b/docs/architecture/node-badge-store.md @@ -1,10 +1,10 @@ # Node Badge Store -Date: 2026-07-05 (updated 2026-07-06) -Status: Partially implemented — decisions 1–4 shipped as -`src/stores/nodeBadgeStore.ts` + `src/systems/badgeSystem.ts` (slice A); -decision 5 and the open decisions below await the consumer-cutover PR -(slice B). Follow-up to the +Date: 2026-07-05 (updated 2026-07-15) +Status: Superseded on this branch by a derive-on-read prototype — see +[Prototype: derive-on-read](#prototype-derive-on-read-2026-07-15) below. +Slices A and B shipped as described; the prototype then removed the +store. Follow-up to the [link topology store](link-topology-store.md), [reroute chain store](reroute-chain-store.md), and the [node data store draft](node-data-store.md) @@ -38,15 +38,15 @@ the store rows the single truth both renderers read. The store holds only plain data (ADR 0008 component rule): ``` -BadgeData { - kind: 'core' | 'credits' | 'extension' - text: string - fgColor?: string - bgColor?: string - iconKey?: string // resolved via a small icon registry ('credits' → SVG) -} +BadgeData = CoreBadgeData | CreditsBadgeData // discriminated on `kind` + // core rows require `part`; credits rows may carry an `iconKey` + // resolved via a small icon registry ('credits' → SVG) ``` +There is no `extension` kind: resolved decision 1 below keeps +`node.badges` as the raw extension surface, so the store holds only +system-computed rows and the system replaces them wholesale per write. + No `onClick` (no producer exists; `LGraphButton`/`title_buttons` are a separate surface and out of scope). No `Image` objects — icons are referenced by key. A `commandId` field can be added if a clickable badge @@ -65,8 +65,9 @@ unregister / unregister-all trio at the `LGraph.add` / `LGraph.remove` / conventions. Rows are partitioned by `kind` at read time; the positional `slice(1)` -convention and icon-identity credits detection are deleted. Display -order is kind order (core, credits, extension), not insertion order. +convention and icon-identity credits detection are deleted. The system +emits rows in display order (core, then credits) and replaces a node's +array wholesale, so reads are identity-stable between writes. ## Decision 3: A reactive BadgeSystem writes the rows @@ -110,53 +111,119 @@ Frame-budget parity per ADR 0008's render mitigations applies. `registeredNodeIds` to attach/detach per-node effect scopes. Litegraph never imports the system, so the pricing/nodeDef dependency graph (which runtime-imports the litegraph barrel) stays acyclic. The system - takes a `resolveNode` seam and will be bootstrapped at the app layer - in slice B, when the `Comfy.NodeBadge` extension stops pushing - closures; until then rows are written only under test. Row writes are + takes `resolveGraphId`/`resolveNode` seams and is bootstrapped once at + the app layer by the `Comfy.NodeBadge` extension (`useNodeBadge`). + The graph id is resolved live on every recompute because + `LGraph.clear()` and `configure()` reassign the root graph's id; a + captured id strands the system on a dead bucket. Row writes are refused for unregistered nodes so a late effect flush cannot - resurrect a bucket key the chokepoints deleted. -- Two write paths: `setBadgesOfKind` is the system's bulk - replace-one-kind recompute path (`@internal`); extension rows go - through `registerBadge`/`deleteBadge` per row, identity-checked, so - independent writers cannot stomp each other. + resurrect a bucket key the chokepoints deleted. `LGraph.add` + registers the node only after `onNodeAdded`: the store write wakes + the system's watcher and queues Vue's flush microtask, which must not + overtake the paste-scan microtask `useErrorClearingHooks` enqueues + from `onNodeAdded`. +- One write path: the system replaces a node's rows wholesale via + `setBadges` on every recompute, so no intermediate per-kind state is + ever observable. - The shell still reads `node.constructor.nodeData` and `node.inputs` (untracked instance state) to map pricing input names to slot indices — parity with the legacy closures. Those reads become store lookups when slot data is store-backed (node data store draft). -- Core rows are fine-grained — one row per part in lifecycle, id, source - order — with one visibility rule (`badgeTextVisible`, the legacy - semantics: `HideBuiltIn` respected for every part). Joining, - bracket decoration, and truncation are renderer presentation and move - to the slice-B legacy draw cache. Rows store lifecycle text with the - `[]` brackets trimmed. Known unification effects: the Vue renderer - gains `HideBuiltIn` handling for id badges, and core nodes' `🦊` - source row becomes data the Vue partition may substitute with its - Comfy-logo chip. +- Core rows are fine-grained — one row per part, tagged + `part: 'lifecycle' | 'id' | 'source'` and carrying the raw projected + text — with one visibility rule (`badgeTextVisible`, the legacy + semantics: `HideBuiltIn` respected for every part). Each renderer owns + presentation: the legacy draw cache joins parts in id, lifecycle, + source order and truncates; the Vue partition trims lifecycle + brackets, and replaces a built-in node's source row with its + Comfy-logo chip. Known unification effect: the Vue renderer gains + `HideBuiltIn` handling for id and lifecycle badges on built-in nodes. - A credits row is emitted only when the display price label is non-empty; async pricing fills it via the per-node revision ref. -- Subgraph credits aggregation is not yet in the system — it stays on - the `updateSubgraphCredits` closure path until open decision 3 below - is resolved. - -## Open decisions (interview pending) - -1. **Legacy `node.badges` surface** — recommended: a converting - accessor exposing the node's `BadgeData[]` proxy; bare - `LGraphBadge`/thunk pushes auto-convert (thunk evaluated once, - `Image` icons dropped) with a one-time deprecation warning pointing - at the store API. Alternatives: delete the property outright, or a - read-only view. Ecosystem scan found zero genuine third-party - writers; ADR 0008 extension-impact guidance applies regardless. -2. **`node.badgePosition`** — recommended: delete (single writer sets a - constant `TopRight` on every node; single reader; renderer policy, - not badge data). Deprecated accessor warns on write. -3. **Subgraph credits aggregation triggers** — recommended: the three - existing events (`litegraph:set-graph`, `subgraph-converted`, - `afterConfigureGraph`) bump a revision the system watches; swap to - reactive `SubgraphStructure` dependencies when that state is - store-backed. -## Scope and sequencing +## Implementation notes (slice B) + +- Wrapper `SubgraphNode` credits rows are aggregated by the system over + the inner (recursively collected, non-wrapper) api nodes — the same + count basis as the old unconditional per-api-node badges: several + collapse to `Partner Nodes x N` (localized), exactly one shows its + price with the wrapper's promoted widget values overriding the inner + node's own. The aggregation tracks the inner nodes' pricing + revisions, the registered-node set, and a structure revision. + `useNodePricing` caches labels per signature so a leaf's own read and + its wrapper's override read do not evict each other and re-schedule + forever. +- Legacy `drawBadges` renders the store rows through a per-node + memoized `LGraphBadge` cache (decision 5) keyed on the rows array's + identity — wholesale replacement makes identity the change signal, so + the per-frame path allocates nothing on cache hits. `iconKey` resolves + through a generic litegraph `badgeIconRegistry`, with the `credits` + icon registered when the system starts. +- The Vue renderer samples `node.badges` whenever its partition computed + re-runs; live array mutation and ticking thunks are visible per frame + only in the legacy canvas. Array interception was considered and + rejected: it cannot see thunk output changes (the dominant ecosystem + pattern), so it buys property patching without covering the real case. + If a pack demonstrably needs live Vue updates, the escalation is a + reactive accessor declared on `LGraphNode` itself, not renderer-side + `defineProperty`. + +## Resolved decisions (2026-07-06 interview) + +1. **Legacy `node.badges` surface — kept as a raw extension-only push + surface.** Directive: delete unless actively used. A GitHub-wide scan + found three custom-node packs actively writing it + (ComfyUI-Wildcard-Pipeline pushes and splices `LGraphBadge` + instances; ComfyUI-Enhancement-Utils and ComfyUI-XENodes push + per-frame getter thunks for ticking execution-time badges), so the + array stays, is no longer written by core/credits code, and both + renderers append it after the store rows — thunks still evaluate per + frame in the legacy canvas. The earlier "zero third-party writers" + scan was wrong. +2. **`node.badgePosition` — deleted**, along with the `BadgePosition` + enum. Zero uses outside this repo; the legacy canvas now always + renders badges top-right (the only surviving behaviour). A no-op + deprecated accessor remains and warns on access. +3. **Subgraph credits aggregation triggers — event-bumped revision.** + `litegraph:set-graph`, `subgraph-converted`, and + `afterConfigureGraph` bump `bumpSubgraphCreditsRevision()`; swap to + reactive `SubgraphStructure` dependencies when that state is + store-backed. Aggregation behaviour itself is preserved (explicit + user requirement). + +## Prototype: derive-on-read (2026-07-15) + +Badge rows are derived presentation, not authoritative entity state: +every row is a pure projection of settings, node definitions, palette, +pricing, and graph structure. Materializing that projection into a store +made the registration/watcher/scope machinery cache invalidation. The +prototype replaces the store with a memoized derivation: + +- `nodeBadges(node)` in `src/systems/badgeSystem.ts` — one lazy + `computed` per node instance in a `WeakMap`. Entries die with their + nodes (workflow loads create new instances), so registration, + unregistration, teardown, and the stale-bucket bug class do not exist. + `computeBadges` stays pure and data-first; the authoritative sources + of truth remain the settings/def/palette/pricing stores and the graph. +- `LGraph`'s ref-backed `id` and `_version` (bumped by + `incrementVersion()` at the `add`/`remove`/`clear` chokepoints and + read by the `nodes` getter) — the revision signals replacing store + bucket membership, `subgraphCreditsRevision`, and the live-graph-id + seams: graph-id-keyed reads and subgraph aggregation re-resolve after + loads and structural changes. Bumps only invalidate; recomputes happen + lazily on the next read. +- `setBadgeRowsProvider` (in `nodeBadgeDraw.ts`) — a one-function seam + installed by `useNodeBadge`, so litegraph never imports the + derivation's pricing/nodeDef dependency graph (same acyclicity + property the store's import-light trio provided). The identity-keyed + draw cache is unchanged: a computed returns the same array until it + recomputes. + +Trade-offs accepted: badge rows are no longer enumerable per graph +(`PartnerNodesList` traverses the graph via `mapUniqueNodes` +instead of querying a bucket), and the structure revision is coarse — +any structural change invalidates all badge computeds, which is cheap +because invalidation is a flag and recomputation is per-read. Slices: (A) store + `BadgeData` + system for core and credits + chokepoint registration; (B) consumer cutover — Vue partition query, diff --git a/src/composables/graph/useGraphNodeManager.ts b/src/composables/graph/useGraphNodeManager.ts index 9ef483a69e2..6a502a7d1e3 100644 --- a/src/composables/graph/useGraphNodeManager.ts +++ b/src/composables/graph/useGraphNodeManager.ts @@ -14,7 +14,6 @@ import type { NodeId } from '@/types/nodeId' import type { LGraph, - LGraphBadge, LGraphNode, LGraphTriggerAction, LGraphTriggerEvent, @@ -23,8 +22,6 @@ import type { import type { TitleMode } from '@/lib/litegraph/src/types/globalEnums' import { NodeSlotType } from '@/lib/litegraph/src/types/globalEnums' -type Badges = (LGraphBadge | (() => LGraphBadge))[] - const reactiveArrayNodes = new WeakSet() export interface VueNodeData { @@ -35,7 +32,6 @@ export interface VueNodeData { title: string type: string apiNode?: boolean - badges?: Badges bgcolor?: string color?: string flags?: { @@ -155,7 +151,6 @@ export function extractVueNodeData(node: LGraphNode): VueNodeData { executing: false, subgraphId, apiNode: node.constructor?.nodeData?.api_node ?? false, - badges: node.badges, hasErrors: !!node.has_errors, inputs, outputs, @@ -386,12 +381,6 @@ export function useGraphNodeManager(graph: LGraph): GraphNodeManager { showAdvanced: Boolean(propertyEvent.newValue) }) break - case 'badges': - vueNodeData.set(nodeId, { - ...currentData, - badges: propertyEvent.newValue as Badges - }) - break } } }, diff --git a/src/composables/node/useNodeBadge.ts b/src/composables/node/useNodeBadge.ts index cfe2ad66f24..33b22aafeae 100644 --- a/src/composables/node/useNodeBadge.ts +++ b/src/composables/node/useNodeBadge.ts @@ -1,47 +1,18 @@ -import _ from 'es-toolkit/compat' import { computed, onMounted, watch } from 'vue' import { useNodePricing } from '@/composables/node/useNodePricing' -import { usePriceBadge } from '@/composables/node/usePriceBadge' -import { useComputedWithWidgetWatch } from '@/composables/node/useWatchWidget' -import { BadgePosition, LGraphBadge } from '@/lib/litegraph/src/litegraph' -import type { LGraphNode } from '@/lib/litegraph/src/litegraph' import { useSettingStore } from '@/platform/settings/settingStore' import { app } from '@/scripts/app' import { useExtensionStore } from '@/stores/extensionStore' -import type { ComfyNodeDefImpl } from '@/stores/nodeDefStore' -import { useNodeDefStore } from '@/stores/nodeDefStore' -import { useColorPaletteStore } from '@/stores/workspace/colorPaletteStore' -import { NodeBadgeMode } from '@/types/nodeSource' +import { installNodeBadges } from '@/systems/badgeSystem' /** - * Add LGraphBadge to LGraphNode based on settings. - * - * Following badges are added: - * - Node ID badge - * - Node source badge - * - Node life cycle badge - * - API node credits badge + * Bootstraps badge derivation: installs it as the legacy canvas's row + * source and keeps the legacy canvas redrawing when badge sources change. */ export const useNodeBadge = () => { const settingStore = useSettingStore() const extensionStore = useExtensionStore() - const colorPaletteStore = useColorPaletteStore() - const priceBadge = usePriceBadge() - - const nodeSourceBadgeMode = computed( - () => - settingStore.get('Comfy.NodeBadge.NodeSourceBadgeMode') as NodeBadgeMode - ) - const nodeIdBadgeMode = computed( - () => settingStore.get('Comfy.NodeBadge.NodeIdBadgeMode') as NodeBadgeMode - ) - const nodeLifeCycleBadgeMode = computed( - () => - settingStore.get( - 'Comfy.NodeBadge.NodeLifeCycleBadgeMode' - ) as NodeBadgeMode - ) const showApiPricingBadge = computed(() => settingStore.get('Comfy.NodeBadge.ShowApiPricing') @@ -49,9 +20,9 @@ export const useNodeBadge = () => { watch( [ - nodeSourceBadgeMode, - nodeIdBadgeMode, - nodeLifeCycleBadgeMode, + () => settingStore.get('Comfy.NodeBadge.NodeSourceBadgeMode'), + () => settingStore.get('Comfy.NodeBadge.NodeIdBadgeMode'), + () => settingStore.get('Comfy.NodeBadge.NodeLifeCycleBadgeMode'), showApiPricingBadge ], () => { @@ -59,21 +30,9 @@ export const useNodeBadge = () => { } ) - const nodeDefStore = useNodeDefStore() - function badgeTextVisible( - nodeDef: ComfyNodeDefImpl | null, - badgeMode: NodeBadgeMode - ): boolean { - return !( - badgeMode === NodeBadgeMode.None || - (nodeDef?.isCoreNode && badgeMode === NodeBadgeMode.HideBuiltIn) - ) - } - onMounted(() => { if (extensionStore.isExtensionInstalled('Comfy.NodeBadge')) return - // TODO: Fix the composables and watchers being setup in onMounted const nodePricing = useNodePricing() watch( @@ -86,138 +45,14 @@ export const useNodeBadge = () => { extensionStore.registerExtension({ name: 'Comfy.NodeBadge', - nodeCreated(node: LGraphNode) { - node.badgePosition = BadgePosition.TopRight - - const badge = computed(() => { - const nodeDef = nodeDefStore.fromLGraphNode(node) - return new LGraphBadge({ - text: _.truncate( - [ - badgeTextVisible(nodeDef, nodeIdBadgeMode.value) - ? `#${node.id}` - : '', - badgeTextVisible(nodeDef, nodeLifeCycleBadgeMode.value) - ? (nodeDef?.nodeLifeCycleBadgeText ?? '') - : '', - badgeTextVisible(nodeDef, nodeSourceBadgeMode.value) - ? (nodeDef?.nodeSource?.badgeText ?? '') - : '' - ] - .filter((s) => s.length > 0) - .join(' '), - { - length: 31 - } - ), - fgColor: - colorPaletteStore.completedActivePalette.colors.litegraph_base - .BADGE_FG_COLOR, - bgColor: - colorPaletteStore.completedActivePalette.colors.litegraph_base - .BADGE_BG_COLOR - }) - }) - - node.badges.push(() => badge.value) - - if (node.constructor.nodeData?.api_node && showApiPricingBadge.value) { - // JSONata rules are dynamic if they depend on any widgets/inputs/input_groups - const pricingConfig = nodePricing.getNodePricingConfig(node) - const hasDynamicPricing = - !!pricingConfig && - ((pricingConfig.depends_on?.widgets?.length ?? 0) > 0 || - (pricingConfig.depends_on?.inputs?.length ?? 0) > 0 || - (pricingConfig.depends_on?.input_groups?.length ?? 0) > 0) - - // Keep the existing widget-watch wiring ONLY to trigger redraws on widget change. - // (We no longer rely on it to hold the current badge value.) - if (hasDynamicPricing) { - // For dynamic pricing nodes, use computed that watches widget changes - const relevantWidgetNames = nodePricing.getRelevantWidgetNames( - node.constructor.nodeData?.name - ) - - const computedWithWidgetWatch = useComputedWithWidgetWatch(node, { - widgetNames: relevantWidgetNames, - triggerCanvasRedraw: true - }) - - // Ensure watchers are installed; ignore the returned value. - // (This call is what registers the widget listeners in most implementations.) - computedWithWidgetWatch(() => 0) - - // Hook into connection changes to trigger price recalculation - // This handles both connect and disconnect in VueNodes mode - const relevantInputs = pricingConfig?.depends_on?.inputs ?? [] - const inputGroupPrefixes = - pricingConfig?.depends_on?.input_groups ?? [] - const hasRelevantInputs = - relevantInputs.length > 0 || inputGroupPrefixes.length > 0 - - if (hasRelevantInputs) { - const originalOnConnectionsChange = node.onConnectionsChange - node.onConnectionsChange = function ( - type, - slotIndex, - isConnected, - link, - ioSlot - ) { - originalOnConnectionsChange?.call( - this, - type, - slotIndex, - isConnected, - link, - ioSlot - ) - // Only trigger if this input affects pricing - const inputName = ioSlot?.name - if (!inputName) return - const isRelevantInput = - relevantInputs.includes(inputName) || - inputGroupPrefixes.some((prefix) => - inputName.startsWith(prefix + '.') - ) - if (isRelevantInput) { - nodePricing.triggerPriceRecalculation(node) - } - } - } - } - - let lastLabel = nodePricing.getNodeDisplayPrice(node) - let lastBadge = priceBadge.getCreditsBadge(lastLabel) - - const creditsBadgeGetter: () => LGraphBadge = () => { - const label = nodePricing.getNodeDisplayPrice(node) - if (label !== lastLabel) { - lastLabel = label - lastBadge = priceBadge.getCreditsBadge(label) - } - return lastBadge - } - - node.badges.push(creditsBadgeGetter) - } - }, init() { + installNodeBadges() app.canvas.canvas.addEventListener<'litegraph:set-graph'>( 'litegraph:set-graph', () => { - for (const node of app.canvas.graph?.nodes ?? []) - priceBadge.updateSubgraphCredits(node) + app.canvas?.setDirty(true, true) } ) - app.canvas.canvas.addEventListener<'subgraph-converted'>( - 'subgraph-converted', - (e) => priceBadge.updateSubgraphCredits(e.detail.subgraphNode) - ) - }, - afterConfigureGraph() { - for (const node of app.canvas.graph?.nodes ?? []) - priceBadge.updateSubgraphCredits(node) } }) }) diff --git a/src/composables/node/useNodePricing.test.ts b/src/composables/node/useNodePricing.test.ts index dc10370620b..14dc9d01a95 100644 --- a/src/composables/node/useNodePricing.test.ts +++ b/src/composables/node/useNodePricing.test.ts @@ -173,6 +173,26 @@ describe('useNodePricing', () => { expect(price).toBe(creditsLabel(0.05)) }) + it('caches per signature so base and override reads both settle', async () => { + const { getNodeDisplayPrice } = useNodePricing() + const node = createMockNodeWithPriceBadge( + 'TestSignatureNode', + priceBadge('{"type":"text","text": widgets.prompt}', [ + { name: 'prompt', type: 'STRING' } + ]), + [{ name: 'prompt', value: 'inner' }] + ) + const overrides = new Map([['prompt', 'outer']]) + + getNodeDisplayPrice(node) + getNodeDisplayPrice(node, overrides) + await vi.waitFor(() => { + expect(getNodeDisplayPrice(node)).toBe('inner') + expect(getNodeDisplayPrice(node, overrides)).toBe('outer') + }) + expect(getNodeDisplayPrice(node)).toBe('inner') + }) + it('should handle FLOAT widget as number', async () => { const { getNodeDisplayPrice } = useNodePricing() const node = createMockNodeWithPriceBadge( @@ -543,58 +563,6 @@ describe('useNodePricing', () => { }) }) - describe('getNodePricingConfig', () => { - it('should return pricing config for nodes with price_badge', () => { - const { getNodePricingConfig } = useNodePricing() - const node = createMockNodeWithPriceBadge( - 'TestConfigNode', - priceBadge('{"type":"usd","usd":0.05}') - ) - - const config = getNodePricingConfig(node) - expect(config).toBeDefined() - expect(config?.engine).toBe('jsonata') - expect(config?.expr).toBe('{"type":"usd","usd":0.05}') - expect(config?.depends_on).toBeDefined() - }) - - it('should return undefined for nodes without price_badge', () => { - const { getNodePricingConfig } = useNodePricing() - const node = createMockNode({ - name: 'NoPricingNode', - api_node: true - }) - - const config = getNodePricingConfig(node) - expect(config).toBeUndefined() - }) - - it('should return undefined for non-API nodes', () => { - const { getNodePricingConfig } = useNodePricing() - const node = createMockNode({ - name: 'RegularNode', - api_node: false - }) - - const config = getNodePricingConfig(node) - expect(config).toBeUndefined() - }) - - it('does not leak the compiled JSONata expression', () => { - const { getNodePricingConfig } = useNodePricing() - const node = createMockNodeWithPriceBadge( - 'TestStripCompiledNode', - priceBadge('{"type":"usd","usd":0.05}') - ) - - const config = getNodePricingConfig(node) - expect(config).toBeDefined() - // _compiled is the runtime JSONata instance and must not be exposed to - // tooling/debug consumers. - expect(config).not.toHaveProperty('_compiled') - }) - }) - describe('reactive revision', () => { it('bumps pricingRevision after an async evaluation resolves (Nodes 1.0 mode)', async () => { const { getNodeDisplayPrice, pricingRevision } = useNodePricing() @@ -691,28 +659,6 @@ describe('useNodePricing', () => { }) }) - describe('triggerPriceRecalculation', () => { - it('should not throw for API nodes with price_badge', () => { - const { triggerPriceRecalculation } = useNodePricing() - const node = createMockNodeWithPriceBadge( - 'TestTriggerNode', - priceBadge('{"type":"usd","usd":0.05}') - ) - - expect(() => triggerPriceRecalculation(node)).not.toThrow() - }) - - it('should not throw for non-API nodes', () => { - const { triggerPriceRecalculation } = useNodePricing() - const node = createMockNode({ - name: 'RegularNode', - api_node: false - }) - - expect(() => triggerPriceRecalculation(node)).not.toThrow() - }) - }) - describe('error handling', () => { it('should return empty string for invalid JSONata expression', async () => { const { getNodeDisplayPrice } = useNodePricing() diff --git a/src/composables/node/useNodePricing.ts b/src/composables/node/useNodePricing.ts index 1409938ea5e..12b7f3f0881 100644 --- a/src/composables/node/useNodePricing.ts +++ b/src/composables/node/useNodePricing.ts @@ -469,21 +469,36 @@ const getNodeRevisionRef = (nodeId: NodeId): Ref => { } // WeakMaps avoid memory leaks when nodes are removed. -type CacheEntry = { sig: string; label: string } type InflightEntry = { sig: string; promise: Promise } -const cache = new WeakMap() -const desiredSig = new WeakMap() +const MAX_CACHED_SIGNATURES = 8 +const cache = new WeakMap>() const inflight = new WeakMap() +function nodeSigCache(node: LGraphNode): Map { + const existing = cache.get(node) + if (existing) return existing + const next = new Map() + cache.set(node, next) + return next +} + +function cacheLabel(node: LGraphNode, sig: string, label: string): void { + const sigCache = nodeSigCache(node) + sigCache.delete(sig) + sigCache.set(sig, label) + for (const oldest of sigCache.keys()) { + if (sigCache.size <= MAX_CACHED_SIGNATURES) break + sigCache.delete(oldest) + } +} + const scheduleEvaluation = ( node: LGraphNode, rule: CompiledJsonataPricingRule, ctx: JsonataEvalContext, sig: string ) => { - desiredSig.set(node, sig) - const running = inflight.get(node) if (running && running.sig === sig) return @@ -491,19 +506,11 @@ const scheduleEvaluation = ( const promise = Promise.resolve(rule._compiled.evaluate(ctx)) .then((res) => { - const label = formatPricingResult(res) - - // Ignore stale results: if the node changed while we were evaluating, - // desiredSig will no longer match. - if (desiredSig.get(node) !== sig) return - - cache.set(node, { sig, label }) + cacheLabel(node, sig, formatPricingResult(res)) }) .catch(() => { // Cache empty to avoid retry-spam for same signature - if (desiredSig.get(node) === sig) { - cache.set(node, { sig, label: '' }) - } + cacheLabel(node, sig, '') }) .finally(() => { const cur = inflight.get(node) @@ -574,26 +581,15 @@ export const useNodePricing = () => { const ctx = buildJsonataContext(node, rule, widgetOverrides) const sig = buildSignature(ctx, rule) - const cached = cache.get(node) - if (cached && cached.sig === sig) { - return cached.label - } + const sigCache = cache.get(node) + const hit = sigCache?.get(sig) + if (hit !== undefined) return hit // Cache miss: start async evaluation. - // Return last-known label (if any) to avoid flicker; otherwise return empty. + // Return the last-known label (if any) to avoid flicker. scheduleEvaluation(node, rule, ctx, sig) - return cached?.label ?? '' - } - - /** - * Expose raw pricing config for tooling/debug UI. - * (Strips compiled expression from returned object.) - */ - const getNodePricingConfig = (node: LGraphNode) => { - const rule = getRuleForNode(node) - if (!rule) return undefined - const { _compiled, ...config } = rule - return config + const labels = [...(sigCache?.values() ?? [])] + return labels.at(-1) ?? '' } /** @@ -657,28 +653,13 @@ export const useNodePricing = () => { return priceBadge?.depends_on?.inputs ?? [] } - /** - * Trigger price recalculation for a node (call when inputs change). - * Forces re-evaluation by calling getNodeDisplayPrice which will detect - * the signature change and schedule a new evaluation. - */ - const triggerPriceRecalculation = (node: LGraphNode): void => { - const nodeData = getNodeConstructorData(node) - if (!nodeData?.api_node) return - - // Call getNodeDisplayPrice to trigger evaluation if signature changed - getNodeDisplayPrice(node) - } - return { getNodeDisplayPrice, - getNodePricingConfig, getRelevantWidgetNames, hasDynamicPricing, getInputGroupPrefixes, getInputNames, getNodeRevisionRef, // Each node has its own independent ref, so updates to one won't trigger others - triggerPriceRecalculation, pricingRevision: readonly(pricingTick) // reactive invalidation signal } } diff --git a/src/composables/node/usePriceBadge.test.ts b/src/composables/node/usePriceBadge.test.ts deleted file mode 100644 index 0ee2bd0045d..00000000000 --- a/src/composables/node/usePriceBadge.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { describe, expect, vi } from 'vitest' - -import { LGraphNode } from '@/lib/litegraph/src/litegraph' -import { useWidgetValueStore } from '@/stores/widgetValueStore' - -import { subgraphTest } from '@/lib/litegraph/src/subgraph/__fixtures__/subgraphFixtures' - -import { usePriceBadge } from '@/composables/node/usePriceBadge' - -const getNodeDisplayPrice = vi.fn( - (_node: LGraphNode, overrides?: ReadonlyMap) => - String(overrides?.get('prompt') ?? 'missing override') -) - -vi.mock('@/composables/node/useNodePricing', () => ({ - useNodePricing: () => ({ getNodeDisplayPrice }) -})) - -vi.mock('@/stores/workspace/colorPaletteStore', () => ({ - useColorPaletteStore: () => ({ - completedActivePalette: { - light_theme: false, - colors: { litegraph_base: {} } - } - }) -})) - -const { updateSubgraphCredits, getCreditsBadge } = usePriceBadge() - -const mockNode = new LGraphNode('mock node') -mockNode.badges = [getCreditsBadge('$0.05/Run')] - -function getBadgeText(node: LGraphNode): string { - const badge = node.badges[0] - return (typeof badge === 'function' ? badge() : badge).text -} - -describe('subgraph pricing', () => { - subgraphTest( - 'should not display badge for subgraphs without API nodes', - ({ subgraphWithNode }) => { - const { subgraphNode } = subgraphWithNode - updateSubgraphCredits(subgraphNode) - expect(subgraphNode.badges.length).toBe(0) - } - ) - subgraphTest( - 'should return the price of a single contained API node', - ({ subgraphWithNode }) => { - const { subgraphNode, subgraph } = subgraphWithNode - subgraph.add(mockNode) - updateSubgraphCredits(subgraphNode) - expect(subgraphNode.badges.length).toBe(1) - expect(getBadgeText(subgraphNode)).toBe('$0.05/Run') - } - ) - subgraphTest( - 'should return the number of api nodes if more than one exists', - ({ subgraphWithNode }) => { - const { subgraphNode, subgraph } = subgraphWithNode - for (let i = 0; i < 5; i++) subgraph.add(mockNode) - updateSubgraphCredits(subgraphNode) - expect(subgraphNode.badges.length).toBe(1) - expect(getBadgeText(subgraphNode)).toBe('Partner Nodes x 5') - } - ) - - subgraphTest( - 'uses promoted widget override from any matching internal link', - ({ subgraphWithNode }) => { - const { subgraphNode, subgraph } = subgraphWithNode - class ApiNode extends LGraphNode { - static override nodeData = { name: 'ApiNode', api_node: true } - } - const apiNode = new ApiNode('api node') - apiNode.badges = [getCreditsBadge('$0.05/Run')] - const apiInput = apiNode.addInput('prompt', 'STRING') - apiInput.widget = { name: 'prompt' } - apiNode.addWidget('string', 'prompt', 'inner value', () => undefined, {}) - - const decoyNode = new LGraphNode('decoy node') - const decoyInput = decoyNode.addInput('prompt', 'STRING') - decoyInput.widget = { name: 'prompt' } - decoyNode.addWidget( - 'string', - 'prompt', - 'decoy value', - () => undefined, - {} - ) - - subgraph.add(decoyNode) - subgraph.add(apiNode) - subgraph.inputNode.slots[0].connect(decoyInput, decoyNode) - subgraph.inputNode.slots[0].connect(apiInput, apiNode) - subgraphNode._internalConfigureAfterSlots() - const inputWidgetId = subgraphNode.inputs[0].widgetId - if (!inputWidgetId) throw new Error('Missing promoted input widgetId') - useWidgetValueStore().setValue(inputWidgetId, 'outer value') - - updateSubgraphCredits(subgraphNode) - - expect(getBadgeText(subgraphNode)).toBe('outer value') - } - ) -}) diff --git a/src/composables/node/usePriceBadge.ts b/src/composables/node/usePriceBadge.ts deleted file mode 100644 index def392b6e82..00000000000 --- a/src/composables/node/usePriceBadge.ts +++ /dev/null @@ -1,152 +0,0 @@ -import type { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph' -import { LGraphBadge } from '@/lib/litegraph/src/litegraph' - -import { useNodePricing } from '@/composables/node/useNodePricing' -import type { INodeInputSlot } from '@/lib/litegraph/src/interfaces' -import type { SubgraphInput } from '@/lib/litegraph/src/subgraph/SubgraphInput' -import { useColorPaletteStore } from '@/stores/workspace/colorPaletteStore' -import { adjustColor } from '@/utils/colorUtil' -import { useWidgetValueStore } from '@/stores/widgetValueStore' - -type LinkedWidgetInput = INodeInputSlot & { - _subgraphSlot?: SubgraphInput -} - -const componentIconSvg = new Image() -componentIconSvg.src = - "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath fill='none' stroke='oklch(83.01%25 0.163 83.16)' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M15.536 11.293a1 1 0 0 0 0 1.414l2.376 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0zm-13.239 0a1 1 0 0 0 0 1.414l2.377 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414L6.088 8.916a1 1 0 0 0-1.414 0zm6.619 6.619a1 1 0 0 0 0 1.415l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.415l-2.377-2.376a1 1 0 0 0-1.414 0zm0-13.238a1 1 0 0 0 0 1.414l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z'/%3E%3C/svg%3E" - -export const usePriceBadge = () => { - const nodePricing = useNodePricing() - - function updateSubgraphCredits(node: LGraphNode) { - if (!node.isSubgraphNode()) return - node.badges = node.badges.filter((b) => !isCreditsBadge(b)) - const innerCreditsBadges = collectCreditsBadges(node.subgraph) - if (innerCreditsBadges.length > 1) { - node.badges.push( - getCreditsBadge('Partner Nodes x ' + innerCreditsBadges.length) - ) - } else if (innerCreditsBadges.length === 1) { - const innerApiNodes = collectInnerApiNodes(node.subgraph) - // When a single inner api node is the price source, swap its static - // getter for a wrapper-aware one that resolves promoted widget values. - if (innerApiNodes.length === 1) { - node.badges.push(buildWrapperAwarePriceBadge(node, innerApiNodes[0])) - } else { - node.badges.push(...innerCreditsBadges) - } - } - const graph = node.graph - if (!graph) return - graph.trigger('node:property:changed', { - type: 'node:property:changed', - nodeId: node.id, - property: 'badges', - oldValue: node.badges, - newValue: node.badges - }) - } - - function collectCreditsBadges( - graph: LGraph, - visited: Set = new Set() - ): (LGraphBadge | (() => LGraphBadge))[] { - if (visited.has(graph.id)) return [] - visited.add(graph.id) - const badges: (LGraphBadge | (() => LGraphBadge))[] = [] - for (const node of graph.nodes) { - badges.push( - ...(node.isSubgraphNode() - ? collectCreditsBadges(node.subgraph, visited) - : node.badges.filter((b) => isCreditsBadge(b))) - ) - } - return badges - } - - function collectInnerApiNodes( - graph: LGraph, - visited: Set = new Set() - ): LGraphNode[] { - if (visited.has(graph.id)) return [] - visited.add(graph.id) - const apiNodes: LGraphNode[] = [] - for (const node of graph.nodes) { - if (node.isSubgraphNode()) { - apiNodes.push(...collectInnerApiNodes(node.subgraph, visited)) - } else if (node.constructor?.nodeData?.api_node) { - apiNodes.push(node) - } - } - return apiNodes - } - - function buildWrapperAwarePriceBadge( - wrapper: LGraphNode, - innerNode: LGraphNode - ): () => LGraphBadge { - return () => - getCreditsBadge( - nodePricing.getNodeDisplayPrice( - innerNode, - collectPromotedOverrides(wrapper, innerNode) - ) - ) - } - - function collectPromotedOverrides( - wrapper: LGraphNode, - innerNode: LGraphNode - ): ReadonlyMap { - const overrides = new Map() - if (!wrapper.isSubgraphNode()) return overrides - - for (const input of wrapper.inputs as LinkedWidgetInput[]) { - if (!input.widgetId) continue - for (const linkId of input._subgraphSlot?.linkIds ?? []) { - const link = wrapper.subgraph.getLink(linkId) - if (link?.target_id !== innerNode.id) continue - const targetInput = innerNode.inputs[link.target_slot] - const widgetName = targetInput?.widget?.name - if (!widgetName) continue - overrides.set( - widgetName, - useWidgetValueStore().getWidget(input.widgetId)?.value - ) - } - } - return overrides - } - - function isCreditsBadge( - badge: Partial | (() => Partial) - ): boolean { - const badgeInstance = typeof badge === 'function' ? badge() : badge - return badgeInstance.icon?.image === componentIconSvg - } - - const colorPaletteStore = useColorPaletteStore() - function getCreditsBadge(price: string): LGraphBadge { - const isLightTheme = colorPaletteStore.completedActivePalette.light_theme - - return new LGraphBadge({ - text: price, - iconOptions: { - image: componentIconSvg, - size: 8 - }, - fgColor: - colorPaletteStore.completedActivePalette.colors.litegraph_base - .BADGE_FG_COLOR, - bgColor: isLightTheme - ? adjustColor('#8D6932', { lightness: 0.5 }) - : '#8D6932' - }) - } - return { - getCreditsBadge, - isCreditsBadge, - updateSubgraphCredits - } -} diff --git a/src/lib/litegraph/src/LGraph.badges.test.ts b/src/lib/litegraph/src/LGraph.badges.test.ts deleted file mode 100644 index ea22c5460a4..00000000000 --- a/src/lib/litegraph/src/LGraph.badges.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { createTestingPinia } from '@pinia/testing' -import { setActivePinia } from 'pinia' -import { beforeEach, describe, expect, it } from 'vitest' - -import { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph' -import { useNodeBadgeStore } from '@/stores/nodeBadgeStore' -import { createUuidv4 } from '@/utils/uuid' - -import { - createTestSubgraphData, - createTestSubgraphNode -} from './subgraph/__fixtures__/subgraphHelpers' - -beforeEach(() => setActivePinia(createTestingPinia({ stubActions: false }))) - -describe('LGraph node badge registration', () => { - it('registers a node in the root bucket on add, unregisters on remove', () => { - const graph = new LGraph() - const node = new LGraphNode('n') - - graph.add(node) - expect(useNodeBadgeStore().registeredNodeIds(graph.rootGraph.id)).toEqual([ - node.id - ]) - - graph.remove(node) - expect(useNodeBadgeStore().registeredNodeIds(graph.rootGraph.id)).toEqual( - [] - ) - }) - - it('clears the root bucket when the root graph is cleared', () => { - const graph = new LGraph() - graph.id = createUuidv4() - graph.add(new LGraphNode('a')) - graph.add(new LGraphNode('b')) - const graphId = graph.rootGraph.id - - graph.clear() - - expect(useNodeBadgeStore().registeredNodeIds(graphId)).toEqual([]) - }) - - it('registers subgraph nodes in the root bucket', () => { - const rootGraph = new LGraph() - const subgraph = rootGraph.createSubgraph(createTestSubgraphData()) - const inner = new LGraphNode('inner') - - subgraph.add(inner) - - expect( - useNodeBadgeStore().registeredNodeIds(rootGraph.rootGraph.id) - ).toContainEqual(inner.id) - }) - - it('unregisters nodes at every nesting depth when a subgraph is cleared', () => { - const rootGraph = new LGraph() - const keeper = new LGraphNode('keeper') - rootGraph.add(keeper) - - const outer = rootGraph.createSubgraph(createTestSubgraphData()) - outer.add(new LGraphNode('direct')) - const nested = rootGraph.createSubgraph(createTestSubgraphData()) - nested.add(new LGraphNode('deep')) - outer.add(createTestSubgraphNode(nested, { parentGraph: outer })) - - outer.clear() - - expect( - useNodeBadgeStore().registeredNodeIds(rootGraph.rootGraph.id) - ).toEqual([keeper.id]) - }) - - it('unregisters inner nodes when the subgraph definition is collected', () => { - const rootGraph = new LGraph() - const subgraph = rootGraph.createSubgraph(createTestSubgraphData()) - const inner = new LGraphNode('inner') - subgraph.add(inner) - const subgraphNode = createTestSubgraphNode(subgraph, { pos: [100, 100] }) - rootGraph.add(subgraphNode) - - rootGraph.remove(subgraphNode) - - expect( - useNodeBadgeStore().registeredNodeIds(rootGraph.rootGraph.id) - ).toEqual([]) - }) -}) diff --git a/src/lib/litegraph/src/LGraph.ts b/src/lib/litegraph/src/LGraph.ts index b773e2d25e4..3d43011e536 100644 --- a/src/lib/litegraph/src/LGraph.ts +++ b/src/lib/litegraph/src/LGraph.ts @@ -15,7 +15,6 @@ import { toLinkId } from '@/types/linkId' import { toRerouteId } from '@/types/rerouteId' import { useLinkStore } from '@/stores/linkStore' import { useRerouteStore } from '@/stores/rerouteStore' -import { useNodeBadgeStore } from '@/stores/nodeBadgeStore' import { usePreviewExposureStore } from '@/stores/previewExposureStore' import { useWidgetValueStore } from '@/stores/widgetValueStore' import { UNASSIGNED_NODE_ID, parseNodeId, toNodeId } from '@/types/nodeId' @@ -303,7 +302,13 @@ export class LGraph revision: number = 0 - _version: number = -1 + private readonly _versionRef = shallowRef(-1) + get _version(): number { + return toRaw(this)._versionRef.value + } + set _version(value: number) { + toRaw(this)._versionRef.value = value + } /** The backing store for links. Keys are wrapped in String() */ _links: Map = new Map() /** @@ -474,17 +479,12 @@ export class LGraph useWidgetValueStore().clearGraph(graphId) useLinkStore().clearGraph(graphId) useRerouteStore().clearGraph(graphId) - useNodeBadgeStore().clearGraph(graphId) } else { // Subgraphs and unconfigured (zero-uuid) graphs share their store // bucket with other graphs, so unregister each link individually. unregisterAllLinkTopologies(this) unregisterAllRerouteChains(this) - forEachNode(this, (node) => - useNodeBadgeStore().unregisterNode(this.rootGraph.id, node.id) - ) } - this.id = zeroUuid this.revision = 0 @@ -558,6 +558,7 @@ export class LGraph } get nodes() { + void this._version return this._nodes } @@ -939,7 +940,6 @@ export class LGraph /** * Increments the internal version counter. - * Currently only read for debug display in {@link LGraphCanvas.renderInfo}. * Centralized so a future VersionSystem can intercept, batch, or replace it. */ incrementVersion(): void { @@ -1089,9 +1089,6 @@ export class LGraph } node.graph = this - this.incrementVersion() - - useNodeBadgeStore().registerNode(this.rootGraph.id, node.id) // Register all widgets with the WidgetValueStore now that node has a // valid ID and graph reference. @@ -1118,6 +1115,9 @@ export class LGraph this.onNodeAdded?.(node) + // Must follow onNodeAdded: its microtask-deferred hooks must run before the Vue flush this write schedules + this.incrementVersion() + this.setDirtyCanvas(true) this.change() @@ -1208,9 +1208,6 @@ export class LGraph if (!hasRemainingReferences) { forEachNode(node.subgraph, fireNodeRemovalLifecycle) - forEachNode(node.subgraph, (innerNode) => - useNodeBadgeStore().unregisterNode(this.rootGraph.id, innerNode.id) - ) unregisterAllLinkTopologies(node.subgraph) unregisterAllRerouteChains(node.subgraph) this.rootGraph.subgraphs.delete(node.subgraph.id) @@ -1239,8 +1236,6 @@ export class LGraph if (pos != -1) this._nodes.splice(pos, 1) delete this._nodes_by_id[node.id] - useNodeBadgeStore().unregisterNode(this.rootGraph.id, node.id) - this.onNodeRemoved?.(node) // close panels diff --git a/src/lib/litegraph/src/LGraphBadge.ts b/src/lib/litegraph/src/LGraphBadge.ts index 25005ce94d5..a4993fd0de3 100644 --- a/src/lib/litegraph/src/LGraphBadge.ts +++ b/src/lib/litegraph/src/LGraphBadge.ts @@ -3,11 +3,6 @@ import { LGraphIcon } from './LGraphIcon' import type { LGraphIconOptions } from './LGraphIcon' import { cachedMeasureText } from './utils/textMeasureCache' -export enum BadgePosition { - TopLeft = 'top-left', - TopRight = 'top-right' -} - export interface LGraphBadgeOptions { text: string fgColor?: string diff --git a/src/lib/litegraph/src/LGraphNode.ts b/src/lib/litegraph/src/LGraphNode.ts index 7f9e6e4ffe2..f162c7fa093 100644 --- a/src/lib/litegraph/src/LGraphNode.ts +++ b/src/lib/litegraph/src/LGraphNode.ts @@ -27,7 +27,8 @@ import { import { cachedMeasureText } from '@/lib/litegraph/src/utils/textMeasureCache' import type { DragAndScale } from './DragAndScale' import type { LGraph } from './LGraph' -import { BadgePosition, LGraphBadge } from './LGraphBadge' +import { LGraphBadge } from './LGraphBadge' +import { badgeDrawObjects, badgeRows } from './nodeBadgeDraw' import { LGraphButton } from './LGraphButton' import type { LGraphButtonOptions } from './LGraphButton' import { LGraphCanvas } from './LGraphCanvas' @@ -420,9 +421,26 @@ export class LGraphNode widgets_start_y?: number lostFocusAt?: number gotFocusAt?: number + /** + * Extension-provided badges, drawn after the derived rows from + * {@link badgeRows}. Thunks are re-evaluated every frame. + */ badges: (LGraphBadge | (() => LGraphBadge))[] = [] + /** @deprecated Badges always render top-right; assignment is ignored. */ + get badgePosition(): string { + warnDeprecated( + 'LGraphNode.badgePosition is deprecated: badges always render top-right.', + this + ) + return 'top-right' + } + set badgePosition(_value: string) { + warnDeprecated( + 'LGraphNode.badgePosition is deprecated: badges always render top-right.', + this + ) + } title_buttons: LGraphButton[] = [] - badgePosition: BadgePosition = BadgePosition.TopLeft onOutputRemoved?(this: LGraphNode, slot: number): void onInputRemoved?(this: LGraphNode, slot: number, input: INodeInputSlot): void /** @@ -3594,18 +3612,16 @@ export class LGraphNode } drawBadges(ctx: CanvasRenderingContext2D, { gap = 2 } = {}): void { - const badgeInstances = this.badges.map((badge) => - badge instanceof LGraphBadge ? badge : badge() - ) - const isLeftAligned = this.badgePosition === BadgePosition.TopLeft - - let currentX = isLeftAligned - ? 0 - : this.width - - badgeInstances.reduce( - (acc, badge) => acc + badge.getWidth(ctx) + gap, - 0 - ) + const badgeInstances = [ + ...badgeDrawObjects(this, badgeRows(this)), + ...this.badges.map((badge) => + badge instanceof LGraphBadge ? badge : badge() + ) + ] + + let currentX = + this.width - + badgeInstances.reduce((acc, badge) => acc + badge.getWidth(ctx) + gap, 0) const y = -(LiteGraph.NODE_TITLE_HEIGHT + gap) for (const badge of badgeInstances) { diff --git a/src/lib/litegraph/src/litegraph.ts b/src/lib/litegraph/src/litegraph.ts index 62e0a7763d9..70a5616af3e 100644 --- a/src/lib/litegraph/src/litegraph.ts +++ b/src/lib/litegraph/src/litegraph.ts @@ -114,7 +114,7 @@ export { type SubgraphId } from './LGraph' export type { LGraphTriggerEvent } from './types/graphTriggers' -export { BadgePosition, LGraphBadge } from './LGraphBadge' +export { LGraphBadge } from './LGraphBadge' export { LGraphCanvas } from './LGraphCanvas' export { LGraphGroup, type GroupId } from './LGraphGroup' export { LGraphNode } from './LGraphNode' diff --git a/src/lib/litegraph/src/nodeBadgeDraw.test.ts b/src/lib/litegraph/src/nodeBadgeDraw.test.ts new file mode 100644 index 00000000000..b3c7ad64668 --- /dev/null +++ b/src/lib/litegraph/src/nodeBadgeDraw.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from 'vitest' + +import type { BadgeData, CoreBadgeData } from '@/types/badgeData' + +import { LGraphNode } from '@/lib/litegraph/src/litegraph' +import { badgeDrawObjects } from './nodeBadgeDraw' + +function coreRow(part: CoreBadgeData['part'], text: string): BadgeData { + return { kind: 'core', part, text, fgColor: '#fff', bgColor: '#000' } +} + +describe('badgeDrawObjects', () => { + it('joins core parts into one badge in id, lifecycle, source order', () => { + const badges = badgeDrawObjects(new LGraphNode('n'), [ + coreRow('lifecycle', '[BETA]'), + coreRow('id', '#5'), + coreRow('source', 'my-pack') + ]) + + expect(badges).toHaveLength(1) + expect(badges[0].text).toBe('#5 [BETA] my-pack') + expect(badges[0].fgColor).toBe('#fff') + expect(badges[0].bgColor).toBe('#000') + }) + + it('truncates the joined core text', () => { + const badges = badgeDrawObjects(new LGraphNode('n'), [ + coreRow('source', 'a'.repeat(40)), + coreRow('id', '#5') + ]) + + expect(badges[0].text).toHaveLength(31) + expect(badges[0].text.endsWith('...')).toBe(true) + }) + + it('draws credits rows separately with their icon', () => { + const badges = badgeDrawObjects(new LGraphNode('n'), [ + coreRow('id', '#5'), + { + kind: 'credits', + text: '$0.04', + fgColor: '#fff', + bgColor: '#8D6932' + } + ]) + + expect(badges).toHaveLength(2) + expect(badges[1].text).toBe('$0.04') + expect(badges[1].bgColor).toBe('#8D6932') + expect(badges[1].icon?.size).toBe(8) + expect(badges[1].icon?.image).toBeInstanceOf(Image) + }) + + it('reuses draw objects until the rows array is replaced', () => { + const node = new LGraphNode('n') + const rows: BadgeData[] = [coreRow('id', '#5')] + + const first = badgeDrawObjects(node, rows) + const second = badgeDrawObjects(node, rows) + expect(second[0]).toBe(first[0]) + + const third = badgeDrawObjects(node, [coreRow('id', '#6')]) + expect(third[0]).not.toBe(first[0]) + expect(third[0].text).toBe('#6') + }) +}) diff --git a/src/lib/litegraph/src/nodeBadgeDraw.ts b/src/lib/litegraph/src/nodeBadgeDraw.ts new file mode 100644 index 00000000000..fc320fe13d8 --- /dev/null +++ b/src/lib/litegraph/src/nodeBadgeDraw.ts @@ -0,0 +1,107 @@ +import { truncate } from 'es-toolkit/compat' + +import { CORE_JOIN_ORDER } from '@/types/badgeData' +import type { BadgeData, CoreBadgeData } from '@/types/badgeData' + +import { LGraphBadge } from './LGraphBadge' +import type { LGraphIconOptions } from './LGraphIcon' +import type { LGraphNode } from './LGraphNode' + +const CORE_TEXT_LIMIT = 31 + +let creditsIconOptions: LGraphIconOptions | undefined + +function getCreditsIconOptions(): LGraphIconOptions { + if (!creditsIconOptions) { + const image = new Image() + image.src = + "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath fill='none' stroke='oklch(83.01%25 0.163 83.16)' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M15.536 11.293a1 1 0 0 0 0 1.414l2.376 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0zm-13.239 0a1 1 0 0 0 0 1.414l2.377 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414L6.088 8.916a1 1 0 0 0-1.414 0zm6.619 6.619a1 1 0 0 0 0 1.415l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.415l-2.377-2.376a1 1 0 0 0-1.414 0zm0-13.238a1 1 0 0 0 0 1.414l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z'/%3E%3C/svg%3E" + creditsIconOptions = { image, size: 8 } + } + return creditsIconOptions +} + +function joinedCoreText(coreRows: readonly CoreBadgeData[]): string { + const byPart = new Map(coreRows.map((row) => [row.part, row.text])) + return truncate( + CORE_JOIN_ORDER.map((part) => byPart.get(part) ?? '') + .filter((text) => text.length > 0) + .join(' '), + { length: CORE_TEXT_LIMIT } + ) +} + +function buildDrawObjects(rows: readonly BadgeData[]): LGraphBadge[] { + const badges: LGraphBadge[] = [] + + const coreRows = rows.filter((row) => row.kind === 'core') + const [firstCore] = coreRows + if (firstCore) { + const coreText = joinedCoreText(coreRows) + if (coreText) { + badges.push( + new LGraphBadge({ + text: coreText, + fgColor: firstCore.fgColor, + bgColor: firstCore.bgColor + }) + ) + } + } + + for (const row of rows) { + if (row.kind === 'core') continue + badges.push( + new LGraphBadge({ + text: row.text, + fgColor: row.fgColor, + bgColor: row.bgColor, + iconOptions: getCreditsIconOptions() + }) + ) + } + return badges +} + +const EMPTY_BADGE_ROWS: readonly BadgeData[] = [] + +export function badgeRows(node: LGraphNode): readonly BadgeData[] { + return rowsProvider?.(node) ?? EMPTY_BADGE_ROWS +} + +type BadgeRowsProvider = typeof badgeRows + +let rowsProvider: BadgeRowsProvider | undefined + +/** + * Installs the app-layer badge derivation. A seam so litegraph never + * imports the derivation's store/pricing dependency graph. + */ +export function registerBadgeRowsProvider(provider: BadgeRowsProvider): void { + if (rowsProvider && rowsProvider !== provider) { + console.error('A badge rows provider is already registered') + return + } + rowsProvider = provider +} + +const drawCache = new WeakMap< + LGraphNode, + { rows: readonly BadgeData[]; badges: LGraphBadge[] } +>() + +/** + * The legacy canvas draw objects for a node's badge rows. The store + * replaces a node's rows array wholesale per write, so array identity + * doubles as the rebuild key. + */ +export function badgeDrawObjects( + node: LGraphNode, + rows: readonly BadgeData[] +): LGraphBadge[] { + const cached = drawCache.get(node) + if (cached?.rows === rows) return cached.badges + const badges = buildDrawObjects(rows) + drawCache.set(node, { rows, badges }) + return badges +} diff --git a/src/locales/en/main.json b/src/locales/en/main.json index f16c5ad2e86..bd94a5fdffd 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -2246,6 +2246,9 @@ "failedToToggleGizmo": "Failed to toggle gizmo", "failedToSetGizmoMode": "Failed to set gizmo mode" }, + "nodeBadge": { + "partnerNodesCount": "Partner Nodes x {count}" + }, "nodeErrors": { "render": "Node Render Error", "content": "Node Content Error", diff --git a/src/renderer/extensions/linearMode/PartnerNodesList.vue b/src/renderer/extensions/linearMode/PartnerNodesList.vue index f94a4af6503..ed150315aa9 100644 --- a/src/renderer/extensions/linearMode/PartnerNodesList.vue +++ b/src/renderer/extensions/linearMode/PartnerNodesList.vue @@ -4,33 +4,24 @@ import { CollapsibleRoot, CollapsibleTrigger } from 'reka-ui' -import { computed, toValue } from 'vue' +import { computed } from 'vue' import { useI18n } from 'vue-i18n' import Button from '@/components/ui/button/Button.vue' import Popover from '@/components/ui/Popover.vue' -import { usePriceBadge } from '@/composables/node/usePriceBadge' +import { useCanvasStore } from '@/renderer/core/canvas/canvasStore' import PartnerNodeItem from '@/renderer/extensions/linearMode/PartnerNodeItem.vue' -import { trackNodePrice } from '@/renderer/extensions/vueNodes/composables/usePartitionedBadges' -import { app } from '@/scripts/app' -import { mapAllNodes } from '@/utils/graphTraversalUtil' +import { graphCreditsBadges } from '@/systems/badgeSystem' defineProps<{ mobile?: boolean }>() -const { isCreditsBadge } = usePriceBadge() const { t } = useI18n() +const canvasStore = useCanvasStore() -const creditsBadges = computed(() => - mapAllNodes(app.graph, (node) => { - if (node.isSubgraphNode()) return - - const priceBadge = node.badges.find(isCreditsBadge) - if (!priceBadge) return - - trackNodePrice(node) - return [node.title, toValue(priceBadge).text, node.id] as const - }) -) +const creditsBadges = computed(() => { + const rootGraph = canvasStore.currentGraph?.rootGraph + return rootGraph ? graphCreditsBadges(rootGraph) : [] +})