diff --git a/apps/device-manager/public/installers/nodedc-arnavi-vps-0.2.4.pyz b/apps/device-manager/public/installers/nodedc-arnavi-vps-0.2.4.pyz new file mode 100644 index 0000000..830994b Binary files /dev/null and b/apps/device-manager/public/installers/nodedc-arnavi-vps-0.2.4.pyz differ diff --git a/apps/device-manager/server/b2-usb.test.mjs b/apps/device-manager/server/b2-usb.test.mjs new file mode 100644 index 0000000..e54a367 --- /dev/null +++ b/apps/device-manager/server/b2-usb.test.mjs @@ -0,0 +1,51 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { readB2Usb } from '../src/b2/usb.mjs'; +function fixture({ model = 231, silence = false, change = false, incomplete = false } = {}) { + let stream, closed = false, identities = 0; const writes = []; + const port = { + getInfo: () => ({ usbVendorId: 0x2e3c, usbProductId: 0x5740 }), + async open(options) { assert.equal(options.flowControl, 'none'); }, + async close() { closed = true; }, + readable: new ReadableStream({ start(controller) { stream = controller; } }), + writable: new WritableStream({ write(bytes) { + const command = new TextDecoder().decode(bytes); writes.push(command); + if (silence) return; + let response; + if (command === '>I 7\r\n') { + identities++; + response = `>DI=${model};0;6\r\n>DN=300\r\n>MN=${change && identities > 1 ? '4' : '3'}23456789012345\r\n>SID0=0\r\n>SID1=0\r\n`; + } else { assert.equal(command, '>D 15;0\r\n'); response = '>SF=synthetic-config\r\n'; } + if (incomplete) response = response.slice(0, -2); + for (let i = 0; i < response.length; i += 7) stream.enqueue(new TextEncoder().encode(response.slice(i, i + 7))); + } }), + }; + return { serial: { async requestPort(options) { assert.deepEqual(options.filters, [{ usbVendorId: 0x2e3c, usbProductId: 0x5740 }]); return port; } }, writes, closed: () => closed, stream: () => stream }; +} +test('read-only USB protocol handles fragmented lines and releases port', async () => { + const f = fixture(); const result = await readB2Usb({ serial: f.serial, timeoutMs: 100 }); + assert.equal(result.settings, 'synthetic-config'); assert.equal(result.before.MN, result.after.MN); + assert.deepEqual(f.writes, ['>I 7\r\n', '>D 15;0\r\n', '>I 7\r\n']); assert.ok(f.closed()); +}); +test('wrong model stops before requesting configuration', async () => { + const f = fixture({ model: 999 }); + await assert.rejects(readB2Usb({ serial: f.serial, timeoutMs: 50 }), /не распознано/); + assert.deepEqual(f.writes, ['>I 7\r\n']); assert.ok(f.closed()); +}); +test('identity change cannot produce a registration snapshot', async () => { + const f = fixture({ change: true }); await assert.rejects(readB2Usb({ serial: f.serial, timeoutMs: 50 }), /изменилось устройство/); assert.ok(f.closed()); +}); +test('incomplete response and silence time out and close the port', async () => { + for (const options of [{ silence: true }, { incomplete: true }]) { + const f = fixture(options); await assert.rejects(readB2Usb({ serial: f.serial, timeoutMs: 15 }), /не ответил/); assert.ok(f.closed()); + } +}); +test('closing the form aborts a pending read and releases USB', async () => { + const f = fixture({ silence: true }), controller = new AbortController(); + const promise = readB2Usb({ serial: f.serial, signal: controller.signal }); + setTimeout(() => controller.abort(), 10); await assert.rejects(promise, { name: 'AbortError' }); assert.ok(f.closed()); +}); +test('disconnect does not turn a partial snapshot into success', async () => { + const f = fixture({ silence: true }); const promise = readB2Usb({ serial: f.serial }); + setTimeout(() => f.stream().close(), 10); await assert.rejects(promise, /USB отключён/); assert.ok(f.closed()); +}); diff --git a/apps/device-manager/src/DeviceControlViews.tsx b/apps/device-manager/src/DeviceControlViews.tsx index ae195a2..afcb05a 100644 --- a/apps/device-manager/src/DeviceControlViews.tsx +++ b/apps/device-manager/src/DeviceControlViews.tsx @@ -17,11 +17,9 @@ import { } from "@nodedc/ui-react"; import { useB2Inventory } from "./b2/useB2Inventory"; -import { B2AddHost } from "./b2/B2AddHost"; import { B2HostSettings } from "./b2/B2HostSettings"; import { - archiveHost, createConfigurationRevision, closeAssetBinding, ensureAsset, @@ -84,8 +82,6 @@ type DialogId = | null; export function DeviceControlView({ - selectedHostRef, - onSelectHost, view, workspace, session, @@ -93,8 +89,6 @@ export function DeviceControlView({ onPoll, onError, }: { - selectedHostRef: string | null; - onSelectHost: (hostRef: string | null) => void; view: ControlViewId; workspace: ProjectWorkspace; session: DeviceManagerSession; @@ -181,13 +175,10 @@ export function DeviceControlView({ ) : null} {view === "hosts" ? ( setDialog("host")} onCreateEndpoint={(hostRef) => { setDialogHostRef(hostRef); setDialog("endpoint"); }} onCreateDeployment={(hostRef) => { setDialogHostRef(hostRef); setDialog("deployment"); }} onCreateService={(hostRef) => { setDialogHostRef(hostRef); setDialog("service-instance"); }} @@ -308,14 +299,6 @@ export function DeviceControlView({ onCreated={completed} onError={onError} /> - void; workspace: ProjectWorkspace; canManageInfrastructure: boolean; canManageAssets: boolean; canManageBindings: boolean; - onCreateHost: () => void; onCreateEndpoint: (hostRef: string) => void; onCreateDeployment: (hostRef: string) => void; onCreateService: (hostRef: string) => void; @@ -524,41 +502,14 @@ function HostsView({ const [expandedHost, setExpandedHost] = useState(null); const [showArchive, setShowArchive] = useState(false); const [showAssets, setShowAssets] = useState(false); - const [archiveTarget, setArchiveTarget] = useState(null); - const [archiving, setArchiving] = useState(false); const b2 = useB2Inventory(workspace.project.projectRef, workspace); const topology = workspace.ontology; const hosts = topology.hosts.filter((host) => showArchive ? host.lifecycleState === 'suspended' : !['suspended', 'retired'].includes(host.lifecycleState)); - const selectedHost = topology.hosts.find((host) => host.hostRef === selectedHostRef); - const source = b2.data?.hosts.find((host) => host.hostRef === selectedHostRef); const isB2 = (host: InfrastructureHostView) => Boolean(b2.data?.hosts.some((item) => item.hostRef === host.hostRef)) || host.hostKey.startsWith('b2-'); const settings = settingsHost ? setSettingsHost(null)} onChanged={onPoll} onError={onError} /> : null; - if (selectedHost) { - if (isB2(selectedHost)) return
- {settings} - setSettingsHost(selectedHost)}> : undefined}> - -
  • {source?.reachable ? 'Доступен' : source ? 'Нет связи' : 'Проверка…'}} />
  • -
  • -
  • -
  • Не подключены} />
  • -
    -
    - {b2.error ?

    {b2.error}

    : null} -
    ; - return item.hostRef === selectedHost.hostRef)} onPoll={onPoll} onError={onError} />; - } return
    {settings} - { if (!archiving) setArchiveTarget(null); }} onConfirm={async () => { - if (!archiveTarget || archiving) return; - setArchiving(true); - try { await archiveHost(workspace.project.projectRef, archiveTarget.hostRef, archiveTarget.lifecycleState !== 'suspended'); setArchiveTarget(null); await onPoll(); } catch (reason) { onError(reason); } finally { setArchiving(false); } - }} /> -
    - {topology.hosts.some((host) => host.lifecycleState === 'suspended') ? : null} - {canManageInfrastructure ? : null} -
    + {topology.hosts.some((host) => host.lifecycleState === 'suspended') ?
    : null} {b2.error ?

    {b2.error}

    : null} {hosts.map((host) => { const remote = b2.data?.hosts.find((item) => item.hostRef === host.hostRef); @@ -568,18 +519,19 @@ function HostsView({ status={{remote ? remote.reachable ? 'Подключён' : 'Нет связи' : host.lifecycleState === 'suspended' ? 'В архиве' : freshnessLabel(host.telemetry.freshness)}} actions={<> {canManageInfrastructure && (isB2(host) || (!host.managementCredentialConfigured && !topology.serviceInstances.some((item) => item.hostRef === host.hostRef))) ? setSettingsHost(host)}> : null} - onSelectHost(host.hostRef)}> setExpandedHost(expanded ? null : host.hostRef)}> } /> - {expanded ? - - {isB2(host) ?
  • : null} - {topology.endpoints.filter((item) => item.hostRef === host.hostRef).map((item) =>
  • )} - {topology.deployments.filter((item) => item.hostRef === host.hostRef).map((item) =>
  • )} - {topology.serviceInstances.filter((item) => item.hostRef === host.hostRef).map((item) =>
  • )} -
    - {canManageInfrastructure ?
    {!isB2(host) ? <> : null}
    : null} -
    : null} + {expanded ?
    + {isB2(host) ? +
  • {remote?.reachable ? 'Доступен' : remote ? 'Нет связи' : 'Проверка…'}} />
  • +
  • +
  • +
  • Не подключены} />
  • +
    : <> + item.hostRef === host.hostRef)} onPoll={onPoll} onError={onError} /> + {canManageInfrastructure ?
    : null} + } +
    : null} ; })}
    {!hosts.length ?

    {showArchive ? 'Архив пуст' : 'Нет подключённых VPS'}

    : null} diff --git a/apps/device-manager/src/DeviceManagerApp.tsx b/apps/device-manager/src/DeviceManagerApp.tsx index 20e968f..2bb918f 100644 --- a/apps/device-manager/src/DeviceManagerApp.tsx +++ b/apps/device-manager/src/DeviceManagerApp.tsx @@ -58,6 +58,8 @@ import type { ProjectWorkspace, } from "./types"; import { EnvironmentMediaPlaylistEditor } from "./EnvironmentMediaPlaylistEditor"; +import { B2AddDevice } from "./b2/B2AddDevice"; +import { B2AddHost } from "./b2/B2AddHost"; import { useB2Inventory } from "./b2/useB2Inventory"; import { capabilityLabel, projectRoleLabel } from "./presentationLabels"; import { @@ -193,11 +195,12 @@ export function DeviceManagerApp() { const [activeProjectRef, setActiveProjectRef] = useState(""); const projectRefCurrent = useRef(activeProjectRef); projectRefCurrent.current = activeProjectRef; - const [selectedHostRef, setSelectedHostRef] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [projectDialogOpen, setProjectDialogOpen] = useState(false); const [collectionDialogOpen, setCollectionDialogOpen] = useState(false); + const [addHostOpen, setAddHostOpen] = useState(false); + const [addDeviceOpen, setAddDeviceOpen] = useState(false); const [enrollmentDialogOpen, setEnrollmentDialogOpen] = useState(false); const [claimEnrollment, setClaimEnrollment] = useState(null); const [projectSettingsOpen, setProjectSettingsOpen] = useState(false); @@ -297,7 +300,6 @@ export function DeviceManagerApp() { setInventoryDetail(null); projectRefCurrent.current = projectRef; setWorkspace(null); - setSelectedHostRef(null); setActiveProjectRef(projectRef); }; @@ -318,7 +320,6 @@ export function DeviceManagerApp() { if (ownerRef === activeOwnerRef) return; setActiveOwnerRef(ownerRef); setInventoryDetail(null); - setSelectedHostRef(null); setWorkspace(null); const nextProject = projects.find((project) => project.ownerScope.ownerRef === ownerRef); if (nextProject) { @@ -417,8 +418,8 @@ export function DeviceManagerApp() { {activeSection === "devices" && activeProject ? ( route.lifecycleState === "active")} - onClick={() => setEnrollmentDialogOpen(true)} + disabled={!canEnroll} + onClick={() => setAddDeviceOpen(true)} > @@ -494,8 +495,10 @@ export function DeviceManagerApp() { expanded={shell.contentExpanded} onExpandedChange={shell.setContentExpanded} onClose={shell.closeView} - utilityActions={[...(activeView === "hosts" && selectedHostRef ? [{ - label: "Вернуться к VPS и хостам", icon: "chevron-left" as const, onClick: () => setSelectedHostRef(null), + utilityActions={[...(activeView === 'inventory' && canEnroll ? [{ + label: 'Добавить устройство', icon: 'plus' as const, onClick: () => setAddDeviceOpen(true), + }] : []), ...(activeView === 'hosts' && capabilities.has('infrastructure.manage') ? [{ + label: 'Добавить VPS', icon: 'plus' as const, onClick: () => setAddHostOpen(true), }] : []), { label: "Обновить данные", icon: "refresh", @@ -504,8 +507,6 @@ export function DeviceManagerApp() { > setError(errorText(reason))} /> + {addDeviceOpen && workspace ? setAddDeviceOpen(false)} onCreated={async () => { setAddDeviceOpen(false); await refreshWorkspace(); }} onError={(reason) => setError(errorText(reason))} onLegacy={workspace.routes.some(route => route.lifecycleState === 'active') ? () => { setAddDeviceOpen(false); setEnrollmentDialogOpen(true); } : undefined} /> : null} + {addHostOpen && activeProject ? setAddHostOpen(false)} onCreated={async () => { setAddHostOpen(false); await refreshWorkspace(); }} onError={(reason) => setError(errorText(reason))} /> : null} void; +function ProjectView({ view, workspace, canManageCollections, canClaim, canConfigure, canManageProject, inventoryDetail, session, onRefresh, onPoll, onError, onCreateCollection, onClaim, onInventoryDetailChange }: { view: ViewId; workspace: ProjectWorkspace | null; canManageCollections: boolean; @@ -803,8 +804,6 @@ function ProjectView({ selectedHostRef, onSelectHost, view, workspace, canManage if (!workspace) return
    Загружаем проект…
    ; if (["catalog", "hosts", "infrastructure", "sessions", "bindings", "commands", "audit", "access", "settings"].includes(view)) { return }; +type Preview = { number: number; identifier: string; firmware: string; configuration: { record_count: number }; parameters: Record }; +export function B2AddDevice({ workspace, onClose, onCreated, onLegacy }: { + workspace: ProjectWorkspace; onClose: () => void; onCreated: () => Promise; + onError: (error: unknown) => void; onLegacy?: () => void; +}) { + const projectRef = workspace.project.projectRef; + const [hosts, setHosts] = useState([]), [hostRef, setHostRef] = useState(''), [contourId, setContourId] = useState(''); + const [name, setName] = useState(''), [method, setMethod] = useState(supportsB2Usb() ? 'usb' : 'manual'); + const [imei, setImei] = useState(''), [number, setNumber] = useState(''); + const [profile, setProfile] = useState(''), [profiles, setProfiles] = useState>([]); + const [snapshot, setSnapshot] = useState(null), [preview, setPreview] = useState(null); + const [loading, setLoading] = useState(true), [catalogReady, setCatalogReady] = useState(false), [retry, setRetry] = useState(0); + const [reading, setReading] = useState(false), [pending, setPending] = useState(false), [error, setError] = useState(''); + const controller = useRef(null), mounted = useRef(true); + useEffect(() => { mounted.current = true; return () => { mounted.current = false; controller.current?.abort(); }; }, []); + useEffect(() => { + let active = true; setLoading(true); setError(''); + b2Request<{ hosts: Host[] }>(projectRef, '', 'enrollment-options').then(result => { + if (!active) return; setHosts(result.hosts); + const first = result.hosts.find(host => host.reachable && host.contours.length); + setHostRef(first?.hostRef || ''); setContourId(first?.contours[0]?.id || ''); + }).catch(reason => { if (active) setError(reason.message); }).finally(() => { if (active) setLoading(false); }); + return () => { active = false; }; + }, [projectRef, retry]); + useEffect(() => { + let active = true; setProfiles([]); setProfile(''); setCatalogReady(false); setSnapshot(null); setPreview(null); + if (hostRef && contourId) b2Request<{ profiles: Array<{ id: string; name: string }> }>(projectRef, hostRef, 'enrollment', { contourId, request: { action: 'catalog' } }) + .then(result => { if (active) { setProfiles(result.profiles); setCatalogReady(true); } }) + .catch(reason => { if (active) setError(reason.message); }); + return () => { active = false; }; + }, [projectRef, hostRef, contourId, retry]); + const busy = pending || reading; + const host = hosts.find(item => item.hostRef === hostRef); + const valid = catalogReady && Boolean(name.trim()) && (method === 'usb' ? Boolean(snapshot && preview) : /^\d{15}$/.test(imei) && /^\d{1,10}$/.test(number) && Number(number) > 0 && Number(number) <= 4294967295); + function close() { if (!pending) { controller.current?.abort(); onClose(); } } + async function readUsb() { + setError(''); setSnapshot(null); setPreview(null); setReading(true); + const abort = new AbortController(); controller.current = abort; + try { + const observed = await readB2Usb({ signal: abort.signal }); + if (abort.signal.aborted) return; + const result = await b2Request(projectRef, hostRef, 'enrollment', { contourId, request: { action: 'inspect', usb: observed } }); + if (!mounted.current || abort.signal.aborted) return; + setSnapshot(observed); setPreview(result); setName(current => current || `ARNavi B2 · ${result.number}`); + } catch (reason) { if (mounted.current && !abort.signal.aborted) setError(reason instanceof Error ? reason.message : 'Не удалось прочитать USB.'); } + finally { if (mounted.current) setReading(false); } + } + return + }> +
    { + event.preventDefault(); if (!valid || busy) return; setPending(true); setError(''); + try { + await b2Request(projectRef, hostRef, 'enrollment', { contourId, request: { action: 'register', name: name.trim(), + ...(method === 'usb' ? { usb: snapshot } : { imei, number: Number(number) }), ...(profile ? { profile_id: profile } : {}) } }); + setSnapshot(null); await onCreated(); + } catch (reason) { setError(reason instanceof Error ? reason.message : 'Не удалось добавить устройство.'); } + finally { if (mounted.current) setPending(false); } + }}> + item.reachable && item.contours.length).map(item => ({ value: item.hostRef, label: item.name }))} onChange={event => { + setHostRef(event); setContourId(hosts.find(item => item.hostRef === event)?.contours[0]?.id || ''); setError(''); + }} /> + {(host?.contours.length || 0) > 1 ? { setMethod(event); setError(''); }} /> +