Skip to content

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

feat(zigbee): opt auto-sync into mesh links from Settings

Pouzor1165b342aa96
diff --git a/backend/app/api/routes/zigbee.py b/backend/app/api/routes/zigbee.py
index 953b041..47d975d 100644
--- a/backend/app/api/routes/zigbee.py
+++ b/backend/app/api/routes/zigbee.py
@@ -193,9 +193,9 @@ def env_import_request() -> ZigbeeImportRequest:
base_topic=settings.zigbee_base_topic,
mqtt_tls=settings.zigbee_mqtt_tls,
mqtt_tls_insecure=settings.zigbee_mqtt_tls_insecure,
- # The scheduled auto-sync keeps the readable parent tree. Importing the
- # full mesh is a deliberate, per-import choice made in the UI.
- include_mesh_links=False,
+ # Parent tree only unless the user opted into the mesh in Settings —
+ # the neighbour links multiply the edge count.
+ include_mesh_links=settings.zigbee_sync_include_mesh_links,
)
@@ -416,6 +416,7 @@ async def get_zigbee_config(_: str = Depends(get_current_user)) -> ZigbeeConfig:
mqtt_tls=settings.zigbee_mqtt_tls,
sync_enabled=settings.zigbee_sync_enabled,
sync_interval=settings.zigbee_sync_interval,
+ include_mesh_links=settings.zigbee_sync_include_mesh_links,
host_configured=bool(settings.zigbee_mqtt_host),
)
@@ -425,7 +426,7 @@ async def save_zigbee_config(
payload: ZigbeeSyncConfig,
_: str = Depends(get_current_user),
) -> ZigbeeConfig:
- """Persist the auto-sync activation (enabled + interval) and apply it live.
+ """Persist the auto-sync activation (enabled, interval, mesh links) and apply it live.
This is the ONLY Zigbee config the app writes. Connection settings
(host/port/credentials/topic/tls) are env-only and are never accepted or
@@ -440,6 +441,7 @@ async def save_zigbee_config(
try:
settings.zigbee_sync_enabled = payload.sync_enabled
settings.zigbee_sync_interval = payload.sync_interval
+ settings.zigbee_sync_include_mesh_links = payload.include_mesh_links
settings.save_overrides()
set_zigbee_sync_enabled(payload.sync_enabled)
if payload.sync_enabled:
diff --git a/backend/app/core/config.py b/backend/app/core/config.py
index fff41d2..bbd6037 100644
--- a/backend/app/core/config.py
+++ b/backend/app/core/config.py
@@ -232,6 +232,9 @@ class Settings(BaseSettings):
zigbee_mqtt_tls_insecure: bool = False
zigbee_sync_enabled: bool = False
zigbee_sync_interval: int = 3600 # seconds (floor 300 enforced on write)
+ # Also import the neighbour (mesh) links on auto-sync / sync-now, not only the
+ # parent tree. Off by default — a mesh multiplies the edge count ~3x.
+ zigbee_sync_include_mesh_links: bool = False
# Seconds to wait for the Z2M bridge to answer a networkmap request. A mesh
# of 200+ devices can take several minutes to build the map, so raise this
# if imports fail with "Timed out waiting for networkmap response".
@@ -332,6 +335,8 @@ class Settings(BaseSettings):
self.zigbee_sync_enabled = bool(data["zigbee_sync_enabled"])
if "zigbee_sync_interval" in data:
self.zigbee_sync_interval = int(data["zigbee_sync_interval"])
+ if "zigbee_sync_include_mesh_links" in data:
+ self.zigbee_sync_include_mesh_links = bool(data["zigbee_sync_include_mesh_links"])
if "zwave_sync_enabled" in data:
self.zwave_sync_enabled = bool(data["zwave_sync_enabled"])
if "zwave_sync_interval" in data:
@@ -375,6 +380,7 @@ class Settings(BaseSettings):
# connection config (host/port/credentials/topic/tls) is env-only.
"zigbee_sync_enabled": self.zigbee_sync_enabled,
"zigbee_sync_interval": self.zigbee_sync_interval,
+ "zigbee_sync_include_mesh_links": self.zigbee_sync_include_mesh_links,
"zwave_sync_enabled": self.zwave_sync_enabled,
"zwave_sync_interval": self.zwave_sync_interval,
# UniFi: non-secret connection config + auto-sync activation persisted.
diff --git a/backend/app/schemas/zigbee.py b/backend/app/schemas/zigbee.py
index 95048d2..4b2532f 100644
--- a/backend/app/schemas/zigbee.py
+++ b/backend/app/schemas/zigbee.py
@@ -142,6 +142,7 @@ class ZigbeeConfig(BaseModel):
mqtt_tls: bool = False
sync_enabled: bool = False
sync_interval: int = Field(3600, ge=300)
+ include_mesh_links: bool = False
host_configured: bool = False
@@ -152,3 +153,5 @@ class ZigbeeSyncConfig(BaseModel):
sync_enabled: bool = False
sync_interval: int = Field(3600, ge=300)
+ # Import the neighbour (mesh) links too, like the manual dialog's checkbox.
+ include_mesh_links: bool = False
diff --git a/backend/tests/test_settings.py b/backend/tests/test_settings.py
index 0f7e8eb..1e09ff0 100644
--- a/backend/tests/test_settings.py
+++ b/backend/tests/test_settings.py
@@ -196,6 +196,18 @@ def test_save_overrides_omits_mesh_credentials(tmp_path):
assert written["zwave_sync_interval"] == 1200
+
+def test_zigbee_mesh_links_setting_round_trips(tmp_path):
+ """The auto-sync mesh-links opt-in is a UI setting: it must survive a restart."""
+ s = Settings(secret_key="x", sqlite_path=str(tmp_path / "homelab.db"))
+ assert s.zigbee_sync_include_mesh_links is False
+ s.zigbee_sync_include_mesh_links = True
+ s.save_overrides()
+ assert json.loads((tmp_path / "scan_config.json").read_text())["zigbee_sync_include_mesh_links"] is True
+ fresh = Settings(secret_key="x", sqlite_path=str(tmp_path / "homelab.db"))
+ fresh.load_overrides()
+ assert fresh.zigbee_sync_include_mesh_links is True
+
def _valid_oidc_settings(**overrides):
values = {
"secret_key": "test-secret-key-that-is-at-least-32-bytes",
diff --git a/backend/tests/test_zigbee_router.py b/backend/tests/test_zigbee_router.py
index 9bc7b6c..bf35523 100644
--- a/backend/tests/test_zigbee_router.py
+++ b/backend/tests/test_zigbee_router.py
@@ -969,6 +969,56 @@ async def test_save_config_persists_only_sync_fields(
assert saved == {"host": "broker", "enabled": True, "interval": 900}
+
+async def test_save_config_persists_mesh_links_opt_in(
+ client: AsyncClient, headers: dict, _restore_zigbee_env, monkeypatch
+) -> None:
+ settings.zigbee_mqtt_host = "broker"
+ monkeypatch.setattr(settings, "zigbee_sync_include_mesh_links", False)
+ with patch.object(type(settings), "save_overrides", lambda self: None), \
+ patch("app.api.routes.zigbee.set_zigbee_sync_enabled"), \
+ patch("app.api.routes.zigbee.reschedule_zigbee_sync"):
+ res = await client.post(
+ "/api/v1/zigbee/config",
+ json={"sync_enabled": True, "sync_interval": 900, "include_mesh_links": True},
+ headers=headers,
+ )
+ assert res.status_code == 200
+ assert res.json()["include_mesh_links"] is True
+ assert settings.zigbee_sync_include_mesh_links is True
+ res = await client.get("/api/v1/zigbee/config", headers=headers)
+ assert res.json()["include_mesh_links"] is True
+
+
+async def test_save_config_mesh_links_defaults_off(
+ client: AsyncClient, headers: dict, _restore_zigbee_env, monkeypatch
+) -> None:
+ settings.zigbee_mqtt_host = "broker"
+ monkeypatch.setattr(settings, "zigbee_sync_include_mesh_links", True)
+ with patch.object(type(settings), "save_overrides", lambda self: None), \
+ patch("app.api.routes.zigbee.set_zigbee_sync_enabled"), \
+ patch("app.api.routes.zigbee.reschedule_zigbee_sync"):
+ res = await client.post(
+ "/api/v1/zigbee/config",
+ json={"sync_enabled": False, "sync_interval": 900},
+ headers=headers,
+ )
+ assert res.status_code == 200
+ assert settings.zigbee_sync_include_mesh_links is False
+
+
[email protected]("enabled", [True, False])
+def test_env_import_request_follows_mesh_links_setting(monkeypatch, enabled: bool) -> None:
+ """Auto-sync and /sync-now both build their request here, so the Settings
+ toggle reaches the scheduled job and the manual re-sync alike."""
+ from app.api.routes.zigbee import env_import_request
+
+ monkeypatch.setattr(settings, "zigbee_mqtt_host", "broker")
+ monkeypatch.setattr(settings, "zigbee_sync_include_mesh_links", enabled)
+ assert env_import_request().include_mesh_links is enabled
+
@pytest.mark.asyncio
async def test_sync_now_creates_scan_run(
client: AsyncClient, headers: dict, _restore_zigbee_env
diff --git a/docs/zigbee-import.md b/docs/zigbee-import.md
index 1228374..22b0e68 100644
--- a/docs/zigbee-import.md
+++ b/docs/zigbee-import.md
@@ -20,7 +20,9 @@ This feature lets you connect Homelable to your MQTT broker, fetch the Zigbee2MQ
edge per device. Tick **Import mesh links** to also draw neighbour-to-neighbour
links, as a distinct `Zigbee Mesh` edge type in its own colour. Expect far more
edges — a 37-device network goes from ~36 to ~115 — which is why it is off by
- default and excluded from the scheduled auto-sync.
+ default. The scheduled auto-sync and **Re-sync now** have their own
+ **Import mesh links** toggle under Settings → Zigbee auto-sync, also off by
+ default.
---
diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts
index 17f1029..5ccd58c 100644
--- a/frontend/src/api/client.ts
+++ b/frontend/src/api/client.ts
@@ -414,6 +414,7 @@ export interface ZigbeeConfigData {
mqtt_tls: boolean
sync_enabled: boolean
sync_interval: number
+ include_mesh_links: boolean
host_configured: boolean
}
@@ -500,7 +501,7 @@ export const zigbeeApi = {
getConfig: () => api.get<ZigbeeConfigData>('/zigbee/config'),
// Only the auto-sync activation is persisted. MQTT connection config
// (host/port/credentials/topic/tls) is env-only and never sent.
- saveConfig: (data: { sync_enabled: boolean; sync_interval: number }) =>
+ saveConfig: (data: { sync_enabled: boolean; sync_interval: number; include_mesh_links: boolean }) =>
api.post<ZigbeeConfigData>('/zigbee/config', data),
syncNow: () => api.post<ScanRunResult>('/zigbee/sync-now'),
}
diff --git a/frontend/src/components/modals/SettingsModal.tsx b/frontend/src/components/modals/SettingsModal.tsx
index 845c197..f858070 100644
--- a/frontend/src/components/modals/SettingsModal.tsx
+++ b/frontend/src/components/modals/SettingsModal.tsx
@@ -1,4 +1,4 @@
-import { useState, useEffect } from 'react'
+import { useState, useEffect, type ReactNode } from 'react'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import {
@@ -48,6 +48,8 @@ interface MeshAutoSyncProps {
description: string
syncing: boolean
onSyncNow: () => void
+ /** Source-specific import options, applied to auto-sync and Re-sync now alike. */
+ options?: ReactNode
}
/**
@@ -58,7 +60,7 @@ interface MeshAutoSyncProps {
*/
function MeshAutoSync({
title, accent, hostConfigured, envHostVar, enabled, onEnabledChange,
- interval, onIntervalChange, description, syncing, onSyncNow,
+ interval, onIntervalChange, description, syncing, onSyncNow, options,
}: MeshAutoSyncProps) {
return (
<div className="pt-3 border-t border-border space-y-2">
@@ -96,6 +98,7 @@ function MeshAutoSync({
</div>
<p className="text-[10px] text-muted-foreground leading-tight">{description}</p>
</div>
+ {options}
<div className="flex items-center gap-2 pt-1">
<Button
variant="outline"
@@ -139,6 +142,7 @@ export function SettingsModal({ open, onClose }: SettingsModalProps) {
const [zbConfig, setZbConfig] = useState<ZigbeeConfigData | null>(null)
const [zbSyncEnabled, setZbSyncEnabled] = useState(false)
const [zbInterval, setZbInterval] = useState(3600)
+ const [zbMeshLinks, setZbMeshLinks] = useState(false)
const [zbSyncing, setZbSyncing] = useState(false)
const [zwConfig, setZwConfig] = useState<ZwaveConfigData | null>(null)
const [zwSyncEnabled, setZwSyncEnabled] = useState(false)
@@ -183,6 +187,7 @@ export function SettingsModal({ open, onClose }: SettingsModalProps) {
setZbConfig(res.data)
setZbSyncEnabled(res.data.sync_enabled)
setZbInterval(res.data.sync_interval)
+ setZbMeshLinks(res.data.include_mesh_links)
})
.catch(() => {/* zigbee not configured */})
zwaveApi.getConfig()
@@ -293,6 +298,7 @@ export function SettingsModal({ open, onClose }: SettingsModalProps) {
await zigbeeApi.saveConfig({
sync_enabled: zbSyncEnabled,
sync_interval: zbInterval,
+ include_mesh_links: zbMeshLinks,
})
}
if (zwConfig) {
@@ -495,6 +501,24 @@ export function SettingsModal({ open, onClose }: SettingsModalProps) {
description="Re-imports the Zigbee mesh into the pending inventory. Min 300s (5 min)."
syncing={zbSyncing}
onSyncNow={handleZbSyncNow}
+ options={
+ <label className="flex items-center justify-between gap-2 cursor-pointer">
+ <span className="text-xs text-foreground">
+ Import mesh links
+ <span className="block text-[10px] text-muted-foreground leading-tight">
+ Neighbour links too, not only the parent tree — many more edges.
+ </span>
+ </span>
+ <input
+ type="checkbox"
+ checked={zbMeshLinks}
+ onChange={(e) => setZbMeshLinks(e.target.checked)}
+ className="cursor-pointer"
+ style={{ accentColor: '#39d353' }}
+ aria-label="Import Zigbee mesh links"
+ />
+ </label>
+ }
/>
)}
diff --git a/frontend/src/components/modals/__tests__/SettingsModal.test.tsx b/frontend/src/components/modals/__tests__/SettingsModal.test.tsx
index f5e2d20..8e4361f 100644
--- a/frontend/src/components/modals/__tests__/SettingsModal.test.tsx
+++ b/frontend/src/components/modals/__tests__/SettingsModal.test.tsx
@@ -194,6 +194,35 @@ describe('SettingsModal', () => {
})
})
+ it('hydrates the Zigbee mesh-links opt-in and persists a change on Save', async () => {
+ vi.mocked(zigbeeApi.getConfig).mockResolvedValue(zbConfig({ sync_enabled: true, sync_interval: 1800, include_mesh_links: false }) as never)
+ render(<SettingsModal open onClose={vi.fn()} />)
+ await screen.findByDisplayValue('60')
+ await waitFor(() => expect(screen.getByLabelText('Toggle Zigbee auto-sync')).toBeChecked())
+ const mesh = screen.getByLabelText('Import Zigbee mesh links')
+ expect(mesh).not.toBeChecked()
+ fireEvent.click(mesh)
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))
+ await waitFor(() => {
+ expect(zigbeeApi.saveConfig).toHaveBeenCalledWith({ sync_enabled: true, sync_interval: 1800, include_mesh_links: true })
+ })
+ })
+
+ it('shows a saved Zigbee mesh-links opt-in as checked, even with auto-sync off', async () => {
+ vi.mocked(zigbeeApi.getConfig).mockResolvedValue(zbConfig({ sync_enabled: false, include_mesh_links: true }) as never)
+ render(<SettingsModal open onClose={vi.fn()} />)
+ // Re-sync now honours it too, so it stays usable while auto-sync is off.
+ await waitFor(() => expect(screen.getByLabelText('Import Zigbee mesh links')).toBeChecked())
+ expect(screen.getByLabelText('Import Zigbee mesh links')).toBeEnabled()
+ })
+
+ it('offers the mesh-links option on Zigbee only, not Z-Wave', async () => {
+ vi.mocked(zwaveApi.getConfig).mockResolvedValue(zwConfig() as never)
+ render(<SettingsModal open onClose={vi.fn()} />)
+ await screen.findByText('Z-Wave auto-sync')
+ expect(screen.queryByLabelText('Import Zigbee mesh links')).toBeNull()
+ })
+
it('triggers an immediate Z-Wave sync from its Re-sync now button', async () => {
vi.mocked(zwaveApi.getConfig).mockResolvedValue(zwConfig() as never)
render(<SettingsModal open onClose={vi.fn()} />)