Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b0df8f389a | |||
| 8bd1c48976 | |||
| 05c98355a6 | |||
| 323dea6798 | |||
| 19cb4b71f5 | |||
| fd86c0f6ad | |||
| 00d44abfad | |||
| 3bd18ab543 | |||
| 4d8bb246f1 | |||
| 07da498d18 | |||
| 0e59f15608 | |||
| bd22891fab | |||
| d96b502524 | |||
| 9cb9d02459 |
+5
-29
@@ -53,37 +53,13 @@ docker compose up -d
|
|||||||
|
|
||||||
## Proxmox LXC Install
|
## Proxmox LXC Install
|
||||||
|
|
||||||
Run this **on the Proxmox host** — it creates a Debian 12 LXC container and installs Homelable inside automatically:
|
You can now install Homelable with community-scripts (proxmox-VE) :
|
||||||
|
|
||||||
|
`https://community-scripts.org/scripts/homelable`
|
||||||
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
bash <(curl -fsSL https://raw.githubusercontent.com/Pouzor/homelable/main/scripts/install-proxmox.sh)
|
bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/ct/homelable.sh)"
|
||||||
```
|
|
||||||
|
|
||||||
Default container settings: 2 cores, 1 GB RAM, 8 GB disk, DHCP on `vmbr0`. Override before running:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
CTID=150 RAM=2048 STORAGE=local-zfs bash <(curl -fsSL .../install-proxmox.sh)
|
|
||||||
```
|
|
||||||
|
|
||||||
The backend runs as a systemd service, the frontend is served via nginx on port 80.
|
|
||||||
|
|
||||||
> To install manually inside an existing Debian/Ubuntu machine or LXC:
|
|
||||||
> ```bash
|
|
||||||
> bash <(curl -fsSL https://raw.githubusercontent.com/Pouzor/homelable/main/scripts/lxc-install.sh)
|
|
||||||
> ```
|
|
||||||
|
|
||||||
### Update (LXC)
|
|
||||||
|
|
||||||
Run the update script inside the container (pulls latest code, rebuilds frontend, restarts services — `.env` and database are never touched):
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo bash /opt/homelable/scripts/update.sh
|
|
||||||
```
|
|
||||||
|
|
||||||
Or directly from GitHub:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo bash <(curl -fsSL https://raw.githubusercontent.com/Pouzor/homelable/main/scripts/update.sh)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
+1
-1
@@ -35,7 +35,7 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
|||||||
|
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="Homelable API",
|
title="Homelable API",
|
||||||
version="1.8.0",
|
version="1.8.3",
|
||||||
lifespan=lifespan,
|
lifespan=lifespan,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
import socket
|
import socket
|
||||||
|
import sys
|
||||||
import time
|
import time
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
@@ -57,8 +58,12 @@ async def check_node(check_method: str, target: str | None, ip: str | None) -> d
|
|||||||
|
|
||||||
|
|
||||||
async def _ping(host: str) -> bool:
|
async def _ping(host: str) -> bool:
|
||||||
|
if sys.platform == "win32":
|
||||||
|
args = ["ping", "-n", "1", "-w", "1000", host]
|
||||||
|
else:
|
||||||
|
args = ["ping", "-c", "1", "-W", "1", host]
|
||||||
proc = await asyncio.create_subprocess_exec(
|
proc = await asyncio.create_subprocess_exec(
|
||||||
"ping", "-c", "1", "-W", "1", host,
|
*args,
|
||||||
stdout=asyncio.subprocess.DEVNULL,
|
stdout=asyncio.subprocess.DEVNULL,
|
||||||
stderr=asyncio.subprocess.DEVNULL,
|
stderr=asyncio.subprocess.DEVNULL,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from app.services.status_checker import _tcp_connect, check_node
|
from app.services.status_checker import _ping, _tcp_connect, check_node
|
||||||
|
|
||||||
# --- check_node dispatcher ---
|
# --- check_node dispatcher ---
|
||||||
|
|
||||||
@@ -149,6 +149,48 @@ async def test_check_node_exception_returns_offline():
|
|||||||
assert result["response_time_ms"] is None
|
assert result["response_time_ms"] is None
|
||||||
|
|
||||||
|
|
||||||
|
# --- _ping platform args ---
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_ping_uses_unix_args_on_non_windows():
|
||||||
|
captured = {}
|
||||||
|
|
||||||
|
async def fake_exec(*args, **kwargs):
|
||||||
|
captured["args"] = args
|
||||||
|
proc = MagicMock()
|
||||||
|
proc.returncode = 0
|
||||||
|
proc.wait = AsyncMock()
|
||||||
|
return proc
|
||||||
|
|
||||||
|
with patch("app.services.status_checker.sys.platform", "linux"), \
|
||||||
|
patch("asyncio.create_subprocess_exec", side_effect=fake_exec):
|
||||||
|
await _ping("192.168.1.1")
|
||||||
|
|
||||||
|
assert "-c" in captured["args"]
|
||||||
|
assert "-W" in captured["args"]
|
||||||
|
assert "-n" not in captured["args"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_ping_uses_windows_args_on_win32():
|
||||||
|
captured = {}
|
||||||
|
|
||||||
|
async def fake_exec(*args, **kwargs):
|
||||||
|
captured["args"] = args
|
||||||
|
proc = MagicMock()
|
||||||
|
proc.returncode = 0
|
||||||
|
proc.wait = AsyncMock()
|
||||||
|
return proc
|
||||||
|
|
||||||
|
with patch("app.services.status_checker.sys.platform", "win32"), \
|
||||||
|
patch("asyncio.create_subprocess_exec", side_effect=fake_exec):
|
||||||
|
await _ping("192.168.1.1")
|
||||||
|
|
||||||
|
assert "-n" in captured["args"]
|
||||||
|
assert "-w" in captured["args"]
|
||||||
|
assert "-c" not in captured["args"]
|
||||||
|
|
||||||
|
|
||||||
# --- _tcp_connect ---
|
# --- _tcp_connect ---
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
|
|||||||
Generated
+790
-875
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "frontend",
|
"name": "frontend",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "1.8.0",
|
"version": "1.8.3",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
@@ -53,7 +53,7 @@
|
|||||||
"eslint-plugin-react-refresh": "^0.4.24",
|
"eslint-plugin-react-refresh": "^0.4.24",
|
||||||
"globals": "^16.5.0",
|
"globals": "^16.5.0",
|
||||||
"jsdom": "^28.1.0",
|
"jsdom": "^28.1.0",
|
||||||
"lucide-react": "^0.577.0",
|
"lucide-react": "^1.7.0",
|
||||||
"tailwindcss": "^4.2.1",
|
"tailwindcss": "^4.2.1",
|
||||||
"typescript": "~5.9.3",
|
"typescript": "~5.9.3",
|
||||||
"typescript-eslint": "^8.48.0",
|
"typescript-eslint": "^8.48.0",
|
||||||
|
|||||||
+34
-3
@@ -44,6 +44,8 @@ export default function App() {
|
|||||||
|
|
||||||
const [themeModalOpen, setThemeModalOpen] = useState(false)
|
const [themeModalOpen, setThemeModalOpen] = useState(false)
|
||||||
const [searchOpen, setSearchOpen] = useState(false)
|
const [searchOpen, setSearchOpen] = useState(false)
|
||||||
|
const [sidebarForceView, setSidebarForceView] = useState<'pending' | 'history' | undefined>(undefined)
|
||||||
|
const [highlightPendingId, setHighlightPendingId] = useState<string | undefined>(undefined)
|
||||||
const [shortcutsOpen, setShortcutsOpen] = useState(false)
|
const [shortcutsOpen, setShortcutsOpen] = useState(false)
|
||||||
const [addNodeOpen, setAddNodeOpen] = useState(false)
|
const [addNodeOpen, setAddNodeOpen] = useState(false)
|
||||||
const [addGroupRectOpen, setAddGroupRectOpen] = useState(false)
|
const [addGroupRectOpen, setAddGroupRectOpen] = useState(false)
|
||||||
@@ -370,6 +372,8 @@ export default function App() {
|
|||||||
onScan={() => setScanConfigOpen(true)}
|
onScan={() => setScanConfigOpen(true)}
|
||||||
onSave={handleSave}
|
onSave={handleSave}
|
||||||
onNodeApproved={setEditNodeId}
|
onNodeApproved={setEditNodeId}
|
||||||
|
forceView={sidebarForceView}
|
||||||
|
highlightPendingId={highlightPendingId}
|
||||||
/>
|
/>
|
||||||
<div className="flex flex-col flex-1 min-w-0">
|
<div className="flex flex-col flex-1 min-w-0">
|
||||||
<Toolbar
|
<Toolbar
|
||||||
@@ -386,7 +390,19 @@ export default function App() {
|
|||||||
/>
|
/>
|
||||||
<div className="flex flex-1 min-h-0">
|
<div className="flex flex-1 min-h-0">
|
||||||
<div ref={canvasRef} className="flex-1 min-w-0 h-full">
|
<div ref={canvasRef} className="flex-1 min-w-0 h-full">
|
||||||
<CanvasContainer onConnect={handleEdgeConnect} onEdgeDoubleClick={handleEdgeDoubleClick} onNodeDragStart={snapshotHistory} />
|
<CanvasContainer
|
||||||
|
onConnect={handleEdgeConnect}
|
||||||
|
onEdgeDoubleClick={handleEdgeDoubleClick}
|
||||||
|
onNodeDragStart={snapshotHistory}
|
||||||
|
onOpenPending={(deviceId) => {
|
||||||
|
setHighlightPendingId(undefined)
|
||||||
|
setSidebarForceView(undefined)
|
||||||
|
setTimeout(() => {
|
||||||
|
setHighlightPendingId(deviceId)
|
||||||
|
setSidebarForceView('pending')
|
||||||
|
}, 0)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
{(selectedNodeId || selectedNodeIds.length > 1) && <DetailPanel onEdit={handleEditNode} />}
|
{(selectedNodeId || selectedNodeIds.length > 1) && <DetailPanel onEdit={handleEditNode} />}
|
||||||
</div>
|
</div>
|
||||||
@@ -438,7 +454,11 @@ export default function App() {
|
|||||||
<ScanConfigModal
|
<ScanConfigModal
|
||||||
open={scanConfigOpen}
|
open={scanConfigOpen}
|
||||||
onClose={() => setScanConfigOpen(false)}
|
onClose={() => setScanConfigOpen(false)}
|
||||||
onScanNow={() => toast.success('Scan triggered')}
|
onScanNow={() => {
|
||||||
|
toast.success('Network scan started — check Scan History for results')
|
||||||
|
setSidebarForceView(undefined)
|
||||||
|
setTimeout(() => setSidebarForceView('history'), 0)
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -484,7 +504,18 @@ export default function App() {
|
|||||||
onClose={() => setThemeModalOpen(false)}
|
onClose={() => setThemeModalOpen(false)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<SearchModal open={searchOpen} onClose={() => setSearchOpen(false)} />
|
<SearchModal
|
||||||
|
open={searchOpen}
|
||||||
|
onClose={() => setSearchOpen(false)}
|
||||||
|
onOpenPending={(deviceId) => {
|
||||||
|
setHighlightPendingId(undefined)
|
||||||
|
setSidebarForceView(undefined)
|
||||||
|
setTimeout(() => {
|
||||||
|
setHighlightPendingId(deviceId)
|
||||||
|
setSidebarForceView('pending')
|
||||||
|
}, 0)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
<ShortcutsModal open={shortcutsOpen} onClose={() => setShortcutsOpen(false)} />
|
<ShortcutsModal open={shortcutsOpen} onClose={() => setShortcutsOpen(false)} />
|
||||||
|
|
||||||
<Toaster theme="dark" position="bottom-right" />
|
<Toaster theme="dark" position="bottom-right" />
|
||||||
|
|||||||
@@ -26,9 +26,10 @@ interface CanvasContainerProps {
|
|||||||
onConnect?: (connection: Connection) => void
|
onConnect?: (connection: Connection) => void
|
||||||
onEdgeDoubleClick?: (edge: Edge<EdgeData>) => void
|
onEdgeDoubleClick?: (edge: Edge<EdgeData>) => void
|
||||||
onNodeDragStart?: () => void
|
onNodeDragStart?: () => void
|
||||||
|
onOpenPending?: (deviceId: string) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
export function CanvasContainer({ onConnect: onConnectProp, onEdgeDoubleClick, onNodeDragStart }: CanvasContainerProps) {
|
export function CanvasContainer({ onConnect: onConnectProp, onEdgeDoubleClick, onNodeDragStart, onOpenPending }: CanvasContainerProps) {
|
||||||
const [lassoMode, setLassoMode] = useState(true)
|
const [lassoMode, setLassoMode] = useState(true)
|
||||||
const {
|
const {
|
||||||
nodes, edges,
|
nodes, edges,
|
||||||
@@ -89,7 +90,7 @@ export function CanvasContainer({ onConnect: onConnectProp, onEdgeDoubleClick, o
|
|||||||
selectionMode={SelectionMode.Partial}
|
selectionMode={SelectionMode.Partial}
|
||||||
multiSelectionKeyCode={['Meta', 'Control']}
|
multiSelectionKeyCode={['Meta', 'Control']}
|
||||||
snapToGrid
|
snapToGrid
|
||||||
snapGrid={[16, 16]}
|
snapGrid={[8, 8]}
|
||||||
colorMode={theme.colors.reactFlowColorMode}
|
colorMode={theme.colors.reactFlowColorMode}
|
||||||
elevateNodesOnSelect={false}
|
elevateNodesOnSelect={false}
|
||||||
connectionMode={ConnectionMode.Loose}
|
connectionMode={ConnectionMode.Loose}
|
||||||
@@ -97,11 +98,11 @@ export function CanvasContainer({ onConnect: onConnectProp, onEdgeDoubleClick, o
|
|||||||
>
|
>
|
||||||
<Background
|
<Background
|
||||||
variant={BackgroundVariant.Dots}
|
variant={BackgroundVariant.Dots}
|
||||||
gap={24}
|
gap={16}
|
||||||
size={1}
|
size={1}
|
||||||
color={theme.colors.canvasDotColor}
|
color={theme.colors.canvasDotColor}
|
||||||
/>
|
/>
|
||||||
<SearchBar />
|
<SearchBar onOpenPending={onOpenPending} />
|
||||||
<Controls>
|
<Controls>
|
||||||
<ControlButton
|
<ControlButton
|
||||||
onClick={() => setLassoMode((m) => !m)}
|
onClick={() => setLassoMode((m) => !m)}
|
||||||
|
|||||||
@@ -2,15 +2,27 @@ import { useState, useEffect, useRef } from 'react'
|
|||||||
import { useReactFlow } from '@xyflow/react'
|
import { useReactFlow } from '@xyflow/react'
|
||||||
import { Search, X } from 'lucide-react'
|
import { Search, X } from 'lucide-react'
|
||||||
import { useCanvasStore } from '@/stores/canvasStore'
|
import { useCanvasStore } from '@/stores/canvasStore'
|
||||||
|
import { scanApi } from '@/api/client'
|
||||||
import { NODE_TYPE_LABELS } from '@/types'
|
import { NODE_TYPE_LABELS } from '@/types'
|
||||||
|
import type { PendingDevice } from '@/components/modals/PendingDeviceModal'
|
||||||
|
|
||||||
export function SearchBar() {
|
interface SearchBarProps {
|
||||||
|
onOpenPending?: (deviceId: string) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SearchBar({ onOpenPending }: SearchBarProps) {
|
||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false)
|
||||||
const [query, setQuery] = useState('')
|
const [query, setQuery] = useState('')
|
||||||
|
const [pendingDevices, setPendingDevices] = useState<PendingDevice[]>([])
|
||||||
const inputRef = useRef<HTMLInputElement>(null)
|
const inputRef = useRef<HTMLInputElement>(null)
|
||||||
const { nodes, setSelectedNode } = useCanvasStore()
|
const { nodes, setSelectedNode } = useCanvasStore()
|
||||||
const { setCenter } = useReactFlow()
|
const { setCenter } = useReactFlow()
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return
|
||||||
|
scanApi.pending().then((res) => setPendingDevices(res.data)).catch(() => {})
|
||||||
|
}, [open])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handler = (e: KeyboardEvent) => {
|
const handler = (e: KeyboardEvent) => {
|
||||||
if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
|
if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
|
||||||
@@ -31,7 +43,7 @@ export function SearchBar() {
|
|||||||
}, [open])
|
}, [open])
|
||||||
|
|
||||||
const q = query.toLowerCase().trim()
|
const q = query.toLowerCase().trim()
|
||||||
const results = q
|
const nodeResults = q
|
||||||
? nodes.filter((n) => {
|
? nodes.filter((n) => {
|
||||||
if (n.data.type === 'groupRect') return false
|
if (n.data.type === 'groupRect') return false
|
||||||
return (
|
return (
|
||||||
@@ -43,6 +55,19 @@ export function SearchBar() {
|
|||||||
})
|
})
|
||||||
: []
|
: []
|
||||||
|
|
||||||
|
const pendingResults = q
|
||||||
|
? pendingDevices.filter((d) =>
|
||||||
|
d.ip.toLowerCase().includes(q) ||
|
||||||
|
d.hostname?.toLowerCase().includes(q) ||
|
||||||
|
d.services.some((s) =>
|
||||||
|
s.service_name?.toLowerCase().includes(q) ||
|
||||||
|
s.category?.toLowerCase().includes(q)
|
||||||
|
)
|
||||||
|
).slice(0, 4)
|
||||||
|
: []
|
||||||
|
|
||||||
|
const totalResults = nodeResults.length + pendingResults.length
|
||||||
|
|
||||||
const goToNode = (id: string) => {
|
const goToNode = (id: string) => {
|
||||||
const node = nodes.find((n) => n.id === id)
|
const node = nodes.find((n) => n.id === id)
|
||||||
if (!node) return
|
if (!node) return
|
||||||
@@ -101,7 +126,7 @@ export function SearchBar() {
|
|||||||
/>
|
/>
|
||||||
{query && (
|
{query && (
|
||||||
<span style={{ fontSize: 11, color: '#6e7681', flexShrink: 0 }}>
|
<span style={{ fontSize: 11, color: '#6e7681', flexShrink: 0 }}>
|
||||||
{results.length} result{results.length !== 1 ? 's' : ''}
|
{totalResults} result{totalResults !== 1 ? 's' : ''}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
<button
|
<button
|
||||||
@@ -113,9 +138,9 @@ export function SearchBar() {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{results.length > 0 && (
|
{totalResults > 0 && (
|
||||||
<div style={{ borderTop: '1px solid #30363d', maxHeight: 260, overflowY: 'auto' }}>
|
<div style={{ borderTop: '1px solid #30363d', maxHeight: 260, overflowY: 'auto' }}>
|
||||||
{results.map((n) => (
|
{nodeResults.map((n) => (
|
||||||
<button
|
<button
|
||||||
key={n.id}
|
key={n.id}
|
||||||
onClick={() => goToNode(n.id)}
|
onClick={() => goToNode(n.id)}
|
||||||
@@ -146,10 +171,43 @@ export function SearchBar() {
|
|||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
|
{pendingResults.length > 0 && nodeResults.length > 0 && (
|
||||||
|
<div style={{ height: 1, background: '#30363d', margin: '2px 0' }} />
|
||||||
|
)}
|
||||||
|
{pendingResults.map((d) => {
|
||||||
|
const serviceName = d.services.find((s) => s.service_name)?.service_name
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={d.id}
|
||||||
|
onClick={() => { onOpenPending?.(d.id); setOpen(false); setQuery('') }}
|
||||||
|
style={{
|
||||||
|
width: '100%',
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
gap: 10,
|
||||||
|
padding: '7px 12px',
|
||||||
|
background: 'none',
|
||||||
|
border: 'none',
|
||||||
|
cursor: 'pointer',
|
||||||
|
textAlign: 'left',
|
||||||
|
}}
|
||||||
|
onMouseEnter={(e) => (e.currentTarget.style.background = '#21262d')}
|
||||||
|
onMouseLeave={(e) => (e.currentTarget.style.background = 'none')}
|
||||||
|
>
|
||||||
|
<span style={{ fontSize: 10, color: '#e3b341', fontFamily: 'JetBrains Mono, monospace', flexShrink: 0 }}>pending</span>
|
||||||
|
<span style={{ fontSize: 12, fontWeight: 600, color: '#e6edf3', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||||
|
{d.hostname ?? d.ip}
|
||||||
|
</span>
|
||||||
|
<span style={{ fontSize: 11, color: '#8b949e', fontFamily: 'JetBrains Mono, monospace', flexShrink: 0 }}>
|
||||||
|
{serviceName ?? d.ip}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{q && results.length === 0 && (
|
{q && totalResults === 0 && (
|
||||||
<div style={{ borderTop: '1px solid #30363d', padding: '10px 12px', fontSize: 12, color: '#6e7681', textAlign: 'center' }}>
|
<div style={{ borderTop: '1px solid #30363d', padding: '10px 12px', fontSize: 12, color: '#6e7681', textAlign: 'center' }}>
|
||||||
No results for “{query}”
|
No results for “{query}”
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -142,9 +142,9 @@ describe('CanvasContainer', () => {
|
|||||||
expect(rfProps.snapToGrid).toBe(true)
|
expect(rfProps.snapToGrid).toBe(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('sets snapGrid to [16, 16]', () => {
|
it('sets snapGrid to [8, 8]', () => {
|
||||||
render(<CanvasContainer />)
|
render(<CanvasContainer />)
|
||||||
expect(rfProps.snapGrid).toEqual([16, 16])
|
expect(rfProps.snapGrid).toEqual([8, 8])
|
||||||
})
|
})
|
||||||
|
|
||||||
// ── Delete key ────────────────────────────────────────────────────────────
|
// ── Delete key ────────────────────────────────────────────────────────────
|
||||||
|
|||||||
@@ -39,11 +39,13 @@ export function BaseNode({ id, data, selected, icon: typeIcon, width, height }:
|
|||||||
style={{
|
style={{
|
||||||
background: colors.background,
|
background: colors.background,
|
||||||
borderColor: colors.border,
|
borderColor: colors.border,
|
||||||
borderWidth: selected ? 2 : 1,
|
borderWidth: 1,
|
||||||
boxShadow: isOnline
|
boxShadow: isOnline && selected
|
||||||
|
? `0 0 0 1px ${colors.border}, 0 0 10px ${colors.border}2e, 0 0 3px ${colors.border}1a`
|
||||||
|
: isOnline
|
||||||
? `0 0 10px ${colors.border}2e, 0 0 3px ${colors.border}1a`
|
? `0 0 10px ${colors.border}2e, 0 0 3px ${colors.border}1a`
|
||||||
: selected
|
: selected
|
||||||
? `0 0 8px ${colors.border}44`
|
? `0 0 0 1px ${colors.border}, 0 0 8px ${colors.border}44`
|
||||||
: 'none',
|
: 'none',
|
||||||
opacity: data.status === 'offline' ? 0.55 : 1,
|
opacity: data.status === 'offline' ? 0.55 : 1,
|
||||||
minWidth: 140,
|
minWidth: 140,
|
||||||
@@ -55,7 +57,7 @@ export function BaseNode({ id, data, selected, icon: typeIcon, width, height }:
|
|||||||
isVisible={selected}
|
isVisible={selected}
|
||||||
minWidth={140}
|
minWidth={140}
|
||||||
minHeight={50}
|
minHeight={50}
|
||||||
lineStyle={{ borderColor: colors.border, borderWidth: 1 }}
|
lineStyle={{ borderColor: 'transparent' }}
|
||||||
handleStyle={{ borderColor: colors.border, background: colors.border, width: 8, height: 8 }}
|
handleStyle={{ borderColor: colors.border, background: colors.border, width: 8, height: 8 }}
|
||||||
/>
|
/>
|
||||||
<Handle
|
<Handle
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ export function GroupRectNode({ id, data, selected }: NodeProps<Node<NodeData>>)
|
|||||||
background: '#00d4ff',
|
background: '#00d4ff',
|
||||||
border: '1px solid #0d1117',
|
border: '1px solid #0d1117',
|
||||||
}}
|
}}
|
||||||
lineStyle={{ borderColor: '#00d4ff55', borderWidth: 1 }}
|
lineStyle={{ borderColor: 'transparent' }}
|
||||||
/>
|
/>
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
@@ -86,7 +86,8 @@ export function GroupRectNode({ id, data, selected }: NodeProps<Node<NodeData>>)
|
|||||||
justifyContent: posStyle.justifyContent,
|
justifyContent: posStyle.justifyContent,
|
||||||
padding: 12,
|
padding: 12,
|
||||||
background: backgroundColor,
|
background: backgroundColor,
|
||||||
border: `${selected ? borderWidth + 1 : borderWidth}px ${selected ? 'solid' : borderStyle} ${selected ? '#00d4ff' : borderColor}`,
|
border: `${borderWidth}px ${borderStyle} ${borderColor}`,
|
||||||
|
boxShadow: selected ? '0 0 0 1px #00d4ff, 0 0 8px #00d4ff44' : 'none',
|
||||||
borderRadius: 10,
|
borderRadius: 10,
|
||||||
boxSizing: 'border-box',
|
boxSizing: 'border-box',
|
||||||
cursor: 'default',
|
cursor: 'default',
|
||||||
|
|||||||
@@ -78,7 +78,7 @@ export function PendingDeviceModal({ device, onClose, onApprove, onHide, onIgnor
|
|||||||
|
|
||||||
const TypeIcon = TYPE_ICONS[device.suggested_type ?? 'generic'] ?? Circle
|
const TypeIcon = TYPE_ICONS[device.suggested_type ?? 'generic'] ?? Circle
|
||||||
|
|
||||||
const handleApprove = () => { onApprove(device); onClose() }
|
const handleApprove = () => { onApprove(device) }
|
||||||
const handleHide = () => { onHide(device); onClose() }
|
const handleHide = () => { onHide(device); onClose() }
|
||||||
const handleIgnore = () => { onIgnore(device); onClose() }
|
const handleIgnore = () => { onIgnore(device); onClose() }
|
||||||
|
|
||||||
@@ -105,7 +105,7 @@ export function PendingDeviceModal({ device, onClose, onApprove, onHide, onIgnor
|
|||||||
{device.discovery_source && (
|
{device.discovery_source && (
|
||||||
<InfoRow label="Source" value={device.discovery_source.toUpperCase()} />
|
<InfoRow label="Source" value={device.discovery_source.toUpperCase()} />
|
||||||
)}
|
)}
|
||||||
<InfoRow label="Discovered" value={new Date(device.discovered_at).toLocaleString()} />
|
<InfoRow label="Discovered" value={new Date(device.discovered_at.endsWith('Z') ? device.discovered_at : device.discovered_at + 'Z').toLocaleString()} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Services */}
|
{/* Services */}
|
||||||
|
|||||||
@@ -24,29 +24,22 @@ export function ScanConfigModal({ open, onClose, onScanNow }: ScanConfigModalPro
|
|||||||
.catch(() => {/* use defaults */})
|
.catch(() => {/* use defaults */})
|
||||||
}, [open])
|
}, [open])
|
||||||
|
|
||||||
const handleSave = async () => {
|
const handleScanNow = async () => {
|
||||||
const cleaned = ranges.map((r) => r.trim()).filter(Boolean)
|
const cleaned = ranges.map((r) => r.trim()).filter(Boolean)
|
||||||
if (cleaned.length === 0) { toast.error('Add at least one IP range'); return }
|
if (cleaned.length === 0) { toast.error('Add at least one IP range'); return }
|
||||||
setSaving(true)
|
setSaving(true)
|
||||||
try {
|
try {
|
||||||
await scanApi.saveConfig({ ranges: cleaned })
|
await scanApi.saveConfig({ ranges: cleaned })
|
||||||
toast.success('Scan config saved')
|
await scanApi.trigger()
|
||||||
|
onScanNow()
|
||||||
onClose()
|
onClose()
|
||||||
} catch {
|
} catch {
|
||||||
toast.error('Failed to save config')
|
toast.error('Failed to start scan')
|
||||||
} finally {
|
} finally {
|
||||||
setSaving(false)
|
setSaving(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleScanNow = async () => {
|
|
||||||
const cleaned = ranges.map((r) => r.trim()).filter(Boolean)
|
|
||||||
if (cleaned.length === 0) { toast.error('Add at least one IP range'); return }
|
|
||||||
await handleSave()
|
|
||||||
onScanNow()
|
|
||||||
onClose()
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
|
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
|
||||||
<DialogContent className="bg-[#161b22] border-border max-w-md">
|
<DialogContent className="bg-[#161b22] border-border max-w-md">
|
||||||
|
|||||||
@@ -1,34 +1,61 @@
|
|||||||
import { useState, useCallback } from 'react'
|
import { useState, useCallback, useEffect } from 'react'
|
||||||
import { useReactFlow } from '@xyflow/react'
|
import { useReactFlow } from '@xyflow/react'
|
||||||
import { Search } from 'lucide-react'
|
import { Search } from 'lucide-react'
|
||||||
import { useCanvasStore } from '@/stores/canvasStore'
|
import { useCanvasStore } from '@/stores/canvasStore'
|
||||||
|
import { scanApi } from '@/api/client'
|
||||||
|
import type { PendingDevice } from '@/components/modals/PendingDeviceModal'
|
||||||
|
|
||||||
interface SearchModalProps {
|
interface SearchModalProps {
|
||||||
open: boolean
|
open: boolean
|
||||||
onClose: () => void
|
onClose: () => void
|
||||||
|
onOpenPending: (deviceId: string) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
export function SearchModal({ open, onClose }: SearchModalProps) {
|
export function SearchModal({ open, onClose, onOpenPending }: SearchModalProps) {
|
||||||
const [query, setQuery] = useState('')
|
const [query, setQuery] = useState('')
|
||||||
|
const [pendingDevices, setPendingDevices] = useState<PendingDevice[]>([])
|
||||||
const nodes = useCanvasStore((s) => s.nodes)
|
const nodes = useCanvasStore((s) => s.nodes)
|
||||||
const setSelectedNode = useCanvasStore((s) => s.setSelectedNode)
|
const setSelectedNode = useCanvasStore((s) => s.setSelectedNode)
|
||||||
const { fitView } = useReactFlow()
|
const { fitView } = useReactFlow()
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return
|
||||||
|
scanApi.pending().then((res) => setPendingDevices(res.data)).catch(() => {})
|
||||||
|
}, [open])
|
||||||
|
|
||||||
const searchable = nodes.filter((n) => n.data.type !== 'groupRect')
|
const searchable = nodes.filter((n) => n.data.type !== 'groupRect')
|
||||||
const q = query.toLowerCase()
|
const q = query.toLowerCase()
|
||||||
const results = q.length === 0 ? [] : searchable.filter((n) =>
|
|
||||||
|
const nodeResults = q.length === 0 ? [] : searchable.filter((n) =>
|
||||||
n.data.label?.toLowerCase().includes(q) ||
|
n.data.label?.toLowerCase().includes(q) ||
|
||||||
n.data.ip?.toLowerCase().includes(q) ||
|
n.data.ip?.toLowerCase().includes(q) ||
|
||||||
n.data.hostname?.toLowerCase().includes(q)
|
n.data.hostname?.toLowerCase().includes(q)
|
||||||
).slice(0, 8)
|
).slice(0, 6)
|
||||||
|
|
||||||
const handleSelect = useCallback((nodeId: string) => {
|
const pendingResults = q.length === 0 ? [] : pendingDevices.filter((d) =>
|
||||||
|
d.ip.toLowerCase().includes(q) ||
|
||||||
|
d.hostname?.toLowerCase().includes(q) ||
|
||||||
|
d.services.some((s) =>
|
||||||
|
s.service_name?.toLowerCase().includes(q) ||
|
||||||
|
s.category?.toLowerCase().includes(q)
|
||||||
|
)
|
||||||
|
).slice(0, 4)
|
||||||
|
|
||||||
|
const totalResults = nodeResults.length + pendingResults.length
|
||||||
|
|
||||||
|
const handleSelectNode = useCallback((nodeId: string) => {
|
||||||
setSelectedNode(nodeId)
|
setSelectedNode(nodeId)
|
||||||
fitView({ nodes: [{ id: nodeId }], duration: 600, padding: 0.4, maxZoom: 1.5 })
|
fitView({ nodes: [{ id: nodeId }], duration: 600, padding: 0.4, maxZoom: 1.5 })
|
||||||
onClose()
|
onClose()
|
||||||
setQuery('')
|
setQuery('')
|
||||||
}, [fitView, setSelectedNode, onClose])
|
}, [fitView, setSelectedNode, onClose])
|
||||||
|
|
||||||
|
const handleSelectPending = useCallback((deviceId: string) => {
|
||||||
|
onOpenPending(deviceId)
|
||||||
|
onClose()
|
||||||
|
setQuery('')
|
||||||
|
}, [onOpenPending, onClose])
|
||||||
|
|
||||||
if (!open) return null
|
if (!open) return null
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -43,23 +70,24 @@ export function SearchModal({ open, onClose }: SearchModalProps) {
|
|||||||
autoFocus
|
autoFocus
|
||||||
value={query}
|
value={query}
|
||||||
onChange={(e) => setQuery(e.target.value)}
|
onChange={(e) => setQuery(e.target.value)}
|
||||||
placeholder="Search nodes by label, IP, hostname…"
|
placeholder="Search nodes, pending devices by IP or service…"
|
||||||
className="flex-1 bg-transparent text-sm text-foreground placeholder:text-muted-foreground outline-none"
|
className="flex-1 bg-transparent text-sm text-foreground placeholder:text-muted-foreground outline-none"
|
||||||
onKeyDown={(e) => {
|
onKeyDown={(e) => {
|
||||||
if (e.key === 'Escape') { onClose(); setQuery('') }
|
if (e.key === 'Escape') { onClose(); setQuery('') }
|
||||||
if (e.key === 'Enter' && results.length > 0) handleSelect(results[0].id)
|
if (e.key === 'Enter' && nodeResults.length > 0) handleSelectNode(nodeResults[0].id)
|
||||||
|
if (e.key === 'Enter' && nodeResults.length === 0 && pendingResults.length > 0) handleSelectPending(pendingResults[0].id)
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<kbd className="text-[10px] text-muted-foreground border border-border rounded px-1">ESC</kbd>
|
<kbd className="text-[10px] text-muted-foreground border border-border rounded px-1">ESC</kbd>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{results.length > 0 && (
|
{totalResults > 0 && (
|
||||||
<ul className="py-1 max-h-64 overflow-y-auto">
|
<ul className="py-1 max-h-72 overflow-y-auto">
|
||||||
{results.map((node) => (
|
{nodeResults.map((node) => (
|
||||||
<li
|
<li
|
||||||
key={node.id}
|
key={node.id}
|
||||||
className="flex items-center gap-3 px-4 py-2 hover:bg-[#21262d] cursor-pointer"
|
className="flex items-center gap-3 px-4 py-2 hover:bg-[#21262d] cursor-pointer"
|
||||||
onClick={() => handleSelect(node.id)}
|
onClick={() => handleSelectNode(node.id)}
|
||||||
>
|
>
|
||||||
<span className="text-xs font-mono text-[#00d4ff] w-16 shrink-0">{node.data.type}</span>
|
<span className="text-xs font-mono text-[#00d4ff] w-16 shrink-0">{node.data.type}</span>
|
||||||
<span className="text-sm text-foreground font-medium flex-1 truncate">{node.data.label}</span>
|
<span className="text-sm text-foreground font-medium flex-1 truncate">{node.data.label}</span>
|
||||||
@@ -68,15 +96,34 @@ export function SearchModal({ open, onClose }: SearchModalProps) {
|
|||||||
)}
|
)}
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
|
{pendingResults.length > 0 && nodeResults.length > 0 && (
|
||||||
|
<li className="px-4 py-1">
|
||||||
|
<div className="h-px bg-border" />
|
||||||
|
</li>
|
||||||
|
)}
|
||||||
|
{pendingResults.map((device) => {
|
||||||
|
const serviceName = device.services.find((s) => s.service_name)?.service_name
|
||||||
|
return (
|
||||||
|
<li
|
||||||
|
key={device.id}
|
||||||
|
className="flex items-center gap-3 px-4 py-2 hover:bg-[#21262d] cursor-pointer"
|
||||||
|
onClick={() => handleSelectPending(device.id)}
|
||||||
|
>
|
||||||
|
<span className="text-xs font-mono text-[#e3b341] w-16 shrink-0">pending</span>
|
||||||
|
<span className="text-sm text-foreground font-medium flex-1 truncate font-mono">{device.hostname ?? device.ip}</span>
|
||||||
|
<span className="text-xs font-mono text-muted-foreground shrink-0">{serviceName ?? device.ip}</span>
|
||||||
|
</li>
|
||||||
|
)
|
||||||
|
})}
|
||||||
</ul>
|
</ul>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{q.length > 0 && results.length === 0 && (
|
{q.length > 0 && totalResults === 0 && (
|
||||||
<p className="px-4 py-3 text-sm text-muted-foreground">No nodes match "{query}"</p>
|
<p className="px-4 py-3 text-sm text-muted-foreground">No results match "{query}"</p>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{q.length === 0 && (
|
{q.length === 0 && (
|
||||||
<p className="px-4 py-3 text-xs text-muted-foreground">Type to search nodes…</p>
|
<p className="px-4 py-3 text-xs text-muted-foreground">Type to search nodes and pending devices…</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -126,7 +126,7 @@ describe('PendingDeviceModal', () => {
|
|||||||
|
|
||||||
// ── Actions ───────────────────────────────────────────────────────────────
|
// ── Actions ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
it('calls onApprove with the device and onClose when Approve is clicked', () => {
|
it('calls onApprove with the device when Approve is clicked (parent controls close on success)', () => {
|
||||||
const device = makeDevice()
|
const device = makeDevice()
|
||||||
const onApprove = vi.fn()
|
const onApprove = vi.fn()
|
||||||
const onClose = vi.fn()
|
const onClose = vi.fn()
|
||||||
@@ -135,7 +135,7 @@ describe('PendingDeviceModal', () => {
|
|||||||
)
|
)
|
||||||
fireEvent.click(screen.getByRole('button', { name: 'Approve' }))
|
fireEvent.click(screen.getByRole('button', { name: 'Approve' }))
|
||||||
expect(onApprove).toHaveBeenCalledWith(device)
|
expect(onApprove).toHaveBeenCalledWith(device)
|
||||||
expect(onClose).toHaveBeenCalledOnce()
|
expect(onClose).not.toHaveBeenCalled()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('calls onHide with the device and onClose when Hide is clicked', () => {
|
it('calls onHide with the device and onClose when Hide is clicked', () => {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ vi.mock('@/api/client', () => ({
|
|||||||
scanApi: {
|
scanApi: {
|
||||||
getConfig: vi.fn(),
|
getConfig: vi.fn(),
|
||||||
saveConfig: vi.fn(),
|
saveConfig: vi.fn(),
|
||||||
|
trigger: vi.fn(),
|
||||||
},
|
},
|
||||||
}))
|
}))
|
||||||
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn() } }))
|
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn() } }))
|
||||||
@@ -20,6 +21,8 @@ describe('ScanConfigModal', () => {
|
|||||||
vi.mocked(scanApi.getConfig).mockResolvedValue(defaultConfig as never)
|
vi.mocked(scanApi.getConfig).mockResolvedValue(defaultConfig as never)
|
||||||
vi.mocked(scanApi.saveConfig).mockReset()
|
vi.mocked(scanApi.saveConfig).mockReset()
|
||||||
vi.mocked(scanApi.saveConfig).mockResolvedValue({} as never)
|
vi.mocked(scanApi.saveConfig).mockResolvedValue({} as never)
|
||||||
|
vi.mocked(scanApi.trigger).mockReset()
|
||||||
|
vi.mocked(scanApi.trigger).mockResolvedValue({} as never)
|
||||||
vi.mocked(toast.success).mockReset()
|
vi.mocked(toast.success).mockReset()
|
||||||
vi.mocked(toast.error).mockReset()
|
vi.mocked(toast.error).mockReset()
|
||||||
})
|
})
|
||||||
@@ -72,7 +75,7 @@ describe('ScanConfigModal', () => {
|
|||||||
expect(scanApi.saveConfig).not.toHaveBeenCalled()
|
expect(scanApi.saveConfig).not.toHaveBeenCalled()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('calls onScanNow after saving on "Scan Now" click', async () => {
|
it('saves config, triggers scan, calls onScanNow and closes on "Scan Now" click', async () => {
|
||||||
const onScanNow = vi.fn()
|
const onScanNow = vi.fn()
|
||||||
const onClose = vi.fn()
|
const onClose = vi.fn()
|
||||||
render(<ScanConfigModal open onClose={onClose} onScanNow={onScanNow} />)
|
render(<ScanConfigModal open onClose={onClose} onScanNow={onScanNow} />)
|
||||||
@@ -80,7 +83,9 @@ describe('ScanConfigModal', () => {
|
|||||||
fireEvent.click(screen.getByRole('button', { name: 'Scan Now' }))
|
fireEvent.click(screen.getByRole('button', { name: 'Scan Now' }))
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
expect(scanApi.saveConfig).toHaveBeenCalledWith({ ranges: ['192.168.1.0/24'] })
|
expect(scanApi.saveConfig).toHaveBeenCalledWith({ ranges: ['192.168.1.0/24'] })
|
||||||
|
expect(scanApi.trigger).toHaveBeenCalledOnce()
|
||||||
expect(onScanNow).toHaveBeenCalledOnce()
|
expect(onScanNow).toHaveBeenCalledOnce()
|
||||||
|
expect(onClose).toHaveBeenCalledOnce()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,12 @@ vi.mock('@xyflow/react', () => ({
|
|||||||
useReactFlow: () => ({ fitView: mockFitView }),
|
useReactFlow: () => ({ fitView: mockFitView }),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
vi.mock('@/api/client', () => ({
|
||||||
|
scanApi: { pending: vi.fn().mockResolvedValue({ data: [] }) },
|
||||||
|
}))
|
||||||
|
|
||||||
|
const mockOnOpenPending = vi.fn()
|
||||||
|
|
||||||
function makeNode(id: string, overrides: Partial<NodeData> = {}): Node<NodeData> {
|
function makeNode(id: string, overrides: Partial<NodeData> = {}): Node<NodeData> {
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
@@ -32,32 +38,32 @@ describe('SearchModal', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('renders nothing when closed', () => {
|
it('renders nothing when closed', () => {
|
||||||
render(<SearchModal open={false} onClose={vi.fn()} />)
|
render(<SearchModal open={false} onClose={vi.fn()} onOpenPending={mockOnOpenPending} />)
|
||||||
expect(screen.queryByPlaceholderText(/search nodes/i)).toBeNull()
|
expect(screen.queryByPlaceholderText(/search nodes/i)).toBeNull()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('renders search input when open', () => {
|
it('renders search input when open', () => {
|
||||||
render(<SearchModal open onClose={vi.fn()} />)
|
render(<SearchModal open onClose={vi.fn()} onOpenPending={mockOnOpenPending} />)
|
||||||
expect(screen.getByPlaceholderText(/search nodes/i)).toBeDefined()
|
expect(screen.getByPlaceholderText(/search nodes/i)).toBeDefined()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('shows "Type to search" hint when query is empty', () => {
|
it('shows "Type to search" hint when query is empty', () => {
|
||||||
render(<SearchModal open onClose={vi.fn()} />)
|
render(<SearchModal open onClose={vi.fn()} onOpenPending={mockOnOpenPending} />)
|
||||||
expect(screen.getByText(/type to search/i)).toBeDefined()
|
expect(screen.getByText(/type to search/i)).toBeDefined()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('shows no results message when query has no matches', () => {
|
it('shows no results message when query has no matches', () => {
|
||||||
useCanvasStore.setState({ nodes: [makeNode('router', { label: 'Router' })] })
|
useCanvasStore.setState({ nodes: [makeNode('router', { label: 'Router' })] })
|
||||||
render(<SearchModal open onClose={vi.fn()} />)
|
render(<SearchModal open onClose={vi.fn()} onOpenPending={mockOnOpenPending} />)
|
||||||
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: 'zzz' } })
|
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: 'zzz' } })
|
||||||
expect(screen.getByText(/no nodes match/i)).toBeDefined()
|
expect(screen.getByText(/no results match/i)).toBeDefined()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('filters nodes by label', () => {
|
it('filters nodes by label', () => {
|
||||||
useCanvasStore.setState({
|
useCanvasStore.setState({
|
||||||
nodes: [makeNode('n1', { label: 'My Router' }), makeNode('n2', { label: 'NAS Server' })],
|
nodes: [makeNode('n1', { label: 'My Router' }), makeNode('n2', { label: 'NAS Server' })],
|
||||||
})
|
})
|
||||||
render(<SearchModal open onClose={vi.fn()} />)
|
render(<SearchModal open onClose={vi.fn()} onOpenPending={mockOnOpenPending} />)
|
||||||
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: 'router' } })
|
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: 'router' } })
|
||||||
expect(screen.getByText('My Router')).toBeDefined()
|
expect(screen.getByText('My Router')).toBeDefined()
|
||||||
expect(screen.queryByText('NAS Server')).toBeNull()
|
expect(screen.queryByText('NAS Server')).toBeNull()
|
||||||
@@ -70,7 +76,7 @@ describe('SearchModal', () => {
|
|||||||
makeNode('n2', { label: 'Box B', ip: '10.0.0.1' }),
|
makeNode('n2', { label: 'Box B', ip: '10.0.0.1' }),
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
render(<SearchModal open onClose={vi.fn()} />)
|
render(<SearchModal open onClose={vi.fn()} onOpenPending={mockOnOpenPending} />)
|
||||||
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: '192.168' } })
|
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: '192.168' } })
|
||||||
expect(screen.getByText('Box A')).toBeDefined()
|
expect(screen.getByText('Box A')).toBeDefined()
|
||||||
expect(screen.queryByText('Box B')).toBeNull()
|
expect(screen.queryByText('Box B')).toBeNull()
|
||||||
@@ -83,7 +89,7 @@ describe('SearchModal', () => {
|
|||||||
makeNode('n2', { label: 'B', hostname: 'nas.local' }),
|
makeNode('n2', { label: 'B', hostname: 'nas.local' }),
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
render(<SearchModal open onClose={vi.fn()} />)
|
render(<SearchModal open onClose={vi.fn()} onOpenPending={mockOnOpenPending} />)
|
||||||
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: 'pve' } })
|
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: 'pve' } })
|
||||||
expect(screen.getByText('A')).toBeDefined()
|
expect(screen.getByText('A')).toBeDefined()
|
||||||
expect(screen.queryByText('B')).toBeNull()
|
expect(screen.queryByText('B')).toBeNull()
|
||||||
@@ -96,25 +102,25 @@ describe('SearchModal', () => {
|
|||||||
makeNode('g1', { label: 'Zone A', type: 'groupRect' }),
|
makeNode('g1', { label: 'Zone A', type: 'groupRect' }),
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
render(<SearchModal open onClose={vi.fn()} />)
|
render(<SearchModal open onClose={vi.fn()} onOpenPending={mockOnOpenPending} />)
|
||||||
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: 'zone' } })
|
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: 'zone' } })
|
||||||
expect(screen.getByText(/no nodes match/i)).toBeDefined()
|
expect(screen.getByText(/no results match/i)).toBeDefined()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('limits results to 8 nodes', () => {
|
it('limits node results to 6', () => {
|
||||||
useCanvasStore.setState({
|
useCanvasStore.setState({
|
||||||
nodes: Array.from({ length: 12 }, (_, i) => makeNode(`n${i}`, { label: `Server ${i}` })),
|
nodes: Array.from({ length: 12 }, (_, i) => makeNode(`n${i}`, { label: `Server ${i}` })),
|
||||||
})
|
})
|
||||||
render(<SearchModal open onClose={vi.fn()} />)
|
render(<SearchModal open onClose={vi.fn()} onOpenPending={mockOnOpenPending} />)
|
||||||
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: 'server' } })
|
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: 'server' } })
|
||||||
const items = screen.getAllByText(/Server \d/)
|
const items = screen.getAllByText(/Server \d/)
|
||||||
expect(items).toHaveLength(8)
|
expect(items).toHaveLength(6)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('selects node and closes on result click', () => {
|
it('selects node and closes on result click', () => {
|
||||||
const onClose = vi.fn()
|
const onClose = vi.fn()
|
||||||
useCanvasStore.setState({ nodes: [makeNode('n1', { label: 'Proxmox' })] })
|
useCanvasStore.setState({ nodes: [makeNode('n1', { label: 'Proxmox' })] })
|
||||||
render(<SearchModal open onClose={onClose} />)
|
render(<SearchModal open onClose={onClose} onOpenPending={mockOnOpenPending} />)
|
||||||
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: 'prox' } })
|
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: 'prox' } })
|
||||||
fireEvent.click(screen.getByText('Proxmox'))
|
fireEvent.click(screen.getByText('Proxmox'))
|
||||||
expect(useCanvasStore.getState().selectedNodeId).toBe('n1')
|
expect(useCanvasStore.getState().selectedNodeId).toBe('n1')
|
||||||
@@ -125,7 +131,7 @@ describe('SearchModal', () => {
|
|||||||
it('selects first result and closes on Enter key', () => {
|
it('selects first result and closes on Enter key', () => {
|
||||||
const onClose = vi.fn()
|
const onClose = vi.fn()
|
||||||
useCanvasStore.setState({ nodes: [makeNode('n1', { label: 'Switch' })] })
|
useCanvasStore.setState({ nodes: [makeNode('n1', { label: 'Switch' })] })
|
||||||
render(<SearchModal open onClose={onClose} />)
|
render(<SearchModal open onClose={onClose} onOpenPending={mockOnOpenPending} />)
|
||||||
const input = screen.getByPlaceholderText(/search nodes/i)
|
const input = screen.getByPlaceholderText(/search nodes/i)
|
||||||
fireEvent.change(input, { target: { value: 'switch' } })
|
fireEvent.change(input, { target: { value: 'switch' } })
|
||||||
fireEvent.keyDown(input, { key: 'Enter' })
|
fireEvent.keyDown(input, { key: 'Enter' })
|
||||||
@@ -135,14 +141,14 @@ describe('SearchModal', () => {
|
|||||||
|
|
||||||
it('closes on Escape key', () => {
|
it('closes on Escape key', () => {
|
||||||
const onClose = vi.fn()
|
const onClose = vi.fn()
|
||||||
render(<SearchModal open onClose={onClose} />)
|
render(<SearchModal open onClose={onClose} onOpenPending={mockOnOpenPending} />)
|
||||||
fireEvent.keyDown(screen.getByPlaceholderText(/search nodes/i), { key: 'Escape' })
|
fireEvent.keyDown(screen.getByPlaceholderText(/search nodes/i), { key: 'Escape' })
|
||||||
expect(onClose).toHaveBeenCalledOnce()
|
expect(onClose).toHaveBeenCalledOnce()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('closes when clicking backdrop', () => {
|
it('closes when clicking backdrop', () => {
|
||||||
const onClose = vi.fn()
|
const onClose = vi.fn()
|
||||||
render(<SearchModal open onClose={onClose} />)
|
render(<SearchModal open onClose={onClose} onOpenPending={mockOnOpenPending} />)
|
||||||
// The backdrop is the fixed inset div — clicking it fires onClose
|
// The backdrop is the fixed inset div — clicking it fires onClose
|
||||||
const backdrop = document.querySelector('.fixed.inset-0') as HTMLElement
|
const backdrop = document.querySelector('.fixed.inset-0') as HTMLElement
|
||||||
fireEvent.click(backdrop)
|
fireEvent.click(backdrop)
|
||||||
@@ -151,14 +157,14 @@ describe('SearchModal', () => {
|
|||||||
|
|
||||||
it('does not close when clicking inside the search box', () => {
|
it('does not close when clicking inside the search box', () => {
|
||||||
const onClose = vi.fn()
|
const onClose = vi.fn()
|
||||||
render(<SearchModal open onClose={onClose} />)
|
render(<SearchModal open onClose={onClose} onOpenPending={mockOnOpenPending} />)
|
||||||
fireEvent.click(screen.getByPlaceholderText(/search nodes/i))
|
fireEvent.click(screen.getByPlaceholderText(/search nodes/i))
|
||||||
expect(onClose).not.toHaveBeenCalled()
|
expect(onClose).not.toHaveBeenCalled()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('search is case-insensitive', () => {
|
it('search is case-insensitive', () => {
|
||||||
useCanvasStore.setState({ nodes: [makeNode('n1', { label: 'My NAS' })] })
|
useCanvasStore.setState({ nodes: [makeNode('n1', { label: 'My NAS' })] })
|
||||||
render(<SearchModal open onClose={vi.fn()} />)
|
render(<SearchModal open onClose={vi.fn()} onOpenPending={mockOnOpenPending} />)
|
||||||
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: 'MY NAS' } })
|
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: 'MY NAS' } })
|
||||||
expect(screen.getByText('My NAS')).toBeDefined()
|
expect(screen.getByText('My NAS')).toBeDefined()
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -85,6 +85,7 @@ export function DetailPanel({ onEdit }: DetailPanelProps) {
|
|||||||
const handleAddService = () => {
|
const handleAddService = () => {
|
||||||
const port = parseInt(newSvc.port, 10)
|
const port = parseInt(newSvc.port, 10)
|
||||||
if (!newSvc.service_name.trim() || isNaN(port) || port < 1 || port > 65535) return
|
if (!newSvc.service_name.trim() || isNaN(port) || port < 1 || port > 65535) return
|
||||||
|
snapshotHistory()
|
||||||
const svc: ServiceInfo = { port, protocol: newSvc.protocol, service_name: newSvc.service_name.trim() }
|
const svc: ServiceInfo = { port, protocol: newSvc.protocol, service_name: newSvc.service_name.trim() }
|
||||||
updateNode(node.id, { services: [...services, svc] })
|
updateNode(node.id, { services: [...services, svc] })
|
||||||
setNewSvc(EMPTY_FORM)
|
setNewSvc(EMPTY_FORM)
|
||||||
@@ -92,6 +93,7 @@ export function DetailPanel({ onEdit }: DetailPanelProps) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleRemoveService = (index: number) => {
|
const handleRemoveService = (index: number) => {
|
||||||
|
snapshotHistory()
|
||||||
const updated = services.filter((_, i) => i !== index)
|
const updated = services.filter((_, i) => i !== index)
|
||||||
updateNode(node.id, { services: updated })
|
updateNode(node.id, { services: updated })
|
||||||
if (editingIndex === index) setEditingFor(null)
|
if (editingIndex === index) setEditingFor(null)
|
||||||
@@ -109,6 +111,7 @@ export function DetailPanel({ onEdit }: DetailPanelProps) {
|
|||||||
if (editingIndex === null) return
|
if (editingIndex === null) return
|
||||||
const port = parseInt(editSvc.port, 10)
|
const port = parseInt(editSvc.port, 10)
|
||||||
if (!editSvc.service_name.trim() || isNaN(port) || port < 1 || port > 65535) return
|
if (!editSvc.service_name.trim() || isNaN(port) || port < 1 || port > 65535) return
|
||||||
|
snapshotHistory()
|
||||||
const updated = services.map((svc, i) =>
|
const updated = services.map((svc, i) =>
|
||||||
i === editingIndex ? { ...svc, port, protocol: editSvc.protocol, service_name: editSvc.service_name.trim() } : svc
|
i === editingIndex ? { ...svc, port, protocol: editSvc.protocol, service_name: editSvc.service_name.trim() } : svc
|
||||||
)
|
)
|
||||||
@@ -147,7 +150,7 @@ export function DetailPanel({ onEdit }: DetailPanelProps) {
|
|||||||
{data.mac && <DetailRow label="MAC" value={data.mac} mono />}
|
{data.mac && <DetailRow label="MAC" value={data.mac} mono />}
|
||||||
{data.os && <DetailRow label="OS" value={data.os} />}
|
{data.os && <DetailRow label="OS" value={data.os} />}
|
||||||
{data.check_method && <DetailRow label="Check" value={data.check_method} mono />}
|
{data.check_method && <DetailRow label="Check" value={data.check_method} mono />}
|
||||||
{data.last_seen && <DetailRow label="Last Seen" value={new Date(data.last_seen).toLocaleString()} />}
|
{data.last_seen && <DetailRow label="Last Seen" value={new Date(data.last_seen.endsWith('Z') ? data.last_seen : data.last_seen + 'Z').toLocaleString()} />}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{(data.cpu_count != null || data.cpu_model || data.ram_gb != null || data.disk_gb != null) && (
|
{(data.cpu_count != null || data.cpu_model || data.ram_gb != null || data.disk_gb != null) && (
|
||||||
|
|||||||
@@ -35,26 +35,26 @@ interface SidebarProps {
|
|||||||
onScan: () => void
|
onScan: () => void
|
||||||
onSave: () => void
|
onSave: () => void
|
||||||
onNodeApproved: (nodeId: string) => void
|
onNodeApproved: (nodeId: string) => void
|
||||||
|
forceView?: SidebarView
|
||||||
|
highlightPendingId?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Sidebar({ onAddNode, onAddGroupRect, onScan, onSave, onNodeApproved }: SidebarProps) {
|
export function Sidebar({ onAddNode, onAddGroupRect, onScan, onSave, onNodeApproved, forceView, highlightPendingId }: SidebarProps) {
|
||||||
const [collapsed, setCollapsed] = useState(false)
|
const [_collapsed, setCollapsed] = useState(false)
|
||||||
const [activeView, setActiveView] = useState<SidebarView>('canvas')
|
const [_activeView, setActiveView] = useState<SidebarView>('canvas')
|
||||||
|
|
||||||
|
// When forceView is set, override local state without useEffect
|
||||||
|
const collapsed = forceView ? false : _collapsed
|
||||||
|
const activeView = forceView ?? _activeView
|
||||||
|
|
||||||
const { nodes, hasUnsavedChanges, hideIp, toggleHideIp } = useCanvasStore()
|
const { nodes, hasUnsavedChanges, hideIp, toggleHideIp } = useCanvasStore()
|
||||||
|
|
||||||
const networkNodes = nodes.filter((n) => n.data.type !== 'groupRect')
|
const networkNodes = nodes.filter((n) => n.data.type !== 'groupRect')
|
||||||
const onlineCount = networkNodes.filter((n) => n.data.status === 'online').length
|
const onlineCount = networkNodes.filter((n) => n.data.status === 'online').length
|
||||||
const offlineCount = networkNodes.filter((n) => n.data.status === 'offline').length
|
const offlineCount = networkNodes.filter((n) => n.data.status === 'offline').length
|
||||||
|
|
||||||
const handleScan = useCallback(async () => {
|
const handleScan = useCallback(() => {
|
||||||
try {
|
onScan()
|
||||||
await scanApi.trigger()
|
|
||||||
toast.success('Network scan started — check Scan History for results')
|
|
||||||
setActiveView('history')
|
|
||||||
onScan()
|
|
||||||
} catch {
|
|
||||||
toast.error('Failed to trigger scan')
|
|
||||||
}
|
|
||||||
}, [onScan])
|
}, [onScan])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -92,7 +92,7 @@ export function Sidebar({ onAddNode, onAddGroupRect, onScan, onSave, onNodeAppro
|
|||||||
{/* View content (only when expanded) */}
|
{/* View content (only when expanded) */}
|
||||||
{!collapsed && activeView !== 'canvas' && (
|
{!collapsed && activeView !== 'canvas' && (
|
||||||
<div className="flex-1 min-h-0 overflow-y-auto border-t border-border">
|
<div className="flex-1 min-h-0 overflow-y-auto border-t border-border">
|
||||||
{activeView === 'pending' && <PendingDevicesPanel onNodeApproved={onNodeApproved} />}
|
{activeView === 'pending' && <PendingDevicesPanel onNodeApproved={onNodeApproved} highlightId={highlightPendingId} />}
|
||||||
{activeView === 'hidden' && <HiddenDevicesPanel />}
|
{activeView === 'hidden' && <HiddenDevicesPanel />}
|
||||||
{activeView === 'history' && <ScanHistoryPanel />}
|
{activeView === 'history' && <ScanHistoryPanel />}
|
||||||
{activeView === 'settings' && <SettingsPanel />}
|
{activeView === 'settings' && <SettingsPanel />}
|
||||||
@@ -156,11 +156,14 @@ export function Sidebar({ onAddNode, onAddGroupRect, onScan, onSave, onNodeAppro
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function PendingDevicesPanel({ onNodeApproved }: { onNodeApproved: (nodeId: string) => void }) {
|
const COMMON_PORTS = new Set([22, 80, 443])
|
||||||
|
|
||||||
|
function PendingDevicesPanel({ onNodeApproved, highlightId }: { onNodeApproved: (nodeId: string) => void; highlightId?: string }) {
|
||||||
const [devices, setDevices] = useState<PendingDevice[]>([])
|
const [devices, setDevices] = useState<PendingDevice[]>([])
|
||||||
const [loading, setLoading] = useState(false)
|
const [loading, setLoading] = useState(false)
|
||||||
const [selected, setSelected] = useState<PendingDevice | null>(null)
|
const [selected, setSelected] = useState<PendingDevice | null>(null)
|
||||||
const { addNode, scanEventTs } = useCanvasStore()
|
const { addNode, scanEventTs } = useCanvasStore()
|
||||||
|
const highlightRef = useRef<HTMLButtonElement>(null)
|
||||||
|
|
||||||
const load = useCallback(async () => {
|
const load = useCallback(async () => {
|
||||||
setLoading(true)
|
setLoading(true)
|
||||||
@@ -190,6 +193,11 @@ function PendingDevicesPanel({ onNodeApproved }: { onNodeApproved: (nodeId: stri
|
|||||||
if (scanEventTs > 0) load()
|
if (scanEventTs > 0) load()
|
||||||
}, [scanEventTs, load])
|
}, [scanEventTs, load])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!highlightId || loading) return
|
||||||
|
highlightRef.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
|
||||||
|
}, [highlightId, loading])
|
||||||
|
|
||||||
const handleApprove = async (device: PendingDevice) => {
|
const handleApprove = async (device: PendingDevice) => {
|
||||||
try {
|
try {
|
||||||
const nodeData = {
|
const nodeData = {
|
||||||
@@ -210,6 +218,7 @@ function PendingDevicesPanel({ onNodeApproved }: { onNodeApproved: (nodeId: stri
|
|||||||
})
|
})
|
||||||
toast.success(`Approved ${nodeData.label}`)
|
toast.success(`Approved ${nodeData.label}`)
|
||||||
setDevices((prev) => prev.filter((d) => d.id !== device.id))
|
setDevices((prev) => prev.filter((d) => d.id !== device.id))
|
||||||
|
setSelected(null)
|
||||||
onNodeApproved(nodeId)
|
onNodeApproved(nodeId)
|
||||||
} catch {
|
} catch {
|
||||||
toast.error('Failed to approve device')
|
toast.error('Failed to approve device')
|
||||||
@@ -256,7 +265,6 @@ function PendingDevicesPanel({ onNodeApproved }: { onNodeApproved: (nodeId: stri
|
|||||||
<p className="text-xs text-muted-foreground text-center py-4">No pending devices</p>
|
<p className="text-xs text-muted-foreground text-center py-4">No pending devices</p>
|
||||||
)}
|
)}
|
||||||
{devices.map((d) => {
|
{devices.map((d) => {
|
||||||
const COMMON_PORTS = new Set([22, 80, 443])
|
|
||||||
const namedService = d.services.find((s) => s.category != null && !COMMON_PORTS.has(s.port))
|
const namedService = d.services.find((s) => s.category != null && !COMMON_PORTS.has(s.port))
|
||||||
const titleService = namedService
|
const titleService = namedService
|
||||||
?? d.services.find((s) => s.port === 80)
|
?? d.services.find((s) => s.port === 80)
|
||||||
@@ -271,11 +279,13 @@ function PendingDevicesPanel({ onNodeApproved }: { onNodeApproved: (nodeId: stri
|
|||||||
const virtualBadge = detectVirtualBadge(d.mac)
|
const virtualBadge = detectVirtualBadge(d.mac)
|
||||||
const sourceColor = d.discovery_source === 'mdns' ? '#a855f7' : '#8b949e'
|
const sourceColor = d.discovery_source === 'mdns' ? '#a855f7' : '#8b949e'
|
||||||
const sourceLabel = d.discovery_source === 'mdns' ? 'mDNS' : d.discovery_source === 'arp' ? 'ARP' : null
|
const sourceLabel = d.discovery_source === 'mdns' ? 'mDNS' : d.discovery_source === 'arp' ? 'ARP' : null
|
||||||
|
const isHighlighted = d.id === highlightId
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
key={d.id}
|
key={d.id}
|
||||||
|
ref={isHighlighted ? highlightRef : null}
|
||||||
onClick={() => setSelected(d)}
|
onClick={() => setSelected(d)}
|
||||||
className="w-full mb-1.5 p-2 rounded-md bg-[#21262d] text-xs text-left hover:bg-[#30363d] transition-colors border border-transparent hover:border-[#30363d]"
|
className={`w-full mb-1.5 p-2 rounded-md text-xs text-left transition-colors border ${isHighlighted ? 'bg-[#2d3748] border-[#e3b341]' : 'bg-[#21262d] border-transparent hover:bg-[#30363d] hover:border-[#30363d]'}`}
|
||||||
>
|
>
|
||||||
<div className="flex items-center gap-1.5">
|
<div className="flex items-center gap-1.5">
|
||||||
<span className="w-1.5 h-1.5 rounded-full bg-[#e3b341] shrink-0" />
|
<span className="w-1.5 h-1.5 rounded-full bg-[#e3b341] shrink-0" />
|
||||||
@@ -467,7 +477,7 @@ function ScanHistoryPanel() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-muted-foreground text-[10px] mt-0.5">
|
<div className="text-muted-foreground text-[10px] mt-0.5">
|
||||||
{new Date(r.started_at).toLocaleString()}
|
{new Date(r.started_at.endsWith('Z') ? r.started_at : r.started_at + 'Z').toLocaleString()}
|
||||||
</div>
|
</div>
|
||||||
{r.ranges.length > 0 && (
|
{r.ranges.length > 0 && (
|
||||||
<div className="text-[#8b949e] text-[10px] font-mono truncate">{r.ranges.join(', ')}</div>
|
<div className="text-[#8b949e] text-[10px] font-mono truncate">{r.ranges.join(', ')}</div>
|
||||||
|
|||||||
@@ -222,20 +222,12 @@ describe('Sidebar', () => {
|
|||||||
|
|
||||||
// ── Scan action ────────────────────────────────────────────────────────────
|
// ── Scan action ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
it('calls scanApi.trigger and onScan prop when Scan Network is clicked', async () => {
|
it('calls onScan prop when Scan Network is clicked (scan trigger moved to ScanConfigModal)', () => {
|
||||||
const { scanApi } = await import('@/api/client')
|
|
||||||
render(<Sidebar {...defaultProps} />)
|
render(<Sidebar {...defaultProps} />)
|
||||||
fireEvent.click(screen.getByText('Scan Network'))
|
fireEvent.click(screen.getByText('Scan Network'))
|
||||||
await waitFor(() => expect(scanApi.trigger).toHaveBeenCalledOnce())
|
|
||||||
expect(defaultProps.onScan).toHaveBeenCalledOnce()
|
expect(defaultProps.onScan).toHaveBeenCalledOnce()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('switches to Scan History view after scan is triggered', async () => {
|
|
||||||
render(<Sidebar {...defaultProps} />)
|
|
||||||
fireEvent.click(screen.getByText('Scan Network'))
|
|
||||||
await waitFor(() => expect(screen.getByText('History')).toBeInTheDocument())
|
|
||||||
})
|
|
||||||
|
|
||||||
// ── Navigation ─────────────────────────────────────────────────────────────
|
// ── Navigation ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
it('shows Pending panel when Pending Devices nav item is clicked', async () => {
|
it('shows Pending panel when Pending Devices nav item is clicked', async () => {
|
||||||
|
|||||||
@@ -1,134 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
# Homelable — Proxmox VE LXC creator
|
|
||||||
# Run this on the Proxmox HOST (not inside a container):
|
|
||||||
# bash <(curl -fsSL https://raw.githubusercontent.com/Pouzor/homelable/main/scripts/install-proxmox.sh)
|
|
||||||
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; CYAN='\033[0;36m'; NC='\033[0m'
|
|
||||||
info() { echo -e "${GREEN}[homelable]${NC} $*"; }
|
|
||||||
warn() { echo -e "${YELLOW}[homelable]${NC} $*"; }
|
|
||||||
error() { echo -e "${RED}[homelable]${NC} $*"; exit 1; }
|
|
||||||
step() { echo -e "\n${CYAN}▶ $*${NC}"; }
|
|
||||||
|
|
||||||
# ── Must run on a Proxmox VE host ─────────────────────────────────────────────
|
|
||||||
[[ $EUID -ne 0 ]] && error "Run as root on the Proxmox host"
|
|
||||||
command -v pct &>/dev/null || error "pct not found — run this on a Proxmox VE host, not inside a container"
|
|
||||||
|
|
||||||
# ── Detect available storages for LXC rootfs ──────────────────────────────────
|
|
||||||
mapfile -t STORAGES < <(pvesm status --content rootdir 2>/dev/null | awk 'NR>1 && $3=="active" {print $1}')
|
|
||||||
[[ ${#STORAGES[@]} -eq 0 ]] && error "No active storage found that supports LXC rootfs (rootdir content type)"
|
|
||||||
|
|
||||||
if [[ ${#STORAGES[@]} -eq 1 ]]; then
|
|
||||||
DEFAULT_STORAGE="${STORAGES[0]}"
|
|
||||||
else
|
|
||||||
echo ""
|
|
||||||
echo "Available storages:"
|
|
||||||
for i in "${!STORAGES[@]}"; do
|
|
||||||
echo " $((i+1))) ${STORAGES[$i]}"
|
|
||||||
done
|
|
||||||
read -rp "Select storage [1]: " STORAGE_IDX
|
|
||||||
STORAGE_IDX="${STORAGE_IDX:-1}"
|
|
||||||
DEFAULT_STORAGE="${STORAGES[$((STORAGE_IDX-1))]}"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# ── Settings (override via env vars) ──────────────────────────────────────────
|
|
||||||
CT_HOSTNAME="${CT_HOSTNAME:-homelable}"
|
|
||||||
STORAGE="${STORAGE:-$DEFAULT_STORAGE}"
|
|
||||||
DISK_SIZE="${DISK_SIZE:-8}" # GB
|
|
||||||
RAM="${RAM:-1024}" # MB
|
|
||||||
CORES="${CORES:-2}"
|
|
||||||
BRIDGE="${BRIDGE:-vmbr0}"
|
|
||||||
RAW="https://raw.githubusercontent.com/Pouzor/homelable/main"
|
|
||||||
|
|
||||||
# ── Interactive prompts ────────────────────────────────────────────────────────
|
|
||||||
DEFAULT_CTID="$(pvesh get /cluster/nextid 2>/dev/null || echo 200)"
|
|
||||||
|
|
||||||
if [[ -z "${CTID:-}" ]]; then
|
|
||||||
read -rp "Container ID [${DEFAULT_CTID}]: " CTID_INPUT
|
|
||||||
CTID="${CTID_INPUT:-$DEFAULT_CTID}"
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ -z "${ROOT_PASSWORD:-}" ]]; then
|
|
||||||
while true; do
|
|
||||||
read -rsp "Root password for LXC container: " ROOT_PASSWORD
|
|
||||||
echo ""
|
|
||||||
[[ -z "$ROOT_PASSWORD" ]] && warn "Password cannot be empty, try again." && continue
|
|
||||||
read -rsp "Confirm root password: " ROOT_PASSWORD_CONFIRM
|
|
||||||
echo ""
|
|
||||||
[[ "$ROOT_PASSWORD" == "$ROOT_PASSWORD_CONFIRM" ]] && break
|
|
||||||
warn "Passwords do not match, try again."
|
|
||||||
done
|
|
||||||
fi
|
|
||||||
|
|
||||||
step "Creating Homelable LXC (CTID=$CTID, hostname=$CT_HOSTNAME, storage=$STORAGE)"
|
|
||||||
|
|
||||||
# ── Download Debian 12 template if needed ─────────────────────────────────────
|
|
||||||
TEMPLATE_STORAGE=$(pvesm status --content vztmpl | awk 'NR>1 {print $1; exit}')
|
|
||||||
TEMPLATE=$(pveam list "$TEMPLATE_STORAGE" 2>/dev/null | grep "debian-12" | tail -1 | awk '{print $1}')
|
|
||||||
|
|
||||||
if [[ -z "$TEMPLATE" ]]; then
|
|
||||||
info "Downloading Debian 12 LXC template..."
|
|
||||||
pveam update
|
|
||||||
TEMPLATE_NAME=$(pveam available --section system | grep "debian-12" | tail -1 | awk '{print $2}')
|
|
||||||
[[ -z "$TEMPLATE_NAME" ]] && error "Could not find a Debian 12 template"
|
|
||||||
pveam download "$TEMPLATE_STORAGE" "$TEMPLATE_NAME"
|
|
||||||
TEMPLATE="$TEMPLATE_STORAGE:vztmpl/$TEMPLATE_NAME"
|
|
||||||
fi
|
|
||||||
|
|
||||||
info "Using template: $TEMPLATE"
|
|
||||||
|
|
||||||
# ── Create the container ───────────────────────────────────────────────────────
|
|
||||||
pct create "$CTID" "$TEMPLATE" \
|
|
||||||
--hostname "$CT_HOSTNAME" \
|
|
||||||
--storage "$STORAGE" \
|
|
||||||
--rootfs "${STORAGE}:${DISK_SIZE}" \
|
|
||||||
--memory "$RAM" \
|
|
||||||
--cores "$CORES" \
|
|
||||||
--net0 "name=eth0,bridge=${BRIDGE},ip=dhcp${VLAN_TAG:+,tag=${VLAN_TAG}}" \
|
|
||||||
--ostype debian \
|
|
||||||
--unprivileged 1 \
|
|
||||||
--features "nesting=1" \
|
|
||||||
--password "$ROOT_PASSWORD" \
|
|
||||||
--start 1
|
|
||||||
|
|
||||||
info "Container $CTID created and started"
|
|
||||||
|
|
||||||
# ── Wait for container to be ready ────────────────────────────────────────────
|
|
||||||
info "Waiting for container to be ready..."
|
|
||||||
for i in $(seq 1 30); do
|
|
||||||
if pct exec "$CTID" -- test -x /usr/bin/apt-get &>/dev/null; then
|
|
||||||
break
|
|
||||||
fi
|
|
||||||
[[ $i -eq 30 ]] && error "Container did not become ready after 30s"
|
|
||||||
sleep 1
|
|
||||||
done
|
|
||||||
|
|
||||||
# Wait a bit more for network (DHCP lease)
|
|
||||||
info "Waiting for network (DHCP)..."
|
|
||||||
for i in $(seq 1 20); do
|
|
||||||
if pct exec "$CTID" -- sh -c "ip route | grep -q default" &>/dev/null; then
|
|
||||||
break
|
|
||||||
fi
|
|
||||||
[[ $i -eq 20 ]] && error "Container has no default route after 20s — check bridge $BRIDGE"
|
|
||||||
sleep 1
|
|
||||||
done
|
|
||||||
|
|
||||||
# ── Grant NET_RAW for nmap (ping-based checks) ─────────────────────────────────
|
|
||||||
echo "lxc.cap.keep = net_raw net_bind_service" >> "/etc/pve/lxc/${CTID}.conf" 2>/dev/null || true
|
|
||||||
|
|
||||||
# ── Bootstrap curl then run the installer ─────────────────────────────────────
|
|
||||||
step "Running Homelable installer inside container $CTID..."
|
|
||||||
pct exec "$CTID" -- apt-get install -y -qq curl
|
|
||||||
pct exec "$CTID" -- bash -c "curl -fsSL ${RAW}/scripts/lxc-install.sh | bash"
|
|
||||||
|
|
||||||
# ── Done ──────────────────────────────────────────────────────────────────────
|
|
||||||
IP=$(pct exec "$CTID" -- hostname -I 2>/dev/null | awk '{print $1}' || echo "<container-ip>")
|
|
||||||
echo ""
|
|
||||||
echo -e " ${GREEN}✓ Homelable installed in LXC $CTID${NC}"
|
|
||||||
echo -e " ${GREEN}✓ Open http://${IP}${NC}"
|
|
||||||
echo -e " Homelable login: ${YELLOW}admin / admin${NC}"
|
|
||||||
echo -e " LXC root SSH: ${YELLOW}root / <password you set>${NC}"
|
|
||||||
echo -e " ${YELLOW}⚠ Change the Homelable password after first login${NC}"
|
|
||||||
echo -e " ${YELLOW} - edit /opt/homelable/backend/.env (AUTH_PASSWORD_HASH)${NC}"
|
|
||||||
echo ""
|
|
||||||
@@ -1,138 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
# Homelable — in-container installer
|
|
||||||
# Runs INSIDE a Debian/Ubuntu LXC container (called automatically by install-proxmox.sh)
|
|
||||||
# Can also be run manually inside any Debian/Ubuntu machine:
|
|
||||||
# bash <(curl -fsSL https://raw.githubusercontent.com/Pouzor/homelable/main/scripts/lxc-install.sh)
|
|
||||||
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
INSTALL_DIR=/opt/homelable
|
|
||||||
DATA_DIR=/opt/homelable/data
|
|
||||||
SERVICE_USER=homelable
|
|
||||||
REPO_URL="https://github.com/Pouzor/homelable.git"
|
|
||||||
|
|
||||||
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
|
|
||||||
info() { echo -e "${GREEN}[homelable]${NC} $*"; }
|
|
||||||
warn() { echo -e "${YELLOW}[homelable]${NC} $*"; }
|
|
||||||
error() { echo -e "${RED}[homelable]${NC} $*"; exit 1; }
|
|
||||||
|
|
||||||
[[ $EUID -ne 0 ]] && error "Run as root (sudo bash ...)"
|
|
||||||
|
|
||||||
# ── Detect OS ─────────────────────────────────────────────────────────────────
|
|
||||||
if [[ -f /etc/os-release ]]; then
|
|
||||||
# shellcheck source=/dev/null
|
|
||||||
. /etc/os-release
|
|
||||||
else
|
|
||||||
error "Cannot detect OS"
|
|
||||||
fi
|
|
||||||
info "Detected: $PRETTY_NAME"
|
|
||||||
[[ "$ID" =~ ^(debian|ubuntu)$ ]] || error "Requires Debian or Ubuntu"
|
|
||||||
|
|
||||||
# ── System deps ───────────────────────────────────────────────────────────────
|
|
||||||
info "Installing system dependencies..."
|
|
||||||
apt-get update
|
|
||||||
apt-get install -y --fix-missing python3 python3-pip python3-venv nmap curl git nginx
|
|
||||||
|
|
||||||
# ── Node.js 20 ────────────────────────────────────────────────────────────────
|
|
||||||
if ! command -v node &>/dev/null; then
|
|
||||||
info "Installing Node.js 20..."
|
|
||||||
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
|
|
||||||
apt-get install -y -qq nodejs
|
|
||||||
fi
|
|
||||||
|
|
||||||
# ── Service user ──────────────────────────────────────────────────────────────
|
|
||||||
if ! id "$SERVICE_USER" &>/dev/null; then
|
|
||||||
useradd --system --shell /sbin/nologin "$SERVICE_USER"
|
|
||||||
info "Created service user: $SERVICE_USER"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# ── Clone / update repo ───────────────────────────────────────────────────────
|
|
||||||
if [[ -d "$INSTALL_DIR/.git" ]]; then
|
|
||||||
info "Updating existing installation..."
|
|
||||||
git -C "$INSTALL_DIR" pull --quiet
|
|
||||||
else
|
|
||||||
info "Cloning repository..."
|
|
||||||
git clone --quiet "$REPO_URL" "$INSTALL_DIR"
|
|
||||||
fi
|
|
||||||
|
|
||||||
mkdir -p "$DATA_DIR"
|
|
||||||
|
|
||||||
# ── Backend ───────────────────────────────────────────────────────────────────
|
|
||||||
info "Setting up Python backend..."
|
|
||||||
cd "$INSTALL_DIR/backend"
|
|
||||||
python3 -m venv .venv
|
|
||||||
.venv/bin/pip install --quiet -r requirements.txt
|
|
||||||
|
|
||||||
# Generate .env if missing
|
|
||||||
if [[ ! -f .env ]]; then
|
|
||||||
SECRET=$(python3 -c "import secrets; print(secrets.token_urlsafe(32))")
|
|
||||||
# Default hash = bcrypt of "admin" (same as .env.example)
|
|
||||||
cat > .env <<EOF
|
|
||||||
SECRET_KEY=$SECRET
|
|
||||||
SQLITE_PATH=$DATA_DIR/homelab.db
|
|
||||||
CORS_ORIGINS=["http://localhost","http://$(hostname -I | awk '{print $1}')"]
|
|
||||||
|
|
||||||
# Auth — default credentials: admin / admin
|
|
||||||
# Change AUTH_PASSWORD_HASH before exposing on a network.
|
|
||||||
# Generate: python3 -c "from passlib.context import CryptContext; print(CryptContext(schemes=['bcrypt']).hash('yourpassword'))"
|
|
||||||
AUTH_USERNAME=admin
|
|
||||||
AUTH_PASSWORD_HASH='\$2b\$12\$RtMbyw17l4N5UGzeXMNAWuzCaVV.XFBY7ZetWheQhxcBDcxahapkG'
|
|
||||||
|
|
||||||
SCANNER_RANGES=["192.168.1.0/24"]
|
|
||||||
STATUS_CHECKER_INTERVAL=60
|
|
||||||
EOF
|
|
||||||
warn "Created .env with default admin/admin — change AUTH_PASSWORD_HASH before exposing on a network!"
|
|
||||||
fi
|
|
||||||
|
|
||||||
chown -R "$SERVICE_USER":"$SERVICE_USER" "$DATA_DIR"
|
|
||||||
chown -R "$SERVICE_USER":"$SERVICE_USER" "$INSTALL_DIR/backend/.venv"
|
|
||||||
|
|
||||||
# ── systemd: backend ──────────────────────────────────────────────────────────
|
|
||||||
cat > /etc/systemd/system/homelable-backend.service <<EOF
|
|
||||||
[Unit]
|
|
||||||
Description=Homelable Backend
|
|
||||||
After=network.target
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
Type=simple
|
|
||||||
User=$SERVICE_USER
|
|
||||||
WorkingDirectory=$INSTALL_DIR/backend
|
|
||||||
EnvironmentFile=$INSTALL_DIR/backend/.env
|
|
||||||
ExecStart=$INSTALL_DIR/backend/.venv/bin/uvicorn app.main:app --host 127.0.0.1 --port 8000
|
|
||||||
Restart=always
|
|
||||||
RestartSec=5
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=multi-user.target
|
|
||||||
EOF
|
|
||||||
|
|
||||||
# ── Frontend ──────────────────────────────────────────────────────────────────
|
|
||||||
info "Building frontend..."
|
|
||||||
cd "$INSTALL_DIR/frontend"
|
|
||||||
npm ci --silent
|
|
||||||
npm run build
|
|
||||||
|
|
||||||
# ── nginx ─────────────────────────────────────────────────────────────────────
|
|
||||||
info "Configuring nginx..."
|
|
||||||
# Use the project nginx config, adjusted for local backend
|
|
||||||
sed \
|
|
||||||
-e 's|http://backend:8000|http://127.0.0.1:8000|g' \
|
|
||||||
-e "s|/usr/share/nginx/html|$INSTALL_DIR/frontend/dist|g" \
|
|
||||||
"$INSTALL_DIR/docker/nginx.conf" > /etc/nginx/sites-available/homelable
|
|
||||||
|
|
||||||
ln -sf /etc/nginx/sites-available/homelable /etc/nginx/sites-enabled/homelable
|
|
||||||
rm -f /etc/nginx/sites-enabled/default
|
|
||||||
nginx -t
|
|
||||||
systemctl reload nginx || systemctl start nginx
|
|
||||||
|
|
||||||
# ── Enable & start ────────────────────────────────────────────────────────────
|
|
||||||
systemctl daemon-reload
|
|
||||||
systemctl enable --now homelable-backend
|
|
||||||
systemctl enable --now nginx
|
|
||||||
|
|
||||||
info "Done!"
|
|
||||||
echo ""
|
|
||||||
echo -e " ${GREEN}Homelable is running at http://$(hostname -I | awk '{print $1}')${NC}"
|
|
||||||
echo -e " Default login: admin / admin"
|
|
||||||
echo -e " ${YELLOW}⚠ Change the password: edit $INSTALL_DIR/backend/.env (AUTH_PASSWORD_HASH)${NC}"
|
|
||||||
echo ""
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
# Homelable — update to latest version
|
|
||||||
# Run inside the LXC / any Linux host where lxc-install.sh was used:
|
|
||||||
# bash /opt/homelable/scripts/update.sh
|
|
||||||
# Or pull-and-run directly:
|
|
||||||
# bash <(curl -fsSL https://raw.githubusercontent.com/Pouzor/homelable/main/scripts/update.sh)
|
|
||||||
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
INSTALL_DIR=/opt/homelable
|
|
||||||
|
|
||||||
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
|
|
||||||
info() { echo -e "${GREEN}[homelable]${NC} $*"; }
|
|
||||||
warn() { echo -e "${YELLOW}[homelable]${NC} $*"; }
|
|
||||||
error() { echo -e "${RED}[homelable]${NC} $*"; exit 1; }
|
|
||||||
|
|
||||||
[[ $EUID -ne 0 ]] && error "Run as root (sudo bash ...)"
|
|
||||||
[[ -d "$INSTALL_DIR/.git" ]] || error "Homelable not found at $INSTALL_DIR — run lxc-install.sh first"
|
|
||||||
|
|
||||||
# ── Pull latest code ──────────────────────────────────────────────────────────
|
|
||||||
info "Pulling latest code..."
|
|
||||||
BEFORE=$(git -C "$INSTALL_DIR" rev-parse HEAD)
|
|
||||||
git -C "$INSTALL_DIR" pull --quiet
|
|
||||||
AFTER=$(git -C "$INSTALL_DIR" rev-parse HEAD)
|
|
||||||
|
|
||||||
if [[ "$BEFORE" == "$AFTER" ]]; then
|
|
||||||
info "Already up to date."
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo ""
|
|
||||||
info "Changes since last update:"
|
|
||||||
git -C "$INSTALL_DIR" log --oneline "${BEFORE}..${AFTER}"
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
# ── Stop backend ─────────────────────────────────────────────────────────────
|
|
||||||
info "Stopping backend service..."
|
|
||||||
systemctl stop homelable-backend
|
|
||||||
|
|
||||||
# ── Backend deps ─────────────────────────────────────────────────────────────
|
|
||||||
info "Updating Python dependencies..."
|
|
||||||
cd "$INSTALL_DIR/backend"
|
|
||||||
.venv/bin/pip install --quiet -r requirements.txt
|
|
||||||
|
|
||||||
# ── Frontend build ────────────────────────────────────────────────────────────
|
|
||||||
info "Rebuilding frontend..."
|
|
||||||
cd "$INSTALL_DIR/frontend"
|
|
||||||
npm ci --silent
|
|
||||||
npm run build
|
|
||||||
|
|
||||||
# ── nginx config ─────────────────────────────────────────────────────────────
|
|
||||||
info "Updating nginx config..."
|
|
||||||
sed \
|
|
||||||
-e 's|http://backend:8000|http://127.0.0.1:8000|g' \
|
|
||||||
-e "s|/usr/share/nginx/html|$INSTALL_DIR/frontend/dist|g" \
|
|
||||||
"$INSTALL_DIR/docker/nginx.conf" > /etc/nginx/sites-available/homelable
|
|
||||||
nginx -t && systemctl reload nginx
|
|
||||||
|
|
||||||
# ── Restart backend ───────────────────────────────────────────────────────────
|
|
||||||
info "Starting backend service..."
|
|
||||||
systemctl start homelable-backend
|
|
||||||
|
|
||||||
echo ""
|
|
||||||
echo -e " ${GREEN}Homelable updated successfully!${NC}"
|
|
||||||
echo -e " Running at http://$(hostname -I | awk '{print $1}')"
|
|
||||||
echo ""
|
|
||||||
Reference in New Issue
Block a user