Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
fix(canvas): stop a canvas save from reverting a device edited elsewhere
Pouzor0c7fd3c12774
diff --git a/backend/app/api/routes/canvas.py b/backend/app/api/routes/canvas.pyindex 722450d..8b80233 100644--- a/backend/app/api/routes/canvas.py+++ b/backend/app/api/routes/canvas.py@@ -87,7 +87,7 @@ async def save_canvas(# Upsert nodes, then route their device facts to the inventory row that owns# them — an edit made on this canvas is an edit to the device itself, and# every other canvas showing it follows.- saved: list[tuple[Node, dict[str, Any]]] = []+ saved: list[tuple[Node, dict[str, Any], list[str] | None]] = []for node_data in body.nodes:db_node = await db.get(Node, node_data.id)payload = node_data.model_dump()@@ -100,11 +100,25 @@ async def save_canvas(else:db_node = Node(**columns)db.add(db_node)- saved.append((db_node, facts))+ saved.append((db_node, facts, node_data.changed_facts))await db.flush()- for node, facts in saved:- await link_facts(db, node, facts, overwrite_scalars=True, replace_lists=True)+ for node, facts, changed in saved:+ # The payload carries a full copy of each device, hydrated when this+ # canvas loaded. Routing all of it back would rewrite the row from a+ # stale snapshot — a save made for nothing but a moved node could revert+ # an edit meanwhile in the inventory modal. `changed_facts` (when the+ # client tracked it) plus the row diff narrow the write to this canvas'+ # actual edit.+ await link_facts(+ db,+ node,+ facts,+ overwrite_scalars=True,+ replace_lists=True,+ only_changed=True,+ changed_fields=changed,+ )# Upsert edgesfor edge_data in body.edges:diff --git a/backend/app/schemas/canvas.py b/backend/app/schemas/canvas.pyindex a7edc89..5fa2bc7 100644--- a/backend/app/schemas/canvas.py+++ b/backend/app/schemas/canvas.py@@ -15,6 +15,13 @@ class NodeSave(BaseModel):# device fields below are still accepted at their canvas values and routed# to that row server-side.device_id: str | None = None+ # Which device facts this canvas edited since it loaded them, if the client+ # tracked that. The payload always carries a *full* copy of the device — it+ # was hydrated from the inventory row on load — so without this a save made+ # for nothing but a moved node would rewrite the row from a snapshot that may+ # be hours old. `None` (an older client, an import, the MCP server) keeps the+ # previous behaviour: every fact is a candidate write.+ changed_facts: list[str] | None = Nonehostname: str | None = Noneip: str | None = Nonemac: str | None = Nonediff --git a/backend/app/services/inventory_sync.py b/backend/app/services/inventory_sync.pyindex 165529a..5425dc6 100644--- a/backend/app/services/inventory_sync.py+++ b/backend/app/services/inventory_sync.py@@ -172,6 +172,55 @@ def merge_services(base: list[Any] | None, incoming: list[Any] | None) -> list[Areturn out+# Observations rather than edits: the checker and the scanner write these, so a+# client never lists them as changed and they survive a `changed_fields` filter.+_LIVE_FACT_FIELDS = frozenset({"status", "last_seen", "last_scan", "response_time_ms"})+++def changed_facts(device: InventoryDevice, facts: Mapping[str, Any]) -> dict[str, Any]:+ """The subset of ``facts`` that actually differs from the row.++ A canvas save sends a *full* copy of the device — the facts were hydrated+ into the node when the canvas loaded — so a save triggered by nothing but a+ node being dragged would otherwise rewrite the row from a snapshot that may+ be minutes or hours old, silently reverting an edit made meanwhile in the+ inventory modal, on another canvas, or by the scanner. Narrowing to what the+ sender changed turns the write-through from "push my whole snapshot" into+ "push my edit", so two writers only collide on the same field.++ The comparison mirrors :func:`merge_facts_into_device`: a blank incoming+ value is not a change (it never clears an established one), and a list+ counts as changed only when it would actually be replaced by a different+ one. Ambiguity is resolved toward reporting a change — a false positive is+ the old behaviour for that field, a false negative would drop a real edit.+ """+ out: dict[str, Any] = {}+ for field in (*DEVICE_SCALARS, "label", "type"):+ incoming = facts.get(field)+ if _blank(incoming) or incoming == getattr(device, field, None):+ continue+ out[field] = incoming++ if not _blank(facts.get("ieee_address")) and _blank(device.ieee_address):+ out["ieee_address"] = facts["ieee_address"]+ if facts.get("show_hardware") and not device.show_hardware:+ out["show_hardware"] = facts["show_hardware"]++ if "properties" in facts and list(facts["properties"] or []) != list(device.properties or []):+ out["properties"] = facts["properties"]+ if "services" in facts and list(facts["services"] or []) != list(device.services or []):+ out["services"] = facts["services"]++ # Live observations, not edits: carried through only where the merge would+ # have used them — filling a row that has never been checked.+ if facts.get("status") and device.status_live in (None, "", "unknown"):+ out["status"] = facts["status"]+ for field in ("last_seen", "last_scan", "response_time_ms"):+ if facts.get(field) is not None:+ out[field] = facts[field]+ return out++def merge_facts_into_device(device: InventoryDevice,facts: Mapping[str, Any],@@ -279,6 +328,8 @@ async def link_facts(*,overwrite_scalars: bool = False,replace_lists: bool = False,+ only_changed: bool = False,+ changed_fields: list[str] | None = None,) -> InventoryDevice | None:"""Point one node at its inventory row, creating or merging as needed.@@ -286,6 +337,16 @@ async def link_facts(or a legacy node's columns during the backfill. Returns the row, or ``None``for canvas furniture. Flushes so a freshly minted row has an id to link to,but does not commit.++ Two narrowings turn a save from "push my whole snapshot" into "push my edit",+ and they compose. Identity matching always uses the full ``facts`` — the row+ has to be found before it can be narrowed against.++ * ``changed_fields`` — what the sender says it edited since it loaded the+ device. Authoritative: a fact absent from the list is not written even when+ it differs, because the difference means the *row* moved on, not the sender.+ * ``only_changed`` — drop facts already equal to the row (see+ :func:`changed_facts`), so a no-op save writes nothing at all."""if is_furniture(node.type):node.device_id = None@@ -304,8 +365,17 @@ async def link_facts(db.add(device)await db.flush()else:+ merged = dict(facts)+ if changed_fields is not None:+ keep = set(changed_fields) | _LIVE_FACT_FIELDS+ merged = {k: v for k, v in merged.items() if k in keep}+ if only_changed:+ merged = changed_facts(device, merged)merge_facts_into_device(- device, facts, overwrite_scalars=overwrite_scalars, replace_lists=replace_lists+ device,+ merged,+ overwrite_scalars=overwrite_scalars,+ replace_lists=replace_lists,)device.discovery_sources = add_source(device.discovery_sources, CANVAS_SOURCE)diff --git a/backend/tests/test_inventory_sync.py b/backend/tests/test_inventory_sync.pyindex 0d03860..687f9df 100644--- a/backend/tests/test_inventory_sync.py+++ b/backend/tests/test_inventory_sync.py@@ -15,6 +15,7 @@ from sqlalchemy import select, textfrom app.db.models import Design, InventoryDevice, Nodefrom app.services.inventory_sync import (backfill_node_devices,+ changed_facts,find_device_for,merge_properties,merge_services,@@ -81,6 +82,64 @@ class TestMergeRules:assert out[1]["port"] == 80+class TestChangedFacts:+ """What a save is allowed to write: its edit, not its whole snapshot."""++ def test_an_unchanged_snapshot_writes_nothing(self):+ device = InventoryDevice(+ id="d-1",+ label="NAS",+ type="nas",+ hostname="nas.lan",+ ip="10.0.0.5",+ notes="in the garage",+ status_live="online",+ properties=[{"key": "Rack", "value": "A1", "icon": None, "visible": True}],+ services=[{"port": 22, "protocol": "tcp", "service_name": "ssh"}],+ )+ facts = {+ "label": "NAS",+ "type": "nas",+ "hostname": "nas.lan",+ "ip": "10.0.0.5",+ "notes": "in the garage",+ "status": "online",+ "properties": [{"key": "Rack", "value": "A1", "icon": None, "visible": True}],+ "services": [{"port": 22, "protocol": "tcp", "service_name": "ssh"}],+ }+ assert changed_facts(device, facts) == {}++ def test_only_the_edited_field_survives(self):+ device = InventoryDevice(id="d-1", hostname="nas.lan", ip="10.0.0.5", notes="old")+ facts = {"hostname": "nas.lan", "ip": "10.0.0.5", "notes": "new"}+ assert changed_facts(device, facts) == {"notes": "new"}++ def test_a_blank_incoming_value_is_not_a_change(self):+ # A blank never clears an established value, so it is not an edit either.+ device = InventoryDevice(id="d-1", hostname="nas.lan", notes="keep me")+ assert changed_facts(device, {"hostname": "", "notes": None}) == {}++ def test_a_changed_list_is_sent_whole(self):+ device = InventoryDevice(+ id="d-1",+ properties=[{"key": "Rack", "value": "A1", "icon": None, "visible": True}],+ services=[{"port": 22, "protocol": "tcp", "service_name": "ssh"}],+ )+ facts = {+ "properties": [],+ "services": [{"port": 22, "protocol": "tcp", "service_name": "ssh"}],+ }+ # Replace semantics need the full list, and the untouched one stays out.+ assert changed_facts(device, facts) == {"properties": []}++ def test_live_status_only_fills_a_row_never_checked(self):+ unknown = InventoryDevice(id="d-1", status_live="unknown")+ assert changed_facts(unknown, {"status": "online"}) == {"status": "online"}+ checked = InventoryDevice(id="d-2", status_live="offline")+ # The status checker owns reachability; a stale canvas must not reset it.+ assert changed_facts(checked, {"status": "online"}) == {}++# --- matching ---------------------------------------------------------------@@ -410,6 +469,209 @@ class TestRoutesKeepTheLinkInStep:await db_session.refresh(device)assert device.properties == []+ @pytest.mark.asyncio+ async def test_a_canvas_save_does_not_revert_an_inventory_edit(+ self, client: AsyncClient, headers, db_session+ ):+ """Regression: a save carries this canvas' edit, not its stale snapshot.++ The canvas payload holds a full copy of the device, hydrated when it+ loaded. Editing the device elsewhere and then saving the still-open+ canvas — for nothing but a moved node — must not roll the row back.+ """+ db_session.add(+ InventoryDevice(+ id="d-1",+ ip="10.0.0.5",+ label="NAS",+ type="nas",+ notes="old note",+ status="approved",+ properties=[{"key": "Rack", "value": "A1", "icon": None, "visible": True}],+ )+ )+ await db_session.commit()+ design_id = (await client.post("/api/v1/designs", json={"name": "A"}, headers=headers)).json()["id"]++ # What the canvas loaded and still holds in memory.+ stale = {+ "id": str(uuid.uuid4()),+ "type": "nas",+ "label": "NAS",+ "status": "unknown",+ "pos_x": 0,+ "pos_y": 0,+ "ip": "10.0.0.5",+ "notes": "old note",+ "properties": [{"key": "Rack", "value": "A1", "icon": None, "visible": True}],+ }+ res = await client.post(+ "/api/v1/canvas/save",+ json={"design_id": design_id, "nodes": [stale], "edges": [], "viewport": {}},+ headers=headers,+ )+ assert res.status_code == 200++ # Meanwhile, in the Device Inventory modal.+ res = await client.patch(+ "/api/v1/scan/pending/d-1",+ json={+ "notes": "moved to the loft",+ "properties": [+ {"key": "Rack", "value": "A1", "icon": None, "visible": True},+ {"key": "Owner", "value": "me", "icon": None, "visible": True},+ ],+ },+ headers=headers,+ )+ assert res.status_code == 200++ # The canvas saves again — only the node position changed, so it claims+ # no device edit at all.+ res = await client.post(+ "/api/v1/canvas/save",+ json={+ "design_id": design_id,+ "nodes": [{**stale, "pos_x": 240, "changed_facts": []}],+ "edges": [],+ "viewport": {},+ },+ headers=headers,+ )+ assert res.status_code == 200++ device = await db_session.get(InventoryDevice, "d-1")+ await db_session.refresh(device)+ assert device.notes == "moved to the loft"+ assert [p["key"] for p in device.properties] == ["Rack", "Owner"]++ @pytest.mark.asyncio+ async def test_a_canvas_save_still_writes_what_that_canvas_changed(+ self, client: AsyncClient, headers, db_session+ ):+ """The narrowing must not cost the write-through: an edit still lands."""+ db_session.add(InventoryDevice(id="d-1", ip="10.0.0.5", label="NAS", type="nas", notes="old note"))+ await db_session.commit()+ design_id = (await client.post("/api/v1/designs", json={"name": "A"}, headers=headers)).json()["id"]+ node = {+ "id": str(uuid.uuid4()),+ "type": "nas",+ "label": "NAS",+ "status": "unknown",+ "pos_x": 0,+ "pos_y": 0,+ "ip": "10.0.0.5",+ "notes": "old note",+ }+ await client.post(+ "/api/v1/canvas/save",+ json={"design_id": design_id, "nodes": [node], "edges": [], "viewport": {}},+ headers=headers,+ )++ res = await client.post(+ "/api/v1/canvas/save",+ json={+ "design_id": design_id,+ "nodes": [+ {+ **node,+ "notes": "edited on the canvas",+ "hostname": "nas.lan",+ "changed_facts": ["notes", "hostname"],+ }+ ],+ "edges": [],+ "viewport": {},+ },+ headers=headers,+ )+ assert res.status_code == 200++ device = await db_session.get(InventoryDevice, "d-1")+ await db_session.refresh(device)+ assert device.notes == "edited on the canvas"+ assert device.hostname == "nas.lan"++ @pytest.mark.asyncio+ async def test_an_edit_writes_without_dragging_the_rest_of_the_snapshot(+ self, client: AsyncClient, headers, db_session+ ):+ """One edited fact lands; the stale fields beside it stay out of the write."""+ db_session.add(+ InventoryDevice(id="d-1", ip="10.0.0.5", label="NAS", type="nas", notes="old note")+ )+ await db_session.commit()+ design_id = (await client.post("/api/v1/designs", json={"name": "A"}, headers=headers)).json()["id"]+ node = {+ "id": str(uuid.uuid4()),+ "type": "nas",+ "label": "NAS",+ "status": "unknown",+ "pos_x": 0,+ "pos_y": 0,+ "ip": "10.0.0.5",+ "notes": "old note",+ }+ await client.post(+ "/api/v1/canvas/save",+ json={"design_id": design_id, "nodes": [node], "edges": [], "viewport": {}},+ headers=headers,+ )+ await client.patch("/api/v1/scan/pending/d-1", json={"notes": "moved to the loft"}, headers=headers)++ # The canvas renames the node; its `notes` copy is stale but unedited.+ await client.post(+ "/api/v1/canvas/save",+ json={+ "design_id": design_id,+ "nodes": [{**node, "label": "Big NAS", "changed_facts": ["label"]}],+ "edges": [],+ "viewport": {},+ },+ headers=headers,+ )++ device = await db_session.get(InventoryDevice, "d-1")+ await db_session.refresh(device)+ assert device.label == "Big NAS"+ assert device.notes == "moved to the loft"++ @pytest.mark.asyncio+ async def test_a_client_that_tracks_no_changes_still_writes_its_facts(+ self, client: AsyncClient, headers, db_session+ ):+ """Backward compatible: an import or older client omits the field entirely."""+ db_session.add(InventoryDevice(id="d-1", ip="10.0.0.5", notes="old note"))+ await db_session.commit()+ design_id = (await client.post("/api/v1/designs", json={"name": "A"}, headers=headers)).json()["id"]++ await client.post(+ "/api/v1/canvas/save",+ json={+ "design_id": design_id,+ "nodes": [+ {+ "id": str(uuid.uuid4()),+ "type": "nas",+ "label": "NAS",+ "status": "unknown",+ "pos_x": 0,+ "pos_y": 0,+ "ip": "10.0.0.5",+ "notes": "from the import",+ }+ ],+ "edges": [],+ "viewport": {},+ },+ headers=headers,+ )++ device = await db_session.get(InventoryDevice, "d-1")+ await db_session.refresh(device)+ assert device.notes == "from the import"+@pytest.mark.asyncioasync def test_the_second_canvas_sees_the_first_canvas_edit(self, client: AsyncClient, headers, db_session):"""No per-node overrides: one device, one set of facts, every canvas."""diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex c26560f..98e06ce 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -167,7 +167,10 @@ export default function App() {if (!options?.silent) toast.success('Canvas saved')return true}- const nodesToSave = nodes.map(serializeNode)+ // Read the baseline at save time (not through the render-time destructure)+ // so a device edited in the inventory a moment ago is already rebased.+ const factsBaseline = useCanvasStore.getState().factsBaseline+ const nodesToSave = nodes.map((n) => serializeNode(n, factsBaseline[n.id]))const edgesToSave = edges.map(serializeEdge)const viewport: Record<string, unknown> = { theme_id: activeTheme }if (floorMap) viewport.floor_map = floorMapdiff --git a/frontend/src/components/modals/InventoryDeviceModal.tsx b/frontend/src/components/modals/InventoryDeviceModal.tsxindex 1d37f59..dd97a31 100644--- a/frontend/src/components/modals/InventoryDeviceModal.tsx+++ b/frontend/src/components/modals/InventoryDeviceModal.tsx@@ -41,7 +41,9 @@ import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectSepaimport { PropertyList } from '@/components/common/PropertyList'import { ServiceModal } from './ServiceModal'import { scanApi } from '@/api/client'+import { useCanvasStore } from '@/stores/canvasStore'import { useThemeStore } from '@/stores/themeStore'+import { deviceFactsToNodeData } from '@/utils/deviceFacts'import { resolveNodeColors } from '@/utils/nodeColors'import { NODE_TYPE_DEFAULT_ICONS } from '@/utils/nodeIcons'import { isRackDevice, orderedSources, SOURCE_META } from '@/utils/deviceSources'@@ -341,6 +343,11 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgnproperties,services,})+ // Push the row straight into the canvas on screen. Its nodes carry a copy+ // of these facts, loaded before this edit — left stale, the next canvas+ // save (even one for a moved node) would report them as an edit and roll+ // the row back.+ useCanvasStore.getState().applyDeviceFacts(device.id, deviceFactsToNodeData(res.data))toast.success('Device updated')setEditing(false)onSaved?.(res.data)diff --git a/frontend/src/stores/__tests__/canvasStore/deviceFacts.test.ts b/frontend/src/stores/__tests__/canvasStore/deviceFacts.test.tsnew file mode 100644index 0000000..8c19ede--- /dev/null+++ b/frontend/src/stores/__tests__/canvasStore/deviceFacts.test.ts@@ -0,0 +1,98 @@+/**+ * The device-fact baseline: what the canvas was given for each node, so a save+ * can report its own edits instead of pushing a stale snapshot over an edit made+ * meanwhile in the Device Inventory.+ */+import { describe, it, expect, beforeEach } from 'vitest'+import { useCanvasStore } from '@/stores/canvasStore'+import { changedFactFields } from '@/utils/deviceFacts'+import { makeNode, makeNodeData } from '@/test/factories'++function resetStore() {+ useCanvasStore.setState({+ nodes: [],+ edges: [],+ hasUnsavedChanges: false,+ editSeq: 0,+ selectedNodeId: null,+ selectedNodeIds: [],+ past: [],+ future: [],+ factsBaseline: {},+ })+}++const loadedNode = (id = 'n1', deviceId = 'd-1') =>+ makeNode(id, makeNodeData({ device_id: deviceId, label: 'NAS', ip: '10.0.0.5', notes: 'in the garage' }))++describe('canvasStore — device fact baseline', () => {+ beforeEach(resetStore)++ it('loadCanvas records what the server sent', () => {+ const node = loadedNode()+ useCanvasStore.getState().loadCanvas([node], [])+ const { factsBaseline } = useCanvasStore.getState()+ expect(changedFactFields(node.data, factsBaseline.n1)).toEqual([])+ })++ it('an edited node reports only what it edited', () => {+ useCanvasStore.getState().loadCanvas([loadedNode()], [])+ useCanvasStore.getState().updateNode('n1', { notes: 'moved to the loft' })+ const { nodes, factsBaseline } = useCanvasStore.getState()+ expect(changedFactFields(nodes[0].data, factsBaseline.n1)).toEqual(['notes'])+ })++ it('markSaved rebases, so the next save claims nothing', () => {+ useCanvasStore.getState().loadCanvas([loadedNode()], [])+ useCanvasStore.getState().updateNode('n1', { notes: 'moved to the loft' })+ useCanvasStore.getState().markSaved()+ const { nodes, factsBaseline } = useCanvasStore.getState()+ expect(changedFactFields(nodes[0].data, factsBaseline.n1)).toEqual([])+ })+})++describe('canvasStore — applyDeviceFacts', () => {+ beforeEach(resetStore)++ it('spreads an inventory edit onto every node drawing that device', () => {+ useCanvasStore.getState().loadCanvas([loadedNode('n1'), loadedNode('n2')], [])+ useCanvasStore.getState().applyDeviceFacts('d-1', { notes: 'moved to the loft' })+ expect(useCanvasStore.getState().nodes.map((n) => n.data.notes)).toEqual([+ 'moved to the loft',+ 'moved to the loft',+ ])+ })++ it('leaves a node drawing another device alone', () => {+ useCanvasStore.getState().loadCanvas([loadedNode('n1', 'd-1'), loadedNode('n2', 'd-2')], [])+ useCanvasStore.getState().applyDeviceFacts('d-1', { notes: 'moved to the loft' })+ expect(useCanvasStore.getState().nodes[1].data.notes).toBe('in the garage')+ })++ it('rebases what it applied, so the canvas does not claim the row edit as its own', () => {+ useCanvasStore.getState().loadCanvas([loadedNode()], [])+ useCanvasStore.getState().applyDeviceFacts('d-1', { notes: 'moved to the loft' })+ const { nodes, factsBaseline } = useCanvasStore.getState()+ expect(changedFactFields(nodes[0].data, factsBaseline.n1)).toEqual([])+ })++ it('is not a canvas edit — the row already holds it', () => {+ useCanvasStore.getState().loadCanvas([loadedNode()], [])+ useCanvasStore.getState().applyDeviceFacts('d-1', { notes: 'moved to the loft' })+ expect(useCanvasStore.getState().hasUnsavedChanges).toBe(false)+ expect(useCanvasStore.getState().editSeq).toBe(0)+ })++ it('keeps a pending canvas edit when the same device changes elsewhere', () => {+ useCanvasStore.getState().loadCanvas([loadedNode()], [])+ useCanvasStore.getState().updateNode('n1', { label: 'Big NAS' })+ // The row carries its own (older) label alongside the edited note.+ useCanvasStore.getState().applyDeviceFacts('d-1', { label: 'NAS', notes: 'moved to the loft' })+ const { nodes, factsBaseline } = useCanvasStore.getState()+ // Unsaved work in progress is not overwritten by the row…+ expect(nodes[0].data.label).toBe('Big NAS')+ expect(nodes[0].data.notes).toBe('moved to the loft')+ // …and is still this canvas' to save. The note is not.+ expect(changedFactFields(nodes[0].data, factsBaseline.n1)).toEqual(['label'])+ })+})diff --git a/frontend/src/stores/canvasStore.ts b/frontend/src/stores/canvasStore.tsindex c15a9bd..def0f18 100644--- a/frontend/src/stores/canvasStore.ts+++ b/frontend/src/stores/canvasStore.ts@@ -15,6 +15,7 @@ import { normalizeHandle, removedHandleIds, handleCountField, sideDefault, handlimport { applyOpacity } from '@/utils/colorUtils'import { readHideIp, writeHideIp } from '@/utils/ipDisplay'import { CONTAINER_MODE_TYPES } from '@/utils/virtualEdgeParent'+import { changedFactFields, factsBaselineOf, factsBaselines, type FactsBaseline } from '@/utils/deviceFacts'type HistoryEntry = { nodes: Node<NodeData>[]; edges: Edge<EdgeData>[] }type Clipboard = { nodes: Node<NodeData>[]; edges: Edge<EdgeData>[] }@@ -122,6 +123,19 @@ interface CanvasState {selectedNodeId: string | nullselectedNodeIds: string[]scanEventTs: number+ /**+ * The device facts as this canvas received them, per node id. A save diffs+ * against it to tell the backend what *this* canvas edited, so a save made for+ * nothing but a moved node cannot push a stale snapshot over an edit made+ * meanwhile in the Device Inventory. Refreshed on load and on save.+ */+ factsBaseline: Record<string, FactsBaseline>+ /**+ * Apply an inventory row's facts to every node drawing that device, and rebase+ * them. Not an edit — the row is already persisted — so it leaves+ * hasUnsavedChanges alone.+ */+ applyDeviceFacts: (deviceId: string, facts: Partial<NodeData>) => void// Live per-service status overlay (not persisted), keyed via serviceStatusKey.serviceStatuses: Record<string, ServiceStatus>@@ -230,6 +244,7 @@ export const useCanvasStore = create<CanvasState>((rawSet) => {editingTextId: null,hideIp: readHideIp(),scanEventTs: 0,+ factsBaseline: {},serviceStatuses: {},floorMap: null,floorMapEditNonce: 0,@@ -905,7 +920,40 @@ export const useCanvasStore = create<CanvasState>((rawSet) => {}}),- markSaved: () => set({ hasUnsavedChanges: false }),+ // The save just became the server's truth, so it is the new baseline: the next+ // save reports only what is edited from here on.+ markSaved: () => set((state) => ({ hasUnsavedChanges: false, factsBaseline: factsBaselines(state.nodes) })),++ applyDeviceFacts: (deviceId, facts) =>+ set((state) => {+ let changed = false+ const factsBaseline = { ...state.factsBaseline }+ const nodes = state.nodes.map((n) => {+ if (n.data.device_id !== deviceId) return n+ const previous = state.factsBaseline[n.id]+ // A fact this canvas has already edited but not saved is the user's+ // work in progress — the row does not get to overwrite it on screen.+ const pending = new Set<string>(changedFactFields(n.data, previous))+ const applied = Object.fromEntries(+ Object.entries(facts).filter(([field]) => !pending.has(field)),+ )+ if (Object.keys(applied).length === 0) return n+ changed = true+ const data = { ...n.data, ...applied }+ // Rebase only what was applied: an untouched pending edit stays reported+ // as this canvas' change so the next save still writes it.+ const rebased = factsBaselineOf(data)+ for (const field of pending) {+ if (previous?.[field] !== undefined) rebased[field] = previous[field]+ }+ factsBaseline[n.id] = rebased+ return { ...n, data }+ })+ // No hasUnsavedChanges: the row already holds this, the canvas is catching+ // up. Rebasing alongside is what keeps the next save from claiming the+ // inventory's own edit as a canvas edit.+ return changed ? { nodes, factsBaseline } : {}+ }),markUnsaved: () => set({ hasUnsavedChanges: true }),@@ -948,7 +996,17 @@ export const useCanvasStore = create<CanvasState>((rawSet) => {const children = nodes.filter((n) => !!n.parentId)// NOTE: clipboard is intentionally preserved here so nodes copied in one// design can be pasted after switching to another design.- set({ nodes: [...parents, ...children], edges, hasUnsavedChanges: false, selectedNodeId: null, past: [], future: [], fitViewPending: true })+ set({+ nodes: [...parents, ...children],+ edges,+ hasUnsavedChanges: false,+ selectedNodeId: null,+ past: [],+ future: [],+ fitViewPending: true,+ // What the server just gave us: the reference a save diffs against.+ factsBaseline: factsBaselines(nodes),+ })},applyLayout: (nodes, edges) =>diff --git a/frontend/src/utils/__tests__/canvasSerializer.deviceLink.test.ts b/frontend/src/utils/__tests__/canvasSerializer.deviceLink.test.tsindex 210c2c3..ea42aaf 100644--- a/frontend/src/utils/__tests__/canvasSerializer.deviceLink.test.ts+++ b/frontend/src/utils/__tests__/canvasSerializer.deviceLink.test.ts@@ -4,6 +4,7 @@*/import { describe, it, expect } from 'vitest'import { serializeNode, deserializeApiNode } from '@/utils/canvasSerializer'+import { DEVICE_FACT_FIELDS, factsBaselineOf } from '@/utils/deviceFacts'import type { NodeData } from '@/types'import type { Node } from '@xyflow/react'@@ -30,6 +31,23 @@ describe('serializeNode — device link', () => {})})+describe('serializeNode — changed_facts', () => {+ it('claims nothing when the node still holds what it loaded', () => {+ const n = node({ device_id: 'dev-1', notes: 'in the garage' })+ expect(serializeNode(n, factsBaselineOf(n.data)).changed_facts).toEqual([])+ })++ it('claims only the edited fact, so the rest of the row is left alone', () => {+ const loaded = node({ device_id: 'dev-1', notes: 'in the garage' })+ const edited = node({ device_id: 'dev-1', notes: 'moved to the loft' })+ expect(serializeNode(edited, factsBaselineOf(loaded.data)).changed_facts).toEqual(['notes'])+ })++ it('claims every fact with no baseline — a node the server has never seen', () => {+ expect(serializeNode(node({ device_id: null })).changed_facts).toEqual([...DEVICE_FACT_FIELDS])+ })+})+describe('deserializeApiNode — device link', () => {it('hoists device_id onto node data', () => {const rf = deserializeApiNode(diff --git a/frontend/src/utils/__tests__/deviceFacts.test.ts b/frontend/src/utils/__tests__/deviceFacts.test.tsnew file mode 100644index 0000000..6987419--- /dev/null+++ b/frontend/src/utils/__tests__/deviceFacts.test.ts@@ -0,0 +1,99 @@+/**+ * A node carries a copy of its inventory row's facts, hydrated on load. Telling+ * "this canvas edited it" apart from "the row moved on since" needs the values+ * the canvas was given — that baseline is what these functions keep.+ */+import { describe, it, expect } from 'vitest'+import {+ DEVICE_FACT_FIELDS,+ changedFactFields,+ deviceFactsToNodeData,+ factsBaselineOf,+ factsBaselines,+} from '@/utils/deviceFacts'+import type { InventoryEntry, NodeData } from '@/types'+import type { Node } from '@xyflow/react'++const data = (over: Partial<NodeData> = {}): NodeData => ({+ label: 'NAS',+ type: 'nas',+ status: 'online',+ services: [],+ ip: '10.0.0.5',+ notes: 'in the garage',+ ...over,+})++describe('changedFactFields', () => {+ it('reports nothing when the node still holds what it was given', () => {+ const base = factsBaselineOf(data())+ expect(changedFactFields(data(), base)).toEqual([])+ })++ it('reports only the edited field', () => {+ const base = factsBaselineOf(data())+ expect(changedFactFields(data({ notes: 'moved to the loft' }), base)).toEqual(['notes'])+ })++ it('ignores live status — the checker owns reachability, not a canvas', () => {+ const base = factsBaselineOf(data())+ expect(changedFactFields(data({ status: 'offline' }), base)).toEqual([])+ expect(DEVICE_FACT_FIELDS).not.toContain('status')+ })++ it('compares lists by value, not identity', () => {+ const props = [{ key: 'Rack', value: 'A1', icon: null, visible: true }]+ const base = factsBaselineOf(data({ properties: props }))+ expect(changedFactFields(data({ properties: [...props] }), base)).toEqual([])+ expect(changedFactFields(data({ properties: [] }), base)).toEqual(['properties'])+ })++ it('treats every fact as changed with no baseline — a new node has nothing to revert', () => {+ expect(changedFactFields(data(), undefined)).toEqual([...DEVICE_FACT_FIELDS])+ })+})++describe('factsBaselines', () => {+ it('keys one baseline per node', () => {+ const nodes = [+ { id: 'n1', position: { x: 0, y: 0 }, data: data() },+ { id: 'n2', position: { x: 0, y: 0 }, data: data({ notes: 'rack B' }) },+ ] as Node<NodeData>[]+ const baselines = factsBaselines(nodes)+ expect(Object.keys(baselines)).toEqual(['n1', 'n2'])+ expect(changedFactFields(nodes[1].data, baselines.n2)).toEqual([])+ expect(changedFactFields(nodes[1].data, baselines.n1)).toEqual(['notes'])+ })+})++describe('deviceFactsToNodeData', () => {+ const row = (over: Partial<InventoryEntry> = {}): InventoryEntry => ({+ id: 'd-1',+ ip: '10.0.0.5',+ mac: null,+ hostname: 'nas.lan',+ os: null,+ services: [],+ suggested_type: null,+ status: 'approved',+ discovered_at: '2026-01-01T00:00:00Z',+ ...over,+ })++ it('carries the curated facts a node draws', () => {+ const out = deviceFactsToNodeData(row({ label: 'Big NAS', type: 'nas', notes: 'loft' }))+ expect(out.label).toBe('Big NAS')+ expect(out.type).toBe('nas')+ expect(out.notes).toBe('loft')+ expect(out.ip).toBe('10.0.0.5')+ })++ it('leaves the inventory lifecycle out — it is not node data', () => {+ expect(deviceFactsToNodeData(row()).status).toBeUndefined()+ })++ it('falls back through the same name precedence the inventory shows', () => {+ expect(deviceFactsToNodeData(row({ friendly_name: 'Nas box' })).label).toBe('Nas box')+ expect(deviceFactsToNodeData(row()).label).toBe('nas.lan')+ })+})diff --git a/frontend/src/utils/canvasSerializer.ts b/frontend/src/utils/canvasSerializer.tsindex 8a431cb..4561280 100644--- a/frontend/src/utils/canvasSerializer.ts+++ b/frontend/src/utils/canvasSerializer.ts@@ -2,6 +2,7 @@ import type { Node, Edge } from '@xyflow/react'import type { NodeData, EdgeData, Waypoint } from '@/types'import { normalizeHandle, clampHandles, handleId, handleCountField, type Side } from '@/utils/handleUtils'import { normalizeMarker } from '@/utils/edgeMarkers'+import { changedFactFields, type FactsBaseline } from '@/utils/deviceFacts'// ── Types ────────────────────────────────────────────────────────────────────@@ -63,7 +64,10 @@ export interface ApiEdge {// ── Serialization (RF node → API save payload) ───────────────────────────────-export function serializeNode(n: Node<NodeData>): Record<string, unknown> {+export function serializeNode(+ n: Node<NodeData>,+ factsBaseline?: FactsBaseline,+): Record<string, unknown> {if (n.data.type === 'groupRect') {return {id: n.id,@@ -102,6 +106,10 @@ export function serializeNode(n: Node<NodeData>): Record<string, unknown> {// The Device Inventory row this node draws. Round-tripped so a save keeps// the link; the device fields below are routed to that row server-side.device_id: n.data.device_id ?? null,+ // Which of those fields this canvas actually edited since it loaded them.+ // The row is shared, so without this the backend cannot tell an edit from a+ // stale copy and a moved node would revert someone else's change.+ changed_facts: changedFactFields(n.data, factsBaseline),hostname: n.data.hostname ?? null,ip: n.data.ip ?? null,mac: n.data.mac ?? null,diff --git a/frontend/src/utils/deviceFacts.ts b/frontend/src/utils/deviceFacts.tsnew file mode 100644index 0000000..cfb175f--- /dev/null+++ b/frontend/src/utils/deviceFacts.ts@@ -0,0 +1,98 @@+import type { Node } from '@xyflow/react'+import type { InventoryEntry, NodeData } from '@/types'++/**+ * What the Device Inventory row owns, as it appears on a canvas node.+ *+ * A node carries a full copy of these — they are hydrated from the row when the+ * canvas loads — so a save cannot tell "I edited this" from "the row moved on+ * since I loaded it" without a baseline. `changedFactFields` compares against+ * the values the canvas was given, and the save sends the answer as+ * `changed_facts` so the backend writes the edit rather than the snapshot.+ *+ * `status` / `last_seen` / `response_time_ms` are deliberately absent: the+ * status checker owns reachability, a canvas never edits it.+ */+export const DEVICE_FACT_FIELDS = [+ 'label',+ 'type',+ 'hostname',+ 'ip',+ 'mac',+ 'os',+ 'notes',+ 'cpu_count',+ 'cpu_model',+ 'ram_gb',+ 'disk_gb',+ 'check_method',+ 'check_target',+ 'show_hardware',+ 'services',+ 'properties',+ 'ieee_address',+] as const++export type DeviceFactField = (typeof DEVICE_FACT_FIELDS)[number]++/** One node's device facts, each serialized so a deep value compares by value. */+export type FactsBaseline = Record<string, string>++const encode = (value: unknown): string => JSON.stringify(value ?? null)++export function factsBaselineOf(data: Partial<NodeData>): FactsBaseline {+ const out: FactsBaseline = {}+ for (const field of DEVICE_FACT_FIELDS) out[field] = encode(data[field])+ return out+}++/** Baselines for a whole canvas, keyed by node id. */+export function factsBaselines(nodes: Node<NodeData>[]): Record<string, FactsBaseline> {+ const out: Record<string, FactsBaseline> = {}+ for (const n of nodes) out[n.id] = factsBaselineOf(n.data)+ return out+}++/**+ * The facts this node changed since its baseline was taken.+ *+ * No baseline means the node is new to the server (or predates the tracking), so+ * every fact it carries counts as changed — the row has nothing to lose.+ */+export function changedFactFields(+ data: Partial<NodeData>,+ baseline: FactsBaseline | undefined,+): DeviceFactField[] {+ if (!baseline) return [...DEVICE_FACT_FIELDS]+ return DEVICE_FACT_FIELDS.filter((field) => encode(data[field]) !== baseline[field])+}++/**+ * An inventory row as node data — what a node drawing this device should show.+ *+ * Used to push an edit made in the Device Inventory into the canvases already+ * on screen, so their in-memory copy stops being stale the moment it is edited+ * rather than at the next reload. Inventory-only fields (friendly_name, vendor,+ * model, lifecycle `status`…) are not node data and stay out.+ */+export function deviceFactsToNodeData(device: InventoryEntry): Partial<NodeData> {+ return {+ label: device.label ?? device.friendly_name ?? device.hostname ?? device.ip ?? 'device',+ ...(device.type ? { type: device.type as NodeData['type'] } : {}),+ hostname: device.hostname ?? undefined,+ ip: device.ip ?? undefined,+ mac: device.mac ?? undefined,+ os: device.os ?? undefined,+ notes: device.notes ?? undefined,+ cpu_count: device.cpu_count ?? undefined,+ cpu_model: device.cpu_model ?? undefined,+ ram_gb: device.ram_gb ?? undefined,+ disk_gb: device.disk_gb ?? undefined,+ check_method: device.check_method ?? undefined,+ check_target: device.check_target ?? undefined,+ show_hardware: device.show_hardware ?? false,+ services: device.services ?? [],+ properties: device.properties ?? [],+ ieee_address: device.ieee_address ?? undefined,+ }+}