Skip to content

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

feat: duplicate a device from the inventory detail modal (#481) (#553)

Pouzor - Rémy Jardientbb2bb3415ae2
diff --git a/backend/app/api/routes/scan.py b/backend/app/api/routes/scan.py
index 30a4c8b..598a302 100644
--- a/backend/app/api/routes/scan.py
+++ b/backend/app/api/routes/scan.py
@@ -546,6 +546,56 @@ async def update_pending(
return (await _with_canvas_counts(db, [device]))[0]
+# What a copy inherits: the facts two identical units share. Addresses, the
+# check target, services and the hostname describe one physical box, so they
+# stay behind — copied, they would make create_pending's dedup and every
+# importer treat the twin as the same device (issue #481).
+_DUPLICATED_FIELDS = (
+ "os", "suggested_type", "type", "model", "vendor", "friendly_name",
+ "device_subtype", "notes", "cpu_count", "cpu_model", "ram_gb", "disk_gb",
+ "show_hardware", "check_method", "rack_faceplate_id", "rack_u_height",
+ "rack_col_span", "rack_color",
+)
+
+
[email protected]("/pending/{device_id}/duplicate", response_model=InventoryDeviceResponse, status_code=201)
+async def duplicate_pending(
+ device_id: str,
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> InventoryDevice:
+ """Copy an inventory row into a new, hand-made one — the second unit of a
+ redundant pair, with the same specs and front panel but no identity yet."""
+ source = (
+ await db.execute(select(InventoryDevice).where(InventoryDevice.id == device_id))
+ ).scalar_one_or_none()
+ if not source:
+ raise HTTPException(status_code=404, detail="Device not found")
+
+ name = source.label or source.friendly_name or source.hostname or source.ip or source.ieee_address
+ discovery_source = "rack" if _is_rack_only(source) else "manual"
+ copy = InventoryDevice(
+ **{field: getattr(source, field) for field in _DUPLICATED_FIELDS},
+ label=f"{name} (copy)" if name else "Device (copy)",
+ properties=[dict(p) for p in source.properties or []],
+ services=[],
+ status="pending",
+ discovery_source=discovery_source,
+ discovery_sources=[discovery_source],
+ # Fresh port ids: a cable names a port by id, so the twin's ports must
+ # never be mistaken for the source's.
+ rack_ports=(
+ [{**p, "id": str(uuid.uuid4())} for p in source.rack_ports]
+ if source.rack_ports is not None
+ else None
+ ),
+ )
+ db.add(copy)
+ await db.commit()
+ await db.refresh(copy)
+ return (await _with_canvas_counts(db, [copy]))[0]
+
+
@router.delete("/pending", response_model=dict)
async def clear_pending(
db: AsyncSession = Depends(get_db),
diff --git a/backend/tests/scan/test_scan_duplicate.py b/backend/tests/scan/test_scan_duplicate.py
new file mode 100644
index 0000000..0091923
--- /dev/null
+++ b/backend/tests/scan/test_scan_duplicate.py
@@ -0,0 +1,170 @@
+"""Duplicating an inventory row: POST /scan/pending/{id}/duplicate (issue #481).
+
+A redundant pair is two identical boxes — the copy carries the specs and the
+front panel, never the identity of the unit it was copied from.
+"""
+import pytest
+from httpx import AsyncClient
+
+from app.db.models import InventoryDevice
+
+
+async def _seed(db_session, **kwargs) -> InventoryDevice:
+ fields = {
+ "ip": "192.168.1.20",
+ "mac": "aa:bb:cc:44:55:66",
+ "hostname": "sw-core-1",
+ "ieee_address": None,
+ "os": "RouterOS",
+ "services": [{"port": 22, "protocol": "tcp", "service_name": "ssh"}],
+ "suggested_type": "switch",
+ "status": "approved",
+ "discovery_source": "arp",
+ "discovery_sources": ["arp"],
+ "properties": [{"key": "PoE", "value": "370W", "icon": None, "visible": True}],
+ "label": "Core switch",
+ "type": "switch",
+ "model": "CRS326",
+ "vendor": "MikroTik",
+ "notes": "top of rack",
+ "ram_gb": 0.5,
+ "show_hardware": True,
+ "check_method": "ping",
+ "check_target": "192.168.1.20",
+ "rack_faceplate_id": "switch-24",
+ "rack_u_height": 1,
+ "rack_col_span": 12,
+ "rack_color": "#00d4ff",
+ "rack_ports": [
+ {"id": "p1", "label": "eth1", "type": "rj45", "x": 0.1, "y": 0.5},
+ {"id": "p2", "label": "sfp1", "type": "sfp", "x": 0.9, "y": 0.5},
+ ],
+ }
+ fields.update(kwargs)
+ device = InventoryDevice(**fields)
+ db_session.add(device)
+ await db_session.commit()
+ return device
+
+
+async def test_duplicate_requires_auth(client: AsyncClient, db_session):
+ device = await _seed(db_session)
+ res = await client.post(f"/api/v1/scan/pending/{device.id}/duplicate")
+ assert res.status_code == 401
+
+
+async def test_duplicate_unknown_id(client: AsyncClient, headers):
+ res = await client.post("/api/v1/scan/pending/nope/duplicate", headers=headers)
+ assert res.status_code == 404
+
+
+async def test_duplicate_copies_the_device_facts(client: AsyncClient, headers, db_session):
+ device = await _seed(db_session)
+ res = await client.post(f"/api/v1/scan/pending/{device.id}/duplicate", headers=headers)
+ assert res.status_code == 201, res.text
+ data = res.json()
+ assert data["id"] != device.id
+ assert data["label"] == "Core switch (copy)"
+ assert data["type"] == "switch"
+ assert data["model"] == "CRS326"
+ assert data["vendor"] == "MikroTik"
+ assert data["os"] == "RouterOS"
+ assert data["notes"] == "top of rack"
+ assert data["ram_gb"] == 0.5
+ assert data["show_hardware"] is True
+ assert data["check_method"] == "ping"
+ assert data["properties"] == [{"key": "PoE", "value": "370W", "icon": None, "visible": True}]
+
+
+async def test_duplicate_carries_the_front_panel_with_fresh_port_ids(
+ client: AsyncClient, headers, db_session
+):
+ """The port layout is the point of the copy, but a cable names a port by id —
+ the twin's ports must not answer to the source's ids."""
+ device = await _seed(db_session)
+ data = (await client.post(f"/api/v1/scan/pending/{device.id}/duplicate", headers=headers)).json()
+ assert data["rack_faceplate_id"] == "switch-24"
+ assert data["rack_u_height"] == 1
+ assert data["rack_col_span"] == 12
+ assert data["rack_color"] == "#00d4ff"
+ ports = data["rack_ports"]
+ assert [(p["label"], p["type"], p["x"], p["y"]) for p in ports] == [
+ ("eth1", "rj45", 0.1, 0.5),
+ ("sfp1", "sfp", 0.9, 0.5),
+ ]
+ ids = [p["id"] for p in ports]
+ assert len(set(ids)) == 2
+ assert not {"p1", "p2"} & set(ids)
+
+
+async def test_duplicate_leaves_the_identity_behind(client: AsyncClient, headers, db_session):
+ """Copied addresses would make dedup fold the twin back into the source."""
+ device = await _seed(db_session, ieee_address="0xABCD")
+ data = (await client.post(f"/api/v1/scan/pending/{device.id}/duplicate", headers=headers)).json()
+ assert data["ip"] is None
+ assert data["mac"] is None
+ assert data["ieee_address"] is None
+ assert data["hostname"] is None
+ assert data["check_target"] is None
+ assert data["services"] == []
+ assert data["status"] == "pending"
+ assert data["discovery_source"] == "manual"
+ assert data["discovery_sources"] == ["manual"]
+
+
+async def test_duplicate_leaves_the_source_untouched(client: AsyncClient, headers, db_session):
+ device = await _seed(db_session)
+ await client.post(f"/api/v1/scan/pending/{device.id}/duplicate", headers=headers)
+ await db_session.refresh(device)
+ assert device.ip == "192.168.1.20"
+ assert device.status == "approved"
+ assert [p["id"] for p in device.rack_ports] == ["p1", "p2"]
+
+
+async def test_duplicate_twice_gives_two_rows(client: AsyncClient, headers, db_session):
+ device = await _seed(db_session, status="pending")
+ first = (await client.post(f"/api/v1/scan/pending/{device.id}/duplicate", headers=headers)).json()
+ second = (await client.post(f"/api/v1/scan/pending/{device.id}/duplicate", headers=headers)).json()
+ assert first["id"] != second["id"]
+ listed = (await client.get("/api/v1/scan/pending", headers=headers)).json()
+ assert {device.id, first["id"], second["id"]} <= {d["id"] for d in listed}
+
+
+async def test_duplicate_of_rack_gear_stays_rack_gear(client: AsyncClient, headers, db_session):
+ """A rack-only row is never approved onto a logical canvas; its twin neither."""
+ device = await _seed(
+ db_session, ip=None, mac=None, discovery_source="rack", discovery_sources=["rack"]
+ )
+ data = (await client.post(f"/api/v1/scan/pending/{device.id}/duplicate", headers=headers)).json()
+ assert data["discovery_source"] == "rack"
+ assert data["discovery_sources"] == ["rack"]
+
+
+async def test_duplicate_names_an_unlabelled_row_after_its_hostname(
+ client: AsyncClient, headers, db_session
+):
+ device = await _seed(db_session, label=None, friendly_name=None)
+ data = (await client.post(f"/api/v1/scan/pending/{device.id}/duplicate", headers=headers)).json()
+ assert data["label"] == "sw-core-1 (copy)"
+
+
+async def test_duplicate_of_an_unmodelled_row_stays_unmodelled(
+ client: AsyncClient, headers, db_session
+):
+ device = await _seed(
+ db_session, rack_faceplate_id=None, rack_u_height=None, rack_col_span=None,
+ rack_color=None, rack_ports=None,
+ )
+ data = (await client.post(f"/api/v1/scan/pending/{device.id}/duplicate", headers=headers)).json()
+ assert data["rack_faceplate_id"] is None
+ assert data["rack_ports"] == []
diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts
index 458663b..bb52bcd 100644
--- a/frontend/src/api/client.ts
+++ b/frontend/src/api/client.ts
@@ -199,6 +199,11 @@ export const scanApi = {
*/
updatePending: (id: string, data: Partial<Omit<InventoryEntry, 'id' | 'status' | 'discovered_at'>>) =>
api.patch<InventoryEntry>(`/scan/pending/${id}`, data),
+ /**
+ * Copy an inventory row into a new pending one: specs, properties and front
+ * panel carried, addresses and services left behind (issue #481).
+ */
+ duplicatePending: (id: string) => api.post<InventoryEntry>(`/scan/pending/${id}/duplicate`),
/**
* Deep-rescan one known device: every TCP port, then re-fingerprint. Answers
* "this device predates the scanner knowing that service" (issue #350).
diff --git a/frontend/src/components/modals/DeviceInventoryModal.tsx b/frontend/src/components/modals/DeviceInventoryModal.tsx
index 041964a..b533d95 100644
--- a/frontend/src/components/modals/DeviceInventoryModal.tsx
+++ b/frontend/src/components/modals/DeviceInventoryModal.tsx
@@ -1003,6 +1003,21 @@ export function DeviceInventoryModal({ open, onClose, highlightId, initialStatus
setDevices((prev) => prev.map((d) => (d.id === saved.id ? saved : d)))
setSelected(saved)
}}
+ onDuplicated={
+ demoDevices
+ ? undefined
+ : (copy) => {
+ // The copy is pending, so it only belongs in the pending list —
+ // right after its source, where the user just was.
+ if (statusFilter === 'pending') {
+ setDevices((prev) => {
+ const at = prev.findIndex((d) => d.id === selected?.id)
+ return at === -1 ? [...prev, copy] : [...prev.slice(0, at + 1), copy, ...prev.slice(at + 1)]
+ })
+ }
+ setSelected(copy)
+ }
+ }
/>
<MergeDevicesModal
diff --git a/frontend/src/components/modals/InventoryDeviceModal.tsx b/frontend/src/components/modals/InventoryDeviceModal.tsx
index 608f96d..a5abf25 100644
--- a/frontend/src/components/modals/InventoryDeviceModal.tsx
+++ b/frontend/src/components/modals/InventoryDeviceModal.tsx
@@ -19,6 +19,7 @@ import {
BookOpen,
Check,
Copy,
+ CopyPlus,
Factory,
Fingerprint,
HeartPulse,
@@ -72,6 +73,9 @@ interface InventoryDeviceModalProps {
onIgnore: (device: InventoryEntry) => void
/** Called with the saved row after an edit, so the list can refresh in place. */
onSaved?: (device: InventoryEntry) => void
+ /** Called with the copy after a Duplicate, so the list can add it and point
+ * this modal at it. Absent wherever there is no backend. */
+ onDuplicated?: (copy: InventoryEntry) => void
/** Opens the Documentation section on this device, writing the document
* first if it has none. Absent wherever there is no backend. */
onOpenDocumentation?: (deviceId: string, label: string) => void
@@ -287,7 +291,7 @@ function toRackModel(d: InventoryEntry): DeviceRackModel | null {
const nullable = (v: string) => (v.trim() === '' ? null : v.trim())
const numeric = (v: string) => (v.trim() === '' ? null : Number(v))
-export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgnore, onSaved, onOpenDocumentation }: InventoryDeviceModalProps) {
+export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgnore, onSaved, onDuplicated, onOpenDocumentation }: InventoryDeviceModalProps) {
const [editing, setEditing] = useState(false)
const [form, setForm] = useState<EditForm>(() => (device ? toForm(device) : toForm({} as InventoryEntry)))
const [properties, setProperties] = useState<NodeProperty[]>(device?.properties ?? [])
@@ -304,6 +308,10 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgn
const [rescanStarting, setRescanStarting] = useState(false)
// The port-range dialog, opened by the Deep scan link.
const [deepScanOpen, setDeepScanOpen] = useState(false)
+ const [duplicating, setDuplicating] = useState(false)
+ // The copy a Duplicate just made: when the parent points the modal at it, it
+ // opens in edit mode, since its IP and MAC are the first thing to fill in.
+ const editOnOpenRef = useRef<string | null>(null)
const activeTheme = useThemeStore((s) => s.activeTheme)
// Kept in a ref so the poll effect below doesn't restart — and lose its
// timer — every time the parent re-renders with a new callback identity.
@@ -332,7 +340,8 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgn
setProperties(d.properties ?? [])
setServices(d.services ?? [])
setRackModel(toRackModel(d))
- setEditing(false)
+ setEditing(editOnOpenRef.current === d.id)
+ editOnOpenRef.current = null
setSvcModal(null)
setRescanRunId(null)
setDeepScanOpen(false)
@@ -408,6 +417,21 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgn
const handleHide = () => { onHide(device); onClose() }
const handleIgnore = () => { onIgnore(device); onClose() }
+ const handleDuplicate = async () => {
+ if (!onDuplicated || duplicating) return
+ setDuplicating(true)
+ try {
+ const res = await scanApi.duplicatePending(device.id)
+ editOnOpenRef.current = res.data.id
+ toast.success('Device duplicated — set its addresses')
+ onDuplicated(res.data)
+ } catch {
+ toast.error('Could not duplicate device')
+ } finally {
+ setDuplicating(false)
+ }
+ }
+
const handleCancel = () => {
setEditing(false)
setForm(toForm(device))
@@ -571,6 +595,18 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgn
<BookOpen size={13} /> Documentation
</Button>
)}
+ {onDuplicated && (
+ <Button
+ size="sm"
+ variant="ghost"
+ className={`gap-1.5 text-[#00d4ff] hover:text-[#00d4ff] hover:bg-[#00d4ff]/10 ${modalStyles['modal-interactive']}`}
+ onClick={handleDuplicate}
+ disabled={duplicating}
+ title="Add a copy of this device — same specs and front panel, no addresses"
+ >
+ {duplicating ? <Loader2 size={13} className="animate-spin" /> : <CopyPlus size={13} />} Duplicate
+ </Button>
+ )}
<Button
size="sm"
variant="ghost"
diff --git a/frontend/src/components/modals/__tests__/DeviceInventoryModalDuplicate.test.tsx b/frontend/src/components/modals/__tests__/DeviceInventoryModalDuplicate.test.tsx
new file mode 100644
index 0000000..9d4a17d
--- /dev/null
+++ b/frontend/src/components/modals/__tests__/DeviceInventoryModalDuplicate.test.tsx
@@ -0,0 +1,97 @@
+/**
+ * The inventory list's half of Duplicate (issue #481): the copy joins the list
+ * next to its source, and the detail modal moves onto it.
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { render, screen, fireEvent, waitFor } from '@testing-library/react'
+import { DeviceInventoryModal } from '../DeviceInventoryModal'
+import { useCanvasStore } from '@/stores/canvasStore'
+
+vi.mock('@/stores/canvasStore')
+
+const mockPending = vi.fn()
+const mockHidden = vi.fn()
+
+vi.mock('@/api/client', () => ({
+ scanApi: {
+ pending: (...a: unknown[]) => mockPending(...a),
+ hidden: (...a: unknown[]) => mockHidden(...a),
+ },
+}))
+
+vi.mock('sonner', async () => (await import('@/test/mocks')).mockSonner())
+
+vi.mock('@/components/modals/InventoryDeviceModal', () => ({
+ InventoryDeviceModal: ({
+ device,
+ onDuplicated,
+ }: {
+ device: { id: string } | null
+ onDuplicated?: (copy: unknown) => void
+ }) =>
+ device ? (
+ <div data-testid={`detail-${device.id}`}>
+ {onDuplicated && (
+ <button data-testid="duplicate" onClick={() => onDuplicated({ ...COPY })}>duplicate</button>
+ )}
+ </div>
+ ) : null,
+}))
+
+function device(id: string, hostname: string) {
+ return {
+ id,
+ ip: null,
+ hostname,
+ mac: null,
+ os: null,
+ services: [],
+ suggested_type: 'switch',
+ status: 'pending',
+ discovery_source: 'manual',
+ discovered_at: '2026-01-01T00:00:00Z',
+ }
+}
+
+const SW1 = device('sw-1', 'sw-core-1')
+const OTHER = device('other', 'other-box')
+const COPY = { ...device('sw-1-copy', ''), hostname: null, label: 'sw-core-1 (copy)' }
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ vi.mocked(useCanvasStore).mockImplementation(((sel?: (s: unknown) => unknown) => {
+ const store = { addNode: vi.fn(), scanEventTs: 0, setSelectedNode: vi.fn() }
+ return sel ? sel(store) : store
+ }) as unknown as typeof useCanvasStore)
+ mockPending.mockResolvedValue({ data: [SW1, OTHER] })
+ mockHidden.mockResolvedValue({ data: [SW1] })
+})
+
+Element.prototype.scrollIntoView = vi.fn()
+
+const cardIds = () =>
+ screen.getAllByTestId(/^pending-card-/).map((el) => el.getAttribute('data-testid')!.replace('pending-card-', ''))
+
+describe('DeviceInventoryModal — duplicate', () => {
+ it('lists the copy right after its source and opens it', async () => {
+ render(<DeviceInventoryModal open onClose={vi.fn()} highlightId="sw-1" />)
+ await waitFor(() => expect(screen.getByTestId('detail-sw-1')).toBeInTheDocument())
+ fireEvent.click(screen.getByTestId('duplicate'))
+ await waitFor(() => expect(screen.getByTestId('detail-sw-1-copy')).toBeInTheDocument())
+ expect(cardIds()).toEqual(['sw-1', 'sw-1-copy', 'other'])
+ })
+
+ it('keeps a pending copy out of the hidden list, but still opens it', async () => {
+ render(<DeviceInventoryModal open onClose={vi.fn()} initialStatus="hidden" highlightId="sw-1" />)
+ await waitFor(() => expect(screen.getByTestId('detail-sw-1')).toBeInTheDocument())
+ fireEvent.click(screen.getByTestId('duplicate'))
+ await waitFor(() => expect(screen.getByTestId('detail-sw-1-copy')).toBeInTheDocument())
+ expect(screen.queryByTestId('pending-card-sw-1-copy')).toBeNull()
+ })
+
+ it('offers no Duplicate in the tour, which never reaches the backend', async () => {
+ render(<DeviceInventoryModal open onClose={vi.fn()} demoDevices={[SW1] as never} highlightId="sw-1" />)
+ await waitFor(() => expect(screen.getByTestId('detail-sw-1')).toBeInTheDocument())
+ expect(screen.queryByTestId('duplicate')).toBeNull()
+ })
+})
diff --git a/frontend/src/components/modals/__tests__/InventoryDeviceModalDuplicate.test.tsx b/frontend/src/components/modals/__tests__/InventoryDeviceModalDuplicate.test.tsx
new file mode 100644
index 0000000..df290ab
--- /dev/null
+++ b/frontend/src/components/modals/__tests__/InventoryDeviceModalDuplicate.test.tsx
@@ -0,0 +1,105 @@
+/**
+ * Duplicate from the device detail modal (issue #481): a redundant pair is two
+ * identical boxes, so the second one starts as a copy of the first.
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { render, screen, fireEvent, waitFor } from '@testing-library/react'
+import { useState } from 'react'
+import { InventoryDeviceModal } from '../InventoryDeviceModal'
+import type { InventoryEntry } from '@/types'
+
+const mockDuplicatePending = vi.fn()
+
+vi.mock('@/api/client', () => ({
+ scanApi: {
+ duplicatePending: (...a: unknown[]) => mockDuplicatePending(...a),
+ },
+}))
+
+vi.mock('sonner', async () => (await import('@/test/mocks')).mockSonner())
+
+function makeDevice(overrides: Partial<InventoryEntry> = {}): InventoryEntry {
+ return {
+ id: 'dev-1',
+ ip: '192.168.1.20',
+ mac: 'aa:bb:cc:44:55:66',
+ hostname: 'sw-core-1',
+ os: null,
+ services: [],
+ suggested_type: 'switch',
+ status: 'pending',
+ discovered_at: '2026-01-15T10:30:00Z',
+ label: 'Core switch',
+ ...overrides,
+ }
+}
+
+const COPY = makeDevice({ id: 'dev-2', ip: null, mac: null, hostname: null, label: 'Core switch (copy)' })
+
+const noop = { onClose: vi.fn(), onApprove: vi.fn(), onHide: vi.fn(), onIgnore: vi.fn() }
+
+/** The parent's half: point the modal at whatever the duplicate returned. */
+function Host({ onDuplicated }: { onDuplicated?: (copy: InventoryEntry) => void }) {
+ const [device, setDevice] = useState<InventoryEntry>(makeDevice())
+ return (
+ <InventoryDeviceModal
+ {...noop}
+ device={device}
+ onDuplicated={(copy) => {
+ onDuplicated?.(copy)
+ setDevice(copy)
+ }}
+ />
+ )
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ mockDuplicatePending.mockResolvedValue({ data: COPY })
+})
+
+describe('InventoryDeviceModal — duplicate', () => {
+ it('offers no Duplicate where the caller cannot take the copy', () => {
+ render(<InventoryDeviceModal {...noop} device={makeDevice()} />)
+ expect(screen.queryByRole('button', { name: /Duplicate/ })).toBeNull()
+ })
+
+ it('duplicates the shown device and hands the copy to the caller', async () => {
+ const onDuplicated = vi.fn()
+ render(<Host onDuplicated={onDuplicated} />)
+ fireEvent.click(screen.getByRole('button', { name: /Duplicate/ }))
+ await waitFor(() => expect(onDuplicated).toHaveBeenCalledWith(COPY))
+ expect(mockDuplicatePending).toHaveBeenCalledWith('dev-1')
+ })
+
+ it('opens the copy in edit mode, its addresses being the first thing to set', async () => {
+ render(<Host />)
+ fireEvent.click(screen.getByRole('button', { name: /Duplicate/ }))
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Save' })).toBeInTheDocument())
+ expect(screen.getAllByText('Core switch (copy)').length).toBeGreaterThan(0)
+ })
+
+ it('stays on the source in view mode when the duplicate fails', async () => {
+ const { toast } = await import('sonner')
+ mockDuplicatePending.mockRejectedValue(new Error('boom'))
+ const onDuplicated = vi.fn()
+ render(<Host onDuplicated={onDuplicated} />)
+ fireEvent.click(screen.getByRole('button', { name: /Duplicate/ }))
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Could not duplicate device'))
+ expect(onDuplicated).not.toHaveBeenCalled()
+ expect(screen.getByRole('button', { name: /Duplicate/ })).not.toBeDisabled()
+ expect(screen.queryByRole('button', { name: 'Save' })).toBeNull()
+ })
+
+ it('disables the button while the copy is on its way', async () => {
+ let resolve: (v: unknown) => void = () => {}
+ mockDuplicatePending.mockReturnValue(new Promise((r) => { resolve = r }))
+ render(<Host />)
+ fireEvent.click(screen.getByRole('button', { name: /Duplicate/ }))
+ await waitFor(() => expect(screen.getByRole('button', { name: /Duplicate/ })).toBeDisabled())
+ fireEvent.click(screen.getByRole('button', { name: /Duplicate/ }))
+ expect(mockDuplicatePending).toHaveBeenCalledTimes(1)
+ resolve({ data: COPY })
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Save' })).toBeInTheDocument())
+ })
+})