Skip to content

Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring

feat(inventory): merge duplicate device rows, by hand or after an import

Pouzor46dac1a89f5a
diff --git a/backend/app/api/routes/proxmox.py b/backend/app/api/routes/proxmox.py
index fab786a..f0e5514 100644
--- a/backend/app/api/routes/proxmox.py
+++ b/backend/app/api/routes/proxmox.py
@@ -33,6 +33,7 @@ from app.schemas.proxmox import (
ProxmoxTestConnectionResponse,
)
from app.schemas.scan import ScanRunResponse
+from app.services.device_merge import reconcile_duplicates
from app.services.discovery_sources import add_source
from app.services.inventory_sync import attach_device_ids
from app.services.mac_utils import normalize_mac
@@ -321,6 +322,12 @@ async def _persist_pending_import(
en.left_handles = max(en.left_handles or 0, 1)
en.right_handles = max(en.right_handles or 0, 1)
+ # Fold in any row this import just proved to be the same device: a guest
+ # matched here by its synthetic ieee can share a MAC or an IP with a row an
+ # earlier scan (or an older canvas node) minted before either side carried
+ # the address that would have matched them.
+ await reconcile_duplicates(db)
+
links_recorded = await _replace_links(db, edges_raw, cluster_pairs)
await db.commit()
diff --git a/backend/app/api/routes/scan.py b/backend/app/api/routes/scan.py
index 4bc4472..12cd5a2 100644
--- a/backend/app/api/routes/scan.py
+++ b/backend/app/api/routes/scan.py
@@ -28,6 +28,7 @@ from app.schemas.scan import (
InventoryDeviceUpdate,
ScanRunResponse,
)
+from app.services.device_merge import merge_devices
from app.services.discovery_sources import add_source
from app.services.doc_links import unlink_documents
from app.services.inventory_sync import find_device_for, merge_properties, merge_services
@@ -117,6 +118,13 @@ def merge_mac_property(
return out
+class MergeDevicesRequest(BaseModel):
+ """Which inventory rows fold into which. ``winner_id`` is the survivor."""
+
+ winner_id: str
+ loser_ids: list[str]
+
+
class BulkActionRequest(BaseModel):
device_ids: list[str]
# Target design for approved nodes. Falls back to the first design when
@@ -621,6 +629,45 @@ async def list_proxmox_children(
return await _with_canvas_counts(db, list(result.scalars().all()))
[email protected]("/pending/merge", response_model=InventoryDeviceResponse)
+async def merge_inventory_devices(
+ payload: MergeDevicesRequest,
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> InventoryDevice:
+ """Fold several inventory rows into one, keeping ``winner_id``.
+
+ The manual half of the duplicate repair. Identity matching only runs when a
+ row is created, so two rows describing one host — minted before either
+ carried the address that would have matched them — stay separate forever.
+ Where they share no address at all, no automatic rule can join them safely
+ (a name is not an identity), and this is the only way to say "these are the
+ same machine".
+
+ Non-destructive: facts are unioned onto the survivor and every canvas node,
+ rack mount and document is re-pointed at it before the extras go.
+ """
+ winner = await db.get(InventoryDevice, payload.winner_id)
+ if winner is None:
+ raise HTTPException(status_code=404, detail="Device not found")
+
+ loser_ids = [i for i in dict.fromkeys(payload.loser_ids) if i != winner.id]
+ if not loser_ids:
+ raise HTTPException(status_code=400, detail="Select at least two devices to merge")
+
+ losers = (
+ await db.execute(select(InventoryDevice).where(InventoryDevice.id.in_(loser_ids)))
+ ).scalars().all()
+ missing = set(loser_ids) - {row.id for row in losers}
+ if missing:
+ raise HTTPException(status_code=404, detail="Device not found")
+
+ await merge_devices(db, winner, list(losers))
+ await db.commit()
+ await db.refresh(winner)
+ return (await _with_canvas_counts(db, [winner]))[0]
+
+
@router.post("/pending/bulk-approve", response_model=dict)
async def bulk_approve_devices(
payload: BulkActionRequest,
diff --git a/backend/app/services/device_merge.py b/backend/app/services/device_merge.py
new file mode 100644
index 0000000..4262fc9
--- /dev/null
+++ b/backend/app/services/device_merge.py
@@ -0,0 +1,447 @@
+"""Fold several `device_inventory` rows describing one host into a single row.
+
+The inventory matches on identity *when a row is created* (``find_device_for``:
+ieee > ip > mac) and never looks again. A row minted while its facts were still
+incomplete — a canvas node saved before anyone typed its IP, a legacy node the
+3.3.0 backfill could only see by label — therefore stays a second row forever,
+even once the missing address arrives and both rows plainly describe the same
+machine. This module is the repair for that, in two shapes:
+
+* :func:`merge_devices` — the user picks the survivor and what folds into it.
+ The only way to collapse rows that share nothing an automatic rule can trust:
+ a name is not an identity.
+* :func:`reconcile_duplicates` — run after an import, collapses only what a
+ shared MAC proves. Never a shared IP alone: that is not an identity.
+
+Merging is non-destructive by construction: facts are unioned, and every
+reference (`nodes`, `rack_devices`, `documents`, mesh links) is re-pointed onto
+the survivor *before* the extras go. That is what separates it from the
+scanner's older collapse, which deleted duplicate rows outright and left canvas
+nodes naming a row that no longer existed — SQLite runs with foreign keys off
+here, so the declared ``ON DELETE SET NULL`` never fires.
+"""
+
+from __future__ import annotations
+
+import logging
+from datetime import datetime
+from typing import Any
+
+from sqlalchemy import or_, select, update
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.db.models import Document, InventoryDevice, InventoryDeviceLink, Node, RackDevice
+from app.services.discovery_sources import add_source
+from app.services.inventory_sync import (
+ VIEW_LISTS,
+ ip_tokens,
+ merge_properties,
+ merge_services,
+ view_of_device,
+)
+from app.services.node_dedupe import dedupe_nodes_by_device
+
+logger = logging.getLogger(__name__)
+
+# Scalars the survivor fills from a loser when — and only when — it has none of
+# its own. `ip`, `mac`, the lists and the timestamps are merged by rule below.
+_FILL_SCALARS = (
+ "hostname",
+ "os",
+ "suggested_type",
+ "discovery_source",
+ "friendly_name",
+ "device_subtype",
+ "model",
+ "vendor",
+ "lqi",
+ "label",
+ "type",
+ "notes",
+ "cpu_count",
+ "cpu_model",
+ "ram_gb",
+ "disk_gb",
+ "check_method",
+ "check_target",
+ "response_time_ms",
+ "rack_faceplate_id",
+ "rack_u_height",
+ "rack_col_span",
+ "rack_color",
+ "rack_ports",
+)
+
+
+def _blank(value: Any) -> bool:
+ return value is None or value == ""
+
+
+def _newest(left: datetime | None, right: datetime | None) -> datetime | None:
+ if left is None or right is None:
+ return left or right
+ return max(left, right)
+
+
+def _merged_ip(winner: str | None, loser: str | None) -> str | None:
+ """Union of both address lists, the survivor's own addresses first.
+
+ A device legitimately holds several addresses (a management VLAN, a second
+ NIC), and dropping the loser's would undo the very match that identified it
+ — the next import would mint the duplicate again.
+ """
+ tokens = ip_tokens(winner)
+ for token in ip_tokens(loser):
+ if token not in tokens:
+ tokens.append(token)
+ return ", ".join(tokens) or None
+
+
+def _merged_status(winner: str, losers: list[InventoryDevice]) -> str:
+ """The lifecycle state the survivor carries.
+
+ ``approved`` wins over everything: a canvas node or a rack mount is about to
+ point at this row, and a row that is pending or hidden would file a drawn
+ device back in the discovery queue or make it vanish from the inventory.
+ """
+ if winner == "approved" or any(loser.status == "approved" for loser in losers):
+ return "approved"
+ return winner
+
+
+async def _merge_documents(db: AsyncSession, winner: InventoryDevice, loser_ids: list[str]) -> int:
+ """Re-point the losers' documents, or orphan them. Returns how many orphaned.
+
+ ``documents.device_id`` is unique per device (a partial index built in
+ ``init_db``), so only one document can describe the survivor. The oldest of
+ the losers' is adopted when the survivor has none; the rest are unlinked
+ rather than deleted — what the user wrote outlives the row it described, and
+ an orphan keeps its denormalized title and can be re-linked from the Library.
+ """
+ docs = (
+ await db.execute(
+ select(Document)
+ .where(Document.device_id.in_(loser_ids))
+ .order_by(Document.created_at, Document.id)
+ )
+ ).scalars().all()
+ if not docs:
+ return 0
+
+ has_own = (
+ await db.execute(select(Document.id).where(Document.device_id == winner.id).limit(1))
+ ).scalar_one_or_none()
+ orphaned = 0
+ for i, doc in enumerate(docs):
+ if i == 0 and has_own is None:
+ doc.device_id = winner.id
+ continue
+ doc.device_id = None
+ orphaned += 1
+ return orphaned
+
+
+async def _show_merged_facts(db: AsyncSession, winner: InventoryDevice) -> int:
+ """Make the survivor's facts visible on every canvas that draws it.
+
+ A node's ``display_view`` is a whitelist: ``apply_view`` appends anything the
+ view does not list *hidden*, which is what keeps a service a later scan found
+ off canvases nobody has enabled it on. After a merge that rule works against
+ the user — a node that came from the poorer row lists only the poorer row's
+ keys, so every service and property it just gained would arrive invisible,
+ and the canvas would look exactly as bare as before the merge.
+
+ So each node drawing the survivor has the keys missing from its view appended
+ as shown. Only *missing* keys: a fact this canvas listed as hidden was hidden
+ on purpose and stays that way. Returns the number of nodes touched.
+ """
+ nodes = (
+ await db.execute(select(Node).where(Node.device_id == winner.id))
+ ).scalars().all()
+ seeds = view_of_device(winner)
+ touched = 0
+ for node in nodes:
+ view = dict(node.display_view or {})
+ changed = False
+ for kind in VIEW_LISTS:
+ entries = view.get(kind)
+ if not isinstance(entries, list):
+ # No view at all for this list — `apply_view` already shows
+ # everything the row holds, merged facts included.
+ continue
+ listed = {str(e.get("key")) for e in entries if isinstance(e, dict)}
+ missing = [entry for entry in seeds[kind] if entry["key"] not in listed]
+ if missing:
+ view[kind] = [*entries, *missing]
+ changed = True
+ if changed:
+ # Reassign rather than mutate: a JSON column tracks identity, not
+ # in-place edits, so a mutated dict would never be written back.
+ node.display_view = view
+ touched += 1
+ return touched
+
+
+async def _refresh_rack_mounts(db: AsyncSession, winner: InventoryDevice, losers: list[InventoryDevice]) -> None:
+ """Point the losers' rack mounts at the survivor and refresh what they copied.
+
+ A mount denormalizes the device's ``label`` so a rack still renders after an
+ inventory purge. Re-pointing alone would leave it printing the name of a row
+ that no longer exists, so a copy that still matches the loser is refreshed to
+ the survivor's name — a label the user typed on the mount itself does not
+ match and is left alone. The faceplate, its size and its ports are overlaid
+ from the inventory row on load, and the merge already filled any the survivor
+ lacked, so the plate keeps rendering as it did.
+ """
+ loser_ids = [row.id for row in losers]
+ mounts = (
+ await db.execute(select(RackDevice).where(RackDevice.device_id.in_(loser_ids)))
+ ).scalars().all()
+ stale = {
+ name
+ for row in losers
+ for name in (row.label, row.friendly_name, row.hostname)
+ if name
+ }
+ winner_name = winner.label or winner.friendly_name or winner.hostname
+ for mount in mounts:
+ mount.device_id = winner.id
+ if winner_name and mount.label in stale:
+ mount.label = winner_name
+
+
+async def _rewrite_links(db: AsyncSession, winner_ieee: str, loser_ieees: list[str]) -> None:
+ """Move mesh/Proxmox links off the losers' IEEEs onto the survivor's.
+
+ ``device_inventory_links`` addresses endpoints by IEEE, not by row id, so a
+ link left on a merged-away address stops resolving to anything. Rewriting
+ can produce a self-link (both endpoints were the same device) or a duplicate
+ pair; both are dropped.
+ """
+ if not loser_ieees:
+ return
+ links = (
+ await db.execute(
+ select(InventoryDeviceLink).where(
+ or_(
+ InventoryDeviceLink.source_ieee.in_(loser_ieees),
+ InventoryDeviceLink.target_ieee.in_(loser_ieees),
+ )
+ )
+ )
+ ).scalars().all()
+ for link in links:
+ if link.source_ieee in loser_ieees:
+ link.source_ieee = winner_ieee
+ if link.target_ieee in loser_ieees:
+ link.target_ieee = winner_ieee
+ await db.flush()
+
+ seen: set[tuple[str, str, str]] = set()
+ all_links = (
+ await db.execute(
+ select(InventoryDeviceLink)
+ .where(
+ or_(
+ InventoryDeviceLink.source_ieee == winner_ieee,
+ InventoryDeviceLink.target_ieee == winner_ieee,
+ )
+ )
+ .order_by(InventoryDeviceLink.discovered_at, InventoryDeviceLink.id)
+ )
+ ).scalars().all()
+ for link in all_links:
+ key = (link.source_ieee, link.target_ieee, link.discovery_source)
+ if link.source_ieee == link.target_ieee or key in seen:
+ await db.delete(link)
+ continue
+ seen.add(key)
+
+
+async def merge_devices(
+ db: AsyncSession,
+ winner: InventoryDevice,
+ losers: list[InventoryDevice],
+) -> dict[str, Any]:
+ """Fold ``losers`` into ``winner``. Does not commit — the caller owns that.
+
+ The survivor keeps every fact it already has; a loser only fills a gap. That
+ rule is the whole safety of the operation: whichever row the user (or the
+ reconcile pass) picked, nothing it recorded is overwritten by an older or
+ less-curated copy, and nothing the extras recorded is lost — lists are
+ unioned, addresses are unioned, sources accumulate.
+
+ Returns counts for the caller to report.
+ """
+ losers = [row for row in losers if row.id != winner.id]
+ if not losers:
+ return {
+ "merged": 0,
+ "device_id": winner.id,
+ "nodes_repointed": 0,
+ "documents_orphaned": 0,
+ "views_extended": 0,
+ }
+
+ loser_ids = [row.id for row in losers]
+ # Oldest first: where two losers both fill the same gap, the older sighting
+ # is the one that has survived longest without being contradicted.
+ for loser in sorted(losers, key=lambda d: (d.discovered_at, d.id)):
+ for field in _FILL_SCALARS:
+ if _blank(getattr(winner, field, None)):
+ value = getattr(loser, field, None)
+ if not _blank(value):
+ setattr(winner, field, value)
+ winner.ip = _merged_ip(winner.ip, loser.ip)
+ winner.mac = winner.mac or loser.mac
+ winner.services = merge_services(winner.services, loser.services)
+ winner.properties = merge_properties(winner.properties, loser.properties)
+ winner.show_hardware = winner.show_hardware or loser.show_hardware
+ for source in add_source(loser.discovery_sources, loser.discovery_source):
+ winner.discovery_sources = add_source(winner.discovery_sources, source)
+ if winner.status_live in (None, "", "unknown"):
+ winner.status_live = loser.status_live
+ winner.last_seen = _newest(winner.last_seen, loser.last_seen)
+ winner.last_scan = _newest(winner.last_scan, loser.last_scan)
+ # The device has been known since the earliest of the rows saw it.
+ if loser.discovered_at and winner.discovered_at:
+ winner.discovered_at = min(winner.discovered_at, loser.discovered_at)
+
+ winner.status = _merged_status(winner.status, losers)
+
+ nodes = await db.execute(
+ update(Node).where(Node.device_id.in_(loser_ids)).values(device_id=winner.id)
+ )
+ await _refresh_rack_mounts(db, winner, losers)
+ orphaned = await _merge_documents(db, winner, loser_ids)
+ await db.flush()
+ shown = await _show_merged_facts(db, winner)
+
+ loser_ieees = [row.ieee_address for row in losers if row.ieee_address]
+ adopted: str | None = None
+ if _blank(winner.ieee_address) and loser_ieees:
+ # `ieee_address` is UNIQUE, so the address can only move once the row
+ # holding it is gone — assigned after the delete below.
+ adopted = loser_ieees[0]
+
+ for loser in losers:
+ await db.delete(loser)
+ await db.flush()
+
+ if adopted is not None:
+ winner.ieee_address = adopted
+ await db.flush()
+ if winner.ieee_address:
+ await _rewrite_links(db, winner.ieee_address, loser_ieees)
+
+ # Two nodes on one canvas may now draw the survivor — that is exactly the
+ # same-design duplicate the node repair collapses.
+ await dedupe_nodes_by_device(db)
+ await db.flush()
+
+ logger.info(
+ "Inventory merge: %d row(s) folded into %s (%s)",
+ len(losers), winner.id, winner.label or winner.friendly_name or winner.ip,
+ )
+ return {
+ "merged": len(losers),
+ "device_id": winner.id,
+ "nodes_repointed": nodes.rowcount or 0,
+ "documents_orphaned": orphaned,
+ "views_extended": shown,
+ }
+
+
+def _conflicting(left: InventoryDevice, right: InventoryDevice) -> bool:
+ """True when two rows carry addresses that say they are different machines.
+
+ A distinct non-blank IEEE on each is decisive: two Proxmox guests (the
+ synthetic ``pve-{host}-{vmid}``) or two radios are never one device. A
+ distinct MAC says the same for hardware. Either one vetoes an automatic
+ merge — the user can still merge them by hand.
+ """
+ if left.ieee_address and right.ieee_address and left.ieee_address.lower() != right.ieee_address.lower():
+ return True
+ return bool(left.mac and right.mac and left.mac != right.mac)
+
+
+def _pick_winner(group: list[InventoryDevice]) -> InventoryDevice:
+ """The row the others fold into.
+
+ An IEEE first: mesh links and the Proxmox host→guest graph are keyed on it,
+ and the import matches on it before anything else, so the row holding one is
+ the row every other writer will come back to. Then an approved row (it is
+ the one already drawn), then the oldest.
+ """
+ return sorted(
+ group,
+ key=lambda d: (
+ 0 if d.ieee_address else 1,
+ 0 if d.status == "approved" else 1,
+ d.discovered_at,
+ d.id,
+ ),
+ )[0]
+
+
+def _auto_groups(rows: list[InventoryDevice]) -> list[list[InventoryDevice]]:
+ """Group rows a shared MAC proves to be one device.
+
+ The MAC and nothing else. A shared IP is not enough on its own — a re-used
+ DHCP lease, two guests behind one NAT, or a container bridge address several
+ guests report all make one address describe several machines — and the
+ scanner already collapses what an IP does justify, under its own guard for
+ rows that are drawn on a canvas. Labels and hostnames are ignored outright:
+ two boxes are often called the same thing, and an automatic pass is not the
+ place to decide they are one. Whatever is left over is what the manual merge
+ is for.
+
+ A group is dropped whole when any pair inside it contradicts (see
+ :func:`_conflicting`) rather than guessing which member does not belong.
+ """
+ by_mac: dict[str, list[InventoryDevice]] = {}
+ for row in rows:
+ if row.mac:
+ by_mac.setdefault(row.mac.lower(), []).append(row)
+
+ out = []
+ for group in by_mac.values():
+ if len(group) < 2:
+ continue
+ pairs = [(a, b) for i, a in enumerate(group) for b in group[i + 1:]]
+ if any(_conflicting(a, b) for a, b in pairs):
+ logger.info(
+ "Inventory reconcile: leaving %d row(s) sharing a MAC alone — "
+ "their IEEE says they are different devices (%s)",
+ len(group), ", ".join(row.id for row in group),
+ )
+ continue
+ out.append(group)
+ return out
+
+
+async def reconcile_duplicates(db: AsyncSession) -> int:
+ """Merge inventory rows a shared MAC proves to be one device. Does not commit.
+
+ Meant to run at the end of an import, where a row that was created blind may
+ have just gained the address that identifies it. Returns the number of rows
+ merged away.
+
+ Hidden rows are excluded on both sides: the user hid one deliberately, and
+ folding it into a visible row would put it back in front of them, while
+ folding a visible row into it would make a device they are using disappear.
+ """
+ rows = (
+ await db.execute(
+ select(InventoryDevice)
+ .where(InventoryDevice.status != "hidden")
+ .order_by(InventoryDevice.discovered_at, InventoryDevice.id)
+ )
+ ).scalars().all()
+
+ merged = 0
+ for group in _auto_groups(list(rows)):
+ winner = _pick_winner(group)
+ result = await merge_devices(db, winner, [row for row in group if row is not winner])
+ merged += int(result["merged"])
+ return merged
diff --git a/backend/app/services/node_dedupe.py b/backend/app/services/node_dedupe.py
index 5c82f9e..0461bd4 100644
--- a/backend/app/services/node_dedupe.py
+++ b/backend/app/services/node_dedupe.py
@@ -15,10 +15,10 @@ from __future__ import annotations
import logging
from typing import Any
-from sqlalchemy import select
+from sqlalchemy import select, update
from sqlalchemy.ext.asyncio import AsyncSession
-from app.db.models import Edge, Node
+from app.db.models import Document, Edge, Node, RackDevice
from app.services.inventory_sync import find_device_for
logger = logging.getLogger(__name__)
@@ -143,6 +143,29 @@ async def dedupe_nodes_by_device(db: AsyncSession) -> int:
continue
seen_pairs.add(key)
+ # A rack mount reads live status through `node_id`, and a document may
+ # describe the node itself. Both are `SET NULL` in the schema and SQLite
+ # runs with foreign keys off here, so a duplicate deleted from under them
+ # would leave the column naming a node that no longer exists.
+ await db.execute(
+ update(RackDevice).where(RackDevice.node_id.in_(dup_ids)).values(node_id=canonical.id)
+ )
+ own_doc = (
+ await db.execute(select(Document.id).where(Document.node_id == canonical.id).limit(1))
+ ).scalar_one_or_none()
+ doc_rows = (
+ await db.execute(
+ select(Document)
+ .where(Document.node_id.in_(dup_ids))
+ .order_by(Document.created_at, Document.id)
+ )
+ ).scalars().all()
+ for i, doc in enumerate(doc_rows):
+ # `documents.node_id` is unique (partial index): only one document
+ # can describe the survivor. The rest are orphaned, not deleted —
+ # what the user wrote outlives the node it was attached to.
+ doc.node_id = canonical.id if i == 0 and own_doc is None else None
+
await db.flush()
for dup in dups:
await db.delete(dup)
diff --git a/backend/app/services/scanner.py b/backend/app/services/scanner.py
index d80bee2..60bfe46 100644
--- a/backend/app/services/scanner.py
+++ b/backend/app/services/scanner.py
@@ -17,6 +17,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.core.config import settings
from app.db.models import InventoryDevice, ScanRun
+from app.services.device_merge import merge_devices, reconcile_duplicates
from app.services.discovery_sources import add_source
from app.services.fingerprint import fingerprint_ports, suggest_node_type
from app.services.http_probe import probe_open_ports
@@ -643,10 +644,12 @@ async def _dedupe_pending_by_ip(db: AsyncSession) -> int:
for group in _group_by_shared_ip(list(rows)):
if len(group) < 2:
continue
- _, dups = _collapse_targets(group)
- for dup in dups:
- await db.delete(dup)
- deleted += 1
+ keep, dups = _collapse_targets(group)
+ if dups:
+ # Non-destructive, for the same reason as `process_host`: whatever
+ # drew the duplicate follows it into `keep`.
+ await merge_devices(db, keep, dups)
+ deleted += len(dups)
if deleted:
await db.commit()
return deleted
@@ -720,8 +723,12 @@ async def process_host(
# by earlier scans — except a second approved row, which keeps its
# own canvas links (see `_collapse_targets`).
keep, dups = _collapse_targets(existing_rows)
- for dup in dups:
- await db.delete(dup)
+ # Merge rather than delete: a duplicate row may be the one a canvas node
+ # or a rack mount points at, and SQLite runs with foreign keys off here
+ # so the declared `ON DELETE SET NULL` never fires. `merge_devices`
+ # re-points every reference onto `keep` and unions the facts first.
+ if dups:
+ await merge_devices(db, keep, dups)
keep.ip = keep.ip or ip # fill an IP a Proxmox import lacked
keep.mac = norm_mac or keep.mac
keep.hostname = host.get("hostname") or keep.hostname
@@ -857,6 +864,14 @@ async def run_scan(
else:
mdns_task.cancel()
+ # A scan is where a row first learns its MAC, so it is also where two
+ # rows can first be proven to be one device — fold those together before
+ # reporting the run done.
+ merged = await reconcile_duplicates(db)
+ if merged:
+ await db.commit()
+ logger.info("Scan %s: merged %d duplicate inventory row(s)", run_id, merged)
+
# Mark scan as done or cancelled
run = await db.get(ScanRun, run_id)
if run:
diff --git a/backend/tests/test_device_merge.py b/backend/tests/test_device_merge.py
new file mode 100644
index 0000000..9a736f0
--- /dev/null
+++ b/backend/tests/test_device_merge.py
@@ -0,0 +1,405 @@
+"""Tests for the inventory duplicate repair (app.services.device_merge).
+
+Two shapes, one merge: the user picks the survivor by hand, or an import proves
+two rows are one device by their shared MAC. What both must guarantee is that
+nothing is lost — not a fact, not a canvas node, not a rack mount, not a
+document, and not the *visibility* of the facts that just arrived on a canvas
+that never saw them.
+"""
+
+from datetime import datetime, timezone
+
+import pytest
+from sqlalchemy import select
+
+from app.db.models import (
+ Design,
+ Document,
+ InventoryDevice,
+ InventoryDeviceLink,
+ Node,
+ Rack,
+ RackDevice,
+)
+from app.services.device_merge import merge_devices, reconcile_duplicates
+
+
+def _at(day: int) -> datetime:
+ return datetime(2026, 1, day, tzinfo=timezone.utc)
+
+
+async def _design(db, name="d1"):
+ design = Design(name=name)
+ db.add(design)
+ await db.flush()
+ return design
+
+
+async def _device(db, **kwargs):
+ kwargs.setdefault("discovered_at", _at(1))
+ device = InventoryDevice(**kwargs)
+ db.add(device)
+ await db.flush()
+ return device
+
+
+async def _node(db, design, device, **kwargs):
+ node = Node(design_id=design.id, device_id=device.id, label=kwargs.pop("label", "n8n"),
+ type=kwargs.pop("type", "lxc"), **kwargs)
+ db.add(node)
+ await db.flush()
+ return node
+
+
+async def _rack(db, design):
+ rack = Rack(design_id=design.id, name="R1", u_height=42)
+ db.add(rack)
+ await db.flush()
+ return rack
+
+
+async def test_merge_unions_facts_without_overwriting_the_survivor(db_session):
+ winner = await _device(
+ db_session, id="w", ip="192.168.1.62", mac="bc:24:11:95:af:8c",
+ hostname="n8n", label="n8n", vendor="Proxmox VE", status="pending",
+ services=[{"service_name": "ssh", "port": 22, "protocol": "tcp"}],
+ properties=[{"key": "VMID", "value": "130", "visible": True}],
+ discovery_source="arp", discovery_sources=["arp", "proxmox"],
+ discovered_at=_at(5),
+ )
+ loser = await _device(
+ db_session, id="l", ip="10.0.0.9", mac=None, hostname="ignored",
+ notes="runs the automations", cpu_count=4, status="approved",
+ services=[{"service_name": "http", "port": 5678, "protocol": "tcp"}],
+ properties=[{"key": "Owner", "value": "me", "visible": True}],
+ discovery_source="canvas", discovery_sources=["canvas"],
+ discovered_at=_at(2),
+ )
+
+ result = await merge_devices(db_session, winner, [loser])
+ await db_session.flush()
+
+ assert result["merged"] == 1
+ assert await db_session.get(InventoryDevice, "l") is None
+ # Established facts are never overwritten by the folded-in row...
+ assert winner.hostname == "n8n"
+ # ...but every gap it can fill, it fills.
+ assert winner.notes == "runs the automations"
+ assert winner.cpu_count == 4
+ # Addresses and lists union; sources accumulate.
+ assert winner.ip == "192.168.1.62, 10.0.0.9"
+ assert {s["service_name"] for s in winner.services} == {"ssh", "http"}
+ assert {p["key"] for p in winner.properties} == {"VMID", "Owner"}
+ assert set(winner.discovery_sources) == {"arp", "proxmox", "canvas"}
+ # Drawn on a canvas, so the survivor cannot go back to the pending queue.
+ assert winner.status == "approved"
+ # Known since the earliest of the two rows saw it.
+ assert winner.discovered_at == _at(2)
+
+
+async def test_merge_repoints_canvas_nodes_and_rack_mounts(db_session):
+ design = await _design(db_session)
+ other = await _design(db_session, name="d2")
+ winner = await _device(db_session, id="w", ip="192.168.1.62", status="approved")
+ loser = await _device(db_session, id="l", ip="192.168.1.62", label="n8n", status="approved")
+
+ kept = await _node(db_session, design, winner, pos_x=10, pos_y=20)
+ moved = await _node(db_session, other, loser, pos_x=300, pos_y=400)
+ rack = await _rack(db_session, design)
+ mount = RackDevice(design_id=design.id, rack_id=rack.id, device_id=loser.id, label="n8n")
+ db_session.add(mount)
+ await db_session.flush()
+
+ await merge_devices(db_session, winner, [loser])
+ await db_session.flush()
+
+ # The node on the other canvas keeps its position and now draws the survivor.
+ await db_session.refresh(moved)
+ assert moved.device_id == "w"
+ assert (moved.pos_x, moved.pos_y) == (300, 400)
+ assert (await db_session.get(Node, kept.id)).device_id == "w"
+ # The mount follows too — a rack that rendered before still renders.
+ await db_session.refresh(mount)
+ assert mount.device_id == "w"
+
+
+async def test_merge_shows_the_new_facts_on_a_canvas_that_never_saw_them(db_session):
+ """The point of the merge: a poorer node must gain the richer row's facts.
+
+ `display_view` is a whitelist — without extending it the folded-in services
+ and properties would render hidden and the canvas would look unchanged.
+ """
+ design = await _design(db_session)
+ winner = await _device(
+ db_session, id="w", ip="192.168.1.62",
+ services=[{"service_name": "ssh", "port": 22, "protocol": "tcp"}],
+ properties=[{"key": "VMID", "value": "130", "visible": True}],
+ )
+ loser = await _device(
+ db_session, id="l", ip="192.168.1.62",
+ services=[{"service_name": "http", "port": 5678, "protocol": "tcp"}],
+ properties=[],
+ )
+ poor = await _node(db_session, design, loser)
+ poor.display_view = {
+ "services": [{"key": "5678|tcp|http", "visible": True}],
+ "properties": [],
+ }
+ await db_session.flush()
+
+ await merge_devices(db_session, winner, [loser])
+ await db_session.flush()
+ await db_session.refresh(poor)
+
+ services = poor.display_view["services"]
+ assert [e["visible"] for e in services] == [True, True]
+ assert {e["key"] for e in services} == {"5678|tcp|http", "22|tcp|ssh"}
+ # A property list this canvas had never seen picks up the survivor's.
+ assert [e["key"] for e in poor.display_view["properties"]] == ["vmid"]
+
+
+async def test_merge_keeps_a_deliberately_hidden_fact_hidden(db_session):
+ design = await _design(db_session)
+ winner = await _device(
+ db_session, id="w", ip="192.168.1.62",
+ services=[{"service_name": "ssh", "port": 22, "protocol": "tcp"}],
+ )
+ loser = await _device(db_session, id="l", ip="192.168.1.62", services=[])
+ node = await _node(db_session, design, loser)
+ node.display_view = {"services": [{"key": "22|tcp|ssh", "visible": False}], "properties": []}
+ await db_session.flush()
+
+ await merge_devices(db_session, winner, [loser])
+ await db_session.flush()
+ await db_session.refresh(node)
+
+ assert node.display_view["services"] == [{"key": "22|tcp|ssh", "visible": False}]
+
+
+async def test_merge_collapses_two_nodes_that_now_draw_one_device(db_session):
+ """Both rows drawn on the *same* canvas: one node survives, the oldest."""
+ design = await _design(db_session)
+ winner = await _device(db_session, id="w", ip="192.168.1.62", status="approved")
+ loser = await _device(db_session, id="l", ip="192.168.1.62", status="approved")
+ keep = await _node(db_session, design, winner, pos_x=10, pos_y=20)
+ await _node(db_session, design, loser, pos_x=99, pos_y=99)
+
+ await merge_devices(db_session, winner, [loser])
+ await db_session.flush()
+
+ nodes = (
+ await db_session.execute(select(Node).where(Node.design_id == design.id))
+ ).scalars().all()
+ assert [n.id for n in nodes] == [keep.id]
+ assert (nodes[0].pos_x, nodes[0].pos_y) == (10, 20)
+
+
+async def test_a_rack_mount_survives_the_node_collapse(db_session):
+ """`rack_devices.node_id` must not be left naming a deleted duplicate node."""
+ design = await _design(db_session)
+ winner = await _device(db_session, id="w", ip="192.168.1.62", status="approved")
+ loser = await _device(db_session, id="l", ip="192.168.1.62", status="approved")
+ keep = await _node(db_session, design, winner)
+ dup = await _node(db_session, design, loser)
+ rack = await _rack(db_session, design)
+ mount = RackDevice(
+ design_id=design.id, rack_id=rack.id, device_id=loser.id, node_id=dup.id, label="n8n"
+ )
+ db_session.add(mount)
+ await db_session.flush()
+
+ await merge_devices(db_session, winner, [loser])
+ await db_session.flush()
+ await db_session.refresh(mount)
+
+ assert mount.device_id == "w"
+ assert mount.node_id == keep.id
+ assert await db_session.get(Node, dup.id) is None
+
+
+async def test_merge_adopts_a_document_or_orphans_it(db_session):
+ winner = await _device(db_session, id="w", ip="192.168.1.62")
+ loser = await _device(db_session, id="l", ip="192.168.1.62")
+ doc = Document(title="n8n", slug="n8n", device_id=loser.id, body="# n8n")
+ db_session.add(doc)
+ await db_session.flush()
+
+ result = await merge_devices(db_session, winner, [loser])
+ await db_session.flush()
+ await db_session.refresh(doc)
+
+ # No document on the survivor, so the loser's is adopted rather than orphaned.
+ assert doc.device_id == "w"
+ assert result["documents_orphaned"] == 0
+
+
+async def test_a_second_document_is_orphaned_not_deleted(db_session):
+ winner = await _device(db_session, id="w", ip="192.168.1.62")
+ loser = await _device(db_session, id="l", ip="192.168.1.62")
+ mine = Document(title="n8n", slug="n8n", device_id=winner.id, body="kept")
+ theirs = Document(title="n8n (dup)", slug="n8n-dup", device_id=loser.id, body="written by hand")
+ db_session.add_all([mine, theirs])
+ await db_session.flush()
+
+ result = await merge_devices(db_session, winner, [loser])
+ await db_session.flush()
+ await db_session.refresh(theirs)
+
+ assert result["documents_orphaned"] == 1
+ assert theirs.device_id is None
+ assert theirs.body == "written by hand" # survives as an orphan
+
+
+async def test_merge_moves_mesh_links_onto_the_survivor_ieee(db_session):
+ winner = await _device(db_session, id="w", ieee_address="pve-pve1-130", ip="192.168.1.62")
+ loser = await _device(db_session, id="l", ieee_address="0xAABB", ip="192.168.1.62")
+ db_session.add(InventoryDeviceLink(source_ieee="pve-host", target_ieee="0xAABB"))
+ db_session.add(InventoryDeviceLink(source_ieee="0xAABB", target_ieee="0xCCDD"))
+ await db_session.flush()
+
+ await merge_devices(db_session, winner, [loser])
+ await db_session.flush()
+
+ links = (await db_session.execute(select(InventoryDeviceLink))).scalars().all()
+ pairs = {(link.source_ieee, link.target_ieee) for link in links}
+ assert pairs == {("pve-host", "pve-pve1-130"), ("pve-pve1-130", "0xCCDD")}
+
+
+async def test_the_survivor_adopts_an_ieee_it_lacks(db_session):
+ winner = await _device(db_session, id="w", ip="192.168.1.62", ieee_address=None)
+ loser = await _device(db_session, id="l", ip="192.168.1.62", ieee_address="pve-pve1-130")
+
+ await merge_devices(db_session, winner, [loser])
+ await db_session.flush()
+
+ assert winner.ieee_address == "pve-pve1-130"
+
+
+async def test_reconcile_merges_rows_sharing_a_mac(db_session):
+ """The reported case: a Proxmox row and a canvas row, same NIC."""
+ scanned = await _device(
+ db_session, id="scanned", ip="192.168.1.62", mac="bc:24:11:95:af:8c",
+ ieee_address="pve-proxmox-ai-130", status="pending", discovered_at=_at(1),
+ )
+ from_canvas = await _device(
+ db_session, id="canvas", ip="192.168.1.62", mac="bc:24:11:95:af:8c",
+ label="n8n", status="approved", discovered_at=_at(20),
+ )
+
+ merged = await reconcile_duplicates(db_session)
+ await db_session.flush()
+
+ assert merged == 1
+ # The IEEE-bearing row wins: the Proxmox import and the link graph key on it.
+ assert await db_session.get(InventoryDevice, from_canvas.id) is None
+ assert (await db_session.get(InventoryDevice, scanned.id)).label == "n8n"
+
+
+async def test_reconcile_leaves_rows_that_only_share_an_ip(db_session):
+ """An IP is not an identity — a re-used lease must not merge two machines."""
+ await _device(db_session, id="a", ip="192.168.1.62", mac="aa:aa:aa:aa:aa:aa")
+ await _device(db_session, id="b", ip="192.168.1.62", mac="bb:bb:bb:bb:bb:bb")
+
+ assert await reconcile_duplicates(db_session) == 0
+ assert len((await db_session.execute(select(InventoryDevice))).scalars().all()) == 2
+
+
+async def test_reconcile_leaves_two_proxmox_guests_sharing_a_mac(db_session):
+ """Distinct synthetic IEEEs are decisive: two guests are never one device."""
+ await _device(db_session, id="a", mac="bc:24:11:95:af:8c", ieee_address="pve-pve1-130")
+ await _device(db_session, id="b", mac="bc:24:11:95:af:8c", ieee_address="pve-pve1-131")
+
+ assert await reconcile_duplicates(db_session) == 0
+ assert len((await db_session.execute(select(InventoryDevice))).scalars().all()) == 2
+
+
+async def test_reconcile_never_touches_a_hidden_row(db_session):
+ """A hidden row was hidden on purpose — merging it would resurrect it."""
+ await _device(db_session, id="visible", mac="bc:24:11:95:af:8c", status="pending")
+ await _device(db_session, id="hidden", mac="bc:24:11:95:af:8c", status="hidden")
+
+ assert await reconcile_duplicates(db_session) == 0
+ hidden = await db_session.get(InventoryDevice, "hidden")
+ assert hidden is not None and hidden.status == "hidden"
+
+
+async def test_reconcile_is_idempotent(db_session):
+ await _device(db_session, id="a", mac="bc:24:11:95:af:8c", ip="192.168.1.62")
+ await _device(db_session, id="b", mac="bc:24:11:95:af:8c", ip="192.168.1.62")
+
+ assert await reconcile_duplicates(db_session) == 1
+ await db_session.flush()
+ assert await reconcile_duplicates(db_session) == 0
+
+
+# --- The route -----------------------------------------------------------
+
+
+async def test_merge_route_returns_the_survivor(client, headers, db_session):
+ await _device(db_session, id="w", ip="192.168.1.62", label="n8n", status="approved")
+ await _device(db_session, id="l", hostname="n8n", notes="the good notes")
+ await db_session.commit()
+
+ res = await client.post(
+ "/api/v1/scan/pending/merge",
+ json={"winner_id": "w", "loser_ids": ["l"]},
+ headers=headers,
+ )
+
+ assert res.status_code == 200
+ body = res.json()
+ assert body["id"] == "w"
+ assert body["notes"] == "the good notes"
+ assert await db_session.get(InventoryDevice, "l") is None
+
+
+async def test_merge_route_rejects_a_single_device(client, headers, db_session):
+ await _device(db_session, id="w", ip="192.168.1.62")
+ await db_session.commit()
+
+ res = await client.post(
+ "/api/v1/scan/pending/merge",
+ json={"winner_id": "w", "loser_ids": ["w"]},
+ headers=headers,
+ )
+
+ assert res.status_code == 400
+
+
+async def test_merge_route_404s_on_an_unknown_row(client, headers, db_session):
+ await _device(db_session, id="w", ip="192.168.1.62")
+ await db_session.commit()
+
+ res = await client.post(
+ "/api/v1/scan/pending/merge",
+ json={"winner_id": "w", "loser_ids": ["nope"]},
+ headers=headers,
+ )
+
+ assert res.status_code == 404
+
+
+async def test_merge_route_requires_auth(client, db_session):
+ res = await client.post(
+ "/api/v1/scan/pending/merge", json={"winner_id": "w", "loser_ids": ["l"]}
+ )
+ assert res.status_code in (401, 403)
diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts
index 7b9b857..1856f17 100644
--- a/frontend/src/api/client.ts
+++ b/frontend/src/api/client.ts
@@ -212,6 +212,14 @@ export const scanApi = {
skipped: number
skipped_devices: SkippedDevice[]
}>('/scan/pending/bulk-approve', { device_ids: ids, design_id: designId ?? undefined }),
+ /**
+ * Fold several inventory rows into one, keeping `winnerId`. Returns the
+ * survivor. The losers' facts, canvas nodes, rack mounts and documents move
+ * onto it first — the identity match only runs when a row is created, so two
+ * rows for one host never converge on their own.
+ */
+ merge: (winnerId: string, loserIds: string[]) =>
+ api.post<InventoryEntry>('/scan/pending/merge', { winner_id: winnerId, loser_ids: loserIds }),
bulkHide: (ids: string[]) => api.post<{ hidden: number; skipped: number }>('/scan/pending/bulk-hide', { device_ids: ids }),
restore: (id: string) => api.post<{ restored: boolean; device_id: string }>(`/scan/pending/${id}/restore`),
bulkRestore: (ids: string[]) => api.post<{ restored: number; skipped: number }>('/scan/pending/bulk-restore', { device_ids: ids }),
diff --git a/frontend/src/components/modals/DeviceInventoryModal.tsx b/frontend/src/components/modals/DeviceInventoryModal.tsx
index d7bce24..79ba176 100644
--- a/frontend/src/components/modals/DeviceInventoryModal.tsx
+++ b/frontend/src/components/modals/DeviceInventoryModal.tsx
@@ -22,6 +22,7 @@ import { getCenteredPosition } from '@/utils/viewportCenter'
import { sourceBuckets, orderedSources, isRackDevice, SOURCE_META, type SourceBucket } from '@/utils/deviceSources'
import { isRackable } from '@/utils/rackable'
import { ProxmoxApproveModal, type ProxmoxApproveChoice } from '@/components/modals/ProxmoxApproveModal'
+import { MergeDevicesModal } from '@/components/modals/MergeDevicesModal'
import { layoutProxmoxContainers, measureProxmoxContainers } from '@/utils/proxmoxContainerLayout'
interface DeviceInventoryModalProps {
@@ -184,6 +185,9 @@ export function DeviceInventoryModal({ open, onClose, highlightId, initialStatus
// Set when a Proxmox host with guests is about to be placed — the user picks
// whether the guests come along, and nested or linked.
const [proxmoxPrompt, setProxmoxPrompt] = useState<{ host: InventoryEntry; children: InventoryEntry[] } | null>(null)
+ // Set when the user asks to merge the selected rows — they pick the survivor.
+ const [mergePrompt, setMergePrompt] = useState<InventoryEntry[] | null>(null)
+ const [merging, setMerging] = useState(false)
const load = useCallback(async () => {
// Tour/demo mode: show injected devices, never touch the backend.
@@ -589,6 +593,27 @@ export function DeviceInventoryModal({ open, onClose, highlightId, initialStatus
}
}
+ const handleMerge = async (winnerId: string) => {
+ const ids = (mergePrompt ?? []).map((d) => d.id).filter((id) => id !== winnerId)
+ if (ids.length === 0) return
+ setMerging(true)
+ try {
+ await scanApi.merge(winnerId, ids)
+ setMergePrompt(null)
+ setSelectedIds(new Set())
+ // Reload rather than patch: a merge moves canvas links around, so
+ // `canvas_count` on the survivor is only right coming from the server.
+ await load()
+ toast.success(`Merged ${ids.length + 1} devices into one`, {
+ description: 'Facts, canvas nodes, rack mounts and documents were kept.',
+ })
+ } catch {
+ toast.error('Failed to merge devices')
+ } finally {
+ setMerging(false)
+ }
+ }
+
const handleBulkHide = async () => {
const ids = [...selectedIds]
if (ids.length === 0) return
@@ -851,6 +876,14 @@ export function DeviceInventoryModal({ open, onClose, highlightId, initialStatus
Clear
</button>
<div className="flex-1" />
+ <button
+ onClick={() => setMergePrompt(devices.filter((d) => selectedIds.has(d.id)))}
+ disabled={selectedIds.size < 2}
+ title="Fold the selected rows into one device"
+ className="text-xs px-3 py-1.5 rounded bg-[#00d4ff]/20 text-[#00d4ff] hover:bg-[#00d4ff]/30 disabled:opacity-40 font-medium transition-colors"
+ >
+ Merge ({selectedIds.size})
+ </button>
{statusFilter === 'pending' && (
<>
<button
@@ -957,6 +990,14 @@ export function DeviceInventoryModal({ open, onClose, highlightId, initialStatus
}}
/>
+ <MergeDevicesModal
+ open={mergePrompt !== null}
+ devices={mergePrompt ?? []}
+ busy={merging}
+ onCancel={() => setMergePrompt(null)}
+ onConfirm={handleMerge}
+ />
+
<ProxmoxApproveModal
open={proxmoxPrompt !== null}
host={proxmoxPrompt?.host ?? null}
diff --git a/frontend/src/components/modals/MergeDevicesModal.tsx b/frontend/src/components/modals/MergeDevicesModal.tsx
new file mode 100644
index 0000000..fa1629f
--- /dev/null
+++ b/frontend/src/components/modals/MergeDevicesModal.tsx
@@ -0,0 +1,123 @@
+import { useState } from 'react'
+import { Merge, Layers } from 'lucide-react'
+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
+import { Button } from '@/components/ui/button'
+import type { InventoryEntry } from '@/types'
+import { deviceName, factCount, suggestWinner } from '@/utils/mergeWinner'
+
+const ACCENT = '#00d4ff'
+
+interface MergeDevicesModalProps {
+ open: boolean
+ /** The rows the user selected in the inventory. Two or more. */
+ devices: InventoryEntry[]
+ onCancel: () => void
+ onConfirm: (winnerId: string) => void
+ /** True while the request is in flight — the dialog stays up, disabled. */
+ busy?: boolean
+}
+
+/**
+ * Asked before several Device Inventory rows are folded into one.
+ *
+ * The inventory only matches devices when a row is created, so two rows for one
+ * host — minted before either carried the address that would have matched them
+ * — never converge on their own. This is where the user says they are the same
+ * machine and picks which row survives.
+ *
+ * Nothing is thrown away by the merge itself: the survivor keeps every fact it
+ * has and fills its gaps from the others, and canvas nodes, rack mounts and
+ * documents are re-pointed at it. The one thing the user must choose is which
+ * id (and so which of two *conflicting* values) stands.
+ */
+export function MergeDevicesModal({ open, devices, onCancel, onConfirm, busy = false }: MergeDevicesModalProps) {
+ // Only the user's override is state. The winner is otherwise derived, so a
+ // choice held over from a previous selection — a row that no longer exists —
+ // falls back to the suggestion instead of pointing at nothing.
+ const [picked, setPicked] = useState<string | undefined>(undefined)
+
+ if (devices.length < 2) return null
+
+ const winnerId = devices.some((d) => d.id === picked) ? picked : suggestWinner(devices)
+ const winner = devices.find((d) => d.id === winnerId)
+
+ return (
+ <Dialog open={open} onOpenChange={(v) => !v && onCancel()}>
+ <DialogContent className="bg-[#161b22] border-border max-w-lg">
+ <DialogHeader>
+ <DialogTitle className="text-foreground flex items-center gap-2">
+ <Merge size={16} style={{ color: ACCENT }} />
+ Merge {devices.length} devices into one
+ </DialogTitle>
+ </DialogHeader>
+
+ <div className="space-y-3 py-1">
+ <p className="text-xs text-muted-foreground">
+ Keep which row? The others fold into it — their facts fill its gaps, and every
+ canvas node, rack mount and document they own moves across.
+ </p>
+
+ <div className="max-h-64 overflow-y-auto space-y-1.5">
+ {devices.map((d) => (
+ <label
+ key={d.id}
+ className={`flex items-start gap-2 rounded-md border px-3 py-2 text-xs cursor-pointer transition-colors ${
+ d.id === winnerId
+ ? 'border-[#00d4ff]/50 bg-[#00d4ff]/10'
+ : 'border-border bg-[#0d1117]/60 hover:border-muted-foreground/40'
+ }`}
+ >
+ <input
+ type="radio"
+ name="merge-winner"
+ checked={d.id === winnerId}
+ onChange={() => setPicked(d.id)}
+ className="mt-0.5 cursor-pointer shrink-0"
+ style={{ accentColor: ACCENT }}
+ />
+ <span className="min-w-0 flex-1">
+ <span className="flex items-center gap-2">
+ <span className="text-foreground font-medium truncate">{deviceName(d)}</span>
+ {(d.canvas_count ?? 0) > 0 && (
+ <span className="flex items-center gap-1 text-[10px] text-[#00d4ff] shrink-0">
+ <Layers size={10} />
+ {d.canvas_count}
+ </span>
+ )}
+ </span>
+ <span className="block text-[11px] text-muted-foreground font-mono truncate">
+ {[d.ip, d.mac, d.ieee_address].filter(Boolean).join(' · ') || 'no address'}
+ </span>
+ <span className="block text-[11px] text-muted-foreground">
+ {factCount(d)} fact{factCount(d) !== 1 ? 's' : ''}
+ {d.services?.length ? ` · ${d.services.length} service${d.services.length !== 1 ? 's' : ''}` : ''}
+ </span>
+ </span>
+ </label>
+ ))}
+ </div>
+
+ <p className="text-[11px] text-muted-foreground">
+ {winner
+ ? `Merging cannot be undone. ${devices.length - 1} row${devices.length - 1 !== 1 ? 's' : ''} will be deleted once their facts and links are on ${deviceName(winner)}.`
+ : 'Pick the row to keep.'}
+ </p>
+ </div>
+
+ <DialogFooter>
+ <Button variant="ghost" size="sm" onClick={onCancel} disabled={busy}>
+ Cancel
+ </Button>
+ <Button
+ size="sm"
+ onClick={() => winnerId && onConfirm(winnerId)}
+ disabled={!winnerId || busy}
+ style={{ backgroundColor: `${ACCENT}33`, color: ACCENT }}
+ >
+ {busy ? 'Merging…' : `Merge into ${winner ? deviceName(winner) : 'this row'}`}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/frontend/src/components/modals/__tests__/DeviceInventoryModal.test.tsx b/frontend/src/components/modals/__tests__/DeviceInventoryModal.test.tsx
index 98e2643..6b60897 100644
--- a/frontend/src/components/modals/__tests__/DeviceInventoryModal.test.tsx
+++ b/frontend/src/components/modals/__tests__/DeviceInventoryModal.test.tsx
@@ -16,6 +16,7 @@ const mockHidden = vi.fn()
const mockAddNode = vi.fn()
const mockSetSelectedNode = vi.fn()
const mockProxmoxChildren = vi.fn()
+const mockMerge = vi.fn()
vi.mock('@/api/client', () => ({
scanApi: {
@@ -30,6 +31,7 @@ vi.mock('@/api/client', () => ({
restore: (...a: unknown[]) => mockRestore(...a),
bulkRestore: (...a: unknown[]) => mockBulkRestore(...a),
proxmoxChildren: (...a: unknown[]) => mockProxmoxChildren(...a),
+ merge: (...a: unknown[]) => mockMerge(...a),
},
}))
@@ -497,6 +499,29 @@ describe('DeviceInventoryModal', () => {
await waitFor(() => expect(mockBulkHide).toHaveBeenCalledWith(['dev-a']))
})
+ it('merge needs two rows, then folds them into the chosen survivor', async () => {
+ mockMerge.mockResolvedValue({ data: { ...DEVICE_IP } })
+ render(<DeviceInventoryModal {...baseProps} />)
+ await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
+ fireEvent.click(screen.getByRole('button', { name: 'Select mode' }))
+
+ // One row is not a duplicate of anything — the action stays disabled.
+ fireEvent.click(screen.getByTestId('pending-card-dev-a'))
+ expect(screen.getByRole('button', { name: /Merge \(1\)/ })).toBeDisabled()
+
+ fireEvent.click(screen.getByTestId('pending-card-dev-b'))
+ fireEvent.click(screen.getByRole('button', { name: /Merge \(2\)/ }))
+
+ // The dialog asks which row survives before anything is sent.
+ expect(mockMerge).not.toHaveBeenCalled()
+ fireEvent.click(await screen.findByRole('button', { name: /^merge into/i }))
+ await waitFor(() => expect(mockMerge).toHaveBeenCalledTimes(1))
+ const [winner, losers] = mockMerge.mock.calls[0]
+ expect([winner, ...losers].sort()).toEqual(['dev-a', 'dev-b'])
+ // Reloaded, so the survivor's canvas count comes from the server.
+ await waitFor(() => expect(mockPending).toHaveBeenCalledTimes(2))
+ })
+
it('does not load when closed', () => {
render(<DeviceInventoryModal {...baseProps} open={false} />)
expect(mockPending).not.toHaveBeenCalled()
diff --git a/frontend/src/components/modals/__tests__/MergeDevicesModal.test.tsx b/frontend/src/components/modals/__tests__/MergeDevicesModal.test.tsx
new file mode 100644
index 0000000..6ed1a07
--- /dev/null
+++ b/frontend/src/components/modals/__tests__/MergeDevicesModal.test.tsx
@@ -0,0 +1,86 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { render, screen, fireEvent } from '@testing-library/react'
+import { MergeDevicesModal } from '../MergeDevicesModal'
+import type { InventoryEntry } from '@/types'
+
+const devices = [
+ {
+ id: 'proxmox', label: 'n8n', ip: '192.168.1.62', mac: 'bc:24:11:95:af:8c',
+ ieee_address: 'pve-proxmox-ai-130', status: 'pending', services: [],
+ discovered_at: '2026-04-01T00:00:00Z',
+ },
+ {
+ id: 'canvas', label: 'n8n', ip: '192.168.1.62', mac: 'bc:24:11:95:af:8c',
+ status: 'approved', canvas_count: 1, services: [],
+ discovered_at: '2026-08-01T00:00:00Z',
+ },
+ {
+ id: 'stub', label: 'n8n', ip: null, mac: null, status: 'pending', services: [],
+ discovered_at: '2026-08-10T00:00:00Z',
+ },
+] as unknown as InventoryEntry[]
+
+const props = {
+ open: true,
+ devices,
+ onCancel: vi.fn(),
+ onConfirm: vi.fn(),
+}
+
+describe('MergeDevicesModal', () => {
+ beforeEach(() => {
+ props.onCancel.mockReset()
+ props.onConfirm.mockReset()
+ })
+
+ it('renders nothing for a selection that cannot be merged', () => {
+ const { container } = render(<MergeDevicesModal {...props} devices={[devices[0]]} />)
+ expect(container.querySelector('[role="dialog"]')).toBeNull()
+ })
+
+ it('lists every selected row with its addresses', () => {
+ render(<MergeDevicesModal {...props} />)
+ expect(screen.getByText(/merge 3 devices into one/i)).toBeDefined()
+ expect(screen.getAllByRole('radio')).toHaveLength(3)
+ expect(screen.getByText(/pve-proxmox-ai-130/)).toBeDefined()
+ // The row with no address says so rather than rendering an empty line.
+ expect(screen.getByText('no address')).toBeDefined()
+ })
+
+ it('preselects the suggested survivor and merges into it', () => {
+ render(<MergeDevicesModal {...props} />)
+ const radios = screen.getAllByRole('radio') as HTMLInputElement[]
+ expect(radios[0].checked).toBe(true) // the IEEE-bearing row
+
+ fireEvent.click(screen.getByRole('button', { name: /^merge into/i }))
+ expect(props.onConfirm).toHaveBeenCalledWith('proxmox')
+ })
+
+ it('lets the user keep a different row instead', () => {
+ render(<MergeDevicesModal {...props} />)
+ fireEvent.click(screen.getAllByRole('radio')[1])
+
+ fireEvent.click(screen.getByRole('button', { name: /^merge into/i }))
+ expect(props.onConfirm).toHaveBeenCalledWith('canvas')
+ })
+
+ it('warns how many rows go, and that it cannot be undone', () => {
+ render(<MergeDevicesModal {...props} />)
+ expect(screen.getByText(/2 rows will be deleted/i)).toBeDefined()
+ expect(screen.getByText(/cannot be undone/i)).toBeDefined()
+ })
+
+ it('disables both actions while the merge is in flight', () => {
+ render(<MergeDevicesModal {...props} busy />)
+ expect(screen.getByRole('button', { name: /merging/i })).toHaveProperty('disabled', true)
+ expect(screen.getByRole('button', { name: /cancel/i })).toHaveProperty('disabled', true)
+ expect(props.onConfirm).not.toHaveBeenCalled()
+ })
+
+ it('cancels without merging', () => {
+ render(<MergeDevicesModal {...props} />)
+ fireEvent.click(screen.getByRole('button', { name: /cancel/i }))
+ expect(props.onCancel).toHaveBeenCalled()
+ expect(props.onConfirm).not.toHaveBeenCalled()
+ })
+})
diff --git a/frontend/src/utils/__tests__/mergeWinner.test.ts b/frontend/src/utils/__tests__/mergeWinner.test.ts
new file mode 100644
index 0000000..9804919
--- /dev/null
+++ b/frontend/src/utils/__tests__/mergeWinner.test.ts
@@ -0,0 +1,61 @@
+import { describe, it, expect } from 'vitest'
+import { deviceName, factCount, suggestWinner } from '@/utils/mergeWinner'
+import type { InventoryEntry } from '@/types'
+
+function entry(over: Partial<InventoryEntry>): InventoryEntry {
+ return {
+ id: 'x', ip: null, mac: null, hostname: null, os: null, services: [],
+ suggested_type: null, status: 'pending', discovered_at: '2026-01-01T00:00:00Z',
+ ...over,
+ } as InventoryEntry
+}
+
+describe('suggestWinner', () => {
+ it('prefers the row carrying an IEEE — imports and links key on it', () => {
+ const devices = [
+ entry({ id: 'canvas', canvas_count: 1, discovered_at: '2025-01-01T00:00:00Z' }),
+ entry({ id: 'proxmox', ieee_address: 'pve-pve1-130' }),
+ ]
+ expect(suggestWinner(devices)).toBe('proxmox')
+ })
+
+ it('falls back to a row that is already drawn on a canvas', () => {
+ const devices = [
+ entry({ id: 'stub' }),
+ entry({ id: 'drawn', canvas_count: 2, discovered_at: '2026-06-01T00:00:00Z' }),
+ ]
+ expect(suggestWinner(devices)).toBe('drawn')
+ })
+
+ it('falls back to the oldest row when nothing else separates them', () => {
+ const devices = [
+ entry({ id: 'young', discovered_at: '2026-06-01T00:00:00Z' }),
+ entry({ id: 'old', discovered_at: '2025-02-01T00:00:00Z' }),
+ ]
+ expect(suggestWinner(devices)).toBe('old')
+ })
+
+ it('is undefined for an empty selection', () => {
+ expect(suggestWinner([])).toBeUndefined()
+ })
+})
+
+describe('factCount', () => {
+ it('counts the scalars, services and properties a row knows', () => {
+ const rich = entry({
+ ip: '192.168.1.62', mac: 'bc:24:11:95:af:8c', hostname: 'n8n',
+ services: [{ port: 22, protocol: 'tcp', service_name: 'ssh' }] as InventoryEntry['services'],
+ properties: [{ key: 'VMID', value: '130' }] as InventoryEntry['properties'],
+ })
+ expect(factCount(rich)).toBe(5)
+ expect(factCount(entry({}))).toBe(0)
+ })
+})
+
+describe('deviceName', () => {
+ it('prefers the name the user gave the device', () => {
+ expect(deviceName(entry({ label: 'n8n', hostname: 'ct130', ip: '10.0.0.1' }))).toBe('n8n')
+ expect(deviceName(entry({ hostname: 'ct130', ip: '10.0.0.1' }))).toBe('ct130')
+ expect(deviceName(entry({}))).toBe('device')
+ })
+})
diff --git a/frontend/src/utils/mergeWinner.ts b/frontend/src/utils/mergeWinner.ts
new file mode 100644
index 0000000..44ede4e
--- /dev/null
+++ b/frontend/src/utils/mergeWinner.ts
@@ -0,0 +1,29 @@
+import type { InventoryEntry } from '@/types'
+
+/** The name the inventory prints for a device — the one the user gave it first. */
+export function deviceName(d: InventoryEntry): string {
+ return d.label ?? d.friendly_name ?? d.hostname ?? d.ip ?? d.ieee_address ?? 'device'
+}
+
+/**
+ * The row the others should fold into, by default.
+ *
+ * Mirrors the backend's own precedence (`device_merge._pick_winner`): an IEEE
+ * first — the Proxmox import and the mesh link graph key on it, so that row is
+ * where every other writer comes back — then a row that is already drawn on a
+ * canvas, then the oldest. Only a suggestion: the user picks in the end.
+ */
+export function suggestWinner(devices: InventoryEntry[]): string | undefined {
+ return [...devices].sort((a, b) => (
+ (a.ieee_address ? 0 : 1) - (b.ieee_address ? 0 : 1)
+ || ((b.canvas_count ?? 0) > 0 ? 1 : 0) - ((a.canvas_count ?? 0) > 0 ? 1 : 0)
+ || a.discovered_at.localeCompare(b.discovered_at)
+ || a.id.localeCompare(b.id)
+ ))[0]?.id
+}
+
+/** How much a row knows — shown so the user can tell the rich one from the stub. */
+export function factCount(d: InventoryEntry): number {
+ const scalars = [d.ip, d.mac, d.hostname, d.os, d.vendor, d.model, d.notes, d.ieee_address]
+ return scalars.filter(Boolean).length + (d.services?.length ?? 0) + (d.properties?.length ?? 0)
+}